Skip to content

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

maj hooks async

Jerome494c3e355890
diff --git a/.claude/agents/orchestrator.md b/.claude/agents/orchestrator.md
index 4d8691e3..b287ba8a 100644
--- a/.claude/agents/orchestrator.md
+++ b/.claude/agents/orchestrator.md
@@ -412,6 +412,8 @@ Agent({ subagent_type: "merger",
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.
+
Emit a progress line only when crossing a milestone the user cares about (a ticket merged, a ticket failed) — never expose `TASK-XXX`, paths, SHAs, branches when reporting (your surface decides the wording).
#### Next wave / wrap-up
@@ -574,11 +576,12 @@ Reply with the user-facing wrap-up, then enter STATE DONE.
## NEVER DO
- ❌ Dispatch an `orchestrator` / `chat-orchestrator` agent — **you ARE the orchestrator**. CLAUDE.md's "dispatch the orchestrator" line is for the main thread only; ignore it. (A hook blocks it anyway.)
-- ❌ Dispatch a `general-purpose` agent for planning/implementation/review/merge — always use the real typed agents: `planner`, `developer`, `quality-reviewer`, `merger`, `documentator`. A `general-purpose` agent has no role constraints and will not produce the expected output contracts.
+- ❌ Dispatch a `general-purpose` agent for planning/implementation/review/merge — always use the real typed agents: `planner`, `developer`, `quality-reviewer`, `merger`, `documentator`. A `general-purpose` agent has no role constraints and will not produce the expected output contracts. **Every `Agent` call MUST set `subagent_type` explicitly** — omitting it defaults to `general-purpose` (shown as `(none)` in the block message), which `block-nested-orchestrator` rejects.
- ❌ `git merge`, `git checkout master/main`, `git pull`, `git worktree remove` from your own Bash — only the merger does this.
- ✅ Exception: during SETUP-INTERVIEW, you may `cd $CLAUDE_PROJECT_DIR && git add docs/project-context.json && git commit -m "chore(setup): …"` on the base branch. The only git write you are allowed.
- ✅ Exception: a `promotion-conflict-resolver` developer may `git add`/`git commit` a merge resolution directly in `$CLAUDE_PROJECT_DIR` on the base branch, under `.promote.lock`.
- ❌ Merge yourself if the merger fails or doesn't report → report failure, stop.
+- ❌ Create, touch, edit, or delete any file under `<session_dir>/reviews` or `<session_dir>/breaker` — those are the review-verdict and dispatch-debounce guards. Fabricating an approval flag or clearing a dispatch marker bypasses review; `bash-guard` blocks it. The reviewer writes its own verdict flag; you only ever read these dirs.
- ❌ Set `run_in_background: true` (or end the turn waiting) on any STATE B dispatch — STATE B is fully foreground.
- ❌ Start a ticket's next stage before the current stage's foreground agents have returned.
- ❌ Run per-ticket mergers concurrently — dispatch one at a time (Stage 3).
diff --git a/.claude/agents/quality-reviewer.md b/.claude/agents/quality-reviewer.md
index b3b3d688..530fcb4b 100644
--- a/.claude/agents/quality-reviewer.md
+++ b/.claude/agents/quality-reviewer.md
@@ -103,7 +103,17 @@ Read the ticket spec at `TICKET_FILE`, read the diff in `WORKTREE_PATH`. Apply y
`session-base/<short>` is the fixed session fork anchor — a local ref, independent of the base branch's name (main, master, or a working branch). It needs no fetch and is not polluted by other sessions' merges into the base branch.
2. **Apply the rubric** below (Parts A and B). Also apply `coding-style.md` and `security-triggers.md` rules.
3. **Evidence rule for "missing X" findings (HARD RULE)** — before issuing a REJECTED for a missing artifact (i18n key, test file, view column, export…), verify the absence yourself with one Grep/Glob against the CURRENT worktree HEAD, and cite that check in the finding. A REJECTED that the developer disproves with a grep costs a full wasted cycle.
-4. **Emit verdict** as the final line of output using the OUTPUT CONTRACT format above.
+4. **Record your verdict flag (COMPLEX wave — required, do this BEFORE emitting the contract line).** The merger is gated on a per-ticket verdict flag; YOU are the source of truth for it — write it yourself with a single Bash call so it never depends on a post-stop transcript read (which races the flush and silently drops APPROVED). The flag dir is the `reviews/` sibling of your ticket file, i.e. `$(dirname "${TICKET_FILE}")/reviews` (which is `<session_dir>/reviews`):
+ - **APPROVED** → create the flag:
+ ```
+ RD="$(dirname "${TICKET_FILE}")/reviews" && mkdir -p "$RD" && touch "$RD/${TASK_ID}-quality-reviewer"
+ ```
+ - **REJECTED** → remove any stale flag so a prior APPROVED can't leak into the merge:
+ ```
+ RD="$(dirname "${TICKET_FILE}")/reviews" && rm -f "$RD/${TASK_ID}-quality-reviewer"
+ ```
+ Substitute the literal `TICKET_FILE` and `TASK_ID` from your spawn prompt. This step is COMPLEX-wave only — skip it in SIMPLE mode and migration-review mode (no ticket, no per-ticket flag).
+5. **Emit verdict** as the final line of output using the OUTPUT CONTRACT format above.
**DO NOT:**
- Run validations (typecheck, prettier, unit, e2e) — hooks do this.
diff --git a/.claude/hooks/bash-guard.mjs b/.claude/hooks/bash-guard.mjs
index d45086eb..9aff0932 100755
--- a/.claude/hooks/bash-guard.mjs
+++ b/.claude/hooks/bash-guard.mjs
@@ -1,5 +1,5 @@
#!/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 (validate-on-stop.mjs runs them automatically on SubagentStop).
+// PreToolUse(Bash) — single guard for Bash commands. Blocks commands that open browser windows (headed Playwright, Vite --open) for every caller, blocks the orchestrator from mutating the review/dispatch guard state under <sessionDir>/{reviews,breaker}, and blocks gated subagents from running validation commands (validate-on-stop.mjs runs them automatically on SubagentStop).
import { readFileSync } from "node:fs";
import { createHookContext } from "./lib/context.mjs";
@@ -39,6 +39,40 @@ if (browserViolation) {
});
}
+// Guard-state rule — orchestrator only: the orchestrator must NEVER mutate the
+// hook state under <sessionDir>/reviews (review-verdict flags) or
+// <sessionDir>/breaker (planner/duplicate-dispatch markers). Those files ARE the
+// safety guards (block-merger-without-review, block-duplicate-dispatch) — an
+// orchestrator that touches/rm's them forges an approval or clears a debounce and
+// bypasses review entirely. This happened in a past session: a racy verdict flag
+// led the orchestrator to `touch reviews/TASK-002-quality-reviewer` and
+// `rm breaker/dispatch-*` to force a merge. Reads (ls/cat) stay allowed.
+// Match the orchestrator the same way block-nested-orchestrator does: agent_type
+// when present, else the CLAUDE_AGENT_NAME-derived ctx.agentType, allowing a
+// suffixed runtime name (orchestrator-…) and the chat- prefix.
+const isOrchestrator = /^(chat-)?orchestrator(-|$)/.test(
+ agent || ctx.agentType || "",
+);
+if (isOrchestrator) {
+ const guardPath = /\/(reviews|breaker)\//;
+ const mutatingVerb =
+ /(^|[;&|]|\bsudo\b|\bxargs\b)\s*(rm|touch|mkdir|mv|cp|truncate|ln)\b/.test(
+ cmd,
+ ) ||
+ /\bsed\s+(-[a-zA-Z]*i\b|--in-place)/.test(cmd) ||
+ /\|\s*tee\b/.test(cmd);
+ const redirectToGuard = />>?\s*\S*\/(reviews|breaker)\//.test(cmd);
+ if ((mutatingVerb && guardPath.test(cmd)) || redirectToGuard) {
+ ctx.block({
+ reason:
+ "Refusing this command: the orchestrator must not write to or delete files under <session_dir>/reviews or <session_dir>/breaker — those ARE the review/dispatch guards. " +
+ "If a merger dispatch was blocked for 'no APPROVED verdict', do NOT fabricate the flag and do NOT re-dispatch the reviewer: the reviewer writes its own flag on APPROVED (quality-reviewer.md). A missing flag means the reviewer did NOT approve — read its output file and act on the real verdict. " +
+ "If a dispatch was blocked as 'still in flight', wait for its task-notification instead of clearing the marker.",
+ log: `BLOCK orchestrator guard-state mutation 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"];
diff --git a/.claude/hooks/lib/reviews.mjs b/.claude/hooks/lib/reviews.mjs
index 515c4089..d37b4a9e 100644
--- a/.claude/hooks/lib/reviews.mjs
+++ b/.claude/hooks/lib/reviews.mjs
@@ -1,9 +1,13 @@
// Per-ticket review verdict flags. The presence of a flag means that reviewer
-// returned APPROVED for the ticket. Written by record-review-verdict.mjs
-// (SubagentStop), read by block-merger-without-review.mjs (PreToolUse/Agent),
-// cleared on REJECTED and when a developer is (re)dispatched (setup-worktree.mjs)
-// so a changed diff invalidates stale approvals. Session-scoped under
-// <sessionDir>/reviews, mirroring the <sessionDir>/flags convention.
+// returned APPROVED for the ticket. PRIMARY writer is the quality-reviewer agent
+// itself — it touches the flag via Bash as its last action before emitting the
+// contract line (see quality-reviewer.md), so the verdict is recorded
+// synchronously and never depends on a post-stop transcript read. FALLBACK writer
+// is record-review-verdict.mjs (SubagentStop), kept as belt-and-suspenders for the
+// case the reviewer forgot the touch. Read by block-merger-without-review.mjs
+// (PreToolUse/Agent), cleared on REJECTED and when a developer is (re)dispatched
+// (setup-worktree.mjs) so a changed diff invalidates stale approvals. Session-scoped
+// under <sessionDir>/reviews, mirroring the <sessionDir>/flags convention.
import { join } from "node:path";
diff --git a/.claude/hooks/record-review-verdict.mjs b/.claude/hooks/record-review-verdict.mjs
index 8aa16c3e..6330d232 100755
--- a/.claude/hooks/record-review-verdict.mjs
+++ b/.claude/hooks/record-review-verdict.mjs
@@ -1,7 +1,14 @@
#!/usr/bin/env node
-// SubagentStop(quality-reviewer) — record the reviewer's verdict
-// as a per-ticket flag so block-merger-without-review.mjs can enforce
-// dev -> reviewer -> merger. SubagentStop cannot block — it only records.
+// SubagentStop(quality-reviewer) — FALLBACK recorder of the reviewer's verdict
+// flag (block-merger-without-review.mjs enforces dev -> reviewer -> merger on it).
+// The PRIMARY writer is now the quality-reviewer agent itself, which touches the
+// flag via Bash before it stops (see quality-reviewer.md) — synchronous, no race.
+// This hook stays as belt-and-suspenders: at SubagentStop the reviewer's final
+// contract line is often not yet flushed to the transcript (and last_assistant_message
+// is absent in this runtime), so verdict recovery here can return UNKNOWN and the
+// flag is left untouched. That silent miss was the TASK-002 cascade — the agent
+// self-write removes the dependency; this hook only catches the case the agent
+// skipped its touch. SubagentStop cannot block — it only records.
//
// Flag (presence == APPROVED): <sessionDir>/reviews/<TASK>-<role>. Cleared on
// REJECTED here; cleared on a developer (re)dispatch by setup-worktree.mjs so a
diff --git a/.claude/hooks/test/bash-guard.test.mjs b/.claude/hooks/test/bash-guard.test.mjs
index ee030a52..040a145a 100644
--- a/.claude/hooks/test/bash-guard.test.mjs
+++ b/.claude/hooks/test/bash-guard.test.mjs
@@ -104,4 +104,69 @@ describe("bash-guard hook", () => {
expect(isBlocked(r)).toBe(false);
});
});
+
+ describe("guard-state rule — orchestrator only", () => {
+ const SD = "/tmp/_repo/sess-1234";
+
+ test("orchestrator touches a review flag → blocked", () => {
+ const r = runHook(
+ "orchestrator",
+ `touch ${SD}/reviews/TASK-002-quality-reviewer`,
+ );
+ expect(r.status).toBe(0);
+ expect(isBlocked(r)).toBe(true);
+ });
+
+ test("orchestrator rm's a breaker marker → blocked", () => {
+ const r = runHook("orchestrator", `rm ${SD}/breaker/dispatch-abc123`);
+ expect(isBlocked(r)).toBe(true);
+ });
+
+ test("orchestrator mkdir + touch a review flag (compound) → blocked", () => {
+ const r = runHook(
+ "orchestrator",
+ `mkdir -p ${SD}/reviews && touch ${SD}/reviews/TASK-002-quality-reviewer`,
+ );
+ expect(isBlocked(r)).toBe(true);
+ });
+
+ test("orchestrator redirects into a breaker file → blocked", () => {
+ const r = runHook("orchestrator", `echo x > ${SD}/breaker/marker`);
+ expect(isBlocked(r)).toBe(true);
+ });
+
+ test("orchestrator lists the reviews dir (read) → allowed", () => {
+ const r = runHook("orchestrator", `ls ${SD}/reviews/`);
+ expect(isBlocked(r)).toBe(false);
+ });
+
+ test("orchestrator cats a review flag with 2>/dev/null (read) → allowed", () => {
+ const r = runHook(
+ "orchestrator",
+ `cat ${SD}/reviews/TASK-002-quality-reviewer 2>/dev/null`,
+ );
+ expect(isBlocked(r)).toBe(false);
+ });
+
+ test("quality-reviewer touches its own flag → allowed (reviewer is the writer)", () => {
+ const r = runHook(
+ "quality-reviewer",
+ `mkdir -p ${SD}/reviews && touch ${SD}/reviews/TASK-002-quality-reviewer`,
+ );
+ expect(isBlocked(r)).toBe(false);
+ });
+
+ test("orchestrator rm of an unrelated tmp file → allowed", () => {
+ const r = runHook("orchestrator", `rm ${SD}/scratch/note.txt`);
+ expect(isBlocked(r)).toBe(false);
+ });
+
+ test("chat-orchestrator variant touching a review flag → blocked", () => {
+ const r = runHook(
+ "chat-orchestrator",
+ `touch ${SD}/reviews/TASK-001-quality-reviewer`,
+ );
+ expect(isBlocked(r)).toBe(true);
+ });
+ });
});
diff --git a/.claude/rules/worktree-scope.md b/.claude/rules/worktree-scope.md
index a884ba9d..eeb76d2f 100644
--- a/.claude/rules/worktree-scope.md
+++ b/.claude/rules/worktree-scope.md
@@ -30,6 +30,7 @@ Each session owns an integration branch `session/<SESSION_SHORT_ID>` (forked fro
|---|---|---|---|
| `<WORKTREE_PATH>/**` (i.e. `<WORKTREE_BASE>/TASK-XXX/`) | ✅ | ✅ | ✅ |
| `${TICKETS_DIR}/TASK-XXX.json` (per-session folder passed in your prompt) | ✅ (ticket source of truth) | ⚠️ merger writes the `status` field — no other writes | — |
+| `${TICKETS_DIR}/reviews/<TASK-XXX>-quality-reviewer` (`reviews/` sibling of the ticket file) | ✅ | ⚠️ quality-reviewer ONLY, and ONLY its own ticket's flag: `touch` on APPROVED / `rm -f` on REJECTED (records its verdict; see quality-reviewer.md). No other agent, no other file under `reviews/`. | — |
| `$REPO/adr/**` | ✅ (learn from past structural decisions) | ❌ (developer writes ADRs inside the worktree at `<WORKTREE_PATH>/adr/`; the merger ships them to `$REPO/adr/`) | — |
| `~/.claude/**` (`$CLAUDE_CONFIG_DIR`) | ✅ (skills, rules) | ❌ | — |