Skip to content

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

fix(harness): block wave mergers from promoting to the base branch

Jerome5a2246ec8e6b
diff --git a/.claude/agents/merger.md b/.claude/agents/merger.md
index d40f6d3a..b4cd04c4 100644
--- a/.claude/agents/merger.md
+++ b/.claude/agents/merger.md
@@ -60,10 +60,10 @@ The orchestrator parses this line by regex. Any other format is treated as `FAIL
### Mode selection (first action — no tool call needed)
- Spawn prompt `ROLE:` mentions **ROLLBACK mode** (rollback-conflict path) → run **ROLLBACK mode** (skip Stage A, run ROLLBACK PROMOTION on `BRANCH_NAME`). Contract `TASK_ID` is the literal `ROLLBACK`.
-- Spawn prompt contains **`STAGE: a-only`** → run **Stage A only** on `BRANCH_NAME` (merge into `session/<SESSION_SHORT_ID>`) and stop after the Stage A contract. Never run Stage B / promotion, whatever the `ROLE:` line says. This takes precedence over the SIMPLE / MIGRATION coupling below. Contract `TASK_ID` stays the literal from the prompt (`SIMPLE` / `MIGRATION`).
+- Spawn prompt contains **`STAGE: a-only`** → run **Stage A only** on `BRANCH_NAME` (merge into `session/<SESSION_SHORT_ID>`) and stop after the Stage A contract. Never run Stage B / promotion, whatever the `ROLE:` line says. This takes precedence over the SIMPLE / MIGRATION coupling below. Contract `TASK_ID` stays the literal from the prompt (`TASK-XXX` for a wave merge, or `SIMPLE` / `MIGRATION`).
- Spawn prompt `ROLE:` mentions **SIMPLE mode** (SIMPLE flow) or **MIGRATION mode** (deploy-time migration round) → run **Stage A**, then immediately run **PROMOTION — Stage B**, then emit the contract. Contract `TASK_ID` is the literal `SIMPLE` or `MIGRATION` respectively. (Both are the same single-shot mechanic on the `<short>/simple` branch.)
- Spawn prompt contains `MODE: promote` → run **PROMOTION — Stage B** only. Contract `TASK_ID` is `PROMOTE`.
-- Otherwise (`TASK_ID` is `TASK-XXX`) → run **Stage A** only, then emit the contract. Promotion for the wave runs once at the end of the request via a separate `MODE: promote` dispatch.
+- Otherwise (`TASK_ID` is `TASK-XXX`) → run **Stage A ONLY**, then emit the contract, and **STOP**. A per-ticket wave merger MUST NEVER run Stage B / promotion: no `git checkout <base>`, no `git merge session/<SESSION_SHORT_ID>` into the base branch. Promoting partial work to the base branch mid-feature corrupts it (this happened once: a wave-1 merger promoted TASK-001 alone onto the base branch). Promotion for the wave runs exactly once, at the end of the request, via a separate `MODE: promote` dispatch. The orchestrator passes `STAGE: a-only` on the wave dispatch (so the rule above applies), and `block-wave-merger-promote.mjs` blocks a Stage-B command from a Stage-A-only merger at runtime (fail-closed); this rule is not honour-system.
---
diff --git a/.claude/agents/orchestrator.md b/.claude/agents/orchestrator.md
index cd3a35d6..d94235ab 100644
--- a/.claude/agents/orchestrator.md
+++ b/.claude/agents/orchestrator.md
@@ -33,7 +33,7 @@ When your dispatch prompt carries `PERSONA: technical` (the `#technical-harness`
1. **Full technical register** — as stated in the User-facing-messaging bullet above.
2. **Raw reporting.** Your final report is not a summary; it is the mechanical truth. Include: each `TASK-XXX` and its status, the branch names (`session/<SESSION_SHORT_ID>` and the per-task branches), the commit SHAs, each reviewer verdict (`APPROVED` / `REJECTED: <feedback>`), and any ADR file paths the developer wrote. Do not soften or omit failures.
3. **Stop at the session branch — never auto-promote.** The session branch is your terminal point. Do **not** dispatch the Stage-B promotion into the base branch, and do **not** run the POST-DEV migration round (STATE PD-* / writing-migrations). Merge every ticket into `session/<SESSION_SHORT_ID>` (Stage A only) and stop. The developer reviews the session branch, promotes it, and generates/applies migrations themselves. Still run the `pending-deploys.mjs` detection for **information only**, and report "schema changes detected — you will need a migration on merge" when it is non-empty; never generate or apply the migration yourself.
-4. **Live progress log.** Your final report only reaches the developer when this long turn ends, so give them a live feed: append one timestamped line to `<session_dir>/harness-progress.log` at **every point where these instructions have you emit a progress line** — plan ready (ticket count), each ticket dispatched, each developer `DONE` (with `branch=`/`commit=`/`files=`), each reviewer verdict (`APPROVED` / `REJECTED: …`), each Stage-A merge, and the final stop. Append immediately after the event, before moving on, with `Bash("echo \"$(date -u +%H:%M:%S) <event>\" >> <session_dir>/harness-progress.log")` (substitute the real `<session_dir>` from your context). Overwrite nothing — append only. The developer runs `tail -f` on this file to watch the harness code in real time.
+4. **Live progress log.** Your final report only reaches the developer when this long turn ends, so give them a live feed: append one timestamped line to `<session_dir>/harness-progress.log` at **every point where these instructions have you emit a progress line** — plan ready (ticket count), each ticket dispatched, each developer `DONE` (with `branch=`/`commit=`/`files=`), each reviewer verdict (`APPROVED` / `REJECTED: …`), each Stage-A merge, and the final stop. Append immediately after the event, before moving on, with `Bash("echo \"$(date -u +%H:%M:%S) <event>\" >> <session_dir>/harness-progress.log")` (substitute the real `<session_dir>` from your context). Overwrite nothing, append only. The developer runs `tail -f` on this file (or a `Monitor` on it) to watch the harness in real time. The `validate-on-stop` hook additionally auto-appends each validation step as it runs (`[validate:TASK-XXX] typecheck…`, `… checks passed` / `… FAILED`), so the otherwise-silent minutes while a developer's SubagentStop runs typecheck / lint / vitest / e2e show up in the same feed, so you do NOT log those yourself.
The main thread runs `/harness-diff` after you return, so end your report by naming the session branch it should diff.
@@ -359,7 +359,7 @@ The planner runs in the **foreground**: its result returns this same turn.
(`migration` and `plan` have the same stops; `migration` is a named alias for callers who want the migration stop stated explicitly. Only `none` runs the plan gate through.)
-**Plan gate.** Pause here UNLESS `GATE` is exactly `none`. To pause: emit the plan (one line per ticket: id, title, `files_to_modify`, `dependencies`, acceptance) plus an approval question, and **END THE TURN** so the user can review and edit the tickets on disk (`${TICKETS_DIR}/TASK-*.json`). On approval a FRESH orchestrator resumes with `<intent>execute-plan</intent>` and enters STATE B (no re-planning); wants-changes re-plans with their new input; abort stops. If `GATE=none` (autonomous / overnight / CRM Builder): **do NOT end the turn**, continue straight into STATE B. You must NEVER silently skip the plan gate for `migration`/`plan`/`waves`. Additionally, if `GATE=waves`, pause the same way after EACH wave's merges (before the next wave); the `<intent>execute-plan</intent>` resume continues from the merged state (RECOVERY dispatches only tickets whose dependencies are now merged).
+**Plan gate.** Pause here UNLESS `GATE` is exactly `none`. To pause: emit an approval question and **END THE TURN** so the user can review and edit the tickets on disk (`${TICKETS_DIR}/TASK-*.json`). What you emit alongside the question depends on persona: under **`PERSONA: technical`** the coordinator (main thread) re-reads the ticket JSONs and renders each ticket's fields inline for the user, so keep YOUR return **terse**: a one-line summary only (ticket count, wave shape, `gate=<level>`, "awaiting review at the plan gate"); do NOT dump one line per ticket (that would duplicate the plan the coordinator already renders). Otherwise (web-chat / non-technical persona, where your message IS the user-facing surface) emit the readable plan: one line per ticket (id, title, `files_to_modify`, `dependencies`, acceptance). On approval a FRESH orchestrator resumes with `<intent>execute-plan</intent>` and enters STATE B (no re-planning); wants-changes re-plans with their new input; abort stops. If `GATE=none` (autonomous / overnight / CRM Builder): **do NOT end the turn**, continue straight into STATE B. You must NEVER silently skip the plan gate for `migration`/`plan`/`waves`. Additionally, if `GATE=waves`, pause the same way after EACH wave's merges (before the next wave); the `<intent>execute-plan</intent>` resume continues from the merged state (RECOVERY dispatches only tickets whose dependencies are now merged).
---
@@ -455,9 +455,11 @@ Per-ticket mergers all merge into the shared `session/<SESSION_SHORT_ID>` branch
```
Agent({ subagent_type: "merger",
description: "Merge T",
- prompt: "ROLE: merger\nTASK_ID: T\nBRANCH_NAME: <SESSION_SHORT_ID>/T\nWORKTREE_PATH: <WORKTREE_BASE>/T\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nTICKETS_DIR: <TICKETS_DIR>" })
+ prompt: "ROLE: merger\nTASK_ID: T\nSTAGE: a-only\nBRANCH_NAME: <SESSION_SHORT_ID>/T\nWORKTREE_PATH: <WORKTREE_BASE>/T\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nTICKETS_DIR: <TICKETS_DIR>" })
```
+The `STAGE: a-only` line is mandatory on every wave merger: it merges the task branch into `session/<SESSION_SHORT_ID>` and STOPS. A wave merger must NEVER promote (no Stage B): promoting partial work to the base branch mid-feature corrupts it. Promotion happens once, after the last wave, via the separate `MODE: promote` dispatch below. Runtime-enforced: `record-merger-stage.mjs` records the dispatch's authorization and `block-wave-merger-promote.mjs` blocks a Stage-B `git merge session/<SESSION_SHORT_ID>` from a Stage-A-only merger (fail-closed).
+
Per result: `DONE: T commit=…` → `stage = DONE`; `FAILED:`/malformed → `stage = FAILED`. (The `block-merger-without-review` hook gates each merger dispatch on the recorded quality-reviewer `APPROVED` verdict.)
**If the merger dispatch is blocked for `no APPROVED verdict yet`:** the quality-reviewer writes its own verdict flag on APPROVED (it's the source of truth — see quality-reviewer.md), so a missing flag means **the reviewer did NOT approve**, regardless of any APPROVED text you think you saw. Do NOT re-dispatch the reviewer to "create the record", and **never create, touch, or delete files under `<session_dir>/reviews` or `<session_dir>/breaker` yourself** — those files ARE the guard, and `bash-guard` blocks you from mutating them. Instead: re-read the reviewer's actual output/contract line for that ticket. If it truly was `REJECTED`, follow the Stage 2 retry path; if the reviewer genuinely emitted `APPROVED` but its self-write failed, re-run the SAME reviewer dispatch (a fresh review, not a flag hack) so it records the flag on its own. Forging the flag bypasses review — that is always a bug.
diff --git a/.claude/hooks/block-wave-merger-promote.mjs b/.claude/hooks/block-wave-merger-promote.mjs
new file mode 100755
index 00000000..b584319c
--- /dev/null
+++ b/.claude/hooks/block-wave-merger-promote.mjs
@@ -0,0 +1,68 @@
+#!/usr/bin/env node
+// PreToolUse(Bash): a Stage-A-only merger (a per-ticket wave merge, or any
+// dispatch carrying STAGE: a-only) must NEVER run Stage B: promoting the session
+// branch into the base branch. Runtime enforcement of merger.md ("TASK-XXX ->
+// Stage A only; promotion runs once at the end via a separate MODE: promote dispatch").
+//
+// Root cause it closes (forensic, session 7ba88e76): a wave merger dispatched as
+// `TASK_ID: TASK-001` (no MODE, no STAGE) ran `git checkout -f <base>` +
+// `git merge --no-ff session/<short> -m "merge(session)"`, promoting partial wave-1
+// work onto the base branch. The merger never checks the persona, so this is
+// mode-agnostic: in a NORMAL run it would corrupt the real base branch (or main)
+// mid-flow. A technical-only guard would merely mask it, so the guard is universal.
+//
+// Authorization is recorded at dispatch by record-merger-stage.mjs into
+// <sessionDir>/merger-stage.json. Fails CLOSED: a missing/unreadable marker blocks
+// the promotion: the running merger cannot prove it is authorized.
+
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { createHookContext } from "./lib/context.mjs";
+import { isMerger } from "./lib/teams.mjs";
+import { sessionBranch } from "./lib/topology.mjs";
+
+const input = JSON.parse(readFileSync(0, "utf8"));
+const ctx = createHookContext(input, "block-wave-merger-promote");
+
+// Only the merger runs Stage B; every other agent is out of scope for this guard.
+if (![ctx.agentName, ctx.agentType].some(isMerger)) process.exit(0);
+
+const cmd = input.tool_input?.command || "";
+if (!cmd) process.exit(0);
+
+// Stage-B signature: a `git merge` that pulls in the session branch (promotion),
+// or the promotion commit message. Stage A merges a <short>/TASK-XXX branch INTO
+// the session branch and never names session/<short> as a merge argument, so it
+// does not match.
+const session = sessionBranch(ctx); // session/<short>
+const isStageBPromotion =
+ /\bgit\s+merge\b/.test(cmd) &&
+ (cmd.includes(session) || /merge\(session\)/.test(cmd));
+if (!isStageBPromotion) process.exit(0);
+
+// Read the dispatch-time authorization marker. Fail CLOSED.
+let promote = false;
+let markerSeen = false;
+try {
+ const marker = JSON.parse(
+ readFileSync(join(ctx.sessionDir, "merger-stage.json"), "utf8"),
+ );
+ markerSeen = true;
+ promote = marker.promote === true;
+} catch {
+ promote = false; // no/unreadable marker -> not authorized
+}
+
+if (promote) process.exit(0);
+
+ctx.fail(
+ "Blocked: this merger is a Stage-A-only dispatch and must NOT promote the session branch to the base branch.\n\n" +
+ `It tried to run Stage B (promotion):\n ${cmd}\n\n` +
+ (markerSeen
+ ? "Its dispatch is not authorized to promote (a per-ticket TASK-XXX wave merge, or STAGE: a-only)."
+ : "No promotion-authorization marker was found for this session (fail-closed).") +
+ "\n\nStage B runs ONLY via a dedicated `MODE: promote` merger after the LAST wave, or a SIMPLE / MIGRATION single-shot. " +
+ `A per-ticket wave merger runs Stage A ONLY: merge <short>/TASK-XXX into ${session} and stop. ` +
+ 'See merger.md ("TASK-XXX -> Stage A only") and orchestrator.md\'s promotion block.',
+ { log: `BLOCK stage-A merger tried Stage B (markerSeen=${markerSeen})` },
+);
diff --git a/.claude/hooks/lib/dispatch-parse.mjs b/.claude/hooks/lib/dispatch-parse.mjs
index ba18db52..3c1c1664 100644
--- a/.claude/hooks/lib/dispatch-parse.mjs
+++ b/.claude/hooks/lib/dispatch-parse.mjs
@@ -32,6 +32,9 @@ export function parseDispatch(input) {
worktreePath: grab(/^WORKTREE_PATH:\s*(\S+)/m),
branchName: grab(/^BRANCH_NAME:\s*(\S+)/m),
mode: grab(/^MODE:\s*(\S+)/m),
+ // STAGE: a-only marks a merger dispatch as Stage A ONLY (no Stage B / promotion),
+ // even in SIMPLE / MIGRATION mode. Read by record-merger-stage to authorize promotion.
+ stage: grab(/^STAGE:\s*(\S+)/m),
sessionShortId: grab(/^SESSION_SHORT_ID:\s*(\S+)/m),
ticketFile: grab(/^TICKET_FILE:\s*(\S+)/m),
ticketsDir: grab(/^TICKETS_DIR:\s*(\S+)/m),
diff --git a/.claude/hooks/lib/progress-log.mjs b/.claude/hooks/lib/progress-log.mjs
new file mode 100644
index 00000000..fcd82b5e
--- /dev/null
+++ b/.claude/hooks/lib/progress-log.mjs
@@ -0,0 +1,32 @@
+// Append a timestamped line to the #technical-harness progress log, but ONLY when
+// that log already exists.
+//
+// Its existence is the technical-run gate: the orchestrator creates
+// <sessionDir>/harness-progress.log under PERSONA: technical, render-status reads it,
+// and a web-chat / normal run has none. Enrichers (validate-on-stop) call this to
+// fill the otherwise-silent stretches BETWEEN the orchestrator's milestones, e.g.
+// the multi-minute validation chain a developer runs on stop, so a `tail -f`, the
+// board's "Recent activity", or a Monitor shows what is happening instead of going
+// dark. Best-effort: logging must never break a run, and it never CREATES the log
+// (creating it would leak a board into a non-technical run).
+
+import { appendFileSync, existsSync } from "node:fs";
+import { join } from "node:path";
+
+/**
+ * @param {string} sessionDir The harness session dir (ctx.sessionDir).
+ * @param {string} line Event text; a `HH:MM:SS ` UTC stamp is prepended to match
+ * the orchestrator's own lines.
+ * @returns {boolean} true if a line was written, false if the log was absent/unwritable.
+ */
+export function appendProgress(sessionDir, line) {
+ try {
+ const file = join(sessionDir, "harness-progress.log");
+ if (!existsSync(file)) return false; // not a technical run -> stay inert
+ const stamp = new Date().toISOString().slice(11, 19); // HH:MM:SS UTC
+ appendFileSync(file, `${stamp} ${line}\n`);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/.claude/hooks/lib/validation.mjs b/.claude/hooks/lib/validation.mjs
index f200b6cc..aba5daa8 100644
--- a/.claude/hooks/lib/validation.mjs
+++ b/.claude/hooks/lib/validation.mjs
@@ -4,6 +4,7 @@ import { basename, join } from "node:path";
import { getBaseBranch, getWorktreeChangeSummary, getWorktreePaths } from "./git.mjs";
import { bash, exec } from "./process.mjs";
import { loadConfig, validationSteps } from "./config.mjs";
+import { appendProgress } from "./progress-log.mjs";
// `only` narrows to a single worktree when the caller already knows it
// (validate-on-stop scoping to the stopping agent's own task worktree);
@@ -207,22 +208,34 @@ export function runValidationSteps(ctx, { worktree = "", base = "" } = {}) {
const perWorktree = steps.filter((s) => s.cwd !== "repo");
const repoLevel = steps.filter((s) => s.cwd === "repo");
+ // Enrich the #technical-harness progress log with each validation step as it runs,
+ // so the otherwise-silent multi-minute chain (typecheck, lint, vitest, e2e) shows up
+ // in a `tail -f` / the board / a Monitor. Inert (no-op) on a non-technical run: the
+ // log does not exist there, so appendProgress writes nothing and creates nothing.
+ const progress = (line) => appendProgress(ctx.sessionDir, line);
+
for (const wt of worktrees) {
+ const label = basename(wt);
for (const step of perWorktree) {
if (stepSkipped(ctx, step)) continue;
+ progress(`[validate:${label}] ${step.id}…`);
const r = runStep(ctx, step, { cwd: wt, base });
if (!r.ok) {
+ progress(`[validate:${label}] ${step.id} FAILED`);
ctx.log(`FAIL step=${step.id} wt=${wt}\n${r.output}`);
return { ok: false, step: step.id, output: `=== ${step.id} failed in ${wt} ===\n${r.output}\n` };
}
}
+ progress(`[validate:${label}] checks passed`);
ctx.log(`OK wt=${wt}`);
}
for (const step of repoLevel) {
if (stepSkipped(ctx, step)) continue;
+ progress(`[validate:repo] ${step.id}…`);
const r = runStep(ctx, step, { cwd: ctx.repo, base });
if (!r.ok) {
+ progress(`[validate:repo] ${step.id} FAILED`);
ctx.log(`FAIL step=${step.id} exit`);
return { ok: false, step: step.id, output: r.output + "\n" };
}
diff --git a/.claude/hooks/record-merger-stage.mjs b/.claude/hooks/record-merger-stage.mjs
new file mode 100755
index 00000000..ab3037fb
--- /dev/null
+++ b/.claude/hooks/record-merger-stage.mjs
@@ -0,0 +1,57 @@
+#!/usr/bin/env node
+// PreToolUse(Agent): record whether the merger being dispatched is authorized to
+// run Stage B (promotion of the session branch into the base branch). Written to
+// <sessionDir>/merger-stage.json at dispatch time; read by
+// block-wave-merger-promote.mjs when the merger runs its git commands.
+//
+// Why the bridge: a per-ticket wave merger (TASK_ID: TASK-XXX, no MODE) is a
+// Stage-A-only dispatch (merger.md "TASK-XXX -> Stage A only") and must NOT promote.
+// The dispatch itself is legitimate, so the violation can only be caught when the
+// merger runs the Stage-B git commands. A PreToolUse(Bash) hook cannot see the
+// merger's dispatch prompt, so its authorization is recorded here at dispatch.
+//
+// Race safety: wave mergers are dispatched sequentially and foreground
+// (merger.md, Stage 3), and promotion is a single dispatch after the last wave, so
+// there is never more than one merger running at a time. A single-slot marker
+// therefore always describes the currently-running merger.
+
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { createHookContext } from "./lib/context.mjs";
+import { parseDispatch } from "./lib/dispatch-parse.mjs";
+
+const input = JSON.parse(readFileSync(0, "utf8"));
+const d = parseDispatch(input);
+
+// Only a merger dispatch carries promotion authorization.
+if (d.subagentType !== "merger") process.exit(0);
+
+const ctx = createHookContext(input, "record-merger-stage");
+
+// A dispatch is Stage-A-only (may NOT promote) when it either carries STAGE: a-only
+// or is a per-ticket wave merge (TASK_ID matches TASK-<n>). Every other merger
+// dispatch (MODE: promote, or a SIMPLE / MIGRATION / ROLLBACK single-shot, none of
+// which set a TASK-<n> id) legitimately promotes.
+const stageAOnly = d.stage === "a-only" || /^TASK-\d+$/.test(d.taskId);
+const promote = !stageAOnly;
+
+try {
+ mkdirSync(ctx.sessionDir, { recursive: true });
+ writeFileSync(
+ join(ctx.sessionDir, "merger-stage.json"),
+ JSON.stringify({
+ promote,
+ taskId: d.taskId,
+ mode: d.mode,
+ stage: d.stage,
+ at: new Date().toISOString(),
+ }) + "\n",
+ );
+ ctx.log(
+ `RECORD promote=${promote} taskId=${d.taskId || "-"} mode=${d.mode || "-"} stage=${d.stage || "-"}`,
+ );
+} catch {
+ // Best-effort: the Bash guard fails CLOSED when the marker is missing/unreadable,
+ // so a failed write cannot silently allow an unauthorized promotion.
+}
+process.exit(0);
diff --git a/.claude/hooks/test/block-wave-merger-promote.test.mjs b/.claude/hooks/test/block-wave-merger-promote.test.mjs
new file mode 100644
index 00000000..f87bb700
--- /dev/null
+++ b/.claude/hooks/test/block-wave-merger-promote.test.mjs
@@ -0,0 +1,145 @@
+// Tests for block-wave-merger-promote.mjs: the PreToolUse(Bash) guard that stops a
+// Stage-A-only merger (a per-ticket wave merge, or STAGE: a-only) from running Stage B
+// (promoting session/<short> into the base branch). Authorization is recorded at
+// dispatch by record-merger-stage.mjs into <sessionDir>/merger-stage.json; the guard
+// exits 2 to block and 0 to allow, and fails CLOSED when no marker exists.
+
+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,
+ beforeEach,
+ afterAll,
+} from "vitest";
+import { sanitizePath } from "../lib/paths.mjs";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const BLOCK = join(HERE, "..", "block-wave-merger-promote.mjs");
+const RECORD = join(HERE, "..", "record-merger-stage.mjs");
+const SS = "ab12cd34";
+const SESSION_ID = `${SS}-1111-2222-3333-444455556666`;
+const STAGE_B = `cd /wt && git merge --no-ff session/${SS} -m "merge(session): ${SS}"`;
+const STAGE_A = `cd /wt && git merge --no-ff ${SS}/TASK-001 -m "merge(${SS}/TASK-001)"`;
+
+let TMP, APP_DIR, env, sessionDir, marker;
+
+const setMarker = (promote) =>
+ writeFileSync(marker, JSON.stringify({ promote }));
+const clearMarker = () => rmSync(marker, { force: true });
+
+// The Bash guard: agent_type carries the (possibly suffixed) merger identity.
+const runBlock = (command, agentType = "merger") =>
+ spawnSync("node", [BLOCK], {
+ input: JSON.stringify({
+ tool_name: "Bash",
+ agent_type: agentType,
+ session_id: SESSION_ID,
+ tool_input: { command },
+ }),
+ env,
+ encoding: "utf8",
+ }).status;
+
+// The Agent dispatch recorder: writes the marker as a side effect.
+const runRecord = (prompt) =>
+ spawnSync("node", [RECORD], {
+ input: JSON.stringify({
+ session_id: SESSION_ID,
+ tool_input: { subagent_type: "merger", prompt },
+ }),
+ env,
+ encoding: "utf8",
+ }).status;
+
+beforeAll(() => {
+ TMP = mkdtempSync(join(tmpdir(), "wave-merger-promote-test-"));
+ APP_DIR = join(TMP, "app");
+ const CRM_TMP_ROOT = join(TMP, "scratch");
+ sessionDir = join(CRM_TMP_ROOT, sanitizePath(APP_DIR), SESSION_ID);
+ marker = join(sessionDir, "merger-stage.json");
+ mkdirSync(sessionDir, { recursive: true });
+ env = { ...process.env, APP_DIR, CRM_TMP_ROOT };
+ delete env.CHAT_SESSION_DIR;
+ delete env.CLAUDE_AGENT_NAME;
+});
+
+beforeEach(() => clearMarker());
+afterAll(() => rmSync(TMP, { recursive: true, force: true }));
+
+describe("block-wave-merger-promote", () => {
+ test("blocks a Stage-B promotion when the marker says promote=false", () => {
+ setMarker(false);
+ expect(runBlock(STAGE_B)).toBe(2);
+ });
+
+ test("allows a Stage-B promotion when the marker says promote=true", () => {
+ setMarker(true);
+ expect(runBlock(STAGE_B)).toBe(0);
+ });
+
+ test("fails CLOSED (blocks) when no authorization marker exists", () => {
+ expect(runBlock(STAGE_B)).toBe(2);
+ });
+
+ test("allows a Stage-A merge (task branch into session), even for a Stage-A-only merger", () => {
+ setMarker(false);
+ expect(runBlock(STAGE_A)).toBe(0);
+ });
+
+ test("detects the promotion via the merge(session) message alone", () => {
+ setMarker(false);
+ expect(runBlock(`git merge --no-ff HEAD -m "merge(session): ${SS}"`)).toBe(
+ 2,
+ );
+ });
+
+ test("ignores a non-merger caller running the same command", () => {
+ setMarker(false);
+ expect(runBlock(STAGE_B, "developer")).toBe(0);
+ });
+
+ test("ignores a merger command that is not a git merge", () => {
+ setMarker(false);
+ expect(runBlock(`git checkout session/${SS}`)).toBe(0);
+ });
+
+ describe("integration with record-merger-stage", () => {
+ test("wave dispatch (TASK-XXX + STAGE: a-only) records promote=false -> Stage B blocked", () => {
+ expect(
+ runRecord(
+ `ROLE: merger\nTASK_ID: TASK-001\nSTAGE: a-only\nBRANCH_NAME: ${SS}/TASK-001`,
+ ),
+ ).toBe(0);
+ expect(runBlock(STAGE_B)).toBe(2);
+ });
+
+ test("plain wave dispatch (TASK-XXX, no STAGE) still records promote=false -> Stage B blocked", () => {
+ expect(
+ runRecord(
+ `ROLE: merger\nTASK_ID: TASK-001\nBRANCH_NAME: ${SS}/TASK-001`,
+ ),
+ ).toBe(0);
+ expect(runBlock(STAGE_B)).toBe(2);
+ });
+
+ test("promotion dispatch (MODE: promote) records promote=true -> Stage B allowed", () => {
+ expect(
+ runRecord(`ROLE: merger\nMODE: promote\nSESSION_SHORT_ID: ${SS}`),
+ ).toBe(0);
+ expect(runBlock(STAGE_B)).toBe(0);
+ });
+
+ test("SIMPLE single-shot dispatch records promote=true -> Stage B allowed", () => {
+ expect(
+ runRecord(`ROLE: merger (SIMPLE mode)\nBRANCH_NAME: ${SS}/simple`),
+ ).toBe(0);
+ expect(runBlock(STAGE_B)).toBe(0);
+ });
+ });
+});
diff --git a/.claude/hooks/test/progress-log.test.mjs b/.claude/hooks/test/progress-log.test.mjs
new file mode 100644
index 00000000..655be71f
--- /dev/null
+++ b/.claude/hooks/test/progress-log.test.mjs
@@ -0,0 +1,49 @@
+// Tests for lib/progress-log.mjs: appendProgress enriches the #technical-harness
+// progress log ONLY when it already exists. The critical invariant: it must NEVER
+// create the log, because the log's existence is the technical-run gate (creating it
+// on a non-technical run would leak a board into the repo via render-status).
+
+import {
+ mkdtempSync,
+ existsSync,
+ readFileSync,
+ writeFileSync,
+ rmSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, test, expect, beforeEach, afterAll } from "vitest";
+import { appendProgress } from "../lib/progress-log.mjs";
+
+let dir;
+const log = () => join(dir, "harness-progress.log");
+const roots = [];
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "progress-log-"));
+ roots.push(dir);
+});
+afterAll(() =>
+ roots.forEach((d) => rmSync(d, { recursive: true, force: true })),
+);
+
+describe("appendProgress", () => {
+ test("does nothing and returns false when the log does not exist (non-technical run)", () => {
+ expect(appendProgress(dir, "typecheck…")).toBe(false);
+ expect(existsSync(log())).toBe(false); // must NOT create it
+ });
+
+ test("appends a timestamped line and returns true when the log exists", () => {
+ writeFileSync(log(), "10:00:00 plan ready\n");
+ expect(appendProgress(dir, "[validate:TASK-001] typecheck…")).toBe(true);
+ const contents = readFileSync(log(), "utf8");
+ expect(contents).toContain("plan ready"); // preserves prior content (append only)
+ expect(contents).toMatch(
+ /\n\d{2}:\d{2}:\d{2} \[validate:TASK-001] typecheck…\n$/,
+ );
+ });
+
+ test("returns false (never throws) when the session dir is missing", () => {
+ expect(appendProgress(join(dir, "does-not-exist"), "x")).toBe(false);
+ });
+});
diff --git a/.claude/settings.json b/.claude/settings.json
index 9bc68f5d..b5f4f730 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -101,6 +101,10 @@
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-orchestrator-merge.mjs"
},
+ {
+ "type": "command",
+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-wave-merger-promote.mjs"
+ },
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/restrict-documentator-bash.mjs"
@@ -139,6 +143,10 @@
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-promote-unmerged.mjs"
},
+ {
+ "type": "command",
+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/record-merger-stage.mjs"
+ },
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/enforce-dev-dispatch.mjs"
diff --git a/CLAUDE.md b/CLAUDE.md
index b91388d8..c28c9b89 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -32,7 +32,7 @@ Off by default. `#harness` (or "use the agent team" / "with the harness") routes
`#technical-harness` is the same opt-in for a real developer: it appends a `PERSONA: technical` line (see `orchestrator.md` -> "`PERSONA: technical`"), which (1) uses the full technical register (file paths, `TASK-XXX`, git terms, `database`/`migration`/`Supabase`), (2) reports the mechanical truth (per-ticket status, branches, SHAs, verdicts, ADR paths), (3) stops at `session/<id>` (no promotion, no migration round; you promote and migrate yourself), and (4) appends every step to `<session_dir>/harness-progress.log`.
-**Live progress (technical runs).** The report lands only at the end (possibly as a `task-notification`), so surface a live view WITHOUT flooding the chat with a raw log tail. The `render-status` SubagentStop hook renders `.harness/<SESSION_SHORT_ID>/{STATUS.md,TICKETS.md,status.json,session.diff}` (gitignored, per-session, cleaned at SessionEnd) from the live session state after every agent stop. **It does not exist until the first agent stops**, so during initial planning there is no board yet: do NOT present its path at dispatch (a link then is dead: "Couldn't read this file"). Relay it only from the plan-gate pause onward, once the files exist; at dispatch, just say the board will be available once planning completes. `STATUS.md` lists tickets (status + review verdict), live worktrees, a changed-files summary, and recent activity, updating itself as agents finish; `TICKETS.md` is the readable plan; `session.diff` is the actual code the harness changed (the extension does not surface the `/tmp` worktree diffs, so this file is how the user reads them). **Give a path that resolves in the user's client - always the ABSOLUTE path.** The board lives at `<repo>/.harness/<SESSION_SHORT_ID>/`. A bare relative `.harness/...` fails with "outside the working directory" on both the desktop app and a multi-root VS Code workspace, because the client resolves it from the workspace root, not the repo subfolder. So ALWAYS give the absolute path (`<repo>/.harness/<SESSION_SHORT_ID>/STATUS.md`): the desktop app's file pane opens arbitrary absolute paths, and it is the universal fallback. For an additionally-clickable link in a multi-root editor workspace, prefix the repo folder (e.g. `atomic-crm/.harness/<SESSION_SHORT_ID>/STATUS.md`); a single-root editor session takes `.harness/<SESSION_SHORT_ID>/STATUS.md` as-is. An opt-in compact statusline is available (`.claude/scripts/harness-statusline.mjs`; wire it in your own `settings.local.json`, see its header) - not committed, since it would override a personal statusline. Dispatch the orchestrator with `run_in_background: true`. Prefer the board; a raw `Monitor({command: "tail -n +1 -F <session_dir>/harness-progress.log", ...})` terminal feed stays available but noisier. The authoritative end signal is the `task-notification`, not the log: on it, `TaskStop` any monitor, relay the report, and run `/harness-diff` on the session branch it stopped on.
+**Live progress (technical runs).** The report lands only at the end (possibly as a `task-notification`), so surface a live view WITHOUT flooding the chat with a raw log tail. The `render-status` SubagentStop hook renders `.harness/<SESSION_SHORT_ID>/{STATUS.md,TICKETS.md,status.json,session.diff}` (gitignored, per-session, cleaned at SessionEnd) from the live session state after every agent stop. **It does not exist until the first agent stops**, so during initial planning there is no board yet: do NOT present its path at dispatch (a link then is dead: "Couldn't read this file"). Relay it only from the plan-gate pause onward, once the files exist; at dispatch, just say the board will be available once planning completes. `STATUS.md` lists tickets (status + review verdict), live worktrees, a changed-files summary, and recent activity, updating itself as agents finish; `TICKETS.md` is the readable plan; `session.diff` is the actual code the harness changed (the extension does not surface the `/tmp` worktree diffs, so this file is how the user reads them). **Give a path that resolves in the user's client - always the ABSOLUTE path.** The board lives at `<repo>/.harness/<SESSION_SHORT_ID>/`. A bare relative `.harness/...` fails with "outside the working directory" on both the desktop app and a multi-root VS Code workspace, because the client resolves it from the workspace root, not the repo subfolder. So ALWAYS give the absolute path (`<repo>/.harness/<SESSION_SHORT_ID>/STATUS.md`): the desktop app's file pane opens arbitrary absolute paths, and it is the universal fallback. Markdown relative links to `.harness/...` (and to the `.harness-session/` symlink) are unreliable in the VS Code extension - observed: clicking does nothing - so do NOT rely on them. Give the ABSOLUTE path (the desktop file pane opens it, and it copy-pastes cleanly everywhere), and to put openable ticket CONTENT in the chat, `Read` the JSON: a `Read` renders a clickable file card that actually opens, which the plan-gate inline render already does. An opt-in compact statusline is available (`.claude/scripts/harness-statusline.mjs`; wire it in your own `settings.local.json`, see its header) - not committed, since it would override a personal statusline. It is **CLI-only** (the terminal statusline); it does NOT render in the VS Code extension or the desktop app, so on those surfaces use the board or the Monitor feed below. Dispatch the orchestrator with `run_in_background: true`. Prefer the board; for a live in-chat feed on ANY surface (extension / desktop / CLI), a `Monitor({command: "tail -n +1 -F <session_dir>/harness-progress.log", ...})` streams each NEW log line as a chat notification the moment it is written - now including the `[validate:TASK-XXX] typecheck…` / `… checks passed` step lines the `validate-on-stop` hook appends, so the minutes-long silent stretches between milestones (a developer's typecheck / lint / vitest / e2e) are visible instead of going dark. It is a line feed, not a rendered board, and is auto-rate-limited if the log is too chatty, so keep the log at milestone/step granularity. The authoritative end signal is the `task-notification`, not the log: on it, `TaskStop` any monitor, relay the report, and run `/harness-diff` on the session branch it stopped on.
## Agents