# Writing command hooks

Hooks are independent executables. `git-workspace` supplies command results; packages such as
a tmux integration or a notifier own their behavior, dependencies, and configuration.

## Discovery and installation

Put executable files or executable symlinks on `PATH` using these names:

```text
git-workspace-hook-add-post-<name>
git-workspace-hook-remove-post-<name>
git-workspace-hook-rename-post-<name>
```

The hook name starts with a lowercase letter or digit and may contain lowercase letters,
digits, `_`, and `-`. A hook is enabled whenever it is discoverable. Discovery happens once
per command invocation. For duplicate executable names, the first executable on `PATH`
wins; a nonexecutable file does not hide a later executable. Distinct hooks for a command
run sequentially in alphabetical order of their executable names.

`git workspace hook list` lists command/phase, name, and resolved executable path in
tab-separated columns. It needs no initialized workspace and never executes the hooks.

Install and remove hooks using their package manager, or manage executables yourself. No
cloning, registration, or installer is built into `git-workspace`. For example, a reusable
npm package can expose one implementation under several names:

```json
{
  "name": "git-workspace-hook-example",
  "version": "1.0.0",
  "type": "module",
  "bin": {
    "git-workspace-hook-add-post-example": "./hook.js",
    "git-workspace-hook-remove-post-example": "./hook.js",
    "git-workspace-hook-rename-post-example": "./hook.js"
  }
}
```

After publishing that package, `npm install -g git-workspace-hook-example` installs its bin
links. The npm global bin directory must be on `PATH`. This is an example package name,
not a bundled integration. The executable needs a shebang and executable permissions.
It can use Bare, Node.js, Python, a shell, or another runtime supplied by the hook author.

An example Node.js `hook.js` that reports results:

```js
#!/usr/bin/env node
import fs from 'node:fs'

const context = JSON.parse(fs.readFileSync(0, 'utf8'))
if (context.version !== 1) throw new Error('Unsupported hook protocol')

for (const { before, after } of context.result.data.checkouts) {
  console.error(`${context.command}: ${before.name} -> ${after.name} (${context.result.status})`)
}
```

## Execution

The executable receives two arguments: the command (`add`, `remove`, or `rename`) and
`post`. Its stdin contains one UTF-8 JSON document, followed by a newline and EOF. The
working directory is the workspace root, normally `~/workspace`, so a removed checkout
is never used as the working directory. The environment is inherited. Both hook stdout
and stderr are forwarded to the CLI's stderr.

Direct command hooks run after the checkout operations, the manifest commit and push
attempt, and the local applied checkpoint attempt. A failed manifest push warns and keeps
the successful local command result; it does not prevent hooks from running. A failed checkpoint only warns, as it does without hooks.
Once an operation has been attempted, its hook also runs if the command fails, reporting
the failure and any partial effects. Invalid command syntax, unresolved workspace configuration,
help, completion, and dry runs do not trigger hooks.

One logical command means one call to each matching hook. Adding `owner/repo@jobs` may
create its root as well; both are included in one add payload. A root rename includes its
worktrees. A successful repeated add still runs its hooks, allowing an integration to restore
a missing session even when no checkout changed. `init`, `list`, `status`, `completion`,
and `hook list` do not have hooks.

Nonzero exit, a signal, or failure to launch a hook prints a warning. Remaining hooks still
run; the original command's exit status is preserved. Hooks cannot veto or roll back an
operation. Hook output is not interpreted as instructions. Execution waits for each hook;
hooks should finish promptly or arrange their own background work.

`--no-hooks` on `add`, `remove`, `rename`, or `pull` skips hooks for that invocation.
Hook subprocesses receive `GIT_WORKSPACE_HOOK=1`; nested workspace commands inherit it and
skip hook dispatch to prevent accidental recursion. Workspace mutations are still blocked
while a pull is pending, including from its hooks.

## JSON protocol, version 1

The common envelope is:

```json
{
  "version": 1,
  "command": "rename",
  "phase": "post",
  "operation": {
    "id": "42f9daef-e15f-4286-a7c9-0c6e93b75943",
    "source": "cli",
    "resumed": false
  },
  "workspace": {
    "root": "/home/me/workspace",
    "manifest": "/home/me/workspace/me/workspace/workspace.json"
  },
  "input": {
    "from": "owner/repo@jobs",
    "to": "owner/repo@fixes"
  },
  "result": {
    "status": "ok",
    "data": {
      "changed": true,
      "checkouts": []
    },
    "error": null
  }
}
```

The empty `checkouts` above abbreviates the payload: it contains a `{ before, after }`
pair for each checkout involved. Each snapshot has this shape:

```json
{
  "id": "e8375481-bac0-4e98-b035-599cbdf7ad4d",
  "kind": "worktree",
  "name": "owner/repo@fixes",
  "path": "/home/me/workspace/owner/repo@fixes",
  "repository": {
    "id": "34a017c5-a0c4-43bb-a3e4-abeb5301c56a",
    "name": "owner/repo",
    "path": "/home/me/workspace/owner/repo"
  },
  "exists": true,
  "registered": true,
  "branch": "fixes",
  "ref": "0123456789012345678901234567890123456789",
  "origin": null
}
```

- `operation.id` identifies this logical operation. Direct invocations get fresh IDs.
  Pull retries retain an operation's ID. `source` is `cli` or `pull`; `resumed` identifies
  delivery during a resumed pull.
- `input` is `{ "repository": "owner/repo[@branch]" }` for add/remove, or `{ "from": "...",
"to": "..." }` for rename. These are parsed names, not the original shell command line.
- `status` is `ok` on success, `partial` on failure with an observed checkout/registration
  change, or `error` on failure without one. `error` is either `null` or `{ "message": "...",
"code": null }`; `code` is the error's code string when available.
- `changed` compares the checkout snapshots. It is false for an unchanged repeated add.
  It does not describe unrelated staged files, manifest commit metadata, or a history of
  transient changes that were rolled back.
- Snapshot `id` is the stable manifest ID when known, otherwise `null`. Removed entries
  retain their ID in the after snapshot. New direct additions acquire IDs when registered;
  pull additions already have IDs in the desired manifest. Never invent IDs from paths.
- `kind` is `repository` or `worktree`. `repository` identifies the root and points to the
  checkout itself for root entries. All paths are absolute.
- `exists` describes the path on disk. A missing checkout still has a snapshot with its
  name, path, and any known ID. `registered` describes the operation's manifest layout;
  during pull this is the intermediate layout as operations are applied, since the manifest
  file already contains the full desired layout.
- `branch` is the currently checked-out branch, or `null` for a missing, detached, or
  unreadable checkout. It may differ from the branch in `name` after a manual Git switch.
  `ref` is the commit of the local branch named by `@branch`, or `null` if unavailable;
  it is also `null` for a root. This distinguishes a removed worktree from a branch ref
  whose deletion failed. `origin` is the root's origin URL, otherwise `null`.

For renames, `after` follows a checkout that moved even if a later branch or manifest update
failed. An occupied destination that caused a rename to be refused is not reported as the
renamed checkout. Root renames include unregistered linked worktrees under the root's
`@branch` naming layout, with null IDs. External linked worktrees whose paths stay unchanged
are not included. Discovered unregistered worktrees can have suffix characters accepted by
ordinary Git but unsupported as CLI input. Add payloads include the root first, then the requested
worktree.

For example, if removal deletes a worktree but cannot delete its branch, the result is
`partial`: `after.exists` is false, `after.registered` is true, and `after.ref` still identifies
the branch. If checkout creation succeeds but the manifest commit fails, the hook sees the
created checkout and a `partial` result with the commit error. Consumers should examine the
outcome and snapshots instead of assuming every post hook means success.

Treat context as data, not shell source. Ignore unfamiliar JSON fields for forward
compatibility. Command-specific data lives under `result.data`; a future command such as
fetch can define its own result shape without adding notification logic to the core.
This release implements neither fetch nor prune.

## Pull and recovery

Pull invokes add/remove/rename hooks for its individual operations, with `source: "pull"`.
It records the filesystem operation as completed and saves its post-hook context together
before running the hooks. It does not run a second set of top-level pull hooks. Pull's final
applied checkpoint is recorded after all operations and hook delivery attempts.

After a crash, the next pull resumes the saved target and delivers any saved post context
without repeating completed filesystem operations. If the process died during hook delivery,
the matching hooks can all run again, including ones that already succeeded. Use stable
checkout IDs and idempotent operations, such as ensuring a session exists or removing it only
if present. `operation.id` can help detect duplicate delivery. The same operation can first
report a partial failure and later succeed, so do not discard a later success solely because
its ID was seen before.

Each retry resolves the currently installed hooks on `PATH`; executable paths are not saved
in the progress journal. Hook failures count as attempted delivery and do not prevent pull
from completing. A dry run never delivers or clears pending hooks. Resuming with `--no-hooks`
discards pending delivery and skips hooks for the remaining operations; it does not defer them
for a later invocation. It still finishes and verifies the workspace normally.

Direct commands have no durable hook journal. A process crash can prevent their hooks from
running, so the API provides no exactly-once delivery guarantee.
