Forge Harness — Claude Code Hooks
Hooks are deterministic shell commands that Claude Code runs automatically at specific lifecycle moments. They close the gap between CLAUDE.md guidance (which the model can forget under pressure) and runtime enforcement (which it cannot).
CLAUDE.md is guidance. Hooks are laws.
The full rationale is docs/claude-code-hooks-deepdive.md in the upstream forge-harness repo (not copied here). This README is the operator’s guide.
What’s Installed
Every hook in this directory is wired in ../settings.json.
| Script | Event | Ships working? | What it enforces |
|---|---|---|---|
block-dangerous-bash.sh |
PreToolUse Bash |
generic | Blocks a recursive forced rm of /, ~ or $HOME in any flag spelling (-rf, -fr, -r -f, …), sudo rm, curl | sh, DROP TABLE, fork bombs, git reset --hard (also behind git -C <dir>), a force-push or a delete push to main/master/develop/staging/production/release/* (a git push whose own arguments name the whole branch and carry -f/--force/--force-with-lease or -d/--delete in any position, alone or inside a group of short flags (-fu, -qd); or a lease on one (--force-with-lease=main), a +<branch> / +<src>:<branch> refspec, or a :<branch> refspec, which deletes it; the command is split on ;, &, ` |
protected-paths.sh |
PreToolUse Edit/Write/MultiEdit |
project-tuned | Blocks edits to other CI configs (.github/workflows/ is commented out at the lead’s request, so Claude makes lead-approved workflow edits directly; the CLAUDE.md rule that CI changes need lead approval still applies), infra, terraform/ and .tf (Terraform lives in forge-et-iaac, AD #23; a session may edit it only in a linked worktree of forge-et-iaac, <WS>/worktrees/<ticket>/…/forge-et-iaac/, made for a work item with an approved plan and shipped as a PR to dev that merges only after Shyamin Ayesh approves it (.claude/rules/forge-et-iaac.md) — the forge-et-iaac checkout itself and Terraform anywhere else stay blocked), charts. Flyway’s db/migration/ is deliberately not protected — every backend feature adds a migration from an approved plan; schema changes are an ASK FIRST item settled at spec and plan approval. Tests: governance-guards.test.sh |
guard-browser-gate.mjs (no longer a registered hook) |
— | — | Not run on any tool call since 2026-11-02, when the browser gate left PRs into main (PRD Rev 81; .forge/design/harness/test-run-cost.md S-4); a PR into release/* is checked by each frontend’s Fast lane last step instead. The file stays because it holds the shell parser that lib/shell-parse.mjs re-exports for guard-docker-resources.sh; moving the parser into lib/shell-parse.mjs and deleting the PR-decision code is an owed.md row. Tests: node --test .claude/hooks/tests/guard-browser-gate.test.mjs, which Repo hygiene runs. What it did while registered (F40, spec FR-10; design record .forge/design/harness/browser-gate-enforcement.md): it refused a non-draft gh pr create / gh pr new, and a gh pr ready, for forge-et-fe or forge-et-pwa unless a passing browser-gate result covered the PR’s pushed head. A one-regex fast path lets every other command through with no process started. Past it, the Node helper .claude/hooks/guard-browser-gate.mjs tokenises the Bash or PowerShell command, finds every PR command at any depth, and allows: a draft (the last --draft / -d decides), --dry-run, --help, gh pr ready --undo; a create whose own --body / --body-file has a Browser gate: skipped — <reason> line; a repo other than the two app repos; a branch whose change touches no gate input; or a result that covers the head. It does not implement the covers rule: it runs the target worktree’s own scripts/browser-gate.mjs (touches-gate-input, then covers). It finds that worktree from the head branch ($WS/<repo>‘s worktrees) and judges the pushed tip, so a push and the gh pr create after it must be separate tool calls. It refuses anything it cannot read: a bare $VAR, $(…) or backtick among the command’s own flags, a non-literal --repo / --head / --base / --body-file / cd target, a flag gh does not define, an unbalanced quote, a shell reading standard input it cannot see (curl … | bash, bash < file). Text a shell reads from a here-document, a here-string or a pipe from literal output is read as a nested command; that covers bash, sh, zsh, dash, ksh, mksh, ash and busybox sh reading standard input through no script operand, -s, a lone -, or /dev/stdin, /dev/fd/0 or /proc/self/fd/0 as the script, and source / . of one of those paths (BUG-064). A prefix command — command, builtin, exec, nohup, env, sudo, timeout, nice, or time — is read with its options, so a shell behind it (echo … | timeout 60 bash) is read as the command; a cd, export GH_REPO=… or GH_REPO=… behind a program or exec (nohup cd x, env GH_REPO=…) changes nothing, as in bash, while a cd or export behind command, builtin or the reserved time counts (after an assignment or a prefix command, time is the program) (BUG-062). Every failure past the fast path is exit 2; the wrapper allows only when the helper exits 0 and prints ALLOW. Fails open only without jq; without node it refuses. Accepted gaps: Claude Code stopping the hook at its 30-second timeout lets the command run (the helper’s own deadline is 20 s; D-6); commands it cannot see into — a script file, a gh alias, a shell nested more than one level deep, a command built at run time ($cmd pr create), a keyword split by quotes or escapes (g''h, cr\eate, $'gh\x20pr', a PowerShell backtick escape); PRs opened outside a Claude session started in the harness (the app repos have no .claude/); and a PR that changes the gate program is judged by that changed program. Three more, each still failed by the app repo’s Fast lane CI check: a --body-file that the same command rewrites before gh runs is read as it was before the command started; on Windows, a call that times out ends only the program the helper started, so its child processes can keep the hook running until Claude Code’s 30-second timeout lets the command run; and arguments that xargs or Start-Process supply or reorder at run time are not read as gh will see them. A directory or GH_REPO change inside a bash function body, a PowerShell script block that is stored or passed as an argument, or a Start-Job / Start-ThreadJob / -Parallel body is counted as if it ran in the same shell; the Fast lane CI check still fails such a PR. env -S '<command>' / --split-string and git aliases (git -c alias.x='!gh pr …' x) run a command the hook does not read; the Fast lane CI check still fails such a PR. Other wrappers (setsid, stdbuf, doas) are not read as prefix commands, so a shell behind one is read only for its -c string; sudo -s or sudo -i with no command starts a shell that reads standard input, which is not read; env -C <dir> in front of a nested shell (env -C <dir> bash -c 'gh pr …') does not move the nested gh’s directory; and sudo -D <dir> / sudo --chdir=<dir> in front of gh is not read as a directory change. The Fast lane CI check still fails such a PR. Any mention of GIT_DIR or GIT_WORK_TREE in the command text, even inside a commit message, refuses a create that has no --repo, so pass --repo explicitly; the Fast lane CI check still fails any PR this rule misses. A bash case statement is read (BUG-044), but some forms are refused even though bash runs them, and the Fast lane CI check still fails any PR that gets through: an extglob pattern (@(a|b)) and coproc are refused as unparseable; a cd or GH_REPO inside a case arm leaves the directory or repo unknown for a gh outside that arm; and a shell that reads standard input with no here-document, here-string or pipe of its own (echo … | case x in *) bash;; esac, { bash; } <<< …) is refused wherever it stands, even when its flags mean it reads nothing (bash --version, sh --help, exec bash -l). The app repos’ CI description check catches the rest. GUARD_BROWSER_GATE_DEADLINE_MS (may only shorten the deadline) and GUARD_BROWSER_GATE_GH (may only name a .mjs stub to run in place of gh) were test-only settings. The wrapper’s own test (guard-browser-gate.test.sh) and its gate-program stub were deleted with the wrapper; the Node test (node --test .claude/hooks/tests/guard-browser-gate.test.mjs, with the stub .claude/hooks/tests/stubs/guard-browser-gate-gh.mjs) still runs in Repo hygiene, because the parser it covers is live |
guard-docker-resources.sh |
PreToolUse Bash|PowerShell (timeout 15 s) |
project-specific (requires jq, node past the fast path, and git) |
Refuses Docker commands that would leave a resource /et-cleanup cannot tie to any work (design record .forge/design/harness/docker-resource-labels.md): a docker run / create without --name et-<ticket>-<role> and an et.workdir label naming the root of the checkout the work belongs to (never the harness), a named volume or network not called et-… or not labelled, and a docker compose up / run / create whose project name does not start with et-, or with no project name in a linked worktree (there it would act on the primary checkout’s stack of the same folder name). A short foreground docker run --rm is exempt. Commands are read with the browser gate’s parser through .claude/hooks/lib/shell-parse.mjs, so text in a commit message, PR body or heredoc is not mistaken for a command; the label may be "$PWD" or $(pwd) after a cd, or a variable assigned earlier in the same command, and must come out an absolute path with no . or .. segment (Docker stores the text as written, and the cleanup compares that text). Only commands whose label, folder or compose project folder is inside the ET workspace are checked. A fast path lets every command without docker (in any case) through with no process started. Fails open, with a warning: no jq, no node, a command it cannot parse, a flag missing from its tables, or the guard itself failing. Accepted gaps: Docker commands inside a script the command runs; xargs and aliases; COMPOSE_PROJECT_NAME or COMPOSE_FILE exported in an earlier command or set in a .env file; sessions started inside an app repo. GUARD_DOCKER_WS (the workspace path) is a test-only setting. Tests: bash .claude/hooks/tests/guard-docker-resources.test.sh (temporary git repositories, no containers); Repo hygiene runs it |
guard-spec-leapfrog.sh |
PreToolUse Edit/Write/MultiEdit |
generic (requires yq) |
Blocks creation/edit of feature specs (.forge/specs/<x>-spec.md) until Gate 2 has passed AND foundation is done. Foundation specs (.forge/specs/foundation/**) are exempt. Reads .forge/tracker.yaml setup.architecture.status + setup.foundation.status. Tests: governance-guards.test.sh |
guard-spec-approval.sh |
PreToolUse Edit/Write/MultiEdit |
generic | Blocks transitions to Status: approved on feature spec files (.forge/specs/<x>-spec.md) unless the file carries a Reviewed-via: /forge-spec-review annotation in either the new edit or the existing file on disk. Enforces that /forge-spec-review (skill + spec-reviewer sub-agent) actually ran before approval. Foundation specs (.forge/specs/foundation/**) are exempt — they go through the manual review cycle alongside the foundation plans. Tests: governance-guards.test.sh |
guard-plan-approval.sh |
PreToolUse Edit/Write/MultiEdit |
generic | Blocks transitions to Status: approved on plan files (.forge/plans/**/*-plan.md) unless the file carries a Reviewed-via: /forge-plan-review annotation in either the new edit or the existing file on disk. Enforces that /forge-plan-review (skill + plan-reviewer sub-agent) actually ran before approval. Foundation plans and feature plans both gated. Tests: governance-guards.test.sh |
guard-prd-shape.sh |
PreToolUse Edit/Write/MultiEdit |
generic (requires jq) |
Path-scoped to project-prd.md: blocks OQ rows, ## Open Questions / ## Risks and Open Questions headings, and ## Revisions / ### Rev N content from landing in the contract file — the stderr message redirects to project-prd-signals.md / project-prd-history.md per the PRD trichotomy (.claude/rules/prd.md). Fails open. Tests: its own --self-test, run by governance-guards.test.sh |
inject-relevant-risks-spikes.sh |
PreToolUse Edit/Write/MultiEdit |
generic (requires yq) |
Advisory only: prints open accepted risks + spikes from .forge/tracker.yaml to stderr whenever a spec or plan is being written/edited. Visible in transcript; never blocks. |
inject-spec-context.sh |
UserPromptSubmit |
generic | Auto-attaches .forge/specs/<name>.md or .forge/plans/<name>.md when the prompt contains @spec:<name> or @plan:<name> |
inject-gate-state.sh |
SessionStart |
generic (requires yq) |
Prints engagement-gate state (Gate 1 / Gate 2 / foundation / Gate 3 status, last-run dates, open risk + spike counts and contents), the delivery phases with status and due date, and the features in progress (any phase but backlog, done or dropped) into Claude’s context at every session start, for the .claude/CLAUDE.md session-start reconcile. From 14 days before the in-progress phase’s due_date until .forge/engagement-gate-runs.md has a Phase <N> boundary check heading, it also prints a reminder to run .forge/checklists/phase-boundary-checklist.md (skipped when python3 is missing). It also prints each open nightly-red issue and, after 06:00, a night the nightly full run did not run (.claude/lib/nightly/run-nightly.py --status: two gh calls of at most 4 seconds each, cached for 30 minutes; nothing when gh or python3 is missing, offline or slow — design test-run-cost.md N-2). It also prints, through .claude/lib/toolchain-check.sh, a warning with the fix commands when this machine’s Node major differs from the app repos’ .nvmrc on origin/main or Corepack is not on PATH (local reads only; nothing when they match). Read-only; never blocks. |
regen-tracker-dashboard.sh |
PostToolUse Edit/Write/MultiEdit + Stop |
generic (requires yq) |
Two modes: on edit, .forge/tracker.yaml → .forge/dashboard/tracker.js and .forge/lessons.md → signals.js; on Stop, both are regenerated unconditionally, once per turn (catches changes made by a script or a git operation, and worktree-session edits, that never fire an Edit hook; no mtime check — see the hook’s Stop-mode comment and lessons L-050). No-op if .forge/dashboard/ doesn’t exist. Fail-open if yq missing. |
regen-reference-graph.sh |
Stop |
generic (requires python3) |
Regenerates .forge/dashboard/harness-reference-graph.{html,md} from .claude/lib/harness-graph.py --write, unconditionally, once per turn (~0.4s). Stop rather than PostToolUse because the analyzer reads the whole repo. Fail-open if python3 or the script is missing. It deliberately has no mtime freshness check: deleting a file changes no surviving file’s mtime, so find -newer skipped the regen and left the artifact citing a file that no longer existed (proven with a probe doc). Watching directory mtimes instead would fire every turn anyway, because a sibling regen hook replacing a dashboard blob bumps .forge/dashboard/. The generator is deterministic, so an unchanged turn rewrites byte-identical files and produces no diff. |
regen-docs-html.sh |
Stop (in the background) |
generic (requires node) |
Rebuilds the rendered doc site docs-html/ from .claude/lib/render-docs-html.js, unconditionally, once per turn (~0.6s). Stop rather than PostToolUse because it renders the whole doc set (same rationale as the reference graph). Ordered after regen-reference-graph.sh: the renderer copies the graph page into docs-html/, so the graph must be current first. Keeps the local doc site fresh every turn without needing ./forge-start.sh or a commit — .githooks/pre-commit and forge-start.sh still rebuild it for out-of-session commits and fresh clones. Fail-open if node or the script is missing. |
regen-metrics-dashboard.sh |
PostToolUse Edit/Write/MultiEdit |
generic (requires jq) |
When .forge/tracker.yaml or any .forge/metrics/*.jsonl ledger is edited, derives .forge/dashboard/metrics.js from the append-only estimation ledgers (registered after regen-tracker-dashboard.sh so both mirrors refresh together; the tracker.yaml coupling catches Bash >> ledger appends that fire no Edit hook). With stdin closed (</dev/null — pages-build.sh, forge-start.sh, a manual run) it regenerates unconditionally, the same two-mode contract as the tracker hook. Never blocks; empty ledgers → explicit empty state. |
phase-scope-skills.sh |
PostToolUse Edit/Write/MultiEdit + manual |
generic (requires yq + jq) |
When .forge/tracker.yaml is edited, derives the current engagement phase from setup.* gate statuses (via .claude/lib/derive-phase.sh) and rewrites .claude/settings.local.json’s skillOverrides so out-of-phase skills load as "off" (description hidden from session). Reads each .claude/skills/*/SKILL.md front-matter phases: field; skills without phases: stay always-on. Writes apply to the next session (Claude Code reads settings before hooks run) — prints a one-line restart nudge on change. Also runnable manually for bootstrapping projects whose tracker.yaml hasn’t been edited since this hook landed: ./.claude/hooks/phase-scope-skills.sh. Idempotent; silent on no-op. |
track-token-usage.sh |
Stop |
generic (requires jq) |
Captures the latest assistant turn’s usage block from Claude Code’s per-session JSONL and appends one row to ~/.claude/forge-usage.jsonl (per-developer, per-machine, append-only). Tags every row with ts, session_id, assistant_message_id, user_email, project_name, phase, model, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens. Phase resolves via the shared .claude/lib/derive-phase.sh helper. Outside a Forge harness (no .forge/ in cwd ancestry): row written with project_name: "<non-forge>" and phase: "n/a". Atomic append under a portable mkdir lock for concurrent sessions (not flock, which macOS lacks). Failure-tolerant: all errors swallowed → exit 0; details logged to ~/.claude/forge-usage.error.log. < 200ms target (NFR-1). Design spec: docs/engineering/specs/2026-05-14-token-usage-tracking.md in the upstream forge-harness repo (not in this one). |
regen-usage-dashboard.sh |
Stop (in the background) |
generic (requires jq) |
Derives two project-scoped artifacts from the global ~/.claude/forge-usage.jsonl: (1) <harness>/.forge/usage.jsonl — raw filtered rows, deduped by assistant_message_id, the primary developer-facing interface for grep/jq/tail -f inspection; (2) <harness>/.forge/dashboard/usage.js — aggregated window.USAGE = {...} JSON consumed by Section 04 of the dashboard. Incremental: each run reads only the bytes added to the global file since the last run (at most 16 MB per run), appends the new rows to the mirror and adds them to running totals in <harness>/.forge/usage-state.json, from which usage.js is rendered. Rows are deduped against the mirror and within the new bytes; concurrent runs serialise on a mkdir lock (.forge/usage-regen.lock). A run that finds the state untrustworthy (missing, the global file replaced or truncated, the mirror shorter than recorded or ending mid-line) starts again from an empty mirror; a backlog is worked through over the next few Stops. All three files and the lock are gitignored (per-developer-per-machine state). Outside any Forge project: exits silently. Same failure-tolerance contract as track-token-usage.sh. |
tracker-freshness.sh |
Stop |
generic (requires jq for user-visible output) |
Soft-warning Stop hook: emits a systemMessage JSON object on stdout when .forge/specs/**/*-spec.md or .forge/plans/**/*-plan.md was modified or newly created (untracked) in the working tree but .forge/tracker.yaml was not. Claude Code renders the message inline in the terminal. Always exits 0 — the session ends regardless. Fails open if not in a git repo, or degrades to debug-log stderr if jq is unavailable. |
pwa-screenshots-freshness.sh |
Stop |
project (requires jq) |
Keeps the capture-app prototype’s screenshots in step with it. When the branch has changed .forge/design/prototypes/pwa-current/ (its source/ or pwa-prototype.html) and the prototype is newer than pwa-current/screenshots/README.md, it blocks the stop once with a reason: ask the developer whether to update the screenshots, and on a yes build the prototype and run screenshots/capture.mjs. It asks once per change (a marker in the git directory) and bails on stop_hook_active. Fails open without jq, git, origin/main or the screenshots folder. |
forge-recap.sh |
Stop |
generic (uses git, requires jq for user-visible output) |
Forge Heartbeat — the “beat”. State-derived session recap, emitted as a systemMessage JSON object on stdout so Claude Code renders it inline in the terminal (zero model-context tokens). Reads git diff --name-only HEAD plus untracked files (git ls-files --others --exclude-standard) for spec/plan/tracker changes, so a newly written spec or plan counts before it is staged; .forge/tracker.yaml for phase + active delivery phase; and .forge/usage.jsonl filtered by session_id for token totals. Interesting-or-silent: emits nothing when no spec/plan/tracker files changed this session. Skips on stop_hook_active = true re-fires to avoid double-printing. Always exit 0. < 200ms target. Design spec: docs/engineering/specs/2026-05-21-forge-heartbeat-spec.md in the upstream forge-harness repo (not in this one). |
lint-and-typecheck.sh |
PostToolUse Edit/Write/MultiEdit |
project-specific (filled for this repo; each check skips if its tool is missing) | Checks the one file just edited, with the tools Repo hygiene CI uses: tracker.yaml parses (yq), *.md frontmatter (check-md-frontmatter.sh), shell scripts (shellcheck -S error), *.js (node --check), *.py (parses), *.json (jq). Exit 2 on a failure. Single-file, well under the 3-second budget. Only files under $CLAUDE_PROJECT_DIR are checked, so edits in a separate worktree are left to Repo hygiene |
verify-before-stop.sh |
Stop |
project-specific (filled for this repo; each check skips if its tool is missing) | Over the files changed in the working tree (tracked changes plus untracked, not gitignored): tracker.yaml parses, changed *.md keep lossless frontmatter, changed shell scripts pass shellcheck -S error. Blocks the Stop (exit 2) on a failure and bails on the stop_hook_active re-fire. Catches files changed by Bash or a script, which no Edit hook sees. A few seconds at most |
Matcher note: the Edit/Write rows are wired in settings.json as Edit|Write|MultiEdit. MultiEdit is no longer a tool in current Claude Code; the matcher keeps the name so an older client that still has it stays covered. Nothing else should reference it.
The generic scripts work immediately on a fresh project (the yq-dependent and jq-dependent hooks need those tools — see Dependencies below). lint-and-typecheck.sh and verify-before-stop.sh ship upstream as no-op templates; in this repo both are filled with the harness’s own structural checks (rows above). An upstream sync must keep these bodies rather than restore the templates.
Stop hooks — foreground and background
Claude Code starts all of an event’s hooks together; it does not run them in the order they are registered, so no Stop hook can rely on another having finished in the same turn. The turn waits for every foreground hook, so the slowest one sets how long each turn ends late. The four hooks that only rebuild gitignored files run in the background ("async": true, 60 s timeout): the turn does not wait for them, and each reads what the previous turn’s runs wrote. The hooks whose output the turn needs stay in the foreground (BUG-322; governance-guards.test.sh checks the wiring):
| Hook | Runs | What it does |
|---|---|---|
track-token-usage.sh |
background | Appends this turn’s usage rows to the global usage file ~/.claude/forge-usage.jsonl, under a lock. Reads the whole session transcript, so it slows as a session grows. |
regen-usage-dashboard.sh |
background | Derives the project mirror and the dashboard data from the global usage file. Incremental, capped at 16 MB of the global file per run; a run stopped by its timeout loses nothing — the next one carries on from the last saved state, and its temp files are removed by its own exit trap or by the next run’s sweep. |
regen-reference-graph.sh |
background | Regenerates the harness reference graph, unconditionally (no freshness check by design — see its table row above; the write is deterministic and goes through os.replace, so an unchanged turn produces no diff and an overlapping run leaves no half-written file). About 6 s on a Mac. |
regen-docs-html.sh |
background | Rebuilds the rendered doc site docs-html/, unconditionally (~0.6 s). The renderer embeds the graph page, so the page it embeds can be one turn old. Fail-open if node is missing. |
regen-tracker-dashboard.sh |
foreground | Stop mode; regenerates tracker.js/signals.js unconditionally, so a source changed without firing an Edit hook is never missed. Fast. |
tracker-freshness.sh |
foreground | Advisory systemMessage if specs/plans were edited without a tracker update. |
forge-recap.sh |
foreground | Heartbeat beat; emits the session recap as a systemMessage, quoting session token totals from the usage files as the earlier turns’ background runs left them. Interesting-or-silent. |
verify-before-stop.sh |
foreground | Structural checks over the changed files (tracker parse, markdown frontmatter, shellcheck); a few seconds (600 s timeout kept from the template). It can block the stop, so it must stay in the foreground. |
pwa-screenshots-freshness.sh |
foreground | Asks, once per change, whether to re-take the capture-app prototype’s screenshots when the prototype is newer than them. Fast (a git diff --quiet and a find). It can block the stop, so it stays in the foreground. |
A hook that only writes local files and takes more than a second or two belongs in the background; a hook that prints a systemMessage or can block belongs in the foreground, because a background hook’s output does not reach the turn.
Why systemMessage JSON, not plain stderr: Claude Code’s Stop hooks at exit 0 send plain stderr to the debug log only, not the user’s terminal. The documented user-facing channel for non-blocking Stop output is a {"systemMessage": "..."} JSON object on stdout (see hooks docs — Exit Code Behavior + JSON Output Fields). Earlier revisions of tracker-freshness.sh wrote to plain stderr and were silently invisible — fixed alongside the Heartbeat recap in v0.23.0.
Dependencies
Three external tools, all common dev dependencies:
yq (Mike Farah’s Go implementation, v4+) — required by inject-gate-state.sh, guard-spec-leapfrog.sh, inject-relevant-risks-spikes.sh, regen-tracker-dashboard.sh, phase-scope-skills.sh, forge-recap.sh (reads setup.* + delivery.*), and .claude/lib/derive-phase.sh (called by phase-scope-skills.sh, track-token-usage.sh, and forge-recap.sh). Used to parse .forge/tracker.yaml. All fail open with a one-line note on stderr if yq is missing.
jq — required by almost every hook: every PreToolUse guard (block-dangerous-bash.sh, protected-paths.sh, guard-docker-resources.sh, guard-spec-leapfrog.sh, guard-spec-approval.sh, guard-plan-approval.sh, guard-prd-shape.sh) parses its stdin with it, as do inject-spec-context.sh, regen-tracker-dashboard.sh (edit mode), regen-metrics-dashboard.sh, inject-relevant-risks-spikes.sh, lint-and-typecheck.sh, verify-before-stop.sh, track-token-usage.sh, regen-usage-dashboard.sh, phase-scope-skills.sh, forge-recap.sh and tracker-freshness.sh (user-visible output). All fail open if jq is missing — and the guards say so on stderr (<hook>: jq not found — … guard skipped), because a guard that silently allows everything is the failure worth noticing. Install jq on every developer machine.
node — guard-docker-resources.sh runs a Node helper, for commands whose text holds docker; it fails open without node (or jq), with a warning, because it is a hygiene rule rather than a quality gate.
brew install yq jq # macOS
# yq: see https://github.com/mikefarah/yq#install
# jq: see https://stedolan.github.io/jq/download/
Without these tools the affected hooks behave as no-ops; the rest of the hook stack is unaffected.
Windows note (at least two of the developers): the hooks are bash scripts — on Windows they run under Git Bash (bundled with Git for Windows), which Claude Code uses when present. Two things to check once per machine: (1) python3 must resolve in Git Bash for regen-reference-graph.sh and .githooks/pre-commit’s graph half — the python.org installer ships python.exe only, so either install from the Microsoft Store (which provides python3.exe) or add an alias/shim; (2) yq/jq/node on PATH as above (winget/scoop/choco all carry them). Everything fails open if missing — the visible symptom is the local mirrors (gitignored) going stale until the next turn regenerates them; Repo hygiene CI runs the generators on every PR regardless. Line endings are pinned repo-side in .gitattributes (*.sh/.githooks/* are forced LF), so core.autocrlf on a Windows clone cannot break script execution.
Token usage tracking
Two of the Stop hooks (track-token-usage.sh, regen-usage-dashboard.sh) implement per-developer token capture per the v0.18 token-usage-tracking spec (docs/engineering/specs/2026-05-14-token-usage-tracking.md in the upstream forge-harness repo). Quick reference:
-
Global source:
~/.claude/forge-usage.jsonl(per-developer, per-machine, append-only, lives outside any repo). -
Project mirror:
<harness>/.forge/usage.jsonl(raw filtered rows, deduped, primary developer-facing interface). Gitignored. -
Dashboard data:
<harness>/.forge/dashboard/usage.js(window.USAGE = {...}aggregated). Gitignored. Visualized in Section 04 ofdashboard/index.html. -
Error log:
~/.claude/forge-usage.error.log— anything that goes wrong in the hooks goes here, never to Claude. -
Disable: comment out the two entries in
../settings.jsonunderStop. No further cleanup needed. -
Manual regen: if the dashboard or mirror looks stale, run
echo '{"cwd":"'"$(pwd)"'"}' | ./.claude/hooks/regen-usage-dashboard.sh. To rebuild both from scratch, delete.forge/usage-state.jsonfirst; the rebuild finishes over the next few runs. -
Inspect raw data:
cat ~/.claude/forge-usage.jsonl | jq(global, all projects) orcat .forge/usage.jsonl | jq(current project only). -
Ad-hoc rollups: until a dedicated command lands, use the raw files directly:
- Current project:
cat .forge/usage.jsonl | jq -c . - Cross-project:
cat ~/.claude/forge-usage.jsonl | jq -c . - Group by project:
cat ~/.claude/forge-usage.jsonl | jq -s 'group_by(.project_name) | map({project: .[0].project_name, turns: length, input: (map(.input_tokens) | add), output: (map(.output_tokens) | add)})'
A
/forge-usageslash command is in the spec but deferred from v1 — the dashboard panel + raw files cover ad-hoc needs for now. - Current project:
Status line segment (the Forge Heartbeat “resting pulse”)
The harness ships a status-line segment provider at .claude/lib/forge-statusline-segment.sh. It is not a hook — Claude Code invokes it via the per-developer statusLine setting, not via the project’s settings.json. The harness deliberately does not register statusLine in settings.json, because the status line is the developer’s personal real estate.
Each developer runs ./install-personal-statusline.sh once per machine, which adds the segment to ~/.claude/statusline.sh and is safe to re-run. To wire it by hand instead, include this snippet (or the equivalent) — three lines, runs the provider only when it exists, fails open if it does not:
# In your personal status-line script (the one wired into ~/.claude/settings.json
# `statusLine.command`). $stdin holds the statusLine JSON Claude Code piped in.
forge_segment_path="$(echo "$stdin" | jq -r '.workspace.project_dir // .cwd // ""')/.claude/lib/forge-statusline-segment.sh"
[ -x "$forge_segment_path" ] && forge_seg=$(echo "$stdin" | "$forge_segment_path") && [ -n "$forge_seg" ] && printf '%s | ' "$forge_seg"
Inside any Forge harness the snippet emits something like:
forge | P2 Auth (3/7) · active: PRJ-002 dev (+1) | <rest of your status line>
Outside any Forge harness it emits nothing — the provider exits 0 with no output, and the trailing | is skipped because forge_seg is empty.
Notes:
- The
statusLinemechanism is terminal-only (Claude Code CLI). The desktop app and VS Code extension do not render it. The Forge harness is operated from terminal Claude Code, so this is accepted. - Zero model-context tokens:
statusLineoutput is terminal UI chrome and never enters the conversation. - The provider exposes a
--self-testmode:./.claude/lib/forge-statusline-segment.sh --self-test.
Why Hooks Exist
Rules in CLAUDE.md are probabilistic — the model knows them but may not honor them under context pressure. Hooks are deterministic:
- Tighten the feedback loop from minutes to seconds. A lint error caught at
PostToolUseis fixed on the next turn, not after CI finishes ten minutes later. - Shrink the model’s responsibility surface. Every rule in a hook is one less rule the model must remember.
- Prevent cascading errors. Bad edits caught immediately don’t propagate into files that depend on them.
- Make quality non-optional. A hook cannot be ignored under pressure.
CLAUDE.mdcan. - Teach the model in-session. Claude reads the stderr from exit-2 hooks and self-corrects — by edit #20 it’s writing project-conventional code on the first try.
Customizing
- Add protected paths — edit
protected-paths.sh, extend theprotectedarray with project-specific directories (payment code, cryptographic material, production configs). - Adjust dangerous patterns — edit
block-dangerous-bash.sh. Keep the false-positive rate low; noisy gates get disabled. - Extend lint/typecheck —
lint-and-typecheck.shhas onecasebranch per file type. Keep each invocation under 3 seconds and single-file, and skip silently when the tool is missing. - Extend Stop verification —
verify-before-stop.shcollects the changed files once; add a check over that list. Keep it to checks theRepo hygieneCI job also runs, so a Stop block always predicts a CI failure.../settings.jsonsets 600s for this hook.
Principles
- Fast beats thorough at PostToolUse. Under 3 seconds or session latency suffers.
- Exit 2 with stderr is the whole mechanism. Claude reads stderr and self-corrects on the next turn. For
UserPromptSubmit, stdout is prepended to Claude’s context instead. stop_hook_activeprevents infinite loops. AnyStophook that blocks on conditions Claude can’t fix will spiral — check the flag and bail on the second firing.- Hooks run unsandboxed with your credentials. Review changes to
../settings.jsonand every file in this directory like production code — a hostile hook can exfiltrate secrets.
Debugging
- Type
/hooksin Claude Code — confirms Claude Code sees the hook. - Run a hook manually:
echo '{"tool_input":{"file_path":"foo.ts"}}' | .claude/hooks/lint-and-typecheck.sh - Check matcher case.
Edit|Writematches,edit|writedoes not. - Exit-2 messages must go to stderr (not stdout) to reach Claude. Exception:
UserPromptSubmitwhere stdout is the injection channel. - Timeout expired? Default is 60s.
verify-before-stop.shis already set to 600s insettings.json.
The longer version is the hooks deep-dive doc in the upstream forge-harness repo.
Relationship to the Forge Quality Model
Hooks are the in-session tier of the quality ladder. They do not replace project-level lint/test/build, adversarial review, CI, or canary — they make those downstream gates hit far less often:
T0 In-agent hooks seconds Claude never "ships" a broken edit
T1 Project lint/test/build seconds Each app repo's own gate (`./gradlew check`, `pnpm check`/`test`/`build` — the repo CLAUDE.md)
T2 Adversarial review seconds /forge-pre-pr-review on the working diff; /forge-review-pr on the open PR
T3 PR CI minutes Fast lane: static checks, gitleaks, Trivy (report-only); the test suites run locally (`Test record`), and nightly on the lead's Mac (`.claude/lib/nightly/`)
T4 Canary / SLO minutes+ Runtime regression catches
A well-engineered T0 means the PRs reaching T3 are already green.