Skip to content

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

Apply review

Jonathan ARNAULTafd5a3d51531
diff --git a/.claude/agents/chat-orchestrator.md b/.claude/agents/chat-orchestrator.md
index 3677492b..09b8a468 100644
--- a/.claude/agents/chat-orchestrator.md
+++ b/.claude/agents/chat-orchestrator.md
@@ -679,9 +679,14 @@ When every ticket of the wave is `DONE` or `FAILED`:
#### Promotion (after the last wave)
First reconcile — a ticket could be `DONE` on disk yet mis-tracked in your note. Run
-this read-only check (allowed — not a merge-class command):
+this read-only check (allowed — not a merge-class command). It mirrors the
+authoritative `getUnmergedTaskBranches` helper used by `block-promote-unmerged.mjs`
+(that hook is the real gate; keep this snippet aligned with it): it skips
+`<SESSION_SHORT_ID>/simple` (the SIMPLE/migration branch promotes straight to main,
+never into the session branch) and treats an empty/failed count as unmerged
+(fail-closed):
```
-Bash("for b in $(git -C $CLAUDE_PROJECT_DIR for-each-ref --format='%(refname:short)' refs/heads/<SESSION_SHORT_ID>); do n=$(git -C $CLAUDE_PROJECT_DIR rev-list --count session/<SESSION_SHORT_ID>..$b 2>/dev/null); [ \"${n:-0}\" -gt 0 ] && echo \"$b: $n unmerged\"; done")
+Bash("for b in $(git -C $CLAUDE_PROJECT_DIR for-each-ref --format='%(refname:short)' refs/heads/<SESSION_SHORT_ID>); do [ \"$b\" = \"<SESSION_SHORT_ID>/simple\" ] && continue; n=$(git -C $CLAUDE_PROJECT_DIR rev-list --count session/<SESSION_SHORT_ID>..$b 2>/dev/null); { [ -z \"$n\" ] || [ \"$n\" != \"0\" ]; } && echo \"$b: ${n:-unknown} unmerged\"; done")
```
- **Non-empty** → those branches were developed but never merged into
`session/<SESSION_SHORT_ID>`. For each, resume its normal stages (review it if it
diff --git a/.claude/hooks/block-promote-unmerged.mjs b/.claude/hooks/block-promote-unmerged.mjs
index 7ac0bd5d..531cbe2c 100755
--- a/.claude/hooks/block-promote-unmerged.mjs
+++ b/.claude/hooks/block-promote-unmerged.mjs
@@ -13,8 +13,8 @@
import { readFileSync } from "node:fs";
import { createHookContext } from "./lib/context.mjs";
import { parseDispatch } from "./lib/dispatch-parse.mjs";
-import { git } from "./lib/git.mjs";
-import { sessionBranch } from "./lib/topology.mjs";
+import { getUnmergedTaskBranches, git } from "./lib/git.mjs";
+import { sessionBranch, simpleBranch } from "./lib/topology.mjs";
const input = JSON.parse(readFileSync(0, "utf8"));
const ctx = createHookContext(input, "block-promote-unmerged");
@@ -33,29 +33,21 @@ if (
process.exit(0);
}
-// Every task branch lives under refs/heads/<short>/ (e.g. <short>/TASK-001,
-// <short>/simple). session/<short> and session-base/<short> have a different
-// prefix and are not matched.
-const branches = git([
- "for-each-ref",
- "--format=%(refname:short)",
- `refs/heads/${short}`,
-])
- .stdout.split("\n")
- .map((s) => s.trim())
- .filter(Boolean);
-
-const unmerged = [];
-for (const br of branches) {
- const n = git(["rev-list", "--count", `${session}..${br}`]).stdout.trim();
- if (Number(n) > 0) unmerged.push(`${br} (${n} unmerged commit(s))`);
-}
+// Task branches under refs/heads/<short>/ with commits not on the session branch.
+// <short>/simple is excluded: the SIMPLE flow / migration round promotes it
+// straight to main, never into the session branch, so it is legitimately "ahead"
+// of session/<short> and must not block a COMPLEX promotion. Fails CLOSED — a
+// branch whose rev-list count can't be read is reported as unmerged.
+const unmerged = getUnmergedTaskBranches(short, session, [simpleBranch(ctx)]);
if (unmerged.length === 0) process.exit(0);
+const describe = ({ branch, count }) =>
+ ` - ${branch} (${count === null ? "unmerged (count unavailable)" : `${count} unmerged commit(s)`})`;
+
ctx.fail(
`Refusing to promote ${session} to main — these task branches have commits NOT yet merged into the session branch:\n` +
- unmerged.map((u) => ` - ${u}`).join("\n") +
+ unmerged.map(describe).join("\n") +
"\n" +
"A ticket was developed but never merged (its reviewers/merger were likely never dispatched). For EACH branch above, drive its ticket through REVIEW -> MERGE (dispatch its quality-reviewer + test-validator if needed, then its per-ticket merger) so its work lands on the session branch. Re-dispatch the promotion merger only once this list is empty.",
{ log: `BLOCK unmerged=${unmerged.length}` },
diff --git a/.claude/hooks/enforce-dev-dispatch.mjs b/.claude/hooks/enforce-dev-dispatch.mjs
index 114c9c0e..8d086b56 100755
--- a/.claude/hooks/enforce-dev-dispatch.mjs
+++ b/.claude/hooks/enforce-dev-dispatch.mjs
@@ -1,9 +1,11 @@
#!/usr/bin/env node
// PreToolUse(Agent) — force `developer` dispatches onto the session worktree that
-// setup-worktree creates (WORKTREE_PATH in the prompt) and forbid the Agent
-// tool's own isolation:"worktree", which spawns off-convention `worktree-agent-*`
+// setup-worktree creates (WORKTREE_PATH in the prompt), forbid the Agent tool's
+// own isolation:"worktree" (which spawns off-convention `worktree-agent-*`
// branches outside the session-branch topology — breaking Stage A merges and the
-// migration diff baseline. Keeps the orchestrator on the STATE B dispatch
+// migration diff baseline), and forbid run_in_background:true (STATE B is fully
+// synchronous — a detached developer would let the orchestrator advance before
+// the worktree is finished). Keeps the orchestrator on the STATE B dispatch
// template instead of improvising a free-form prompt.
//
// simple-developer is intentionally NOT gated here: setup-worktree derives its
@@ -40,6 +42,13 @@ if (d.isolation === "worktree") {
);
}
+if (d.runInBackground) {
+ ctx.fail(
+ "developer must NOT be dispatched with run_in_background:true — STATE B drives every wave synchronously in the foreground (a foreground Agent call blocks until the subagent returns). A detached developer would let the orchestrator advance to review/merge before the worktree is finished. Drop run_in_background.",
+ { log: "BLOCK run_in_background" },
+ );
+}
+
if (!d.worktreePath) {
ctx.fail(
"developer dispatch prompt is missing 'WORKTREE_PATH: <WORKTREE_BASE>/TASK-XXX' (and BRANCH_NAME). Use the STATE B dispatch template verbatim instead of a free-form prompt.",
diff --git a/.claude/hooks/lib/git.mjs b/.claude/hooks/lib/git.mjs
index 1c751f8d..624dd5fa 100644
--- a/.claude/hooks/lib/git.mjs
+++ b/.claude/hooks/lib/git.mjs
@@ -37,18 +37,52 @@ export function getWorktreeEntries() {
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) {
+// Combined per-worktree change summary in a single `git status --porcelain`
+// (working tree) + one `git log` (commits ahead of base) + one `git diff
+// --name-only` (committed file names). Returns { dirty, changedFiles } so callers
+// (validate-on-stop) get both signals without spawning `git status` twice.
+export function getWorktreeChangeSummary(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)]),
+ const ahead = exec("git", ["-C", wt, "log", "--oneline", `${base}..HEAD`]).stdout.trim();
+ const committed = exec("git", ["-C", wt, "diff", "--name-only", `${base}..HEAD`]).stdout;
+ const changedFiles = [
+ ...new Set([
+ ...nonEmpty(committed).map((l) => l.trim()),
+ ...nonEmpty(working).map(statusPath),
+ ]),
];
+ return { dirty: Boolean(working.trim() || ahead), changedFiles };
+}
+
+// Task branches under refs/heads/<short>/ that still have commits NOT merged into
+// `sessionRef`. The single source of truth for the promotion-safety check
+// (block-promote-unmerged.mjs); the chat-orchestrator's STATE B reconcile Bash
+// mirrors it and must stay aligned. Fails CLOSED: a failed/unparseable rev-list
+// count is reported as unmerged (count: null) rather than silently treated as
+// merged. `exclude` drops branches that legitimately never merge into the session
+// branch (e.g. <short>/simple, which promotes straight to main).
+export function getUnmergedTaskBranches(short, sessionRef, exclude = []) {
+ const branches = git([
+ "for-each-ref",
+ "--format=%(refname:short)",
+ `refs/heads/${short}`,
+ ])
+ .stdout.split("\n")
+ .map((s) => s.trim())
+ .filter(Boolean)
+ .filter((b) => !exclude.includes(b));
+
+ const unmerged = [];
+ for (const br of branches) {
+ const r = git(["rev-list", "--count", `${sessionRef}..${br}`]);
+ const n = Number(r.stdout.trim());
+ if (r.status !== 0 || !Number.isFinite(n)) {
+ unmerged.push({ branch: br, count: null }); // fail closed
+ } else if (n > 0) {
+ unmerged.push({ branch: br, count: n });
+ }
+ }
+ return unmerged;
}
diff --git a/.claude/hooks/lib/io.mjs b/.claude/hooks/lib/io.mjs
index 060949e5..c50debca 100644
--- a/.claude/hooks/lib/io.mjs
+++ b/.claude/hooks/lib/io.mjs
@@ -1,10 +1,5 @@
-// 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) : "";
-}
-
+// Emit a PreToolUse "block" decision on stdout — the channel Claude Code reads to
+// deny a tool call while surfacing `reason` to the agent.
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
index bacd4768..7503ea88 100644
--- a/.claude/hooks/lib/paths.mjs
+++ b/.claude/hooks/lib/paths.mjs
@@ -14,7 +14,6 @@ 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) {
diff --git a/.claude/hooks/lib/teams.mjs b/.claude/hooks/lib/teams.mjs
index 31363aed..e5443c77 100644
--- a/.claude/hooks/lib/teams.mjs
+++ b/.claude/hooks/lib/teams.mjs
@@ -5,7 +5,6 @@ export const getFirstTaskId = (text) => (String(text ?? "").match(/TASK-[0-9]+/)
// Agent-name role predicates. 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 || "");
diff --git a/.claude/hooks/lib/validation.mjs b/.claude/hooks/lib/validation.mjs
index 05668de1..f1e1bb76 100644
--- a/.claude/hooks/lib/validation.mjs
+++ b/.claude/hooks/lib/validation.mjs
@@ -1,7 +1,7 @@
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 { getBaseBranch, getWorktreeChangeSummary, getWorktreePaths } from "./git.mjs";
import { bash, exec } from "./process.mjs";
// `only` narrows to a single worktree when the caller already knows it
@@ -16,7 +16,7 @@ export function getActiveWorktrees(ctx, only = "") {
// Pure query — never exits. An empty list with a non-empty skipReason means
// there is nothing to validate.
-function getWorktreesToValidate(ctx, { skipAdrOnly = false, only = "" } = {}) {
+function getWorktreesToValidate(ctx, { skipAdrOnly = false, only = "", base = "" } = {}) {
if (!existsSync(ctx.repo)) {
return { worktrees: [], skipReason: "cd_failed" };
}
@@ -24,14 +24,20 @@ function getWorktreesToValidate(ctx, { skipAdrOnly = false, only = "" } = {}) {
if (active.length === 0) {
return { worktrees: [], skipReason: "no_active_worktree" };
}
- const base = getBaseBranch();
+ // Compare against the branch the worktree forked from (the session branch,
+ // passed by validate-on-stop) so the change set is the ticket's OWN work, not
+ // everything since the repo's checked-out base branch — which would over- or
+ // under-report a worktree's delta whenever the base branch has diverged from
+ // the session branch. Falls back to the repo base branch when no override.
+ const effectiveBase = base || getBaseBranch();
const isAdrOnly = (files) => files.length > 0 && files.every((f) => f.startsWith("adr/"));
const worktrees = active.filter((wt) => {
- if (!isWorktreeDirty(wt, base)) {
+ const { dirty, changedFiles } = getWorktreeChangeSummary(wt, effectiveBase);
+ if (!dirty) {
ctx.log(`SKIP wt=${wt} (no changes)`);
return false;
}
- if (skipAdrOnly && isAdrOnly(getWorktreeChangedFiles(wt, base))) {
+ if (skipAdrOnly && isAdrOnly(changedFiles)) {
ctx.log(`SKIP wt=${wt} (adr-only)`);
return false;
}
@@ -78,7 +84,7 @@ function runVitest(wt, configFile, projects = []) {
// 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 = "" } = {}) {
+export function runValidationSteps(ctx, { worktree = "", base = "" } = {}) {
if (process.env.VALIDATE_DRY_RUN === "1") {
ctx.log("DRY_RUN=1, skipping validation");
return { ok: true, skipReason: "dry_run" };
@@ -91,6 +97,7 @@ export function runValidationSteps(ctx, { worktree = "" } = {}) {
const { worktrees, skipReason } = getWorktreesToValidate(ctx, {
skipAdrOnly: true,
only: worktree,
+ base,
});
if (skipReason) return { ok: true, skipReason };
diff --git a/.claude/hooks/record-review-verdict.mjs b/.claude/hooks/record-review-verdict.mjs
index 61acdeb5..f5322563 100755
--- a/.claude/hooks/record-review-verdict.mjs
+++ b/.claude/hooks/record-review-verdict.mjs
@@ -90,7 +90,13 @@ const lastAssistantText = () => {
lastText = content;
}
if (!role) {
- const m = line.match(/ROLE:\s*(quality-reviewer|test-validator)/);
+ // Anchor to a dispatch-line boundary — start of the JSONL record, an
+ // escaped newline (\n inside the JSON string), or the prompt field's
+ // opening quote — so an inline prose mention ("...the ROLE: test-validator
+ // agent...") cannot mis-assign the role.
+ const m = line.match(
+ /(?:^|\\n|")ROLE:\s*(quality-reviewer|test-validator)/,
+ );
if (m) role = m[1];
}
if (!task) {
@@ -107,17 +113,34 @@ const lastAssistantText = () => {
return lastText;
};
-// Verdict = the LAST line that opens with the contract keyword. Not simply the
-// final non-empty line: a `REJECTED:` verdict is followed by a bulleted feedback
-// list (one bullet per issue, per agent-output-format.md), so the marker line is
-// not the last line. Scanning for the last marker handles both the bare
-// `APPROVED` and the multi-line `REJECTED:\n- ...` shapes, and ignores any
-// keyword that appears only in the informational body above the verdict.
+// Verdict = the last CLEAN contract marker, read bottom-up. The contract puts the
+// verdict on the final line: a bare `APPROVED`, or `REJECTED:` followed by a
+// bulleted feedback list (so the REJECTED marker is NOT the last line). We scan
+// upward from the bottom and take the first clean marker, skipping feedback
+// bullets and trailing prose. Two deliberate asymmetries stop a chatty trailing
+// line from FLIPPING a real verdict:
+// - APPROVED matches only a standalone `APPROVED` (optionally trailing
+// punctuation) — not "APPROVED parts: ..." prose.
+// - REJECTED requires the contract colon `REJECTED:` — so a trailing sentence
+// like "REJECTED concerns are resolved" after a real APPROVED is ignored.
+// A line that is neither a clean marker nor a feedback bullet is skipped (keep
+// scanning up); if none is found the verdict is UNKNOWN and the flag is untouched.
const src = lastAssistantText();
+const isApproved = (l) => l.replace(/[.!\s]+$/, "") === "APPROVED";
+const isRejected = (l) => /^REJECTED:/.test(l);
let verdict = "";
-for (const line of src.split("\n").map((s) => s.trim())) {
- if (/^APPROVED\b/.test(line)) verdict = "APPROVED";
- else if (/^REJECTED\b/.test(line)) verdict = "REJECTED";
+const verdictLines = src.split("\n").map((s) => s.trim());
+for (let i = verdictLines.length - 1; i >= 0; i--) {
+ const line = verdictLines[i];
+ if (!line) continue;
+ if (isRejected(line)) {
+ verdict = "REJECTED";
+ break;
+ }
+ if (isApproved(line)) {
+ verdict = "APPROVED";
+ break;
+ }
}
ctx.log(
diff --git a/.claude/hooks/setup-worktree.mjs b/.claude/hooks/setup-worktree.mjs
index d882151e..3f15998f 100755
--- a/.claude/hooks/setup-worktree.mjs
+++ b/.claude/hooks/setup-worktree.mjs
@@ -29,8 +29,8 @@ import { dirname, join } from "node:path";
import { createHookContext } from "./lib/context.mjs";
import { parseDispatch } from "./lib/dispatch-parse.mjs";
import { getBaseBranch, getWorktreePaths, git } from "./lib/git.mjs";
-import { getFirstTaskId } from "./lib/teams.mjs";
import { REVIEW_ROLES, reviewFlag } from "./lib/reviews.mjs";
+import { getFirstTaskId } from "./lib/teams.mjs";
import {
sessionBaseBranch,
sessionBranch,
@@ -41,6 +41,13 @@ import {
taskWorktreePath,
} from "./lib/topology.mjs";
+// Advisory-lock tuning (see the acquire loop below). LOCK_ACQUIRE_TIMEOUT_MS must
+// stay comfortably under this hook's PreToolUse timeout in settings.json so a
+// waiter gives up and proceeds best-effort rather than being killed mid-run.
+const LOCK_ACQUIRE_TIMEOUT_MS = 20_000;
+const LOCK_STALE_MS = 60_000;
+const LOCK_SPIN_MS = 100;
+
const input = JSON.parse(readFileSync(0, "utf8"));
const ctx = createHookContext(input, "setup-worktree");
const d = parseDispatch(input);
@@ -62,10 +69,22 @@ if (taskId) {
} else if (d.subagentType === "simple-developer") {
worktreePath = simpleWorktreePath(ctx);
branchName = simpleBranch(ctx);
+} else if (d.role === "promotion-conflict-resolver") {
+ // The sanctioned $REPO-on-main exception (see enforce-dev-dispatch /
+ // worktree-scope): it works directly in the repo under the promote lock and
+ // owns no task worktree, so there is nothing to create here.
+ ctx.accept(
+ "promotion-conflict-resolver — operates in $REPO on main, no worktree",
+ );
} else {
- // developer without a resolvable task id — enforce-dev-dispatch blocks the
- // missing-WORKTREE_PATH case separately; nothing safe to create here.
- ctx.accept("developer dispatch with no task id — skipped");
+ // A developer that passed enforce-dev-dispatch (so it carries WORKTREE_PATH)
+ // but whose TASK id can't be resolved from TASK_ID or the dispatch name. We
+ // can't derive the canonical worktree path; accepting would let the developer
+ // cd into a directory that was never created. Fail closed instead.
+ ctx.fail(
+ "developer dispatch carries WORKTREE_PATH but no resolvable TASK-XXX id (expected a 'TASK_ID: TASK-XXX' line or a 'developer-TASK-XXX' name). Use the STATE B dispatch template with a real ticket id.",
+ { log: "BLOCK unresolvable task id" },
+ );
}
mkdirSync(ctx.sessionDir, { recursive: true });
@@ -79,7 +98,7 @@ const lockDir = join(ctx.sessionDir, ".setup-worktree.lock");
const sleepSync = (ms) =>
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
let locked = false;
-const deadline = Date.now() + 20000;
+const deadline = Date.now() + LOCK_ACQUIRE_TIMEOUT_MS;
while (Date.now() < deadline) {
try {
mkdirSync(lockDir);
@@ -88,14 +107,14 @@ while (Date.now() < deadline) {
} catch (e) {
if (e.code !== "EEXIST") break; // can't lock — proceed best-effort
try {
- if (Date.now() - statSync(lockDir).mtimeMs > 60000) {
+ if (Date.now() - statSync(lockDir).mtimeMs > LOCK_STALE_MS) {
rmSync(lockDir, { recursive: true, force: true });
continue;
}
} catch {
continue; // lock vanished — retry immediately
}
- sleepSync(100);
+ sleepSync(LOCK_SPIN_MS);
}
}
// Release the advisory lock. Idempotent (guarded by `locked`) so it is safe to
diff --git a/.claude/hooks/test/block-merger-without-review.test.mjs b/.claude/hooks/test/block-merger-without-review.test.mjs
new file mode 100644
index 00000000..837023b4
--- /dev/null
+++ b/.claude/hooks/test/block-merger-without-review.test.mjs
@@ -0,0 +1,93 @@
+// Tests for block-merger-without-review.mjs — the PreToolUse(Agent) gate that
+// blocks a per-ticket merger until BOTH reviewers recorded APPROVED (flags under
+// <sessionDir>/reviews/<TASK>-<role>, written by record-review-verdict.mjs). The
+// gate exits 2 to block and 0 to allow. Skipped for promotion-only / SIMPLE /
+// ROLLBACK dispatches and when the ticket id can't be parsed (fail open).
+
+import { mkdtempSync, mkdirSync, writeFileSync, 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";
+import { sanitizePath } from "../lib/paths.mjs";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const HOOK = join(HERE, "..", "block-merger-without-review.mjs");
+const SS = "ab12cd34";
+const SESSION_ID = `${SS}-1111-2222-3333-444455556666`;
+
+let TMP;
+let APP_DIR;
+let env;
+let reviewsDir;
+
+const run = (prompt, subagentType = "merger") =>
+ spawnSync("node", [HOOK], {
+ input: JSON.stringify({
+ session_id: SESSION_ID,
+ tool_input: { subagent_type: subagentType, prompt },
+ }),
+ env,
+ encoding: "utf8",
+ }).status;
+
+const approve = (task, role) =>
+ writeFileSync(join(reviewsDir, `${task}-${role}`), "");
+
+beforeAll(() => {
+ TMP = mkdtempSync(join(tmpdir(), "block-merger-test-"));
+ APP_DIR = join(TMP, "app");
+ const CRM_TMP_ROOT = join(TMP, "scratch");
+ reviewsDir = join(CRM_TMP_ROOT, sanitizePath(APP_DIR), SESSION_ID, "reviews");
+ mkdirSync(reviewsDir, { recursive: true });
+ env = { ...process.env, APP_DIR, CRM_TMP_ROOT };
+});
+
+afterAll(() => rmSync(TMP, { recursive: true, force: true }));
+
+describe("block-merger-without-review", () => {
+ test("blocks a per-ticket merger when no reviewer flags exist", () => {
+ expect(
+ run(`ROLE: merger\nTASK_ID: TASK-001\nBRANCH_NAME: ${SS}/TASK-001`),
+ ).toBe(2);
+ });
+
+ test("blocks when only one reviewer has approved", () => {
+ approve("TASK-002", "quality-reviewer");
+ expect(
+ run(`ROLE: merger\nTASK_ID: TASK-002\nBRANCH_NAME: ${SS}/TASK-002`),
+ ).toBe(2);
+ });
+
+ test("allows the merger once BOTH reviewers approved", () => {
+ approve("TASK-003", "quality-reviewer");
+ approve("TASK-003", "test-validator");
+ expect(
+ run(`ROLE: merger\nTASK_ID: TASK-003\nBRANCH_NAME: ${SS}/TASK-003`),
+ ).toBe(0);
+ });
+
+ test("ignores the promotion-only merger (MODE: promote)", () => {
+ expect(run(`ROLE: merger\nMODE: promote\nSESSION_SHORT_ID: ${SS}`)).toBe(0);
+ });
+
+ test("ignores the SIMPLE merger (no per-ticket review)", () => {
+ expect(
+ run(`ROLE: merger\nTASK_ID: SIMPLE\nBRANCH_NAME: ${SS}/simple`),
+ ).toBe(0);
+ });
+
+ test("ignores a non-merger dispatch", () => {
+ expect(
+ run(
+ `ROLE: developer\nTASK_ID: TASK-001\nWORKTREE_PATH: /wt`,
+ "developer",
+ ),
+ ).toBe(0);
+ });
+
+ test("fails open when the ticket id can't be parsed (no TASK_ID line)", () => {
+ expect(run(`ROLE: merger\nBRANCH_NAME: ${SS}/whatever`)).toBe(0);
+ });
+});
diff --git a/.claude/hooks/test/block-promote-unmerged.test.mjs b/.claude/hooks/test/block-promote-unmerged.test.mjs
index 6d4326cf..a19bcbd8 100644
--- a/.claude/hooks/test/block-promote-unmerged.test.mjs
+++ b/.claude/hooks/test/block-promote-unmerged.test.mjs
@@ -2,12 +2,12 @@
// "claude" Node project). Builds a throwaway repo with a session branch + one
// merged and one unmerged task branch, then exercises the PreToolUse(Agent) hook.
-import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } 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 { afterAll, beforeAll, describe, expect, test } from "vitest";
const HERE = dirname(fileURLToPath(import.meta.url));
const HOOK = join(HERE, "..", "block-promote-unmerged.mjs");
@@ -101,4 +101,16 @@ describe("block-promote-unmerged", () => {
g("checkout", "-q", "main");
expect(run(PROMOTE)).toBe(0);
});
+
+ test("ignores the <short>/simple branch even when ahead of the session branch", () => {
+ // <short>/simple promotes straight to main (never into the session branch),
+ // so its commits are legitimately not on session/<short> and must NOT block a
+ // COMPLEX promotion.
+ g("checkout", "-q", "-b", `${SS}/simple`, "main");
+ writeFileSync(join(APP_DIR, "simple.txt"), "s\n");
+ g("add", ".");
+ g("commit", "-qm", "feat: a simple change");
+ g("checkout", "-q", "main");
+ expect(run(PROMOTE)).toBe(0);
+ });
});
diff --git a/.claude/hooks/test/enforce-dev-dispatch.test.mjs b/.claude/hooks/test/enforce-dev-dispatch.test.mjs
index 9df13e1c..fb284233 100644
--- a/.claude/hooks/test/enforce-dev-dispatch.test.mjs
+++ b/.claude/hooks/test/enforce-dev-dispatch.test.mjs
@@ -63,6 +63,17 @@ describe("enforce-dev-dispatch", () => {
).toBe(2);
});
+ test("blocks a developer dispatch using run_in_background:true", () => {
+ expect(
+ run({
+ subagent_type: "developer",
+ run_in_background: true,
+ prompt:
+ "ROLE: developer\nTASK_ID: TASK-001\nWORKTREE_PATH: /wt/x/TASK-001\nBRANCH_NAME: x/TASK-001",
+ }),
+ ).toBe(2);
+ });
+
test("allows the promotion-conflict-resolver (no WORKTREE_PATH by design)", () => {
expect(
run({
diff --git a/.claude/hooks/test/record-review-verdict.test.mjs b/.claude/hooks/test/record-review-verdict.test.mjs
index 0d84606d..e874483c 100644
--- a/.claude/hooks/test/record-review-verdict.test.mjs
+++ b/.claude/hooks/test/record-review-verdict.test.mjs
@@ -82,6 +82,27 @@ describe("record-review-verdict", () => {
expect(existsSync(flag("TASK-009-quality-reviewer"))).toBe(false);
});
+ test("trailing prose starting with REJECTED does not flip a real APPROVED", () => {
+ // A chatty reviewer that approves but adds a clarifying sentence which happens
+ // to start with the keyword must NOT be recorded as REJECTED. The contract
+ // REJECTED form requires a colon (`REJECTED:`), so this trailing prose is
+ // ignored and the standalone APPROVED above wins.
+ run({
+ agent_type: "quality-reviewer-TASK-010",
+ last_assistant_message:
+ "APPROVED\nREJECTED concerns from the first pass are now resolved.",
+ });
+ expect(existsSync(flag("TASK-010-quality-reviewer"))).toBe(true);
+ });
+
+ test("standalone APPROVED with a trailing note still approves", () => {
+ run({
+ agent_type: "test-validator-TASK-010",
+ last_assistant_message: "APPROVED\nNice work — all e2e specs present.",
+ });
+ expect(existsSync(flag("TASK-010-test-validator"))).toBe(true);
+ });
+
test("unknown verdict leaves state untouched (no flag written)", () => {
run({
agent_type: "quality-reviewer-TASK-008",
diff --git a/.claude/hooks/test/setup-worktree.test.mjs b/.claude/hooks/test/setup-worktree.test.mjs
index f583a3d7..e0b60a72 100755
--- a/.claude/hooks/test/setup-worktree.test.mjs
+++ b/.claude/hooks/test/setup-worktree.test.mjs
@@ -4,19 +4,19 @@
// throwaway git repo (APP_DIR) + CRM_TMP_ROOT. Tests are ordered and stateful —
// each observes the state produced by the previous step.
+import { spawnSync } from "node:child_process";
import {
- mkdtempSync,
+ existsSync,
mkdirSync,
- writeFileSync,
+ mkdtempSync,
readFileSync,
- existsSync,
rmSync,
+ writeFileSync,
} 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 { afterAll, beforeAll, describe, expect, test } from "vitest";
import { sanitizePath } from "../lib/paths.mjs";
const HERE = dirname(fileURLToPath(import.meta.url));
@@ -169,6 +169,39 @@ describe("setup-worktree session-branch topology (PreToolUse/Agent)", () => {
expect(existsSync(join(WB, "simple"))).toBe(true);
});
+ test("developer with WORKTREE_PATH but unresolvable task id is blocked (exit 2)", () => {
+ const r = spawnSync("node", [HOOK], {
+ input: JSON.stringify({
+ session_id: SESSION_ID,
+ tool_input: {
+ subagent_type: "developer",
+ name: "developer",
+ prompt:
+ "ROLE: developer\nWORKTREE_PATH: /wt/nowhere\nBRANCH_NAME: x/y",
+ },
+ }),
+ env,
+ encoding: "utf8",
+ });
+ expect(r.status).toBe(2);
+ });
+
+ test("promotion-conflict-resolver is accepted with no worktree (exit 0)", () => {
+ const r = spawnSync("node", [HOOK], {
+ input: JSON.stringify({
+ session_id: SESSION_ID,
+ tool_input: {
+ subagent_type: "developer",
+ name: "developer",
+ prompt: `ROLE: promotion-conflict-resolver (gated $CLAUDE_PROJECT_DIR exception)\nSESSION_SHORT_ID: ${SS}`,
+ },
+ }),
+ env,
+ encoding: "utf8",
+ });
+ expect(r.status).toBe(0);
+ });
+
test("no SESSION-BRANCH FAILED logged", () => {
let logTxt = "";
try {
diff --git a/.claude/hooks/test/turn-complete.test.mjs b/.claude/hooks/test/turn-complete.test.mjs
new file mode 100644
index 00000000..5147afde
--- /dev/null
+++ b/.claude/hooks/test/turn-complete.test.mjs
@@ -0,0 +1,36 @@
+// Tests for turn-complete.mjs — the Stop hook that drops a per-session sentinel
+// (/tmp/pty-sentinels/pty-turn-done-<session_id>) the chat-service PtySession
+// watcher polls. Must always exit 0 (a Stop hook never blocks) and never throw on
+// a missing/malformed payload.
+
+import { existsSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { spawnSync } from "node:child_process";
+import { describe, test, expect, afterAll } from "vitest";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const HOOK = join(HERE, "..", "turn-complete.mjs");
+// A unique id so the test never collides with a real session's sentinel.
+const SID = "turn-complete-test-7e3a9f21";
+const sentinel = join("/tmp/pty-sentinels", `pty-turn-done-${SID}`);
+
+const run = (input) => spawnSync("node", [HOOK], { input, encoding: "utf8" });
+
+afterAll(() => rmSync(sentinel, { force: true }));
+
+describe("turn-complete", () => {
+ test("creates the per-session sentinel and exits 0", () => {
+ const r = run(JSON.stringify({ session_id: SID }));
+ expect(r.status).toBe(0);
+ expect(existsSync(sentinel)).toBe(true);
+ });
+
+ test("no session id → no throw, exits 0", () => {
+ expect(run(JSON.stringify({})).status).toBe(0);
+ });
+
+ test("malformed payload → no throw, exits 0", () => {
+ expect(run("not json").status).toBe(0);
+ });
+});
diff --git a/.claude/hooks/validate-on-stop.mjs b/.claude/hooks/validate-on-stop.mjs
index 44b4b009..d1ba4784 100755
--- a/.claude/hooks/validate-on-stop.mjs
+++ b/.claude/hooks/validate-on-stop.mjs
@@ -3,8 +3,13 @@
import { readFileSync } from "node:fs";
import { createHookContext } from "./lib/context.mjs";
+import { git } from "./lib/git.mjs";
import { getFirstTaskId } from "./lib/teams.mjs";
-import { simpleWorktreePath, taskWorktreePath } from "./lib/topology.mjs";
+import {
+ sessionBranch,
+ simpleWorktreePath,
+ taskWorktreePath,
+} from "./lib/topology.mjs";
import { runValidationSteps } from "./lib/validation.mjs";
const ctx = createHookContext(readFileSync(0, "utf8"), "validate");
@@ -22,11 +27,22 @@ const ownWorktree = taskId
? simpleWorktreePath(ctx)
: "";
+// Diff each worktree against the branch it forked from (session/<short>), not the
+// repo's checked-out base branch, so validation sees the ticket's OWN change set.
+// Empty base → validation.mjs falls back to the repo base branch (e.g. before the
+// session branch exists).
+const sessionRef = sessionBranch(ctx);
+const base =
+ git(["show-ref", "--verify", "--quiet", `refs/heads/${sessionRef}`])
+ .status === 0
+ ? sessionRef
+ : "";
+
ctx.log(
- `START REPO=${ctx.repo} MODE=${process.env.MODE || ""} wt=${ownWorktree || "all"}`,
+ `START REPO=${ctx.repo} MODE=${process.env.MODE || ""} wt=${ownWorktree || "all"} base=${base || "repo-default"}`,
);
-const result = runValidationSteps(ctx, { worktree: ownWorktree });
+const result = runValidationSteps(ctx, { worktree: ownWorktree, base });
if (!result.ok) {
ctx.fail(
diff --git a/.claude/settings.json b/.claude/settings.json
index 199e9016..b8dabcf3 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -75,7 +75,7 @@
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/setup-worktree.mjs",
- "timeout": 60,
+ "timeout": 180,
"statusMessage": "Setting up worktree..."
}
]