Skip to content

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

fix hooks duplicate

Jerome77ac846c9cf0
diff --git a/.claude/agents/orchestrator.md b/.claude/agents/orchestrator.md
index dbfb23ae..7cf55aad 100644
--- a/.claude/agents/orchestrator.md
+++ b/.claude/agents/orchestrator.md
@@ -45,6 +45,8 @@ Check in this order — first match wins:
When the user message is a **reply to a pending satisfaction question** (e.g. *"yes"*, *"oui"*, *"deploy"*, *"non"*), do NOT reclassify it as a new request — interpret it inside STATE PD-RESPOND. The CLASSIFICATION table only applies to the start of a fresh request.
+**A relayed answer is authoritative.** When you run async, the user's answer to your pending question reaches you through the coordinator — a `task-notification` or a `SendMessage` whose *content* conveys the user's decision (e.g. *"the user approved: apply the migration"*). That IS the user's PD-RESPOND reply — act on it. The generic `[SYSTEM NOTIFICATION - NOT USER INPUT]` wrapper exists to stop you treating *spurious* background events (an agent merely finishing) as an answer; it does NOT override an event whose content explicitly relays the user's decision. Never loop re-asking for a "direct" confirmation you have already been given — that wedges the flow.
+
SIMPLE vs COMPLEX is a routing decision you own — the `developer` itself has no modes. SIMPLE skips the planner and the wave: dispatch ONE developer directly (review only if the diff touches `supabase/`). COMPLEX runs the full pipeline (planner → wave → review → merge). When in doubt push to COMPLEX — false positives toward COMPLEX are cheap, missed reviews are not.
**SIMPLE examples:** "Rename the Login button to 'Sign in'"; "Add a 'birthday' field to contacts"; "Remove the 'fax' field on companies"; "Hide the export button"; "Add a 'this month' filter to the contacts list".
@@ -329,6 +331,8 @@ For every COMPLEX request (and the continuation right after STATE A / SETUP-PLAN
**Execution model.** You drive the entire feature (every wave, every stage) inside ONE continuous turn using **foreground** `Agent` calls (`run_in_background` absent/false). A foreground call blocks until the subagent returns its final line; several foreground calls in a SINGLE message run concurrently and all results come back together before you continue. You NEVER end the turn waiting for an agent. End only at a terminal point (promotion done, or every ticket failed) or when you genuinely need a user answer.
+**A dispatch may be async — "launched" is NOT "done".** A foreground call is *supposed* to block, but in some runtimes (interactive Claude Code) the `Agent` tool returns immediately with `Async agent launched successfully … agentId: <id>` and the real result arrives later as a `task-notification`. Treat that acknowledgement as *dispatched, not finished*: do NOT proceed, and **do NOT re-dispatch the same role for the same ticket** to "get a result" — wait for the matching `task-notification`, then read the agent's output file and parse its contract line. **Running two agents for the same ticket+role concurrently is always a bug** — it once spawned two `quality-reviewer`s racing on one worktree. One dispatch per ticket+role in flight at a time; the `block-duplicate-dispatch` hook is a backstop, not a license to fire twice. Stage barriers still hold whether results come inline (sync) or via notifications (async): every agent dispatched in a stage must have returned before you start the next.
+
Parse the planner's output into dependency-ordered **waves**:
- Wave 1 = tickets with `dependencies: []`.
- Wave N+1 = tickets whose deps are all merged in waves ≤ N.
diff --git a/.claude/hooks/block-duplicate-dispatch.mjs b/.claude/hooks/block-duplicate-dispatch.mjs
new file mode 100755
index 00000000..cd614a8e
--- /dev/null
+++ b/.claude/hooks/block-duplicate-dispatch.mjs
@@ -0,0 +1,139 @@
+#!/usr/bin/env node
+// PreToolUse(Agent) — block accidental duplicate dispatches. Two concerns,
+// grouped in one hook because both are "don't dispatch the same thing twice":
+//
+// 1. planner: at most ONE `planner` dispatch per request.
+// Scope = caller orchestrator agent_id + TICKETS_DIR (one planning round).
+// A 2nd planner would overwrite the TASK-*.json the wave is already running
+// against. 1-hour staleness reset so a stuck marker can't poison a
+// long-lived orchestrator.
+//
+// 2. developer / quality-reviewer / merger: debounce identical re-dispatches
+// inside a short window. A foreground Agent call is SUPPOSED to block and
+// return the subagent's final line inline; in some runtimes (interactive
+// Claude Code) it instead returns immediately with "Async agent launched …
+// agentId: <id>" and the real result arrives later as a task-notification.
+// An orchestrator expecting an inline result then re-dispatches the SAME
+// role for the SAME ticket seconds later — two agents racing on one
+// worktree/branch. This produced duplicate quality-reviewers on TASK-001 in
+// a past session. Block the second dispatch inside the window; the prompt
+// tells the caller to wait for the task-notification instead. The window is
+// short (< the time any agent takes to finish) so it only ever catches the
+// rapid re-dispatch, never a legitimate retry minutes later (which also
+// carries a different prompt).
+
+import {
+ existsSync,
+ mkdirSync,
+ readFileSync,
+ statSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { join } from "node:path";
+import { createHash } from "node:crypto";
+import { createHookContext } from "./lib/context.mjs";
+import { parseDispatch } from "./lib/dispatch-parse.mjs";
+
+const DEBOUNCE_ROLES = new Set(["developer", "quality-reviewer", "merger"]);
+const DEBOUNCE_WINDOW_MS = 90 * 1000;
+const PLANNER_STALE_MS = 60 * 60 * 1000;
+
+const input = JSON.parse(readFileSync(0, "utf8"));
+const ctx = createHookContext(input, "block-duplicate-dispatch");
+const d = parseDispatch(input);
+const prompt = String(input.tool_input?.prompt ?? "");
+
+// Without a caller agent_id we can't scope a marker safely — allow rather than
+// risk over-blocking the only dispatch.
+const caller = ctx.agentId;
+if (!caller) process.exit(0);
+
+const markerDir = join(ctx.sessionDir, "breaker");
+try {
+ mkdirSync(markerDir, { recursive: true });
+} catch {
+ process.exit(0); // can't persist a marker → don't risk blocking a real dispatch
+}
+
+const sha = (s) => createHash("sha1").update(s).digest("hex").slice(0, 16);
+
+// ---- Concern 1: at most one planner per request -------------------------------
+if (d.subagentType === "planner") {
+ // The STATE A planner template writes `TICKETS_DIR=<path>` (equals);
+ // parseDispatch only captures the `TICKETS_DIR:` (colon) form, so accept both.
+ const promptTicketsDir =
+ (prompt.match(/^TICKETS_DIR[:=]\s*(\S+)/m) || [])[1] || "";
+ const ticketsDir = d.ticketsDir || promptTicketsDir || ctx.ticketsDir || "";
+ const marker = join(markerDir, `planner-${sha(`${caller}::${ticketsDir}`)}`);
+
+ if (existsSync(marker)) {
+ try {
+ if (Date.now() - statSync(marker).mtimeMs > PLANNER_STALE_MS)
+ unlinkSync(marker);
+ } catch {
+ // ignore — fall through to the existence check
+ }
+ }
+ if (existsSync(marker)) {
+ ctx.block({
+ reason:
+ `A \`planner\` has ALREADY been dispatched for this request (TICKETS_DIR=${ticketsDir || "(session default)"}). ` +
+ `Do NOT dispatch a second planner — a re-plan overwrites the existing TASK-*.json while the wave may already be running against them. ` +
+ `Read the tickets already in TICKETS_DIR and continue into STATE B with them. ` +
+ `If the first plan looks wrong, fix the ticket JSON in place — do not re-run the planner.`,
+ log: `BLOCK 2nd planner caller=${caller} ticketsDir=${ticketsDir || "(default)"}`,
+ });
+ }
+ try {
+ writeFileSync(marker, `${caller} ${ticketsDir}\n`);
+ } catch {
+ // if we can't record the marker, still allow this (first) planner through
+ }
+ ctx.log(
+ `ALLOW 1st planner caller=${caller} ticketsDir=${ticketsDir || "(default)"}`,
+ );
+ process.exit(0);
+}
+
+// ---- Concern 2: debounce duplicate developer/reviewer/merger dispatches -------
+if (DEBOUNCE_ROLES.has(d.subagentType)) {
+ // Key on the ticket identity when present (TASK-001 / SIMPLE / MIGRATION /
+ // PROMOTE / ROLLBACK); fall back to a prompt hash for dispatches with no
+ // TASK_ID line (e.g. the SIMPLE inline CHANGE_REQUEST), so two identical
+ // prompts inside the window still collide while a genuine retry — which
+ // carries different prompt text (RETRY_FEEDBACK / FIX findings) — does not.
+ const idPart = d.taskId || `prompt:${sha(prompt)}`;
+ const marker = join(
+ markerDir,
+ `dispatch-${sha(`${caller}::${d.subagentType}::${idPart}`)}`,
+ );
+
+ if (existsSync(marker)) {
+ let ageMs = Infinity;
+ try {
+ ageMs = Date.now() - statSync(marker).mtimeMs;
+ } catch {
+ // unreadable mtime → treat as stale, fall through to refresh + allow
+ }
+ if (ageMs < DEBOUNCE_WINDOW_MS) {
+ ctx.block({
+ reason:
+ `A \`${d.subagentType}\` dispatch for ${idPart} was made ${Math.round(ageMs / 1000)}s ago and is still in flight. ` +
+ `A dispatch can return immediately as "Async agent launched … agentId: <id>" WITHOUT blocking — that acknowledgement means "dispatched", not "done". ` +
+ `Do NOT re-dispatch the same role for the same ticket: wait for its task-notification, then read the agent's output file and parse its contract line. ` +
+ `Two ${d.subagentType}s on the same ticket race on one worktree/branch — that is always a bug.`,
+ log: `BLOCK duplicate ${d.subagentType} key=${idPart} age=${Math.round(ageMs / 1000)}s caller=${caller}`,
+ });
+ }
+ }
+ try {
+ writeFileSync(marker, `${caller} ${d.subagentType} ${idPart}\n`);
+ } catch {
+ // can't record → allow this dispatch through
+ }
+ ctx.log(`ALLOW ${d.subagentType} dispatch key=${idPart} caller=${caller}`);
+ process.exit(0);
+}
+
+process.exit(0);
diff --git a/.claude/hooks/block-duplicate-planner.mjs b/.claude/hooks/block-duplicate-planner.mjs
deleted file mode 100755
index 5283800e..00000000
--- a/.claude/hooks/block-duplicate-planner.mjs
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/usr/bin/env node
-// PreToolUse(Agent) — at most ONE `planner` dispatch per request.
-//
-// Scope = one request, not one session and not one orchestrator lifetime:
-// key = caller orchestrator agent_id + TICKETS_DIR.
-// - Developer session: the main thread dispatches a fresh orchestrator (new
-// agent_id) per request, so the key never collides across requests.
-// - chat-orchestrator (one long-lived instance, many requests): TICKETS_DIR is
-// per-request, so each genuine new request gets a new key and its own planner.
-// Same orchestrator + same TICKETS_DIR = same planning round → the 2nd planner
-// is blocked. A 1-hour staleness reset prevents a stuck marker from poisoning a
-// long-lived orchestrator.
-
-import {
- existsSync,
- mkdirSync,
- readFileSync,
- statSync,
- unlinkSync,
- writeFileSync,
-} from "node:fs";
-import { join } from "node:path";
-import { createHash } from "node:crypto";
-import { createHookContext } from "./lib/context.mjs";
-import { parseDispatch } from "./lib/dispatch-parse.mjs";
-
-const input = JSON.parse(readFileSync(0, "utf8"));
-const ctx = createHookContext(input, "block-duplicate-planner");
-const d = parseDispatch(input);
-
-// Only gate planner dispatches.
-if (d.subagentType !== "planner") process.exit(0);
-
-// Scope the marker to (caller orchestrator, TICKETS_DIR) = one planning round.
-// Without a caller agent_id we can't scope safely — allow rather than over-block.
-const caller = ctx.agentId;
-if (!caller) process.exit(0);
-// The STATE A planner template writes `TICKETS_DIR=<path>` (equals); parseDispatch
-// only captures the `TICKETS_DIR:` (colon) form, so read it here accepting both.
-const prompt = String(input.tool_input?.prompt ?? "");
-const promptTicketsDir =
- (prompt.match(/^TICKETS_DIR[:=]\s*(\S+)/m) || [])[1] || "";
-const ticketsDir = d.ticketsDir || promptTicketsDir || ctx.ticketsDir || "";
-const keyHash = createHash("sha1")
- .update(`${caller}::${ticketsDir}`)
- .digest("hex")
- .slice(0, 16);
-
-const markerDir = join(ctx.sessionDir, "breaker");
-try {
- mkdirSync(markerDir, { recursive: true });
-} catch {
- process.exit(0); // can't persist a marker → don't risk blocking the only planner
-}
-const marker = join(markerDir, `planner-${keyHash}`);
-
-// Auto-reset a stale marker (>1h) so a long-lived orchestrator isn't poisoned.
-if (existsSync(marker)) {
- try {
- if (Date.now() - statSync(marker).mtimeMs > 60 * 60 * 1000)
- unlinkSync(marker);
- } catch {
- // ignore — fall through to the existence check
- }
-}
-
-if (existsSync(marker)) {
- ctx.block({
- reason:
- `A \`planner\` has ALREADY been dispatched for this request (TICKETS_DIR=${ticketsDir || "(session default)"}). ` +
- `Do NOT dispatch a second planner — a re-plan overwrites the existing TASK-*.json while the wave may already be running against them. ` +
- `Read the tickets already in TICKETS_DIR and continue into STATE B with them. ` +
- `If the first plan looks wrong, fix the ticket JSON in place — do not re-run the planner.`,
- log: `BLOCK 2nd planner caller=${caller} ticketsDir=${ticketsDir || "(default)"}`,
- });
-}
-
-try {
- writeFileSync(marker, `${caller} ${ticketsDir}\n`);
-} catch {
- // if we can't record the marker, still allow this (first) planner through
-}
-ctx.log(
- `ALLOW 1st planner caller=${caller} ticketsDir=${ticketsDir || "(default)"}`,
-);
-process.exit(0);
diff --git a/.claude/hooks/test/block-duplicate-dispatch.test.mjs b/.claude/hooks/test/block-duplicate-dispatch.test.mjs
new file mode 100644
index 00000000..6bf4013f
--- /dev/null
+++ b/.claude/hooks/test/block-duplicate-dispatch.test.mjs
@@ -0,0 +1,151 @@
+// Tests for block-duplicate-dispatch.mjs — the PreToolUse(Agent) gate that
+// stops accidental duplicate dispatches. Two concerns:
+// 1. planner: at most one per (caller, TICKETS_DIR).
+// 2. developer/quality-reviewer/merger: debounce identical re-dispatches
+// inside a short window (the async-runtime "Async agent launched" trap).
+// A block is emitted via decisionBlock: exit 0 with {"decision":"block"} on
+// stdout (NOT exit 2). An allowed dispatch exits 0 with no decision JSON.
+
+import {
+ mkdtempSync,
+ mkdirSync,
+ readdirSync,
+ rmSync,
+ utimesSync,
+} 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-duplicate-dispatch.mjs");
+const SESSION_ID = "ab12cd34-1111-2222-3333-444455556666";
+const CALLER = "orchestrator-agent-1";
+
+let TMP;
+let APP_DIR;
+let breakerDir;
+let env;
+
+// Returns { blocked: boolean } — blocked when the decisionBlock JSON is printed.
+const run = (prompt, subagentType, agentId = CALLER) => {
+ const r = spawnSync("node", [HOOK], {
+ input: JSON.stringify({
+ session_id: SESSION_ID,
+ agent_id: agentId,
+ tool_input: { subagent_type: subagentType, prompt },
+ }),
+ env,
+ encoding: "utf8",
+ });
+ return {
+ blocked: /"decision":"block"/.test(r.stdout || ""),
+ status: r.status,
+ };
+};
+
+// Backdate every marker so the next dispatch sees it as outside the debounce
+// window (and a planner marker as stale).
+const ageMarkers = (secondsAgo) => {
+ const when = Date.now() / 1000 - secondsAgo;
+ for (const f of readdirSync(breakerDir)) {
+ utimesSync(join(breakerDir, f), when, when);
+ }
+};
+
+beforeAll(() => {
+ TMP = mkdtempSync(join(tmpdir(), "block-dup-dispatch-test-"));
+ APP_DIR = join(TMP, "app");
+ const CRM_TMP_ROOT = join(TMP, "scratch");
+ breakerDir = join(CRM_TMP_ROOT, sanitizePath(APP_DIR), SESSION_ID, "breaker");
+ mkdirSync(breakerDir, { recursive: true });
+ env = { ...process.env, APP_DIR, CRM_TMP_ROOT };
+});
+
+afterAll(() => rmSync(TMP, { recursive: true, force: true }));
+
+describe("block-duplicate-dispatch — planner", () => {
+ test("allows the first planner, blocks the second for the same TICKETS_DIR", () => {
+ const p = `TICKETS_DIR=${join(TMP, "tickets")}`;
+ expect(run(p, "planner").blocked).toBe(false);
+ expect(run(p, "planner").blocked).toBe(true);
+ });
+
+ test("allows a planner again once the marker is stale (>1h)", () => {
+ ageMarkers(2 * 60 * 60); // 2h
+ const p = `TICKETS_DIR=${join(TMP, "tickets")}`;
+ expect(run(p, "planner").blocked).toBe(false);
+ });
+});
+
+describe("block-duplicate-dispatch — reviewer/developer/merger debounce", () => {
+ test("blocks a second quality-reviewer for the same ticket within the window", () => {
+ const p = `ROLE: quality-reviewer\nTASK_ID: TASK-100\nWORKTREE_PATH: /wt`;
+ expect(run(p, "quality-reviewer").blocked).toBe(false);
+ expect(run(p, "quality-reviewer").blocked).toBe(true);
+ });
+
+ test("allows a reviewer for a different ticket", () => {
+ expect(
+ run(
+ `ROLE: quality-reviewer\nTASK_ID: TASK-200\nWORKTREE_PATH: /wt`,
+ "quality-reviewer",
+ ).blocked,
+ ).toBe(false);
+ });
+
+ test("allows the same reviewer again once outside the debounce window", () => {
+ ageMarkers(5 * 60); // 5 min — well past the 90s window
+ expect(
+ run(
+ `ROLE: quality-reviewer\nTASK_ID: TASK-100\nWORKTREE_PATH: /wt`,
+ "quality-reviewer",
+ ).blocked,
+ ).toBe(false);
+ });
+
+ test("debounces by ticket, not role: a merger for a fresh ticket is allowed", () => {
+ expect(
+ run(`ROLE: merger\nTASK_ID: TASK-300\nBRANCH_NAME: x`, "merger").blocked,
+ ).toBe(false);
+ });
+
+ test("a different caller is not debounced against the first caller's marker", () => {
+ const p = `ROLE: developer\nTASK_ID: TASK-400\nWORKTREE_PATH: /wt`;
+ expect(run(p, "developer", "orchestrator-A").blocked).toBe(false);
+ expect(run(p, "developer", "orchestrator-B").blocked).toBe(false);
+ });
+
+ test("falls back to a prompt hash when there is no TASK_ID (SIMPLE flow)", () => {
+ const p = `ROLE: developer\nCHANGE_REQUEST: rename the button\nWORKTREE_PATH: /wt`;
+ expect(run(p, "developer").blocked).toBe(false);
+ expect(run(p, "developer").blocked).toBe(true); // identical prompt → duplicate
+ // A different change request is a distinct dispatch, not a duplicate.
+ expect(
+ run(
+ `ROLE: developer\nCHANGE_REQUEST: hide the export\nWORKTREE_PATH: /wt`,
+ "developer",
+ ).blocked,
+ ).toBe(false);
+ });
+});
+
+describe("block-duplicate-dispatch — pass-through", () => {
+ test("ignores roles outside the debounce set (documentator)", () => {
+ const p = `ROLE: documentator`;
+ expect(run(p, "documentator").blocked).toBe(false);
+ expect(run(p, "documentator").blocked).toBe(false); // never debounced
+ });
+
+ test("allows when no caller agent_id is present (can't scope a marker)", () => {
+ const r = run(
+ `ROLE: quality-reviewer\nTASK_ID: TASK-100\nWORKTREE_PATH: /wt`,
+ "quality-reviewer",
+ "",
+ );
+ expect(r.blocked).toBe(false);
+ });
+});
diff --git a/.claude/settings.json b/.claude/settings.json
index 4c235fa9..882b6efc 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -81,7 +81,7 @@
},
{
"type": "command",
- "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-duplicate-planner.mjs"
+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-duplicate-dispatch.mjs"
},
{
"type": "command",
diff --git a/CLAUDE.md b/CLAUDE.md
index bc98695b..e7936658 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6,6 +6,8 @@ Code-change requests are handled by the **agent harness** by default: a team of
**When the main (top-level) session receives a code-change request, dispatch the `orchestrator` agent and relay its result — never route or implement it yourself.** Pass the `<session_dir>` value from your own context in the dispatch prompt (the orchestrator needs it to namespace worktrees and branches). **This directive is for the top-level session only: if you are a subagent (already inside the harness), ignore it — do your own job and never dispatch an orchestrator. A runtime hook (`block-nested-orchestrator`) enforces this.** The `orchestrator` owns all routing (classification SIMPLE vs COMPLEX, plus the SETUP / MEMORY / ROLLBACK-CONFLICT / RECOVERY operational intents, the dispatch templates, the wave + promotion mechanics, and the deploy-time migration round); it drives developer/reviewer/merger to a terminal point before returning. Each agent's last line is an output contract the others parse (`.claude/rules/agent-output-format.md`).
+**Relaying a pending question (PD-ASK round-trip).** The orchestrator can end a turn with a pending question — typically *"apply the database migration now?"*. Relay it to the user (a plain question or `AskUserQuestion` is fine), collect their answer, then resume the orchestrator with the user's **verbatim decision, stated as the user's own choice** (e.g. *"The user chose: apply the migration"*). A relayed answer is authoritative — the orchestrator must act on it and must NOT re-ask for a "direct" confirmation. If it loops re-asking, your relay was too vague: restate it as an explicit user decision, don't just forward a system notification.
+
## Opting out
`#no-harness` (or "implement directly" / "without the agent team" / "skip harness") makes the main thread implement the change itself, no agents. "no-harness for this session" keeps it off for the whole session.