Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Fix(harness): improv scripts code quality

Jonathan ARNAULTc358d6ce050f
diff --git a/.claude/agents/chat-orchestrator.md b/.claude/agents/chat-orchestrator.md
index e914dd08..2e358688 100644
--- a/.claude/agents/chat-orchestrator.md
+++ b/.claude/agents/chat-orchestrator.md
@@ -166,7 +166,7 @@ start it again here.
- `ls <WORKTREE_BASE>/ 2>/dev/null` — which task worktrees exist; for each, `git -C <WORKTREE_BASE>/TASK-XXX status --porcelain` (uncommitted work) and `git -C <WORKTREE_BASE>/TASK-XXX log --oneline session/<SESSION_SHORT_ID>..HEAD` (committed-but-unmerged work).
3. Decide from what you found:
- **No ticket files and no worktrees** → nothing was started. Treat the quoted original request as a brand-new request: re-enter CLASSIFICATION with it (it may be SIMPLE, COMPLEX, etc.).
- - **Tickets exist, at least one not `merged`** → resume the COMPLEX flow. `TeamCreate({team_name: "tickets-<SESSION_SHORT_ID>"})` (a PreToolUse hook wipes any orphan team of the same name from the dead run — do not assume the old team survived). Then for each non-merged ticket re-dispatch the full trio + the shared merger exactly as STATE B does, adding to each developer's `GO`: `RESUME: a worktree may already hold partial work — check for uncommitted changes and existing commits and continue from there; do not restart from scratch.` Then re-enter STATE C.
+ - **Tickets exist, at least one not `merged`** → resume the COMPLEX flow. `TeamCreate({team_name: "tickets-<SESSION_SHORT_ID>"})` (an orphan team of the same name may survive from the dead run, in which case TeamCreate auto-suffixes — always use the team name TeamCreate RETURNS verbatim in all subsequent dispatches, and do not assume the old team survived). Then for each non-merged ticket re-dispatch the full trio + the shared merger exactly as STATE B does, adding to each developer's `GO`: `RESUME: a worktree may already hold partial work — check for uncommitted changes and existing commits and continue from there; do not restart from scratch.` Then re-enter STATE C.
- **All tickets `merged` but the session branch was never promoted** → go straight to STATE D (promotion).
4. One text line to the user in their language: e.g. *"Picking your changes back up where they stopped."*
@@ -406,7 +406,6 @@ The dev's (or reviewer's) final response is in your context.
2. If reviewer returned `BLOCKED:` → you should not be here: a `BLOCKED:` routes to STATE S-FIX (silent dev loop), and only reaches the user after 2 failed fix attempts. Never merge a `BLOCKED:` change.
3. If dev returned `DONE: branch=<X>...` and (review skipped OR review `APPROVED`) → dispatch merger (no `team_name`, no SendMessage). Use the **ROLLBACK merger template** when the original user turn was `<intent>rollback-conflict</intent>`, otherwise the **SIMPLE merger template**:
```
- Bash("touch /tmp/notified-merger-<SESSION_SHORT_ID>-simple")
Agent({
subagent_type: "merger",
description: "Merge SIMPLE branch <X>", // or "Promote rollback branch <X>"
@@ -707,7 +706,6 @@ Dispatch ONE quality-reviewer (no team) with `MODE: migration-review` and the mi
Dispatch the SIMPLE merger for branch `<SESSION_SHORT_ID>/simple` (Stage A + promotion to main):
```
-Bash("touch /tmp/notified-merger-<SESSION_SHORT_ID>-simple")
Agent({
subagent_type: "merger",
description: "Merge SIMPLE branch <SESSION_SHORT_ID>/simple with migration",
diff --git a/.claude/agents/developer.md b/.claude/agents/developer.md
index dfb31ba8..5ff4d5fb 100644
--- a/.claude/agents/developer.md
+++ b/.claude/agents/developer.md
@@ -117,11 +117,11 @@ File modifications go through Edit or Write. **NEVER** use Bash to write files.
Forbidden: `sed -i`, `awk -i inplace`, `cat > file`, `cat >> file`, `echo > file`, `python3 -c '... write_text() ...'`, `node -e '... writeFileSync ...'`, any `command > file` / `command | tee file`.
-Bash writes bypass PostToolUse hooks (prettier, typecheck) and leave the codebase unformatted. Violation = rejected at review.
+Bash writes bypass the harness's edit tracking and reach reviewers unformatted. Violation = rejected at review.
## Validation commands — DO NOT RUN
-See `.claude/rules/validation-commands.md` for the full list and rationale. Short version: typecheck / prettier / unit / e2e / lint / build are blocked by `block-bash-validation`. After implementation + commit: **SendMessage to your reviewers** (WORKFLOW step 5 above). The `validate-before-review` PreToolUse hook runs validation automatically when you attempt that SendMessage — if validation fails the message is blocked and you fix + commit + retry. Do NOT stop here and wait for SubagentStop hooks; those are for simple-developer only.
+See `.claude/rules/validation-commands.md` for the full list and rationale. Short version: typecheck / prettier / unit / e2e / lint / build are blocked by `bash-guard`. After implementation + commit: **SendMessage to your reviewers** (WORKFLOW step 5 above). The `validate-before-review` PreToolUse hook runs validation automatically when you attempt that SendMessage — if validation fails the message is blocked and you fix + commit + retry. Always notify BOTH reviewers (step 5) before messaging the merger (step 8): the merger relies on reviewer approvals, and each notification revalidates only when the worktree SHA changed. Do NOT stop here and wait for SubagentStop hooks; those are for simple-developer only.
## Bash — what IS allowed
@@ -129,7 +129,7 @@ See `.claude/rules/validation-commands.md` for the full list and rationale. Shor
- Git: `git status`, `git diff`, `git log`, `git add`, `git commit`, `git worktree list`, `git branch`
- Quick fs checks where Glob/Grep don't fit: `ls -la`, `test -f`
-Each Bash counts against a 30/subagent budget. Prefer Glob/Grep/Read for exploration.
+Keep Bash usage lean — around 30 calls per ticket is the expected ceiling. Prefer Glob/Grep/Read for exploration.
## Tool call efficiency — HARD RULE
diff --git a/.claude/agents/simple-developer.md b/.claude/agents/simple-developer.md
index 56c28cee..549bfbff 100644
--- a/.claude/agents/simple-developer.md
+++ b/.claude/agents/simple-developer.md
@@ -115,7 +115,7 @@ Then `Read("$CLAUDE_PROJECT_DIR/MEMORY.md")` — domain vocabulary. Even a label
- Locate the file (Grep / Glob).
- Edit/Write the change.
-- File modifications MUST go through Edit or Write — NEVER use Bash to write files (`sed -i`, `cat > file`, `echo > file`, etc. are blocked by `block-bash-file-write`). Renames via `git mv` are allowed — the hook only blocks redirections and in-place edits, not git's own file operations.
+- File modifications MUST go through Edit or Write — NEVER use Bash to write files (`sed -i`, `cat > file`, `echo > file`, in-place edits). Renames via `git mv` are allowed.
- Stay strictly within the scope above — cosmetic, single-field (optionally with i18n labels for that field), or a list filter reusing existing components. Anything broader (multiple fields, import, new entity, new custom component) → refuse with `FAILED: out of scope — needs COMPLEX flow`.
### 4. Commit
@@ -126,7 +126,7 @@ cd <WORKTREE_PATH> && git add -A && git commit -m "simple: <one-line summary>"
### 5. Stop
-After the commit, **stop and report DONE**. The `SubagentStop` hooks (typecheck, prettier, unit tests, e2e) run automatically:
+After the commit, **stop and report DONE**. The `validate-on-stop` SubagentStop hook (prettier auto-fix, typecheck, unit tests, e2e) runs automatically:
- All pass → your stop is final, output below is returned to the orchestrator.
- One fails → you receive stderr in the next turn. Fix the issue, commit again, stop again. Loop until clean.
@@ -150,7 +150,7 @@ FAILED: <one-line reason>
## NEVER (SIMPLE mode)
-- ❌ Run `npm run typecheck`, `npm run prettier`, `npm test`, `npx playwright test`, etc. — `block-bash-validation` blocks these for you; SubagentStop hooks do them.
+- ❌ Run `npm run typecheck`, `npm run prettier`, `npm test`, `npx playwright test`, etc. — `bash-guard` blocks these for you; the `validate-on-stop` SubagentStop hook runs them.
- ❌ Run `git merge`, `git checkout main`, `git pull`, `git worktree remove` — the merger does these on the next orchestrator turn.
- ❌ SendMessage anyone — you have no peers in SIMPLE flow.
- ❌ Add tests, change unrelated logic, refactor surrounding code.
diff --git a/.claude/agents/test-validator.md b/.claude/agents/test-validator.md
index 790aa2ec..863d9b1f 100644
--- a/.claude/agents/test-validator.md
+++ b/.claude/agents/test-validator.md
@@ -123,7 +123,7 @@ Read each screenshot you take. Legibility failure (text invisible on its backgro
## Step 3 — e2e spec sanity check
-Execution is the `run-e2e-tests.mjs` hook's job (full mode only). You only verify:
+Execution is the validation hooks' job (`validate-on-stop.mjs` / `validate-before-review.mjs`, full mode only). You only verify:
- Spec file exists if acceptance criteria require it
- Spec targets the right route/component (read-only)
diff --git a/.claude/hooks/bash-guard.mjs b/.claude/hooks/bash-guard.mjs
new file mode 100755
index 00000000..359d7fad
--- /dev/null
+++ b/.claude/hooks/bash-guard.mjs
@@ -0,0 +1,103 @@
+#!/usr/bin/env node
+// PreToolUse(Bash) — single guard for Bash commands. Blocks commands that open browser windows (headed Playwright, Vite --open) for every caller, and blocks gated subagents from running validation commands (the validation hooks run them: validate-on-stop.mjs on SubagentStop, validate-before-review.mjs on SendMessage).
+
+import { readFileSync } from "node:fs";
+import { createHookContext } from "./lib/context.mjs";
+
+const input = JSON.parse(readFileSync(0, "utf8"));
+const ctx = createHookContext(input, "bash-guard");
+
+const agent = input.agent_type || "";
+const cmd = input.tool_input?.command || "";
+
+if (!cmd) process.exit(0);
+
+// Browser rules — any caller: this sandbox has no display, a headed run hangs forever.
+const opensHeadedPlaywright = (c) =>
+ /playwright/.test(c) &&
+ /(screenshot|test|codegen)/.test(c) &&
+ !c.includes("--headless");
+const opensViteBrowser = (c) =>
+ /(vite|npm run (dev|start|start-demo))/.test(c) && c.includes("--open");
+
+const BROWSER_RULES = [
+ [
+ opensHeadedPlaywright,
+ "Playwright must always use --headless. Add --headless to the command.",
+ ],
+ [
+ opensViteBrowser,
+ "Vite must not use --open (opens a browser window). Remove the --open flag.",
+ ],
+];
+
+const browserViolation = BROWSER_RULES.find(([matches]) => matches(cmd));
+if (browserViolation) {
+ ctx.block({
+ reason: browserViolation[1],
+ log: `browser cmd=${cmd.slice(0, 120)}`,
+ });
+}
+
+// Validation rules — gated subagents only: the validation hooks already run
+// these; manual runs burn budget and can hang (vitest headed without CI=true).
+const GATED_AGENTS = [
+ "developer",
+ "quality-reviewer",
+ "test-validator",
+ "simple-developer",
+];
+if (!GATED_AGENTS.includes(agent)) process.exit(0);
+
+const runsTypecheck = (c) =>
+ /(make\s+typecheck|npm\s+run\s+typecheck|npx\s+tsc(\s|$)|tsc\s+--noEmit)/.test(
+ c,
+ );
+const runsPrettier = (c) =>
+ /(npm\s+run\s+prettier(:apply)?|npx\s+prettier(\s|$)|make\s+prettier)/.test(
+ c,
+ );
+const runsUnitTests = (c) =>
+ /(npm\s+run\s+test(:unit)?(:[a-z]+)?|npm\s+test\b|npx\s+vitest|make\s+test(-unit)?(-[a-z]+)?)/.test(
+ c,
+ );
+const runsE2eTests = (c) => /(npx\s+playwright\s+test|make\s+test-e2e)/.test(c);
+const runsLint = (c) => /(make\s+lint\b|npm\s+run\s+lint\b)/.test(c);
+const runsBuild = (c) => /(npx\s+vite\s+build|npm\s+run\s+build\b|make\s+build\b)/.test(c);
+
+const VALIDATION_RULES = [
+ [
+ runsTypecheck,
+ "typecheck — the validation hooks run this automatically (validate-on-stop.mjs after you stop, validate-before-review.mjs before review messages); read their stderr output instead.",
+ ],
+ [
+ runsPrettier,
+ "prettier — the validation hooks auto-apply prettier and commit the result; don't run it manually.",
+ ],
+ [
+ runsUnitTests,
+ "unit tests — the validation hooks run vitest automatically. In this sandbox vitest browser mode HANGS without CI=true (chromium headed waits for display). Trust the hooks.",
+ ],
+ [
+ runsE2eTests,
+ "e2e tests — the validation hooks run playwright in full mode only; in demo mode they're skipped. Don't run them manually.",
+ ],
+ [
+ runsLint,
+ "lint — prettier is auto-applied by the validation hooks; eslint runs via the project's editor config. Skip it.",
+ ],
+ [
+ runsBuild,
+ "build — don't run production builds during tickets; typecheck (run by the validation hooks) catches type errors.",
+ ],
+];
+
+const violation = VALIDATION_RULES.find(([matches]) => matches(cmd));
+if (violation) {
+ ctx.block({
+ reason: `Validation command forbidden: ${violation[1]} See .claude/rules/validation-commands.md.`,
+ log: `cmd=${cmd.slice(0, 120)}`,
+ });
+}
+
+process.exit(0);
diff --git a/.claude/hooks/block-bash-file-write.mjs b/.claude/hooks/block-bash-file-write.mjs
deleted file mode 100755
index e4cbd4cb..00000000
--- a/.claude/hooks/block-bash-file-write.mjs
+++ /dev/null
@@ -1,67 +0,0 @@
-#!/usr/bin/env node
-// PreToolUse hook — block file writes via Bash.
-// Developers must use Edit/Write tools to modify files. Using bash redirection
-// (cat >, echo >, sed -i, etc.) bypasses PostToolUse hooks (prettier, typecheck)
-// and leaves orphan temp files in /tmp. Violated in run 2026-04-22-complex-priority
-// where a developer ran `cat > /tmp/task-002-update.json` leaving an empty tmp file.
-//
-// Blocks the Bash call + a clear error message telling the dev to use Edit/Write
-// instead. Allows read-only uses (grep, ls, find, cat FOR READING) and
-// legitimate git/npm/make commands.
-//
-// Input on stdin: { session_id, tool_name, tool_input, ... }
-
-import { readStdin, parseJson, crmIdentity, decisionBlock } from "./lib/common.mjs";
-
-const input = parseJson(readStdin());
-const ctx = crmIdentity(input);
-
-if (input.tool_name !== "Bash") process.exit(0);
-
-// Subagents only — this enforces "developers must use Edit/Write". The main
-// session (no agent_id) is left untouched so interactive Bash is never blocked.
-if (!ctx.agentId) process.exit(0);
-
-const cmd = input.tool_input?.command || "";
-
-let blocked = "";
-
-// File-writing redirections: `> path` or `>> path` where path isn't /dev/null
-// or a log file. Allow HERE-DOCs being consumed by git/other commands
-// (git commit -m "$(cat <<'EOF'\n...\nEOF)") — those use `<<EOF` inside $(...),
-// not `> file`.
-if (/(^|[^0-9&])>>?\s*(\/[a-zA-Z]|\.\/|[a-zA-Z][a-zA-Z0-9._-]*\.[a-zA-Z]+)/.test(cmd)) {
- // Allow explicit /dev/null
- if (!/>>?\s*\/dev\/null/.test(cmd)) {
- blocked = "bash redirection to file (> or >>). Use Edit or Write tool instead.";
- }
-}
-
-// sed -i: in-place file modification
-if (!blocked && /sed\s+(-[a-zA-Z]*i\b|--in-place)/.test(cmd)) {
- blocked = "sed -i (in-place edit). Use Edit tool instead.";
-}
-
-// awk -i inplace
-if (!blocked && /awk\s+-i\s+inplace/.test(cmd)) {
- blocked = "awk -i inplace. Use Edit tool instead.";
-}
-
-// tee writing to a file path (not /dev/null)
-if (!blocked && /\|\s*tee\s+[^-]/.test(cmd)) {
- if (!/\|\s*tee\s+(\/dev\/null|-a\s+\/dev\/null)/.test(cmd)) {
- blocked = "pipe to tee (file write). Use Write tool instead.";
- }
-}
-
-// node / python -e / -c with explicit filesystem write calls
-if (!blocked && /(node|python3?)\s+-[ecp].*(writeFileSync|writeFile|write_text|os\.write|fs\.write)/.test(cmd)) {
- blocked = "scripted file write via node/python. Use Write/Edit tool instead.";
-}
-
-if (blocked) {
- ctx.log(`block-bash-write BLOCKED cmd=${cmd.slice(0, 120)}`);
- decisionBlock(`File editing via Bash is forbidden: ${blocked} See developer.md's HARD RULE.`);
-}
-
-process.exit(0);
diff --git a/.claude/hooks/block-bash-validation.mjs b/.claude/hooks/block-bash-validation.mjs
deleted file mode 100755
index 879f6282..00000000
--- a/.claude/hooks/block-bash-validation.mjs
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/env node
-// PreToolUse hook — block subagents from running validation commands via Bash.
-// These are already run by SubagentStop hooks (typecheck, prettier, unit tests,
-// e2e). A subagent running them manually:
-// - wastes Bash budget (circuit breaker)
-// - hangs on `npx vitest` without CI=true (chromium headed mode attempts
-// to launch without display → infinite wait)
-// - produces redundant results that may conflict with hook output
-//
-// Blocks with a clear reason so the subagent knows to stop running these and
-// trust the hook output.
-//
-// Input on stdin: { session_id, tool_name, tool_input, agent_type, ... }
-
-import { readStdin, parseJson, crmIdentity, decisionBlock } from "./lib/common.mjs";
-
-const input = parseJson(readStdin());
-const ctx = crmIdentity(input);
-
-const tool = input.tool_name || "";
-const agent = input.agent_type || "";
-const cmd = input.tool_input?.command || "";
-
-if (tool !== "Bash") process.exit(0);
-
-// Only block for subagents whose prompt forbids validation commands.
-// The orchestrator (no agent_type) and planner/merger/project-manager are
-// allowed. simple-developer is also blocked — SubagentStop hooks (wired in
-// settings.json with matcher "simple-developer") do the validation; the
-// agent should not run them inline. Claude Code's PreToolUse hook matcher
-// filters on tool_name only — agent-type filtering must happen here.
-if (!["developer", "quality-reviewer", "test-validator", "simple-developer"].includes(agent)) {
- process.exit(0);
-}
-
-// Patterns to block — each matches a specific kind of validation command.
-// Use word boundaries where possible to avoid false positives (e.g., block
-// `npm run test:unit:app` but not `git log src/tests/...`).
-let blocked = "";
-
-if (/(make\s+typecheck|npm\s+run\s+typecheck|npx\s+tsc(\s|$)|tsc\s+--noEmit)/.test(cmd)) {
- blocked =
- "typecheck — the typecheck-on-commit.mjs hook runs this automatically after you finish; read its stderr output instead.";
-}
-
-if (!blocked && /(npm\s+run\s+prettier(:apply)?|npx\s+prettier(\s|$)|make\s+prettier)/.test(cmd)) {
- blocked =
- "prettier — the prettier-on-stop.mjs hook runs this automatically; read its stderr output instead.";
-}
-
-if (
- !blocked &&
- /(npm\s+run\s+test(:unit)?(:[a-z]+)?|npm\s+test\b|npx\s+vitest|make\s+test(-unit)?(-[a-z]+)?)/.test(cmd)
-) {
- blocked =
- "unit tests — the run-unit-tests-*.mjs hooks run these automatically. In this sandbox vitest browser mode HANGS without CI=true (chromium headed waits for display). Trust the hooks.";
-}
-
-if (!blocked && /(npx\s+playwright\s+test|make\s+test-e2e)/.test(cmd)) {
- blocked =
- "e2e tests — the run-e2e-tests.mjs hook runs these in full mode only; in demo mode they're skipped. Don't run them manually.";
-}
-
-if (!blocked && /(make\s+lint\b|npm\s+run\s+lint\b)/.test(cmd)) {
- blocked =
- "lint — prettier is already run by prettier-on-stop.mjs; eslint runs via the project's editor config. Skip it.";
-}
-
-if (blocked) {
- ctx.log(`block-bash-validation BLOCKED cmd=${cmd.slice(0, 120)}`);
- decisionBlock(`Validation command forbidden: ${blocked} See developer.md "Validation commands — DO NOT RUN THEM".`);
-}
-
-process.exit(0);
diff --git a/.claude/hooks/block-migration-writes.mjs b/.claude/hooks/block-migration-writes.mjs
index 157ba39b..7a754ca8 100755
--- a/.claude/hooks/block-migration-writes.mjs
+++ b/.claude/hooks/block-migration-writes.mjs
@@ -1,52 +1,43 @@
#!/usr/bin/env node
-// PreToolUse / Write|Edit hook — enforces the deferred-migration rule.
-//
-// Rule from agents/developer.md ("Never write SQL migrations") and the
-// deferred-migration design: migrations are generated only at deploy time by
-// `simple-developer` in MIGRATION MODE. Developer agents writing migrations
-// during feature TASKs is a regression that occurred in sessions 630fb0fe
-// and 2e53c631 — instructions alone don't enforce it.
-//
-// Block conditions:
-// 1. Any Write/Edit on `supabase/migrations-pending/*` — the folder was
-// removed by the deferred-migration design (see spec 2026-05-27) but
-// agents keep recreating it from training memory.
-// 2. Any Write/Edit on `supabase/migrations/*` when the calling agent is
-// `developer` (the multi-file feature-ticket agent). Migrations belong
-// to the PD-MIG round, handled by `simple-developer` only.
-//
-// Pass-through for any other agent or path. simple-developer is allowed to
-// write to supabase/migrations/ because that's its job in MIGRATION MODE.
-
-import { readStdin, parseJson, crmIdentity, decisionBlock } from "./lib/common.mjs";
-
-const input = parseJson(readStdin());
-const ctx = crmIdentity(input);
+// PreToolUse(Write|Edit) — enforce deferred migrations: block writes to supabase/migrations-pending/* and writes to supabase/migrations/* by the `developer` agent. simple-developer is allowed (MIGRATION MODE).
+
+import { readFileSync } from "node:fs";
+import { createHookContext } from "./lib/context.mjs";
+
+const input = JSON.parse(readFileSync(0, "utf8"));
+const ctx = createHookContext(input, "block-migration-writes");
const filePath = input.tool_input?.file_path || "";
if (!filePath) process.exit(0);
-// Prefer the suffixed env name (e.g. "developer-TASK-003"). Fall back to base type.
-const agent = process.env.CLAUDE_AGENT_NAME || input.agent_type || "";
-// Normalise: strip the -TASK-XXX suffix to get the base agent type.
+// Prefer the suffixed runtime name (developer-TASK-003) over the bare type.
+const agent = ctx.agentName || ctx.agentType;
const baseAgent = agent.split("-TASK-")[0];
-// Rule 1: nobody writes to supabase/migrations-pending/* — the folder is dead.
-if (filePath.includes("/supabase/migrations-pending/")) {
- ctx.log(`block-migration-writes BLOCKED agent=${agent} path=${filePath} reason=pending-folder`);
- decisionBlock(
- "supabase/migrations-pending/ was removed by the deferred-migration design (spec 2026-05-27). Migrations live in supabase/migrations/ and are written only by simple-developer in MIGRATION MODE."
- );
- process.exit(0);
-}
+const isPendingMigration = (p) => p.includes("/supabase/migrations-pending/");
+const isMigration = (p) => p.includes("/supabase/migrations/");
+
+const RULES = [
+ {
+ blocked: isPendingMigration(filePath),
+ tag: "pending-folder",
+ reason:
+ "supabase/migrations-pending/ was removed by the deferred-migration design (spec 2026-05-27). Migrations live in supabase/migrations/ and are written only by simple-developer in MIGRATION MODE.",
+ },
+ {
+ blocked: baseAgent === "developer" && isMigration(filePath),
+ tag: "developer-migration",
+ reason:
+ "developer agent is forbidden from writing SQL migrations (see agents/developer.md, deferred-migration design). Migrations are generated at deploy time by the PD-MIG round (simple-developer in MIGRATION MODE) from the session-branch diff.",
+ },
+];
-// Rule 2: developer (feature-ticket agent) never writes migrations.
-if (baseAgent === "developer" && filePath.includes("/supabase/migrations/")) {
- ctx.log(`block-migration-writes BLOCKED agent=${agent} path=${filePath} reason=developer-migration`);
- decisionBlock(
- "developer agent is forbidden from writing SQL migrations (see agents/developer.md, deferred-migration design). Migrations are generated at deploy time by the PD-MIG round (simple-developer in MIGRATION MODE) from the session-branch diff."
- );
- process.exit(0);
+const violation = RULES.find((rule) => rule.blocked);
+if (violation) {
+ ctx.block({
+ reason: violation.reason,
+ log: `agent=${agent} path=${filePath} reason=${violation.tag}`,
+ });
}
process.exit(0);
diff --git a/.claude/hooks/block-orchestrator-merge.mjs b/.claude/hooks/block-orchestrator-merge.mjs
deleted file mode 100755
index 4b298f1e..00000000
--- a/.claude/hooks/block-orchestrator-merge.mjs
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/env node
-// PreToolUse hook — block the chat-orchestrator (team-lead) from running
-// merge-class git commands via Bash.
-//
-// The orchestrator must NEVER act as merger. The shared `merger` agent is the
-// only one who runs `git merge`, `git checkout master|main`, `git pull`, or
-// `git worktree remove`. When the orchestrator falls back to doing these
-// commands itself (typically because it didn't get a "merged" report from
-// the merger), the team workflow looks healthy but is silently broken — the
-// merger agent never received the dev's "ready" message, the dev↔merger
-// communication path is dead, and the bug is hidden.
-//
-// This hook is the runtime guard. The behavioral rule is documented in
-// chat-orchestrator.md ("NEVER act as merger yourself").
-//
-// Detection: in Claude Code's PreToolUse hook input, the `agent_type` field
-// is empty ("") for the main orchestrator session, and contains the agent
-// name (e.g. "merger", "developer") for dispatched subagents. So we block
-// when agent_type is empty AND the command matches a merge-class pattern.
-//
-// Exits 2 + stderr message that points back to the rule. The orchestrator sees
-// this as a tool_use_error and must report failure to the user instead.
-
-import { readStdin, parseJson } from "./lib/common.mjs";
-
-// OPT-IN GUARD. This hook blocks the MAIN session (empty agent_type) from running
-// merge-class git commands. In the hosted chat-service the main session was always
-// the team-lead/orchestrator, so that was safe. In a plain Claude Code checkout the
-// main session is a general assistant, and blocking its git merge/pull/checkout
-// would break normal use. So it stays inert unless explicitly enabled by exporting
-// ATOMIC_CRM_ENFORCE_MERGE_GUARD=1 (e.g. by the orchestrator before a team wave).
-if (process.env.ATOMIC_CRM_ENFORCE_MERGE_GUARD !== "1") process.exit(0);
-
-const input = parseJson(readStdin());
-const tool = input.tool_name || "";
-const agent = input.agent_type || "";
-const cmd = input.tool_input?.command || "";
-
-if (tool !== "Bash") process.exit(0);
-
-// Only block when called from the main orchestrator session (agent_type empty).
-// Subagents (merger, developer, etc.) are allowed.
-if (agent) process.exit(0);
-
-let blocked = "";
-
-if (/(^|[;&|\s])git\s+merge(\s|$)/.test(cmd)) {
- blocked = "git merge";
-}
-if (!blocked && /(^|[;&|\s])git\s+checkout\s+(master|main)(\s|$)/.test(cmd)) {
- blocked = "git checkout master/main";
-}
-if (!blocked && /(^|[;&|\s])git\s+pull(\s|$)/.test(cmd)) {
- blocked = "git pull";
-}
-if (!blocked && /(^|[;&|\s])git\s+worktree\s+remove(\s|$)/.test(cmd)) {
- blocked = "git worktree remove";
-}
-if (!blocked && /apply-app-variant\.sh/.test(cmd)) {
- blocked = "apply-app-variant.sh (merger-only command)";
-}
-
-if (blocked) {
- process.stderr.write(`[block-orchestrator-merge] Blocked: orchestrator attempted to run "${blocked}".
-
-Rule: chat-orchestrator must NEVER act as merger. Only the dispatched
-\`merger\` agent runs merge-class git commands. See chat-orchestrator.md
-section "NEVER act as merger yourself".
-
-If you got here because the merger didn't report back, it means the
-team communication broke — the dev's "ready" message never reached the
-merger. Don't salvage by merging yourself. Report the failure to the
-user ("Something went wrong on the merge step. Want me to try again?")
-and stop. Salvaging hides the bug.
-
-Blocked command:
- ${cmd}
-`);
- process.exit(2);
-}
-
-process.exit(0);
diff --git a/.claude/hooks/block-premature-shutdowns.mjs b/.claude/hooks/block-premature-shutdowns.mjs
index 1944e249..4dca0bc0 100755
--- a/.claude/hooks/block-premature-shutdowns.mjs
+++ b/.claude/hooks/block-premature-shutdowns.mjs
@@ -1,66 +1,53 @@
#!/usr/bin/env node
-// PreToolUse hook — block ANY SendMessage(shutdown_request) when no merge report
-// has yet arrived in the team-lead's inbox.
-//
-// Safety-net role: the orchestrator's prompt and the agent-team skill describe
-// the correct flow (Phase 1 dispatches → wait → Phase 3 teardown after merger
-// reports). This hook is the runtime guardrail in case the model collapses
-// Phase 1 and Phase 3 into a single turn: if any shutdown_request is sent before
-// the merger has produced even one merged/merge-failed report, it is blocked.
-//
-// Generalized from "merger-only" to "all members" because the developer must
-// converse with reviewers BEFORE notifying the merger; pre-emptively shutting
-// reviewers down would break the review loop.
-//
-// Exits 2 with a stderr message pointing to the agent-team skill.
+// PreToolUse(SendMessage) — block any shutdown_request until the merger has reported a merge result (a team-lead inbox message, or a TASK-*.json with status=merged). Prevents collapsing Phase 1 and Phase 3.
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";
-import { readStdin, parseJson, crmIdentity, readJson, teamConfigs, TEAMS_DIR } from "./lib/common.mjs";
+import { stringifyMessage } from "./lib/io.mjs";
+import { createHookContext } from "./lib/context.mjs";
+import { getTeamConfigsForSession, isValidTeamName } from "./lib/teams.mjs";
+import { TEAMS_DIR } from "./lib/paths.mjs";
-const input = parseJson(readStdin());
-const ctx = crmIdentity(input);
+const isMergeReport = (text) =>
+ /(^|\s)merged\s+TASK-/.test(text) || /merge\s+failed/.test(text);
+const isTicketFile = (name) => /^TASK-.*\.json$/.test(name);
+
+const input = JSON.parse(readFileSync(0, "utf8"));
+const ctx = createHookContext(input, "block-premature-shutdowns");
const ti = input.tool_input || {};
const tool = input.tool_name || "";
const to = ti.to || "";
-const msg = typeof ti.message === "string" ? ti.message : ti.message ? JSON.stringify(ti.message) : "";
+const msg = stringifyMessage(ti.message);
const sessionId = input.session_id || "";
if (tool !== "SendMessage") process.exit(0);
-// Only gate when the message is a shutdown_request.
if (!msg.includes("shutdown_request")) process.exit(0);
-// Resolve the team. SendMessage's tool_input has no team_name. Resolution order:
-// 1. tickets-<sessionShort> derived from the session id.
-// 2. leadSessionId in config.json — covers the orchestrator when the session
-// id isn't propagated to the team config.
-// Failing both, exit 0 (fails open for non-lead senders).
let team = ti.team_name || "";
-if (!team || /[^A-Za-z0-9_-]/.test(team)) {
+if (!isValidTeamName(team)) {
team = "";
- if (ctx.sessionShort && existsSync(join(TEAMS_DIR, `tickets-${ctx.sessionShort}`))) {
+ if (
+ ctx.sessionShort &&
+ existsSync(join(TEAMS_DIR, `tickets-${ctx.sessionShort}`))
+ ) {
team = `tickets-${ctx.sessionShort}`;
}
if (!team && sessionId && existsSync(TEAMS_DIR)) {
- for (const cfg of teamConfigs()) {
- if ((readJson(cfg)?.leadSessionId || "") === sessionId) {
- team = basename(dirname(cfg));
- break;
- }
- }
+ const cfg = getTeamConfigsForSession(sessionId)[0];
+ if (cfg) team = basename(dirname(cfg));
}
}
-if (!team) process.exit(0); // No team for this session — nothing to gate against.
+if (!team) process.exit(0);
const inboxPath = join(TEAMS_DIR, team, "inboxes", "team-lead.json");
const inboxExists = existsSync(inboxPath);
-const blockWithReason = (reason) => {
- process.stderr.write(
- `[block-premature-shutdowns] Blocked: SendMessage(to: "${to}", shutdown_request)
+const blockWithReason = (reason) =>
+ ctx.fail(
+ `Blocked: SendMessage(to: "${to}", shutdown_request)
before any merge has been reported.
${reason}
@@ -78,55 +65,48 @@ issue Phase 3 shutdowns to all members in one batch.
See chat-orchestrator.md "Trigger condition for Phase 3 — strict" and
agent-team skill Phase 3.
-`
+`,
);
-};
-// Check 1: inbox messages from the merger reporting a merge result.
-let inboxCount = 0;
-if (inboxExists) {
- const inbox = readJson(inboxPath) || [];
- for (const entry of Array.isArray(inbox) ? inbox : []) {
- if ((entry.from || "") !== "merger") continue;
- const text = (entry.text || entry.message || "").toString();
- if (/(^|\s)merged\s+TASK-/.test(text) || /merge\s+failed/.test(text) || /TASK-[A-Za-z0-9_-]+\s+merge\s+failed/.test(text)) {
- inboxCount++;
- }
- }
-}
+const hasMergerReport = () => {
+ if (!inboxExists) return false;
+ const inbox = JSON.parse(readFileSync(inboxPath, "utf8")) || [];
+ return (Array.isArray(inbox) ? inbox : []).some(
+ (entry) =>
+ (entry.from || "") === "merger" &&
+ isMergeReport((entry.text || entry.message || "").toString()),
+ );
+};
-if (inboxCount >= 1) process.exit(0); // At least one merger report — allow.
+if (hasMergerReport()) process.exit(0);
-// Check 2 (fallback): any TASK-*.json in ticketsDir with "status": "merged".
-// Catches a merger that used a non-standard SendMessage format but did update
-// the ticket JSON.
-let ticketMergedCount = 0;
-if (ctx.ticketsDir && existsSync(ctx.ticketsDir)) {
+const hasMergedTicket = () => {
+ if (!ctx.ticketsDir || !existsSync(ctx.ticketsDir)) return false;
let files = [];
try {
- files = readdirSync(ctx.ticketsDir).filter((f) => /^TASK-.*\.json$/.test(f));
+ files = readdirSync(ctx.ticketsDir).filter(isTicketFile);
} catch {
- files = [];
+ return false;
}
- for (const f of files) {
+ return files.some((f) => {
try {
- if (readFileSync(join(ctx.ticketsDir, f), "utf8").includes('"status": "merged"')) ticketMergedCount++;
+ return readFileSync(join(ctx.ticketsDir, f), "utf8").includes(
+ '"status": "merged"',
+ );
} catch {
- // unreadable — skip
+ return false;
}
- }
-}
+ });
+};
-if (ticketMergedCount >= 1) process.exit(0);
+if (hasMergedTicket()) process.exit(0);
-// Nothing found — block.
if (inboxExists) {
blockWithReason(
- `The team-lead inbox at ${inboxPath} has 0 messages from the merger matching "merged TASK-..." or "...merge failed", and no TASK-*.json in ${ctx.ticketsDir} shows status=merged.`
+ `The team-lead inbox at ${inboxPath} has 0 messages from the merger matching "merged TASK-..." or "...merge failed", and no TASK-*.json in ${ctx.ticketsDir} shows status=merged.`,
);
} else {
blockWithReason(
- `The team-lead inbox at ${inboxPath} does not exist yet, and no TASK-*.json in ${ctx.ticketsDir} shows status=merged.`
+ `The team-lead inbox at ${inboxPath} does not exist yet, and no TASK-*.json in ${ctx.ticketsDir} shows status=merged.`,
);
}
-process.exit(2);
diff --git a/.claude/hooks/circuit-breaker.mjs b/.claude/hooks/circuit-breaker.mjs
deleted file mode 100755
index 57165df5..00000000
--- a/.claude/hooks/circuit-breaker.mjs
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/env node
-// PreToolUse hook — per-subagent circuit breaker.
-// Detects agents stuck in Bash loops without sabotaging legitimate multi-agent
-// workflows that cumulatively exceed a session-wide budget.
-//
-// Keyed on `agent_id` (unique per subagent dispatch). Verified empirically in
-// Claude Code 2.1.x: the hook input JSON includes `agent_id` ONLY when the
-// calling context is a subagent — absent for the top-level orchestrator.
-// So each subagent gets its own budget, and a loop in one doesn't block others.
-//
-// Input on stdin: { session_id, transcript_path, agent_id?, agent_type?,
-// tool_name, tool_input, ... }
-
-import { existsSync, mkdirSync, readFileSync, writeFileSync, statSync, unlinkSync } from "node:fs";
-import { join } from "node:path";
-import { createHash } from "node:crypto";
-import { readStdin, parseJson, crmIdentity, tmpRoot, decisionBlock } from "./lib/common.mjs";
-
-// Per-subagent Bash budget. Calibrated on the "hooks own validation" model:
-// developer doesn't run typecheck/prettier/vitest/e2e himself (those are
-// run by SubagentStop hooks and blocked at PreToolUse via
-// block-bash-validation.mjs). So a dev's legitimate Bash usage is:
-// worktree setup (1) + git add/commit/status (5-8) + git exploration (2-3)
-// + fix retries (5-10) = ~15-20 Bash calls per ticket.
-// 45 is comfortable for this workload and catches infinite loops (which
-// typically hit 100+ in a few seconds).
-const ITERATION_LIMIT = 45;
-
-const input = parseJson(readStdin());
-const ctx = crmIdentity(input);
-
-// Per-subagent breaker only. The main session (no agent_id) is never throttled —
-// an interactive session legitimately makes many Bash calls.
-if (!ctx.agentId) process.exit(0);
-
-const key = `sub-${ctx.agentId}`;
-const keyHash = createHash("sha1").update(key).digest("hex").slice(0, 16);
-
-let counterDir = join(ctx.sessionDir, "breaker");
-try {
- mkdirSync(counterDir, { recursive: true });
-} catch {
- counterDir = tmpRoot();
-}
-const counterFile = join(counterDir, `bash-count-${keyHash}`);
-
-// Auto-reset if counter file is older than 1 hour (stale subagent).
-if (existsSync(counterFile)) {
- try {
- const ageMs = Date.now() - statSync(counterFile).mtimeMs;
- if (ageMs > 60 * 60 * 1000) unlinkSync(counterFile);
- } catch {
- // ignore
- }
-}
-
-let count = 0;
-try {
- count = parseInt(readFileSync(counterFile, "utf8"), 10) || 0;
-} catch {
- count = 0;
-}
-count += 1;
-try {
- writeFileSync(counterFile, String(count));
-} catch {
- // ignore
-}
-
-// Observability: record the keyed count so we can audit per-agent budgets.
-ctx.log(`circuit-breaker key=${key} hash=${keyHash} count=${count}`);
-
-if (count > ITERATION_LIMIT) {
- decisionBlock(
- `Circuit breaker: this subagent has made ${count} Bash calls — likely stuck in a loop. Stop, report where you are blocked so the orchestrator can re-dispatch with a fresh context.`
- );
-}
-
-process.exit(0);
diff --git a/.claude/hooks/cleanup-worktree.mjs b/.claude/hooks/cleanup-worktree.mjs
index 9beec6a0..f738f338 100755
--- a/.claude/hooks/cleanup-worktree.mjs
+++ b/.claude/hooks/cleanup-worktree.mjs
@@ -1,141 +1,141 @@
#!/usr/bin/env node
-// SubagentStop hook — removes session worktrees after the merger completes.
-// Only acts on worktrees under this session's worktreeBase.
-//
-// Guard: only removes worktrees whose branch has been merged into the repo's
-// base branch AND has commits. If the merger stopped prematurely (before
-// merging), the worktree is preserved.
-
-import { existsSync, readdirSync, rmSync, rmdirSync } from "node:fs";
-import { join } from "node:path";
-import { readStdin, crmIdentity, baseBranch, git, exec } from "./lib/common.mjs";
+// SubagentStop — remove this session's task worktrees once their branch has been
+// merged (--no-ff, the merger's contract) into the session integration branch and
+// the worktree has no uncommitted changes. Session worktrees/branches (_session,
+// simple, session*/), fresh worktrees, and unmerged work are preserved.
-const ctx = crmIdentity(readStdin());
+import { existsSync, readdirSync, readFileSync, rmSync, rmdirSync } from "node:fs";
+import { join } from "node:path";
+import { createHookContext } from "./lib/context.mjs";
+import {
+ getBaseBranch,
+ getWorktreeEntries,
+ getWorktreePaths,
+ git,
+} from "./lib/git.mjs";
+import { exec } from "./lib/process.mjs";
+import {
+ isInfraWorktreePath,
+ isProtectedBranch,
+ isTaskWorktreeDirName,
+ sessionBaseBranch,
+ sessionBranch,
+} from "./lib/topology.mjs";
+
+const ctx = createHookContext(readFileSync(0, "utf8"), "cleanup-worktree");
if (!existsSync(ctx.worktreeBase)) {
- ctx.log(`cleanup-worktree SKIP ${ctx.worktreeBase} not found`);
- process.exit(0);
-}
-
-const base = baseBranch();
-ctx.log(`cleanup-worktree START session=${ctx.sessionShort} base=${ctx.worktreeBase} branch=${base}`);
-
-let removed = 0;
-let skipped = 0;
-const branchesToDelete = [];
-
-// Parse `git worktree list --porcelain` into { path, branch } entries.
-// Format: a "worktree <path>" line, optional "branch refs/heads/<name>" line
-// (absent when detached), then a blank line separating entries.
-const porcelain = git(["worktree", "list", "--porcelain"]).stdout;
-const entries = [];
-let cur = null;
-for (const line of porcelain.split("\n")) {
- if (line.startsWith("worktree ")) {
- cur = { path: line.slice("worktree ".length), branch: "" };
- entries.push(cur);
- } else if (line.startsWith("branch refs/heads/") && cur) {
- cur.branch = line.slice("branch refs/heads/".length);
- }
+ ctx.accept(`${ctx.worktreeBase} not found`);
}
-for (const { path: wtPath, branch } of entries) {
- if (!(wtPath === ctx.worktreeBase || wtPath.startsWith(ctx.worktreeBase + "/"))) continue;
-
- // Never clean the session integration worktree or the SIMPLE worktree; both
- // persist for the whole session (_session for complex merges, <ID>/simple for
- // the optional POST-DEV migration round).
- if (wtPath.endsWith("/_session") || wtPath.endsWith("/simple")) {
- ctx.log(`cleanup-worktree SKIP-SESSION-WORKTREE ${wtPath}`);
- skipped++;
- continue;
+const base = getBaseBranch();
+ctx.log(
+ `START session=${ctx.sessionShort} base=${ctx.worktreeBase} branch=${base}`,
+);
+
+const isUnderBase = (p) =>
+ p === ctx.worktreeBase || p.startsWith(ctx.worktreeBase + "/");
+
+const hasLocalBranch = (ref) =>
+ git(["show-ref", "--verify", "--quiet", `refs/heads/${ref}`]).status === 0;
+
+// Tips that were merged with --no-ff into the session integration branch: the
+// second-plus parents of its merge commits. Ancestry alone cannot tell a merged
+// branch from a fresh one that never diverged (both tips are ancestors), and a
+// fresh worktree may belong to a developer still working — so only branches
+// whose tip is a recorded merge parent are removable.
+const getMergedTips = () => {
+ const integration = sessionBranch(ctx);
+ if (!hasLocalBranch(integration)) return new Set();
+ const anchor = sessionBaseBranch(ctx);
+ const range = hasLocalBranch(anchor)
+ ? `${anchor}..${integration}`
+ : integration;
+ return new Set(
+ git(["log", "--merges", "--format=%P", range])
+ .stdout.split("\n")
+ .filter(Boolean)
+ .flatMap((line) => line.split(" ").slice(1)),
+ );
+};
+const mergedTips = getMergedTips();
+
+const shouldRemove = ({ path: wtPath, branch }) => {
+ if (isInfraWorktreePath(wtPath)) {
+ ctx.log(`SKIP-SESSION-WORKTREE ${wtPath}`);
+ return false;
}
-
- // Only remove if the branch has developer commits AND is merged into base:
- // - A detached HEAD has no branch name to check.
- // - A freshly created branch (no commits) has HEAD == base, so --merged would
- // flag it merged; check for commits first to avoid removing a just-started one.
- // - An unmerged branch with commits must be preserved until the merger runs.
if (!branch) {
- ctx.log(`cleanup-worktree SKIP-DETACHED ${wtPath} (detached HEAD)`);
- skipped++;
- continue;
+ ctx.log(`SKIP-DETACHED ${wtPath} (detached HEAD)`);
+ return false;
}
- const ahead = git(["log", "--oneline", `${base}..${branch}`]).stdout.split("\n")[0] || "";
- if (!ahead.trim()) {
- ctx.log(`cleanup-worktree SKIP-NO-COMMITS ${wtPath} branch=${branch}`);
- skipped++;
- continue;
+ const tip = git(["rev-parse", "--verify", branch]).stdout.trim();
+ if (!tip || !mergedTips.has(tip)) {
+ ctx.log(`SKIP-UNMERGED ${wtPath} branch=${branch}`);
+ return false;
}
- const mergedOut = git(["branch", "--merged", base]).stdout;
- const isMerged = mergedOut.split("\n").some((l) => l.includes(` ${branch}`));
- if (!isMerged) {
- ctx.log(`cleanup-worktree SKIP-UNMERGED ${wtPath} branch=${branch}`);
- skipped++;
- continue;
+ if (exec("git", ["-C", wtPath, "status", "--porcelain"]).stdout.trim()) {
+ ctx.log(`SKIP-DIRTY ${wtPath} (uncommitted changes)`);
+ return false;
}
+ return true;
+};
- branchesToDelete.push(branch);
+const removeWorktree = (wtPath) => {
if (git(["worktree", "remove", "--force", wtPath]).status === 0) {
- ctx.log(`cleanup-worktree REMOVED ${wtPath}`);
- } else {
- rmSync(wtPath, { recursive: true, force: true });
- ctx.log(`cleanup-worktree RM-RF ${wtPath}`);
+ ctx.log(`REMOVED ${wtPath}`);
+ return;
}
- removed++;
-}
-
-for (const branch of branchesToDelete) {
- if (!branch) continue;
- // Never delete session branches, the anchor ref, or the SIMPLE branch — they
- // must persist for the whole session (*/simple may be reused by POST-DEV migration).
- if (/^session\//.test(branch) || /^session-base\//.test(branch) || /\/simple$/.test(branch)) {
- ctx.log(`cleanup-worktree SKIP-SESSION-BRANCH ${branch}`);
- continue;
+ rmSync(wtPath, { recursive: true, force: true });
+ ctx.log(`RM-RF ${wtPath}`);
+};
+
+const deleteBranch = (branch) => {
+ if (!branch) return;
+ if (isProtectedBranch(branch)) {
+ ctx.log(`SKIP-SESSION-BRANCH ${branch}`);
+ return;
}
if (git(["branch", "-d", branch]).status !== 0) {
git(["branch", "-D", branch]);
}
- ctx.log(`cleanup-worktree BRANCH-DELETED ${branch}`);
-}
+ ctx.log(`BRANCH-DELETED ${branch}`);
+};
+
+const ourWorktrees = getWorktreeEntries().filter((e) => isUnderBase(e.path));
+const toRemove = ourWorktrees.filter(shouldRemove);
+
+toRemove.forEach((e) => removeWorktree(e.path));
+toRemove.map((e) => e.branch).forEach(deleteBranch);
git(["worktree", "prune"]);
-// Remove leftover dirs not registered as git worktrees.
-const registered = git(["worktree", "list", "--porcelain"])
- .stdout.split("\n")
- .filter((l) => l.startsWith("worktree "))
- .map((l) => l.slice("worktree ".length));
+const registered = getWorktreePaths();
-for (const entry of readdirSync(ctx.worktreeBase, { withFileTypes: true })) {
- if (!entry.isDirectory()) continue;
+const sweepLeftover = (entry) => {
+ if (!entry.isDirectory()) return;
const dir = join(ctx.worktreeBase, entry.name);
- // Never remove the session integration worktree; it persists for the whole session.
if (dir.endsWith("/_session")) {
- ctx.log(`cleanup-worktree SKIP-SESSION-LEFTOVER ${dir}`);
- continue;
+ ctx.log(`SKIP-SESSION-LEFTOVER ${dir}`);
+ return;
}
- // Only sweep orphaned *worktree* directories (named TASK-XXX or "simple"). In
- // the portable path layout `worktreeBase` IS `sessionDir`, so sibling session
- // state dirs (tickets, flags, breaker) and the hooks log live here too — they
- // are NOT worktrees and must never be deleted by this sweep. (In the original
- // chat-service layout these lived under /chat-service/logs, outside the base.)
- const isWorktreeDir = /^TASK-[0-9]+$/.test(entry.name) || entry.name === "simple";
- if (!isWorktreeDir) {
- ctx.log(`cleanup-worktree SKIP-NON-WORKTREE ${dir}`);
- continue;
+ if (!isTaskWorktreeDirName(entry.name)) {
+ ctx.log(`SKIP-NON-WORKTREE ${dir}`);
+ return;
}
- if (!registered.includes(dir)) {
- rmSync(dir, { recursive: true, force: true });
- ctx.log(`cleanup-worktree LEFTOVER RM ${dir}`);
- }
-}
+ if (registered.includes(dir)) return;
+ rmSync(dir, { recursive: true, force: true });
+ ctx.log(`LEFTOVER RM ${dir}`);
+};
+
+readdirSync(ctx.worktreeBase, { withFileTypes: true }).forEach(sweepLeftover);
try {
- rmdirSync(ctx.worktreeBase); // only succeeds if now empty
+ rmdirSync(ctx.worktreeBase);
} catch {
// not empty / already gone — fine
}
-ctx.log(`cleanup-worktree EXIT=0 removed=${removed} skipped=${skipped} session=${ctx.sessionShort}`);
-process.exit(0);
+ctx.accept(
+ `removed=${toRemove.length} skipped=${ourWorktrees.length - toRemove.length} session=${ctx.sessionShort}`,
+);
diff --git a/.claude/hooks/format-file.mjs b/.claude/hooks/format-file.mjs
deleted file mode 100755
index a2297ae0..00000000
--- a/.claude/hooks/format-file.mjs
+++ /dev/null
@@ -1,13 +0,0 @@
-#!/usr/bin/env node
-// PostToolUse hook — runs prettier --write on the file a Write/Edit just touched.
-// (Not currently wired in settings.json; kept for ad-hoc use.)
-
-import { readStdin, parseJson, exec } from "./lib/common.mjs";
-
-const input = parseJson(readStdin());
-const filePath = input.tool_input?.file_path || input.tool_input?.notebook_path || "";
-
-// Only format files with supported extensions.
-if (/\.(ts|tsx|js|jsx|json|css|md|html)$/.test(filePath)) {
- exec("npx", ["prettier", "--write", filePath]);
-}
diff --git a/.claude/hooks/lib/common.mjs b/.claude/hooks/lib/common.mjs
deleted file mode 100644
index 0bd779cf..00000000
--- a/.claude/hooks/lib/common.mjs
+++ /dev/null
@@ -1,285 +0,0 @@
-// Portable path + identity helpers for Atomic CRM .claude hooks.
-//
-// These hooks were migrated from a hosted "chat-service" harness that hard-coded
-// /app (repo), /chat-service/logs (per-session dir) and /home/developer/.claude
-// (config home), and relied on injected env vars (CHAT_SESSION_DIR,
-// CLAUDE_AGENT_NAME). None of that exists in a plain Claude Code checkout. This
-// library derives every path from the running environment so the hooks work
-// wherever the repo lives.
-//
-// Usage — import near the top of a hook, then derive identity from the stdin
-// JSON the hook reads on fd 0:
-//
-// import { readStdin, crmIdentity } from "./lib/common.mjs";
-// const ctx = crmIdentity(readStdin());
-// ctx.log("my-hook START");
-//
-// crmIdentity returns a context object with the session-scoped paths
-// (sessionDir, worktreeBase, logFile, ticketsDir, flagsDir, sessionId,
-// sessionShort, agentType, agentId, transcriptPath) plus bound helpers
-// (log, linkNodeModules). Hooks that only need REPO / CONFIG_DIR / TEAMS_DIR
-// can import those constants directly without calling crmIdentity.
-//
-// Portability model:
-// REPO project root <- $APP_DIR | $CLAUDE_PROJECT_DIR | git toplevel | $PWD
-// CONFIG_DIR Claude config home <- $CLAUDE_CONFIG_DIR | $HOME/.claude
-// TEAMS_DIR team state <- $CONFIG_DIR/teams
-// sessionId full session id <- stdin .session_id (Claude Code native)
-// sessionDir per-session scratch <- /tmp/<REPO with '/'->'_'>/<sessionId>
-// worktreeBase git worktrees <- sessionDir (children: TASK-XXX, _session, simple)
-// logFile hook log <- sessionDir/hooks.log
-// ticketsDir ticket JSON files <- sessionDir/tickets
-// flagsDir coordination flags <- sessionDir/flags
-
-import { readFileSync, readdirSync, mkdirSync, appendFileSync, existsSync, symlinkSync, unlinkSync } from "node:fs";
-import { dirname, basename, join } from "node:path";
-import { tmpdir } from "node:os";
-import { spawnSync } from "node:child_process";
-
-// --- project root (replaces hard-coded /app) ------------------------------
-// APP_DIR is honored as an explicit override (used by the hook tests) and kept
-// as a back-compat alias; it otherwise tracks REPO.
-function deriveRepo() {
- if (process.env.APP_DIR) return process.env.APP_DIR;
- if (process.env.CLAUDE_PROJECT_DIR) return process.env.CLAUDE_PROJECT_DIR;
- const top = spawnSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8" });
- if (top.status === 0 && top.stdout.trim()) return top.stdout.trim();
- return process.cwd();
-}
-
-export const REPO = deriveRepo();
-export const APP_DIR = REPO;
-
-// --- config home (replaces /home/developer/.claude) -----------------------
-export const CONFIG_DIR =
- process.env.CLAUDE_CONFIG_DIR || join(process.env.HOME || "/root", ".claude");
-export const TEAMS_DIR = join(CONFIG_DIR, "teams");
-
-// Root of per-session scratch. Tests / callers may override with CRM_TMP_ROOT.
-export function tmpRoot() {
- return process.env.CRM_TMP_ROOT || "/tmp";
-}
-
-// Sanitize a path by replacing every "/" with "_" — implements the
-// `${path.replace('/', '_')}` worktree-directory convention.
-export function sanitizePath(p) {
- return String(p ?? "").replace(/\//g, "_");
-}
-
-// Repo default branch (base for worktrees / merge checks). Replaces hard-coded
-// "master"/"main".
-export function baseBranch() {
- const r = spawnSync("git", ["-C", REPO, "symbolic-ref", "--short", "HEAD"], { encoding: "utf8" });
- const name = r.status === 0 ? r.stdout.trim() : "";
- return name || "main";
-}
-
-// Read the hook's stdin (fd 0) as a string. Returns "" if nothing is piped.
-export function readStdin() {
- try {
- return readFileSync(0, "utf8");
- } catch {
- return "";
- }
-}
-
-// Parse a JSON string defensively — never throws, returns {} on failure.
-export function parseJson(str) {
- try {
- return JSON.parse(str || "{}") || {};
- } catch {
- return {};
- }
-}
-
-// Read + parse a JSON file. Returns null on any error (missing / malformed).
-export function readJson(path) {
- try {
- return JSON.parse(readFileSync(path, "utf8"));
- } catch {
- return null;
- }
-}
-
-// Absolute paths of every <TEAMS_DIR>/<team>/config.json (the team registry).
-// Mirrors `find "$TEAMS_DIR" -mindepth 2 -maxdepth 2 -name config.json`.
-export function teamConfigs() {
- try {
- return readdirSync(TEAMS_DIR, { withFileTypes: true })
- .filter((e) => e.isDirectory())
- .map((e) => join(TEAMS_DIR, e.name, "config.json"))
- .filter((p) => existsSync(p));
- } catch {
- return [];
- }
-}
-
-// Run a command without throwing. Returns { status, stdout, stderr }.
-// `status` is the numeric exit code (1 when the binary could not be spawned).
-export function exec(file, args = [], opts = {}) {
- const r = spawnSync(file, args, { encoding: "utf8", ...opts });
- return {
- status: r.status ?? (r.error ? 1 : 0),
- stdout: r.stdout ?? "",
- stderr: r.stderr ?? "",
- error: r.error,
- };
-}
-
-// Run a shell pipeline via `bash -c`. Same return shape as exec().
-export function bash(cmd, opts = {}) {
- return exec("bash", ["-c", cmd], opts);
-}
-
-// Convenience: `git -C <REPO> ...`. Returns { status, stdout, stderr }.
-export function git(args = [], opts = {}) {
- return exec("git", ["-C", REPO, ...args], opts);
-}
-
-// Print a PreToolUse "block" decision to stdout (the JSON-decision mechanism).
-// The caller still exits 0 afterwards — Claude Code reads the decision from stdout.
-export function decisionBlock(reason) {
- process.stdout.write(JSON.stringify({ decision: "block", reason }) + "\n");
-}
-
-// Derive identity + session-scoped paths from a hook's stdin (raw JSON string or
-// an already-parsed object). Ported from the original bash crm_identity.
-export function crmIdentity(input) {
- const i = typeof input === "string" ? parseJson(input) : input || {};
- const clean = (s) => String(s ?? "").replace(/[\t\n]/g, " ");
-
- let sessionId = clean(i.session_id);
- let agentType = clean(i.agent_type);
- const agentId = clean(i.agent_id);
- const transcriptPath = clean(i.transcript_path);
-
- // Fallbacks. CLAUDE_AGENT_NAME / CHAT_SESSION_DIR are chat-service-era vars,
- // honored only if still injected, never required.
- if (!sessionId) sessionId = process.env.CLAUDE_CODE_SESSION_ID || "";
- if (!sessionId && process.env.CHAT_SESSION_DIR) sessionId = basename(process.env.CHAT_SESSION_DIR);
- if (!sessionId) sessionId = "default";
- if (!agentType) agentType = process.env.CLAUDE_AGENT_NAME || "";
-
- // First dash-segment of the session id — a short, readable branch component.
- const sessionShort = sessionId.split("-")[0];
- const sessionDir = join(tmpRoot(), sanitizePath(REPO), sessionId);
- const logFile = join(sessionDir, "hooks.log");
-
- const ctx = {
- repo: REPO,
- configDir: CONFIG_DIR,
- teamsDir: TEAMS_DIR,
- sessionId,
- agentType,
- agentId,
- transcriptPath,
- sessionShort,
- sessionDir,
- worktreeBase: sessionDir,
- logFile,
- ticketsDir: process.env.TICKETS_DIR || join(sessionDir, "tickets"),
- flagsDir: join(sessionDir, "flags"),
-
- // Append a timestamped line to logFile, creating its directory on demand.
- log(...parts) {
- try {
- mkdirSync(dirname(logFile), { recursive: true });
- appendFileSync(logFile, `[${new Date().toISOString()}] ${parts.join(" ")}\n`);
- } catch {
- // no-op safe — logging must never break a hook
- }
- },
-
- // Link the repo's node_modules into a worktree. Tries a hard-link tree
- // (fast, zero-copy, same filesystem) and falls back to a symlink when the
- // worktree is on a different filesystem (e.g. /tmp on tmpfs).
- linkNodeModules(wt) {
- const target = join(wt, "node_modules");
- if (existsSync(target)) return;
- if (!existsSync(join(REPO, "node_modules"))) return;
- if (exec("cp", ["-al", join(REPO, "node_modules"), target]).status === 0) return;
- try {
- symlinkSync(join(REPO, "node_modules"), target);
- } catch {
- // best-effort
- }
- },
- };
-
- return ctx;
-}
-
-// --- validation-runner helpers (shared by the SubagentStop check hooks) ----
-
-// Active feature worktrees to validate. When VALIDATE_WORKTREE is set (by
-// validate-before-review), restrict to that single worktree; otherwise every
-// registered worktree under this session's worktreeBase. Mirrors the
-// `git worktree list --porcelain | awk … | grep "^$WORKTREE_BASE/"` chain.
-export function activeWorktrees(ctx) {
- const only = process.env.VALIDATE_WORKTREE;
- if (only && existsSync(only)) return [only];
- return git(["worktree", "list", "--porcelain"])
- .stdout.split("\n")
- .filter((l) => l.startsWith("worktree "))
- .map((l) => l.slice("worktree ".length))
- .filter((p) => p.startsWith(ctx.worktreeBase + "/"));
-}
-
-// True when a worktree has uncommitted changes OR commits ahead of base.
-export function worktreeDirty(wt, base) {
- const changed = exec("git", ["-C", wt, "status", "--porcelain"]).stdout.trim();
- const ahead = exec("git", ["-C", wt, "log", "--oneline", `${base}..HEAD`]).stdout.trim();
- return Boolean(changed || ahead);
-}
-
-// Changed file paths in a worktree (committed vs base + working tree), deduped,
-// empties dropped. Mirrors the `git diff --name-only … ; git status --porcelain
-// | awk '{print $NF}' | sort -u | grep -v '^$'` pipeline.
-export function worktreeChangedFiles(wt, base) {
- const files = new Set();
- const committed = exec("git", ["-C", wt, "diff", "--name-only", `${base}..HEAD`]).stdout;
- for (const l of committed.split("\n")) if (l.trim()) files.add(l.trim());
- const working = exec("git", ["-C", wt, "status", "--porcelain"]).stdout;
- for (const l of working.split("\n")) {
- const t = l.trim();
- if (!t) continue;
- const parts = t.split(/\s+/);
- files.add(parts[parts.length - 1]); // $NF — last field
- }
- return [...files];
-}
-
-// Keep only the last `n` lines of a text blob (like `tail -n`).
-export function tailLines(text, n) {
- return text.split("\n").slice(-n).join("\n");
-}
-
-// Run vitest once (CI mode, headless) against a config file, capturing output
-// via a temp file rather than a pipe. The bash hooks did this deliberately: a
-// lingering vitest worker can keep the stdout pipe open after the main process
-// exits, which would hang a $()-style capture forever. Writing to a file lets
-// the parent return as soon as the (coreutils) `timeout` wrapper exits.
-// Returns { status, output, timedOut }. status 124 == timeout.
-// `projects` (optional) narrows the run to specific vitest projects via repeated
-// --project flags — used since the app/claude/functions suites share one config.
-export function runVitest(wt, configFile, projects = []) {
- const projectTag = projects.length ? `-${projects.join("-")}` : "";
- const out = join(tmpdir(), `vitest-${basename(configFile)}${projectTag}-${process.pid}.out`);
- const projectFlags = projects.map((p) => `--project ${p}`).join(" ");
- const r = bash(
- `CI=true timeout 180 npx vitest run --config ${configFile} ${projectFlags} > "${out}" 2>&1`,
- { cwd: wt },
- );
- let output = "";
- try {
- output = tailLines(readFileSync(out, "utf8"), 40);
- } catch {
- // no output file — leave empty
- }
- try {
- unlinkSync(out);
- } catch {
- // best-effort cleanup
- }
- return { status: r.status, output, timedOut: r.status === 124 };
-}
diff --git a/.claude/hooks/lib/context.mjs b/.claude/hooks/lib/context.mjs
new file mode 100644
index 00000000..aa8f50a1
--- /dev/null
+++ b/.claude/hooks/lib/context.mjs
@@ -0,0 +1,129 @@
+// Build a hook context from a hook's stdin payload: identity, session-scoped
+// paths, a logger, and terminal accept/block/fail helpers. The `name` is the
+// hook's label; log() and error() prefix every line with `[name]`, and
+// accept/block/fail add the `ACCEPT|BLOCK|FAIL` verb on top — so call sites pass
+// only the detail and never repeat the name.
+
+import { mkdirSync, appendFileSync, existsSync, symlinkSync } from "node:fs";
+import { dirname, basename, join } from "node:path";
+import { decisionBlock } from "./io.mjs";
+import { exec } from "./process.mjs";
+import { REPO, TMP_ROOT, sanitizePath } from "./paths.mjs";
+
+/**
+ * @param {string | Record<string, unknown>} input
+ * @param {string} [name]
+ * @returns {object}
+ */
+export function createHookContext(input, name = "hook") {
+ const i = typeof input === "string" ? JSON.parse(input) : input || {};
+ const clean = (s) => String(s ?? "").replace(/[\t\n]/g, " ");
+
+ const agentId = clean(i.agent_id);
+ // agentName is the runtime-assigned (possibly TASK-suffixed) name from the
+ // environment; agentType prefers the payload's agent_type and falls back to it.
+ const agentName = process.env.CLAUDE_AGENT_NAME || "";
+ const chatSessionId = process.env.CHAT_SESSION_DIR ? basename(process.env.CHAT_SESSION_DIR) : "";
+
+ const sessionId =
+ clean(i.session_id) || process.env.CLAUDE_CODE_SESSION_ID || chatSessionId || "default";
+ const agentType = clean(i.agent_type) || agentName;
+
+ const sessionShort = sessionId.split("-")[0];
+ const sessionDir = join(TMP_ROOT, sanitizePath(REPO), sessionId);
+ const logFile = join(sessionDir, "hooks.log");
+
+ /**
+ * @param {...unknown} parts
+ * @returns {void}
+ */
+ const log = (...parts) => {
+ try {
+ mkdirSync(dirname(logFile), { recursive: true });
+ appendFileSync(
+ logFile,
+ `[${new Date().toISOString()}] [${name}] ${parts.join(" ")}\n`,
+ );
+ } catch {
+ // logging must never break a hook
+ }
+ };
+
+ /**
+ * Write to stderr (the agent-visible channel), prefixed with `[${name}]` the
+ * same way log() prefixes each log line. The prefix is added once, so
+ * multi-line payloads (compiler/test output) stay readable; a trailing
+ * newline is ensured.
+ * @param {...unknown} parts
+ * @returns {void}
+ */
+ const error = (...parts) => {
+ const text = parts.join(" ");
+ process.stderr.write(`[${name}] ${text}${text.endsWith("\n") ? "" : "\n"}`);
+ };
+
+ const verdict = (verb, detail) => log(detail ? `${verb} ${detail}` : verb);
+
+ return {
+ name,
+ repo: REPO,
+ sessionId,
+ agentType,
+ agentName,
+ agentId,
+ sessionShort,
+ sessionDir,
+ worktreeBase: sessionDir,
+ logFile,
+ ticketsDir: process.env.TICKETS_DIR || join(sessionDir, "tickets"),
+
+ log,
+ error,
+
+ /**
+ * @param {string} [detail]
+ * @returns {never}
+ */
+ accept(detail) {
+ verdict("ACCEPT", detail);
+ process.exit(0);
+ },
+
+ /**
+ * @param {{ reason: string, log?: string }} options
+ * @returns {never}
+ */
+ block({ reason, log: detail }) {
+ verdict("BLOCK", detail);
+ decisionBlock(reason);
+ process.exit(0);
+ },
+
+ /**
+ * @param {string} message
+ * @param {{ log?: string }} [options]
+ * @returns {never}
+ */
+ fail(message, { log: detail } = {}) {
+ verdict("FAIL", detail);
+ error(message);
+ process.exit(2);
+ },
+
+ /**
+ * @param {string} wt
+ * @returns {void}
+ */
+ linkNodeModules(wt) {
+ const target = join(wt, "node_modules");
+ if (existsSync(target)) return;
+ if (!existsSync(join(REPO, "node_modules"))) return;
+ if (exec("cp", ["-al", join(REPO, "node_modules"), target]).status === 0) return;
+ try {
+ symlinkSync(join(REPO, "node_modules"), target);
+ } catch {
+ // best-effort
+ }
+ },
+ };
+}
diff --git a/.claude/hooks/lib/git.mjs b/.claude/hooks/lib/git.mjs
new file mode 100644
index 00000000..1c751f8d
--- /dev/null
+++ b/.claude/hooks/lib/git.mjs
@@ -0,0 +1,54 @@
+// Git repo and worktree state queries.
+
+import { REPO } from "./paths.mjs";
+import { exec } from "./process.mjs";
+
+export function git(args = [], opts = {}) {
+ return exec("git", ["-C", REPO, ...args], opts);
+}
+
+export function getBaseBranch() {
+ const r = git(["symbolic-ref", "--short", "HEAD"]);
+ return (r.status === 0 ? r.stdout.trim() : "") || "main";
+}
+
+const WORKTREE_PREFIX = "worktree ";
+const BRANCH_PREFIX = "branch refs/heads/";
+
+// Value of the first line carrying `prefix`, stripped of it; "" when absent.
+const lineValue = (lines, prefix) => {
+ const line = lines.find((l) => l.startsWith(prefix));
+ return line ? line.slice(prefix.length) : "";
+};
+
+// `--porcelain` emits one blank-line-separated block per worktree, each opening
+// with a `worktree <path>` line and (unless detached/bare) a `branch refs/...`
+// line. Parse each block independently; drop blocks with no path (trailing blank).
+export function getWorktreeEntries() {
+ return git(["worktree", "list", "--porcelain"]).stdout
+ .split("\n\n")
+ .map((block) => block.split("\n"))
+ .map((lines) => ({
+ path: lineValue(lines, WORKTREE_PREFIX),
+ branch: lineValue(lines, BRANCH_PREFIX),
+ }))
+ .filter((entry) => entry.path);
+}
+
+export const getWorktreePaths = () => getWorktreeEntries().map((e) => e.path);
+
+export function isWorktreeDirty(wt, base) {
+ const changed = exec("git", ["-C", wt, "status", "--porcelain"]).stdout.trim();
+ const ahead = exec("git", ["-C", wt, "log", "--oneline", `${base}..HEAD`]).stdout.trim();
+ return Boolean(changed || ahead);
+}
+
+export function getWorktreeChangedFiles(wt, base) {
+ const nonEmpty = (lines) => lines.split("\n").filter((l) => l.trim());
+ const statusPath = (line) => line.trim().split(/\s+/).pop();
+ const committed = exec("git", ["-C", wt, "diff", "--name-only", `${base}..HEAD`]).stdout;
+ const working = exec("git", ["-C", wt, "status", "--porcelain"]).stdout;
+ return [
+ ...new Set([...nonEmpty(committed).map((l) => l.trim()), ...nonEmpty(working).map(statusPath)]),
+ ];
+}
diff --git a/.claude/hooks/lib/io.mjs b/.claude/hooks/lib/io.mjs
new file mode 100644
index 00000000..060949e5
--- /dev/null
+++ b/.claude/hooks/lib/io.mjs
@@ -0,0 +1,10 @@
+// SendMessage bodies may be strings or structured objects; gating hooks match
+// substrings (shutdown_request, TASK-XXX) against one canonical stringification.
+export function stringifyMessage(message) {
+ if (typeof message === "string") return message;
+ return message != null ? JSON.stringify(message) : "";
+}
+
+export function decisionBlock(reason) {
+ process.stdout.write(JSON.stringify({ decision: "block", reason }) + "\n");
+}
diff --git a/.claude/hooks/lib/paths.mjs b/.claude/hooks/lib/paths.mjs
new file mode 100644
index 00000000..bacd4768
--- /dev/null
+++ b/.claude/hooks/lib/paths.mjs
@@ -0,0 +1,22 @@
+import { join } from "node:path";
+import { exec } from "./process.mjs";
+
+// APP_DIR / CLAUDE_PROJECT_DIR override the detected root (used by hook tests).
+function getRepo() {
+ if (process.env.APP_DIR) return process.env.APP_DIR;
+ if (process.env.CLAUDE_PROJECT_DIR) return process.env.CLAUDE_PROJECT_DIR;
+ const top = exec("git", ["rev-parse", "--show-toplevel"]);
+ if (top.status === 0 && top.stdout.trim()) return top.stdout.trim();
+ return process.cwd();
+}
+
+export const REPO = getRepo();
+
+export const CONFIG_DIR =
+ process.env.CLAUDE_CONFIG_DIR || join(process.env.HOME || "/root", ".claude");
+export const TEAMS_DIR = join(CONFIG_DIR, "teams");
+export const TMP_ROOT = process.env.CRM_TMP_ROOT || "/tmp";
+
+export function sanitizePath(p) {
+ return String(p ?? "").replace(/\//g, "_");
+}
diff --git a/.claude/hooks/lib/process.mjs b/.claude/hooks/lib/process.mjs
new file mode 100644
index 00000000..4b3d8357
--- /dev/null
+++ b/.claude/hooks/lib/process.mjs
@@ -0,0 +1,15 @@
+import { spawnSync } from "node:child_process";
+
+export function exec(file, args = [], opts = {}) {
+ const r = spawnSync(file, args, { encoding: "utf8", ...opts });
+ return {
+ status: r.status ?? (r.error ? 1 : 0),
+ stdout: r.stdout ?? "",
+ stderr: r.stderr ?? "",
+ error: r.error,
+ };
+}
+
+export function bash(cmd, opts = {}) {
+ return exec("bash", ["-c", cmd], opts);
+}
diff --git a/.claude/hooks/lib/teams.mjs b/.claude/hooks/lib/teams.mjs
new file mode 100644
index 00000000..9382df4e
--- /dev/null
+++ b/.claude/hooks/lib/teams.mjs
@@ -0,0 +1,34 @@
+import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { TEAMS_DIR } from "./paths.mjs";
+
+export const isValidTeamName = (name) => /^[A-Za-z0-9_-]+$/.test(name || "");
+
+export const getFirstTaskId = (text) => (String(text ?? "").match(/TASK-[0-9]+/) || [])[0] || "";
+
+// Agent-name role predicates — the single source for every hook that gates on
+// who an agent is. Match the bare role, a suffixed name (merger-TASK-003), or
+// an @-qualified address.
+export const isDeveloper = (name) => /^developer([-@]|$)/.test(name || "");
+export const isQualityReviewer = (name) => /^quality-reviewer([-@]|$)/.test(name || "");
+export const isTestValidator = (name) => /^test-validator([-@]|$)/.test(name || "");
+export const isMerger = (name) => /^merger([-@]|$)/.test(name || "");
+
+// Internal: enumerated only by getTeamConfigsForSession below.
+function getTeamConfigs() {
+ try {
+ return readdirSync(TEAMS_DIR, { withFileTypes: true })
+ .filter((e) => e.isDirectory())
+ .map((e) => join(TEAMS_DIR, e.name, "config.json"))
+ .filter((p) => existsSync(p));
+ } catch {
+ return [];
+ }
+}
+
+// Team configs whose leadSessionId matches the given session — the ownership
+// lookup used by block-premature-shutdowns.
+export const getTeamConfigsForSession = (sessionId) =>
+ getTeamConfigs().filter(
+ (cfg) => (JSON.parse(readFileSync(cfg, "utf8"))?.leadSessionId || "") === (sessionId || ""),
+ );
diff --git a/.claude/hooks/lib/topology.mjs b/.claude/hooks/lib/topology.mjs
new file mode 100644
index 00000000..47d8950e
--- /dev/null
+++ b/.claude/hooks/lib/topology.mjs
@@ -0,0 +1,25 @@
+// Session worktree/branch topology — the single source for the layout created
+// by setup-worktree and torn down by cleanup-worktree:
+// <worktreeBase>/TASK-XXX on branch <short>/TASK-XXX (one per ticket)
+// <worktreeBase>/simple on branch <short>/simple (SIMPLE flow / migration)
+// <worktreeBase>/_session on branch session/<short> (merger integration)
+// session-base/<short> (fixed fork anchor)
+// Every hook that builds or matches these names must go through this module.
+
+import { join } from "node:path";
+
+export const taskWorktreePath = (ctx, taskId) => join(ctx.worktreeBase, taskId);
+export const simpleWorktreePath = (ctx) => join(ctx.worktreeBase, "simple");
+export const sessionWorktreePath = (ctx) => join(ctx.worktreeBase, "_session");
+
+export const taskBranch = (ctx, taskId) => `${ctx.sessionShort}/${taskId}`;
+export const simpleBranch = (ctx) => `${ctx.sessionShort}/simple`;
+export const sessionBranch = (ctx) => `session/${ctx.sessionShort}`;
+export const sessionBaseBranch = (ctx) => `session-base/${ctx.sessionShort}`;
+
+// Infrastructure worktrees are never removed by cleanup.
+export const isInfraWorktreePath = (p) => p.endsWith("/_session") || p.endsWith("/simple");
+// Session-lifetime branches are never deleted by cleanup.
+export const isProtectedBranch = (b) => /^session(-base)?\//.test(b) || /\/simple$/.test(b);
+// Directory names under <worktreeBase> that the leftover sweep may touch.
+export const isTaskWorktreeDirName = (name) => /^TASK-[0-9]+$/.test(name) || name === "simple";
diff --git a/.claude/hooks/lib/validation.mjs b/.claude/hooks/lib/validation.mjs
new file mode 100644
index 00000000..43a2323c
--- /dev/null
+++ b/.claude/hooks/lib/validation.mjs
@@ -0,0 +1,150 @@
+import { existsSync, readFileSync, unlinkSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { basename, join } from "node:path";
+import { getBaseBranch, getWorktreeChangedFiles, getWorktreePaths, isWorktreeDirty } from "./git.mjs";
+import { bash, exec } from "./process.mjs";
+
+// `only` narrows to a single worktree when the caller already knows it
+// (validate-before-review with a task id); VALIDATE_WORKTREE is the test
+// override. Either falls back to all session worktrees when the path is gone.
+export function getActiveWorktrees(ctx, only = "") {
+ const narrowed = only || process.env.VALIDATE_WORKTREE || "";
+ if (narrowed && existsSync(narrowed)) return [narrowed];
+ return getWorktreePaths().filter((p) => p.startsWith(ctx.worktreeBase + "/"));
+}
+
+// Pure query — never exits. An empty list with a non-empty skipReason means
+// there is nothing to validate.
+function getWorktreesToValidate(ctx, { skipAdrOnly = false, only = "" } = {}) {
+ if (!existsSync(ctx.repo)) {
+ return { worktrees: [], skipReason: "cd_failed" };
+ }
+ const active = getActiveWorktrees(ctx, only);
+ if (active.length === 0) {
+ return { worktrees: [], skipReason: "no_active_worktree" };
+ }
+ const base = getBaseBranch();
+ const isAdrOnly = (files) => files.length > 0 && files.every((f) => f.startsWith("adr/"));
+ const worktrees = active.filter((wt) => {
+ if (!isWorktreeDirty(wt, base)) {
+ ctx.log(`SKIP wt=${wt} (no changes)`);
+ return false;
+ }
+ if (skipAdrOnly && isAdrOnly(getWorktreeChangedFiles(wt, base))) {
+ ctx.log(`SKIP wt=${wt} (adr-only)`);
+ return false;
+ }
+ return true;
+ });
+ return { worktrees, skipReason: worktrees.length === 0 ? "no_dirty_worktree" : "" };
+}
+
+const tailLines = (text, n) => text.split("\n").slice(-n).join("\n");
+
+// Last `n` lines of a file, "" if it can't be read.
+const tailFile = (path, n) => {
+ try {
+ return tailLines(readFileSync(path, "utf8"), n);
+ } catch {
+ return "";
+ }
+};
+
+// Best-effort cleanup — a leftover temp file must never break validation.
+const tryUnlink = (path) => {
+ try {
+ unlinkSync(path);
+ } catch {
+ /* swallow error */
+ }
+};
+
+function runVitest(wt, configFile, projects = []) {
+ const projectTag = projects.length ? `-${projects.join("-")}` : "";
+ const out = join(tmpdir(), `vitest-${basename(configFile)}${projectTag}-${process.pid}.out`);
+ const projectFlags = projects.map((p) => `--project ${p}`).join(" ");
+ const r = bash(
+ `CI=true timeout 180 npx vitest run --config ${configFile} ${projectFlags} > "${out}" 2>&1`,
+ { cwd: wt },
+ );
+ const output = tailFile(out, 40);
+ tryUnlink(out);
+ return { status: r.status, output, timedOut: r.status === 124 };
+}
+
+// The full validation chain, shared by both validation entry points
+// (validate-on-stop.mjs on SubagentStop, validate-before-review.mjs on
+// SendMessage). Per dirty worktree, fail-fast: prettier auto-fix (+ commit),
+// typecheck, unit app, unit functions; then e2e once in the repo (full mode
+// only). VALIDATE_DRY_RUN=1 skips everything, =fail simulates a failure.
+// Returns { ok: true, skipReason? } or { ok: false, step, output }.
+export function runValidationSteps(ctx, { worktree = "" } = {}) {
+ if (process.env.VALIDATE_DRY_RUN === "1") {
+ ctx.log("DRY_RUN=1, skipping validation");
+ return { ok: true, skipReason: "dry_run" };
+ }
+ if (process.env.VALIDATE_DRY_RUN === "fail") {
+ ctx.log("DRY_RUN=fail, simulating a failure");
+ return { ok: false, step: "dry-run", output: "Validation failed (simulated)." };
+ }
+
+ const { worktrees, skipReason } = getWorktreesToValidate(ctx, {
+ skipAdrOnly: true,
+ only: worktree,
+ });
+ if (skipReason) return { ok: true, skipReason };
+
+ const hasFunctions = existsSync(join(ctx.repo, "supabase", "functions"));
+
+ for (const wt of worktrees) {
+ const failed = (step, output) => {
+ ctx.log(`FAIL step=${step} wt=${wt}`);
+ return { ok: false, step, output: `=== ${step} failed in ${wt} ===\n${output}\n` };
+ };
+
+ const pretty = bash(
+ "npx prettier --write 'src/**/*.{ts,tsx,js,jsx,css,json,html}' 2>&1",
+ { cwd: wt },
+ );
+ if (pretty.status !== 0) {
+ return failed(
+ "prettier",
+ "Prettier could not format one or more files (likely a syntax error). Fix the issue and commit.\n" +
+ tailLines(pretty.stdout, 15),
+ );
+ }
+ if (exec("git", ["-C", wt, "diff", "--quiet"]).status !== 0) {
+ exec("git", ["-C", wt, "add", "-A"]);
+ exec("git", ["-C", wt, "commit", "-m", `style(${basename(wt)}): auto-apply prettier`]);
+ ctx.log(`auto-prettier committed wt=${wt}`);
+ }
+
+ const typecheck = bash("npm run typecheck 2>&1", { cwd: wt });
+ if (typecheck.status !== 0) return failed("typecheck", tailLines(typecheck.stdout, 20));
+
+ const app = runVitest(wt, "vitest.config.ts", ["app", "claude"]);
+ if (app.timedOut) return failed("unit-app", "TIMEOUT (>180s) -- vitest did not exit. Tests may be hanging.");
+ if (app.status !== 0) return failed("unit-app", app.output);
+
+ if (hasFunctions) {
+ const fn = runVitest(wt, "vitest.config.ts", ["functions"]);
+ if (fn.timedOut) return failed("unit-fn", "TIMEOUT (>180s) -- vitest did not exit. Tests may be hanging.");
+ if (fn.status !== 0) return failed("unit-fn", fn.output);
+ }
+
+ ctx.log(`OK wt=${wt}`);
+ }
+
+ const mode = process.env.MODE || "demo";
+ if (mode === "demo") {
+ ctx.log("e2e skipped (demo mode)");
+ return { ok: true };
+ }
+ const e2e = bash("npx playwright test 2>&1", { cwd: ctx.repo });
+ if (e2e.status !== 0) {
+ ctx.log(`FAIL step=e2e exit=${e2e.status}`);
+ return { ok: false, step: "e2e", output: tailLines(e2e.stdout, 50) + "\n" };
+ }
+ ctx.log("e2e OK");
+ return { ok: true };
+}
diff --git a/.claude/hooks/member-idle-gate.mjs b/.claude/hooks/member-idle-gate.mjs
deleted file mode 100755
index 6a3d9235..00000000
--- a/.claude/hooks/member-idle-gate.mjs
+++ /dev/null
@@ -1,135 +0,0 @@
-#!/usr/bin/env node
-// PreToolUse hook — prevents quality-reviewer-* and test-validator-* from using
-// any tool before the developer has sent them a "ready for review" message.
-//
-// Rationale: reviewers are dispatched simultaneously with the developer. Without
-// this gate they read an empty worktree and send unsolicited "nothing to review"
-// messages, confusing the developer and breaking the review loop.
-//
-// Why NOT check the team inbox file: reviewers are dispatched with their task
-// context already in the spawn prompt (a <teammate-message> from team-lead), so
-// the inbox has 1 message immediately at spawn time — an inbox COUNT >= 1 check
-// would always pass. The flag file written by validate-before-review is the
-// correct signal: it appears only when the developer explicitly validates and
-// sends "ready for review", which is a strictly later event.
-//
-// Flags (under flagsDir, already session-scoped so a stale flag from a previous
-// session never unblocks a reviewer in a new one):
-// notified-qr-TASK-XXX (quality-reviewer-TASK-XXX)
-// notified-tv-TASK-XXX (test-validator-TASK-XXX)
-// notified-merger-TASK-XXX / notified-merger-simple (merger)
-
-import { existsSync, mkdirSync, writeFileSync, readdirSync } from "node:fs";
-import { join } from "node:path";
-import { readStdin, parseJson, crmIdentity } from "./lib/common.mjs";
-
-const input = parseJson(readStdin());
-const ctx = crmIdentity(input);
-
-// crm_identity sets agentType to the full agent name (e.g. "quality-reviewer-
-// TASK-001") for in-process teammates, falling back to CLAUDE_AGENT_NAME.
-const agent = ctx.agentType;
-
-let gateType;
-if (/^quality-reviewer(-|$)/.test(agent)) gateType = "qr";
-else if (/^test-validator(-|$)/.test(agent)) gateType = "tv";
-else if (/^merger(-|$)/.test(agent)) gateType = "merger";
-else process.exit(0);
-
-const toolInput = input.tool_input || {};
-
-// Extract TASK_ID: first from the agent name, then from tool_input fields.
-let taskId = (agent.match(/TASK-[0-9]+/) || [])[0] || "";
-if (!taskId) {
- const candidates = [
- toolInput.file_path || "",
- toolInput.command || "",
- toolInput.path || "",
- toolInput.to || "",
- toolInput.message || "",
- JSON.stringify(toolInput),
- ];
- for (const s of candidates) {
- const m = String(s).match(/TASK-[0-9]+/);
- if (m) {
- taskId = m[0];
- break;
- }
- }
-}
-
-const touch = (path) => {
- try {
- mkdirSync(ctx.flagsDir, { recursive: true });
- writeFileSync(path, "");
- } catch {
- // best-effort
- }
-};
-
-const blockNoTask = () => {
- ctx.log(`member-idle-gate BLOCK-NOTASK agent=${agent} gate=${gateType} (no TASK_ID in input)`);
- process.stderr.write(
- `[member-idle-gate] Cannot determine TASK_ID for agent '${agent}'.\n` +
- `Do NOT call any tool until you receive the developer's "ready for review" SendMessage.\n`
- );
- process.exit(2);
-};
-
-const simpleWt = join(ctx.worktreeBase, "simple");
-const toolInputStr = JSON.stringify(toolInput);
-
-if (!taskId) {
- // Merger special case: the merger often runs git/shell commands that don't
- // mention TASK-XXX. Once the developer has validated and sent to the merger,
- // a notified-merger-* flag exists → allow all its tool calls.
- if (gateType === "merger") {
- let mergerFlag = "";
- try {
- mergerFlag = readdirSync(ctx.flagsDir).find((f) => f.startsWith("notified-merger-")) || "";
- } catch {
- mergerFlag = "";
- }
- if (mergerFlag) {
- ctx.log(`member-idle-gate PASS agent=${agent} task=any (session merger flag: ${mergerFlag})`);
- process.exit(0);
- }
- // SIMPLE flow: orchestrator dispatches merger directly (no SendMessage, no
- // validate-before-review) so no merger flag is ever written. Detect by the
- // presence of the SIMPLE worktree path in tool_input.
- if (toolInputStr.includes(simpleWt)) {
- touch(join(ctx.flagsDir, "notified-merger-simple"));
- ctx.log(`member-idle-gate PASS agent=${agent} task=simple (SIMPLE flow, wrote notified-merger-simple)`);
- process.exit(0);
- }
- }
- // Migration-round reviewer bypass: a quality-reviewer operating on the
- // migration worktree (<worktreeBase>/simple) is dispatched sequentially AFTER
- // the SQL is written — the empty-worktree race cannot happen. Allow it.
- if (gateType === "qr" && toolInputStr.includes(simpleWt)) {
- ctx.log(`member-idle-gate PASS agent=${agent} task=migration (migration-review bypass)`);
- process.exit(0);
- }
- // No TASK_ID anywhere — block conservatively.
- blockNoTask();
-}
-
-const flag = {
- qr: join(ctx.flagsDir, `notified-qr-${taskId}`),
- tv: join(ctx.flagsDir, `notified-tv-${taskId}`),
- merger: join(ctx.flagsDir, `notified-merger-${taskId}`),
-}[gateType];
-
-if (!existsSync(flag)) {
- ctx.log(`member-idle-gate BLOCK agent=${agent} task=${taskId} flag=${flag} not found`);
- process.stderr.write(
- `[member-idle-gate] Your flag (${flag}) does not exist yet.\n` +
- `The developer has not sent you a "ready for review" message.\n` +
- `Do NOT call any tool (Read, Bash, Grep, SendMessage…).\n` +
- `Idle until you receive the developer's first SendMessage.\n`
- );
- process.exit(2);
-}
-
-ctx.log(`member-idle-gate PASS agent=${agent} task=${taskId}`);
-process.exit(0);
diff --git a/.claude/hooks/prettier-on-stop.mjs b/.claude/hooks/prettier-on-stop.mjs
deleted file mode 100755
index 9be252eb..00000000
--- a/.claude/hooks/prettier-on-stop.mjs
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/env node
-// SubagentStop hook — prettier check in any active worktree with changes.
-// Exit 2 on failure → stderr injected, subagent stays alive to run prettier:apply.
-
-import { existsSync } from "node:fs";
-import {
- readStdin,
- crmIdentity,
- baseBranch,
- activeWorktrees,
- worktreeDirty,
- tailLines,
- bash,
-} from "./lib/common.mjs";
-
-const ctx = crmIdentity(readStdin());
-ctx.log(`prettier START REPO=${ctx.repo}`);
-
-if (!existsSync(ctx.repo)) {
- ctx.log("prettier EXIT=0 cd_failed");
- process.exit(0);
-}
-
-// Only check ACTIVE feature worktrees under this session's worktreeBase. See
-// typecheck hook for the rationale (skip main repo — pre-existing state is not
-// our concern). VALIDATE_WORKTREE narrows to one worktree.
-const worktrees = activeWorktrees(ctx);
-if (worktrees.length === 0) {
- ctx.log("prettier EXIT=0 no_active_worktree");
- process.exit(0);
-}
-
-const base = baseBranch();
-let failed = false;
-let aggregatedErr = "";
-
-for (const wt of worktrees) {
- if (!worktreeDirty(wt, base)) {
- ctx.log(`prettier SKIP wt=${wt} (no changes)`);
- continue;
- }
-
- // Scope to src/ only — avoids false positives on docs/ files created by the
- // planner (e.g. project-context.json) that the developer didn't touch.
- const result = bash("npx prettier --check 'src/**/*.{ts,tsx,js,jsx,css,json,html}' 2>&1", { cwd: wt });
- if (result.status !== 0) {
- failed = true;
- aggregatedErr += `=== prettier failed in ${wt} ===\n${tailLines(result.stdout, 15)}\n\n`;
- ctx.log(`prettier FAIL wt=${wt} EXIT=${result.status}`);
- } else {
- ctx.log(`prettier OK wt=${wt}`);
- }
-}
-
-if (failed) {
- process.stderr.write("Prettier check failed — run 'npm run prettier:apply' in the worktree(s) below:\n");
- process.stderr.write(aggregatedErr);
- ctx.log("prettier EXIT=2");
- process.exit(2);
-}
-
-ctx.log("prettier EXIT=0 OK (all worktrees)");
-process.exit(0);
diff --git a/.claude/hooks/restrict-documentator-bash.mjs b/.claude/hooks/restrict-documentator-bash.mjs
index f60a9ea7..6073175c 100755
--- a/.claude/hooks/restrict-documentator-bash.mjs
+++ b/.claude/hooks/restrict-documentator-bash.mjs
@@ -1,38 +1,40 @@
#!/usr/bin/env node
-// PreToolUse / Bash hook. Restricts the documentator's bash usage to a strict
-// read-only whitelist. Pass-through for any other agent or for non-documentator
-// claude sessions (no DOCUMENTATOR_RUN env var).
+// PreToolUse(Bash) — restrict the documentator (DOCUMENTATOR_RUN=1) to a read-only / MEMORY.md-commit whitelist, rejecting shell metacharacters first; pass-through otherwise.
-import { readStdin, parseJson } from "./lib/common.mjs";
+import { readFileSync } from "node:fs";
+import { createHookContext } from "./lib/context.mjs";
if (process.env.DOCUMENTATOR_RUN !== "1") process.exit(0);
-// Read the JSON envelope from stdin and extract tool_input.command. If the
-// payload is malformed, treat as block (safer than passing through with an
-// empty command that would later match `^ls( |$)` against an empty string).
-const command = parseJson(readStdin()).tool_input?.command || "";
+// Fail closed: a malformed payload is a block signal for this restricted
+// agent, not a pass-through. Leave input empty so the !command guard below
+// exits 2 (exit 1 from an uncaught throw would let the Bash command through).
+let input = {};
+try {
+ input = JSON.parse(readFileSync(0, "utf8"));
+} catch {
+ // fall through to the empty-command block below
+}
+const ctx = createHookContext(input, "restrict-documentator-bash");
+const command = input.tool_input?.command || "";
if (!command) {
- process.stderr.write("Bash command blocked for documentator: empty or unparseable command.\n");
+ ctx.error(
+ "Bash command blocked for documentator: empty or unparseable command.",
+ );
process.exit(2);
}
-// Reject any command containing shell metacharacters that could chain or
-// redirect. The prefix whitelist below trusts that the command is a single
-// atom, so we have to enforce that here first.
-const METACHARS = [";", "&&", "||", "|", "`", "$(", ">", "<", "\n"];
-if (METACHARS.some((m) => command.includes(m))) {
- process.stderr.write(
- 'Bash command blocked for documentator: shell metacharacters not allowed (";", "&&", "||", "|", backtick, "$(", redirections, newline).\n'
+const SHELL_METACHARS = [";", "&&", "||", "|", "`", "$(", ">", "<", "\n"];
+const hasShellMetachars = (cmd) => SHELL_METACHARS.some((m) => cmd.includes(m));
+
+if (hasShellMetachars(command)) {
+ ctx.error(
+ 'Bash command blocked for documentator: shell metacharacters not allowed (";", "&&", "||", "|", backtick, "$(", redirections, newline).',
);
process.exit(2);
}
-// Allowed-prefix patterns (anchored). Mode 1: read-only inspection.
-// Mode 2: read the session diff vs origin/main, commit MEMORY.md with the
-// pinned Documentator identity (never via `cd && …` — chaining is blocked).
-// The `-C <repo>` target is matched generically ([^ ]+) so the whitelist is
-// portable to any checkout location, not just /app.
const WHITELIST = [
/^git log( |$)/,
/^git show( |$)/,
@@ -43,16 +45,16 @@ const WHITELIST = [
/^ls( |$)/,
/^wc -l( |$)/,
/^git -C [^ ]+ add MEMORY\.md *$/,
- // commit: accept user.name/user.email in either order
/^git -C [^ ]+ -c user\.name=['"]?Documentator['"]? -c user\.email=['"]?documentator@atomic-crm\.local['"]? commit -m /,
/^git -C [^ ]+ -c user\.email=['"]?documentator@atomic-crm\.local['"]? -c user\.name=['"]?Documentator['"]? commit -m /,
];
+const isWhitelisted = (cmd) => WHITELIST.some((pattern) => pattern.test(cmd));
-if (WHITELIST.some((pattern) => pattern.test(command))) {
+if (isWhitelisted(command)) {
process.exit(0);
}
-process.stderr.write(
- "Bash command blocked for documentator. Allowed: git log, git show, git diff, ls, wc -l; Mode 2 only: 'git -C <repo> fetch origin main --quiet', 'git -C <repo> diff …', 'git -C <repo> log …', 'git -C <repo> add MEMORY.md', 'git -C <repo> -c user.name=Documentator -c [email protected] commit -m …'. Use Read/Glob/Grep otherwise.\n"
+ctx.error(
+ "Bash command blocked for documentator. Allowed: git log, git show, git diff, ls, wc -l; Mode 2 only: 'git -C <repo> fetch origin main --quiet', 'git -C <repo> diff …', 'git -C <repo> log …', 'git -C <repo> add MEMORY.md', 'git -C <repo> -c user.name=Documentator -c [email protected] commit -m …'. Use Read/Glob/Grep otherwise.",
);
process.exit(2);
diff --git a/.claude/hooks/restrict-documentator-write.mjs b/.claude/hooks/restrict-documentator-write.mjs
index e23b8b26..f711ad7d 100755
--- a/.claude/hooks/restrict-documentator-write.mjs
+++ b/.claude/hooks/restrict-documentator-write.mjs
@@ -1,21 +1,29 @@
#!/usr/bin/env node
-// PreToolUse / Write|Edit hook. Restricts the documentator's writes to a small
-// set of paths: the ledger, the runtime additions tree, MEMORY.md, and
-// settings.local.json. All other paths are blocked — the documentator is not
-// allowed to touch application code or to modify the base config under
-// $CONFIG_DIR/{agents,skills,hooks,rules,settings.json}.
-// Pass-through for any other agent or for non-documentator claude sessions
-// (no DOCUMENTATOR_RUN env var).
+// PreToolUse(Write|Edit) — restrict the documentator (DOCUMENTATOR_RUN=1) writes to the ledger, the runtime additions tree (CONFIG_DIR/local/**), MEMORY.md, and settings.local.json; pass-through otherwise.
+import { readFileSync } from "node:fs";
import { join } from "node:path";
-import { readStdin, parseJson, REPO, CONFIG_DIR } from "./lib/common.mjs";
+import { createHookContext } from "./lib/context.mjs";
+import { REPO, CONFIG_DIR } from "./lib/paths.mjs";
if (process.env.DOCUMENTATOR_RUN !== "1") process.exit(0);
-const filePath = parseJson(readStdin()).tool_input?.file_path || "";
+// Fail closed: a malformed payload is a block signal for this restricted
+// agent, not a pass-through. Leave input empty so the !filePath guard below
+// exits 2 (exit 1 from an uncaught throw would let the Write through).
+let input = {};
+try {
+ input = JSON.parse(readFileSync(0, "utf8"));
+} catch {
+ // fall through to the empty-file_path block below
+}
+const ctx = createHookContext(input, "restrict-documentator-write");
+const filePath = input.tool_input?.file_path || "";
if (!filePath) {
- process.stderr.write("Write/Edit blocked for documentator: empty or unparseable file_path.\n");
+ ctx.error(
+ "Write/Edit blocked for documentator: empty or unparseable file_path.",
+ );
process.exit(2);
}
@@ -24,16 +32,17 @@ const LOCAL_PREFIX = join(CONFIG_DIR, "local") + "/";
const SETTINGS_LOCAL = join(CONFIG_DIR, "settings.local.json");
const MEMORY = join(REPO, "MEMORY.md");
-if (
- filePath === LEDGER ||
- filePath === SETTINGS_LOCAL ||
- filePath === MEMORY ||
- filePath.startsWith(LOCAL_PREFIX)
-) {
+const isAllowedPath = (p) =>
+ p === LEDGER ||
+ p === SETTINGS_LOCAL ||
+ p === MEMORY ||
+ p.startsWith(LOCAL_PREFIX);
+
+if (isAllowedPath(filePath)) {
process.exit(0);
}
-process.stderr.write(
- `Write/Edit blocked for documentator: ${filePath} is outside the allowed set. Allowed: ${LEDGER}, ${SETTINGS_LOCAL}, ${MEMORY}, ${LOCAL_PREFIX}**.\n`
+ctx.error(
+ `Write/Edit blocked for documentator: ${filePath} is outside the allowed set. Allowed: ${LEDGER}, ${SETTINGS_LOCAL}, ${MEMORY}, ${LOCAL_PREFIX}**.`,
);
process.exit(2);
diff --git a/.claude/hooks/run-e2e-tests.mjs b/.claude/hooks/run-e2e-tests.mjs
deleted file mode 100755
index 323e6773..00000000
--- a/.claude/hooks/run-e2e-tests.mjs
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/usr/bin/env node
-// SubagentStop hook — e2e tests.
-// Exit 2 on failure → stderr injected, subagent stays alive.
-
-import { existsSync } from "node:fs";
-import { readStdin, crmIdentity, tailLines, bash } from "./lib/common.mjs";
-
-const ctx = crmIdentity(readStdin());
-const mode = process.env.MODE || "demo";
-ctx.log(`e2e START MODE=${mode} REPO=${ctx.repo}`);
-
-if (!existsSync(ctx.repo)) {
- ctx.log("e2e EXIT=0 cd_failed");
- process.exit(0);
-}
-
-if (mode === "demo") {
- ctx.log("e2e EXIT=0 skipped_demo");
- process.exit(0);
-}
-
-const result = bash("npx playwright test 2>&1", { cwd: ctx.repo });
-if (result.status !== 0) {
- process.stderr.write(tailLines(result.stdout, 50) + "\n");
- ctx.log(`e2e EXIT=2 playwright_exit=${result.status}`);
- process.exit(2);
-}
-
-ctx.log("e2e EXIT=0 OK");
-process.exit(0);
diff --git a/.claude/hooks/run-unit-tests-app.mjs b/.claude/hooks/run-unit-tests-app.mjs
deleted file mode 100755
index fac63634..00000000
--- a/.claude/hooks/run-unit-tests-app.mjs
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/env node
-// SubagentStop hook — unit tests (app) in each active worktree with changes.
-// Exit 2 on failure → stderr injected, subagent stays alive.
-
-import { existsSync } from "node:fs";
-import {
- readStdin,
- crmIdentity,
- baseBranch,
- activeWorktrees,
- worktreeDirty,
- worktreeChangedFiles,
- runVitest,
-} from "./lib/common.mjs";
-
-const ctx = crmIdentity(readStdin());
-ctx.log(`unit-app START REPO=${ctx.repo}`);
-
-if (!existsSync(ctx.repo)) {
- ctx.log("unit-app EXIT=0 cd_failed");
- process.exit(0);
-}
-
-// VALIDATE_WORKTREE narrows to one worktree (set by validate-before-review).
-// See typecheck hook header for rationale.
-const worktrees = activeWorktrees(ctx);
-if (worktrees.length === 0) {
- ctx.log("unit-app EXIT=0 no_active_worktree");
- process.exit(0);
-}
-
-const base = baseBranch();
-let failed = false;
-let aggregatedErr = "";
-
-for (const wt of worktrees) {
- if (!worktreeDirty(wt, base)) {
- ctx.log(`unit-app SKIP wt=${wt} (no changes)`);
- continue;
- }
-
- // Skip ADR-only diffs (.md docs, no test impact).
- const changed = worktreeChangedFiles(wt, base);
- if (changed.length > 0 && changed.every((f) => f.startsWith("adr/"))) {
- ctx.log(`unit-app SKIP wt=${wt} (adr-only)`);
- continue;
- }
-
- // Call vitest directly with the `run` subcommand (not `npm run test:unit:app`)
- // because the package.json script invokes `vitest --config …` without `run`,
- // which puts vitest into watch mode. In a non-TTY agent context, watch mode
- // hangs at startup instead of running tests once and exiting.
- // Scope to the browser ("app") and harness ("claude") projects; the Deno-style
- // "functions" project is handled by run-unit-tests-functions.mjs.
- const { status, output, timedOut } = runVitest(wt, "vitest.config.ts", [
- "app",
- "claude",
- ]);
- if (timedOut) {
- ctx.log(`unit-app TIMEOUT wt=${wt} (180s)`);
- failed = true;
- aggregatedErr += `=== unit-app TIMEOUT in ${wt} (>180s) -- vitest did not exit. Tests may be hanging. ===\n\n`;
- continue;
- }
- if (status !== 0) {
- failed = true;
- aggregatedErr += `=== unit-app failed in ${wt} ===\n${output}\n\n`;
- ctx.log(`unit-app FAIL wt=${wt} EXIT=${status}`);
- } else {
- ctx.log(`unit-app OK wt=${wt}`);
- }
-}
-
-if (failed) {
- process.stderr.write(aggregatedErr);
- ctx.log("unit-app EXIT=2");
- process.exit(2);
-}
-
-ctx.log("unit-app EXIT=0 OK (all worktrees)");
-process.exit(0);
diff --git a/.claude/hooks/run-unit-tests-functions.mjs b/.claude/hooks/run-unit-tests-functions.mjs
deleted file mode 100755
index 6de322cf..00000000
--- a/.claude/hooks/run-unit-tests-functions.mjs
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/env node
-// SubagentStop hook — unit tests (functions) in each active worktree with changes.
-// Exit 2 on failure → stderr injected, subagent stays alive.
-
-import { existsSync } from "node:fs";
-import { join } from "node:path";
-import {
- readStdin,
- crmIdentity,
- baseBranch,
- activeWorktrees,
- worktreeDirty,
- worktreeChangedFiles,
- runVitest,
-} from "./lib/common.mjs";
-
-const ctx = crmIdentity(readStdin());
-ctx.log(`unit-fn START REPO=${ctx.repo}`);
-
-if (!existsSync(ctx.repo)) {
- ctx.log("unit-fn EXIT=0 cd_failed");
- process.exit(0);
-}
-
-// Functions test suite is optional: skip cleanly when the project has no
-// Edge Functions (the supabase/functions/ dir may have been removed). The tests
-// themselves live in the "functions" project of vitest.config.ts.
-if (!existsSync(join(ctx.repo, "supabase", "functions"))) {
- ctx.log("unit-fn EXIT=0 no_functions_dir");
- process.exit(0);
-}
-
-// VALIDATE_WORKTREE narrows to one worktree (set by validate-before-review).
-const worktrees = activeWorktrees(ctx);
-if (worktrees.length === 0) {
- ctx.log("unit-fn EXIT=0 no_active_worktree");
- process.exit(0);
-}
-
-const base = baseBranch();
-let failed = false;
-let aggregatedErr = "";
-
-for (const wt of worktrees) {
- if (!worktreeDirty(wt, base)) {
- ctx.log(`unit-fn SKIP wt=${wt} (no changes)`);
- continue;
- }
-
- // Skip ADR-only diffs (.md docs, no test impact).
- const changed = worktreeChangedFiles(wt, base);
- if (changed.length > 0 && changed.every((f) => f.startsWith("adr/"))) {
- ctx.log(`unit-fn SKIP wt=${wt} (adr-only)`);
- continue;
- }
-
- const { status, output, timedOut } = runVitest(wt, "vitest.config.ts", [
- "functions",
- ]);
- if (timedOut) {
- ctx.log(`unit-fn TIMEOUT wt=${wt} (180s)`);
- failed = true;
- aggregatedErr += `=== unit-fn TIMEOUT in ${wt} (>180s) -- vitest did not exit. Tests may be hanging. ===\n\n`;
- continue;
- }
- if (status !== 0) {
- failed = true;
- aggregatedErr += `=== unit-fn failed in ${wt} ===\n${output}\n\n`;
- ctx.log(`unit-fn FAIL wt=${wt} EXIT=${status}`);
- } else {
- ctx.log(`unit-fn OK wt=${wt}`);
- }
-}
-
-if (failed) {
- process.stderr.write(aggregatedErr);
- ctx.log("unit-fn EXIT=2");
- process.exit(2);
-}
-
-ctx.log("unit-fn EXIT=0 OK (all worktrees)");
-process.exit(0);
diff --git a/.claude/hooks/setup-worktree.mjs b/.claude/hooks/setup-worktree.mjs
index 9f44b56f..a4a0ec7b 100755
--- a/.claude/hooks/setup-worktree.mjs
+++ b/.claude/hooks/setup-worktree.mjs
@@ -1,115 +1,106 @@
#!/usr/bin/env node
-// SubagentStart hook — creates the git worktree + links node_modules.
-// Triggered for developer and simple-developer agents.
-//
-// Identity logic (from the SubagentStart stdin JSON, no injected env needed):
-// agent_type contains TASK-XXX → COMPLEX developer
-// agent_type == simple-developer → SIMPLE (no explicit name)
-//
-// COMPLEX (developer-TASK-XXX):
-// worktreePath = <worktreeBase>/<TASK_ID> (worktreeBase = /tmp/<repo>/<session>)
-// branchName = <sessionShort>/<TASK_ID>
-//
-// SIMPLE (simple-developer):
-// worktreePath = <worktreeBase>/simple
-// branchName = <sessionShort>/simple
-//
-// Recovery:
-// 1. Already registered in git → skip (restart scenario)
-// 2. Orphan dir, not registered → rm -rf, then retry
-// 3. Orphan branch, no worktree → force-delete branch so -b works
+// SubagentStart — for developer/simple-developer agents, create the per-session integration branch + _session worktree and the task worktree, then link node_modules. developer-TASK-XXX → <base>/<TASK_ID>; simple-developer → <base>/simple. Recovers from stale registrations, orphan dirs, and orphan branches.
-import { existsSync, mkdirSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
import { dirname, join } from "node:path";
-import { readStdin, crmIdentity, baseBranch, git } from "./lib/common.mjs";
+import { createHookContext } from "./lib/context.mjs";
+import { getBaseBranch, git, getWorktreePaths } from "./lib/git.mjs";
+import { getFirstTaskId } from "./lib/teams.mjs";
+import {
+ sessionBaseBranch,
+ sessionBranch,
+ sessionWorktreePath,
+ simpleBranch,
+ simpleWorktreePath,
+ taskBranch,
+ taskWorktreePath,
+} from "./lib/topology.mjs";
-const ctx = crmIdentity(readStdin());
+const ctx = createHookContext(readFileSync(0, "utf8"), "setup-worktree");
-// Classify the agent FIRST and bail out for anything that isn't a worktree-owning
-// developer. This MUST happen before we create the session branch / _session
-// worktree, otherwise every SubagentStart (Explore, reviewers, etc.) would create
-// session infrastructure in the repo.
const agentType = ctx.agentType || "";
-const taskMatch = agentType.match(/TASK-[0-9]+/);
+const taskId = getFirstTaskId(agentType);
let worktreePath;
let branchName;
-if (taskMatch) {
- worktreePath = join(ctx.worktreeBase, taskMatch[0]);
- branchName = `${ctx.sessionShort}/${taskMatch[0]}`;
+if (taskId) {
+ worktreePath = taskWorktreePath(ctx, taskId);
+ branchName = taskBranch(ctx, taskId);
} else if (agentType === "simple-developer") {
- worktreePath = join(ctx.worktreeBase, "simple");
- branchName = `${ctx.sessionShort}/simple`;
+ worktreePath = simpleWorktreePath(ctx);
+ branchName = simpleBranch(ctx);
} else {
- // Not a worktree-owning developer — do nothing (no log dir, no branch, no worktree).
process.exit(0);
}
mkdirSync(ctx.sessionDir, { recursive: true });
-const base = baseBranch();
-const sessionBranch = `session/${ctx.sessionShort}`;
+const base = getBaseBranch();
+const integrationBranch = sessionBranch(ctx);
-// Create the per-session integration branch, its fixed fork anchor, and the
-// integration worktree. The anchor ref never moves and is the stable diff
-// baseline for migrations (later phase). Branch and worktree creation are
-// guarded independently so a partial failure retries on the next invocation.
-const sessionWt = join(ctx.worktreeBase, "_session");
-if (git(["show-ref", "--verify", "--quiet", `refs/heads/${sessionBranch}`]).status !== 0) {
- git(["branch", sessionBranch, base]);
- git(["branch", `session-base/${ctx.sessionShort}`, base]);
+const sessionWt = sessionWorktreePath(ctx);
+if (
+ git(["show-ref", "--verify", "--quiet", `refs/heads/${integrationBranch}`])
+ .status !== 0
+) {
+ git(["branch", integrationBranch, base]);
+ git(["branch", sessionBaseBranch(ctx), base]);
}
-// A live git worktree owns a `.git` file pointing at its gitdir. Test that, not
-// mere dir presence: on a session restart the cleanup can wipe the directory
-// while git still holds the registration, and `git worktree add` then refuses
-// with "missing but already registered worktree". Prune drops stale
-// registrations so the add can recreate it.
if (!existsSync(join(sessionWt, ".git"))) {
- rmSync(sessionWt, { recursive: true, force: true }); // clear orphan dir (no .git)
+ rmSync(sessionWt, { recursive: true, force: true });
mkdirSync(dirname(sessionWt), { recursive: true });
git(["worktree", "prune"]);
- const add = git(["worktree", "add", sessionWt, sessionBranch]);
+ const add = git(["worktree", "add", sessionWt, integrationBranch]);
if (add.status === 0) {
ctx.linkNodeModules(sessionWt);
- ctx.log(`setup-worktree SESSION-BRANCH created ${sessionBranch} from ${base}`);
+ ctx.log(
+ `SESSION-BRANCH created ${integrationBranch} from ${base}`,
+ );
} else {
- ctx.log(`setup-worktree SESSION-BRANCH FAILED _session worktree ${sessionBranch} err=${add.stderr.replace(/\n/g, " ")}`);
+ ctx.log(
+ `SESSION-BRANCH FAILED _session worktree ${integrationBranch} err=${add.stderr.replace(/\n/g, " ")}`,
+ );
}
}
-ctx.log(`setup-worktree START agent=${agentType} path=${worktreePath} branch=${branchName}`);
+ctx.log(
+ `START agent=${agentType} path=${worktreePath} branch=${branchName}`,
+);
-// Recovery 1: already registered → restart, use as-is.
-if (git(["worktree", "list", "--porcelain"]).stdout.includes(`worktree ${worktreePath}`)) {
- ctx.log(`setup-worktree SKIP already registered (${worktreePath})`);
- process.exit(0);
+if (getWorktreePaths().includes(worktreePath)) {
+ ctx.accept(`already registered (${worktreePath})`);
}
-// Recovery 2: orphan dir → clean slate. (Never targets _session — different path.)
if (existsSync(worktreePath)) {
rmSync(worktreePath, { recursive: true, force: true });
- ctx.log(`setup-worktree REMOVED orphan dir ${worktreePath}`);
+ ctx.log(`REMOVED orphan dir ${worktreePath}`);
}
mkdirSync(dirname(worktreePath), { recursive: true });
-// Recovery 3: orphan branch → force-delete so -b works cleanly.
if (git(["branch", "--list", branchName]).stdout.trim()) {
git(["branch", "-D", branchName]);
- ctx.log(`setup-worktree DELETED orphan branch ${branchName}`);
+ ctx.log(`DELETED orphan branch ${branchName}`);
}
-const add = git(["worktree", "add", worktreePath, "-b", branchName, sessionBranch]);
-if (add.status === 0) {
- ctx.log(`setup-worktree CREATED branch=${branchName} path=${worktreePath}`);
-} else {
- ctx.log(`setup-worktree EXIT=2 path=${worktreePath} err=${add.stderr}`);
- process.stderr.write(`[setup-worktree] Cannot create worktree at ${worktreePath} (branch=${branchName}): ${add.stderr}\n`);
- process.exit(2);
+const add = git([
+ "worktree",
+ "add",
+ worktreePath,
+ "-b",
+ branchName,
+ integrationBranch,
+]);
+if (add.status !== 0) {
+ ctx.fail(
+ `Cannot create worktree at ${worktreePath} (branch=${branchName}): ${add.stderr}\n`,
+ {
+ log: `path=${worktreePath} err=${add.stderr}`,
+ },
+ );
}
+ctx.log(`CREATED branch=${branchName} path=${worktreePath}`);
-// Link node_modules (hard-link when same filesystem, symlink across devices).
ctx.linkNodeModules(worktreePath);
-ctx.log(`setup-worktree OK wt=${worktreePath}`);
-process.exit(0);
+ctx.accept(`OK wt=${worktreePath}`);
diff --git a/.claude/hooks/silent-mode-check.mjs b/.claude/hooks/silent-mode-check.mjs
deleted file mode 100755
index fe203e23..00000000
--- a/.claude/hooks/silent-mode-check.mjs
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/usr/bin/env node
-// PreToolUse hook — blocks commands that open browser windows.
-// Rules: Playwright without --headless, Vite with --open.
-
-import { readStdin, parseJson, decisionBlock } from "./lib/common.mjs";
-
-const input = parseJson(readStdin());
-const command = input.tool_input?.command || "";
-
-if (!command) process.exit(0);
-
-// Playwright: must always use --headless
-if (/playwright/.test(command)) {
- if (/(screenshot|test|codegen)/.test(command) && !command.includes("--headless")) {
- decisionBlock("Playwright must always use --headless. Add --headless to the command.");
- process.exit(0);
- }
-}
-
-// Vite: forbid --open
-if (/vite|npm run (dev|start|start-demo)/.test(command)) {
- if (command.includes("--open")) {
- decisionBlock("Vite must not use --open (opens a browser window). Remove the --open flag.");
- process.exit(0);
- }
-}
-
-process.exit(0);
diff --git a/.claude/hooks/teamcreate-wipe-orphan.mjs b/.claude/hooks/teamcreate-wipe-orphan.mjs
deleted file mode 100755
index 7912d39c..00000000
--- a/.claude/hooks/teamcreate-wipe-orphan.mjs
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/env node
-// PreToolUse hook for TeamCreate.
-//
-// Wipes orphan teams (those owned by a different session) before TeamCreate
-// runs, so the new team can claim the requested team_name verbatim. Without
-// this, Claude CLI's collision handling assigns a random unique team_name
-// (e.g. "ancient-drifting-coral") and subsequent Agent({team_name: "tickets"})
-// calls keep routing into the stale team — the new members get auto-suffixed
-// (`-2`, `-3`, …) and SendMessages from the developer route to dead members
-// from prior crashed sessions.
-//
-// Why a hook, not a skill instruction: we tried having the team-lead call
-// TeamDelete({team_name: "tickets"}) as preflight; the LLM dropped the argument
-// and called TeamDelete({}) instead (a no-op). This hook is the deterministic
-// safety net.
-//
-// Safety:
-// - Only wipes if `leadSessionId` in the team's config differs from the current
-// session's `session_id`. A team owned by THIS session is live and must go
-// through graceful shutdown (teamdelete-gate enforces that).
-// - team_name is regex-validated to prevent path traversal.
-// - Always exits 0 — never blocks TeamCreate.
-
-import { existsSync, rmSync, unlinkSync } from "node:fs";
-import { join } from "node:path";
-import { readStdin, parseJson, crmIdentity, readJson, TEAMS_DIR } from "./lib/common.mjs";
-
-const stdin = readStdin();
-if (!stdin) process.exit(0);
-const input = parseJson(stdin);
-const ctx = crmIdentity(input);
-
-const teamName = input.tool_input?.team_name || "";
-const sessionId = input.session_id || "";
-
-if (!teamName) process.exit(0);
-if (!sessionId) process.exit(0);
-
-// Strict regex — must match the same charset accepted by teamdelete-cleanup.
-if (!/^[A-Za-z0-9_-]+$/.test(teamName)) process.exit(0);
-
-const target = join(TEAMS_DIR, teamName);
-const config = join(target, "config.json");
-
-if (!existsSync(config)) process.exit(0);
-
-const leadOfTeam = readJson(config)?.leadSessionId || "";
-
-// Empty leadSessionId is exactly the orphan/corrupt case (partial config write,
-// older CLI build). Treat the same as a different-session lead — wipe so the
-// next TeamCreate can claim the name. Only skip wipe when the team is owned by
-// THIS session (live → graceful shutdown owned by teamdelete-gate).
-if (leadOfTeam === sessionId) process.exit(0);
-
-// Defensive: only delete inside TEAMS_DIR.
-if (!target.startsWith(TEAMS_DIR + "/")) process.exit(0);
-
-rmSync(target, { recursive: true, force: true });
-ctx.log(`teamcreate-wipe-orphan REMOVED ${target} (orphan leadSession=${leadOfTeam} current=${sessionId})`);
-
-// Clear the circuit-breaker flag for this session if it was set by an earlier
-// teamdelete-cleanup "no team" path — the upcoming TeamCreate is genuine and
-// the next TeamDelete (Phase 3) should not be blocked.
-try {
- unlinkSync(join(ctx.sessionDir, "teamdelete-empty"));
-} catch {
- // flag absent — nothing to clear
-}
-
-process.exit(0);
diff --git a/.claude/hooks/teamdelete-cleanup.mjs b/.claude/hooks/teamdelete-cleanup.mjs
deleted file mode 100755
index 4091e082..00000000
--- a/.claude/hooks/teamdelete-cleanup.mjs
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/env node
-// PostToolUse hook for TeamDelete tool.
-//
-// Runs AFTER a successful TeamDelete to:
-// 1. Remove residual disk artifacts (inboxes/, transcripts).
-// 2. Write a circuit-breaker flag when TeamDelete found no team
-// (response: "No team name found, nothing to clean up"). This flag is read
-// by teamdelete-gate (PreToolUse) to block the next call, preventing the
-// orchestrator from looping in STATE DONE. The flag is cleared when a real
-// team is deleted, so multi-wave sessions still work correctly.
-//
-// Behavior:
-// - If tool_response.success is not true → no-op (let user investigate)
-// - If success but no team_name → write empty-flag, skip disk cleanup
-// - If success and team_name present → disk cleanup + clear empty-flag
-// - Always exit 0 — this hook is informational, never blocks
-//
-// Safety: the team_name regex prevents path traversal. We only ever delete
-// inside TEAMS_DIR.
-
-import { existsSync, mkdirSync, rmSync, writeFileSync, unlinkSync } from "node:fs";
-import { join } from "node:path";
-import { readStdin, parseJson, crmIdentity, TEAMS_DIR } from "./lib/common.mjs";
-
-const stdin = readStdin();
-if (!stdin) process.exit(0);
-const input = parseJson(stdin);
-const ctx = crmIdentity(input);
-
-const success = input.tool_response?.success === true;
-if (!success) {
- ctx.log("teamdelete-cleanup SKIP non-success");
- process.exit(0);
-}
-
-const sessionId = input.session_id || "";
-const teamName = input.tool_response?.team_name || input.tool_input?.team_name || "";
-const emptyFlag = join(ctx.sessionDir, "teamdelete-empty");
-
-if (!teamName) {
- // TeamDelete found no team — write circuit-breaker flag so the gate blocks
- // the next call and prevents a STATE DONE loop.
- if (sessionId) {
- try {
- mkdirSync(ctx.sessionDir, { recursive: true });
- writeFileSync(emptyFlag, "");
- ctx.log(`teamdelete-cleanup SET empty-flag session=${sessionId}`);
- } catch {
- // best-effort
- }
- }
- ctx.log("teamdelete-cleanup SKIP no team_name");
- process.exit(0);
-}
-
-// Strict validation: alphanumeric, dash, underscore only. Blocks path traversal.
-if (!/^[A-Za-z0-9_-]+$/.test(teamName)) {
- ctx.log(`teamdelete-cleanup REFUSE invalid team_name=${teamName}`);
- process.exit(0);
-}
-
-const target = join(TEAMS_DIR, teamName);
-
-// Defensive: only delete if the path is exactly under TEAMS_DIR.
-if (!target.startsWith(TEAMS_DIR + "/")) {
- ctx.log(`teamdelete-cleanup REFUSE path outside teams dir: ${target}`);
- process.exit(0);
-}
-
-if (existsSync(target)) {
- rmSync(target, { recursive: true, force: true });
- ctx.log(`teamdelete-cleanup REMOVED ${target}`);
- // Real deletion — clear the circuit-breaker flag so the next wave can call
- // TeamCreate + TeamDelete again without being blocked.
- try {
- unlinkSync(emptyFlag);
- } catch {
- // flag absent — fine
- }
-} else {
- ctx.log(`teamdelete-cleanup NOOP ${target} (not present)`);
-}
-
-process.exit(0);
diff --git a/.claude/hooks/teamdelete-gate.mjs b/.claude/hooks/teamdelete-gate.mjs
deleted file mode 100755
index 275d3309..00000000
--- a/.claude/hooks/teamdelete-gate.mjs
+++ /dev/null
@@ -1,138 +0,0 @@
-#!/usr/bin/env node
-// PreToolUse hook for TeamDelete tool.
-//
-// Two guards, checked in order:
-//
-// 1. Circuit-breaker: if PostToolUse already flagged that the last TeamDelete
-// found no team, block immediately with a STATE DONE message. This prevents
-// the orchestrator from looping in STATE DONE after all waves are complete.
-// Flag file: <sessionDir>/teamdelete-empty (written by teamdelete-cleanup).
-//
-// 2. Member shutdown check: blocks TeamDelete if any non-lead member has not
-// been gracefully shut down. Points to the agent-team skill Phase 3 protocol.
-//
-// Behavior:
-// - exit 0 → allow TeamDelete
-// - exit 2 → block with stderr pointing to the missing step
-
-import { existsSync } from "node:fs";
-import { dirname, basename, join } from "node:path";
-import { readStdin, parseJson, crmIdentity, readJson, teamConfigs, TEAMS_DIR } from "./lib/common.mjs";
-
-const stdin = readStdin();
-if (!stdin) process.exit(0);
-const input = parseJson(stdin);
-const ctx = crmIdentity(input);
-
-const teamName = input.tool_input?.team_name || "";
-const sessionId = input.session_id || "";
-
-// Guard 1 — circuit-breaker: block if the previous TeamDelete already found no team.
-if (sessionId) {
- if (existsSync(join(ctx.sessionDir, "teamdelete-empty"))) {
- ctx.log(`teamdelete-gate BLOCK circuit-breaker session=${sessionId}`);
- process.stderr.write(
- [
- "TeamDelete blocked: the previous call already returned 'no team found'.",
- "You are in STATE DONE — do not call TeamDelete again.",
- "The session's work is complete. Report done to the user and stop.",
- ].join("\n") + "\n"
- );
- process.exit(2);
- }
-}
-
-if (!existsSync(TEAMS_DIR)) process.exit(0);
-
-// Resolve the team to inspect.
-let teamDir;
-if (teamName) {
- teamDir = join(TEAMS_DIR, teamName);
-} else {
- // TeamDelete({}) — find the unique team owned by this session.
- const matches = teamConfigs().filter((cfg) => (readJson(cfg)?.leadSessionId || "") === sessionId);
- // 0 → no team for this session (guard 1 handles the loop case; allow here).
- // 2+ → ambiguous, runtime will respond. 1 → use it.
- if (matches.length !== 1) process.exit(0);
- teamDir = dirname(matches[0]);
-}
-
-const config = join(teamDir, "config.json");
-const leadInbox = join(teamDir, "inboxes", "team-lead.json");
-
-if (!existsSync(config)) process.exit(0);
-const team = basename(teamDir);
-
-// Orphan bypass: if the team was created by a different session (lead crashed,
-// user STOPped, container restarted), graceful shutdown is impossible — the
-// prior members are dead processes that will never ack a shutdown_request.
-// Allow the deletion so the next wave can claim a clean `tickets` team.
-const leadOfTeam = readJson(config)?.leadSessionId || "";
-if (leadOfTeam && sessionId && leadOfTeam !== sessionId) {
- ctx.log(`teamdelete-gate ALLOW orphan team=${team} leadSession=${leadOfTeam} current=${sessionId}`);
- process.exit(0);
-}
-
-// Non-lead members.
-const members = (readJson(config)?.members || [])
- .filter((m) => m && m.agentType !== "team-lead" && m.name)
- .map((m) => m.name);
-if (members.length === 0) process.exit(0);
-
-// Lead inbox may not yet exist if no message has reached the lead. Treat as
-// "no approvals received" rather than aborting.
-const inbox = existsSync(leadInbox) ? readJson(leadInbox) || [] : null;
-
-const pendingNoApproval = []; // No shutdown_approved at all
-const pendingNoYield = []; // shutdown_approved present but read:false
-
-for (const m of members) {
- if (inbox === null) {
- pendingNoApproval.push(m);
- continue;
- }
- const matching = (Array.isArray(inbox) ? inbox : []).filter(
- (e) => e && e.from === m && (e.text || "").includes("shutdown_approved")
- );
- if (matching.length === 0) {
- pendingNoApproval.push(m);
- continue;
- }
- const latestRead = matching[matching.length - 1].read === true;
- if (!latestRead) pendingNoYield.push(m);
-}
-
-const total = pendingNoApproval.length + pendingNoYield.length;
-if (total === 0) {
- ctx.log(`teamdelete-gate ALLOW team=${team}`);
- process.exit(0);
-}
-
-ctx.log(
- `teamdelete-gate BLOCK team=${team} no_approval=${pendingNoApproval.join(" ")} no_yield=${pendingNoYield.join(" ")}`
-);
-
-const lines = [`TeamDelete blocked: ${total} teammate(s) in team '${team}' have not been gracefully shut down.`, ""];
-if (pendingNoApproval.length > 0) {
- lines.push("No shutdown_approved received from (Step 3a missing or in flight):");
- for (const m of pendingNoApproval) lines.push(` - ${m}`);
- lines.push("");
- lines.push("Step 3a — Send shutdown_request to each pending member, in ONE assistant message:");
- for (const m of pendingNoApproval) lines.push(` SendMessage({to: "${m}", message: {"type": "shutdown_request"}})`);
- lines.push("");
-}
-if (pendingNoYield.length > 0) {
- lines.push("shutdown_approved present but unread (Step 3b missing):");
- for (const m of pendingNoYield) lines.push(` - ${m}`);
- lines.push("");
-}
-lines.push("Step 3b — Emit a brief assistant text and STOP. Do NOT call any other tool in this turn.");
-lines.push(" Yielding the turn is what lets the runtime deliver shutdown_approved replies.");
-lines.push("Step 3c — On the NEXT turn, the runtime injects <teammate-message> blocks marking");
-lines.push(" shutdown_approved as read.");
-lines.push("Step 3d — Then retry TeamDelete.");
-lines.push("");
-lines.push("DO NOT call TeamDelete again immediately — without yielding it will fail the same way.");
-
-process.stderr.write(lines.join("\n") + "\n");
-process.exit(2);
diff --git a/.claude/hooks/test/bash-guard.test.mjs b/.claude/hooks/test/bash-guard.test.mjs
new file mode 100644
index 00000000..652b98c0
--- /dev/null
+++ b/.claude/hooks/test/bash-guard.test.mjs
@@ -0,0 +1,101 @@
+// Tests for bash-guard.mjs — browser rules (any caller) and validation-command rules (gated agents only). Blocks are decision JSON on stdout with exit 0; allowed commands produce no decision.
+
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { spawnSync } from "node:child_process";
+import { afterAll, describe, test, expect } from "vitest";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const HOOK = join(HERE, "..", "bash-guard.mjs");
+
+const tmpRoot = mkdtempSync(join(tmpdir(), "bash-guard-tmp-"));
+
+afterAll(() => {
+ rmSync(tmpRoot, { recursive: true, force: true });
+});
+
+const runHook = (agent, command) => {
+ const env = { ...process.env, CRM_TMP_ROOT: tmpRoot };
+ delete env.CLAUDE_AGENT_NAME;
+ const input = JSON.stringify({
+ tool_name: "Bash",
+ agent_type: agent,
+ session_id: "test-1234",
+ tool_input: { command },
+ });
+ return spawnSync("node", [HOOK], { input, env, encoding: "utf8" });
+};
+
+const isBlocked = (r) => r.stdout.includes('"decision":"block"');
+
+describe("bash-guard hook", () => {
+ describe("browser rules — any caller", () => {
+ test("headed playwright test from main session → blocked", () => {
+ const r = runHook("", "npx playwright test");
+ expect(r.status).toBe(0);
+ expect(isBlocked(r)).toBe(true);
+ expect(r.stdout).toContain("--headless");
+ });
+
+ test("headed playwright screenshot from merger → blocked", () => {
+ const r = runHook("merger", "npx playwright screenshot http://localhost:5173 out.png");
+ expect(isBlocked(r)).toBe(true);
+ });
+
+ test("playwright with --headless from main session → allowed", () => {
+ const r = runHook("", "npx playwright screenshot --headless http://localhost:5173 out.png");
+ expect(r.status).toBe(0);
+ expect(isBlocked(r)).toBe(false);
+ });
+
+ test("vite --open → blocked", () => {
+ const r = runHook("", "npm run dev -- --open");
+ expect(isBlocked(r)).toBe(true);
+ });
+
+ test("vite without --open → allowed", () => {
+ const r = runHook("", "npm run dev");
+ expect(isBlocked(r)).toBe(false);
+ });
+ });
+
+ describe("validation rules — gated agents only", () => {
+ const cases = [
+ ["developer", "npm run typecheck"],
+ ["developer", "npx tsc --noEmit"],
+ ["simple-developer", "npx vitest run"],
+ ["simple-developer", "npm run prettier:apply"],
+ ["quality-reviewer", "npx playwright test --headless"],
+ ["test-validator", "make lint"],
+ ["developer", "npm run build"],
+ ];
+
+ test.each(cases)("%s running '%s' → blocked", (agent, command) => {
+ const r = runHook(agent, command);
+ expect(r.status).toBe(0);
+ expect(isBlocked(r)).toBe(true);
+ });
+
+ test("non-gated agent running validation command → allowed", () => {
+ const r = runHook("merger", "npm run typecheck");
+ expect(isBlocked(r)).toBe(false);
+ });
+
+ test("main session running validation command → allowed", () => {
+ const r = runHook("", "npx vitest run");
+ expect(isBlocked(r)).toBe(false);
+ });
+
+ test("gated agent running plain git command → allowed", () => {
+ const r = runHook("developer", "git status && git log --oneline -3");
+ expect(isBlocked(r)).toBe(false);
+ });
+
+ test("empty command → allowed", () => {
+ const r = runHook("developer", "");
+ expect(isBlocked(r)).toBe(false);
+ });
+ });
+});
diff --git a/.claude/hooks/test/cleanup-worktree.test.mjs b/.claude/hooks/test/cleanup-worktree.test.mjs
new file mode 100644
index 00000000..1de0cc3f
--- /dev/null
+++ b/.claude/hooks/test/cleanup-worktree.test.mjs
@@ -0,0 +1,113 @@
+// Tests for cleanup-worktree.mjs removal semantics (vitest, Node project). A
+// task worktree is removed only once its branch was merged with --no-ff into
+// the session branch and the worktree is clean; fresh, unmerged, and dirty
+// worktrees are preserved. Tests are ordered and stateful — each observes the
+// state produced by the previous step.
+
+import {
+ mkdtempSync,
+ mkdirSync,
+ writeFileSync,
+ existsSync,
+ rmSync,
+ unlinkSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { spawnSync } from "node:child_process";
+import { describe, test, expect, beforeAll, afterAll } from "vitest";
+import { sanitizePath } from "../lib/paths.mjs";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const SETUP = join(HERE, "..", "setup-worktree.mjs");
+const CLEANUP = join(HERE, "..", "cleanup-worktree.mjs");
+const SESSION_ID = "cd34ef56-1111-2222-3333-444455556666";
+const SS = SESSION_ID.split("-")[0];
+
+let TMP;
+let APP_DIR;
+let WB;
+let env;
+
+const g = (...args) =>
+ spawnSync("git", ["-C", APP_DIR, ...args], { encoding: "utf8" });
+const gWt = (wt, ...args) =>
+ spawnSync("git", ["-C", wt, ...args], { encoding: "utf8" });
+const dispatch = (hook, agentType) =>
+ spawnSync("node", [hook], {
+ input: JSON.stringify({ agent_type: agentType, session_id: SESSION_ID }),
+ env,
+ encoding: "utf8",
+ });
+
+beforeAll(() => {
+ TMP = mkdtempSync(join(tmpdir(), "cleanup-wt-test-"));
+ APP_DIR = join(TMP, "app");
+ mkdirSync(APP_DIR, { recursive: true });
+ g("init", "-q", "-b", "main");
+ g("config", "user.email", "[email protected]");
+ g("config", "user.name", "t");
+ writeFileSync(join(APP_DIR, "seed.txt"), "seed\n");
+ g("add", ".");
+ g("commit", "-q", "-m", "seed");
+ mkdirSync(join(APP_DIR, "node_modules"), { recursive: true });
+
+ const CRM_TMP_ROOT = join(TMP, "scratch");
+ WB = join(CRM_TMP_ROOT, sanitizePath(APP_DIR), SESSION_ID);
+
+ env = { ...process.env, APP_DIR, CRM_TMP_ROOT };
+ delete env.VALIDATE_WORKTREE;
+
+ dispatch(SETUP, "developer-TASK-001");
+ dispatch(SETUP, "developer-TASK-002");
+});
+
+afterAll(() => {
+ rmSync(TMP, { recursive: true, force: true });
+});
+
+describe("cleanup-worktree removal semantics", () => {
+ test("fresh worktrees (no commits) are preserved", () => {
+ expect(dispatch(CLEANUP, "developer-TASK-001").status).toBe(0);
+ expect(existsSync(join(WB, "TASK-001"))).toBe(true);
+ expect(existsSync(join(WB, "TASK-002"))).toBe(true);
+ });
+
+ test("unmerged commits are preserved", () => {
+ const wt = join(WB, "TASK-001");
+ writeFileSync(join(wt, "work.txt"), "work\n");
+ gWt(wt, "add", ".");
+ gWt(wt, "commit", "-q", "-m", "TASK-001 work");
+ dispatch(CLEANUP, "developer-TASK-001");
+ expect(existsSync(wt)).toBe(true);
+ expect(g("branch", "--list", `${SS}/TASK-001`).stdout.trim()).not.toBe("");
+ });
+
+ test("merged but dirty worktree is preserved", () => {
+ const sessionWt = join(WB, "_session");
+ const merge = gWt(
+ sessionWt,
+ "merge",
+ "--no-ff",
+ `${SS}/TASK-001`,
+ "-m",
+ "merge TASK-001",
+ );
+ expect(merge.status).toBe(0);
+ writeFileSync(join(WB, "TASK-001", "uncommitted.txt"), "wip\n");
+ dispatch(CLEANUP, "developer-TASK-001");
+ expect(existsSync(join(WB, "TASK-001"))).toBe(true);
+ });
+
+ test("merged clean worktree is removed, branch deleted, fresh sibling kept", () => {
+ unlinkSync(join(WB, "TASK-001", "uncommitted.txt"));
+ expect(dispatch(CLEANUP, "developer-TASK-001").status).toBe(0);
+ expect(existsSync(join(WB, "TASK-001"))).toBe(false);
+ expect(g("branch", "--list", `${SS}/TASK-001`).stdout.trim()).toBe("");
+ expect(existsSync(join(WB, "TASK-002"))).toBe(true);
+ expect(
+ g("show-ref", "--verify", "--quiet", `refs/heads/session/${SS}`).status,
+ ).toBe(0);
+ });
+});
diff --git a/.claude/hooks/test/member-idle-gate.test.mjs b/.claude/hooks/test/member-idle-gate.test.mjs
deleted file mode 100755
index 31fd0641..00000000
--- a/.claude/hooks/test/member-idle-gate.test.mjs
+++ /dev/null
@@ -1,61 +0,0 @@
-// Tests the migration-review bypass for quality-reviewer (vitest, Node project).
-
-import { mkdtempSync, mkdirSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { spawnSync } from "node:child_process";
-import { describe, test, expect, beforeAll, afterAll } from "vitest";
-
-const HERE = dirname(fileURLToPath(import.meta.url));
-const HOOK = join(HERE, "..", "member-idle-gate.mjs");
-const SESSION_ID = "ab12cd34-1111-2222-3333-444455556666";
-
-let TMP;
-let WB;
-let env;
-
-beforeAll(() => {
- TMP = mkdtempSync(join(tmpdir(), "idle-gate-test-"));
- const APP_DIR = join(TMP, "app");
- mkdirSync(APP_DIR, { recursive: true });
- const CRM_TMP_ROOT = join(TMP, "scratch");
- // WORKTREE_BASE mirrors lib/common.mjs.
- WB = join(CRM_TMP_ROOT, APP_DIR.replace(/\//g, "_"), SESSION_ID);
- env = { ...process.env, APP_DIR, CRM_TMP_ROOT };
-});
-
-afterAll(() => {
- rmSync(TMP, { recursive: true, force: true });
-});
-
-const run = (stdin) =>
- spawnSync("node", [HOOK], { input: stdin, env, encoding: "utf8" }).status;
-
-describe("member-idle-gate migration-review bypass", () => {
- test("migration-review on simple worktree → allowed", () => {
- // A quality-reviewer reading the migration (simple) worktree must be ALLOWED (exit 0).
- expect(
- run(
- JSON.stringify({
- agent_type: "quality-reviewer",
- session_id: SESSION_ID,
- tool_input: { command: `cat ${WB}/simple/supabase/migrations/x.sql` },
- }),
- ),
- ).toBe(0);
- });
-
- test("premature review, no flag, no migration path → blocked", () => {
- // A plain quality-reviewer with no flag and no migration path stays BLOCKED (exit 2).
- expect(
- run(
- JSON.stringify({
- agent_type: "quality-reviewer",
- session_id: SESSION_ID,
- tool_input: { command: "ls" },
- }),
- ),
- ).toBe(2);
- });
-});
diff --git a/.claude/hooks/test/restrict-documentator-write.test.mjs b/.claude/hooks/test/restrict-documentator-write.test.mjs
index fdd8d7cb..46d04b0c 100755
--- a/.claude/hooks/test/restrict-documentator-write.test.mjs
+++ b/.claude/hooks/test/restrict-documentator-write.test.mjs
@@ -1,10 +1,4 @@
-// Tests for restrict-documentator-write.mjs (vitest, Node project).
-// Hook is gated on DOCUMENTATOR_RUN=1. When active, it allows writes to:
-// - <REPO>/docs/learnings/patterns.md (the ledger)
-// - <CONFIG_DIR>/settings.local.json
-// - <REPO>/MEMORY.md
-// - <CONFIG_DIR>/local/** (runtime additions)
-// Everything else is blocked. When inactive (no env var), pass-through.
+// Tests for restrict-documentator-write.mjs — the DOCUMENTATOR_RUN=1 allowlist (ledger, settings.local.json, MEMORY.md, CONFIG_DIR/local/**) and pass-through when inactive (vitest, Node project).
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -14,14 +8,12 @@ import { describe, test, expect } from "vitest";
const HERE = dirname(fileURLToPath(import.meta.url));
const HOOK = join(HERE, "..", "restrict-documentator-write.mjs");
-// Pin the portable roots so the allow/deny path literals below are deterministic
-// regardless of where this repo is checked out.
const baseEnv = {
...process.env,
CLAUDE_PROJECT_DIR: "/app",
CLAUDE_CONFIG_DIR: "/home/developer/.claude",
};
-delete baseEnv.APP_DIR; // APP_DIR would override CLAUDE_PROJECT_DIR
+delete baseEnv.APP_DIR;
const runHook = (envFlag, input) => {
const env = { ...baseEnv };
@@ -31,7 +23,6 @@ const runHook = (envFlag, input) => {
};
describe("restrict-documentator-write hook", () => {
- // --- Inactive (no DOCUMENTATOR_RUN env var) — pass-through always ---
test("non-documentator session, any path → allowed", () => {
expect(
runHook(
@@ -50,7 +41,6 @@ describe("restrict-documentator-write hook", () => {
).toBe(0);
});
- // --- Active (DOCUMENTATOR_RUN=1) — strict allowlist ---
test("ledger write → allowed", () => {
expect(
runHook(
@@ -164,7 +154,6 @@ describe("restrict-documentator-write hook", () => {
expect(runHook("1", "not-json{")).toBe(2);
});
- // --- Edge cases: path lookalikes ---
test("path that contains 'local/' but not under base local/ → blocked", () => {
expect(
runHook(
diff --git a/.claude/hooks/test/setup-worktree.test.mjs b/.claude/hooks/test/setup-worktree.test.mjs
index 186c5349..0c265d99 100755
--- a/.claude/hooks/test/setup-worktree.test.mjs
+++ b/.claude/hooks/test/setup-worktree.test.mjs
@@ -1,10 +1,4 @@
-// Tests for setup-worktree.mjs session-branch topology (vitest, Node project).
-// Uses a throwaway git repo as the project root via the APP_DIR override, and a
-// throwaway CRM_TMP_ROOT so worktrees land in a predictable, isolated location.
-//
-// The tests are intentionally ordered and stateful: each one observes (or mutates)
-// the worktree state produced by the previous step. Vitest runs tests within a file
-// sequentially in declaration order, which preserves that contract.
+// Tests for setup-worktree.mjs session-branch topology (vitest, Node project). Uses a throwaway git repo (APP_DIR) + CRM_TMP_ROOT. Tests are ordered and stateful — each observes the state produced by the previous step.
import {
mkdtempSync,
@@ -19,15 +13,16 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
import { describe, test, expect, beforeAll, afterAll } from "vitest";
+import { sanitizePath } from "../lib/paths.mjs";
const HERE = dirname(fileURLToPath(import.meta.url));
const HOOK = join(HERE, "..", "setup-worktree.mjs");
const SESSION_ID = "ab12cd34-1111-2222-3333-444455556666";
-const SS = SESSION_ID.split("-")[0]; // ab12cd34
+const SS = SESSION_ID.split("-")[0];
let TMP;
let APP_DIR;
-let WB; // WORKTREE_BASE: <CRM_TMP_ROOT>/<APP_DIR with '/'->'_'>/<SESSION_ID>
+let WB;
let env;
const g = (...args) =>
@@ -51,14 +46,12 @@ beforeAll(() => {
g("commit", "-q", "-m", "seed");
mkdirSync(join(APP_DIR, "node_modules"), { recursive: true });
- // Isolated scratch root + full session id supplied on stdin (no chat-service).
const CRM_TMP_ROOT = join(TMP, "scratch");
- WB = join(CRM_TMP_ROOT, APP_DIR.replace(/\//g, "_"), SESSION_ID);
+ WB = join(CRM_TMP_ROOT, sanitizePath(APP_DIR), SESSION_ID);
env = { ...process.env, APP_DIR, CRM_TMP_ROOT };
delete env.VALIDATE_WORKTREE;
- // Dispatch a COMPLEX developer for TASK-001.
dispatch("developer-TASK-001");
});
@@ -89,7 +82,6 @@ describe("setup-worktree session-branch topology", () => {
});
test("task branch forked from session branch", () => {
- // Task branch must fork from the session branch, not main directly.
expect(
g("merge-base", "--is-ancestor", `session/${SS}`, `${SS}/TASK-001`)
.status,
@@ -97,13 +89,9 @@ describe("setup-worktree session-branch topology", () => {
});
test("idempotent second run exits 0", () => {
- // Restart scenario: a second dispatch with the same session must be a no-op.
expect(dispatch("developer-TASK-001").status).toBe(0);
});
- // Regression: session restart where cleanup wiped the _session directory but git
- // still holds the worktree registration. Plain `worktree add` fails with "missing
- // but already registered"; the hook must prune + recreate.
test("stale _session registration survives dir wipe", () => {
rmSync(join(WB, "_session"), { recursive: true, force: true });
expect(
diff --git a/.claude/hooks/test/validate-on-stop.test.mjs b/.claude/hooks/test/validate-on-stop.test.mjs
new file mode 100644
index 00000000..6078ea2a
--- /dev/null
+++ b/.claude/hooks/test/validate-on-stop.test.mjs
@@ -0,0 +1,53 @@
+// Tests for validate-on-stop.mjs — dry-run short-circuits (VALIDATE_DRY_RUN=1 accepts, =fail exits 2) and the no-active-worktree accept, without running real tools.
+
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { spawnSync } from "node:child_process";
+import { afterAll, describe, test, expect } from "vitest";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const HOOK = join(HERE, "..", "validate-on-stop.mjs");
+
+const appDir = mkdtempSync(join(tmpdir(), "validate-on-stop-app-"));
+const tmpRoot = mkdtempSync(join(tmpdir(), "validate-on-stop-tmp-"));
+
+afterAll(() => {
+ rmSync(appDir, { recursive: true, force: true });
+ rmSync(tmpRoot, { recursive: true, force: true });
+});
+
+const INPUT = '{"session_id":"test-1234","agent_type":"simple-developer"}';
+
+const runHook = (dryRun) => {
+ const env = {
+ ...process.env,
+ APP_DIR: appDir,
+ CRM_TMP_ROOT: tmpRoot,
+ };
+ delete env.VALIDATE_WORKTREE;
+ delete env.VALIDATE_DRY_RUN;
+ delete env.MODE;
+ if (dryRun) env.VALIDATE_DRY_RUN = dryRun;
+ return spawnSync("node", [HOOK], { input: INPUT, env, encoding: "utf8" });
+};
+
+describe("validate-on-stop hook", () => {
+ test("VALIDATE_DRY_RUN=1 → accept (exit 0)", () => {
+ const r = runHook("1");
+ expect(r.status).toBe(0);
+ });
+
+ test("VALIDATE_DRY_RUN=fail → exit 2 with simulated failure on stderr", () => {
+ const r = runHook("fail");
+ expect(r.status).toBe(2);
+ expect(r.stderr).toContain("Validation failed");
+ expect(r.stderr).toContain("simulated");
+ });
+
+ test("no active worktree → accept (exit 0)", () => {
+ const r = runHook("");
+ expect(r.status).toBe(0);
+ });
+});
diff --git a/.claude/hooks/typecheck-on-commit.mjs b/.claude/hooks/typecheck-on-commit.mjs
deleted file mode 100755
index 03afb4aa..00000000
--- a/.claude/hooks/typecheck-on-commit.mjs
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/env node
-// SubagentStop hook — runs typecheck on each active worktree with changes.
-// Exit 2 on failure → stderr injected as error, subagent stays alive to fix.
-
-import { existsSync } from "node:fs";
-import {
- readStdin,
- crmIdentity,
- baseBranch,
- activeWorktrees,
- worktreeDirty,
- worktreeChangedFiles,
- tailLines,
- bash,
-} from "./lib/common.mjs";
-
-const ctx = crmIdentity(readStdin());
-ctx.log(`typecheck START REPO=${ctx.repo} MODE=${process.env.MODE || ""}`);
-
-if (!existsSync(ctx.repo)) {
- ctx.log("typecheck EXIT=0 cd_failed");
- process.exit(0);
-}
-
-// Only check ACTIVE feature worktrees under this session's worktreeBase. The
-// main repo is the merge target — pre-existing state there is not the current
-// subagent's concern. Running typecheck on the repo with orphan untracked files
-// from previous sessions caused a regression where a developer deviated from its
-// task to "fix" unrelated typecheck errors.
-//
-// VALIDATE_WORKTREE: when set by validate-before-review, restrict to that single
-// worktree. Avoids the "shared brakes" issue where one dev's broken state blocks
-// all parallel SendMessages (one bad TASK poisoning N reviewers).
-const worktrees = activeWorktrees(ctx);
-if (worktrees.length === 0) {
- ctx.log("typecheck EXIT=0 no_active_worktree");
- process.exit(0);
-}
-
-const base = baseBranch();
-let failed = false;
-let aggregatedErr = "";
-
-for (const wt of worktrees) {
- if (!worktreeDirty(wt, base)) {
- ctx.log(`typecheck SKIP wt=${wt} (no changes)`);
- continue;
- }
-
- // Skip if every changed path is under adr/. ADRs are .md docs and don't
- // affect typecheck; running it on a doc-only commit wastes ~10-20s per ADR.
- const changed = worktreeChangedFiles(wt, base);
- if (changed.length > 0 && changed.every((f) => f.startsWith("adr/"))) {
- ctx.log(`typecheck SKIP wt=${wt} (adr-only)`);
- continue;
- }
-
- const result = bash("npm run typecheck 2>&1", { cwd: wt });
- if (result.status !== 0) {
- failed = true;
- aggregatedErr += `=== typecheck failed in ${wt} ===\n${tailLines(result.stdout, 20)}\n\n`;
- ctx.log(`typecheck FAIL wt=${wt} EXIT=${result.status}`);
- } else {
- ctx.log(`typecheck OK wt=${wt}`);
- }
-}
-
-if (failed) {
- process.stderr.write("Typecheck failed — fix TypeScript errors before completing:\n");
- process.stderr.write(aggregatedErr);
- ctx.log("typecheck EXIT=2");
- process.exit(2);
-}
-
-ctx.log("typecheck EXIT=0 OK (all worktrees)");
-process.exit(0);
diff --git a/.claude/hooks/validate-before-review.mjs b/.claude/hooks/validate-before-review.mjs
index 988d17ee..110b13ea 100755
--- a/.claude/hooks/validate-before-review.mjs
+++ b/.claude/hooks/validate-before-review.mjs
@@ -1,60 +1,55 @@
#!/usr/bin/env node
-// PreToolUse hook for SendMessage tool.
-// When the developer is about to SendMessage a reviewer or the merger, run the
-// project validation chain. If any step fails, exit 2 to block the SendMessage;
-// the dev sees the stderr as a tool_use_error.
-//
-// Why gate reviewers AND merger:
-// - If validation fails, the dev must fix and commit again — and the reviewers
-// must re-evaluate the new commit. So reviewers only ever see validated commits.
-// - The per-worktree SHA cache makes validating before every reviewer message
-// essentially free on unchanged HEADs (the "dev messages reviewer-A then
-// reviewer-B" pair runs the chain once, then hits the cache).
-//
-// Behavior:
-// - Skips for non-reviewer/non-merger recipients.
-// - Per-worktree SHA cache: a previous success on the same HEAD short-circuits.
-// - Otherwise runs (in order): typecheck, prettier, unit-app, unit-functions, e2e.
-// - First failure → exit 2 with the failing script's stderr passed through.
-//
-// DRY RUN MODE: VALIDATE_DRY_RUN=1 → sub-scripts skipped, exit 0.
-// VALIDATE_DRY_RUN=fail → simulates a failure, exit 2.
+// PreToolUse(SendMessage) — when a developer messages a reviewer/merger, run the validation chain (prettier auto-fix, typecheck, unit-app, unit-functions, e2e) on the caller's worktree; exit 2 blocks the SendMessage on failure. A per-worktree SHA cache short-circuits repeats. VALIDATE_DRY_RUN=1 skips the chain; =fail simulates a failure.
-import { existsSync, mkdirSync, writeFileSync, readFileSync, unlinkSync } from "node:fs";
+import { readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { join } from "node:path";
-import { readStdin, parseJson, crmIdentity, sanitizePath, exec, bash, git } from "./lib/common.mjs";
-
-const stdin = readStdin();
-const input = parseJson(stdin);
-const ctx = crmIdentity(input);
-const { flagsDir, worktreeBase, sessionId } = ctx;
-
-try {
- mkdirSync(flagsDir, { recursive: true });
-} catch {
- // best-effort
-}
-
-const touch = (p) => {
+import { createHookContext } from "./lib/context.mjs";
+import { stringifyMessage } from "./lib/io.mjs";
+import { sanitizePath } from "./lib/paths.mjs";
+import { exec } from "./lib/process.mjs";
+import {
+ getFirstTaskId,
+ isDeveloper,
+ isMerger,
+ isQualityReviewer,
+ isTestValidator,
+} from "./lib/teams.mjs";
+import { taskWorktreePath } from "./lib/topology.mjs";
+import { getActiveWorktrees, runValidationSteps } from "./lib/validation.mjs";
+
+const stdin = readFileSync(0, "utf8");
+const input = JSON.parse(stdin);
+const ctx = createHookContext(input, "validate-before-review");
+
+const cacheFile = (wt, suffix) =>
+ join(ctx.sessionDir, `cache-${sanitizePath(wt)}${suffix}`);
+const headOf = (wt) =>
+ exec("git", ["-C", wt, "rev-parse", "HEAD"]).stdout.trim();
+const readSha = (file) => {
try {
- writeFileSync(p, "");
+ return readFileSync(file, "utf8").trim();
} catch {
- // best-effort
+ return "";
}
};
+const allAtCachedSha = (worktrees, suffix) =>
+ worktrees.length > 0 &&
+ worktrees.every((wt) => {
+ const head = headOf(wt);
+ return head && head === readSha(cacheFile(wt, suffix));
+ });
+
+const isGatedRecipient = (to) =>
+ isQualityReviewer(to) || isTestValidator(to) || isMerger(to);
-// On exit, emit an EXIT=N log line. When the exit is a block (code 2) AND we
-// reached actual validation (logWt set), also write a fail-cache so sibling
-// SendMessages for the same SHA fail instantly instead of re-running the chain.
-// (This mirrors the bash `trap … EXIT`.)
let logWt = "";
function finish(code) {
- ctx.log(`validate-before-review EXIT=${code} wt=${logWt}`);
+ ctx.log(`EXIT=${code} wt=${logWt}`);
if (code === 2 && logWt) {
- const sha = exec("git", ["-C", logWt, "rev-parse", "HEAD"]).stdout.trim();
+ const sha = headOf(logWt);
if (sha) {
try {
- writeFileSync(join(flagsDir, `cache-${sanitizePath(logWt)}.bad.sha`), sha);
+ writeFileSync(cacheFile(logWt, ".bad.sha"), sha);
} catch {
// best-effort
}
@@ -65,221 +60,70 @@ function finish(code) {
if (!stdin) finish(0);
-// (A) Only gate when a developer agent is the caller. The orchestrator also
-// sends to merger (bare name) — without this check, its shutdown batch and
-// merge-forward messages get fully validated, wasting ~60s each.
-const agentName = process.env.CLAUDE_AGENT_NAME || "";
-const agentType = input.agent_type || "";
-const recv = input.tool_input?.to || "";
-ctx.log(`validate-before-review INVOKE agent_env='${agentName}' agent_type='${agentType}' to='${recv}'`);
+const { agentName, agentType } = ctx;
+const to = input.tool_input?.to || "";
+ctx.log(
+ `INVOKE agent_env='${agentName}' agent_type='${agentType}' to='${to}'`,
+);
-const callerIsDeveloper =
- /^developer-/.test(agentName) || agentType === "developer" || /^developer-/.test(agentType);
+const callerIsDeveloper = isDeveloper(agentName) || isDeveloper(agentType);
if (!callerIsDeveloper) finish(0);
-const to = input.tool_input?.to || "";
+if (!isGatedRecipient(to)) finish(0);
-// Gate only for reviewer / validator / merger recipients.
-const gated =
- /^quality-reviewer[-@]/.test(to) || /^test-validator[-@]/.test(to) || /^merger[-@]/.test(to) || to === "merger";
-if (!gated) finish(0);
-
-// (B) Skip validation for shutdown_request messages — teardown carries no diff.
-const message = input.tool_input?.message;
-const msgBody = typeof message === "string" ? message : message != null ? JSON.stringify(message) : "";
+const msgBody = stringifyMessage(input.tool_input?.message);
if (msgBody.includes("shutdown_request")) finish(0);
-// Derive the caller's worktree so chained scripts validate only that one.
-// Source of truth: TASK-XXX suffix on the recipient name, else in the message.
-let taskId = (to.match(/TASK-[0-9]+/) || [])[0] || "";
-if (!taskId) taskId = (msgBody.match(/TASK-[0-9]+/) || [])[0] || "";
-
-let validateWorktree = "";
-let flagQr;
-let flagTv;
-let flagMerger;
-if (taskId) {
- validateWorktree = join(worktreeBase, taskId);
- process.env.VALIDATE_WORKTREE = validateWorktree; // exported for the sub-scripts
- flagQr = join(flagsDir, `notified-qr-${taskId}`);
- flagTv = join(flagsDir, `notified-tv-${taskId}`);
- flagMerger = join(flagsDir, `notified-merger-${taskId}`);
-}
+const taskId = getFirstTaskId(to) || getFirstTaskId(msgBody);
+const validateWorktree = taskId ? taskWorktreePath(ctx, taskId) : "";
logWt = validateWorktree;
-// (F) Enforce that the developer notifies BOTH reviewers before reaching merger.
-if (taskId && (to === "merger" || /^merger-/.test(to))) {
- let missing = "";
- if (!existsSync(flagQr)) missing += `quality-reviewer-${taskId} `;
- if (!existsSync(flagTv)) missing += `test-validator-${taskId} `;
- if (missing) {
- process.stderr.write(
- `[validate-before-review] Blocked: cannot message merger for ${taskId} before notifying all reviewers. Missing: ${missing}\n`
- );
- process.stderr.write(
- `Send "ready, please review" to both quality-reviewer-${taskId} AND test-validator-${taskId} first.\n`
- );
- finish(2);
- }
- // Both reviewer flags exist → the full chain already ran and passed when the
- // developer first notified the reviewers. Skip re-running it for the merger.
- ctx.log(`validate-before-review COMPLEX-SKIP to=merger ${taskId} (both reviewer flags present)`);
- touch(flagMerger);
- finish(0);
-}
-
-ctx.log(`validate-before-review START to=${to} wt=${validateWorktree}`);
+// Same scope as the validation chain: the task worktree when the task id is
+// known, otherwise all session worktrees.
+const cacheWorktrees = getActiveWorktrees(ctx, validateWorktree);
-// Active worktrees under this session's base.
-const activeWorktrees = git(["worktree", "list", "--porcelain"])
- .stdout.split("\n")
- .filter((l) => l.startsWith("worktree "))
- .map((l) => l.slice("worktree ".length))
- .filter((p) => p.startsWith(worktreeBase + "/"));
-
-// (C) Scope the SHA cache to the specific worktree when set, else all active.
-const cacheWorktrees = validateWorktree ? [validateWorktree] : activeWorktrees;
-
-const headOf = (wt) => exec("git", ["-C", wt, "rev-parse", "HEAD"]).stdout.trim();
-const readSha = (file) => {
- try {
- return readFileSync(file, "utf8").trim();
- } catch {
- return "";
- }
-};
-
-// SHA cache: skip the chain if HEAD of every cache worktree matches the SHA we
-// last validated successfully. Invalidated by every new commit.
-if (cacheWorktrees.length > 0) {
- let allCached = true;
- for (const wt of cacheWorktrees) {
- const head = headOf(wt);
- if (!head || head !== readSha(join(flagsDir, `cache-${sanitizePath(wt)}.sha`))) {
- allCached = false;
- break;
- }
- }
- if (allCached) {
- ctx.log(`validate-before-review CACHE HIT to=${to} (worktree at last-validated SHA)`);
- if (taskId) {
- if (/^quality-reviewer-/.test(to)) touch(flagQr);
- else if (/^test-validator-/.test(to)) touch(flagTv);
- else if (to === "merger" || /^merger-/.test(to)) touch(flagMerger);
- }
- finish(0);
- }
-}
-
-// Fail cache: if the current HEAD already failed a previous run on the same SHA,
-// fail instantly instead of re-running the full chain (handles the dev messaging
-// both reviewers simultaneously on the same broken commit).
-if (cacheWorktrees.length > 0) {
- let allFailed = true;
- for (const wt of cacheWorktrees) {
- const head = headOf(wt);
- if (!head || head !== readSha(join(flagsDir, `cache-${sanitizePath(wt)}.bad.sha`))) {
- allFailed = false;
- break;
- }
- }
- if (allFailed) {
- ctx.log(`validate-before-review FAIL-CACHE HIT to=${to} (SHA already failed)`);
- process.stderr.write(
- "This commit already failed validation. Fix the issue and make a new commit before messaging the reviewer.\n"
- );
- finish(2);
- }
+if (allAtCachedSha(cacheWorktrees, ".sha")) {
+ ctx.log(`CACHE HIT to=${to} (worktree at last-validated SHA)`);
+ finish(0);
}
-// Dry-run hooks (test-only).
-if (process.env.VALIDATE_DRY_RUN === "1") {
- process.stderr.write(`VALIDATE_WORKTREE=${validateWorktree || "<all>"}\n`);
- ctx.log("validate-before-review DRY_RUN=1, skipping checks, exit 0");
- finish(0);
-} else if (process.env.VALIDATE_DRY_RUN === "fail") {
- ctx.log("validate-before-review DRY_RUN=fail, exit 2");
- process.stderr.write("Validation failed (simulated).\n");
+if (allAtCachedSha(cacheWorktrees, ".bad.sha")) {
+ ctx.log(`FAIL-CACHE HIT to=${to} (SHA already failed)`);
+ ctx.error(
+ "This commit already failed validation. Fix the issue and make a new commit before messaging the reviewer.",
+ );
finish(2);
}
-// Auto-apply prettier before the validation chain. If prettier --write fails
-// (e.g. a syntax error), exit early with the actual error.
-if (validateWorktree && existsSync(validateWorktree)) {
- const pretty = bash("npx prettier --write 'src/**/*.{ts,tsx,js,jsx,css,json,html}' 2>&1", { cwd: validateWorktree });
- if (pretty.status !== 0) {
- ctx.log(`validate-before-review auto-prettier FAILED exit=${pretty.status} wt=${validateWorktree}`);
- process.stderr.write(
- "Prettier could not format one or more files (likely a syntax error). Fix the issue and commit before sending to reviewer.\n"
- );
- process.stderr.write(pretty.stdout + "\n");
- finish(2);
- }
- if (exec("git", ["-C", validateWorktree, "diff", "--quiet"]).status !== 0) {
- exec("git", ["-C", validateWorktree, "add", "-A"]);
- exec("git", ["-C", validateWorktree, "commit", "-m", `style(${taskId}): auto-apply prettier`]);
- ctx.log(`validate-before-review auto-prettier wt=${validateWorktree} committed`);
- }
-}
+ctx.log(`START to=${to} wt=${validateWorktree}`);
-// Ordered list: cheapest checks first to fail fast.
-const scripts = [
- "typecheck-on-commit.mjs",
- "prettier-on-stop.mjs",
- "run-unit-tests-app.mjs",
- "run-unit-tests-functions.mjs",
- "run-e2e-tests.mjs",
-];
-// Pipe a SubagentStop-like stdin so the sub-scripts don't error on empty input.
-const emptyStdin = JSON.stringify({
- hook_event_name: "PreToolUse_SendMessage",
- matcher: "SendMessage",
- session_id: sessionId,
-});
+const result = runValidationSteps(ctx, { worktree: validateWorktree });
-for (const script of scripts) {
- const full = join(import.meta.dirname, script);
- if (!existsSync(full)) {
- ctx.log(`validate-before-review WARN ${script} missing, skipping`);
- continue;
- }
- const r = exec("node", [full], { input: emptyStdin });
- if (r.status === 0) {
- ctx.log(`validate-before-review ${script} OK`);
- } else {
- ctx.log(`validate-before-review ${script} FAILED exit=${r.status}`);
- process.stderr.write((r.stdout || "") + (r.stderr || ""));
- finish(2);
- }
+if (!result.ok) {
+ ctx.error(
+ `Validation failed at step '${result.step}'. Fix the issue and commit before messaging the reviewer.`,
+ );
+ ctx.error(result.output);
+ finish(2);
}
-ctx.log(`validate-before-review ALL OK to=${to}`);
+ctx.log(`ALL OK to=${to}${result.skipReason ? ` (${result.skipReason})` : ""}`);
-// Cache the SHA(s) we just validated so subsequent SendMessages on the same
-// commit short-circuit. Also clear the fail cache so a future fix+commit isn't
-// blocked by a stale bad-SHA entry.
-for (const wt of cacheWorktrees) {
- const head = headOf(wt);
- if (head) {
+if (!result.skipReason) {
+ for (const wt of cacheWorktrees) {
+ const head = headOf(wt);
+ if (!head) continue;
try {
- writeFileSync(join(flagsDir, `cache-${sanitizePath(wt)}.sha`), head);
+ writeFileSync(cacheFile(wt, ".sha"), head);
} catch {
// best-effort
}
try {
- unlinkSync(join(flagsDir, `cache-${sanitizePath(wt)}.bad.sha`));
+ unlinkSync(cacheFile(wt, ".bad.sha"));
} catch {
// best-effort
}
}
}
-// (F) Record that this reviewer/validator/merger was successfully notified.
-// member-idle-gate reads these flags to unblock each agent type.
-if (taskId) {
- if (/^quality-reviewer-/.test(to)) touch(flagQr);
- else if (/^test-validator-/.test(to)) touch(flagTv);
- else if (to === "merger" || /^merger-/.test(to)) touch(flagMerger);
-}
-
finish(0);
diff --git a/.claude/hooks/validate-on-stop.mjs b/.claude/hooks/validate-on-stop.mjs
new file mode 100755
index 00000000..1657b5e8
--- /dev/null
+++ b/.claude/hooks/validate-on-stop.mjs
@@ -0,0 +1,21 @@
+#!/usr/bin/env node
+// SubagentStop — full validation chain (prettier auto-fix, typecheck, unit app/functions, e2e) on active worktrees with changes; exit 2 keeps the subagent alive to fix and commit. VALIDATE_DRY_RUN=1 skips the chain; =fail simulates a failure.
+
+import { readFileSync } from "node:fs";
+import { createHookContext } from "./lib/context.mjs";
+import { runValidationSteps } from "./lib/validation.mjs";
+
+const ctx = createHookContext(readFileSync(0, "utf8"), "validate");
+ctx.log(`START REPO=${ctx.repo} MODE=${process.env.MODE || ""}`);
+
+const result = runValidationSteps(ctx);
+
+if (!result.ok) {
+ ctx.fail(
+ `Validation failed at step '${result.step}' — fix the errors and commit before completing:\n` +
+ result.output,
+ { log: `step=${result.step}` },
+ );
+}
+
+ctx.accept(result.skipReason || "OK (all worktrees)");
diff --git a/.claude/rules/validation-commands.md b/.claude/rules/validation-commands.md
index 71f432b9..29b03024 100644
--- a/.claude/rules/validation-commands.md
+++ b/.claude/rules/validation-commands.md
@@ -5,9 +5,10 @@ paths: []
# Validation commands — DO NOT RUN
Validation is automated:
-- `SubagentStop` hooks run typecheck / prettier / unit / e2e after every developer stops.
-- `validate-before-review` PreToolUse hook re-runs them when a COMPLEX dev SendMessages a reviewer or merger.
-- `block-bash-validation` PreToolUse hook blocks `developer`, `quality-reviewer`, `test-validator` from running them manually.
+- The `validate-on-stop.mjs` SubagentStop hook runs the full chain (prettier auto-fix, typecheck, unit, e2e) after the simple-developer stops.
+- The `validate-before-review.mjs` PreToolUse hook runs the same chain when a COMPLEX dev SendMessages a reviewer or merger (SHA-cached: unchanged worktrees are not revalidated).
+- The `bash-guard.mjs` PreToolUse hook blocks `developer`, `simple-developer`, `quality-reviewer`, `test-validator` from running them manually.
+- Prettier is auto-applied and committed by the validation chain — formatting never needs manual action unless a file has a syntax error.
## Forbidden commands (developer / quality-reviewer / test-validator)
@@ -23,7 +24,7 @@ Validation is automated:
Why blocked:
- Burns tool budget — each call returns a hook block error.
- Can hang — `npx vitest` launches a headed Chromium browser; without a display it waits forever. Hooks set `CI=true` to force `chromium-headless-shell`; manual calls don't.
-- Duplicates hook work — `SubagentStop` already runs them after you stop; failures appear in stderr.
+- Duplicates hook work — the validation hooks already run them; failures appear in stderr.
## What to do instead
diff --git a/.claude/settings.json b/.claude/settings.json
index 7381c6dc..5999b24c 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -25,37 +25,12 @@
},
"hooks": {
"PreToolUse": [
- {
- "matcher": "Bash|Read|Grep|Glob|SendMessage",
- "hooks": [
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/member-idle-gate.mjs"
- }
- ]
- },
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/silent-mode-check.mjs"
- },
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/circuit-breaker.mjs"
- },
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-bash-file-write.mjs"
- },
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-bash-validation.mjs"
- },
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-orchestrator-merge.mjs"
+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/bash-guard.mjs"
},
{
"type": "command",
@@ -86,43 +61,10 @@
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-before-review.mjs",
- "timeout": 180,
+ "timeout": 900,
"statusMessage": "Validating before review/merge..."
}
]
- },
- {
- "matcher": "TeamDelete",
- "hooks": [
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/teamdelete-gate.mjs",
- "timeout": 5,
- "statusMessage": "Checking team teardown state..."
- }
- ]
- },
- {
- "matcher": "TeamCreate",
- "hooks": [
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/teamcreate-wipe-orphan.mjs",
- "timeout": 5
- }
- ]
- }
- ],
- "PostToolUse": [
- {
- "matcher": "TeamDelete",
- "hooks": [
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/teamdelete-cleanup.mjs",
- "timeout": 5
- }
- ]
}
],
"SubagentStart": [
@@ -155,33 +97,9 @@
"hooks": [
{
"type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/typecheck-on-commit.mjs",
- "timeout": 120,
- "statusMessage": "Validating typecheck..."
- },
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/prettier-on-stop.mjs",
- "timeout": 60,
- "statusMessage": "Validating prettier..."
- },
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/run-unit-tests-app.mjs",
- "timeout": 180,
- "statusMessage": "Running unit tests (app)..."
- },
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/run-unit-tests-functions.mjs",
- "timeout": 180,
- "statusMessage": "Running unit tests (functions)..."
- },
- {
- "type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/run-e2e-tests.mjs",
- "timeout": 600,
- "statusMessage": "Running e2e tests..."
+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-on-stop.mjs",
+ "timeout": 900,
+ "statusMessage": "Running validation (prettier, typecheck, unit, e2e)..."
}
]
}
diff --git a/.claude/skills/agent-team/SKILL.md b/.claude/skills/agent-team/SKILL.md
index 8076d441..f64eb914 100644
--- a/.claude/skills/agent-team/SKILL.md
+++ b/.claude/skills/agent-team/SKILL.md
@@ -18,7 +18,7 @@ Invoked by `chat-orchestrator` (team-lead) for COMPLEX requests.
## Wave of N tickets
1. PLANNER produces N tickets.
-2. Lead `TeamCreate({team_name: "tickets-<SESSION_SHORT_ID>"})` (once per wave). Replace `<SESSION_SHORT_ID>` with the actual 8-char value (e.g. `tickets-46bc14c5`). A PreToolUse hook wipes any orphan team with the same name from a prior crashed run of THIS session before creation.
+2. Lead `TeamCreate({team_name: "tickets-<SESSION_SHORT_ID>"})` (once per wave). Replace `<SESSION_SHORT_ID>` with the actual 8-char value (e.g. `tickets-46bc14c5`). If an orphan team from a prior crashed run still holds the name, TeamCreate may return an auto-suffixed name — always use the team name TeamCreate RETURNS verbatim in all subsequent dispatches.
3. Lead dispatches all members in ONE message: **N developers + 2N reviewers + 1 shared `merger` = 3N + 1**.
4. Lead `SendMessage(GO)` to each `developer-TASK-XXX` (one message per dev, in one assistant turn).
5. Lead enters passive wait. Each ticket's dev↔reviewers↔merger flow runs concurrently inside the team.
@@ -174,11 +174,11 @@ Scan incoming `<teammate-message>` blocks for `shutdown_approved`:
TeamDelete({})
```
-`{}` = "the only team this session has open". `teamdelete-gate.mjs` blocks if any non-lead member hasn't acknowledged. If blocked: yield first, retry next turn — do not retry in same turn.
+`{}` = "the only team this session has open". Delete only after step 3c: every non-lead member must have acknowledged the shutdown (or been logged as unresponsive). If TeamDelete errors because members are still busy: yield first, retry next turn — do not retry in same turn.
-### 3e — Cleanup (automatic)
+### 3e — Cleanup
-`teamdelete-cleanup.mjs` (PostToolUse) silently removes residual `~/.claude/teams/tickets-<SESSION_SHORT_ID>/`. Lead does nothing.
+Residual `~/.claude/teams/tickets-<SESSION_SHORT_ID>/` directories from crashed runs are harmless — TeamCreate auto-suffixes when a name is taken (see step 2). Lead does nothing.
Subagent transcripts (`subagents/agent-<task_id>.{jsonl,meta.json}`) are kept for stats/debugging — removed at chat-service session end.
diff --git a/eslint.config.js b/eslint.config.js
index fc758b55..c95e62d8 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -11,11 +11,10 @@ export default tseslint.config(
{ ignores: ["dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
- files: ["**/*.{ts,tsx}"],
+ files: ["**/*.{ts,tsx,mjs}"],
ignores: ["**/node_modules/**", "**/dist/**", "**/.astro/**"],
languageOptions: {
ecmaVersion: 2020,
- globals: globals.browser,
},
plugins: {
"react-hooks": reactHooks,
@@ -39,6 +38,23 @@ export default tseslint.config(
"@typescript-eslint/consistent-type-imports": "warn",
},
},
+ {
+ files: ["**/*.{ts,tsx}"],
+ languageOptions: {
+ globals: globals.browser,
+ },
+ },
+ {
+ // Node scripts and Claude Code hooks. TypeScript files rely on the
+ // compiler for undefined identifiers; plain JS needs no-undef back on.
+ files: ["**/*.mjs"],
+ languageOptions: {
+ globals: globals.node,
+ },
+ rules: {
+ "no-undef": "error",
+ },
+ },
{
files: [
"src/components/admin/*.{ts,tsx}",
diff --git a/package.json b/package.json
index d35a11eb..5c93d5d4 100644
--- a/package.json
+++ b/package.json
@@ -15,8 +15,8 @@
"preview": "vite preview",
"lint:apply": "eslint **/*.{mjs,ts,tsx} --fix",
"lint": "eslint **/*.{mjs,ts,tsx}",
- "prettier:apply": "prettier --config ./.prettierrc.json --write --list-different \"**/*.{js,json,ts,tsx,css,md,html}\"",
- "prettier": "prettier --config ./.prettierrc.json --check \"**/*.{js,json,ts,tsx,css,md,html}\"",
+ "prettier:apply": "prettier --config ./.prettierrc.json --write --list-different \"**/*.{mjs,js,json,ts,tsx,css,md,html}\"",
+ "prettier": "prettier --config ./.prettierrc.json --check \"**/*.{mjs,js,json,ts,tsx,css,md,html}\"",
"registry:build": "npx shadcn build",
"registry:gen": "node ./scripts/generate-registry.mjs",
"ghpages:deploy": "node ./scripts/ghpages-deploy.mjs",
diff --git a/scripts/ghpages-deploy.mjs b/scripts/ghpages-deploy.mjs
index cfc11bd3..003ea15d 100644
--- a/scripts/ghpages-deploy.mjs
+++ b/scripts/ghpages-deploy.mjs
@@ -1,14 +1,14 @@
-import * as ghpages from 'gh-pages';
+import * as ghpages from "gh-pages";
ghpages.publish(
- 'dist',
- {
- branch: process.env.DEPLOY_BRANCH || 'gh-pages',
- repo: process.env.DEPLOY_REPO_URL || undefined,
- },
- function (err) {
- if (err) {
- console.error('Failed to deploy to GitHub Pages', err);
- }
+ "dist",
+ {
+ branch: process.env.DEPLOY_BRANCH || "gh-pages",
+ repo: process.env.DEPLOY_REPO_URL || undefined,
+ },
+ function (err) {
+ if (err) {
+ console.error("Failed to deploy to GitHub Pages", err);
}
+ },
);
diff --git a/scripts/supabase-remote-init.mjs b/scripts/supabase-remote-init.mjs
index a2de747f..83ad4958 100644
--- a/scripts/supabase-remote-init.mjs
+++ b/scripts/supabase-remote-init.mjs
@@ -159,6 +159,7 @@ async function selectRegion() {
}
async function waitForProjectToBeReady({ projectRef }) {
+ // eslint-disable-next-line no-console
console.log("Waiting for project to be ready...");
const { stdout } = await execa(
"npx",
@@ -208,6 +209,7 @@ async function linkProject({ projectRef, databasePassword }) {
).catch(() => {
retry++;
if (retry === 1) {
+ // eslint-disable-next-line no-console
console.log("Waiting for project to be ready...");
}
return sleep(1000).then(() =>