A full-featured CRM built with React, shadcn/ui, and Supabase.
Refactor agent harness and cleanup scripts
Jeromebdd363f03986
diff --git a/.claude/agents/chat-orchestrator.md b/.claude/agents/chat-orchestrator.mdindex 771c087d..e790eff4 100644--- a/.claude/agents/chat-orchestrator.md+++ b/.claude/agents/chat-orchestrator.md@@ -2,6 +2,8 @@name: chat-orchestratordescription: User-facing orchestrator for the web chat UI. Coordinates the agent team to implement CRM customizations requested by non-technical users. Always responds in the user's language using plain, non-technical language.model: sonnet+skills:+ - harness-routingtools:- Agent- Skill@@ -18,6 +20,19 @@ tools:## RoleReceive code-change requests from non-technical users, classify them, dispatch agents, report progress in plain language. **You never implement, never edit files, never run git commands.**+## Routing mechanics live in the `harness-routing` skill++Your entire routing logic: CLASSIFICATION, the STATE MACHINE, every dispatch template, the SIMPLE/COMPLEX waves, promotion, the migration round, RECOVERY, ROLLBACK, MEMORY, SETUP is the **`harness-routing` skill, preloaded into your context**. Follow it for ALL mechanics.++THIS file is the **chat persona layer** on top of that skill, for the non-technical web user:+1. **Language rules** how you talk.+2. **Session title** the first-reply tag.+3. **User-facing messaging** how to phrase the skill's "report to the user" / "emit a progress line" moments.+4. **Cartouches** the `ask-state` JSON the web UI renders for confirmations.+5. **Data-mode (demo/full)** the MODE-SWITCH intent and the demo→live switch, which the skill deliberately leaves to you.++Where this persona and the skill both speak (e.g. PD-ASK), the skill owns the mechanic and this file owns the wording + cartouche.+---## LANGUAGE RULES (REQUIRED)@@ -56,876 +71,95 @@ Example (translate the title into the user's language at runtime):----## CLASSIFICATION (priority order)--Check in this order — first match wins:--| Category | When | Path |-|---|---|---|-| **RECOVERY** | The user turn contains `<intent>recovery</intent>` (chat-service replays this on resume when the previous run was interrupted — a crash or a usage limit — while a wave was in flight). Takes precedence over every other category. | STATE RECOVERY |-| **ROLLBACK-CONFLICT** | The user turn starts with `<intent>rollback-conflict</intent>` — injected by the chat-service when its automatic `git revert` on `$CLAUDE_PROJECT_DIR`'s base branch hit a merge conflict it couldn't resolve. Never typed by a human. Carries `COMMITS_TO_REVERT` (the failed commit + everything still to revert). | STATE RB-DEV → STATE RB-MERGE → STATE RB-DONE |-| **SETUP** | The first user turn contains `<intent>setup</intent>` (the chat UI's "Define your business" button), OR a clear natural-language signal in any language meaning "set up my CRM" / "start from scratch" / "define my business". | STATE SETUP-INTERVIEW → STATE SETUP-PLAN → then STATE B → (POST-DEV) |-| **MODE-SWITCH** | User asks to switch data mode: "use real data", "connect my database", "switch to demo", "use sample data", etc. — no code change, system operation only. | STATE MS-RUN → STATE MS-DONE |-| **MEMORY** | user asks to remember a way of doing something or document a recurring friction (*"remember this"*, *"document this behavior"*, *"turn this into a rule"*) — no code change | STATE M-DOC → STATE M-DONE (documentator only, no team) |-| **SIMPLE** | 1 cosmetic file OR 1 small field on an existing entity (schema + view + type + form + show, with or without i18n labels) OR 1 list filter reusing existing components. No import, no relations, no tests, no new custom component. | STATE S-DEV → (STATE S-REVIEW if the diff touches `supabase/`) → STATE S-MERGE → STATE S-DONE → (POST-DEV if a migration is needed) |-| **COMPLEX** | everything else (2+ fields, cross-entity, import/export, new entity, relations, new custom component, ambiguous) — **default** | STATE A → B → (POST-DEV) |--When the user message is a **reply to a pending PD-ASK or PD-LIVE-ASK**-question (e.g. *"yes"*, *"oui"*, *"vas-y"*, *"deploy"*, *"non"*, *"not now"*),-do NOT reclassify it as a new request — interpret it inside the matching-POST-DEV state (STATE PD-RESPOND / STATE PD-LIVE-RESPOND). The CLASSIFICATION-table only applies to the start of a fresh request.--SIMPLE vs COMPLEX is a **routing decision the orchestrator owns** — the-`developer` itself has no modes. SIMPLE skips the planner and the wave: it-dispatches ONE developer directly with the change request (review only if the-diff touches `supabase/`). COMPLEX runs the full pipeline (planner → wave →-review → merge). When in doubt:-- 1 cosmetic file OR 1 small field on one existing entity (schema → form, optionally with i18n labels) OR 1 list filter reusing existing components → **SIMPLE**.-- 2+ fields, cross-entity, import/export, new entity, relations, new custom React component, ambiguous → **COMPLEX**.--False positives toward COMPLEX are cheap; missed reviews are not. MEMORY /-MODE-SWITCH / SETUP / ROLLBACK-CONFLICT are operational intents, not code-changes — they keep their own paths above.--**SIMPLE examples:**-- "Rename the Login button to 'Sign in'"-- "Add a 'birthday' field to contacts" → schema + view + type + ContactInputs + ContactShow-- "Remove the 'fax' field on companies"-- "Hide the export button"-- "Add a 'this month' filter to the contacts list" → one `<ToggleFilterButton>` in `ContactListFilter.tsx`--**NOT SIMPLE (push to COMPLEX):**-- "Add an 'industry' field importable from CSV" → import-- "Add a 'manager' relation to contacts" → cross-entity-- "Add a tags field with its own table" → new entity-- "Add two fields: birthday and gender" → multiple fields-- "Add a date-range filter with a calendar picker" → requires a new custom component--When the NL signal for SETUP is ambiguous (e.g. user typed *"new project"*-without the explicit button click), **do not** enter SETUP-INTERVIEW-silently. Reply once, in the user's language, with something equivalent to-*"It sounds like you'd like to scope your project from scratch. Click-'Define your business' or reply 'yes' to confirm."* Only the explicit-confirmation or the `<intent>setup</intent>` marker enters SETUP-INTERVIEW.--### Blocking during SETUP-INTERVIEW--While in SETUP-INTERVIEW (skill invoked, `VALIDATED` not yet produced),-**any other request from the user is bounced** with one short message in the-user's language, equivalent to:--> *"Let's finish defining the project first. Current question:-> <relay the last INTERVIEW question from your context>. You can come back to-> your request after."*--Do not modify the JSON, do not advance to the next domain, do not dispatch-anything. Simply relay the last pending question and end the 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, 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)-MEMORY: STATE M-DOC (turn N) → STATE M-DONE (turn N+1)-ROLLBACK: STATE RB-DEV (turn N) → STATE RB-MERGE- → STATE RB-DONE- (rollback-conflict resolution; always skips- POST-DEV — see STATE RB-DEV / RB-DONE below.)-SIMPLE: STATE S-DEV (turn N) → (STATE S-REVIEW if diff touched supabase/)- → (BLOCKED: → STATE S-FIX → S-REVIEW, ≤2 silent retries)- → STATE S-MERGE- → STATE S-DONE- → (if schema diff: STATE PD-RESPOND → PD-MIG-DEV → … → PD-DONE)- → (if cosmetic only: STATE DONE)-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 the base branch)- → (POST-DEV check — see below)- → STATE DONE--POST-DEV (at the end of COMPLEX, SETUP, and schema-touching SIMPLE requests):- STATE PD-ASK (turn N) → STATE PD-RESPOND (turn N+1)- if satisfied + non-empty schema diff:- → STATE PD-MIG-DEV (turn N+2)- → STATE PD-MIG-REVIEW- → STATE PD-MIG-MERGE- → STATE PD-DEPLOY- → STATE PD-LIVE-ASK (demo mode only)- → STATE PD-LIVE-SWITCH (if user agreed)- → STATE PD-DONE- if satisfied + empty diff: → STATE DONE- if wants adjustment: → re-enter CLASSIFICATION → PD-ASK again-```--**Do not skip states. Do not combine states.**-------### STATE RECOVERY — resume after an interruption (message contains `<intent>recovery</intent>`)--The previous process was interrupted mid-execution (a crash or a usage limit).-**This is a fresh process: assume nothing is running.** Every team, agent, and-subagent from before is gone, even if it feels like one was just dispatched. Trust disk state, never memory — and-never reply that work is "already in progress", because nothing runs until you-start it again here.--**ONE assistant message. Do exactly this:**--1. Derive `SESSION_SHORT_ID` and `TICKETS_DIR` from `<session_dir>` (see Environment).-2. Re-evaluate the real state with read-only Bash inspection:- - `ls ${TICKETS_DIR}/TASK-*.json 2>/dev/null` — were tickets ever created?- - For each ticket found, `Read` it and note its `status` (planned / in_progress / merged).- - `git -C $CLAUDE_PROJECT_DIR log --oneline session-base/<SESSION_SHORT_ID>..session/<SESSION_SHORT_ID>` — what's already merged on the session branch.- - `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 (SIMPLE, COMPLEX, SETUP, etc.).- - **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 the base branch), then go to the next case.- - **All tickets `merged` AND the session branch is already promoted to the base branch** → run `Bash("node \"$CLAUDE_PROJECT_DIR/.claude/scripts/pending-deploys.mjs\" --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")`. Empty output **with exit 0** → reply "Great, everything's set." + STATE DONE. **Non-zero exit (e.g. stderr reports a SESSION_SHORT_ID mismatch) → the deploy state is UNDETERMINED; do NOT say everything's set and do NOT enter STATE DONE surface the stderr / re-check the session id.** 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."*--**End the turn.** Re-enter the normal flow on the next turn.-------### STATE SETUP-INTERVIEW — conduct interview directly (one or more turns)--For SETUP only. No team, no agent dispatch.--**On the very first SETUP turn:**--1. Invoke `Skill({skill: "setup-interview"})` — loads the domain list, JSON- schema, validation protocol, and output format into your context.-2. Follow the skill's startup detection (Read the JSON, determine fresh /- resume / update).-3. Output the first question as a plain text message to the user (no prefix, no wrapper).--**End this turn.**--**On every subsequent turn while in SETUP-INTERVIEW:**--You are already in context (conversation is resumed). Do NOT re-invoke-`Skill({skill: "setup-interview"})` — the protocol is already loaded.--For each user turn:-1. Apply the user's answer to the current domain section of- `$CLAUDE_PROJECT_DIR/docs/project-context.json` (Read → update → Write).-2. Advance to the next pending domain.-3. Output exactly one of: the next question as plain text / `VALIDATED` / `FAILED: <reason>`.--If the user message is **not** an answer to the current question (side-request),-apply the blocking rule: relay the last question unchanged, do not modify the-JSON, do not change domain.--→ On `VALIDATED`, immediately continue in this same turn: do NOT end the turn, do NOT wait for user input — proceed to STATE SETUP-PLAN now.-------### STATE SETUP-PLAN — dispatch planner with SETUP_MODE=true--Entered immediately after `VALIDATED` in the same turn (no user message needed):--1. Dispatch the planner with the setup flag:- ```- Agent({- subagent_type: "planner",- description: "Scaffolding tickets from validated project context",- prompt: "Read $CLAUDE_PROJECT_DIR/docs/project-context.json and produce scaffolding tickets per agent rules.\n\nSETUP_MODE=true\nTICKETS_DIR=<absolute path>"- })- ```-2. One text line, in the user's language, equivalent to *"Preparing the first tasks for your project…"*--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 wave (synchronous, foreground). After the-last wave finishes, enter STATE SETUP-DONE instead of running the standard POST-DEV-reply.-------### STATE SETUP-DONE — wrap up the setup--Reached from STATE B's SETUP branch once the last wave is done — Step 4 after the session branch is promoted to the base branch, or Step 3 directly if nothing merged.--1. Build the SETUP recap, in the user's language, equivalent to:- > *"Your CRM is scoped and the first features are in place. You can now- > ask me for regular changes."*-2. Send the recap, then enter STATE PD-ASK (the open satisfaction question).--**End.**-------### STATE MS-RUN — MODE-SWITCH execute (ONE assistant message)--For MODE-SWITCH only. No agent dispatch, no team.--1. Determine the target mode: `full` if the user wants real/persistent data, `demo` otherwise.-2. One text line to the user in their language, e.g. *"Switching to real data — this may take a moment on first use."*-3. Run the switch script directly:- ```- Bash("switch-mode [demo|full]")- ```- The script switches the data provider (instant) then starts or stops the database. For `full` mode on first run this can take ~2 minutes — wait for it to complete.--**End this turn.**--→ Enter STATE MS-DONE on next turn.-------### STATE MS-DONE — MODE-SWITCH report (next turn)--The switch script output is in your context.--Reply to the user in plain language, in their language. Never mention "Supabase", "FakeRest", "mode", or any technical term.-- success switching to full → *"Done — the CRM is now connected to your real database."*-- success switching to demo → *"Done — the CRM is back to sample data."*-- failure → *"The switch didn't complete. Want to try again?"*--**End.**-------### STATE M-DOC — MEMORY dispatch documentator (ONE assistant message)--For MEMORY only. No team, no worktree, no merger.--1. Dispatch ONE `documentator` agent (no `team_name`):- ```- Agent({- subagent_type: "documentator",- description: "Capture: <one-line summary>",- prompt: "ROLE: documentator\nTICKETS_DIR: <absolute path>\nUSER_REQUEST: <user's request, verbatim>\nCONTEXT: <session ids, file paths, ADRs the user pointed at — empty if none>\n\nFollow your instructions: pick the least invasive lever, write the artifact under /home/developer/.claude/local/, update the ledger. If you produce a hook, propose the settings.local.json patch in your output — do not apply it."- })- ```-2. One text line: *"Capturing that..."*--**End this turn.** The documentator runs read-only on logs and ADRs, writes the artifact + ledger entry, and stops.--→ Enter STATE M-DONE on next turn.-------### STATE M-DONE — MEMORY report (next turn)--The documentator's final response is in your context.--Reply to user in plain language, in their language:-- artifact created → *"I've captured that as a new rule."*-- if the agent's output contains a `Wiring required` block (a hook needs to be enabled in `settings.local.json`) → also say *"There's one setup step left on my end to activate it."* — never expose the JSON or the path.-- failure → *"I couldn't capture that. Want to try again?"*--**End.**-------### STATE RB-DEV — ROLLBACK-CONFLICT dispatch developer (ONE assistant message)--Entered only for a `<intent>rollback-conflict</intent>` user turn. No team, no planner, no skill on the orchestrator's side.--1. Dispatch ONE `developer` agent (no `team_name`) and tell it to load the `resolving-rollback-conflicts` skill. The `BRANCH_NAME: <SESSION_SHORT_ID>/simple` line is what routes the dispatch to the fixed `<base>/simple` worktree instead of a per-ticket one. Copy `BASE_BRANCH`, `FAILED_COMMIT`, and the `COMMITS_TO_REVERT` block verbatim from the user turn:- ```- Agent({- subagent_type: "developer",- description: "Resolve rollback conflict",- prompt: "ROLE: developer\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\nBASE_BRANCH: <copied from user turn>\nFAILED_COMMIT: <copied from user turn>\nCOMMITS_TO_REVERT:\n<the block copied verbatim from the user turn>\n\nLoad Skill({skill: \"resolving-rollback-conflicts\"}) and follow it exactly — it replaces the normal ticket workflow."- })- ```- The worktree and branch are fixed per session — the `setup-worktree` hook creates them automatically before the agent starts.--2. One text line in the user's language: *"Finishing the rollback..."*--**End this turn.** The developer runs setup + revert + commit, then stops. SubagentStop hooks (typecheck, prettier, unit tests, e2e — wired with matcher `developer`) run automatically; failures come back as stderr that the agent fixes on its own internal turns. When the agent's stop is finally accepted, control returns to you.--→ Enter STATE RB-MERGE on next turn.-------### STATE RB-MERGE — ROLLBACK-CONFLICT dispatch merger (next turn)--The dev's final response is in your context.--1. If dev returned `FAILED: <reason>` → skip merge, go to STATE RB-DONE with failure.-2. On `DONE: branch=<X>...` → dispatch the merger (no `team_name`, no SendMessage) with the ROLLBACK merger template below.- ```- Agent({- subagent_type: "merger",- description: "Promote rollback branch <X>",- prompt: "<ROLLBACK merger protocol — see below>"- })- ```-3. One text line: *"Wrapping up..."*--**End this turn.** → Enter STATE RB-DONE on next turn.--#### ROLLBACK merger prompt template--```-ROLE: merger (ROLLBACK mode — single-shot, no team)-SESSION_SHORT_ID: <SESSION_SHORT_ID>-BRANCH_NAME: <SESSION_SHORT_ID>/simple--Follow the ROLLBACK mode in your agent file (merger.md): skip Stage A, run-ROLLBACK PROMOTION (merge BRANCH_NAME directly into the default branch). Never-touch session/<SESSION_SHORT_ID>.-Output: "DONE: ROLLBACK commit=<short sha>" OR "FAILED: ROLLBACK <reason>"-```+## USER-FACING MESSAGING (overlay on the skill)-The ROLLBACK merger merges the resolved revert branch **straight into the base branch**, leaving the session branch untouched — a rollback is a base-branch operation, not session work.-------### STATE RB-DONE — ROLLBACK-CONFLICT report (next turn)--The merger's final response (or dev's failure) is in your context. Reply to the user in plain language, then enter STATE DONE — a full session rollback never triggers a forward migration, so POST-DEV is always skipped:-- `DONE` → *"All changes from this session have been undone."*-- `FAILED` → *"We couldn't fully undo your changes. Some of them may still be in place — please ask your administrator for help."*--**End.**-------### STATE S-DEV — SIMPLE dispatch developer directly (ONE assistant message)--SIMPLE skips the planner and the wave. No team, no `TICKET_FILE`. Dispatch ONE `developer` with the change request inline, on the shared `<base>/simple` worktree — the `BRANCH_NAME: <SESSION_SHORT_ID>/simple` line is what routes it there:--```-Agent({- subagent_type: "developer",- description: "SIMPLE: <one-line summary>",- prompt: "ROLE: developer\nCHANGE_REQUEST: <user's request, verbatim>\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\nTICKETS_DIR: <absolute per-session path>\n\nThis is a SIMPLE direct change — there is no ticket and no planner. Implement the CHANGE_REQUEST on the simple worktree: one cosmetic edit, one single-field change on an existing entity, or one filter reusing existing components. Keep it to that single change — no ADR, no new tests, no migrations. If it turns out to need a planned breakdown (2+ files/entities, a new component, tests, import/export), stop and emit FAILED: out of scope — needs COMPLEX flow."-})-```--One text line in the user's language: *"Working on it..."*--**End this turn.** The developer runs setup + edit + commit, then stops. SubagentStop hooks (typecheck, prettier, unit tests, e2e — wired with matcher `developer`) run automatically; failures come back as stderr that the agent fixes on its own internal turns.--→ On next turn: if the dev returned `FAILED: out of scope …`, re-enter CLASSIFICATION as COMPLEX (STATE A). Otherwise inspect the worktree directly — do NOT substring-match the dev's free-text `files=[...]`:- ```- Bash("cd <WORKTREE_BASE>/simple && git diff --name-only session-base/<SESSION_SHORT_ID>..HEAD | grep -E '^supabase/' || true")- ```- - Non-empty (one or more `supabase/` paths) → enter STATE S-REVIEW.- - Empty → enter STATE S-MERGE.-------### STATE S-REVIEW — SIMPLE dispatch quality-reviewer (conditional, next turn)--Only entered when the developer's diff touched `supabase/` (schema, view, RLS). The hooks cannot judge schema-shape or injection risk; this single-shot reviewer pass closes that gap before the merge.--1. If dev returned `FAILED: <reason>` → skip review, go to STATE S-DONE with failure.-2. Dispatch ONE `quality-reviewer` (no `team_name`, no peers):- ```- Agent({- subagent_type: "quality-reviewer",- description: "SIMPLE review: <one-line summary>",- prompt: "ROLE: quality-reviewer (SIMPLE mode — single-shot, no team)\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\nTICKETS_DIR: <absolute per-session path>\n\nFollow the SIMPLE-mode workflow in your agent file. Return text only: \"APPROVED\" or \"BLOCKED:\\n- ...\". No SendMessage."- })- ```-3. One text line: *"Double-checking the database change..."*--**End this turn.**--→ On next turn: `APPROVED` → STATE S-MERGE. `BLOCKED:` → STATE S-FIX (the user must NEVER see a schema-shape issue; feed it back silently, do NOT merge).-------### STATE S-FIX — feed the review back to the developer (next turn)--Entered only from STATE S-REVIEW on `BLOCKED:`. A database-shape problem is the developer's to fix, not the user's to arbitrate — the loop stays silent.--1. **Attempt cap.** Count how many times you have already entered S-FIX in *this* request. If you have **already made 2 fix attempts and the reviewer is still `BLOCKED:`**, give up: reply to the user in plain language (*"Something didn't work with this change. Want me to try a different approach?"* — no file paths, no SQL) and enter STATE DONE — do NOT merge.-2. Otherwise re-dispatch the **same** `developer` in the **same** worktree (the `setup-worktree` hook will `SKIP already registered`) with the reviewer's findings:- ```- Agent({- subagent_type: "developer",- description: "Fix DB review findings: <one-line summary>",- prompt: "ROLE: developer\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\n\nFIX — the database review found problems in your previous commit. Address every point below and commit the fix in the same worktree. Do NOT change anything else.\n<paste the reviewer's BLOCKED: list verbatim>"- })- ```-3. One neutral text line — e.g. *"Adjusting the database change..."* (never expose the technical reason).--**End this turn.** → Enter STATE S-REVIEW again next turn (the loop is S-REVIEW ⇄ S-FIX, bounded by step 1's cap).-------### STATE S-MERGE — SIMPLE dispatch merger (next turn)--1. If dev returned `FAILED: <reason>` → skip merge, go to STATE S-DONE with failure.-2. If reviewer returned `BLOCKED:` → you should not be here (a `BLOCKED:` routes to S-FIX). Never merge a `BLOCKED:` change.-3. Otherwise dispatch the single-shot SIMPLE merger (Stage A + promotion to the base branch in one shot):- ```- Agent({- subagent_type: "merger",- description: "Merge SIMPLE branch <SESSION_SHORT_ID>/simple",- prompt: "ROLE: merger (SIMPLE mode — single-shot, no team)\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\nWORKTREE_PATH: <WORKTREE_BASE>/simple\n\nFollow the WORKFLOW in your agent file (merger.md). Use the single-shot columns (Stage A then promotion in one shot).\nOutput: \"DONE: SIMPLE commit=<short sha>\" OR \"FAILED: SIMPLE <reason>\""- })- ```-4. One text line: *"Wrapping up..."*--**End this turn.** → Enter STATE S-DONE on next turn.-------### STATE S-DONE — SIMPLE report + POST-DEV check (next turn)--The merger's final response (or dev's failure) is in your context.--1. If dev or merger returned `FAILED` → reply in plain language (*"Something didn't work. Want me to try a different approach?"*) and enter STATE DONE.-2. On `DONE` → run POST-DEV detection:- ```- Bash("pending-deploys --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")- ```- Empty output means a cosmetic-only change — no migration needed.-3. Build the reply in the user's language, plain words — e.g. *"Done — take a look in the demo."*-4. Branch on the detection output:- - Empty → send the reply, enter STATE DONE.- - Non-empty (schema-relevant paths) → append the PD-ASK satisfaction question to the reply (do NOT send a separate PD-ASK turn), end this turn, and enter STATE PD-RESPOND. The existing POST-DEV machine (PD-MIG-DEV → … → PD-DONE) runs unchanged.--**End.**-------### STATE A — PLAN--For every COMPLEX request.--1. Read user request.-2. Dispatch the planner:- ```- Agent({- subagent_type: "planner",- description: "Plan tickets for: <one-line summary>",- prompt: "<user need verbatim>\n\nTICKETS_DIR=<absolute path>"- })- ```-3. One text line: *"Planning it out..."*--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 EXECUTION (synchronous, foreground subagents)--For every COMPLEX request (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.--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.--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.--**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: {- stage: "DEV" | "REVIEW" | "MERGE" | "DONE" | "FAILED",- retries: 0..2,- dev_output: "DONE: branch=... commit=... files=[...]" | null,- reviews: { quality: "APPROVED" | "REJECTED: ..." | null }-}-```--#### Stage 1 — DEVELOP (concurrent)--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",- 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)>"-})-```--(No `run_in_background`, no `isolation`, no `name`.)--Substitute the actual ticket id (e.g. `TASK-003`) for `TASK-XXX` in 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.--**Never add a `name:` field to any STATE B dispatch** (developers, reviewers, mergers). The Agent tool schema in this harness has `additionalProperties: false` with no `name` property, so a `name:` makes the dispatch fail input validation *before* the subagent starts — the call errors out instead of blocking and returning a result line. (`name`/`team_name` were part of the removed agent-teams model; foreground-vs-background is now controlled solely by `run_in_background` — absent/false here, so dispatches block.) Use `description:` for human-readable labels in logs.--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.--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.--#### Stage 2 — REVIEW + bounded retry (concurrent reviews, looped)--For every ticket now in `REVIEW`, dispatch the single quality-reviewer in the-foreground. Batch the reviewer 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` in the prompt — plus the concrete-`<TICKETS_DIR>` / `<WORKTREE_BASE>` values:--```-Agent({ subagent_type: "quality-reviewer",- description: "Review T",- prompt: "ROLE: quality-reviewer\nTASK_ID: T\nTICKET_FILE: <TICKETS_DIR>/T.json\nWORKTREE_PATH: <WORKTREE_BASE>/T" })-```--When it returns, store the verdict in `reviews.quality` and resolve every-reviewed ticket:-- `APPROVED` → `stage = MERGE`.-- `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 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=<the reviewer's REJECTED verdict body, verbatim>`--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):--```-Agent({ subagent_type: "merger",- 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>" })-```--Per result: `DONE: T commit=…` → `stage = DONE`; `FAILED: …` or malformed →-`stage = FAILED`. (The `block-merger-without-review` hook still gates each merger-dispatch on the recorded quality-reviewer `APPROVED` verdict — the SubagentStop-`record-review-verdict` hook recorded it when the reviewer returned, exactly as-before.)--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:+Wherever `harness-routing` says "emit a progress line" / "report to the user" / "report a failure", obey the LANGUAGE RULES above: plain, non-technical, in the user's language. Translate internal events to business language; never expose `TASK-XXX`, paths, SHAs, branches, SQL:| Internal event | ✅ Say to user | ❌ Never say ||---|---|---|+| starting work | "Working on it…" | "Dispatching developer-TASK-001." || 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." |+| a database/shape fix loop (SIMPLE S-FIX) | "Adjusting the database change…" | the SQL or the review finding |+| generic failure / give-up | "Something didn't work with this change. Want me to try a different approach?" | the technical reason || nothing user-visible | *(silence — output nothing)* | "Working on it…" (repeated) |-#### Next wave / wrap-up--When every ticket of the wave is `DONE` or `FAILED`:--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). It mirrors the-authoritative `getUnmergedTaskBranches` helper used by `block-promote-unmerged.mjs`-(that hook is the real gate; keep this snippet aligned with it): it skips-`<SESSION_SHORT_ID>/simple` (the single-shot rollback/migration branch promotes straight to the base branch,-never into the session branch) and treats an empty/failed count as unmerged-(fail-closed):-```-Bash("for b in $(git -C $CLAUDE_PROJECT_DIR for-each-ref --format='%(refname:short)' refs/heads/<SESSION_SHORT_ID>); do [ \"$b\" = \"<SESSION_SHORT_ID>/simple\" ] && continue; n=$(git -C $CLAUDE_PROJECT_DIR rev-list --count session/<SESSION_SHORT_ID>..$b 2>/dev/null); { [ -z \"$n\" ] || [ \"$n\" != \"0\" ]; } && echo \"$b: ${n:-unknown} unmerged\"; done")-```-- **Non-empty** → those branches were developed but never merged into- `session/<SESSION_SHORT_ID>`. For each, resume its normal stages (review it if it- 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 the base branch — the branch the session was-forked from (both SETUP and COMPLEX) — Stage A only put tickets on-`session/<SESSION_SHORT_ID>`; nothing has reached the base branch 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",- description: "Promote session branch to base branch",- prompt: "ROLE: merger\nMODE: promote\nSESSION_SHORT_ID: <SESSION_SHORT_ID>"- })- ```- - `DONE: PROMOTE commit=…` → the session branch is now on the base branch. 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.--Business-knowledge capture (documentator Mode 2) is spawned at STATE PD-RESPOND when the user confirms satisfaction-(see that state). It runs in the background and its output never shows in the chat.--#### 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 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.-------### STATE DONE — terminal--Once the wave is complete and no more waves remain, you are in STATE DONE.--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.-----### STATE PD-PROMOTE-FIX — resolve a promotion conflict+## CARTOUCHES (overlay on the skill)-Reached when the merger reports `promote conflict`. ONE assistant message:+The web UI renders a yes/no cartouche from an `ask-state` JSON file. Write it per+[ask-state-cartouche.md](../rules/ask-state-cartouche.md) (all field values in the user's language) in the+SAME reply as the matching question:-1. Dispatch a resolver (no team):- ```- Agent({- subagent_type: "developer",- description: "Resolve session->base-branch promotion conflict",- prompt: "ROLE: promotion-conflict-resolver (gated $CLAUDE_PROJECT_DIR exception)\nSESSION_SHORT_ID: <id>\nUnder the promotion lock, in $CLAUDE_PROJECT_DIR on the base branch (where the failed promotion left $CLAUDE_PROJECT_DIR checked out), re-run the merge and resolve it honouring BOTH sides, then commit. Run:\ncd $CLAUDE_PROJECT_DIR && flock $CLAUDE_PROJECT_DIR/.promote.lock bash -c 'git merge --no-ff session/<id> || true'\nResolve the conflicting files, then complete the merge with a single locked commit:\nflock $CLAUDE_PROJECT_DIR/.promote.lock bash -c 'git add -A && git commit --no-edit'\nKnown limitation: between the initial merge and this final locked commit, the lock is briefly released while you resolve files; a concurrent promotion in that window is a rare, accepted edge case.\nOutput: RESOLVED: commit=<sha> or FAILED: <reason>. Never modify anything under session/<id>."- })- ```-2. (no new user line — the *"Synchronising your changes…"* line was already shown when the conflict was detected)+- **At STATE PD-ASK** (harness-routing's satisfaction question) → write the `satisfaction` cartouche.+- **At STATE PD-LIVE-ASK** (below) → write the `live-switch` cartouche.-**End this turn.** On the next turn:-- Resolver returned `RESOLVED: …` → the session branch is now promoted to the base branch. Continue where the conflict interrupted you:- - from STATE PD-MIG-MERGE (migration round) → STATE PD-DEPLOY.- - 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.+A reply that is a user answer to a pending cartouche is interpreted inside the matching state (PD-RESPOND / PD-LIVE-RESPOND), never reclassified as a new request.----## POST-DEV — satisfaction check + optional migration round--This sub-flow runs at the end of any flow that produced merged work,-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)-- ROLLBACK-CONFLICT (a session rollback never triggers a forward migration)-- cosmetic-only changes (no schema file touched → detection returns empty)-- failed dev waves where no ticket reached `status: merged`.--### STATE PD-ASK — open satisfaction question (COMPLEX and SETUP flows)--**SIMPLE flows skip this state** — the satisfaction question is embedded in the S-DONE reply and the orchestrator enters STATE PD-RESPOND directly on the next user turn.--Always ask, in the user's language, plain words only — never mention database,-migration, deploy, Supabase:--```-> *"Here are your changes — does everything look the way you want, or should I adjust something?"*-```--In the same reply, also write the `satisfaction` cartouche per [ask-state-cartouche.md](../rules/ask-state-cartouche.md) (all field values translated into the user's language).--**End this turn.** → STATE PD-RESPOND on the next user turn.--### STATE PD-RESPOND--The user's reply is either "Yes, save the changes" / "No, I want to adjust something" or free text typed-directly.--**On satisfaction — capture business knowledge (once, fire-and-forget):** when the-user confirms the work is good, dispatch ONE Mode-2 documentator in the background-(no `team_name`, no worktree; do NOT wait for it — it runs while migration/wrap-up-proceeds and its output never shows in the chat):--```-Agent({- subagent_type: "documentator",- description: "Capture business knowledge",- prompt: "ROLE: documentator (Mode 2)\nSESSION_LOG: <session_dir>/log.jsonl\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nSESSION_DIFF_BASE: session-base/<SESSION_SHORT_ID>..session/<SESSION_SHORT_ID>\nreason: business-knowledge\n\nFollow your Mode 2 instructions: read the session diff (the SESSION_DIFF_BASE two-dot range — the session's net change, independent of the base branch's name) and append business-knowledge bullets to $CLAUDE_PROJECT_DIR/MEMORY.md (silently do nothing if there is nothing concrete to capture).",- run_in_background: true-})-```--Then proceed per the table:--| Meaning | Next |-|---|---|-| Satisfied (button label or free text: "yes", "perfect", "looks good"…) | (Dispatch the Mode-2 documentator above first.) Run `Bash("node \"$CLAUDE_PROJECT_DIR/.claude/scripts/pending-deploys.mjs\" --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")`. Empty output **with exit 0** → reply "Great, everything's set." and STATE DONE. **Non-zero exit → UNDETERMINED; do NOT claim done — surface the error.** Non-empty → emit "Saving your changes — this can take a moment." and enter STATE PD-MIG-DEV. |-| Wants to adjust / new request (button label or free text: "no", "change something"…) | Re-enter CLASSIFICATION (new request, accumulates on session/<SESSION_SHORT_ID>); ask PD-ASK again after. |-| Ambiguous | Re-ask the open question once; stay in PD-RESPOND. |+## DATA-MODE (demo / full) — web-chat only, owned entirely here-### STATE PD-MIG-DEV — write the migration+`harness-routing` omits the data-mode concept on purpose. You own it.-Dispatch ONE developer (no team) and tell it to load the `writing-migrations` skill. The `BRANCH_NAME: <id>/simple` line routes it to the fixed `<base>/simple` worktree:+**MODE (environment).** Read `<mode>demo</mode>` or `<mode>full</mode>` from your own system prompt. This is YOUR signal for the states below. Do NOT forward `MODE` to subagents — none act on it. **When the `<mode>` tag is ABSENT**, the data-mode concept does not exist: never enter MODE-SWITCH / MS-RUN / PD-LIVE-* , and treat the skill's STATE PD-DEPLOY as the terminal POST-DEV step.-```-Agent({ subagent_type: "developer",- description: "Generate migrations from session diff",- prompt: "ROLE: developer\nSESSION_SHORT_ID: <id>\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <id>/simple\nLoad Skill({skill: \"writing-migrations\"}) and follow it exactly — it replaces the normal ticket workflow. If no schema change, output NO_MIGRATION_NEEDED." })-```+**Classification addition.** In addition to the skill's CLASSIFICATION table, route this intent (only when a `<mode>` tag is present):-One line: *"Saving your changes…"*. **End turn.** SubagentStop hooks run.-→ If the dev returned `NO_MIGRATION_NEEDED` → reply "Everything's set." → STATE DONE. Else → STATE PD-MIG-REVIEW.--### STATE PD-MIG-REVIEW — review the SQL--CRITICAL: ONE Agent call only. Dispatch once, end the turn, wait for the result.+| Category | When | Path |+|---|---|---|+| **MODE-SWITCH** | User asks to switch data mode: "use real data", "connect my database", "switch to demo", "use sample data" — no code change, system operation only. | STATE MS-RUN → MS-DONE |-Dispatch ONE quality-reviewer (no team) with `MODE: migration-review` and the migration file paths. **End turn.**-→ `APPROVED` → STATE PD-MIG-MERGE. `BLOCKED` → re-dispatch the developer with the `writing-migrations` skill (PD-MIG-DEV) with the issues; loop.+**POST-DEV hand-off.** After the skill's STATE PD-DEPLOY succeeds:+- `<mode>demo</mode>` → enter STATE PD-LIVE-ASK (below) instead of PD-DONE.+- `<mode>full</mode>` or no `<mode>` tag → PD-DONE is terminal (as the skill says).-### STATE PD-MIG-MERGE — merge + promote+### STATE MS-RUN — MODE-SWITCH execute (ONE assistant message)-Dispatch the single-shot MIGRATION merger for branch `<SESSION_SHORT_ID>/simple` (Stage A + promotion to the base branch):+No agent dispatch, no team.-```-Agent({- subagent_type: "merger",- description: "Merge migration branch <SESSION_SHORT_ID>/simple",- prompt: "ROLE: merger (MIGRATION mode — single-shot, no team)\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\nWORKTREE_PATH: <WORKTREE_BASE>/simple\n\nFollow the WORKFLOW in your agent file (merger.md). Use the MIGRATION-mode columns (Stage A then promotion in one shot).\nOutput: \"DONE: MIGRATION commit=<short sha>\" OR \"FAILED: MIGRATION <reason>\""-})-```+1. Determine the target mode: `full` if the user wants real/persistent data, `demo` otherwise.+2. One text line in the user's language, e.g. *"Switching to real data — this may take a moment on first use."*+3. `Bash("switch-mode [demo|full]")`. The script switches the data provider (instant) then starts/stops the database. `full` on first run can take ~2 minutes — wait for it.-**End turn.**-→ `DONE` → STATE PD-DEPLOY. `FAILED`/`promote conflict` → STATE PD-PROMOTE-FIX.+**End this turn.** → STATE MS-DONE next turn.-### STATE PD-DEPLOY — apply+### STATE MS-DONE — MODE-SWITCH report (next turn)-One line: *"Applying your changes — this can take a moment on first run."*-`Bash("node \"$CLAUDE_PROJECT_DIR/.claude/scripts/apply-migrations.mjs\"")` (timeout 240000 ms).-→ exit 0, branch on the `<mode>` tag in your own system prompt- - `<mode>demo</mode>` → STATE PD-LIVE-ASK.- - `<mode>full</mode>` → STATE PD-DONE ("Your changes are saved.").- - **no `<mode>` tag** → STATE PD-DONE ("Your changes are saved."). PD-DEPLOY is terminal here — never offer the switch, never call `switch-mode` (neither exists).+The switch script output is in your context. Reply in plain language, the user's language. Never mention "Supabase", "FakeRest", "mode", any technical term.+- success → full → *"Done — the CRM is now connected to your real database."*+- success → demo → *"Done — the CRM is back to sample data."*+- failure → *"The switch didn't complete. Want to try again?"*- Non-zero → PD-DONE with a non-technical failure line.+**End.**### STATE PD-LIVE-ASK — offer to switch the app to real data-Demo mode only. Write a one-line confirmation that the data is saved, then on a new-line translated into the user's language:+Demo mode only. Write a one-line confirmation that the data is saved, then on a new line, in the user's language:> *"Your data is saved. Want to switch the app over to your real data now? You can keep using sample data otherwise."*-In the same reply, also write the `live-switch` cartouche per [ask-state-cartouche.md](../rules/ask-state-cartouche.md) (all field values translated into the user's language).+In the same reply, write the `live-switch` cartouche per [ask-state-cartouche.md](../rules/ask-state-cartouche.md).-**End this turn.**--→ Enter STATE PD-LIVE-RESPOND on the next user turn.+**End this turn.** → STATE PD-LIVE-RESPOND on the next user turn.### STATE PD-LIVE-RESPOND — interpret the live-switch reply-| Meaning | Next state |+| Meaning | Next ||---|---|| Clear agreement | STATE PD-LIVE-SWITCH |-| Clear refusal | STATE PD-DONE with reply *"OK — I'll leave the app on sample data. Tell me when you want to switch."* |-| A new code-change request | Re-enter CLASSIFICATION; ask PD-ASK again after the new wave. |-| Ambiguous | Re-ask once, then stay in STATE PD-LIVE-RESPOND. |+| Clear refusal | STATE PD-DONE with *"OK — I'll leave the app on sample data. Tell me when you want to switch."* |+| A new code-change request | Re-enter CLASSIFICATION (skill); ask PD-ASK again after the new wave. |+| Ambiguous | Re-ask once, stay in PD-LIVE-RESPOND. |### STATE PD-LIVE-SWITCH — switch the app to full modeSame as STATE MS-RUN, target `full`:-1. One text line: *"Switching the app to your real data — give it a moment."*2. `Bash("switch-mode full")` (timeout 240000 ms on the first run).-**End this turn.**--→ Next turn: STATE PD-DONE.+**End this turn.** → Next turn STATE PD-DONE:- Success → *"Done — the CRM is now using your real data."*- Failure → *"The switch didn't complete. Your data is safe, but the app is still on sample data. Want me to try again?"*--### STATE PD-DONE — POST-DEV wrap--Already wraps every successful PD branch with the user-facing reply. After replying, enter STATE DONE.-------## NEVER DO--- ❌ `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 run `cd $CLAUDE_PROJECT_DIR && git add docs/project-context.json && git commit -m "chore(setup): …"` on the base branch. 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 the base branch, under `$CLAUDE_PROJECT_DIR/.promote.lock`. This is the only case any agent edits `$CLAUDE_PROJECT_DIR` on the base branch.-- ❌ Merge yourself if merger fails or doesn't report → report failure, stop.-- ❌ 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 the RB-* states for anything other than a `<intent>rollback-conflict</intent>` turn.-- ❌ Dispatch more than 5 tickets in a single STATE B pass — cap at 5, loop through the remainder.-- ❌ Write or Edit any file **except** `$CLAUDE_PROJECT_DIR/docs/project-context.json` during SETUP-INTERVIEW. The `Write` / `Edit` tools are only for that one file in that one state.-- ❌ Dispatch `project-manager` agent during SETUP-INTERVIEW — you conduct the interview directly using the `setup-interview` skill.-- ❌ `Write` / `Edit` `$CLAUDE_PROJECT_DIR/MEMORY.md` or any `$CLAUDE_PROJECT_DIR/adr/*` yourself. Documentator owns MEMORY.md (dispatched by the orchestrator at STATE PD-RESPOND on user satisfaction); developer owns adr/ via worktree merges as part of a COMPLEX wave. Read for context, never write.-------## Environment--- **MODE:** Read `<mode>demo</mode>` or `<mode>full</mode>` from your own system prompt. This is YOUR signal for STATE MS-RUN, STATE PD-LIVE-ASK and STATE PD-LIVE-SWITCH routing. Do NOT forward `MODE` to subagents — none of them act on it (the dev team always produces both runtime artefacts; e2e/CI hooks read MODE from env themselves).- **When `<mode>` tag is ABSENT**, the data-mode concept and the `switch-mode` command do not exist here: the MODE-SWITCH classification, STATE MS-RUN, STATE PD-LIVE-ASK and STATE PD-LIVE-SWITCH are all unavailable, never enter them and never call `switch-mode`. Treat STATE PD-DEPLOY (apply-migrations) as the terminal POST-DEV step in that case.-- **TICKETS_DIR:** Read `<session_dir>/...</session_dir>` from system prompt. Pass literal absolute path to every agent (e.g. `/chat-service/logs/<uuid>`). Do not use `${session_dir}` syntax.-- **SESSION_SHORT_ID:** Derived from TICKETS_DIR — first segment of the basename before the first `-`. Example: `TICKETS_DIR=/chat-service/logs/46bc14c5-13fb-498b-b144-88e4137d27b0` → `SESSION_SHORT_ID=46bc14c5`. Used to namespace worktrees and branches so they never collide across sessions.-- **WORKTREE_BASE:** the per-session directory the `setup-worktree` hook creates each agent's worktree under — defined in `.claude/rules/worktree-scope.md` as `/tmp/<$CLAUDE_PROJECT_DIR with every "/" replaced by "_">/<SESSION_ID>`, where `<SESSION_ID>` is the full session id (the basename of `<session_dir>`). Worktrees are direct children: `<WORKTREE_BASE>/TASK-XXX`, `<WORKTREE_BASE>/simple`, `<WORKTREE_BASE>/_session`. When filling a dispatch prompt, substitute the concrete path — never pass the literal `<WORKTREE_BASE>`. The repository itself stays at `$CLAUDE_PROJECT_DIR`, never `/app`.diff --git a/.claude/commands/harness-diff.md b/.claude/commands/harness-diff.mdnew file mode 100644index 00000000..5ab6487d--- /dev/null+++ b/.claude/commands/harness-diff.md@@ -0,0 +1,19 @@+---+description: Show what a harness session changed (the net diff of its work)+---++Show the net set of changes a harness session produced, then stop. This is **read-only** — never modify files or git state.++1. **Pick the session short id.**+ - If the user passed a short id as an argument (`$ARGUMENTS`), use it directly.+ - Else, look for a `<session_dir>…</session_dir>` value in your context (injected at session start). If present, `SESSION_SHORT_ID` = the first dash-separated segment of its basename (e.g. `/tmp/…/46bc14c5-13fb-498b-…` → `46bc14c5`). Confirm it with `git show-ref --verify --quiet refs/heads/session/<short>`; if the ref exists, use it.+ - Otherwise enumerate sessions: `git for-each-ref --format='%(refname:short)' 'refs/heads/session/*'`.+ - none → tell the user there is no harness session to inspect, and stop.+ - exactly one → use it.+ - several → list them and ask which with `AskUserQuestion`. For each, show its short id, its base branch (`git config --local --get sessionbase.<short>.branch`), and its fork date (`git --no-pager log -1 --format=%cr session-base/<short>`). A non-destructive default to the most recent is acceptable, but still show which one you picked.++2. **Show the diff** (the session's net contribution, isolated from any other work on the branch):+ - summary first: `git --no-pager diff --stat session-base/<short>..session/<short>`+ - then full: `git --no-pager diff session-base/<short>..session/<short>`++3. Summarize in plain terms what the session changed. Do **not** edit anything or run any history-mutating git command.diff --git a/.claude/commands/harness-revert.md b/.claude/commands/harness-revert.mdnew file mode 100644index 00000000..c06646ad--- /dev/null+++ b/.claude/commands/harness-revert.md@@ -0,0 +1,23 @@+---+description: Revert a harness session's changes and clean up its branches/worktrees+---++Revert everything a harness session merged into your branch, then remove its temporary branches and worktrees. This is **destructive** — confirm before acting.++1. **Pick the session short id.**+ - If the user passed a short id as an argument (`$ARGUMENTS`), use it.+ - Else, look for a `<session_dir>…</session_dir>` value in your context. If present and `git show-ref --verify --quiet refs/heads/session/<short>` succeeds, that is the current session — use it.+ - Otherwise enumerate `git for-each-ref --format='%(refname:short)' 'refs/heads/session/*'`.+ - none → tell the user there is no harness session to revert, and stop.+ - exactly one → use it.+ - several → list them (short id + base branch via `git config --local --get sessionbase.<short>.branch` + fork date via `git --no-pager log -1 --format=%cr session-base/<short>`) and ask which with `AskUserQuestion`. Because this is destructive, **always** make the user choose explicitly when more than one exists — never silently pick the latest.++2. **Show what will be undone, then confirm.** Run `git --no-pager diff --stat session-base/<short>..session/<short>` and name the base branch it landed on. Then ask the user to confirm with `AskUserQuestion` (yes / no). Do not proceed without an explicit yes.++3. **On confirmation, run the script** from the repo root:+ ```+ node "$(git rev-parse --show-toplevel)/scripts/harness-revert.mjs" <short>+ ```+ (Run it once with `--dry-run` appended first if you want to preview the exact git actions.) Relay the script's output to the user. It reverts this session's promotion merge commit(s) — safe even if other sessions landed on the same branch — then removes the session's worktrees, branches, `sessionbase.<short>` config, and `/tmp` dir.++4. **If the script reports a conflict**, tell the user which step stopped and that another session likely touched the same files; they must resolve it manually before re-running. Never force the revert.diff --git a/.claude/hooks/block-routing-skill.mjs b/.claude/hooks/block-routing-skill.mjsnew file mode 100755index 00000000..8228ab7c--- /dev/null+++ b/.claude/hooks/block-routing-skill.mjs@@ -0,0 +1,44 @@+#!/usr/bin/env node+// PreToolUse(Skill) — keep the heavy `harness-routing` skill out of worker agents.+//+// `harness-routing` is the orchestrator's routing brain (~600 lines: classify,+// dispatch waves, promote, migrate). The chat-orchestrator PRELOADS it (skills:+// frontmatter) and the main thread INVOKES it on demand to route. But developer+// and quality-reviewer also carry the Skill tool (they need writing-migrations,+// resolving-rollback-conflicts, frontend-dev, …), and Claude Code has no native+// per-agent skill denylist — a subagent with the Skill tool can invoke ANY skill.+// This gate is the runtime guard: a developer/quality-reviewer must never load the+// routing logic — it is irrelevant to implementing or reviewing a ticket and would+// just be noise.+//+// merger / planner / documentator have no Skill tool at all, so they can't reach+// it anyway; this only needs to cover the two workers that can.+//+// Preloading via the `skills:` frontmatter does NOT go through the Skill tool, so+// the orchestrator's preload is unaffected. The main thread (no agent_type) and+// the orchestrator are allowed through.++import { readFileSync } from "node:fs";+import { createHookContext } from "./lib/context.mjs";++const input = JSON.parse(readFileSync(0, "utf8"));+const ctx = createHookContext(input, "block-routing-skill");++const skill = input.tool_input?.skill || "";+if (skill !== "harness-routing") process.exit(0);++// Match the base agent type even when the runtime name is suffixed+// (e.g. developer-TASK-001).+const agent = input.agent_type || ctx.agentType || "";+const BLOCKED = ["developer", "quality-reviewer"];+const isBlocked = BLOCKED.some((a) => agent === a || agent.startsWith(`${a}-`));++if (isBlocked) {+ ctx.block({+ reason:+ "The `harness-routing` skill is the orchestrator's routing logic and must NOT be loaded by a developer or quality-reviewer — it is orchestration mechanics, irrelevant to implementing or reviewing a ticket. Follow your own agent instructions and the ticket; do not load harness-routing.",+ log: `BLOCK harness-routing for ${agent}`,+ });+}++process.exit(0);diff --git a/.claude/hooks/session-bootstrap.mjs b/.claude/hooks/session-bootstrap.mjsnew file mode 100755index 00000000..c7a4891b--- /dev/null+++ b/.claude/hooks/session-bootstrap.mjs@@ -0,0 +1,54 @@+#!/usr/bin/env node+// SessionStart — bootstrap the harness session context so the orchestrator (or the+// main thread acting as one) can run on ANY Claude Code surface (CLI, VS Code+// extension, desktop), not only via a launch script that injects+// --append-system-prompt.+//+// It injects `<session_dir>` via hookSpecificOutput.additionalContext, derived+// from the REAL session id the harness assigns. Because every other hook+// (setup-worktree, merger, ...) also keys off that same real session id, the+// alignment invariant `basename(session_dir) == session_id` holds by construction+// — no minted UUID, no forced --session-id.++// Pure env-inspection + additionalContext: no MCP calls (MCP may be disabled in+// hosted/headless runs), no git mutation, never throws.++import { readFileSync, mkdirSync } from "node:fs";+import { createHookContext } from "./lib/context.mjs";++// A managed launcher owns the session context — stay out of its way.+if (process.env.CHAT_SESSION_DIR) process.exit(0);++let input = {};+try {+ input = JSON.parse(readFileSync(0, "utf8"));+} catch {+ // no payload → nothing to inject+ process.exit(0);+}++const ctx = createHookContext(input, "session-bootstrap");++// Use the SAME per-session dir that setup-worktree builds its worktrees under+// (ctx.sessionDir = /tmp/<sanitized repo>/<session_id>, via context.mjs). Its+// BASENAME is the real session id — what the orchestrator turns into+// SESSION_SHORT_ID and WORKTREE_BASE — so the alignment holds and tickets/logs+// share the one session namespace instead of a separate root.+const sessionDir = ctx.sessionDir;+try {+ mkdirSync(sessionDir, { recursive: true });+} catch {+ // best-effort: the orchestrator/agents recreate it as needed+}++ctx.log(`SESSION-BOOTSTRAP session_dir=${sessionDir}`);++process.stdout.write(+ JSON.stringify({+ hookSpecificOutput: {+ hookEventName: "SessionStart",+ additionalContext: `<session_dir>${sessionDir}</session_dir>`,+ },+ }) + "\n",+);+process.exit(0);diff --git a/.claude/hooks/setup-worktree.mjs b/.claude/hooks/setup-worktree.mjsindex d347f691..e3f7f78f 100755--- a/.claude/hooks/setup-worktree.mjs+++ b/.claude/hooks/setup-worktree.mjs@@ -165,8 +165,9 @@ if (// is captured here. Written only when missing: that pins the value at fork time// and never overwrites it with a later, possibly drifted, $REPO HEAD. The key// lives for the whole session — like session/<short> and session-base/<short> it-// is NOT torn down per request (cleanup-worktree leaves it in place); clean-harness-// removes it at session teardown. Keyed by session short id (a config subsection,+// is NOT torn down per request (cleanup-worktree leaves it in place);+// harness-revert.mjs (the /harness-revert command) removes it at session teardown.+// Keyed by session short id (a config subsection,// so any short id is valid).const baseBranchKey = `sessionbase.${ctx.sessionShort}.branch`;if (!git(["config", "--get", baseBranchKey]).stdout.trim()) {diff --git a/.claude/settings.json b/.claude/settings.jsonindex 182c27fa..8912c9b8 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -22,6 +22,17 @@"pr": ""},"hooks": {+ "SessionStart": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/session-bootstrap.mjs",+ "timeout": 10+ }+ ]+ }+ ],"PreToolUse": [{"matcher": "Bash",@@ -61,6 +72,15 @@}]},+ {+ "matcher": "Skill",+ "hooks": [+ {+ "type": "command",+ "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/block-routing-skill.mjs"+ }+ ]+ },{"matcher": "Agent","hooks": [diff --git a/.claude/skills/harness-routing/SKILL.md b/.claude/skills/harness-routing/SKILL.mdnew file mode 100644index 00000000..94f91764--- /dev/null+++ b/.claude/skills/harness-routing/SKILL.md@@ -0,0 +1,568 @@+---+name: harness-routing+description: Routing and orchestration logic for implementing ANY code change in this repo via the agent harness team — classify SIMPLE vs COMPLEX, plan, dispatch developer/reviewer/merger waves in git worktrees, promote to the base branch, generate deploy-time migrations. Load this whenever handling a code-change / feature / bugfix request that should go through the harness (the default for code changes; opt out with #no-harness). Also covers RECOVERY (resume after interruption), ROLLBACK-CONFLICT, MEMORY capture, and SETUP (scaffold a CRM from scratch).+---++# HARNESS ROUTING++You are the **router** for the agent harness — either the `chat-orchestrator` agent (which preloads this skill) or the main thread acting as the orchestrator. This skill is the surface-agnostic routing brain: **how to classify a request, dispatch the agents in `.claude/agents/`, drive the wave, promote, and run the migration round.**++**You never implement, never edit application files, never run merge-class git commands yourself.** You route to agents and parse their output-contract lines (`.claude/rules/agent-output-format.md`).++The harness is the **default** for any code-change request — there is no plan-mode gate, it engages from the start. The user opts out with `#no-harness` ("implement directly" / "without the agent team" / "skip harness"), in which case you implement directly with no agents. "no-harness for this session" keeps it off all session.++## Surface adaptation (read first)++This skill is the **mechanics**. Two concerns are owned by whoever loads it, NOT by this skill:++- **User-facing messaging.** Where this skill says "emit a progress line" or "report to the user", phrase it for your surface. The `chat-orchestrator` persona uses plain, non-technical language in the user's language (no file paths, no `TASK-XXX`, no git terms) and writes `ask-state` cartouches for confirmations; a developer session uses normal technical language and asks confirmations as plain questions. Example phrasings below are guidance, not literal scripts.+- **Data-mode (demo/full).** The MODE-SWITCH intent and the demo→live data switch live in the `chat-orchestrator` persona, never here, and exist only when a `<mode>` tag is present in your context. With no `<mode>` tag — the default — data-mode does not exist: treat applying the migration as the terminal POST-DEV step.++---++## CLASSIFICATION (priority order)++Check in this order — first match wins:++| Category | When | Path |+|---|---|---|+| **RECOVERY** | The user turn contains `<intent>recovery</intent>` (replayed on resume when a previous run was interrupted mid-wave). Takes precedence over everything. | STATE RECOVERY |+| **ROLLBACK-CONFLICT** | The user turn starts with `<intent>rollback-conflict</intent>` — injected when an automatic `git revert` on the base branch hit a conflict. Never typed by a human. Carries `COMMITS_TO_REVERT`. | STATE RB-DEV → RB-MERGE → RB-DONE |+| **SETUP** | The first user turn contains `<intent>setup</intent>`, OR a clear natural-language signal meaning "set up my CRM" / "start from scratch" / "define my business". | STATE SETUP-INTERVIEW → SETUP-PLAN → STATE B → (POST-DEV) |+| **MEMORY** | User asks to remember a way of doing something or document a recurring friction (*"remember this"*, *"turn this into a rule"*) — no code change. | STATE M-DOC → M-DONE (documentator only) |+| **SIMPLE** | 1 cosmetic file OR 1 small field on an existing entity (schema + view + type + form + show, ± i18n labels) OR 1 list filter reusing existing components. No import, no relations, no tests, no new custom component. | STATE S-DEV → (S-REVIEW if diff touches `supabase/`) → S-MERGE → S-DONE → (POST-DEV if a migration is needed) |+| **COMPLEX** | Everything else (2+ fields, cross-entity, import/export, new entity, relations, new custom component, ambiguous) — **default**. | STATE A → B → (POST-DEV) |++> MODE-SWITCH (switch data demo/full) is handled by the `chat-orchestrator` persona (only when a `<mode>` tag is present), not by this skill.++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.++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".++**NOT SIMPLE (push to COMPLEX):** "Add an 'industry' field importable from CSV" (import); "Add a 'manager' relation to contacts" (cross-entity); "Add a tags field with its own table" (new entity); "Add two fields" (multiple); "Add a date-range filter with a calendar picker" (new custom component).++When the SETUP signal is ambiguous (e.g. *"new project"*), do not enter SETUP-INTERVIEW silently — ask the user to confirm once. Only an explicit confirmation or the `<intent>setup</intent>` marker enters SETUP-INTERVIEW.++### Blocking during SETUP-INTERVIEW++While in SETUP-INTERVIEW (skill invoked, `VALIDATED` not yet produced), any other request is bounced with one short message: relay the last pending interview question and end the turn. Do not modify the JSON, do not advance, do not dispatch.++---++## STATE MACHINE — one state per turn (except STATE A → STATE B, which run as one continuous foreground-driven turn)++```+RECOVERY: STATE RECOVERY (one turn) → re-enters the flow the real state implies+SETUP: SETUP-INTERVIEW (turns N..N+K) → SETUP-PLAN → STATE B (foreground waves) → SETUP-DONE → (POST-DEV)+MEMORY: M-DOC (turn N) → M-DONE (turn N+1)+ROLLBACK: RB-DEV (turn N) → RB-MERGE → RB-DONE (always skips POST-DEV)+SIMPLE: S-DEV (turn N) → (S-REVIEW if diff touched supabase/ → BLOCKED?→ S-FIX → S-REVIEW, ≤2 retries)+ → S-MERGE → S-DONE → (if schema diff: PD-RESPOND → PD-MIG-DEV → … → PD-DONE) / (else STATE DONE)+COMPLEX: STATE A (turn N) → STATE B (same turn: Stage 1 develop → Stage 2 review → Stage 3 merge, per wave,+ all foreground; then promotion to the base branch) → (POST-DEV) → STATE DONE++POST-DEV (end of COMPLEX, SETUP, schema-touching SIMPLE), conditional on a schema-relevant diff:+ PD-ASK (turn N) → PD-RESPOND (turn N+1)+ satisfied + non-empty schema diff: → PD-MIG-DEV → PD-MIG-REVIEW → PD-MIG-MERGE → PD-DEPLOY → PD-DONE+ satisfied + empty diff: → STATE DONE+ wants adjustment: → re-enter CLASSIFICATION → PD-ASK again+```++**Do not skip states. Do not combine states.**++---++### STATE RECOVERY — resume after an interruption (`<intent>recovery</intent>`)++The previous process was interrupted (crash or usage limit). **This is a fresh process: assume nothing is running.** Trust disk state, never memory; never reply that work is "already in progress".++**ONE assistant message. Do exactly this:**++1. Derive `SESSION_SHORT_ID` and `TICKETS_DIR` from `<session_dir>` (see Environment).+2. Re-evaluate the real state with read-only Bash inspection:+ - `ls ${TICKETS_DIR}/TASK-*.json 2>/dev/null` — were tickets ever created?+ - For each ticket, `Read` it and note its `status` (planned / in_progress / merged).+ - `git -C $CLAUDE_PROJECT_DIR log --oneline session-base/<SESSION_SHORT_ID>..session/<SESSION_SHORT_ID>` — what's merged on the session branch.+ - `ls <WORKTREE_BASE>/ 2>/dev/null` — which task worktrees exist; for each, `git -C <WORKTREE_BASE>/TASK-XXX status --porcelain` and `git -C <WORKTREE_BASE>/TASK-XXX log --oneline session/<SESSION_SHORT_ID>..HEAD`.+3. Decide from what you found:+ - **No tickets and no worktrees** → nothing started. Treat the quoted original request as brand-new: re-enter CLASSIFICATION.+ - **Tickets exist, ≥1 not `merged`** → resume the COMPLEX/SETUP flow the way STATE B does. Non-merged = `pending`/`planned`/`in_progress` — dispatch ALL of them, respecting wave ordering (only tickets whose `dependencies` are all `merged`). 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-init the per-ticket state note, then enter STATE B. **Never enter POST-DEV while any ticket is not `merged`.**+ - **All tickets `merged` but session branch never promoted** → dispatch the promotion merger (`MODE: promote`) as in STATE B's Promotion block, then go to the next case.+ - **All tickets `merged` AND session branch already promoted** → run `Bash("node \"$CLAUDE_PROJECT_DIR/.claude/scripts/pending-deploys.mjs\" --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")`. Empty + exit 0 → report done + STATE DONE. **Non-zero exit → UNDETERMINED; do NOT claim done — surface the stderr / re-check the session id.** Non-empty → STATE PD-ASK. **Never jump directly to PD-MIG-DEV on resume** — always ask first.+4. One progress line to the user, e.g. *"Picking your changes back up where they stopped."*++**End the turn.** Re-enter the normal flow next turn.++---++### STATE SETUP-INTERVIEW — conduct interview directly (one or more turns)++For SETUP only. No team, no agent dispatch.++**On the first SETUP turn:**+1. Invoke `Skill({skill: "setup-interview"})` — loads the domain list, JSON schema, validation protocol, output format.+2. Follow the skill's startup detection (Read the JSON; fresh / resume / update).+3. Output the first question as a plain message. **End this turn.**++**On every subsequent turn while in SETUP-INTERVIEW** (do NOT re-invoke the skill — already loaded):+1. Apply the user's answer to the current domain section of `$CLAUDE_PROJECT_DIR/docs/project-context.json` (Read → update → Write).+2. Advance to the next pending domain.+3. Output one of: the next question / `VALIDATED` / `FAILED: <reason>`.++If the user message is not an answer (side-request), apply the blocking rule (relay the last question, change nothing).++→ On `VALIDATED`, continue in the SAME turn into STATE SETUP-PLAN — do NOT end the turn.++---++### STATE SETUP-PLAN — dispatch planner with SETUP_MODE=true++Entered immediately after `VALIDATED` (same turn):++1. Dispatch the planner with the setup flag:+ ```+ Agent({+ subagent_type: "planner",+ description: "Scaffolding tickets from validated project context",+ prompt: "Read $CLAUDE_PROJECT_DIR/docs/project-context.json and produce scaffolding tickets per agent rules.\n\nSETUP_MODE=true\nTICKETS_DIR=<absolute path>"+ })+ ```+2. One progress line, e.g. *"Preparing the first tasks for your project…"*++The planner runs in the **foreground** — its result returns this same turn. **Do NOT end the turn**; continue into STATE B and treat it like any wave. After the last wave, enter STATE SETUP-DONE instead of the standard POST-DEV reply.++---++### STATE SETUP-DONE — wrap up the setup++Reached from STATE B's SETUP branch once the last wave is done (after the session branch is promoted, or directly if nothing merged).++1. Build a setup recap, e.g. *"Your CRM is scoped and the first features are in place. You can now ask me for regular changes."*+2. Send it, then enter STATE PD-ASK.++**End.**++---++### STATE M-DOC — MEMORY: dispatch documentator (ONE assistant message)++For MEMORY only. No team, no worktree, no merger.++1. Dispatch ONE `documentator`:+ ```+ Agent({+ subagent_type: "documentator",+ description: "Capture: <one-line summary>",+ prompt: "ROLE: documentator\nTICKETS_DIR: <absolute path>\nUSER_REQUEST: <user's request, verbatim>\nCONTEXT: <session ids, file paths, ADRs the user pointed at — empty if none>\n\nFollow your instructions: pick the least invasive lever, write the artifact under /home/developer/.claude/local/, update the ledger. If you produce a hook, propose the settings.local.json patch in your output — do not apply it."+ })+ ```+2. One progress line, e.g. *"Capturing that..."*++**End this turn.** → STATE M-DONE next turn.++### STATE M-DONE — MEMORY report (next turn)++The documentator's response is in your context. Report to the user:+- artifact created → *"I've captured that as a new rule."*+- output contains a `Wiring required` block → also note one setup step is left to activate it.+- failure → offer to retry.++**End.**++---++### STATE RB-DEV — ROLLBACK-CONFLICT: dispatch developer (ONE assistant message)++Only for `<intent>rollback-conflict</intent>`. No team, no planner.++1. Dispatch ONE `developer` and tell it to load the `resolving-rollback-conflicts` skill. The `BRANCH_NAME: <SESSION_SHORT_ID>/simple` line routes it to the fixed `<base>/simple` worktree. Copy `BASE_BRANCH`, `FAILED_COMMIT`, `COMMITS_TO_REVERT` verbatim from the user turn:+ ```+ Agent({+ subagent_type: "developer",+ description: "Resolve rollback conflict",+ prompt: "ROLE: developer\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\nBASE_BRANCH: <copied>\nFAILED_COMMIT: <copied>\nCOMMITS_TO_REVERT:\n<block copied verbatim>\n\nLoad Skill({skill: \"resolving-rollback-conflicts\"}) and follow it exactly — it replaces the normal ticket workflow."+ })+ ```+2. One progress line, e.g. *"Finishing the rollback..."*++**End this turn.** SubagentStop hooks run validation automatically. → STATE RB-MERGE next turn.++### STATE RB-MERGE — ROLLBACK-CONFLICT: dispatch merger (next turn)++1. If dev returned `FAILED:` → skip merge, go to RB-DONE with failure.+2. On `DONE: branch=…` → dispatch the merger with the ROLLBACK template:+ ```+ Agent({+ subagent_type: "merger",+ description: "Promote rollback branch",+ prompt: "ROLE: merger (ROLLBACK mode — single-shot, no team)\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\n\nFollow the ROLLBACK mode in merger.md: skip Stage A, run ROLLBACK PROMOTION (merge BRANCH_NAME directly into the base branch). Never touch session/<SESSION_SHORT_ID>.\nOutput: \"DONE: ROLLBACK commit=<short sha>\" OR \"FAILED: ROLLBACK <reason>\""+ })+ ```+3. One progress line, e.g. *"Wrapping up..."*++**End this turn.** → STATE RB-DONE next turn.++### STATE RB-DONE — ROLLBACK-CONFLICT report (next turn)++Report, then enter STATE DONE — a full session rollback never triggers a forward migration, so POST-DEV is always skipped:+- `DONE` → *"All changes from this session have been undone."*+- `FAILED` → *"We couldn't fully undo your changes. Some may still be in place — please ask your administrator for help."*++**End.**++---++### STATE S-DEV — SIMPLE: dispatch developer directly (ONE assistant message)++SIMPLE skips the planner and the wave. No team, no `TICKET_FILE`. Dispatch ONE `developer` with the change inline on the shared `<base>/simple` worktree — the `BRANCH_NAME: <SESSION_SHORT_ID>/simple` line routes it there:++```+Agent({+ subagent_type: "developer",+ description: "SIMPLE: <one-line summary>",+ prompt: "ROLE: developer\nCHANGE_REQUEST: <user's request, verbatim>\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\nTICKETS_DIR: <absolute per-session path>\n\nThis is a SIMPLE direct change — no ticket, no planner. Implement the CHANGE_REQUEST on the simple worktree: one cosmetic edit, one single-field change on an existing entity, or one filter reusing existing components. Keep it to that single change — no ADR, no new tests, no migrations. If it needs a planned breakdown (2+ files/entities, a new component, tests, import/export), stop and emit FAILED: out of scope — needs COMPLEX flow."+})+```++One progress line, e.g. *"Working on it..."* **End this turn.** SubagentStop hooks run validation automatically.++→ Next turn: if dev returned `FAILED: out of scope …`, re-enter CLASSIFICATION as COMPLEX (STATE A). Otherwise inspect the worktree directly — do NOT substring-match the dev's free-text `files=[...]`:+```+Bash("cd <WORKTREE_BASE>/simple && git diff --name-only session-base/<SESSION_SHORT_ID>..HEAD | grep -E '^supabase/' || true")+```+- Non-empty (`supabase/` paths) → STATE S-REVIEW.+- Empty → STATE S-MERGE.++### STATE S-REVIEW — SIMPLE: dispatch quality-reviewer (conditional, next turn)++Only when the diff touched `supabase/` (schema, view, RLS) — the hooks can't judge schema-shape or injection risk.++1. If dev returned `FAILED:` → skip review, go to S-DONE with failure.+2. Dispatch ONE `quality-reviewer`:+ ```+ Agent({+ subagent_type: "quality-reviewer",+ description: "SIMPLE review: <one-line summary>",+ prompt: "ROLE: quality-reviewer (SIMPLE mode — single-shot, no team)\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\nTICKETS_DIR: <absolute per-session path>\n\nFollow the SIMPLE-mode workflow in your agent file. Return text only: \"APPROVED\" or \"BLOCKED:\\n- ...\". No SendMessage."+ })+ ```+3. One progress line, e.g. *"Double-checking the database change..."*++**End this turn.** → `APPROVED` → S-MERGE. `BLOCKED:` → S-FIX (a schema-shape issue is never the user's to arbitrate — feed it back; do NOT merge).++### STATE S-FIX — feed the review back to the developer (next turn)++Entered only from S-REVIEW on `BLOCKED:`.++1. **Attempt cap.** If you have already made **2 fix attempts** and the reviewer is still `BLOCKED:`, give up: report a generic failure (no SQL, no file paths) and enter STATE DONE — do NOT merge.+2. Otherwise re-dispatch the **same** developer in the **same** worktree with the findings:+ ```+ Agent({+ subagent_type: "developer",+ description: "Fix DB review findings: <one-line summary>",+ prompt: "ROLE: developer\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\n\nFIX — the database review found problems in your previous commit. Address every point below and commit the fix in the same worktree. Do NOT change anything else.\n<paste the reviewer's BLOCKED: list verbatim>"+ })+ ```+3. One neutral progress line (never expose the technical reason).++**End this turn.** → S-REVIEW again next turn (loop S-REVIEW ⇄ S-FIX, bounded by the cap).++### STATE S-MERGE — SIMPLE: dispatch merger (next turn)++1. `FAILED:` from dev → skip, go to S-DONE with failure.+2. `BLOCKED:` from reviewer → you should not be here; never merge a `BLOCKED:` change.+3. Otherwise dispatch the single-shot SIMPLE merger (Stage A + promotion in one shot):+ ```+ Agent({+ subagent_type: "merger",+ description: "Merge SIMPLE branch <SESSION_SHORT_ID>/simple",+ prompt: "ROLE: merger (SIMPLE mode — single-shot, no team)\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\nWORKTREE_PATH: <WORKTREE_BASE>/simple\n\nFollow the WORKFLOW in merger.md. Use the single-shot columns (Stage A then promotion in one shot).\nOutput: \"DONE: SIMPLE commit=<short sha>\" OR \"FAILED: SIMPLE <reason>\""+ })+ ```+4. One progress line, e.g. *"Wrapping up..."*++**End this turn.** → STATE S-DONE next turn.++### STATE S-DONE — SIMPLE report + POST-DEV check (next turn)++1. `FAILED` from dev or merger → report a generic failure, enter STATE DONE.+2. On `DONE` → run POST-DEV detection: `Bash("node \"$CLAUDE_PROJECT_DIR/.claude/scripts/pending-deploys.mjs\" --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")`. Empty = cosmetic-only, no migration.+3. Build the reply (e.g. *"Done — take a look."*).+4. Branch on detection:+ - Empty → send reply, STATE DONE.+ - Non-empty (schema-relevant) → append the satisfaction question to the reply (do NOT send a separate PD-ASK turn), end the turn, enter STATE PD-RESPOND. The POST-DEV machine (PD-MIG-DEV → … → PD-DONE) runs unchanged.++**End.**++---++### STATE A — PLAN (every COMPLEX request)++1. Read the user request.+2. Dispatch the planner:+ ```+ Agent({+ subagent_type: "planner",+ description: "Plan tickets for: <one-line summary>",+ prompt: "<user need verbatim>\n\nTICKETS_DIR=<absolute path>"+ })+ ```+3. One progress line, e.g. *"Planning it out..."*++The planner runs in the **foreground** — its result returns this same turn. **Do NOT end the turn** — continue into STATE B.++---++### STATE B — WAVE EXECUTION (synchronous, foreground subagents)++For every COMPLEX request (and the continuation right after STATE A / SETUP-PLAN — the planner already ran in the foreground, output is in your context).++**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.++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.++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.++**Per-ticket state note (kept in your working context for this one turn):**+```+TASK-XXX: {+ stage: "DEV" | "REVIEW" | "MERGE" | "DONE" | "FAILED",+ retries: 0..2,+ dev_output: "DONE: branch=... commit=... files=[...]" | null,+ reviews: { quality: "APPROVED" | "REJECTED: ..." | null }+}+```++#### Stage 1 — DEVELOP (concurrent)++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",+ 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)>"+})+```++(No `run_in_background`, no `isolation`, no `name`.)++Substitute the actual ticket id and the concrete `<TICKETS_DIR>` / `<WORKTREE_BASE>` / `<SESSION_SHORT_ID>`. For `BRANCH_NAME`, use the ticket's `branch_name` when it starts with the ticket id (`TASK-XXX-...`); otherwise build `TASK-XXX-<slug>` (short kebab-case from the title). The `setup-worktree` hook rejects any branch not matching `<SESSION_SHORT_ID>/TASK-XXX[-suffix]` — never carry over a planner `feature/...`/`fix/...` prefix. **The `WORKTREE_PATH` and `BRANCH_NAME` lines are required and must follow the template verbatim**: `setup-worktree` runs on THIS dispatch (PreToolUse/Agent), reads `WORKTREE_PATH`/`BRANCH_NAME`/`TASK_ID`, 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"`.++**Never add a `name:` field to any STATE B dispatch.** The Agent tool schema has `additionalProperties: false` with no `name` property, so a `name:` fails input validation before the subagent starts. Use `description:` for labels; foreground-vs-background is controlled solely by `run_in_background` (absent/false → dispatches block).++Emit one short progress line. **Do NOT end the turn.**++When all developers return, parse each last line:+- `DONE: branch=… commit=… files=[…]` → `stage = REVIEW`, store in `dev_output`.+- `FAILED: …` or any other shape → `stage = FAILED`, drop from the wave.++If an `Agent` dispatch *call itself* errors, mark that ticket `{stage: "FAILED", failure_reason: "dispatch error: <message>"}` and keep the others — one dispatch failure never hangs the wave. Same for reviewer/merger dispatch errors.++#### Stage 2 — REVIEW + bounded retry (concurrent reviews, looped)++For every ticket in `REVIEW`, dispatch the quality-reviewer in the foreground. Batch all review-ready tickets into ONE message (reviewers are read-only on separate worktrees):++```+Agent({ subagent_type: "quality-reviewer",+ description: "Review T",+ prompt: "ROLE: quality-reviewer\nTASK_ID: T\nTICKET_FILE: <TICKETS_DIR>/T.json\nWORKTREE_PATH: <WORKTREE_BASE>/T" })+```++Store the verdict in `reviews.quality` and resolve each:+- `APPROVED` → `stage = MERGE`.+- `REJECTED` (malformed reviewer output → treat as `REJECTED`) → increment `retries`. If `retries ≤ MAX_RETRIES` (2): `stage = DEV`, clear `reviews`, **re-develop**. If `retries > MAX_RETRIES`: `stage = FAILED`.++**Re-develop** = one foreground developer dispatch reusing 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), PLUS a trailing line: `RETRY_FEEDBACK=<the reviewer's REJECTED verdict body, verbatim>`.++After re-developing, **re-review** it. **Loop Stage 2 until every still-live ticket is `MERGE` or `FAILED`** — 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 `.git/index.lock`. Dispatch them **one at a time**: one foreground merger per message, wait, then the next. `<branch>` is the `branch=` value from this ticket's stored `dev_output` (NOT the planner's suggestion):++```+Agent({ subagent_type: "merger",+ 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>" })+```++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.)++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++When every ticket of the wave is `DONE` or `FAILED`:+1. **More waves remain** → emit a short summary, then **continue this same turn into Stage 1 of the next wave**. The state note carries forward; new-wave tickets start at `{stage: "DEV", retries: 0}`.+2. **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. Run this read-only check (mirrors `getUnmergedTaskBranches` used by `block-promote-unmerged.mjs`; skips `<SESSION_SHORT_ID>/simple`; fail-closed):+```+Bash("for b in $(git -C $CLAUDE_PROJECT_DIR for-each-ref --format='%(refname:short)' refs/heads/<SESSION_SHORT_ID>); do [ \"$b\" = \"<SESSION_SHORT_ID>/simple\" ] && continue; n=$(git -C $CLAUDE_PROJECT_DIR rev-list --count session/<SESSION_SHORT_ID>..$b 2>/dev/null); { [ -z \"$n\" ] || [ \"$n\" != \"0\" ]; } && echo \"$b: ${n:-unknown} unmerged\"; done")+```+- **Non-empty** → those branches were developed but never merged. For each, resume its normal stages (review if no recorded verdict, then merge), then re-run the check until empty.+- **Empty** → every developed ticket is on the session branch.++Then promote the session branch to the base branch (the branch the session was forked from — both SETUP and COMPLEX). Stage A only put tickets on `session/<SESSION_SHORT_ID>`; nothing has reached the base branch yet.+- **≥ 1 ticket reached `DONE`** → dispatch the promotion merger in the **foreground** and handle its result inline (do NOT run Stage 1–3 transitions for it):+ ```+ Agent({+ subagent_type: "merger",+ description: "Promote session branch to base branch",+ prompt: "ROLE: merger\nMODE: promote\nSESSION_SHORT_ID: <SESSION_SHORT_ID>"+ })+ ```+ - `DONE: PROMOTE commit=…` → SETUP path → STATE SETUP-DONE. COMPLEX path → report one line per ticket, then STATE PD-ASK.+ - `FAILED: PROMOTE promote conflict: files=[…]` → one progress line (*"Synchronising your changes…"*) and STATE PD-PROMOTE-FIX.+ - `FAILED: PROMOTE …` (other) → one failure line and STATE DONE.+- **Every ticket FAILED** → skip promotion. SETUP → STATE SETUP-DONE; COMPLEX → report per-ticket and STATE DONE.++Business-knowledge capture (documentator Mode 2) is spawned at STATE PD-RESPOND on satisfaction (background, output never shows in chat).++#### Interruption & recovery++This whole flow is one long foreground process; a message typed during it is queued and delivered after the process exits. If interrupted (crash or usage limit), the next resume replays `<intent>recovery</intent>` into a fresh process that lands in STATE RECOVERY — the single place recovery happens. Never try to recover from within STATE B.++#### Safety bounds++- `MAX_RETRIES = 2` per ticket (3 developer attempts total). On REJECTED, increment first, then: now > MAX_RETRIES → `stage = FAILED`; otherwise re-develop with `RETRY_FEEDBACK`.+- Malformed agent output (not matching `DONE:`/`FAILED:`/`APPROVED`/`REJECTED:`) → `FAILED` (developer/merger) or `REJECTED` (reviewer) for that stage — never guess intent.+- If a wave can't progress (every live ticket failed on dispatch, or a ticket exhausts retries), don't spin: stop cleanly, carry whatever reached `DONE` into promotion/wrap-up, report what merged and what didn't.++---++### STATE DONE — terminal++Once the wave is complete and no more waves remain, you are in STATE DONE. The turn ends here. Any stray message that arrives after this point is silently ignored.++---++### STATE PD-PROMOTE-FIX — resolve a promotion conflict++Reached when the merger reports `promote conflict`. ONE assistant message:++1. Dispatch a resolver (no team):+ ```+ Agent({+ subagent_type: "developer",+ description: "Resolve session->base-branch promotion conflict",+ prompt: "ROLE: promotion-conflict-resolver (gated $CLAUDE_PROJECT_DIR exception)\nSESSION_SHORT_ID: <id>\nUnder the promotion lock, in $CLAUDE_PROJECT_DIR on the base branch (where the failed promotion left $CLAUDE_PROJECT_DIR checked out), re-run the merge and resolve it honouring BOTH sides, then commit. Run:\ncd $CLAUDE_PROJECT_DIR && flock $CLAUDE_PROJECT_DIR/.promote.lock bash -c 'git merge --no-ff session/<id> || true'\nResolve the conflicting files, then complete the merge with a single locked commit:\nflock $CLAUDE_PROJECT_DIR/.promote.lock bash -c 'git add -A && git commit --no-edit'\nKnown limitation: between the initial merge and this final locked commit, the lock is briefly released while you resolve files; a concurrent promotion in that window is a rare, accepted edge case.\nOutput: RESOLVED: commit=<sha> or FAILED: <reason>. Never modify anything under session/<id>."+ })+ ```+2. (No new user line — the *"Synchronising your changes…"* line was already shown.)++**End this turn.** Next turn:+- `RESOLVED: …` → session branch now promoted. Continue where the conflict interrupted: from PD-MIG-MERGE → PD-DEPLOY; from STATE B's Promotion, SETUP → SETUP-DONE; COMPLEX → one line per ticket, then PD-ASK.+- `FAILED: …` → report a generic finalisation failure and stop.++---++## POST-DEV — satisfaction check + optional migration round++Runs at the end of any flow that produced merged work (STATE B Promotion for COMPLEX, SETUP-DONE, S-DONE), conditional on the session-branch diff touching schema-relevant files. Does NOT run for: MEMORY, ROLLBACK-CONFLICT, cosmetic-only changes (detection empty), or failed waves where nothing merged.++### STATE PD-ASK — satisfaction question (COMPLEX and SETUP flows)++**SIMPLE flows skip this state** — the satisfaction question is embedded in the S-DONE reply and you enter PD-RESPOND directly on the next user turn.++Ask the user whether the changes look right or need adjustment — confirm BEFORE applying anything to their data. (Persona overlay: ask plainly, never mention database/migration/Supabase, and write the `satisfaction` cartouche; a developer surface just asks in text.)++**End this turn.** → PD-RESPOND on the next user turn.++### STATE PD-RESPOND++The user's reply means satisfied / wants-adjustment / ambiguous.++**On satisfaction — capture business knowledge (once, fire-and-forget):** dispatch ONE Mode-2 documentator in the **background** (do NOT wait — it runs while migration/wrap-up proceeds; its output never shows in chat):+```+Agent({+ subagent_type: "documentator",+ description: "Capture business knowledge",+ prompt: "ROLE: documentator (Mode 2)\nSESSION_LOG: <session_dir>/log.jsonl\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nSESSION_DIFF_BASE: session-base/<SESSION_SHORT_ID>..session/<SESSION_SHORT_ID>\nreason: business-knowledge\n\nFollow your Mode 2 instructions: read the session diff (the SESSION_DIFF_BASE two-dot range) and append business-knowledge bullets to $CLAUDE_PROJECT_DIR/MEMORY.md (silently do nothing if there is nothing concrete).",+ run_in_background: true+})+```++Then:+| Meaning | Next |+|---|---|+| Satisfied | (Dispatch the Mode-2 documentator first.) Run `Bash("node \"$CLAUDE_PROJECT_DIR/.claude/scripts/pending-deploys.mjs\" --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")`. Empty + exit 0 → report done, STATE DONE. **Non-zero exit → UNDETERMINED; do NOT claim done — surface the error.** Non-empty → report "saving your changes" and enter STATE PD-MIG-DEV. |+| Wants to adjust / new request | Re-enter CLASSIFICATION (new request, accumulates on session/<SESSION_SHORT_ID>); ask PD-ASK again after. |+| Ambiguous | Re-ask once; stay in PD-RESPOND. |++### STATE PD-MIG-DEV — write the migration++Dispatch ONE developer and tell it to load the `writing-migrations` skill. `BRANCH_NAME: <id>/simple` routes it to the fixed `<base>/simple` worktree:+```+Agent({ subagent_type: "developer",+ description: "Generate migrations from session diff",+ prompt: "ROLE: developer\nSESSION_SHORT_ID: <id>\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <id>/simple\nLoad Skill({skill: \"writing-migrations\"}) and follow it exactly — it replaces the normal ticket workflow. If no schema change, output NO_MIGRATION_NEEDED." })+```+One progress line. **End turn.** SubagentStop hooks run.+→ `NO_MIGRATION_NEEDED` → report done → STATE DONE. Else → STATE PD-MIG-REVIEW.++### STATE PD-MIG-REVIEW — review the SQL++CRITICAL: ONE Agent call only. Dispatch once, end the turn, wait for the result.++Dispatch ONE quality-reviewer with `MODE: migration-review` and the migration file paths. **End turn.**+→ `APPROVED` → STATE PD-MIG-MERGE. `BLOCKED` → re-dispatch the developer with the `writing-migrations` skill (PD-MIG-DEV) with the issues; loop.++### STATE PD-MIG-MERGE — merge + promote++Dispatch the single-shot MIGRATION merger for `<SESSION_SHORT_ID>/simple` (Stage A + promotion):+```+Agent({+ subagent_type: "merger",+ description: "Merge migration branch <SESSION_SHORT_ID>/simple",+ prompt: "ROLE: merger (MIGRATION mode — single-shot, no team)\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\nWORKTREE_PATH: <WORKTREE_BASE>/simple\n\nFollow the WORKFLOW in merger.md. Use the MIGRATION-mode columns (Stage A then promotion in one shot).\nOutput: \"DONE: MIGRATION commit=<short sha>\" OR \"FAILED: MIGRATION <reason>\""+})+```+**End turn.** → `DONE` → STATE PD-DEPLOY. `FAILED`/`promote conflict` → STATE PD-PROMOTE-FIX.++### STATE PD-DEPLOY — apply++One progress line (*"Applying your changes — this can take a moment on first run."*).+`Bash("node \"$CLAUDE_PROJECT_DIR/.claude/scripts/apply-migrations.mjs\"")` (timeout 240000 ms).+→ exit 0 → STATE PD-DONE ("Your changes are saved."). This is the terminal POST-DEV step. (Persona overlay: in demo mode only, branch to the demo→live switch instead; absent a `<mode>` tag, PD-DEPLOY is terminal — never offer a data switch.)+→ Non-zero → STATE PD-DONE with a failure line.++### STATE PD-DONE — POST-DEV wrap++Reply with the user-facing wrap-up, then enter STATE DONE.++---++## NEVER DO++- ❌ `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.+- ❌ 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).+- ❌ Treat malformed agent output as anything other than `FAILED` for that stage.+- ❌ Use the RB-* states for anything other than a `<intent>rollback-conflict</intent>` turn.+- ❌ Dispatch more than 5 tickets in a single STATE B pass — cap at 5, loop the remainder.+- ❌ Write/Edit any file **except** `$CLAUDE_PROJECT_DIR/docs/project-context.json` during SETUP-INTERVIEW.+- ❌ Dispatch a `project-manager` agent during SETUP-INTERVIEW — conduct the interview directly via the `setup-interview` skill.+- ❌ Write/Edit `$CLAUDE_PROJECT_DIR/MEMORY.md` or `$CLAUDE_PROJECT_DIR/adr/*` yourself. Documentator owns MEMORY.md; developer owns adr/ via worktree merges. Read for context, never write.++---++## Environment++- **`<session_dir>`** is injected into your context (by the `session-bootstrap` SessionStart hook, or by an external launcher's `--append-system-prompt`). Everything below derives from it.+- **TICKETS_DIR** = `<session_dir>`. Pass the literal absolute path to every agent (e.g. `/tmp/<repo>/<uuid>`). Do not use `${session_dir}` syntax.+- **SESSION_SHORT_ID** = first dash-segment of `basename(<session_dir>)`. Example: `…/46bc14c5-13fb-498b-…` → `46bc14c5`. Namespaces worktrees and branches so they never collide across sessions.+- **WORKTREE_BASE** = `/tmp/<$CLAUDE_PROJECT_DIR with every "/" replaced by "_">/<SESSION_ID>`, where `<SESSION_ID>` is the full basename of `<session_dir>`. Worktrees are direct children: `<WORKTREE_BASE>/TASK-XXX`, `<WORKTREE_BASE>/simple`, `<WORKTREE_BASE>/_session`. Substitute the concrete path in dispatch prompts — never pass the literal `<WORKTREE_BASE>`. The repository itself stays at `$CLAUDE_PROJECT_DIR`.diff --git a/CLAUDE.md b/CLAUDE.mdindex c34d1b00..76a13c08 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2,24 +2,13 @@# Agent Workflow-Once a plan is approved (`ExitPlanMode`), the main thread does not implement directly — it routes to the agents in `.claude/agents/` (each carries its own full contract). Trigger is *plan approved*, not task size.+Code-change requests are handled by the **agent harness** by default: a team of subagents (planner, developer, quality-reviewer, merger, documentator) that implements the change through a deterministic, foreground pipeline in git worktrees.-## Opting out--Harness routing is the **default**. `#no-harness` (or "implement directly" / "without the agent team" / "skip harness") makes the main thread implement itself, no agents, even after plan approval. "no-harness for this session" keeps it off all session. Irrelevant under `make harness` (orchestrator always routes).--## Routing: SIMPLE vs COMPLEX--The **chat-orchestrator** is the user-facing entry point. It routes, narrates progress, and never implements. It classifies each code change:+**To route a code-change request, load the `harness-routing` skill and follow it.** It is the single source of truth for 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. Each agent's last line is an output contract the others parse (`.claude/rules/agent-output-format.md`).-- **SIMPLE** — one cosmetic edit, OR one single-field change on an existing entity (schema + view + type + form + show), OR one list filter reusing existing components (no import, no relations, no new custom component). The orchestrator skips the planner and the wave: it dispatches ONE `developer` directly with the change request on the shared `<base>/simple` worktree, reviews only if the diff touched `supabase/`, then merges. No planner, no peer review otherwise.-- **COMPLEX** — everything else (default). Runs the full pipeline below.--SIMPLE vs COMPLEX is purely a routing decision the orchestrator owns — the `developer` itself has no modes. The orchestrator also branches away for non-code operational intents: SETUP, MODE-SWITCH, MEMORY, ROLLBACK-CONFLICT, RECOVERY.--## The COMPLEX pipeline+## Opting out-planner (tickets JSON + waves) → developer per ticket (implements + commits in a worktree; no SQL migrations, deploy-time only) → quality-reviewer (code + security + QA) → merger (`git merge --no-ff` only; Stage A per ticket, then one `MODE: promote` to the base branch under `flock`) → documentator (appends to `MEMORY.md`). Agents run as **foreground** subagents in one synchronous turn; each agent's last line is an output contract the orchestrator parses (`.claude/rules/agent-output-format.md`).+`#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.## Agentsdiff --git a/makefile b/makefileindex f18ae9b1..1d58dc3c 100644--- a/makefile+++ b/makefile@@ -159,12 +159,6 @@ update-changelog: ## Update the changelog with the unreleased changes (ran automstorybook: ## start storybooknpm run storybook-harness: ## run the agent harness interactively (pass REQUEST="..." to pre-fill)- scripts/launch-harness.sh "$(REQUEST)"--clean-harness: ## clean up the agent harness session- scripts/clean-harness.sh-watch: ## live monitor of the most recent agent session (agents, hooks, diagnosis)node scripts/harness-monitor.mjs --watchdiff --git a/scripts/clean-harness.sh b/scripts/clean-harness.shdeleted file mode 100755index 8e93180e..00000000--- a/scripts/clean-harness.sh+++ /dev/null@@ -1,216 +0,0 @@-#!/usr/bin/env bash-#-# Clean up Atomic CRM agent-workflow session artifacts.-#-# Removes everything the SIMPLE/COMPLEX agent pipeline leaves behind:-# - session git worktrees under /tmp/<repo-slug>/-# - branches checked out in those worktrees, plus session/* and session-base/*-# - the sessionbase.* git config keys recording each session's fork-base branch-# - the .promote.lock promotion lock file-# - the /tmp/<repo-slug> session directory tree-#-# It NEVER deletes the current branch, main, or any branch not tied to a-# session worktree.-#-# By default it also lands you back where you launched the harness from:-# - checks out the branch you started on (a safety net, in case the harness or-# a drifted session left you on a different branch),-# - hard-resets that branch to the pre-harness commit (dropping every commit-# the harness promoted onto it — promotion now targets the start branch, not-# main),-# - restores main to origin/main as a backstop (older sessions promoted onto-# main; current sessions promote onto the start branch instead).-#-# The start branch + commit are read from .git/clean-harness-return, written by-# launch-harness.sh at launch (it survives the /tmp cleanup). If that record is-# missing, it falls back to the most recent session-base anchor and resets the-# current branch in place.-#-# Usage:-# scripts/clean-harness.sh # clean + reset to latest harness-start anchor-# scripts/clean-harness.sh --no-reset # clean session artifacts only, no reset-# scripts/clean-harness.sh --dry-run # print what would happen, change nothing-#-set -euo pipefail--REPO_ROOT="$(git rev-parse --show-toplevel)"-cd "$REPO_ROOT"--DRY_RUN=false-NO_RESET=false-RESET_REF=""-for arg in "$@"; do- case "$arg" in- --dry-run|-n) DRY_RUN=true ;;- --no-reset) NO_RESET=true ;;- *) echo "Unknown argument: $arg" >&2; exit 2 ;;- esac-done--CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"-HEAD_SHA="$(git rev-parse HEAD)"--# Preferred target: the launch record written by launch-harness.sh, which captures-# the branch + commit you started from (the exact pre-harness anchor). It lives-# under .git/ so it survives the /tmp cleanup below.-RETURN_FILE="$REPO_ROOT/.git/clean-harness-return"-START_BRANCH=""-if [[ -z "$RESET_REF" ]] && ! $NO_RESET && [[ -f "$RETURN_FILE" ]]; then- IFS=$'\t' read -r START_BRANCH RESET_REF < "$RETURN_FILE" || true- if [[ -n "$RESET_REF" ]] && ! git rev-parse --verify --quiet "${RESET_REF}^{commit}" >/dev/null; then- echo "Warning: recorded start commit ${RESET_REF:0:12} no longer exists; ignoring record." >&2- RESET_REF=""- START_BRANCH=""- fi-fi--# Fallback target: the most recent harness-start anchor.-#-# setup-worktree.mjs records each harness run's starting point as a-# `session-base/<id>` branch pointing at HEAD before any agent work. We pick the-# anchor with the most commits in its history (= started latest) among those-# that are a STRICT ancestor of HEAD, so the agent commits stacked on top get-# dropped while pre-run history is kept.-if [[ -z "$RESET_REF" ]] && ! $NO_RESET; then- best_count=-1- while IFS= read -r ref; do- [[ -z "$ref" ]] && continue- sha="$(git rev-parse "$ref")"- [[ "$sha" == "$HEAD_SHA" ]] && continue # not strict- git merge-base --is-ancestor "$sha" "$HEAD_SHA" || continue # must be ancestor- count="$(git rev-list --count "$sha")"- if (( count > best_count )); then- best_count=$count- RESET_REF="$sha"- fi- done < <(git for-each-ref --format='%(refname:short)' 'refs/heads/session-base/*')-- if [[ -z "$RESET_REF" ]]; then- echo "Warning: no session-base anchor (strict ancestor of HEAD) found; skipping reset." >&2- echo " Use --no-reset to silence this." >&2- fi-fi--# /tmp base: repo path with every "/" replaced by "_" (see worktree-scope rule).-SLUG="${REPO_ROOT//\//_}"-TMP_BASE="/tmp/${SLUG}"--say() { printf '%s\n' "$*"; }-do_run() {- if $DRY_RUN; then- say "[dry-run] $*"- else- "$@"- fi-}--say "==> Repo: $REPO_ROOT"-say "==> Tmp base: $TMP_BASE"-say "==> Branch: $CURRENT_BRANCH"-$DRY_RUN && say "==> Mode: DRY-RUN (no changes)"--# 1. Collect branches checked out in /tmp session worktrees (before removal).-mapfile -t SESSION_WT_BRANCHES < <(- git worktree list --porcelain | awk -v base="$TMP_BASE/" '- /^worktree / { wt = $2 }- /^branch / { sub("refs/heads/", "", $2); if (index(wt, base) == 1) print $2 }- '-)--# 2. Remove every worktree under the tmp base.-say "==> Removing session worktrees..."-while IFS= read -r wt; do- [[ -z "$wt" ]] && continue- say " - $wt"- do_run git worktree remove --force "$wt"-done < <(git worktree list --porcelain | awk -v base="$TMP_BASE/" '/^worktree / && index($2, base) == 1 { print $2 }')-do_run git worktree prune--# 3. Delete session branches: those from /tmp worktrees + session/* + session-base/*.-say "==> Deleting session branches..."-{- printf '%s\n' "${SESSION_WT_BRANCHES[@]:-}"- git for-each-ref --format='%(refname:short)' refs/heads/session refs/heads/session-base 2>/dev/null || true- git for-each-ref --format='%(refname:short)' 'refs/heads/session/*' 'refs/heads/session-base/*'-} | sort -u | while IFS= read -r br; do- [[ -z "$br" ]] && continue- [[ "$br" == "$CURRENT_BRANCH" ]] && { say " ! skip current branch: $br"; continue; }- if git show-ref --verify --quiet "refs/heads/$br"; then- say " - $br"- do_run git branch -D "$br"- fi-done--# 3b. Remove recorded session fork-base config keys (sessionbase.<short>.branch,-# written by setup-worktree.mjs and read by the promotion merger). Every session-# branch is being deleted above, so a stray key would only outlive its branch and-# accumulate in .git/config. `--get-regexp` exits non-zero with no matches, hence-# the `|| true` guard under `set -e`.-say "==> Removing session base-branch config keys..."-{ git config --local --get-regexp '^sessionbase\.' 2>/dev/null || true; } \- | awk '{ sub(/\.branch$/, "", $1); print $1 }' \- | sort -u \- | while IFS= read -r subsection; do- [[ -z "$subsection" ]] && continue- say " - $subsection"- do_run git config --local --remove-section "$subsection" 2>/dev/null || true- done--# 4. Remove the promotion lock.-if [[ -f "$REPO_ROOT/.promote.lock" ]]; then- say "==> Removing .promote.lock"- do_run rm -f "$REPO_ROOT/.promote.lock"-fi--# 5. Remove the /tmp session directory tree.-if [[ -d "$TMP_BASE" ]]; then- say "==> Removing $TMP_BASE"- do_run rm -rf "$TMP_BASE"-fi--# 6. Land back on the start branch + commit, and restore main.-if [[ -n "$RESET_REF" ]]; then- # 6-pre. Safety net: never let the hard reset destroy uncommitted work. If the- # working tree has tracked changes, stash them first so a surprise is always- # recoverable with `git stash pop`. Untracked files are left alone (reset does- # not touch them).- if [[ -n "$(git status --porcelain --untracked-files=no)" ]]; then- say "==> Stashing uncommitted changes before reset (recover with: git stash pop)"- do_run git stash push -m "clean-harness safety stash"- fi-- # 6a. Switch off whatever the harness left us on (e.g. main) onto the branch- # we started from.- if [[ -n "$START_BRANCH" && "$START_BRANCH" != "$CURRENT_BRANCH" ]]; then- if git show-ref --verify --quiet "refs/heads/$START_BRANCH"; then- say "==> Checking out $START_BRANCH"- do_run git checkout "$START_BRANCH"- else- say " ! start branch '$START_BRANCH' no longer exists; staying on $CURRENT_BRANCH"- START_BRANCH=""- fi- fi- TARGET_BRANCH="${START_BRANCH:-$CURRENT_BRANCH}"-- # 6b. Restore main to origin/main (undo the merge the harness made on main),- # unless main is the branch we are landing on.- if [[ "$TARGET_BRANCH" != "main" ]] && git show-ref --verify --quiet refs/heads/main; then- if git rev-parse --verify --quiet "origin/main^{commit}" >/dev/null; then- say "==> Restoring main to origin/main"- do_run git branch -f main origin/main- else- say " ! origin/main not found; leaving main untouched"- fi- fi-- # 6c. Reset the start branch to the pre-harness commit.- say "==> Resetting $TARGET_BRANCH to $RESET_REF"- do_run git reset --hard "$RESET_REF"-- # 6d. Consume the launch record.- if [[ -f "$RETURN_FILE" ]]; then- do_run rm -f "$RETURN_FILE"- fi-fi--say "==> Done."diff --git a/scripts/harness-monitor.mjs b/scripts/harness-monitor.mjsindex d206d8d5..30a4fdaf 100755--- a/scripts/harness-monitor.mjs+++ b/scripts/harness-monitor.mjs@@ -41,8 +41,6 @@ const CLAUDE_PROJ = join("projects",REPO.replace(/\//g, "-"),);-const HARNESS_ROOT = "/tmp/atomic-crm-harness";-// A session id is a worktree-base subdir that has a hooks.log. Test fixtures// (td-1, td-2, …) are skipped — they are not real sessions.function listSessions() {@@ -63,7 +61,9 @@ function sessionPaths(id) {hooksLog: join(base, "hooks.log"),mainTranscript: join(CLAUDE_PROJ, `${id}.jsonl`),subagentsDir: join(CLAUDE_PROJ, id, "subagents"),- ticketDirs: [join(HARNESS_ROOT, id), join(base, "tickets")],+ // Tickets land in the session dir itself (TICKETS_DIR = session_dir = base);+ // <base>/tickets is the legacy fallback layout.+ ticketDirs: [base, join(base, "tickets")],};}@@ -643,7 +643,7 @@ const sessionId = valueOf("--session") || listSessions()[0]?.id;if (!sessionId) {console.error(red(- `No session found under ${WORKTREE_ROOT}. Start the harness first (make harness).`,+ `No session found under ${WORKTREE_ROOT}. Start a harness session first (ask Claude Code for a change).`,),);process.exit(1);diff --git a/scripts/harness-revert.mjs b/scripts/harness-revert.mjsnew file mode 100755index 00000000..9903064f--- /dev/null+++ b/scripts/harness-revert.mjs@@ -0,0 +1,194 @@+#!/usr/bin/env node+//+// Per-session revert for the agent harness.+//+// Undoes ONE harness session's promoted work and removes its artifacts, leaving+// every other (possibly parallel) session untouched. Replaces a global hard-reset:+// instead of resetting the branch to a single fork anchor (which would wipe a+// parallel session that landed on the same branch), it reverts only THIS session's+// promotion merge commits, keyed by SESSION_SHORT_ID.+//+// Driven by the `/harness-revert` slash command (portable across CLI / VS Code+// extension / desktop), which resolves the short id and confirms before calling+// this. It can also be run directly.+//+// How a session lands on the base branch: the merger promotes with+// git merge --no-ff session/<short> -m "merge(session): <short>"+// (see .claude/agents/merger.md, Stage B). So this session's footprint on the base+// branch is exactly the merge commits whose subject is "merge(session): <short>".+//+// Usage:+// scripts/harness-revert.mjs <SESSION_SHORT_ID> # revert + clean up+// scripts/harness-revert.mjs <SESSION_SHORT_ID> --dry-run # print, change nothing+//+import { spawnSync } from "node:child_process";+import { existsSync, readdirSync, rmSync } from "node:fs";+import { join } from "node:path";++const argv = process.argv.slice(2);+const DRY_RUN = argv.includes("--dry-run") || argv.includes("-n");+const SHORT = argv.find((a) => !a.startsWith("-"));++const log = (msg) => process.stdout.write(`${msg}\n`);+const err = (msg) => process.stderr.write(`${msg}\n`);++if (!SHORT) {+ err("usage: harness-revert.mjs <SESSION_SHORT_ID> [--dry-run]");+ process.exit(2);+}++// Run git, capturing output. Returns { code, out, err }.+function git(args) {+ const res = spawnSync("git", args, { encoding: "utf8" });+ return {+ code: res.status ?? (res.error ? 1 : 0),+ out: (res.stdout || "").trim(),+ err: (res.stderr || "").trim(),+ };+}++// Run a mutating git command, honouring --dry-run.+function gitRun(args) {+ if (DRY_RUN) {+ log(`[dry-run] git ${args.join(" ")}`);+ return { code: 0, out: "", err: "" };+ }+ return git(args);+}++// Repo root (authoritative via git; falls back to env/cwd).+const top = git(["rev-parse", "--show-toplevel"]);+const REPO_ROOT =+ (top.code === 0 && top.out) ||+ process.env.CLAUDE_PROJECT_DIR ||+ process.cwd();+process.chdir(REPO_ROOT);++const CURRENT_BRANCH = git(["rev-parse", "--abbrev-ref", "HEAD"]).out;+const BASE_BRANCH = git([+ "config",+ "--local",+ "--get",+ `sessionbase.${SHORT}.branch`,+]).out;++log(`==> Session: ${SHORT}`);+log(`==> Base branch: ${BASE_BRANCH || "(unknown — cleanup only)"}`);+if (DRY_RUN) log("==> Mode: DRY-RUN (no changes)");++// 1. Find this session's promotion merge commits on the base branch (newest+// first, so reverting in order unwinds the stack cleanly).+let merges = [];+if (+ BASE_BRANCH &&+ git(["show-ref", "--verify", "--quiet", `refs/heads/${BASE_BRANCH}`]).code ===+ 0+) {+ const subject = `merge(session): ${SHORT}`;+ merges = git(["log", "--merges", "--format=%H%x09%s", BASE_BRANCH])+ .out.split("\n")+ .filter(Boolean)+ .map((line) => line.split("\t"))+ .filter(([, subj]) => subj === subject)+ .map(([sha]) => sha);+}++// 2. Revert each promotion merge. `-m 1` keeps the base-branch side and backs out+// everything the session merged in. Abort + report on conflict (a parallel+// session may have touched the same files) — the user resolves, like the+// resolving-rollback-conflicts flow.+if (merges.length === 0) {+ log(+ `==> No promotion merge found for session ${SHORT} — nothing to revert (cleanup only).`,+ );+} else {+ if (BASE_BRANCH && CURRENT_BRANCH !== BASE_BRANCH) {+ err(+ `!! You are on '${CURRENT_BRANCH}' but session ${SHORT} promoted onto '${BASE_BRANCH}'.`,+ );+ err(` Switch to it first: git checkout ${BASE_BRANCH}`);+ process.exit(1);+ }+ // Never let a revert clobber uncommitted work.+ if (git(["status", "--porcelain", "--untracked-files=no"]).out) {+ log("==> Stashing uncommitted changes (recover with: git stash pop)");+ gitRun(["stash", "push", "-m", `harness-revert ${SHORT} safety stash`]);+ }+ for (const sha of merges) {+ log(`==> Reverting promotion merge ${sha.slice(0, 12)}`);+ const r = gitRun(["revert", "--no-edit", "-m", "1", sha]);+ if (r.code !== 0) {+ git(["revert", "--abort"]);+ err(+ `!! Revert hit a conflict on ${sha.slice(0, 12)} (another session may have touched the same files).`,+ );+ err(+ " Resolve it manually, then re-run. Aborted before cleanup — nothing was removed.",+ );+ process.exit(1);+ }+ }+}++// 3. Remove this session's worktrees (matched by their checked-out branch, since+// the worktree path carries the full session id we don't have here).+const worktrees = [];+{+ const lines = git(["worktree", "list", "--porcelain"]).out.split("\n");+ let wt = "";+ for (const line of lines) {+ if (line.startsWith("worktree ")) wt = line.slice("worktree ".length);+ else if (line.startsWith("branch ")) {+ const br = line.slice("branch refs/heads/".length);+ if (br === `session/${SHORT}` || br.startsWith(`${SHORT}/`))+ worktrees.push(wt);+ }+ }+}+for (const wt of worktrees) {+ log(`==> Removing worktree ${wt}`);+ gitRun(["worktree", "remove", "--force", wt]);+}+gitRun(["worktree", "prune"]);++// 4. Delete this session's branches (task/simple, integration, fork anchor).+const branches = git([+ "for-each-ref",+ "--format=%(refname:short)",+ `refs/heads/${SHORT}/*`,+ `refs/heads/session/${SHORT}`,+ `refs/heads/session-base/${SHORT}`,+])+ .out.split("\n")+ .filter(Boolean);+for (const br of branches) {+ if (br === CURRENT_BRANCH) {+ log(` ! skip current branch: ${br}`);+ continue;+ }+ log(`==> Deleting branch ${br}`);+ gitRun(["branch", "-D", br]);+}++// 5. Remove the fork-base config subsection.+log(`==> Removing config sessionbase.${SHORT}`);+gitRun(["config", "--local", "--remove-section", `sessionbase.${SHORT}`]);++// 6. Remove this session's /tmp dir(s). Worktree base is /tmp/<slug>/<full-id>;+// the full id starts with the short id, so match on it.+const slug = REPO_ROOT.replace(/\//g, "_");+const tmpBase = `/tmp/${slug}`;+if (existsSync(tmpBase)) {+ for (const name of readdirSync(tmpBase)) {+ if (!name.startsWith(SHORT)) continue;+ const dir = join(tmpBase, name);+ log(`==> Removing session dir ${dir}`);+ if (DRY_RUN) log(`[dry-run] rm -rf ${dir}`);+ else rmSync(dir, { recursive: true, force: true });+ }+}++// NOTE: .promote.lock is intentionally left in place — it is shared across+// sessions and removing it could break a concurrent promotion's mutual exclusion.++log("==> Done.");diff --git a/scripts/launch-harness.sh b/scripts/launch-harness.shdeleted file mode 100755index 31f4aa59..00000000--- a/scripts/launch-harness.sh+++ /dev/null@@ -1,65 +0,0 @@-#!/usr/bin/env bash-#-# Launch the chat-orchestrator agent locally-#-#-# Usage:-# scripts/launch-harness.sh ["CRM change request"]-#-# The request is optional: pass it to pre-fill the first message, or omit it and-# type your request once the session opens.--set -euo pipefail--# Capture the optional request before we touch the positional parameters.-REQUEST="$*"--# Run from the repo root so CLAUDE_PROJECT_DIR and the hook-computed worktree-# paths line up.-REPO="$(git rev-parse --show-toplevel)"-cd "$REPO"--# Record the branch + commit we start from so `make clean-harness` can land us-# back here afterwards. The harness checks out the base branch (the branch you-# started on) to promote merged work, which would otherwise leave you stranded on-# it with your branch behind. Stored under .git/ so it survives the /tmp session-# cleanup. Detached HEAD → empty branch field (clean-harness then just resets in place).-START_BRANCH="$(git symbolic-ref --short HEAD 2>/dev/null || true)"-START_SHA="$(git rev-parse HEAD)"-printf '%s\t%s\n' "$START_BRANCH" "$START_SHA" > "$REPO/.git/clean-harness-return"--# Mint a fresh session id and build the session dir from it. The hooks-# (setup-worktree, merger, ...) derive the worktree base from the process's real-# session id, while the orchestrator derives WORKTREE_BASE from-# basename(session_dir) -- they only agree when basename(session_dir) == the-# session id, hence --session-id below points at the same UUID.-UUID="$(uuidgen 2>/dev/null | tr 'A-Z' 'a-z' || cat /proc/sys/kernel/random/uuid)"-SAN="$(printf '%s' "$REPO" | sed 's#/#_#g')"-SESSION_DIR="/tmp/atomic-crm-harness/${UUID}"-mkdir -p "$SESSION_DIR"--echo "Harness session"-echo " session id: $UUID"-echo " session dir: $SESSION_DIR"-echo " worktree base: /tmp/${SAN}/${UUID} (created lazily by the setup-worktree hook)"-echo " hooks log: /tmp/${SAN}/${UUID}/hooks.log"-echo--# Build the claude argument list. The request, if any, is passed as the first-# message (positional prompt); otherwise the session starts blank.-ARGS=(- --agent chat-orchestrator- --session-id "$UUID"- --permission-mode auto- --append-system-prompt "<session_dir>${SESSION_DIR}</session_dir>"-)-if [ -n "$REQUEST" ]; then- ARGS+=("$REQUEST")-fi--exec env \- CLAUDE_PROJECT_DIR="$REPO" \- CHAT_SESSION_DIR="$SESSION_DIR" \- DISABLE_AUTOUPDATER=1 \- CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 \- claude "${ARGS[@]}"