A full-featured CRM built with React, shadcn/ui, and Supabase.
Consolidate harness pipeline reliability (audit P1/P2/P3)
Jerome72b8b38679e0
diff --git a/.claude/agents/orchestrator.md b/.claude/agents/orchestrator.mdindex f9b29afa..d1ad29f0 100644--- a/.claude/agents/orchestrator.md+++ b/.claude/agents/orchestrator.md@@ -347,9 +347,9 @@ The planner runs in the **foreground** — its result returns this same turn. **For every COMPLEX request (and the continuation right after STATE A / SETUP-PLAN — the planner already ran in the foreground, output is in your context).-**Execution model.** You drive the entire feature (every wave, every stage) inside ONE continuous turn using **foreground** `Agent` calls (`run_in_background` absent/false). A foreground call blocks until the subagent returns its final line; several foreground calls in a SINGLE message run concurrently and all results come back together before you continue. You NEVER end the turn waiting for an agent. End only at a terminal point (promotion done, or every ticket failed) or when you genuinely need a user answer.+**Execution model.** You drive the entire feature (every wave, every stage) inside ONE continuous turn using **foreground** `Agent` calls. Pass `run_in_background: false` EXPLICITLY on every dispatch: an absent field means BACKGROUND in the VS Code extension, and that orphans the pipeline (see below). A foreground call blocks until the subagent returns its final line; several foreground calls in a SINGLE message run concurrently and all results come back together before you continue. You NEVER end the turn waiting for an agent. End only at a terminal point (promotion done, or every ticket failed) or when you genuinely need a user answer.-**A dispatch may be async — "launched" is NOT "done".** A foreground call is *supposed* to block, but in some runtimes (interactive Claude Code) the `Agent` tool returns immediately with `Async agent launched successfully … agentId: <id>` and the real result arrives later as a `task-notification`. Treat that acknowledgement as *dispatched, not finished*: do NOT proceed, and **do NOT re-dispatch the same role for the same ticket** to "get a result" — wait for the matching `task-notification`, then read the agent's output file and parse its contract line. **Running two agents for the same ticket+role concurrently is always a bug** — it once spawned two `quality-reviewer`s racing on one worktree. One dispatch per ticket+role in flight at a time; the `block-duplicate-dispatch` hook is a backstop, not a license to fire twice. Stage barriers still hold whether results come inline (sync) or via notifications (async): every agent dispatched in a stage must have returned before you start the next.+**Always dispatch FOREGROUND; you are NOT re-invoked.** You are a nested subagent (spawnDepth >= 1), and a nested subagent is NEVER woken when a background child completes (verified: `task-notif-reinvokes = 0`). So a background dispatch is a dead end: if you launch a child in the background and end your turn "to await the notification", the wakeup never comes, review/merge/promotion never run, and the finished dev work is orphaned. Verified by probe: an explicit `run_in_background: false` DOES block and returns the child's result inline (the runtime default is background). Therefore: set `run_in_background: false` on EVERY dispatch, and NEVER end your turn to wait for a child. The `force-foreground-orchestrator-dispatch` hook enforces this (it denies a background/absent pipeline dispatch); if you are ever denied, re-dispatch the same call with `run_in_background: false`. **Do NOT re-dispatch the same role for the same ticket** to "get a result": a foreground call already returns it inline (`block-duplicate-dispatch` is a backstop, not a license to fire twice; two `quality-reviewer`s once raced on one worktree). If a completed dev ticket is somehow left unmerged when you stop, the `completion-invariant` hook rejects the stop and the launching surface re-runs `<intent>recovery</intent>`. Stage barriers hold: every agent dispatched in a stage must have returned (inline) before you start the next.Parse the planner's output into dependency-ordered **waves**:- Wave 1 = tickets with `dependencies: []`.diff --git a/.claude/hooks/circuit-breaker.mjs b/.claude/hooks/circuit-breaker.mjsindex 50ba6cdc..12598c66 100755--- a/.claude/hooks/circuit-breaker.mjs+++ b/.claude/hooks/circuit-breaker.mjs@@ -1,8 +1,8 @@#!/usr/bin/env node-// PreToolUse(Bash) — per-subagent circuit breaker. Counts Bash calls per subagent+// PreToolUse(Bash) - per-subagent circuit breaker. Counts Bash calls per subagent// (keyed on agent_id, present only for subagents) and blocks once a subagent// exceeds the loop limit, so a stuck agent can't spin forever. The main session-// (no agent_id) is never throttled — interactive sessions legitimately make many+// (no agent_id) is never throttled - interactive sessions legitimately make many// Bash calls.import {@@ -18,17 +18,79 @@ import { createHash } from "node:crypto";import { createHookContext } from "./lib/context.mjs";import { TMP_ROOT } from "./lib/paths.mjs";-// Per-subagent Bash budget. A developer's legitimate Bash usage is worktree setup-// + git add/commit/status + exploration + fix retries (~15-20 calls). 45 is-// comfortable for that workload and catches infinite loops (which hit 100+ fast).+// Per-subagent budget of WORK calls. Read-only exploration and git plumbing/commit+// are free (see isFreeCommand), so this counts only "real work" (builds, scripts,+// migrations, rebases). 45 work calls is comfortable and catches infinite loops+// (which hit 100+ fast). Before this exclusion, devs burned the whole budget on+// grep-based symbol search (0 LSP / 209 grep in one session) and had none left to+// commit -- audit finding #02, ADR P2.const ITERATION_LIMIT = 45;+// A Bash call is "free" (never counted) when its primary command is read-only+// exploration or git plumbing/commit. Strips a leading `cd <path> &&` (the worktree+// convention) and inspects the first token of the first pipeline stage.+function isFreeCommand(raw) {+ let c = String(raw || "").trim();+ c = c.replace(/^cd\s+\S+\s*(?:&&|;)\s*/, "").trim();+ const first = c.split(/[|&;]/)[0].trim().split(/\s+/)[0] || "";+ const READONLY = new Set([+ "grep",+ "rg",+ "egrep",+ "fgrep",+ "find",+ "ls",+ "cat",+ "wc",+ "head",+ "tail",+ "pwd",+ "tree",+ "stat",+ "file",+ "which",+ "echo",+ "dirname",+ "basename",+ "realpath",+ ]);+ if (READONLY.has(first)) return true;+ const gm = c.match(/^git\s+(\S+)/);+ if (gm) {+ const GIT_FREE = new Set([+ "add",+ "commit",+ "status",+ "diff",+ "log",+ "show",+ "branch",+ "rev-parse",+ "rev-list",+ "stash",+ "worktree",+ "ls-files",+ "merge-base",+ ]);+ if (GIT_FREE.has(gm[1])) return true;+ }+ return false;+}+const input = JSON.parse(readFileSync(0, "utf8"));const ctx = createHookContext(input, "circuit-breaker");// Per-subagent breaker only. The main session (no agent_id) is never throttled.if (!ctx.agentId) process.exit(0);+// Read-only exploration (grep/find/ls/cat/...) and git plumbing (add/commit/status)+// do NOT count against the budget. The breaker exists to catch stuck WORK loops, not+// to ration symbol search or starve the final commit. See ADR P2 / audit #02.+if (isFreeCommand(input.tool_input?.command)) {+ ctx.log(`free: ${String(input.tool_input?.command ?? "").slice(0, 80)}`);+ process.exit(0);+}+const key = `sub-${ctx.agentId}`;const keyHash = createHash("sha1").update(key).digest("hex").slice(0, 16);@@ -68,7 +130,7 @@ ctx.log(`key=${key} hash=${keyHash} count=${count}`);if (count > ITERATION_LIMIT) {ctx.block({- reason: `Circuit breaker: this subagent has made ${count} Bash calls — likely stuck in a loop. Stop, and report where you are blocked so the orchestrator can re-dispatch with a fresh context.`,+ reason: `Circuit breaker: this subagent has made ${count} Bash calls - likely stuck in a loop. Stop, and report where you are blocked so the orchestrator can re-dispatch with a fresh context.`,log: `BLOCK count=${count}`,});}diff --git a/.claude/hooks/completion-invariant.mjs b/.claude/hooks/completion-invariant.mjsnew file mode 100755index 00000000..6a2d422a--- /dev/null+++ b/.claude/hooks/completion-invariant.mjs@@ -0,0 +1,142 @@+#!/usr/bin/env node+// SubagentStop(orchestrator) - completion invariant. INSURANCE for the P1 handoff+// stall: P1a (force-foreground) + P1b are the real fix (foreground blocks, verified),+// but if the orchestrator ever stops with APPROVED dev work NOT merged into the session+// branch, that is an orphaned / incomplete pipeline. Reject the stop a few times (keep+// it alive to finish the merges FOREGROUND); if it still stops orphaned, drop a+// `needs-recovery` marker so the LAUNCHING SURFACE (main thread / chat-service, which IS+// re-invokable) re-runs <intent>recovery</intent>. Fail-open: any doubt or error accepts+// the stop, so this never wedges a legitimate completion.++import {+ existsSync,+ mkdirSync,+ readFileSync,+ unlinkSync,+ writeFileSync,+} from "node:fs";+import { join } from "node:path";+import { createHookContext } from "./lib/context.mjs";+import { readAgentMeta } from "./lib/agent-meta.mjs";+import { getUnmergedTaskBranches, git } from "./lib/git.mjs";+import { sessionBranch, simpleBranch } from "./lib/topology.mjs";++const REJECT_LIMIT = 2; // reject at most twice, then allow + mark for recovery++let ctx;+try {+ const raw = readFileSync(0, "utf8");+ ctx = createHookContext(raw, "completion-invariant");+ const payload = JSON.parse(raw);++ // Only the orchestrator's stop is our concern. SubagentStop matchers do not reliably+ // filter (see cleanup-worktree) and agent_type in the payload is empty, so identify+ // via the sibling meta.json. Any doubt -> accept (never block a non-orchestrator stop).+ const meta = readAgentMeta(payload);+ if (!meta || meta.agentType !== "orchestrator") {+ ctx.accept(`not orchestrator (${meta?.agentType || "unknown"})`);+ }++ // No session branch yet -> nothing could be orphaned.+ const sessionRef = sessionBranch(ctx);+ if (+ git(["show-ref", "--verify", "--quiet", `refs/heads/${sessionRef}`])+ .status !== 0+ ) {+ ctx.accept("no session branch");+ }++ // Committed dev work not merged into the session branch. Reuse the promotion-safety+ // helper (single source of truth, fail-closed). Exclude <short>/simple (it promotes+ // straight to base, never into the session branch).+ const unmerged = getUnmergedTaskBranches(ctx.sessionShort, sessionRef, [+ simpleBranch(ctx),+ ]);++ // Only an APPROVED-but-unmerged branch is "orphaned by a stall". A branch with no+ // APPROVED review flag is a FAILED or still-in-review ticket, not our concern -+ // flagging it would be a false positive on every failed-ticket run.+ const orphaned = unmerged+ .map((u) => u.branch)+ .filter((br) => {+ const taskId = br.split("/").pop(); // <short>/TASK-XXX -> TASK-XXX+ return existsSync(+ join(ctx.ticketsDir, "reviews", `${taskId}-quality-reviewer`),+ );+ });++ if (orphaned.length === 0) {+ clearRejects();+ ctx.accept("no approved-but-unmerged work");+ }++ const list = orphaned.join(", ");+ const rejects = readRejects();++ if (rejects < REJECT_LIMIT) {+ writeRejects(rejects + 1);+ ctx.fail(+ `Completion invariant: APPROVED work on [${list}] is NOT merged into ${sessionRef}. ` ++ `You are a nested subagent and are never re-invoked by a background child, so finish ` ++ `the pipeline NOW in this turn: dispatch the merger for these FOREGROUND ` ++ `(run_in_background:false). Do not end your turn. (attempt ${rejects + 1}/${REJECT_LIMIT})`,+ { log: `reject ${rejects + 1}/${REJECT_LIMIT} orphaned=[${list}]` },+ );+ }++ // Still orphaned after REJECT_LIMIT tries -> stop looping. Hand off to the launching+ // surface: write a recovery marker and allow the stop.+ writeRecoveryMarker(orphaned);+ clearRejects();+ ctx.accept(`needs-recovery written; orphaned=[${list}]`);+} catch (e) {+ // Fail-open: our own error must never wedge a stop.+ if (ctx) ctx.log(`error, accepting: ${String(e).slice(0, 140)}`);+ process.exit(0);+}++// --- markers -----------------------------------------------------------------+function breakerFile() {+ const dir = join(ctx.sessionDir, "breaker");+ try {+ mkdirSync(dir, { recursive: true });+ } catch {+ /* best effort */+ }+ return join(dir, "completion-invariant-rejects");+}+function readRejects() {+ try {+ return parseInt(readFileSync(breakerFile(), "utf8"), 10) || 0;+ } catch {+ return 0;+ }+}+function writeRejects(n) {+ try {+ writeFileSync(breakerFile(), String(n));+ } catch {+ /* best effort */+ }+}+function clearRejects() {+ try {+ unlinkSync(breakerFile());+ } catch {+ /* absent - fine */+ }+}+function writeRecoveryMarker(branches) {+ try {+ writeFileSync(+ join(ctx.sessionDir, "needs-recovery"),+ JSON.stringify({+ reason: "orphaned-task-branches",+ branches,+ at: new Date().toISOString(),+ }) + "\n",+ );+ } catch {+ /* best effort */+ }+}diff --git a/.claude/hooks/force-foreground-orchestrator-dispatch.mjs b/.claude/hooks/force-foreground-orchestrator-dispatch.mjsnew file mode 100755index 00000000..5100ab2b--- /dev/null+++ b/.claude/hooks/force-foreground-orchestrator-dispatch.mjs@@ -0,0 +1,72 @@+#!/usr/bin/env node+// PreToolUse(Agent) - force the orchestrator's pipeline dispatches to run FOREGROUND.+//+// Root cause (transcript forensics + a probe): the VS Code extension defaults the Agent+// tool to BACKGROUND, and a nested subagent (the orchestrator, spawnDepth >= 1) is NEVER+// re-invoked when a background child completes. So a background dispatch from the+// orchestrator ends its turn "to await a notification" that never comes - review / merge /+// promotion never run and finished dev work is orphaned (audit finding #01, 4/11 sessions).+// A probe confirmed explicit run_in_background:false DOES block (child output inline) while+// the default is async; CLI defaults to foreground, so the bug only ever bit the extension.+//+// Enforcement (the prose guard in orchestrator.md was ignored): DENY any orchestrator->child+// pipeline dispatch that is not explicitly run_in_background:false, forcing a re-dispatch+// with false. Detection is by the CHILD role - only the orchestrator dispatches these - so+// main->orchestrator (child=orchestrator) and the fire-and-forget documentator are never+// touched. Fail-open: any error or unrecognized shape allows the dispatch.++import { readFileSync } from "node:fs";+import { createHookContext } from "./lib/context.mjs";+import { parseDispatch } from "./lib/dispatch-parse.mjs";++// Pipeline roles whose result the orchestrator MUST consume in the same turn. The+// orchestrator (main->orchestrator hop) and documentator (fire-and-forget) are deliberately+// excluded: their background dispatch is correct.+const PIPELINE_ROLES = new Set([+ "developer",+ "quality-reviewer",+ "merger",+ "planner",+ "simple-developer",+]);++let input;+try {+ input = JSON.parse(readFileSync(0, "utf8"));+} catch {+ process.exit(0); // no / unparseable payload -> allow+}++const ctx = createHookContext(input, "force-foreground-orchestrator-dispatch");++try {+ const d = parseDispatch(input);+ const childRole = PIPELINE_ROLES.has(d.subagentType)+ ? d.subagentType+ : PIPELINE_ROLES.has(d.role)+ ? d.role+ : "";++ // Not an orchestrator->pipeline-child dispatch -> none of our business.+ if (!childRole) ctx.accept("not a pipeline dispatch");++ // Read run_in_background RAW: parseDispatch coerces absent->false, but the difference+ // matters here - in the extension, ABSENT means the background default, which is the bug.+ // Only an EXPLICIT false is safe.+ const rib = input.tool_input?.run_in_background;+ if (rib === false) ctx.accept(`${childRole} foreground (explicit false)`);++ ctx.block({+ reason:+ `Nested orchestrator dispatch of "${childRole}" must be FOREGROUND. A nested subagent ` ++ `is never re-invoked when a background child completes, so this dispatch would orphan ` ++ `the pipeline (review/merge/promotion never run). Re-dispatch it with ` ++ `run_in_background: false - verified to block and return the child's result inline in ` ++ `this runtime.`,+ log: `blocked ${childRole} rib=${rib === undefined ? "absent" : String(rib)}`,+ });+} catch (e) {+ // Never let this gate break a real dispatch.+ ctx.log(`error, allowing: ${String(e).slice(0, 120)}`);+ process.exit(0);+}diff --git a/.claude/hooks/test/circuit-breaker.test.mjs b/.claude/hooks/test/circuit-breaker.test.mjsindex c537142e..7651080d 100644--- a/.claude/hooks/test/circuit-breaker.test.mjs+++ b/.claude/hooks/test/circuit-breaker.test.mjs@@ -1,5 +1,6 @@-// Tests for circuit-breaker.mjs — per-subagent Bash counter. Blocks are decision+// Tests for circuit-breaker.mjs - per-subagent WORK-call counter. Blocks are decision// JSON on stdout with exit 0; the main session (no agent_id) is never throttled.+// Read-only exploration and git plumbing/commit are "free" (never counted) - ADR P2.import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";@@ -20,13 +21,15 @@ afterAll(() => {});// agentId controls the per-subagent counter file; vary it per test for isolation.-const runHook = (agentId, sessionId = "cb-1234") => {+// `command` decides whether the call counts: a WORK command counts, a free one does not.+const WORK = "node work.mjs";+const runHook = (agentId, command = WORK, sessionId = "cb-1234") => {const env = { ...process.env, CRM_TMP_ROOT: tmpRoot, APP_DIR: appDir };delete env.CLAUDE_AGENT_NAME;const payload = {tool_name: "Bash",session_id: sessionId,- tool_input: { command: "ls" },+ tool_input: { command },};if (agentId) payload.agent_id = agentId;return spawnSync("node", [HOOK], {@@ -41,24 +44,68 @@ const isBlocked = (r) => r.stdout.includes('"decision":"block"');describe("circuit-breaker hook", () => {test("main session (no agent_id) is never throttled", () => {let last;- for (let i = 0; i < 60; i++) last = runHook("");+ for (let i = 0; i < 60; i++) last = runHook("", WORK);expect(last.status).toBe(0);expect(isBlocked(last)).toBe(false);});- test("subagent is blocked once it exceeds the iteration limit", () => {+ test("subagent is blocked once its WORK calls exceed the iteration limit", () => {let r;- for (let i = 1; i <= 45; i++) r = runHook("agent-loop");- expect(isBlocked(r)).toBe(false); // 45th call still allowed- const blocked = runHook("agent-loop"); // 46th+ for (let i = 1; i <= 45; i++) r = runHook("agent-loop", WORK);+ expect(isBlocked(r)).toBe(false); // 45th work call still allowed+ const blocked = runHook("agent-loop", WORK); // 46thexpect(blocked.status).toBe(0);expect(isBlocked(blocked)).toBe(true);expect(blocked.stdout).toContain("stuck in a loop");});test("each subagent has an independent budget", () => {- for (let i = 1; i <= 46; i++) runHook("agent-busy");- const otherAgent = runHook("agent-fresh");+ for (let i = 1; i <= 46; i++) runHook("agent-busy", WORK);+ const otherAgent = runHook("agent-fresh", WORK);expect(isBlocked(otherAgent)).toBe(false);});++ test("read-only search (grep/find/ls/cat) is free - never counted", () => {+ let last;+ for (const cmd of [+ "grep -rn Foo src",+ "find . -name x",+ "ls -la",+ "cat pkg.json",+ "wc -l f",+ ]) {+ for (let i = 0; i < 20; i++) last = runHook("agent-explore", cmd);+ }+ expect(isBlocked(last)).toBe(false); // 100 read-only calls, still not blocked+ });++ test("git add/commit/status is free - the final commit is never starved", () => {+ let last;+ for (let i = 0; i < 60; i++)+ last = runHook("agent-commit", 'git commit -m "feat(TASK-001): x"');+ expect(isBlocked(last)).toBe(false);+ });++ test("a `cd <worktree> &&` prefix is stripped before classifying", () => {+ // free command behind a cd prefix stays free+ let free;+ for (let i = 0; i < 60; i++)+ free = runHook("agent-cd-free", "cd /tmp/wt && grep -rn Foo src");+ expect(isBlocked(free)).toBe(false);+ // work command behind a cd prefix still counts+ let work;+ for (let i = 1; i <= 46; i++)+ work = runHook("agent-cd-work", "cd /tmp/wt && node work.mjs");+ expect(isBlocked(work)).toBe(true);+ });++ test("free calls do not consume the work budget (mixed workload)", () => {+ // 100 greps then 45 work calls on the same agent: still under the limit.+ for (let i = 0; i < 100; i++) runHook("agent-mixed", "grep -rn Foo src");+ let r;+ for (let i = 1; i <= 45; i++) r = runHook("agent-mixed", WORK);+ expect(isBlocked(r)).toBe(false); // greps did not eat the budget+ const blocked = runHook("agent-mixed", WORK); // 46th work call+ expect(isBlocked(blocked)).toBe(true);+ });});diff --git a/.claude/rules/git-policy.md b/.claude/rules/git-policy.mdindex 17b297c1..7e144cba 100644--- a/.claude/rules/git-policy.md+++ b/.claude/rules/git-policy.md@@ -5,27 +5,42 @@ paths:# Git policy for agents-Agents must not perform history-mutating git operations. The user owns-all branches, commits, merges, and pushes.--## Allowed--- `git diff` (any form — working tree, staged, against a base)-- `git status`-- `git log`-- `git branch --show-current`-- `git fetch` — to refresh remote refs for comparison-- `git stash` / `git stash pop` — to temporarily set aside changes- and inspect an alternate state--## Forbidden--- `git commit`, `git commit --amend`-- `git checkout` (branch switching), `git switch`-- `git push`, `git pull`-- `git merge`, `git rebase`-- `git reset --hard`, `git restore --source`-- Any other history-mutating or remote-mutating command--Read-only inspection is encouraged whenever it helps catch bugs (e.g.-fetching the latest base, stashing to compare two states).+The user owns the REMOTE and the promotion of shared history. Agents never push,+pull, or force-push. What an agent MAY do LOCALLY depends on its role and is scoped+to its own worktree / branch.++(Audit #03: the previous blanket "agents must not commit" contradicted the+developer's need to build its own branch and the `validate-on-stop` auto-commit, so+devs wasted budget on a "forbidden" commit and one suspected a prompt injection.+SOMETHING must commit the task branch - it is exactly what the reviewer reads and the+merger merges. This rule scopes commit rights instead of banning them.)++## Developer / simple-developer - commit your OWN task branch (required)++Building your task branch IS the mechanism the reviewer reads and the merger merges,+so you MUST commit. Allowed, scoped to `<WORKTREE_PATH>` on `BRANCH_NAME`:++- `git add`, `git commit` - atomic commits, subject `feat(TASK-XXX):` / `fix(TASK-XXX):`+- `git rebase session/<SESSION_SHORT_ID>` - rebase your OWN branch onto the session+ branch (NEVER onto the base branch: that pulls other sessions' work into yours)+- `git status` / `git diff` / `git log` / `git branch` / `git stash`++Not allowed: committing on the base branch / `session/<id>` / `main`; `git push` /+`git pull`; force-push; `git reset --hard` onto a shared ref.++## Merger - the ONLY agent that mutates shared branches++Merging task branches into `session/<id>`, promoting `session/<id>` into the base+branch under `.promote.lock`, and the promotion-lock command set in MIGRATION / PROMOTE+mode (including the destructive git ops the lock needs) ARE its job. See `merger.md`.++## quality-reviewer / planner / orchestrator / documentator - read-only git++`git diff` / `status` / `log` / `branch --show-current` / `git fetch` (read) /+`git stash`. No `commit` / `rebase` / `merge` / `push` / `pull` / `reset` / branch+`checkout`.++## Never (any role)++`git push`, `git pull`, force-push, or any write to the remote. The user owns the+remote and the base branch.diff --git a/.claude/settings.json b/.claude/settings.jsonindex 05a70116..274b68a4 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -98,6 +98,10 @@"type": "command","command": "$CLAUDE_PROJECT_DIR/.claude/hooks/enforce-dev-dispatch.mjs"},+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/force-foreground-orchestrator-dispatch.mjs"+ },{"type": "command","command": "$CLAUDE_PROJECT_DIR/.claude/hooks/setup-worktree.mjs",@@ -150,6 +154,16 @@"statusMessage": "Running validation (prettier, typecheck, unit, e2e)..."}]+ },+ {+ "matcher": "orchestrator",+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/completion-invariant.mjs",+ "timeout": 30+ }+ ]}]},diff --git a/CLAUDE.md b/CLAUDE.mdindex 950d3056..00423808 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -6,7 +6,7 @@ Code-change requests can be handled by the **agent harness**: a team of subagent**Dispatch rule (top-level session only).** Only when the request opts into the harness (triggers under "Opting in") does the top-level session dispatch the `orchestrator` agent and relay its result; never route or implement it yourself in that case. Pass your context's `<session_dir>` in the dispatch prompt (the orchestrator needs it to namespace worktrees and branches). If you are a subagent (already inside the harness), ignore this: do your own job and never dispatch an orchestrator (the `block-nested-orchestrator` hook enforces it). The orchestrator owns all routing (classification SIMPLE vs COMPLEX, plus the SETUP / MEMORY / ROLLBACK-CONFLICT / RECOVERY intents, dispatch templates, wave + promotion mechanics, and the deploy-time migration round); it drives developer/reviewer/merger to a terminal point before returning. Each agent's last line is an output contract the others parse (`.claude/rules/agent-output-format.md`).-**"Launched" is NOT "done" (read before you fill the silence).** The dispatch is *meant* to block until the orchestrator's final report, but in some runtimes (interactive Claude Code / the VS Code extension) the `Agent` tool returns immediately with `Async agent launched successfully … agentId: <id>` and the real result arrives later as a `task-notification`. That acknowledgement means dispatched, not finished. Do NOT read the quiet as "nothing is happening", and do NOT start implementing the feature yourself (no `Write`/`Edit`/`Bash` on the change, no re-dispatch): that is the exact bug that produces a duplicate, the main thread coding the same feature the orchestrator's developer is already building. While it runs your ONLY job is to surface progress and then relay the final `task-notification` report: for a `#technical-harness` run, stream its progress log into the chat (recipe under "Opting in"); for a plain `#harness` run there is no log, so just wait for the notification. This mirrors the guard the orchestrator applies to its own workers (`.claude/agents/orchestrator.md` → "launched is NOT done").+**"Launched" is NOT "done" (read before you fill the silence).** The dispatch is *meant* to block until the orchestrator's final report, but in some runtimes (interactive Claude Code / the VS Code extension) the `Agent` tool returns immediately with `Async agent launched successfully … agentId: <id>` and the real result arrives later as a `task-notification`. That acknowledgement means dispatched, not finished. Do NOT read the quiet as "nothing is happening", and do NOT start implementing the feature yourself (no `Write`/`Edit`/`Bash` on the change, no re-dispatch): that is the exact bug that produces a duplicate, the main thread coding the same feature the orchestrator's developer is already building. While it runs your ONLY job is to surface progress and then relay the final `task-notification` report: for a `#technical-harness` run, stream its progress log into the chat (recipe under "Opting in"); for a plain `#harness` run there is no log, so just wait for the notification. This mirrors the guard the orchestrator applies to its own workers (`.claude/agents/orchestrator.md` → "launched is NOT done"). On the orchestrator's completion, before relaying, check `<session_dir>/needs-recovery`: the `completion-invariant` hook writes it when the orchestrator stopped with APPROVED-but-unmerged work (a nested orchestrator cannot resume itself). If present, dispatch a FRESH `orchestrator` whose prompt begins with `<intent>recovery</intent>` and passes the same `<session_dir>` (never `SendMessage` the old one); wait for it, then relay. It clears the marker on a clean finish.**PD-ASK round-trip (migration confirmation).** The orchestrator ends its turn with a pending question, typically *"apply the database migration now?"*, and the task completes. Relay it to the user (plain text or `AskUserQuestion`). Do NOT resume the old orchestrator with `SendMessage` to relay the answer: the runtime tags coordinator messages as carrying no user authority, so a relayed approval is ignored and the orchestrator loops re-asking forever. On the user's reply:- **Approved**: dispatch a **fresh** `orchestrator` (new `Agent` call) whose prompt begins with `<intent>apply-migration</intent>`, states the approval, and passes the same `<session_dir>`; it resumes the migration round from disk and applies it.