Skip to content

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

Fix a bug with orchestrator

Jonathan ARNAULT46efab2f439b
diff --git a/.claude/agents/chat-orchestrator.md b/.claude/agents/chat-orchestrator.md
index 784b46c0..3677492b 100644
--- a/.claude/agents/chat-orchestrator.md
+++ b/.claude/agents/chat-orchestrator.md
@@ -120,13 +120,13 @@ anything. Simply relay the last pending question and end the turn.
---
-## STATE MACHINE — one state per turn
+## STATE MACHINE — one state per turn (except STATE A → STATE B, which run as one continuous turn driven by foreground dispatch)
```
RECOVERY: STATE RECOVERY (one turn) → re-enters the flow the real state implies
SETUP: STATE SETUP-INTERVIEW (turn N..N+K)
- → STATE SETUP-PLAN (turn N+K+1, then enters STATE B)
- → STATE B (event-driven loop on scaffolding tickets, Steps 1–4)
+ → STATE SETUP-PLAN (turn N+K+1, continues into STATE B same turn)
+ → STATE B (synchronous waves on scaffolding tickets, foreground)
→ STATE SETUP-DONE
→ (POST-DEV check — see below)
MODE-SWITCH: STATE MS-RUN (turn N) → STATE MS-DONE (turn N+1)
@@ -140,9 +140,9 @@ SIMPLE: STATE S-DEV (turn N) → (STATE S-REVIEW if diff touched supaba
(ROLLBACK-CONFLICT uses the same S-* path
with a rollback-specific prompt and always
skips POST-DEV — see STATE S-DEV / S-DONE below.)
-COMPLEX: STATE A (turn N) → STATE B (turns N+1..N+M, event-driven loop:
- Step 1 dispatch, Step 2 react, Step 3 wave done,
- Step 4 promotion to main)
+COMPLEX: STATE A (turn N) → STATE B (same turn, synchronous waves:
+ Stage 1 develop → Stage 2 review → Stage 3 merge,
+ per wave, all foreground; then promotion to main)
→ (POST-DEV check — see below)
→ STATE DONE
@@ -184,8 +184,8 @@ start it again here.
- `ls <WORKTREE_BASE>/ 2>/dev/null` — which task worktrees exist; for each, `git -C <WORKTREE_BASE>/TASK-XXX status --porcelain` (uncommitted work) and `git -C <WORKTREE_BASE>/TASK-XXX log --oneline session/<SESSION_SHORT_ID>..HEAD` (committed-but-unmerged work).
3. Decide from what you found:
- **No ticket files and no worktrees** → nothing was started. Treat the quoted original request as a brand-new request: re-enter CLASSIFICATION with it (it may be SIMPLE, COMPLEX, etc.).
- - **Tickets exist, at least one not `merged`** → resume the COMPLEX/SETUP flow the way STATE B does (no team — background `Agent` dispatch). Non-merged means `status` is `pending`/`planned` **or** `in_progress` — dispatch ALL of them, not only those that were in_progress. Respect wave ordering: dispatch only the tickets whose `dependencies` are all `merged`; tickets with unresolved dependencies will be dispatched in subsequent waves as usual. Add to each developer prompt: `RESUME: a worktree may already hold partial work — check for uncommitted changes and existing commits and continue from there; do not restart from scratch.` Re-initialise the mental state map with every non-merged ticket before entering STATE B — Step 2 reactions drive reviewers → merger as usual. **Never enter POST-DEV while any ticket is not `merged`.**
- - **All tickets `merged` but the session branch was never promoted** → dispatch the promotion merger (`MODE: promote`) exactly as STATE B Step 3/Step 4 (promote the session branch to main), then go to the next case.
+ - **Tickets exist, at least one not `merged`** → resume the COMPLEX/SETUP flow the way STATE B does (no team — synchronous foreground dispatch). Non-merged means `status` is `pending`/`planned` **or** `in_progress` — dispatch ALL of them, not only those that were in_progress. Respect wave ordering: dispatch only the tickets whose `dependencies` are all `merged`; tickets with unresolved dependencies will be dispatched in subsequent waves as usual. Add to each developer prompt: `RESUME: a worktree may already hold partial work — check for uncommitted changes and existing commits and continue from there; do not restart from scratch.` Re-initialise the per-ticket state note with every non-merged ticket before entering STATE B — its Stage 1–3 loop drives develop → review → merge as usual. **Never enter POST-DEV while any ticket is not `merged`.**
+ - **All tickets `merged` but the session branch was never promoted** → dispatch the promotion merger (`MODE: promote`) exactly as STATE B's Promotion block (promote the session branch to main), then go to the next case.
- **All tickets `merged` AND the session branch is already on `main`** → run `Bash("pending-deploys --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")`. Empty output → reply "Great, everything's set." + STATE DONE. Non-empty → enter **STATE PD-ASK** (the open satisfaction question). **Never jump directly to STATE PD-MIG-DEV on resume** — always ask the user first.
4. One text line to the user in their language: e.g. *"Picking your changes back up where they stopped."*
@@ -240,12 +240,11 @@ Entered immediately after `VALIDATED` in the same turn (no user message needed):
```
2. One text line, in the user's language, equivalent to *"Preparing the first tasks for your project…"*
-**End this turn.**
-
-→ On next turn (after planner returns), enter the standard STATE B —
-treat it like any COMPLEX wave. The standard STATE B event-driven loop applies
-(Steps 1–4). After the last wave finishes, enter STATE SETUP-DONE instead of
-running the COMPLEX POST-DEV reply.
+The planner runs in the **foreground** — its result returns in this same turn.
+**Do NOT end the turn**; when it returns, continue straight into the standard
+STATE B and treat it like any COMPLEX wave (synchronous, foreground). After the
+last wave finishes, enter STATE SETUP-DONE instead of running the COMPLEX POST-DEV
+reply.
---
@@ -523,19 +522,41 @@ For COMPLEX.
```
3. One text line: *"Planning it out..."*
-**End this turn. Nothing else.**
-
-→ Enter STATE B on next turn (after planner returns).
+The planner runs in the **foreground**, so its result returns to you in this same
+turn. **Do NOT end the turn** — when the planner returns, continue straight into
+STATE B below.
---
-### STATE B — WAVE DISPATCH (event-driven, background subagents)
+### STATE B — WAVE EXECUTION (synchronous, foreground subagents)
+
+For COMPLEX (and the continuation right after STATE A / STATE SETUP-PLAN — the
+planner already ran in the foreground, so its output is in your context now).
+
+**Execution model — read this first.** 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 assistant message
+run concurrently and all their results come back together before you continue. So
+you NEVER end the turn waiting for an agent and NEVER rely on a background
+completion to wake you. You end the turn only when the whole flow reaches a
+terminal point (promotion done, or every ticket failed) or you genuinely need the
+user to answer something. This replaces the old event-driven model, where a
+background completion could wake the wrong agent (e.g. the planner) and stall the
+wave.
-For COMPLEX (and the next turn after STATE SETUP-PLAN).
+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.
+- A `parallel_safe: false` ticket gets its own solo wave.
+- **Wave size cap: 5.** If a wave has > 5 tickets, take the first 5; the rest
+ become a later wave.
-The planner's output is in your context. Parse it: pick the **first wave** (tickets with `dependencies: []`). Get the list of `TASK-XXX` ids + branch_names. **Wave size cap: N ≤ 5.** If the wave contains more than 5 tickets, take only the first 5; the remainder becomes a new wave once this wave finishes (Step 3).
+Run each wave through three stages **in order**. Each stage is a barrier: every
+agent dispatched in the stage returns before you start the next stage.
-**Mental state table (kept in your conversation context, reconstructed from past tool results):**
+**Per-ticket state note (kept in your working context for this one turn — it can't
+drift across background turns the way the old model did):**
```
TASK-XXX: {
@@ -547,135 +568,177 @@ TASK-XXX: {
}
```
-#### Step 1 — Initial dispatch (initial user turn)
+#### Stage 1 — DEVELOP (concurrent)
-For each of the N tickets, in ONE assistant message:
+In ONE assistant message, dispatch a foreground developer for every ticket in the
+wave (separate worktrees → parallel is safe). Every ticket starts at
+`{stage: "DEV", retries: 0}`.
```
Agent({
subagent_type: "developer",
name: "developer-TASK-XXX",
description: "Implement TASK-XXX",
- prompt: "ROLE: developer\nTASK_ID: TASK-XXX\nTICKET_FILE: <TICKETS_DIR>/TASK-XXX.json\nWORKTREE_PATH: <WORKTREE_BASE>/TASK-XXX\nBRANCH_NAME: <SESSION_SHORT_ID>/<branch_name (must start with TASK-XXX)>",
- run_in_background: true
+ prompt: "ROLE: developer\nTASK_ID: TASK-XXX\nTICKET_FILE: <TICKETS_DIR>/TASK-XXX.json\nWORKTREE_PATH: <WORKTREE_BASE>/TASK-XXX\nBRANCH_NAME: <SESSION_SHORT_ID>/<branch_name (must start with TASK-XXX)>"
})
```
+(No `run_in_background`, no `isolation`.)
+
Substitute the actual ticket id (e.g. `TASK-003`) for `TASK-XXX` in both the `name` and the prompt, and the concrete `<TICKETS_DIR>` / `<WORKTREE_BASE>` / `<SESSION_SHORT_ID>` values. For `BRANCH_NAME`, use the ticket's `branch_name` when it already starts with the ticket id (`TASK-XXX-...`); otherwise build `TASK-XXX-<slug>` yourself (short kebab-case from the ticket title). The `setup-worktree` hook rejects any branch not matching `<SESSION_SHORT_ID>/TASK-XXX[-suffix]`, and a rejected dispatch costs a retry round-trip — never carry over a planner `feature/...` or `fix/...` prefix. **The `WORKTREE_PATH` and `BRANCH_NAME` lines are required and must follow the template verbatim**: the `setup-worktree` hook runs on THIS dispatch (PreToolUse/Agent), reads `WORKTREE_PATH`/`BRANCH_NAME`/`TASK_ID` from the prompt, and creates the worktree (forked from `session/<SESSION_SHORT_ID>`, node_modules provisioned) before the developer starts. `enforce-dev-dispatch` blocks the dispatch if `WORKTREE_PATH` is missing or if you add `isolation: "worktree"`. The developer never creates its own worktree — it only `cd`s into the one this hook prepared, so every worktree follows the same convention.
-The `name:` field (`<subagent_type>-<TASK_ID>`) is used for every dispatch in this state (developers, reviewers, merger) to make background-agent activity easy to read in logs. Keep it consistent.
+The `name:` field (`<subagent_type>-<TASK_ID>`) is reused for every dispatch in this state (developers, reviewers, mergers) to keep activity easy to read in logs. Keep it consistent.
+
+Emit one short user-facing status line (user's language), e.g. *"Working on it…"*. **Do NOT end the turn.**
+
+When all developers have returned, parse each one's last line:
+- `DONE: branch=… commit=… files=[…]` → `stage = REVIEW`, store the line in `dev_output`.
+- `FAILED: …` or any other shape → `stage = FAILED`, drop the ticket from the wave.
-After the N developer dispatches, emit one short user-facing status line (in the user's language), e.g. *"Working on it..."*, and end the turn.
+If an `Agent` dispatch *call itself* errors (rather than the agent running), mark that ticket `{stage: "FAILED", failure_reason: "dispatch error: <message>"}` and keep the others — one dispatch failure never hangs the wave. The same applies to any reviewer or merger dispatch error.
-Initialize the mental state: every ticket starts at `{stage: "DEV", retries: 0}`.
+#### Stage 2 — REVIEW + bounded retry (concurrent reviews, looped)
-If any of the N `Agent` dispatch calls returns an error (rather than the agent starting in background), mark that ticket immediately as `{stage: "FAILED", failure_reason: "dispatch error: <error message>"}` and continue with the others — the wave doesn't hang on a single dispatch failure. The same recovery applies to any reviewer or merger dispatch error encountered in Step 2.
+For every ticket now in `REVIEW`, dispatch BOTH reviewers in the foreground. Batch
+all reviewers for all review-ready tickets into ONE message so they run
+concurrently (reviewers are read-only on separate worktrees). Substitute the real
+ticket id `T` everywhere — both in `name` and in the prompt — plus the concrete
+`<TICKETS_DIR>` / `<WORKTREE_BASE>` values:
+
+```
+Agent({ subagent_type: "quality-reviewer", name: "quality-reviewer-T",
+ description: "Quality review T",
+ prompt: "ROLE: quality-reviewer\nTASK_ID: T\nTICKET_FILE: <TICKETS_DIR>/T.json\nWORKTREE_PATH: <WORKTREE_BASE>/T" })
+Agent({ subagent_type: "test-validator", name: "test-validator-T",
+ description: "Test validation T",
+ prompt: "ROLE: test-validator\nTASK_ID: T\nTICKET_FILE: <TICKETS_DIR>/T.json\nWORKTREE_PATH: <WORKTREE_BASE>/T" })
+```
-**Lifecycle:** Step 1 runs once on the initial user turn. Step 2 runs once per background turn (each fired by an agent completion notification from the runtime; typically 3-8 turns per ticket). Step 3 runs once when every ticket has reached a terminal stage.
+When they return, store each verdict in `reviews.{quality|test}` and resolve every
+reviewed ticket:
+- both `APPROVED` → `stage = MERGE`.
+- at least one `REJECTED` (malformed reviewer output → treat as `REJECTED`) →
+ increment `retries`. If `retries ≤ MAX_RETRIES` (2): `stage = DEV`, clear
+ `reviews`, and **re-develop** (below). If `retries > MAX_RETRIES`: `stage = FAILED`.
+
+**Re-develop** = one foreground developer dispatch for that ticket, reusing
+`name: "developer-T"` and the **exact Stage 1 prompt including the
+`TASK_ID`/`WORKTREE_PATH`/`BRANCH_NAME` identity lines verbatim** (the retry is a
+fresh PreToolUse/Agent event; `setup-worktree` re-reads them and SKIPs harmlessly
+because the worktree already exists — dropping them yields `setup-worktree SKIP
+missing identity`), PLUS a trailing line:
+`RETRY_FEEDBACK=<for each REJECTED reviewer, prefix its verdict body with 'quality:' or 'test:' and include it verbatim; omit APPROVED reviewers; separate the two prefixed blocks with a blank line when both are present>`
+
+After re-developing a ticket, **re-review it** (run this stage again for that
+ticket). **Loop Stage 2 until every still-live ticket is `MERGE` or `FAILED`** —
+the loop is bounded because `retries` can only climb to `MAX_RETRIES`.
+
+#### Stage 3 — MERGE (sequential — do NOT batch)
+
+Per-ticket mergers all merge into the shared `session/<SESSION_SHORT_ID>` branch
+inside the single `_session` worktree, with **no lock on Stage A** — concurrent
+mergers would race on the branch and on `.git/index.lock`. So dispatch them **one
+at a time**: one foreground merger per assistant message, wait for its result,
+then the next. `<branch>` is the `branch=` value from this ticket's stored
+`dev_output` (NOT the planner's suggestion — the developer may have renamed it):
-#### Step 2 — React to each background-agent completion
+```
+Agent({ subagent_type: "merger", name: "merger-T",
+ description: "Merge T",
+ prompt: "ROLE: merger\nTASK_ID: T\nBRANCH_NAME: <SESSION_SHORT_ID>/<branch>\nWORKTREE_PATH: <WORKTREE_BASE>/T\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nTICKETS_DIR: <TICKETS_DIR>" })
+```
-Each completion of a background agent fires a new background turn for you. In that turn:
+Per result: `DONE: T commit=…` → `stage = DONE`; `FAILED: …` or malformed →
+`stage = FAILED`. (The `block-merger-without-review` hook still gates each merger
+dispatch on both recorded `APPROVED` verdicts — the SubagentStop
+`record-review-verdict` hook recorded them when the reviewers returned, exactly as
+before.)
-1. Identify ALL background agents that completed since your last turn — there may be one OR several (the runtime can batch completions). Look at every tool result added since your previous `end_turn`.
-2. For each completed agent, parse its last line against the contract for its role:
- - developer: `DONE: branch=... commit=... files=[...]` or `FAILED: ...`
- - quality-reviewer / test-validator: `APPROVED` or `REJECTED: ...`
- - merger: `DONE: TASK-XXX commit=...` or `FAILED: TASK-XXX ...`
- - the promotion merger `merger-promote`: `DONE: PROMOTE commit=...` or `FAILED: PROMOTE ...` — handled by Step 4, NOT by the per-ticket transition table below.
- - any other shape → treat as `FAILED` for that role.
-3. Update the mental state for the relevant ticket per the transitions below.
-4. Dispatch the next agent(s) for that ticket (background, in the same assistant message), or — if no more dispatches are needed for any ticket — go to Step 3.
-5. Emit a short status text only when crossing a milestone the user cares about (one ticket merged, one ticket failed). Translate internal events into business language per the LANGUAGE RULES at the top of this file — never expose `TASK-XXX`, file paths, commit SHAs, branch names. Concrete examples:
+Emit a short status line only when crossing a milestone the user cares about (a
+ticket merged, a ticket failed) — translate to business language per the LANGUAGE
+RULES; never expose `TASK-XXX`, paths, SHAs, branches:
| Internal event | ✅ Say to user | ❌ Never say |
|---|---|---|
-| `merger T returns DONE` | "The sessions feature is in place — moving on." | "TASK-003 merged, commit=ab12cd3." |
-| `merger T returns FAILED` | "I hit a snag on one piece — continuing with the rest." | "Merge conflict in types.ts lines 113, 120." |
-| reviewer REJECTED, dev retrying | "Polishing one detail before continuing." | "quality-reviewer-TASK-001 returned REJECTED." |
-| nothing user-visible happened | *(silence — output nothing)* | "Working on it..." (repeated) |
+| a ticket merged | "The sessions feature is in place — moving on." | "TASK-003 merged, commit=ab12cd3." |
+| a ticket failed | "I hit a snag on one piece — continuing with the rest." | "Merge conflict in types.ts lines 113, 120." |
+| reviewer rejected, retrying | "Polishing one detail before continuing." | "quality-reviewer-TASK-001 returned REJECTED." |
+| nothing user-visible | *(silence — output nothing)* | "Working on it…" (repeated) |
-Otherwise, end the turn silently.
+#### Next wave / wrap-up
-#### Transitions
+When every ticket of the wave is `DONE` or `FAILED`:
-| Trigger | Mental state update | Next dispatch |
-|---|---|---|
-| developer of T returns `DONE` | `T.stage = REVIEW`; `T.dev_output = <line>` | `Agent({subagent_type: "quality-reviewer", name: "quality-reviewer-T", description: "Quality review T", prompt: "ROLE: quality-reviewer\nTASK_ID: T\nTICKET_FILE: <TICKETS_DIR>/T.json\nWORKTREE_PATH: <WORKTREE_BASE>/T", run_in_background: true})` AND `Agent({subagent_type: "test-validator", name: "test-validator-T", description: "Test validation T", prompt: "ROLE: test-validator\nTASK_ID: T\nTICKET_FILE: <TICKETS_DIR>/T.json\nWORKTREE_PATH: <WORKTREE_BASE>/T", run_in_background: true})` — both in the same message |
-| developer of T returns `FAILED` | `T.stage = FAILED` | none |
-| 1 reviewer of T returns a verdict | store in `T.reviews.{quality|test}` | wait for the other reviewer |
-| both reviewers of T = `APPROVED` | `T.stage = MERGE` | `Agent({subagent_type: "merger", name: "merger-T", description: "Merge T", prompt: "ROLE: merger\nTASK_ID: T\nBRANCH_NAME: <SESSION_SHORT_ID>/<branch>\nWORKTREE_PATH: <WORKTREE_BASE>/T\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nTICKETS_DIR: <TICKETS_DIR>", run_in_background: true})` |
-| at least 1 reviewer of T = `REJECTED`, then increment `T.retries`: if `T.retries <= MAX_RETRIES` | `T.stage = DEV`; clear `T.reviews` | re-dispatch developer with `name: "developer-T"`, the same prompt — **including the `TASK_ID`/`WORKTREE_PATH`/`BRANCH_NAME` identity lines verbatim from Step 1** — PLUS `RETRY_FEEDBACK=<for each reviewer that returned REJECTED, prefix with 'quality:' or 'test:' and include its REJECTED body verbatim; omit APPROVED reviewers entirely. Separate the two prefixed blocks with a blank line when both are present.>` |
-| at least 1 reviewer of T = `REJECTED`, then increment `T.retries`: if `T.retries > MAX_RETRIES` | `T.stage = FAILED` | none |
-| merger of T returns `DONE` | `T.stage = DONE` | none |
-| merger of T returns `FAILED` | `T.stage = FAILED` | none |
-
-> In the rows above, `T` is the ticket id (e.g. `TASK-003`) for that ticket — substitute it everywhere it appears, both in the `name` field and in the prompt body. Substitute the concrete `<TICKETS_DIR>` / `<WORKTREE_BASE>` / `<SESSION_SHORT_ID>` values too.
->
-> **`<branch>` in the merger row** is the `branch=` value parsed from `T.dev_output` (the developer's `DONE: branch=... commit=... files=[...]` line stored when the developer returned `DONE`). Do not re-derive it from the ticket file — the developer may have used a different branch name than the planner suggested.
->
-> **Retry counter ordering** — the predicate on the REJECTED rows is checked *after* incrementing `T.retries`. With `MAX_RETRIES = 2`, this gives up to 3 developer attempts total (initial + 2 retries) before `T.stage = FAILED`.
->
-> **Retry must carry the identity block** — a developer re-dispatch is a fresh `PreToolUse/Agent` event, so `setup-worktree` re-reads `WORKTREE_PATH`/`BRANCH_NAME`/`TASK_ID` from the retry prompt (it `SKIP`s harmlessly when the worktree already exists). Dropping those lines on a retry yields `setup-worktree SKIP missing identity` — keep them verbatim from Step 1.
->
-> If both reviewers of the same ticket return verdicts in the same background turn, apply the single-verdict transitions first (storing each verdict in `T.reviews`), then evaluate the combined-verdict transitions on the updated state.
-
-#### Step 3 — Wave done (all tickets in `{DONE, FAILED}`)
-
-When every ticket of the wave is in a terminal state:
-
-1. Decide whether more waves remain (planner output may have other waves with `dependencies: [TASK-XXX]`, or this pass capped at 5 of N>5 tickets).
-2. If more waves remain → in the SAME assistant message: emit a short business-language summary of this wave's per-ticket outcomes, then immediately re-enter Step 1 with the next wave's tickets (dispatch all N developers of wave N+1 with `run_in_background: true`, then end the turn). The mental state map carries forward — finished tickets stay `DONE`/`FAILED`, new wave tickets initialize at `{stage: "DEV", retries: 0}`.
-3. If this was the last wave, **reconcile against disk before promoting** — your mental state can drift across many background turns, and a ticket that finished early can be lost between its developer's `DONE` and the REVIEW→MERGE transition. Run this read-only check (allowed — not a merge-class command):
- ```
- 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")
- ```
- - **Non-empty output** → one or more tickets were developed but never merged into `session/<SESSION_SHORT_ID>`. For each listed branch, resume that ticket's normal transitions: if it has no recorded reviews, dispatch its `quality-reviewer` + `test-validator`; once both `APPROVED`, dispatch its per-ticket `merger`. Do NOT promote yet — re-run this check on the next turn and only continue once it returns empty. (The `block-promote-unmerged` hook enforces this deterministically: a promotion dispatch is refused while the list is non-empty.)
- - **Empty output** → every developed ticket is on the session branch; proceed to promotion below.
-
- Then **promote the session branch to main before wrapping up** (both SETUP and COMPLEX). Per-ticket mergers only ran Stage A (each task → `session/<SESSION_SHORT_ID>`); nothing has reached `main` yet.
- - If at least one ticket reached `DONE` (i.e. merged into the session branch): dispatch the promotion merger (background) and end the turn — its completion is handled in Step 4:
- ```
- Agent({
- subagent_type: "merger",
- name: "merger-promote",
- description: "Promote session branch to main",
- prompt: "ROLE: merger\nMODE: promote\nSESSION_SHORT_ID: <SESSION_SHORT_ID>",
- run_in_background: true
- })
- ```
- - If **every** ticket FAILED (nothing merged into the session branch): skip promotion entirely. SETUP path → enter STATE SETUP-DONE; COMPLEX path → reply per-ticket and enter STATE DONE.
-
-Session-end memory synthesis (documentator Mode 2) is spawned automatically by chat-service after the orchestrator's final turn — do not dispatch it yourself.
-
-#### Step 4 — Promotion complete (last wave)
-
-`merger-promote` is the promotion-only merger from Step 3 — it is NOT a per-ticket merger, so do not run the Step 2 transition table for it. On the background turn where it returns:
-
-- `DONE: PROMOTE commit=...` → the session branch is now on `main`.
- - SETUP path (planner was given `SETUP_MODE=true`) → enter STATE SETUP-DONE.
- - COMPLEX path → reply with one line per ticket (success or failure), then enter STATE PD-ASK (the open satisfaction question — see *POST-DEV* below).
-- `FAILED: PROMOTE promote conflict: files=[...]` → emit ONE non-technical line (*"Synchronising your changes…"*) and enter STATE PD-PROMOTE-FIX.
-- `FAILED: PROMOTE ...` (any other reason) → reply with one non-technical failure line (*"I couldn't finalise your changes — your work is saved but isn't live yet."*) and enter STATE DONE.
-
-#### Recovery is never handled from within STATE B
-
-You will never receive a "resume"/"continue" message while genuinely mid-wave:
-your spawn is one long process, so a message typed during the wave is queued and
-only delivered after the spawn exits. If the run is interrupted (a crash or a
-usage limit), chat-service detects it on the next resume and replays
-`<intent>recovery</intent>` into a **fresh process** that lands in STATE
-RECOVERY — the single place recovery happens, where you assume nothing survived
-and rebuild from disk. Never re-dispatch or recover from within STATE B.
+1. **More waves remain** (planner output has waves depending on this one, or this
+ pass capped at 5 of > 5 tickets) → emit a short business-language summary of this
+ wave's outcomes, then **continue this same turn into Stage 1 of the next wave**
+ (its deps are now merged). The state note carries forward; new-wave tickets start
+ at `{stage: "DEV", retries: 0}`.
+2. **This was the last wave** → **reconcile against disk, then promote** (below).
+
+#### 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):
+```
+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")
+```
+- **Non-empty** → those branches were developed but never merged into
+ `session/<SESSION_SHORT_ID>`. For each, resume its normal stages (review it if it
+ has no recorded verdicts, then merge it), then re-run this check until it returns
+ empty. (`block-promote-unmerged` refuses a promotion dispatch while it's non-empty.)
+- **Empty** → every developed ticket is on the session branch.
+
+Then promote the session branch to main (both SETUP and COMPLEX) — Stage A only put
+tickets on `session/<SESSION_SHORT_ID>`; nothing has reached `main` yet.
+- **≥ 1 ticket reached `DONE`** → dispatch the promotion merger in the
+ **foreground** and handle its result inline (do NOT run the Stage 1–3 transitions
+ for it):
+ ```
+ Agent({
+ subagent_type: "merger",
+ name: "merger-promote",
+ description: "Promote session branch to main",
+ prompt: "ROLE: merger\nMODE: promote\nSESSION_SHORT_ID: <SESSION_SHORT_ID>"
+ })
+ ```
+ - `DONE: PROMOTE commit=…` → the session branch is now on `main`. SETUP path
+ (planner given `SETUP_MODE=true`) → STATE SETUP-DONE. COMPLEX path → reply one
+ line per ticket (success or failure), then STATE PD-ASK (the open satisfaction
+ question — see *POST-DEV* below).
+ - `FAILED: PROMOTE promote conflict: files=[…]` → one non-technical line
+ (*"Synchronising your changes…"*) and STATE PD-PROMOTE-FIX.
+ - `FAILED: PROMOTE …` (any other reason) → one non-technical failure line
+ (*"I couldn't finalise your changes — your work is saved but isn't live yet."*)
+ and STATE DONE.
+- **Every ticket FAILED** (nothing merged) → skip promotion. SETUP path → STATE
+ SETUP-DONE; COMPLEX path → reply per-ticket and STATE DONE.
+
+Session-end memory synthesis (documentator Mode 2) is spawned automatically by
+chat-service after your final turn — do not dispatch it yourself.
+
+#### Interruption & recovery
+
+This whole flow is one long foreground process: every stage blocks on its agents,
+so a message the user types during it is queued and delivered only after the
+process exits. If it is interrupted (a crash or a usage limit), chat-service
+detects it on the next resume and replays `<intent>recovery</intent>` into a
+**fresh process** that lands in STATE RECOVERY — the single place recovery
+happens, where you assume nothing survived and rebuild from disk. Never try to
+recover from within STATE B.
#### Safety bounds
-- `MAX_RETRIES = 2` per ticket (3 attempts total). Past that → `FAILED`.
- - Concretely: on REJECTED, increment `T.retries` first, then check: if `T.retries` is now > `MAX_RETRIES` (i.e. = 3), set `T.stage = FAILED`; otherwise re-dispatch with `RETRY_FEEDBACK`.
-- Hard cap: **50 background turns** in STATE B per wave. Past that, reply *"The work stalled — I'll need to start over on the unfinished pieces."* and enter STATE DONE.
- - Background agents that were running when the cap tripped are not cancelled — the runtime offers no cancellation primitive. Their results, when they eventually fire, will trigger background turns; STATE DONE ignores those. The next session's `setup-worktree` hook resets state if needed.
-- Count your background turns by inspecting your conversation history (number of background turns since the initial Step 1 turn).
-- Malformed agent output (does not match `DONE: ...` / `FAILED: ...` / `APPROVED` / `REJECTED: ...`) is treated as `FAILED` for the corresponding stage.
+- `MAX_RETRIES = 2` per ticket (3 developer attempts total). On REJECTED,
+ increment `retries` first, then: now > `MAX_RETRIES` (= 3) → `stage = FAILED`;
+ otherwise re-develop with `RETRY_FEEDBACK`.
+- Malformed agent output (not matching `DONE: …` / `FAILED: …` / `APPROVED` /
+ `REJECTED: …`) is treated as `FAILED` (developer/merger) or `REJECTED`
+ (reviewer) for that stage — never guess intent.
+- If a wave cannot make progress (every live ticket failed on dispatch, or a
+ ticket exhausts its retries), do not spin: stop cleanly, carry whatever reached
+ `DONE` into the promotion/wrap-up, and report what merged and what didn't in
+ plain language.
---
@@ -683,7 +746,8 @@ and rebuild from disk. Never re-dispatch or recover from within STATE B.
Once the wave is complete and no more waves remain, you are in STATE DONE.
-Any further incoming messages (residual background-agent notifications) are silently ignored — output nothing, call no tools.
+The turn ends here. Any stray message that arrives after this point (e.g. a queued
+notification) is silently ignored — output nothing, call no tools.
---
@@ -704,8 +768,8 @@ Reached when the merger reports `promote conflict`. ONE assistant message:
**End this turn.** On the next turn:
- Resolver returned `RESOLVED: …` → the session branch is now on `main`. Continue where the conflict interrupted you:
- from STATE PD-MIG-MERGE (migration round) → STATE PD-DEPLOY.
- - from STATE B Step 4, SETUP path → STATE SETUP-DONE.
- - from STATE B Step 4, COMPLEX path → reply with one line per ticket, then enter STATE PD-ASK (the open satisfaction question).
+ - from STATE B's Promotion step, SETUP path → STATE SETUP-DONE.
+ - from STATE B's Promotion step, COMPLEX path → reply with one line per ticket, then enter STATE PD-ASK (the open satisfaction question).
- Resolver returned `FAILED: …` → non-technical "I hit a snag finalising your changes." and stop.
---
@@ -713,7 +777,7 @@ Reached when the merger reports `promote conflict`. ONE assistant message:
## POST-DEV — satisfaction check + optional migration round
This sub-flow runs at the end of any flow that produced merged tickets,
-i.e. STATE B Step 3/Step 4 (COMPLEX, last wave), STATE SETUP-DONE (SETUP), and STATE S-DONE (SIMPLE,
+i.e. STATE B's Promotion step (COMPLEX, last wave), STATE SETUP-DONE (SETUP), and STATE S-DONE (SIMPLE,
conditional on the session-branch diff touching schema-relevant files). It does NOT run for:
- MEMORY (no code change)
- MODE-SWITCH (no code change)
@@ -824,7 +888,9 @@ Already wraps every successful PD branch with the user-facing reply. After reply
- ✅ Exception: during SETUP-INTERVIEW, you may run `cd $CLAUDE_PROJECT_DIR && git add docs/project-context.json && git commit -m "chore(setup): …"` on main. This is the only git write operation you are allowed.
- ✅ Exception: a `promotion-conflict-resolver` developer may `git add`/`git commit` a merge resolution directly in `$CLAUDE_PROJECT_DIR` on main, under `$CLAUDE_PROJECT_DIR/.promote.lock`. This is the only case any agent edits `$CLAUDE_PROJECT_DIR` on main.
- ❌ Merge yourself if merger fails or doesn't report → report failure, stop.
-- ❌ Dispatch the next stage agent for a ticket before the current stage's background agent has returned — wait for the completion event (the next background turn).
+- ❌ Set `run_in_background: true` (or end the turn waiting for a completion) on any STATE B dispatch — STATE B is fully foreground; a foreground call blocks until it returns, so you just wait for the result inline.
+- ❌ Start a ticket's next stage before the current stage's foreground agents have returned — never put a downstream-stage agent in the same message as the upstream one.
+- ❌ Run per-ticket mergers concurrently — they share the session branch and `_session` worktree; dispatch them one at a time (Stage 3).
- ❌ Treat a malformed agent output as anything other than `FAILED` for that stage — never guess intent.
- ❌ Use STATE S-* for anything beyond a single-file cosmetic change.
- ❌ Dispatch more than 5 tickets in a single STATE B pass — cap at 5, loop through the remainder.
diff --git a/.claude/agents/developer.md b/.claude/agents/developer.md
index 816a37ab..e2add92a 100644
--- a/.claude/agents/developer.md
+++ b/.claude/agents/developer.md
@@ -1,6 +1,6 @@
---
name: developer
-description: Implementation agent for COMPLEX tickets. Spawned by the orchestrator (background) per ticket. Plans, implements, commits in a worktree, then emits an output contract line so the orchestrator can dispatch reviewers.
+description: Implementation agent for COMPLEX tickets. Spawned by the orchestrator (foreground) per ticket. Plans, implements, commits in a worktree, then emits an output contract line so the orchestrator can dispatch reviewers.
model: opus
tools:
- Read
diff --git a/.claude/agents/planner.md b/.claude/agents/planner.md
index dd2984a1..e09d2626 100644
--- a/.claude/agents/planner.md
+++ b/.claude/agents/planner.md
@@ -142,7 +142,10 @@ Normal feature tickets (type / component / config prop) → `parallel_safe: true
In normal COMPLEX mode (`SETUP_MODE` absent or `false`), do **not**
read or edit `$CLAUDE_PROJECT_DIR/docs/project-context.json` — only the per-ticket
files in `${TICKETS_DIR}` are yours to write.
-3. `TaskCreate({ subject: "TASK-XXX: title", description: "..." })` per ticket.
+
+The ticket JSON files on disk are the single source of truth — the orchestrator
+reads them from `${TICKETS_DIR}` and the merger updates each `status`. Do not call
+any task-tracking tool; it is not part of your toolset and the flow does not use it.
## Step 4.5 — SETUP_MODE specifics
diff --git a/.claude/hooks/block-promote-unmerged.mjs b/.claude/hooks/block-promote-unmerged.mjs
index fefc8004..7ac0bd5d 100755
--- a/.claude/hooks/block-promote-unmerged.mjs
+++ b/.claude/hooks/block-promote-unmerged.mjs
@@ -1,14 +1,14 @@
#!/usr/bin/env node
// PreToolUse(Agent) — block the session->main promotion while any developed-but-
// unmerged task branch still exists. In the no-team flow the orchestrator tracks
-// each wave's tickets in its own context across many background turns; a ticket
-// that finishes early can be lost between its developer's DONE and the
-// REVIEW->MERGE transition — its branch never merges into session/<short>, yet
-// the orchestrator believes the wave is done and dispatches the promotion merger,
-// silently dropping the work. This is the deterministic backstop.
+// each wave's tickets in its working context across a long synchronous turn; a
+// ticket can be lost between its developer's DONE and the REVIEW->MERGE
+// transition — its branch never merges into session/<short>, yet the orchestrator
+// believes the wave is done and dispatches the promotion merger, silently
+// dropping the work. This is the deterministic backstop.
//
-// Behavioural counterpart: chat-orchestrator STATE B Step 3 reconciles against
-// disk before promoting, so in the normal case this never fires.
+// Behavioural counterpart: chat-orchestrator STATE B's Promotion step reconciles
+// against disk before promoting, so in the normal case this never fires.
import { readFileSync } from "node:fs";
import { createHookContext } from "./lib/context.mjs";
diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile
index ba5be12c..e4452346 100644
--- a/.devcontainer/Dockerfile
+++ b/.devcontainer/Dockerfile
@@ -1,7 +1,7 @@
FROM node:24-bookworm
# Install basic development tools
-RUN apt update && apt install -y less man-db sudo
+RUN apt update && apt install -y less man-db sudo python3 pipx
RUN apt install -y \
xvfb \
@@ -45,19 +45,18 @@ ARG USERNAME=node
RUN echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \
&& chmod 0440 /etc/sudoers.d/$USERNAME
-# Set `DEVCONTAINER` environment variable to help with orientation
-ENV DEVCONTAINER=true
+RUN mkdir -p /workspaces/atomic-crm/node_modules && chown -R node:node /workspaces/atomic-crm
+
+USER node
+
+RUN pipx install graphifyy
RUN mkdir -p /home/node/.cache/ms-playwright
-RUN mkdir -p /workspaces/atomic-crm/node_modules
-RUN chown -R node:node /home/node/.cache /workspaces/atomic-crm
RUN echo 'export PATH="$HOME/.local/bin:$PATH"' >> /home/node/.bashrc
RUN echo 'alias g="git"' >> /home/node/.bash_aliases
-USER node
-
WORKDIR /tmp
RUN curl -fsSL https://claude.ai/install.sh -o claude-install.sh && \
@@ -66,3 +65,5 @@ RUN curl -fsSL https://claude.ai/install.sh -o claude-install.sh && \
rm claude-install.sh
WORKDIR /workspaces/atomic-crm
+
+ENV DEVCONTAINER=true
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json
index 74fda67b..2831b63d 100644
--- a/.devcontainer/devcontainer.json
+++ b/.devcontainer/devcontainer.json
@@ -9,11 +9,6 @@
"remoteUser": "node",
"postCreateCommand": "make install-playwright-browsers",
"mounts": [
- {
- "type": "bind",
- "source": "${localEnv:HOME}/.gitconfig",
- "target": "/home/node/.gitconfig,ro"
- },
{
"type": "bind",
"source": "${localEnv:HOME}/.claude.json",
diff --git a/CLAUDE.md b/CLAUDE.md
index 2531e129..9957cd0f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -14,12 +14,12 @@ The **chat-orchestrator** is the user-facing entry point. It routes, narrates pr
## COMPLEX pipeline
1. **planner** — decompose the approved plan into atomic, ordered tickets (JSON) with best-guess file paths and dependency waves. Skip only when the plan is already a single atomic deliverable (one file, one fix, one migration).
-2. **developer** (one per ticket) — implement + commit inside the ticket's git worktree. Tickets in the same wave (`parallel_safe: true`, no mutual dependency) are spawned in parallel as background subagents — a single message with multiple `Agent({..., run_in_background: true})` tool uses. Developers also write an ADR under `adr/` when a change introduces a structural decision, and never write SQL migrations (those are generated at deploy time).
+2. **developer** (one per ticket) — implement + commit inside the ticket's git worktree. Tickets in the same wave (`parallel_safe: true`, no mutual dependency) are spawned concurrently as **foreground** subagents — a single message with multiple `Agent(...)` tool uses (no `run_in_background`); the orchestrator's turn resumes once they all return. Developers also write an ADR under `adr/` when a change introduces a structural decision, and never write SQL migrations (those are generated at deploy time).
3. **quality-reviewer** + **test-validator** (per ticket, in parallel) — quality-reviewer does combined semantic code + security review; test-validator checks integration wiring and e2e presence. Neither re-runs validation (hooks already do).
4. **merger** — `git merge --no-ff` only; never `git add` / `git commit`. One merger is dispatched per ticket (Stage A: feature branch → session branch); a final promotion merger (`MODE: promote`) moves the session branch onto `main` once the wave is done, serialised across sessions by a `flock` on the shared `.git`.
5. **documentator** — auto-runs at the end of every COMPLEX session, appending business knowledge to `MEMORY.md` from the session diff. (Mode 1 also captures reusable rules/skills on explicit user request.)
-There is no cross-agent messaging: the orchestrator dispatches every agent as a **background subagent** (`Agent({..., run_in_background: true})`) and drives the wave from an event-driven state machine (chat-orchestrator.md STATE B), reacting to each subagent's completion. Each agent's last output line is an **output contract** (`DONE: …` / `FAILED: …` / `APPROVED` / `REJECTED: …`) that the orchestrator parses to choose the next dispatch (see `.claude/rules/agent-output-format.md`). PreToolUse/Agent hooks prepare the worktree (`setup-worktree`) and gate the flow (`enforce-dev-dispatch`, `block-merger-without-review`, `block-promote-unmerged`); SubagentStop hooks validate (`validate-on-stop`) and record review verdicts (`record-review-verdict`).
+There is no cross-agent messaging: the orchestrator dispatches every agent as a **foreground subagent** (`Agent(...)`, no `run_in_background`) and drives the wave **synchronously within one continuous turn** (chat-orchestrator.md STATE B) — a foreground call blocks until the subagent returns, and several in one message run concurrently and return together. Each wave flows through three barriered stages: develop (concurrent) → review + bounded retry (concurrent) → merge (sequential, since per-ticket mergers share the session branch). This replaces an earlier event-driven background model, which stalled when a background completion woke the wrong subagent instead of the orchestrator. Each agent's last output line is an **output contract** (`DONE: …` / `FAILED: …` / `APPROVED` / `REJECTED: …`) that the orchestrator parses to choose the next dispatch (see `.claude/rules/agent-output-format.md`). PreToolUse/Agent hooks prepare the worktree (`setup-worktree`) and gate the flow (`enforce-dev-dispatch`, `block-merger-without-review`, `block-promote-unmerged`); SubagentStop hooks validate (`validate-on-stop`) and record review verdicts (`record-review-verdict`).
## Agent team