Skip to content

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

merge "developer" adn "simple-developer"

erwanMarmelab5d5dec016698
diff --git a/.claude/agents/chat-orchestrator.md b/.claude/agents/chat-orchestrator.md
index fb42cb20..187d722e 100644
--- a/.claude/agents/chat-orchestrator.md
+++ b/.claude/agents/chat-orchestrator.md
@@ -63,12 +63,11 @@ 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 S-DEV (rollback variant) → STATE S-MERGE → STATE S-DONE (rollback variant) |
+| **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 was written) |
-| **COMPLEX** | everything else (2+ fields, cross-entity, import/export, new entity, relations, new custom component, ambiguous) — **default** | STATE A → B → (POST-DEV) |
+| **CODE-CHANGE** | Any request that changes the CRM code or schema — cosmetic tweak, single field, filter, new entity, relation, import/export, anything. **The default category.** Always goes through the full pipeline (plan → wave → review → merge), regardless of size. | 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"*),
@@ -76,27 +75,13 @@ 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.
-When in doubt between SIMPLE and COMPLEX:
-- 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 only applies when the user explicitly asks to capture a pattern — not for code changes.
-
-**SIMPLE examples:**
-- "Rename the Login button to 'Sign in'"
-- "Add a 'birthday' field to contacts" → migration + view + type + ContactInputs + ContactShow
-- "Add a localized 'priority' field to deals" → migration + view + type + DealInputs + DealShow + i18n labels in `englishCrmMessages.ts` / `frenchCrmMessages.ts`
-- "Remove the 'fax' field on companies"
-- "Hide the export button"
-- "Add a 'this month' filter to the contacts list" → one `<ToggleFilterButton>` in `ContactListFilter.tsx`
-- "Filter deals by amount above 10k" → one toggle in `DealListFilter.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
+There is **no SIMPLE-vs-COMPLEX triage** any more: every code or schema change —
+a one-line label rename just as much as a new entity with relations — runs the
+same pipeline (planner → developer wave → quality-reviewer → merger). The planner
+decomposes the request into 1..N tickets; a tiny change is simply a one-ticket
+wave. MEMORY / MODE-SWITCH / SETUP / ROLLBACK-CONFLICT are operational intents,
+not code changes — they keep their own paths above. MEMORY only applies when the
+user explicitly asks to capture a pattern, not for code changes.
When the NL signal for SETUP is ambiguous (e.g. user typed *"new project"*
without the explicit button click), **do not** enter SETUP-INTERVIEW
@@ -131,25 +116,18 @@ SETUP: STATE SETUP-INTERVIEW (turn N..N+K)
→ (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)
-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)
- (ROLLBACK-CONFLICT uses the same S-* path
- with a rollback-specific prompt and always
- skips POST-DEV — see STATE S-DEV / S-DONE below.)
-COMPLEX: STATE A (turn N) → STATE B (same turn, synchronous waves:
+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.)
+CODE-CHANGE: STATE A (turn N) → STATE B (same turn, synchronous waves:
Stage 1 develop → Stage 2 review → Stage 3 merge,
per wave, all foreground; then promotion to main)
→ (POST-DEV check — see below)
→ STATE DONE
-POST-DEV (at the end of COMPLEX, SETUP, and schema-touching SIMPLE requests):
- COMPLEX/SETUP only: STATE PD-ASK (turn N) → STATE PD-RESPOND (turn N+1)
- SIMPLE with schema diff: skips PD-ASK (satisfaction question already sent in S-DONE)
- → STATE PD-RESPOND (next user turn)
+POST-DEV (at the end of every CODE-CHANGE and SETUP request):
+ 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
@@ -177,14 +155,14 @@ 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 (read-only Bash; same kind of inspection STATE S-DEV already does):
- - `ls ${TICKETS_DIR}/TASK-*.json 2>/dev/null` — were COMPLEX tickets ever created?
+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 (it may be SIMPLE, COMPLEX, etc.).
- - **Tickets exist, at least one not `merged`** → resume the COMPLEX/SETUP flow the way STATE B does (no team — 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`.**
+ - **No ticket files and no worktrees** → nothing was started. Treat the quoted original request as a brand-new request: re-enter CLASSIFICATION with it (CODE-CHANGE, SETUP, etc.).
+ - **Tickets exist, at least one not `merged`** → resume the CODE-CHANGE/SETUP flow the way STATE B does (no team — synchronous foreground dispatch). Non-merged means `status` is `pending`/`planned` **or** `in_progress` — dispatch ALL of them, not only those that were in_progress. Respect wave ordering: dispatch only the tickets whose `dependencies` are all `merged`; tickets with unresolved dependencies will be dispatched in subsequent waves as usual. Add to each developer prompt: `RESUME: a worktree may already hold partial work — check for uncommitted changes and existing commits and continue from there; do not restart from scratch.` Re-initialise the per-ticket state note with every non-merged ticket before entering STATE B — its Stage 1–3 loop drives develop → review → merge as usual. **Never enter POST-DEV while any ticket is not `merged`.**
- **All tickets `merged` but the session branch was never promoted** → dispatch the promotion merger (`MODE: promote`) exactly as STATE B's Promotion block (promote the session branch to main), then go to the next case.
- **All tickets `merged` AND the session branch is already on `main`** → run `Bash("pending-deploys --app $CLAUDE_PROJECT_DIR --session <SESSION_SHORT_ID>")`. Empty output → reply "Great, everything's set." + STATE DONE. Non-empty → enter **STATE PD-ASK** (the open satisfaction question). **Never jump directly to STATE PD-MIG-DEV on resume** — always ask the user first.
4. One text line to the user in their language: e.g. *"Picking your changes back up where they stopped."*
@@ -242,8 +220,8 @@ Entered immediately after `VALIDATED` in the same turn (no user message needed):
The planner runs in the **foreground** — its result returns in this same turn.
**Do NOT end the turn**; when it returns, continue straight into the standard
-STATE B and treat it like any COMPLEX wave (synchronous, foreground). After the
-last wave finishes, enter STATE SETUP-DONE instead of running the COMPLEX POST-DEV
+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.
---
@@ -325,137 +303,51 @@ Reply to user in plain language, in their language:
---
-### STATE S-DEV — SIMPLE dispatch simple-developer (ONE assistant message)
-
-For SIMPLE and ROLLBACK-CONFLICT. No team, no planner, no skill on the orchestrator's side.
+### STATE RB-DEV — ROLLBACK-CONFLICT dispatch developer (ONE assistant message)
-The user turn determines which prompt template to use:
+Entered only for a `<intent>rollback-conflict</intent>` user turn. No team, no planner, no skill on the orchestrator's side.
-- **Regular SIMPLE** (cosmetic change): use the CHANGE_REQUEST template below.
-- **ROLLBACK-CONFLICT** (user turn starts with `<intent>rollback-conflict</intent>`): use the ROLLBACK_CONFLICT template below. Copy `BASE_BRANCH`, `FAILED_COMMIT`, and the `COMMITS_TO_REVERT` block verbatim from the user turn.
-
-1. Dispatch ONE `simple-developer` agent (no `team_name`):
-
- **SIMPLE template**:
+1. Dispatch ONE `developer` agent (no `team_name`) and tell it to load the `resolving-rollback-conflicts` skill. The `BRANCH_NAME: <SESSION_SHORT_ID>/ops` line is what routes the dispatch to the fixed `<base>/ops` 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: "simple-developer",
- description: "SIMPLE: <one-line summary>",
- prompt: "ROLE: simple-developer\nCHANGE_REQUEST: <user's request, verbatim>\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <SESSION_SHORT_ID>/simple\nTICKETS_DIR: <absolute per-session path>"
- })
- ```
-
- **ROLLBACK_CONFLICT template**:
- ```
- Agent({
- subagent_type: "simple-developer",
+ subagent_type: "developer",
description: "Resolve rollback conflict",
- prompt: "ROLE: simple-developer\nMODE: ROLLBACK_CONFLICT\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>"
+ prompt: "ROLE: developer\nWORKTREE_PATH: <WORKTREE_BASE>/ops\nBRANCH_NAME: <SESSION_SHORT_ID>/ops\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:
- - SIMPLE: *"Working on it..."*
- - ROLLBACK_CONFLICT: *"Finishing the rollback..."*
-
-**End this turn.** The simple-developer runs setup + edit + commit, then stops. SubagentStop hooks (typecheck, prettier, unit tests, e2e — wired with matcher `simple-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.
-
-→ On next turn: inspect the worktree directly — do NOT substring-match the dev's free-text `files=[...]` (paths like `SupabaseStatus.tsx` would false-trigger; omissions would false-skip):
- ```
- Bash("cd <WORKTREE_BASE>/simple && git diff --name-only $(git merge-base main HEAD)..HEAD | grep -E '^supabase/' || true")
- ```
- - Non-empty output (one or more paths starting with `supabase/`) → enter STATE S-REVIEW.
- - Empty output → enter STATE S-MERGE.
-
----
-
-### STATE S-REVIEW — SIMPLE dispatch quality-reviewer (conditional, next turn)
-
-Only entered when the simple-developer's diff touched `supabase/` (raw SQL, migration, 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` agent (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 workflow in your agent file. Apply Part A.6b (view migrations), Part B.1 (RLS), Part B.3 (injection in raw SQL). Return text only: \"APPROVED\" or \"BLOCKED:\\n- ...\". No SendMessage."
- })
- ```
-3. One text line: *"Double-checking the database change..."*
-
-**End this turn.** The reviewer reads the worktree diff and returns text.
-
-→ On next turn:
-- `APPROVED` → STATE S-MERGE.
-- `BLOCKED:` → **STATE S-FIX** — the user must NEVER see a schema-shape / migration issue. Feed it back to the developer; do NOT merge, do NOT surface it to the user.
-
----
+2. One text line in the user's language: *"Finishing the rollback..."*
-### STATE S-FIX — feed the review back to the developer (next turn)
+**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.
-Entered only from STATE S-REVIEW on `BLOCKED:`. A database-shape problem (view column order, RLS, raw-SQL injection…) is the developer's to fix, not the user's to arbitrate — the loop stays silent.
-
-1. **Attempt cap.** Look back in your own context and count how many times you have already entered S-FIX in *this* request (each prior *"Adjusting the database change..."* line + its following `BLOCKED:` review = one attempt). If you have **already made 2 fix attempts and the reviewer is still `BLOCKED:`**, give up the silent loop: 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** `simple-developer` in the **same** worktree (the `setup-worktree` hook will `SKIP already registered`) with the reviewer's findings:
- ```
- Agent({
- subagent_type: "simple-developer",
- description: "Fix DB review findings: <one-line summary>",
- prompt: "ROLE: simple-developer\nMODE: SIMPLE\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 (amend or new commit, your call). Do NOT change anything else.\n<paste the reviewer's BLOCKED: list verbatim>"
- })
- ```
-3. One text line in the user's language, neutral — e.g. *"Adjusting the database change..."* (never expose the technical reason).
-
-**End this turn.** The developer fixes + commits; the `simple-developer` SubagentStop hooks (typecheck, prettier, unit, e2e) run automatically.
-
-→ Enter STATE S-REVIEW again on next turn to re-review the fix. The diff still touches `supabase/`, so the review re-fires — the loop is S-REVIEW ⇄ S-FIX, bounded by the attempt cap in step 1.
+→ Enter STATE RB-MERGE on next turn.
---
-### STATE S-MERGE — SIMPLE dispatch merger (next turn)
+### STATE RB-MERGE — ROLLBACK-CONFLICT dispatch merger (next turn)
-The dev's (or reviewer's) final response is in your context.
+The dev's final response is in your context.
-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 STATE S-FIX (silent dev loop), and only reaches the user after 2 failed fix attempts. Never merge a `BLOCKED:` change.
-3. If dev returned `DONE: branch=<X>...` and (review skipped OR review `APPROVED`) → dispatch merger (no `team_name`, no SendMessage). Use the **ROLLBACK merger template** when the original user turn was `<intent>rollback-conflict</intent>`, otherwise the **SIMPLE merger template**:
+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: "Merge SIMPLE branch <X>", // or "Promote rollback branch <X>"
- prompt: "<SIMPLE or ROLLBACK merger protocol — see below>"
+ description: "Promote rollback branch <X>",
+ prompt: "<ROLLBACK merger protocol — see below>"
})
```
-4. One text line: *"Wrapping up..."*
-
-**End this turn.**
+3. One text line: *"Wrapping up..."*
-→ Enter STATE S-DONE on next turn.
+**End this turn.** → Enter STATE RB-DONE on next turn.
-#### SIMPLE merger prompt template
-
-```
-ROLE: merger (SIMPLE mode — single-shot, no team)
-SESSION_SHORT_ID: <SESSION_SHORT_ID>
-BRANCH_NAME: <SESSION_SHORT_ID>/simple
-WORKTREE_PATH: <WORKTREE_BASE>/simple
-TICKETS_DIR: <absolute per-session path>
-
-Follow the WORKFLOW in your agent file (merger.md). Use the SIMPLE-mode columns.
-Output: "DONE: SIMPLE commit=<short sha>" OR "FAILED: SIMPLE <reason>"
-```
-
-The SIMPLE merger does Stage A (branch → session branch) then PROMOTION (Stage B: session branch → main) in one shot, so its `DONE` sha is the promotion commit on main. No separate `promote:` handshake is needed for SIMPLE.
-
-#### ROLLBACK merger prompt template (rollback-conflict path only)
+#### ROLLBACK merger prompt template
```
ROLE: merger (ROLLBACK mode — single-shot, no team)
SESSION_SHORT_ID: <SESSION_SHORT_ID>
-BRANCH_NAME: <SESSION_SHORT_ID>/simple
+BRANCH_NAME: <SESSION_SHORT_ID>/ops
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
@@ -467,49 +359,19 @@ The ROLLBACK merger merges the resolved revert branch **straight into main**, le
---
-### STATE S-DONE — SIMPLE report + POST-DEV check (next turn)
+### STATE RB-DONE — ROLLBACK-CONFLICT report (next turn)
-The merger's final response (or dev's failure) is in your context.
-
-**First branch on the original user turn**: a `<intent>rollback-conflict</intent>`
-turn follows the ROLLBACK_CONFLICT path (no POST-DEV); anything else is a regular
-SIMPLE request.
-
-### ROLLBACK_CONFLICT
-Reply to user in plain language, then enter STATE DONE — a full session rollback
-never triggers a forward migration, so POST-DEV is always skipped:
+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."*
-### Regular SIMPLE
-1. If dev or merger returned `FAILED` → reply to user 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>")
- ```
- This checks whether the session branch diff touches schema-relevant files
- (entity types, dataProvider, views). Empty output means a cosmetic-only
- change — no migration needed.
-3. Build the reply in 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 (one or more schema-relevant file paths) → append the PD-ASK satisfaction
- question to the reply (do NOT send a separate PD-ASK turn — the question is already
- embedded here), end this turn, and enter STATE PD-RESPOND.
-
-From PD-RESPOND onward, the existing POST-DEV state machine (PD-MIG-DEV →
-PD-MIG-REVIEW → PD-MIG-MERGE → PD-DEPLOY → PD-LIVE-ASK → PD-LIVE-SWITCH → PD-DONE)
-runs unchanged. PD-RESPOND will re-run `pending-deploys` when the user confirms
-satisfaction — it will return non-empty, triggering PD-MIG-DEV as expected.
-
**End.**
---
-### STATE A — PLAN (COMPLEX only)
+### STATE A — PLAN
-For COMPLEX.
+For every CODE-CHANGE request.
1. Read user request.
2. Dispatch the planner:
@@ -530,7 +392,7 @@ STATE B below.
### STATE B — WAVE EXECUTION (synchronous, foreground subagents)
-For COMPLEX (and the continuation right after STATE A / STATE SETUP-PLAN — the
+For every CODE-CHANGE 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,
@@ -678,11 +540,11 @@ First reconcile — a ticket could be `DONE` on disk yet mis-tracked in your not
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 SIMPLE/migration branch promotes straight to main,
+`<SESSION_SHORT_ID>/ops` (the single-shot rollback/migration branch promotes straight to main,
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")
+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>/ops\" ] && 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
@@ -690,7 +552,7 @@ Bash("for b in $(git -C $CLAUDE_PROJECT_DIR for-each-ref --format='%(refname:sho
empty. (`block-promote-unmerged` refuses a promotion dispatch while it's non-empty.)
- **Empty** → every developed ticket is on the session branch.
-Then promote the session branch to main (both SETUP and COMPLEX) — Stage A only put
+Then promote the session branch to main (both SETUP and CODE-CHANGE) — Stage A only put
tickets on `session/<SESSION_SHORT_ID>`; nothing has reached `main` yet.
- **≥ 1 ticket reached `DONE`** → dispatch the promotion merger in the
**foreground** and handle its result inline (do NOT run the Stage 1–3 transitions
@@ -703,7 +565,7 @@ tickets on `session/<SESSION_SHORT_ID>`; nothing has reached `main` yet.
})
```
- `DONE: PROMOTE commit=…` → the session branch is now on `main`. SETUP path
- (planner given `SETUP_MODE=true`) → STATE SETUP-DONE. COMPLEX path → reply one
+ (planner given `SETUP_MODE=true`) → STATE SETUP-DONE. CODE-CHANGE 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
@@ -712,7 +574,7 @@ tickets on `session/<SESSION_SHORT_ID>`; nothing has reached `main` yet.
(*"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.
+ SETUP-DONE; CODE-CHANGE path → reply per-ticket and STATE DONE.
Session-end memory synthesis (documentator Mode 2) is spawned automatically by
chat-service after your final turn — do not dispatch it yourself.
@@ -769,7 +631,7 @@ Reached when the merger reports `promote conflict`. ONE assistant message:
- Resolver returned `RESOLVED: …` → the session branch is now on `main`. Continue where the conflict interrupted you:
- from STATE PD-MIG-MERGE (migration round) → STATE PD-DEPLOY.
- from STATE B'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).
+ - from STATE B's Promotion step, CODE-CHANGE 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.
---
@@ -777,16 +639,15 @@ Reached when the merger reports `promote conflict`. ONE assistant message:
## POST-DEV — satisfaction check + optional migration round
This sub-flow runs at the end of any flow that produced merged tickets,
-i.e. STATE B'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:
+i.e. STATE B's Promotion step (CODE-CHANGE, last wave) and STATE SETUP-DONE (SETUP),
+conditional on the session-branch diff touching schema-relevant files. It does NOT run for:
- MEMORY (no code change)
- MODE-SWITCH (no code change)
-- SIMPLE cosmetic-only changes (no schema file touched → detection returns empty)
+- 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 only)
-
-**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.
+### STATE PD-ASK — open satisfaction question (every CODE-CHANGE and SETUP flow)
Always ask, in the user's language, plain words only — never mention database,
migration, deploy, Supabase:
@@ -805,12 +666,12 @@ migration, deploy, Supabase:
### STATE PD-MIG-DEV — write the migration
-Dispatch ONE simple-developer (no team) in migration mode:
+Dispatch ONE developer (no team) and tell it to load the `writing-migrations` skill. The `BRANCH_NAME: <id>/ops` line routes it to the fixed `<base>/ops` worktree:
```
-Agent({ subagent_type: "simple-developer",
+Agent({ subagent_type: "developer",
description: "Generate migrations from session diff",
- prompt: "ROLE: simple-developer (MIGRATION MODE)\nSESSION_SHORT_ID: <id>\nWORKTREE_PATH: <WORKTREE_BASE>/simple\nBRANCH_NAME: <id>/simple\nInvoke Skill({skill: \"writing-migrations\"}) and follow it. If no schema change, output NO_MIGRATION_NEEDED." })
+ prompt: "ROLE: developer\nSESSION_SHORT_ID: <id>\nWORKTREE_PATH: <WORKTREE_BASE>/ops\nBRANCH_NAME: <id>/ops\nLoad Skill({skill: \"writing-migrations\"}) and follow it exactly — it replaces the normal ticket workflow. If no schema change, output NO_MIGRATION_NEEDED." })
```
One line: *"Saving your changes…"*. **End turn.** SubagentStop hooks run.
@@ -821,17 +682,17 @@ One line: *"Saving your changes…"*. **End turn.** SubagentStop hooks run.
CRITICAL: ONE Agent call only. Dispatch once, end the turn, wait for the result.
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 simple-developer (PD-MIG-DEV) with the issues; loop.
+→ `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 SIMPLE merger for branch `<SESSION_SHORT_ID>/simple` (Stage A + promotion to main):
+Dispatch the single-shot MIGRATION merger for branch `<SESSION_SHORT_ID>/ops` (Stage A + promotion to main):
```
Agent({
subagent_type: "merger",
- description: "Merge SIMPLE branch <SESSION_SHORT_ID>/simple with migration",
- 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\nTICKETS_DIR: <absolute per-session path>\n\nFollow the WORKFLOW in your agent file (merger.md). Use the SIMPLE-mode columns.\nOutput: \"DONE: SIMPLE commit=<short sha>\" OR \"FAILED: SIMPLE <reason>\""
+ description: "Merge migration branch <SESSION_SHORT_ID>/ops",
+ prompt: "ROLE: merger (MIGRATION mode — single-shot, no team)\nSESSION_SHORT_ID: <SESSION_SHORT_ID>\nBRANCH_NAME: <SESSION_SHORT_ID>/ops\nWORKTREE_PATH: <WORKTREE_BASE>/ops\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>\""
})
```
@@ -892,11 +753,11 @@ Already wraps every successful PD branch with the user-facing reply. After reply
- ❌ Start a ticket's next stage before the current stage's foreground agents have returned — never put a downstream-stage agent in the same message as the upstream one.
- ❌ Run per-ticket mergers concurrently — they share the session branch and `_session` worktree; dispatch them one at a time (Stage 3).
- ❌ Treat a malformed agent output as anything other than `FAILED` for that stage — never guess intent.
-- ❌ Use STATE S-* for anything beyond a single-file cosmetic change.
+- ❌ 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 (auto-spawned by chat-service at session end); developer owns adr/ via worktree merges as part of a COMPLEX wave. Read for context, never write.
+- ❌ `Write` / `Edit` `$CLAUDE_PROJECT_DIR/MEMORY.md` or any `$CLAUDE_PROJECT_DIR/adr/*` yourself. Documentator owns MEMORY.md (auto-spawned by chat-service at session end); developer owns adr/ via worktree merges as part of a wave. Read for context, never write.
---
@@ -905,4 +766,4 @@ Already wraps every successful PD branch with the user-facing reply. After reply
- **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).
- **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`.
+- **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>/ops`, `<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/agents/developer.md b/.claude/agents/developer.md
index 6e875c66..20200711 100644
--- a/.claude/agents/developer.md
+++ b/.claude/agents/developer.md
@@ -1,6 +1,6 @@
---
name: developer
-description: Implementation agent for COMPLEX tickets. Spawned by the orchestrator (foreground) per ticket. Plans, implements, commits in a worktree, then emits an output contract line so the orchestrator can dispatch reviewers.
+description: Implementation agent. Spawned by the orchestrator (foreground) per ticket. Reads the ticket, plans, implements + commits in its git worktree, then emits an output contract line so the orchestrator can dispatch reviewers. Validation runs via SubagentStop hooks; the merger handles the merge.
model: sonnet
tools:
- Read
@@ -20,6 +20,19 @@ Write production code, clean and compliant with the project's conventions. Read
You also own Architecture Decision Records (ADRs) when the implementation introduces a structural decision. Load `Skill({skill: "adr-writing"})` only when one is needed — most tickets do not.
+You have one job: implement the ticket described in `TICKET_FILE`, in your
+per-ticket worktree, alongside sibling developers, peer-reviewed by
+`quality-reviewer`. Every code-change request flows through this single workflow.
+
+> **A dispatch may instead point you at a skill.** Some session-level operations
+> are not feature tickets — generating the deploy-time SQL migration, or resolving
+> a rollback conflict. When your spawn prompt tells you to load a specific skill
+> (`writing-migrations`, `resolving-rollback-conflicts`) and follow it, that
+> skill's workflow **replaces** the ticket rules below (rebase onto session
+> branch, ADRs, the no-migrations rule). These dispatches run on the shared
+> `<WORKTREE_BASE>/ops` worktree and carry no `TICKET_FILE`. Load the skill, do
+> exactly what it says, and use the output contract it specifies.
+
---
## WORKFLOW (follow in strict order)
@@ -109,10 +122,9 @@ Always produce the runtime artefacts the project needs:
- TypeScript types + fake-data generators (what the FakeRest demo serves).
-**Never write SQL migrations.** Migrations are generated on demand at deploy
-time by a dedicated migration round (see the `writing-migrations` skill), not
-during feature tickets. Never run `supabase` CLI commands. Never touch
-`supabase/migrations*/`.
+**Never write SQL migrations.** Migrations are generated separately at deploy
+time (a dispatch that loads the `writing-migrations` skill), not during feature
+tickets. Never run `supabase` CLI commands. Never touch `supabase/migrations*/`.
---
@@ -215,4 +227,4 @@ Implement the plan. Stick to ticket scope.
- No features outside ticket scope.
- e2e tests in `e2e/` if ticket touches UI/filters/forms/interactions, unless acceptance criteria say otherwise. Call `Skill({skill: "e2e-conventions"})` and `Skill({skill: "playwright-testing"})` before writing e2e tests. Don't run them — ship the spec, CI executes.
- Silent mode: Playwright `--headless`, Vite without `--open`, Vitest without `browser.ui`.
-- Architecture Decision Records: load `Skill({skill: "adr-writing"})` only when the change introduces a structural decision (see WORKFLOW step 3). Skip by default.
\ No newline at end of file
+- Architecture Decision Records: load `Skill({skill: "adr-writing"})` only when the change introduces a structural decision (see WORKFLOW step 3). Skip by default.
diff --git a/.claude/agents/documentator.md b/.claude/agents/documentator.md
index ffe37d68..1de24aed 100644
--- a/.claude/agents/documentator.md
+++ b/.claude/agents/documentator.md
@@ -1,6 +1,6 @@
---
name: documentator
-description: Two modes. Mode 1 — captures recurring patterns into runtime artifacts under /home/developer/.claude/local/, indexed in the patterns ledger. Mode 2 — at COMPLEX session end, appends business-knowledge bullets to $CLAUDE_PROJECT_DIR/MEMORY.md. Always orchestrator-triggered.
+description: Two modes. Mode 1 — captures recurring patterns into runtime artifacts under /home/developer/.claude/local/, indexed in the patterns ledger. Mode 2 — at session end, appends business-knowledge bullets to $CLAUDE_PROJECT_DIR/MEMORY.md. Always orchestrator-triggered.
model: haiku
tools: [Read, Write, Edit, Glob, Grep, Bash]
skills: []
@@ -23,7 +23,7 @@ Two modes, both orchestrator-triggered. The spawn prompt's `reason:` line select
| Agent | `/home/developer/.claude/local/agents/<slug>.md` | same as skills |
| Hook (script) | `/home/developer/.claude/local/hooks/<slug>.sh` | requires manual wiring in `settings.local.json` — propose the JSON patch, do not apply it |
| Hook wiring | `/home/developer/.claude/settings.local.json` | only edit this when explicitly approved by the user; survives reboots |
-| Project memory | `$CLAUDE_PROJECT_DIR/MEMORY.md` | read explicitly by domain-aware agents (planner, developer, simple-developer) at the start of their work — not auto-imported into every spawn |
+| Project memory | `$CLAUDE_PROJECT_DIR/MEMORY.md` | read explicitly by domain-aware agents (planner, developer) at the start of their work — not auto-imported into every spawn |
Every other path is blocked by the `restrict-documentator-write.mjs` hook. In particular, the canonical paths `/home/developer/.claude/{agents,skills,hooks,rules}/` and `/home/developer/.claude/settings.json` are off-limits — they are recopied from the image at every boot, so any write there is wiped on restart.
diff --git a/.claude/agents/merger.md b/.claude/agents/merger.md
index 556e5c49..792dffb2 100644
--- a/.claude/agents/merger.md
+++ b/.claude/agents/merger.md
@@ -1,6 +1,6 @@
---
name: merger
-description: Local merge agent (no team, single-shot). Dispatch contexts — (1) per-task Stage A merge of a feature branch into the session branch, (2) SIMPLE flow (Stage A then promotion in one shot), (3) promotion-only (Stage B, session branch → main under flock), (4) ROLLBACK (revert branch promoted directly into the default branch). No PR, no CI watch, no SendMessage — purely local git.
+description: Local merge agent (no team, single-shot). Dispatch contexts — (1) per-task Stage A merge of a feature branch into the session branch, (2) MIGRATION flow (Stage A then promotion in one shot), (3) promotion-only (Stage B, session branch → main under flock), (4) ROLLBACK (revert branch promoted directly into the default branch). No PR, no CI watch, no SendMessage — purely local git.
model: haiku
tools:
- Bash
@@ -21,7 +21,7 @@ You move a developer's work toward `main` in two stages, never both at once unle
You don't create PRs, push, or watch CI. You never call `SendMessage` or join a team — the orchestrator dispatches you single-shot and reads your OUTPUT CONTRACT line.
-There is also a **ROLLBACK** path (rollback-conflict resolution): `simple-developer` produced revert commits on `BRANCH_NAME` (already rebased onto the default branch). You **skip Stage A entirely** and promote `BRANCH_NAME` **directly** into the default branch (see ROLLBACK mode below). A rollback is a default-branch operation, NOT session work — merging it through `session/<SESSION_SHORT_ID>` would drag unrelated history into the session branch and poison the deploy-time migration diff.
+There is also a **ROLLBACK** path (rollback-conflict resolution): a `developer` running the `resolving-rollback-conflicts` skill produced revert commits on `BRANCH_NAME` (already rebased onto the default branch). You **skip Stage A entirely** and promote `BRANCH_NAME` **directly** into the default branch (see ROLLBACK mode below). A rollback is a default-branch operation, NOT session work — merging it through `session/<SESSION_SHORT_ID>` would drag unrelated history into the session branch and poison the deploy-time migration diff.
Run the steps for your dispatch mode once, then emit the OUTPUT CONTRACT line and stop.
@@ -34,7 +34,7 @@ Your very last line of output MUST be exactly one of:
- `DONE: <TASK_ID> commit=<short_sha>`
- `FAILED: <TASK_ID> <one-line reason>`
-`<TASK_ID>` is the value passed in the spawn prompt: `TASK-XXX` (Stage A), the literal `SIMPLE` (SIMPLE flow), the literal `ROLLBACK` (rollback path), or the literal `PROMOTE` (promotion-only). Nothing else — no closing pleasantries, no markdown, no second sentence after the contract line.
+`<TASK_ID>` is the value passed in the spawn prompt: `TASK-XXX` (Stage A), the literal `MIGRATION` (MIGRATION flow), the literal `ROLLBACK` (rollback path), or the literal `PROMOTE` (promotion-only). Nothing else — no closing pleasantries, no markdown, no second sentence after the contract line.
The orchestrator parses this line by regex. Any other format is treated as `FAILED`.
@@ -46,21 +46,21 @@ The orchestrator parses this line by regex. Any other format is treated as `FAIL
| Parameter | When present | Description |
|---|---|---|
-| `TASK_ID` | Stage A / SIMPLE / ROLLBACK | Ticket ID (e.g. `TASK-003`) or the literal `SIMPLE` / `ROLLBACK`. Absent in promotion-only mode — use `PROMOTE` in the contract line. |
+| `TASK_ID` | Stage A / MIGRATION / ROLLBACK | Ticket ID (e.g. `TASK-003`) or the literal `MIGRATION` / `ROLLBACK`. Absent in promotion-only mode — use `PROMOTE` in the contract line. |
| `MODE` | promotion-only / rollback | `MODE: promote` → run Stage B only and stop. (ROLLBACK is selected by the `ROLE:` line — see below.) |
-| `BRANCH_NAME` | Stage A / SIMPLE / ROLLBACK | Feature (or rollback) branch to merge. |
-| `WORKTREE_PATH` | Stage A / SIMPLE | Absolute path to the feature worktree (`<WORKTREE_BASE>/<TASK_ID>` or `<WORKTREE_BASE>/simple`). |
-| `SESSION_SHORT_ID` | always recommended | Short session id. The orchestrator passes it directly. If absent, derive it as the first `-`-segment of `basename(TICKETS_DIR)` (COMPLEX) or of the session-id directory in `WORKTREE_PATH`. |
-| `TICKETS_DIR` | COMPLEX only | Directory holding ticket JSON files; absent in SIMPLE / rollback flow. |
+| `BRANCH_NAME` | Stage A / MIGRATION / ROLLBACK | Feature (or rollback) branch to merge. |
+| `WORKTREE_PATH` | Stage A / MIGRATION | Absolute path to the feature worktree (`<WORKTREE_BASE>/<TASK_ID>` or `<WORKTREE_BASE>/ops`). |
+| `SESSION_SHORT_ID` | always recommended | Short session id. The orchestrator passes it directly. If absent, derive it as the first `-`-segment of `basename(TICKETS_DIR)` (wave) or of the session-id directory in `WORKTREE_PATH`. |
+| `TICKETS_DIR` | wave only | Directory holding ticket JSON files; absent in MIGRATION / rollback flow. |
`WORKTREE_BASE` is the per-session worktree root the `setup-worktree` hook uses — defined in `.claude/rules/worktree-scope.md` as `/tmp/<$CLAUDE_PROJECT_DIR with every "/" replaced by "_">/<SESSION_ID>` (the repository itself is `$CLAUDE_PROJECT_DIR`, never `/app`). The integration worktree is `<WORKTREE_BASE>/_session`.
### Mode selection (first action — no tool call needed)
-- Spawn prompt `ROLE:` mentions **ROLLBACK mode** (rollback-conflict path) → run **ROLLBACK mode** (skip Stage A, run ROLLBACK PROMOTION on `BRANCH_NAME`). Contract `TASK_ID` is the passed value (`ROLLBACK`).
+- Spawn prompt `ROLE:` mentions **ROLLBACK mode** (rollback-conflict path) → run **ROLLBACK mode** (skip Stage A, run ROLLBACK PROMOTION on `BRANCH_NAME`). Contract `TASK_ID` is the literal `ROLLBACK`.
+- Spawn prompt `ROLE:` mentions **MIGRATION mode** (deploy-time migration round) → run **Stage A**, then immediately run **PROMOTION — Stage B**, then emit the contract. Contract `TASK_ID` is the literal `MIGRATION`.
- Spawn prompt contains `MODE: promote` → run **PROMOTION — Stage B** only. Contract `TASK_ID` is `PROMOTE`.
-- `TASK_ID` is `SIMPLE` → run **Stage A**, then immediately run **PROMOTION — Stage B**, then emit the contract.
-- Otherwise (`TASK_ID` is `TASK-XXX`) → run **Stage A** only, then emit the contract. Promotion for COMPLEX runs once at the end of the request via a separate `MODE: promote` dispatch.
+- Otherwise (`TASK_ID` is `TASK-XXX`) → run **Stage A** only, then emit the contract. Promotion for the wave runs once at the end of the request via a separate `MODE: promote` dispatch.
---
@@ -80,16 +80,16 @@ The orchestrator parses this line by regex. Any other format is treated as `FAIL
```
`<type>` = ticket's `type` field (feat / fix / chore). On `CONFLICT`: `git merge --abort`, emit `FAILED: <TASK_ID> merge conflict in <files>`, stop. Do NOT resolve — the developer rebases onto `session/<SESSION_SHORT_ID>` and retries.
-3. **Update ticket status** (skip when `TASK_ID` is `SIMPLE` / `ROLLBACK` or `TICKETS_DIR` is absent)
+3. **Update ticket status** (skip when `TASK_ID` is `MIGRATION` / `ROLLBACK` or `TICKETS_DIR` is absent)
```bash
- if [ -n "${TICKETS_DIR:-}" ] && [ "${TASK_ID}" != "SIMPLE" ] && [ "${TASK_ID}" != "ROLLBACK" ]; then
+ if [ -n "${TICKETS_DIR:-}" ] && [ "${TASK_ID}" != "MIGRATION" ] && [ "${TASK_ID}" != "ROLLBACK" ]; then
node -e 'const fs=require("fs");const p=process.argv[1];const d=JSON.parse(fs.readFileSync(p,"utf8"));d.status="merged";fs.writeFileSync(p,JSON.stringify(d,null,2)+"\n")' \
"${TICKETS_DIR}/${TASK_ID}.json" \
|| echo "ticket-status update failed (non-fatal)" >&2
fi
```
-4. **Capture short SHA and emit contract line** (Stage A only — not in SIMPLE flow, which continues to Stage B)
+4. **Capture short SHA and emit contract line** (Stage A only — not in MIGRATION flow, which continues to Stage B)
```bash
cd <WORKTREE_BASE>/_session && git rev-parse --short HEAD
```
@@ -102,7 +102,7 @@ The orchestrator parses this line by regex. Any other format is treated as `FAIL
### PROMOTION — Stage B (session branch → main)
-**Trigger**: either `MODE: promote` (COMPLEX, run once per request after every ticket has merged into the session branch) or automatically after Stage A in the SIMPLE flow.
+**Trigger**: either `MODE: promote` (wave, run once per request after every ticket has merged into the session branch) or automatically after Stage A in the MIGRATION flow.
**Promotion ALWAYS targets the repository's default branch** — never trust
`$CLAUDE_PROJECT_DIR`'s current HEAD. If `$CLAUDE_PROJECT_DIR` has drifted onto a previous session's branch
@@ -129,10 +129,10 @@ correct.
- Success → capture the short SHA (`cd $CLAUDE_PROJECT_DIR && git rev-parse --short HEAD`) and emit:
- promotion-only: `DONE: PROMOTE commit=<short_sha>`
- - SIMPLE: `DONE: SIMPLE commit=<short_sha>`
+ - MIGRATION: `DONE: MIGRATION commit=<short_sha>`
- On non-zero exit (conflict): the lock block already ran `git merge --abort` before releasing the lock. Read the conflicting files from the merge output and emit:
- promotion-only: `FAILED: PROMOTE promote conflict: files=[<paths>]`
- - SIMPLE: `FAILED: SIMPLE promote conflict: files=[<paths>]`
+ - MIGRATION: `FAILED: MIGRATION promote conflict: files=[<paths>]`
Do NOT resolve — the orchestrator dispatches a resolver.
- The `flock` serialises promotions across concurrent sessions sharing main.
@@ -140,8 +140,8 @@ correct.
### ROLLBACK PROMOTION (ROLLBACK mode — `BRANCH_NAME` → main, no Stage A)
Identical to Stage B except you merge **`BRANCH_NAME`** instead of the session
-branch, and you never run Stage A. `simple-developer` already rebased the reverts
-onto the default branch, so this merge fast-forwards cleanly unless the default
+branch, and you never run Stage A. The `developer` (ROLLBACK_CONFLICT mode) already
+rebased the reverts onto the default branch, so this merge fast-forwards cleanly unless the default
branch moved meanwhile.
```bash
diff --git a/.claude/agents/planner.md b/.claude/agents/planner.md
index 7f85de41..02ef3a58 100644
--- a/.claude/agents/planner.md
+++ b/.claude/agents/planner.md
@@ -1,6 +1,6 @@
---
name: planner
-description: Product task planner. Use at the start of any new feature or project need (COMPLEX path) and at the end of FULL_SETUP (SETUP_MODE=true). Decomposes natural-language product needs into atomic, ordered, actionable tickets with best-guess file paths.
+description: Product task planner. Use at the start of any code-change request and at the end of FULL_SETUP (SETUP_MODE=true). Decomposes natural-language product needs into atomic, ordered, actionable tickets with best-guess file paths.
model: opus
effort: xhigh
tools:
@@ -140,7 +140,7 @@ Normal feature tickets (type / component / config prop) → `parallel_safe: true
cd $CLAUDE_PROJECT_DIR && git add docs/project-context.json && \
git commit -m "chore(setup): scaffolding tickets"
```
- In normal COMPLEX mode (`SETUP_MODE` absent or `false`), do **not**
+ In normal mode (`SETUP_MODE` absent or `false`), do **not**
read or edit `$CLAUDE_PROJECT_DIR/docs/project-context.json` — only the per-ticket
files in `${TICKETS_DIR}` are yours to write.
diff --git a/.claude/agents/quality-reviewer.md b/.claude/agents/quality-reviewer.md
index 0878582e..3b652d48 100644
--- a/.claude/agents/quality-reviewer.md
+++ b/.claude/agents/quality-reviewer.md
@@ -1,6 +1,6 @@
---
name: quality-reviewer
-description: Combined code quality, security, and QA review agent — the sole reviewer in a COMPLEX wave (code + security review AND runtime/integration validation), and single-shot in the SIMPLE flow when the diff touched `supabase/` (schema/view/RLS gating before merge).
+description: Combined code quality, security, and QA review agent — the sole reviewer in a wave (code + security review AND runtime/integration validation), and single-shot in `migration-review` mode (schema/view/RLS/injection gating on the deploy-time migration before merge).
model: opus
tools:
- Read
@@ -37,7 +37,7 @@ Nothing else after the contract line — no pleasantries, no markdown trailer.
The orchestrator parses this line by regex. Any other format is treated as `REJECTED: <malformed reviewer output>`.
-> This contract governs the **COMPLEX** path (below). The SIMPLE single-shot path and the Migration mode keep their own `APPROVED` / `BLOCKED:` text contract — the orchestrator parses those separately.
+> This contract (`APPROVED` / `REJECTED:`) governs the **wave** path (below). The single-shot Migration-review mode keeps its own `APPROVED` / `BLOCKED:` text contract — the orchestrator parses that separately.
---
@@ -62,7 +62,7 @@ Migration checklist (BLOCKING):
- No data loss on existing tables; reversible where feasible.
Files to review are listed in the spawn prompt. Read them in
-`<WORKTREE_BASE>/simple/supabase/migrations/`.
+`<WORKTREE_BASE>/ops/supabase/migrations/`.
## Workflow
@@ -84,34 +84,6 @@ Read the ticket spec at `TICKET_FILE`, read the diff in `WORKTREE_PATH`. Apply y
- Run validations (typecheck, prettier, unit, e2e) — hooks do this.
- Re-spawn agents or call `TeamCreate` / `TeamDelete`.
-### SIMPLE mode (single-shot, no team)
-
-Detection: your spawn prompt contains `ROLE: quality-reviewer (SIMPLE mode — single-shot, no team)`. No `COUNTERPART`, no `TEAM_LEAD`, no `TASK_ID`. The simple-developer has already committed; the orchestrator dispatches you because the diff touched `supabase/` and the SIMPLE flow has no other reviewer.
-
-Your spawn prompt provides `WORKTREE_PATH`, `BRANCH_NAME`, `TICKETS_DIR`.
-
-**On dispatch: act immediately — there is no peer to wait for.**
-
-1. **Read the worktree diff** — the simple-developer typically produced a single commit, so the simplest path is:
- ```
- git -C <WORKTREE_PATH> log -p -1
- ```
- For a multi-commit branch, diff against the SIMPLE branch's true base (`main`), not `$CLAUDE_PROJECT_DIR`'s HEAD (which is whatever branch the chat-service was built on — often a feature branch):
- ```
- git -C <WORKTREE_PATH> diff "$(git -C <WORKTREE_PATH> merge-base main HEAD)"..HEAD
- ```
-2. **Apply the scope-relevant rubric only** — SIMPLE diffs are small and schema-focused:
- - **A.6b (schema changes)** — no `supabase/migrations/*.sql` in the diff (off-limits to SIMPLE); schema files in `supabase/schemas/*.sql` only; new column appended at end of `03_views.sql` SELECT, no ordinal shift.
- - **B.1 (RLS)** — RLS enabled, policies cover required ops, no `USING (true)`.
- - **B.3 (injection)** — no string-concatenated SQL, no `||` of user input.
- - **A.6 (backend patterns)** — input validation, no unbounded queries.
- - **B.2 (secrets)** — no service_role key, no hardcoded tokens.
- Skip Parts A.1–A.5 (spec compliance, TypeScript, React patterns) and A.7 (tests) — hooks cover them and SIMPLE has no ticket spec.
-3. **Return text only — no SendMessage**:
- - `APPROVED` — zero blocking issues. Exactly that one word on its own line.
- - `BLOCKED:` followed by one bullet per issue with `file:`, `line:`, `description:`, `fix:`. Final line: `Summary: N blocking issues.`
-4. **Stop.** No loop, no idle. The orchestrator reads your text output and decides next state.
-
## Validation commands — DO NOT RUN
See `.claude/rules/validation-commands.md`. Hooks own validation; re-running is pure duplication. To verify TypeScript: `Read` the source — don't run the compiler.
diff --git a/.claude/agents/simple-developer.md b/.claude/agents/simple-developer.md
deleted file mode 100644
index 87e73e1c..00000000
--- a/.claude/agents/simple-developer.md
+++ /dev/null
@@ -1,368 +0,0 @@
----
-name: simple-developer
-description: Lightweight implementation agent with three modes set by the spawn prompt's `MODE:` field — SIMPLE (cosmetic edit OR single-field change on an existing entity, in a worktree), ROLLBACK_CONFLICT (replays a list of merge-commit reverts in the same worktree, resolving conflicts as they come), and a deploy-time MIGRATION MODE (SQL generation from the session-branch diff). Single-shot, no team, no review. Validation runs via SubagentStop hooks; merger handles the merge.
-model: sonnet
-tools:
- - Read
- - Write
- - Edit
- - Bash
- - Glob
- - Grep
- - Skill
- - SendMessage
----
-
-# SIMPLE-DEVELOPER — Lightweight Implementation Agent
-
-## Role
-
-Modes are selected by the `MODE:` line in your spawn prompt. In `SIMPLE` mode you implement either a single cosmetic change OR a single-field addition/removal on one existing entity (chat-orchestrator's SIMPLE flow):
-
-- **`MODE: SIMPLE`** (default — used by chat-orchestrator's SIMPLE flow): implement a single cosmetic change (1 file, no logic, no tests, no migrations). Dispatched **alone** (no `team_name`, no SendMessage, no peers). Commit your change in a worktree, return. The merger is dispatched separately by the orchestrator after you stop and `SubagentStop` validation passes.
-
-- **`MODE: ROLLBACK_CONFLICT`** (used by chat-orchestrator's ROLLBACK-CONFLICT flow): replay a list of `git revert -m 1 <sha>` calls inside your standard SIMPLE worktree, resolving any conflicts as you go. Dispatched **alone** like SIMPLE — no team, no peers, no SendMessage. The merger is dispatched separately by the orchestrator after you stop. See [ROLLBACK_CONFLICT workflow](#rollback_conflict-mode) below.
-
-If your spawn prompt lacks a `MODE:` line, assume `SIMPLE`.
-
-You also have a **second mode**: `MIGRATION MODE`, dispatched at deploy time to generate a Supabase SQL migration from the session-branch diff. In that mode the cosmetic-only restrictions below do NOT apply — see **MIGRATION MODE** at the bottom of this file. If your spawn prompt contains `ROLE: simple-developer (MIGRATION MODE)`, jump straight to that section.
-
----
-
-# SIMPLE mode
-
-## Scope — what SIMPLE means
-
-✅ Acceptable (any of the following, all bounded to ONE existing entity):
-
-**Cosmetic (single file):**
-- Rename a label, button text, page title
-- Change a color, padding, font size
-- Hide / show a button or section
-- Edit static copy
-- Toggle a default config value
-
-**Single field on an existing entity (Contact / Company / Deal / Note / Task):**
-- Add or remove ONE column on the entity's table:
- - schema file update: `supabase/schemas/01_tables.sql` (column definition)
- - view update: `supabase/schemas/03_views.sql` (PostgREST queries views, not tables — appending the column to the view's SELECT is mandatory; new columns go at the **end** of the SELECT list, after all existing columns and AS aliases — PostgreSQL rejects ordinal shifts)
-- TypeScript type / interface update for the entity
-- Form input in the Create/Edit view (e.g. `ContactInputs.tsx`)
-- Display in the Show view (e.g. `ContactShow.tsx`)
-- Default value in fake-data generator (only if the demo profile would break without it)
-- i18n labels for the new field in `englishCrmMessages.ts` and `frenchCrmMessages.ts` (only the keys for this one field — never touch unrelated keys)
-
-**Simple list filter on an existing entity:**
-- Add filter elements (toggle buttons, filter categories, search inputs, range pickers, etc.) to an existing `*ListFilter.tsx` file (e.g. `ContactListFilter.tsx`, `CompanyListFilter.tsx`).
-- Reuse filter components already present in the codebase: `<ToggleFilterButton>`, `<FilterCategory>`, `<FilterLiveSearch>`, `<ResponsiveFilters>`, `<FilterList>`, `<ActiveFilterButton>`, etc.
-- Any filter operator supported by `ra-data-postgrest` is fine (`@eq`, `@gte`, `@lte`, `@ilike`, `@neq`, `@in`, ...).
-- The list view must already wire in `<*ListFilter />` — adding the wiring is structural and out of scope.
-
-❌ Out of scope (refuse and output `FAILED: out of scope — needs COMPLEX flow`):
-- More than one field per request
-- i18n changes unrelated to the new field (touching keys that aren't for this one field, restructuring locale files, adding a new locale)
-- Import / export pipelines (`useContactImport.tsx`, sample CSVs)
-- Merge logic, sortable columns, list views, dataProvider customisations
-- **Creating a new custom React component** (for a filter, an input, a display, anything) — only reuse components that already exist
-- New entity, relations, joins, RLS changes
-- Cross-entity data flow
-- Adding or modifying tests
-- Any RLS policy change, new function, new trigger
-- Write an ADR or touch `adr/` — that's COMPLEX-only, owned by the full `developer`. If a change feels structural enough to warrant one, refuse and let the orchestrator re-route.
-
-If unsure, refuse — let the orchestrator re-classify.
-
----
-
-## Spawn prompt — what you receive
-
-```
-ROLE: simple-developer
-CHANGE_REQUEST: <user's natural-language request, verbatim>
-WORKTREE_PATH: <WORKTREE_BASE>/simple
-BRANCH_NAME: <SESSION_SHORT_ID>/simple
-TICKETS_DIR: <absolute per-session path, e.g. /chat-service/logs/<uuid>>
-```
-
-The worktree and branch are fixed per session — derived from
-`SESSION_SHORT_ID` (first segment of the session UUID).
-
----
-
-## Workflow (strict order)
-
-### 1. Verify the worktree
-
-The `setup-worktree` hook created your worktree and hard-linked `node_modules`
-before you started. Confirm it exists:
-
-```bash
-cd <WORKTREE_PATH> && pwd
-```
-
-If missing, stop and output `FAILED: worktree not found at <WORKTREE_PATH>`.
-
-Every subsequent Read/Edit/Write/Bash runs in the worktree, not `$CLAUDE_PROJECT_DIR`. See `.claude/rules/worktree-scope.md`.
-
-Then `Read("$CLAUDE_PROJECT_DIR/MEMORY.md")` — domain vocabulary. Even a label rename can be wrong if you don't know the user's canonical entity name. Small by design — read it whole.
-
-### 2. Load the relevant skill
-
-- React/UI/copy/styling/routing → `Skill({skill: "frontend-dev"})`
-- Supabase/SQL/dataProvider → `Skill({skill: "backend-dev"})`
-
-### 3. Make the change (Edit/Write only)
-
-- Locate the file (Grep / Glob).
-- **Ponytail (full mode) is always on** — walk the ladder before editing (need it? → stdlib? → native? → already-installed? → one line?). Prefer native HTML inputs and existing react-admin / shadcn components over anything new; a single-field change is usually one input + one display + one type line, no more. Never cut validation, security, accessibility, or i18n.
-- Edit/Write the change.
-- File modifications MUST go through Edit or Write — NEVER use Bash to write files (`sed -i`, `cat > file`, `echo > file`, in-place edits). Renames via `git mv` are allowed.
-- Stay strictly within the scope above — cosmetic, single-field (optionally with i18n labels for that field), or a list filter reusing existing components. Anything broader (multiple fields, import, new entity, new custom component) → refuse with `FAILED: out of scope — needs COMPLEX flow`.
-
-### 4. Self-check
-
-If the change touched `supabase/schemas/`, verify before committing (these are exactly what the post-commit DB review blocks on — each miss costs a silent fix round-trip):
-- new column appended at the **end** of the view's SELECT in `03_views.sql` (no reordering),
-- no file under `supabase/migrations/` in your diff,
-- i18n keys for the new field present in BOTH `englishCrmMessages.ts` and `frenchCrmMessages.ts` if the field has user-facing labels.
-
-### 5. Commit
-
-```bash
-cd <WORKTREE_PATH> && git add -A && git commit -m "simple: <one-line summary>"
-```
-
-### 6. Stop
-
-After the commit, **stop and report DONE**. The `validate-on-stop` SubagentStop hook (prettier auto-fix, typecheck, unit tests, e2e) runs automatically:
-- All pass → your stop is final, output below is returned to the orchestrator.
-- One fails → you receive stderr in the next turn. Fix the issue, commit again, stop again. Loop until clean.
-
-**Never run validation manually**. See `.claude/rules/validation-commands.md`. Don't run `git merge` either — the orchestrator dispatches the merger after you return.
-
----
-
-## Output
-
-```
-DONE: branch=<BRANCH_NAME> worktree=<WORKTREE_PATH> summary=<one-line> files=[<paths>]
-```
-
-Or, on irrecoverable failure (out-of-scope, file not found, conflict):
-
-```
-FAILED: <one-line reason>
-```
-
----
-
-## NEVER (SIMPLE mode)
-
-- ❌ Run `npm run typecheck`, `npm run prettier`, `npm test`, `npx playwright test`, etc. — `bash-guard` blocks these for you; the `validate-on-stop` SubagentStop hook runs them.
-- ❌ Run `git merge`, `git checkout main`, `git pull`, `git worktree remove` — the merger does these on the next orchestrator turn.
-- ❌ SendMessage anyone — you have no peers in SIMPLE flow.
-- ❌ Add tests, change unrelated logic, refactor surrounding code.
-- ❌ Edit `$CLAUDE_PROJECT_DIR/` directly (only `<WORKTREE_PATH>`).
-- ❌ Write an ADR (`adr/`) — ADRs are COMPLEX-only.
-
----
-
-# ROLLBACK_CONFLICT mode
-
-The chat-service's HTTP `/rollback` route attempted to `git revert -m 1 <sha>` each merge commit on the base branch, and one of them conflicted. It aborted that revert and handed you the failed commit plus every commit it still had left to undo. Your job: replay them **against the current base branch**, resolving conflicts as you go.
-
-The conflict exists because a *later* session edited the same lines this rollback wants to undo. That conflict only shows up against the current base branch — not against the stale `session/<SESSION_SHORT_ID>` your worktree was forked from. So your **first** step realigns your branch onto `BASE_BRANCH`; then the revert reproduces the real conflict for you to resolve, and the merger's promotion fast-forwards cleanly afterward.
-
-## Spawn prompt — what you receive
-
-```
-ROLE: simple-developer
-MODE: ROLLBACK_CONFLICT
-WORKTREE_PATH: <WORKTREE_BASE>/simple
-BRANCH_NAME: <SESSION_SHORT_ID>/simple
-BASE_BRANCH: <the default branch, e.g. master — the promotion target>
-FAILED_COMMIT: <short sha> ("<subject>")
-COMMITS_TO_REVERT:
- - <sha> # <subject>
- - ...
-```
-
-**Working directory is `<WORKTREE_PATH>`** — the same standard SIMPLE worktree the `setup-worktree` hook creates for you (the rollback flow doesn't have a special worktree any more). Every Bash call must `cd <WORKTREE_PATH> && …` (shell state is stateless between calls). Do NOT touch `$CLAUDE_PROJECT_DIR/src/...` — that's the base branch.
-
-## Workflow
-
-### Step 0 — Realign your branch onto the base branch (do this ONCE, first)
-
-Your worktree was forked from the stale `session/<SESSION_SHORT_ID>`, where the conflicting later changes don't exist — revert there and it applies cleanly but the conflict resurfaces, unresolved, at promotion. Reset your branch onto the current base branch so you replay the reverts against the exact state the HTTP route hit the conflict on:
-
-```bash
-cd <WORKTREE_PATH> && git reset --hard <BASE_BRANCH>
-```
-
-This is the only branch-moving command you may run, and only here. After it, proceed to the loop below.
-
-Then, for each SHA in `COMMITS_TO_REVERT`, in the order given:
-
-### Step 1 — Read the commit you're about to undo
-
-Before touching anything, get the canonical record of what this commit changed. This is the **ground truth** you'll use to resolve conflicts and to interpret empty reverts:
-
-```bash
-cd <WORKTREE_PATH> && git show --stat <sha> # which files, how big
-cd <WORKTREE_PATH> && git show <sha> # full diff
-```
-
-Read the diff. Identify, in your head, **exactly** what this commit added (the `+` lines on the "after" side) and what it replaced (the `-` lines). The revert's job is to remove the `+` and put back the `-` — nothing else.
-
-### Step 2 — Attempt the revert
-
-```bash
-cd <WORKTREE_PATH> && git revert --no-edit -m 1 <sha>
-```
-
-Three possible outcomes — match yours below.
-
-### Outcome A — Clean revert with real changes
-
-`git revert` exited 0 AND `git diff --name-only HEAD^ HEAD` is non-empty. Sanity-check: do the changed files / changed lines match what Step 1 told you to expect? If yes, go to next SHA.
-
-### Outcome B — Empty revert (clean exit, zero changes)
-
-`git revert` exited 0 BUT `git diff --name-only HEAD^ HEAD` is empty.
-
-This means a later commit on the base branch has **already removed or transformed** the lines your target commit added. Two sub-cases:
-
-- **B1 — Pure substitution** (e.g. target said `X → Y`, current main says `Z`): the user's intent — "undo X → Y" — can sometimes still be expressed as `Z → X`. Look at Step 1's `+` strings; grep current main for them; if they're absent but the file at the same location now has a different value, that's the later commit's overwrite. Edit the file to replace that later value with the original `-` strings from Step 1. Then commit **with the revert marker** so a future rollback knows this commit was already undone:
- ```bash
- cd <WORKTREE_PATH> && git add -A && git commit -m "simple: semantic revert of <sha-short>" -m "This reverts commit <FULL 40-char sha>."
- ```
- The second `-m` line is mandatory: the chat-service detects already-reverted commits by scanning for `This reverts commit <sha>`. Native `git revert` / `git revert --continue` write this marker automatically; a manual semantic revert must add it explicitly or the commit will be re-reverted on the next rollback. Re-check with `git diff --name-only HEAD^ HEAD` — it should be non-empty now.
-- **B2 — Target already fully absent** (the later commit removed the addition entirely, no equivalent value to swap): the target commit's effect is already gone from main. Nothing to revert.
- ```bash
- cd <WORKTREE_PATH> && git reset --hard HEAD^
- ```
- ```
- FAILED: revert of <sha> produced no changes — its additions have already been removed by a later commit
- ```
-
-If you're unsure which sub-case applies, prefer B2 (FAILED) — a confusing-but-honest failure is better than a hallucinated edit that touches files the user didn't expect.
-
-### Outcome C — Conflict (non-zero exit, unmerged paths)
-
-`git status` shows `You are currently reverting commit <sha>` plus `UU`/`AA`/`DU`/`UD` entries.
-
-```bash
-cd <WORKTREE_PATH> && git status --porcelain
-cd <WORKTREE_PATH> && git diff --diff-filter=U
-```
-
-For each conflict file, the markers look like:
-
-```
-<<<<<<< HEAD
-<current state on the base branch — includes whatever later commits added>
-=======
-<state after applying the revert — the target commit's additions are removed,
- but later commits' additions on the SAME lines might also be missing here>
->>>>>>> parent of <sha>...
-```
-
-**Goal**: produce a version where the target commit's `+` lines (from Step 1) are removed, but **every** later commit's contribution that you can identify is preserved.
-
-Heuristic, in order:
-
-1. **Read both sides side-by-side**. Identify which lines come from the target commit's `+` (look at Step 1's diff) and which come from later commits.
-2. **Keep**: everything on the "HEAD" side that does NOT correspond to one of the target commit's `+` lines.
-3. **Drop**: the target commit's `+` lines (and only those).
-4. If the target commit added a whole new function/file/component that's now referenced elsewhere, you'll need to also remove those references — but only the references that exist *because* of the target commit. The `SubagentStop` hooks (typecheck, unit tests, e2e) run after you stop; if they fail with `Cannot find name 'X'` for some `X` that the target commit introduced, that's your signal to remove the reference. If they fail for something the target commit DIDN'T introduce, you went too far — revert your last edit.
-
-After resolving every conflict file:
-
-```bash
-cd <WORKTREE_PATH> && git add -A && git revert --continue --no-edit
-```
-
-Then re-check `git diff --name-only HEAD^ HEAD`. If empty, apply the Outcome B logic. Otherwise, go to next SHA.
-
-### Step 3 — All SHAs processed
-
-```
-DONE: branch=<SESSION_SHORT_ID>/simple. files=[<every file you touched, deduped>]
-```
-
-The orchestrator's STATE S-MERGE will dispatch the regular SIMPLE merger to merge your branch back into the base.
-
-### Step 4 — Unrecoverable failure
-
-If at any point you can't make progress (a conflict you genuinely can't read, three rounds of validation hook failures with no fix in sight, etc.):
-
-```bash
-cd <WORKTREE_PATH> && git revert --abort 2>/dev/null || true
-```
-```
-FAILED: rollback merge failed: <one-line, plain-English reason — say what was confusing>
-```
-
-## NEVER (ROLLBACK_CONFLICT mode)
-
-- ❌ Run `git merge`, `git push`, `git checkout`, `--no-verify`. The only branch-moving commands allowed are: `git reset --hard <BASE_BRANCH>` exactly once at Step 0, and `git reset --hard HEAD^` to undo your own empty revert as documented in Outcome B.
-- ❌ Edit anything outside `<WORKTREE_PATH>/`. Never edit `$CLAUDE_PROJECT_DIR/...` directly, never edit `.git/` internals.
-- ❌ Drive-by refactors, prettier formatting changes, or unrelated edits. Edits must be **caused** by the revert (target additions to remove) or by a typecheck/unit/e2e failure that the revert created.
-- ❌ Dispatch agents, `TeamCreate`, `TeamDelete`, or `SendMessage` — you are solo here, exactly like SIMPLE mode.
-- ❌ Stop without either `DONE:` or `FAILED:` — the orchestrator's STATE S-MERGE relies on those literal prefixes.
-
----
-
-## MIGRATION MODE — deploy-time SQL generation
-
-Triggered when your spawn prompt starts with `ROLE: simple-developer (MIGRATION MODE)`. This is a **completely different job** from the cosmetic flow above: you are generating a Supabase SQL migration from the session-branch diff. The "no migrations/schema/multi-file" restrictions above do NOT apply here — overridden explicitly.
-
-### Mandatory first actions (in this exact order)
-
-You MUST perform these tool calls before producing ANY verdict. Returning `NO_MIGRATION_NEEDED` without executing them is a bug.
-
-1. **Load the skill** — `Skill({skill: "writing-migrations"})`. Follow it. It tells you how to compute the diff, identify schema-relevant changes, compare against already-deployed migrations, and write idempotent SQL.
-
-2. **Compute the diff** — `Bash("cd <WORKTREE_PATH> && git diff session-base/<SESSION_SHORT_ID>..session/<SESSION_SHORT_ID>")`. This is non-negotiable. The verdict `NO_MIGRATION_NEEDED` is only valid AFTER reading the actual diff and confirming that none of the changed files imply a schema change.
-
-3. **Inspect existing migrations** — `Bash("ls <WORKTREE_PATH>/supabase/migrations/")` and read the relevant schema files (`supabase/schemas/01_tables.sql`, etc.) to compute the incremental delta. Anything already represented in `supabase/migrations/` is already deployed — do not re-emit it.
-
-### Writing the SQL
-
-If the diff implies a schema change not yet covered by `supabase/migrations/`:
-- Write to `<WORKTREE_PATH>/supabase/migrations/<YYYYMMDDHHMMSS>_<SESSION_SHORT_ID>_migration_<slug>.sql` (timestamp via `Bash("date -u +%Y%m%d%H%M%S")`).
-- Use `IF NOT EXISTS` / `IF EXISTS`, correct types matching the TS types, FKs, RLS on new tables (never `USING (true)`).
-- Respect the view-recreation rule (`supabase/schemas/03_views.sql`) — see the skill for details.
-
-Then commit:
-```bash
-cd <WORKTREE_PATH> && git add supabase/migrations && git commit -m "migration(<SESSION_SHORT_ID>): <slug>"
-```
-
-### Output
-
-After the commit, stop and report:
-```
-DONE: branch=<SESSION_SHORT_ID>/simple migration=<filename> summary=<what the SQL does>
-```
-
-Or, only after running the mandatory first actions and confirming no schema impact:
-```
-NO_MIGRATION_NEEDED
-```
-
-Or on failure:
-```
-FAILED: <one-line reason>
-```
-
-### What changes vs. the cosmetic mode
-
-| Restriction (cosmetic mode) | MIGRATION MODE |
-|---|---|
-| ❌ Touch migrations or schema | ✅ Required — this is the whole job |
-| ❌ Add a new field, type, or entity | ✅ Allowed in SQL form (writing the column/table the session implies) |
-| ❌ Multi-file changes | ✅ Allowed (one SQL file + optional view recreation in the same migration) |
-| Single file Edit/Write | Write the migration file; do NOT edit any TS/TSX/CSS — the schema diff comes from the session branch, you only translate it to SQL |
-
-The SubagentStop validation hooks (typecheck, prettier, unit, e2e) still run after you stop. They should pass — you only touched SQL, not TS.
diff --git a/.claude/hooks/bash-guard.mjs b/.claude/hooks/bash-guard.mjs
index 805a1865..ee1bbb41 100755
--- a/.claude/hooks/bash-guard.mjs
+++ b/.claude/hooks/bash-guard.mjs
@@ -41,7 +41,7 @@ if (browserViolation) {
// Validation rules — gated subagents only: the validation hooks already run
// these; manual runs burn budget and can hang (vitest headed without CI=true).
-const GATED_AGENTS = ["developer", "quality-reviewer", "simple-developer"];
+const GATED_AGENTS = ["developer", "quality-reviewer"];
if (!GATED_AGENTS.includes(agent)) process.exit(0);
const runsTypecheck = (c) =>
diff --git a/.claude/hooks/block-merger-without-review.mjs b/.claude/hooks/block-merger-without-review.mjs
index 5724dcef..1bb42ab8 100755
--- a/.claude/hooks/block-merger-without-review.mjs
+++ b/.claude/hooks/block-merger-without-review.mjs
@@ -6,7 +6,7 @@
// dev -> reviewer -> (APPROVED) -> merger ordering structurally.
//
// Verdicts are recorded by record-review-verdict.mjs (SubagentStop) as flags
-// under <sessionDir>/reviews/<TASK>-<role>. Skipped for the SIMPLE flow,
+// under <sessionDir>/reviews/<TASK>-<role>. Skipped for the migration round,
// promotion-only, and rollback dispatches (no per-ticket review), and when the
// ticket can't be identified (fail open, never wedge the flow).
@@ -21,7 +21,7 @@ const d = parseDispatch(input);
if (d.subagentType !== "merger") process.exit(0); // only gate merger dispatches
if (d.mode === "promote") process.exit(0); // promotion-only carries no per-ticket review
-if (["SIMPLE", "PROMOTE", "ROLLBACK"].includes(d.taskId)) process.exit(0);
+if (["MIGRATION", "PROMOTE", "ROLLBACK"].includes(d.taskId)) process.exit(0);
if (!/^TASK-\d+$/.test(d.taskId)) process.exit(0); // can't identify a ticket → fail open
const missing = REVIEW_ROLES.filter(
diff --git a/.claude/hooks/block-migration-writes.mjs b/.claude/hooks/block-migration-writes.mjs
index 1a028046..d94662ff 100755
--- a/.claude/hooks/block-migration-writes.mjs
+++ b/.claude/hooks/block-migration-writes.mjs
@@ -1,5 +1,12 @@
#!/usr/bin/env node
-// PreToolUse(Write|Edit) — enforce deferred migrations: block writes to supabase/migrations-pending/* and writes to supabase/migrations/* by the `developer` agent. simple-developer is allowed (MIGRATION MODE).
+// PreToolUse(Write|Edit) — enforce deferred migrations: block writes to
+// supabase/migrations-pending/* (always) and writes to supabase/migrations/* from
+// anywhere except the <base>/ops worktree. The developer writes migrations only
+// when a dispatch sends it to the `writing-migrations` skill, which runs on the
+// shared <base>/ops worktree; a per-ticket developer writes under <base>/TASK-XXX
+// and must never touch migrations. The worktree path is the discriminator (the
+// dispatch intent isn't visible at Write time), and it is authoritative —
+// setup-worktree derives it, not the dispatch naming.
import { readFileSync } from "node:fs";
import { createHookContext } from "./lib/context.mjs";
@@ -16,19 +23,25 @@ const baseAgent = agent.split("-TASK-")[0];
const isPendingMigration = (p) => p.includes("/supabase/migrations-pending/");
const isMigration = (p) => p.includes("/supabase/migrations/");
+// Migrations are only legitimate in the deploy-time migration round, which always
+// runs on the fixed <base>/ops worktree (the writing-migrations skill).
+const isOpsWorktreeMigration = (p) => p.includes("/ops/supabase/migrations/");
const RULES = [
{
blocked: isPendingMigration(filePath),
tag: "pending-folder",
reason:
- "Writing to supabase/migrations-pending/ is not allowed. Migrations live in supabase/migrations/ and are written only by simple-developer in MIGRATION MODE.",
+ "Writing to supabase/migrations-pending/ is not allowed. Migrations live in supabase/migrations/ and are written only via the writing-migrations skill (on the <base>/ops worktree).",
},
{
- blocked: baseAgent === "developer" && isMigration(filePath),
+ blocked:
+ baseAgent === "developer" &&
+ isMigration(filePath) &&
+ !isOpsWorktreeMigration(filePath),
tag: "developer-migration",
reason:
- "The developer agent is not allowed to write SQL migrations. Only simple-developer in MIGRATION MODE may do so.",
+ "A per-ticket developer is not allowed to write SQL migrations. They are written only via the writing-migrations skill, on the <base>/ops worktree.",
},
];
diff --git a/.claude/hooks/block-promote-unmerged.mjs b/.claude/hooks/block-promote-unmerged.mjs
index b718cc3c..2a156cd3 100755
--- a/.claude/hooks/block-promote-unmerged.mjs
+++ b/.claude/hooks/block-promote-unmerged.mjs
@@ -14,7 +14,7 @@ import { readFileSync } from "node:fs";
import { createHookContext } from "./lib/context.mjs";
import { parseDispatch } from "./lib/dispatch-parse.mjs";
import { getUnmergedTaskBranches, git } from "./lib/git.mjs";
-import { sessionBranch, simpleBranch } from "./lib/topology.mjs";
+import { opsBranch, sessionBranch } from "./lib/topology.mjs";
const input = JSON.parse(readFileSync(0, "utf8"));
const ctx = createHookContext(input, "block-promote-unmerged");
@@ -34,11 +34,11 @@ if (
}
// Task branches under refs/heads/<short>/ with commits not on the session branch.
-// <short>/simple is excluded: the SIMPLE flow / migration round promotes it
+// <short>/ops is excluded: the single-shot rollback/migration round promotes it
// straight to main, never into the session branch, so it is legitimately "ahead"
-// of session/<short> and must not block a COMPLEX promotion. Fails CLOSED — a
+// of session/<short> and must not block a wave promotion. Fails CLOSED — a
// branch whose rev-list count can't be read is reported as unmerged.
-const unmerged = getUnmergedTaskBranches(short, session, [simpleBranch(ctx)]);
+const unmerged = getUnmergedTaskBranches(short, session, [opsBranch(ctx)]);
if (unmerged.length === 0) process.exit(0);
diff --git a/.claude/hooks/cleanup-worktree.mjs b/.claude/hooks/cleanup-worktree.mjs
index f738f338..aeabb613 100755
--- a/.claude/hooks/cleanup-worktree.mjs
+++ b/.claude/hooks/cleanup-worktree.mjs
@@ -2,9 +2,15 @@
// SubagentStop — remove this session's task worktrees once their branch has been
// merged (--no-ff, the merger's contract) into the session integration branch and
// the worktree has no uncommitted changes. Session worktrees/branches (_session,
-// simple, session*/), fresh worktrees, and unmerged work are preserved.
+// ops, session*/), fresh worktrees, and unmerged work are preserved.
-import { existsSync, readdirSync, readFileSync, rmSync, rmdirSync } from "node:fs";
+import {
+ existsSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ rmdirSync,
+} from "node:fs";
import { join } from "node:path";
import { createHookContext } from "./lib/context.mjs";
import {
diff --git a/.claude/hooks/enforce-dev-dispatch.mjs b/.claude/hooks/enforce-dev-dispatch.mjs
index 8d086b56..2656592a 100755
--- a/.claude/hooks/enforce-dev-dispatch.mjs
+++ b/.claude/hooks/enforce-dev-dispatch.mjs
@@ -8,10 +8,11 @@
// the worktree is finished). Keeps the orchestrator on the STATE B dispatch
// template instead of improvising a free-form prompt.
//
-// simple-developer is intentionally NOT gated here: setup-worktree derives its
-// fixed <short>/simple worktree from the session even when the SIMPLE template
-// omits WORKTREE_PATH (the COMPLEX developer has no such fallback — its path is
-// per-ticket and must be carried explicitly).
+// A developer dispatch on the <short>/ops branch (single-shot rollback /
+// migration) is intentionally NOT gated here: setup-worktree derives its fixed
+// <short>/ops worktree from the session, so those templates don't need a
+// per-ticket WORKTREE_PATH (the per-ticket wave developer has no such fallback —
+// its path is per-ticket and must be carried explicitly).
//
// The promotion-conflict-resolver is also a `developer` dispatch but is the one
// sanctioned exception that works in $REPO on `main` under the promote lock (see
@@ -35,6 +36,13 @@ if (d.role === "promotion-conflict-resolver") {
);
}
+// Single-shot ops flows run on the fixed <short>/ops worktree that setup-worktree
+// derives from the session; their templates need no per-ticket WORKTREE_PATH, so
+// skip the per-ticket gate below.
+if (/\/ops$/.test(d.branchName) || /\/ops$/.test(d.worktreePath)) {
+ ctx.accept("single-shot ops developer (<short>/ops) — fixed ops worktree");
+}
+
if (d.isolation === "worktree") {
ctx.fail(
"developer must NOT use isolation:worktree — setup-worktree already creates <WORKTREE_BASE>/TASK-XXX. Drop isolation and pass WORKTREE_PATH + BRANCH_NAME in the prompt (STATE B template).",
diff --git a/.claude/hooks/lib/dispatch-parse.mjs b/.claude/hooks/lib/dispatch-parse.mjs
index 505f3adc..378a506d 100644
--- a/.claude/hooks/lib/dispatch-parse.mjs
+++ b/.claude/hooks/lib/dispatch-parse.mjs
@@ -4,7 +4,7 @@
// block-merger-without-review, block-promote-unmerged) parses through here, so
// the contract regexes live in exactly one place.
//
-// TASK_ID is anchored at line start and only accepts TASK-<n> | SIMPLE | PROMOTE
+// TASK_ID is anchored at line start and only accepts TASK-<n> | MIGRATION | PROMOTE
// | ROLLBACK, so prose mentioning another ticket (e.g. "TASK-001 is merged; now
// merge this one") can never mis-key a gate.
@@ -28,7 +28,7 @@ export function parseDispatch(input) {
isolation: String(ti.isolation ?? ""),
runInBackground: Boolean(ti.run_in_background),
role: grab(/^ROLE:\s*(\S+)/m),
- taskId: grab(/^TASK_ID:\s*(TASK-\d+|SIMPLE|PROMOTE|ROLLBACK)\b/m),
+ taskId: grab(/^TASK_ID:\s*(TASK-\d+|MIGRATION|PROMOTE|ROLLBACK)\b/m),
worktreePath: grab(/^WORKTREE_PATH:\s*(\S+)/m),
branchName: grab(/^BRANCH_NAME:\s*(\S+)/m),
mode: grab(/^MODE:\s*(\S+)/m),
diff --git a/.claude/hooks/lib/git.mjs b/.claude/hooks/lib/git.mjs
index 624dd5fa..6a0970b0 100644
--- a/.claude/hooks/lib/git.mjs
+++ b/.claude/hooks/lib/git.mjs
@@ -62,7 +62,7 @@ export function getWorktreeChangeSummary(wt, base) {
// mirrors it and must stay aligned. Fails CLOSED: a failed/unparseable rev-list
// count is reported as unmerged (count: null) rather than silently treated as
// merged. `exclude` drops branches that legitimately never merge into the session
-// branch (e.g. <short>/simple, which promotes straight to main).
+// branch (e.g. <short>/ops, which promotes straight to main).
export function getUnmergedTaskBranches(short, sessionRef, exclude = []) {
const branches = git([
"for-each-ref",
diff --git a/.claude/hooks/lib/topology.mjs b/.claude/hooks/lib/topology.mjs
index 47d8950e..bcf3dc8c 100644
--- a/.claude/hooks/lib/topology.mjs
+++ b/.claude/hooks/lib/topology.mjs
@@ -1,7 +1,7 @@
// Session worktree/branch topology — the single source for the layout created
// by setup-worktree and torn down by cleanup-worktree:
// <worktreeBase>/TASK-XXX on branch <short>/TASK-XXX (one per ticket)
-// <worktreeBase>/simple on branch <short>/simple (SIMPLE flow / migration)
+// <worktreeBase>/ops on branch <short>/ops (single-shot rollback / migration)
// <worktreeBase>/_session on branch session/<short> (merger integration)
// session-base/<short> (fixed fork anchor)
// Every hook that builds or matches these names must go through this module.
@@ -9,17 +9,17 @@
import { join } from "node:path";
export const taskWorktreePath = (ctx, taskId) => join(ctx.worktreeBase, taskId);
-export const simpleWorktreePath = (ctx) => join(ctx.worktreeBase, "simple");
+export const opsWorktreePath = (ctx) => join(ctx.worktreeBase, "ops");
export const sessionWorktreePath = (ctx) => join(ctx.worktreeBase, "_session");
export const taskBranch = (ctx, taskId) => `${ctx.sessionShort}/${taskId}`;
-export const simpleBranch = (ctx) => `${ctx.sessionShort}/simple`;
+export const opsBranch = (ctx) => `${ctx.sessionShort}/ops`;
export const sessionBranch = (ctx) => `session/${ctx.sessionShort}`;
export const sessionBaseBranch = (ctx) => `session-base/${ctx.sessionShort}`;
// Infrastructure worktrees are never removed by cleanup.
-export const isInfraWorktreePath = (p) => p.endsWith("/_session") || p.endsWith("/simple");
+export const isInfraWorktreePath = (p) => p.endsWith("/_session") || p.endsWith("/ops");
// Session-lifetime branches are never deleted by cleanup.
-export const isProtectedBranch = (b) => /^session(-base)?\//.test(b) || /\/simple$/.test(b);
+export const isProtectedBranch = (b) => /^session(-base)?\//.test(b) || /\/ops$/.test(b);
// Directory names under <worktreeBase> that the leftover sweep may touch.
-export const isTaskWorktreeDirName = (name) => /^TASK-[0-9]+$/.test(name) || name === "simple";
+export const isTaskWorktreeDirName = (name) => /^TASK-[0-9]+$/.test(name) || name === "ops";
diff --git a/.claude/hooks/lib/validation.mjs b/.claude/hooks/lib/validation.mjs
index f1e1bb76..c4060caa 100644
--- a/.claude/hooks/lib/validation.mjs
+++ b/.claude/hooks/lib/validation.mjs
@@ -80,7 +80,7 @@ function runVitest(wt, configFile, projects = []) {
}
// The full validation chain, run by validate-on-stop.mjs on SubagentStop (after
-// every developer / simple-developer stop). Per dirty worktree, fail-fast: prettier auto-fix (+ commit),
+// every developer stop, ticket or lightweight MODE). Per dirty worktree, fail-fast: prettier auto-fix (+ commit),
// typecheck, unit app, unit functions; then e2e once in the repo (full mode
// only). VALIDATE_DRY_RUN=1 skips everything, =fail simulates a failure.
// Returns { ok: true, skipReason? } or { ok: false, step, output }.
diff --git a/.claude/hooks/setup-worktree.mjs b/.claude/hooks/setup-worktree.mjs
index 3f15998f..11ad7011 100755
--- a/.claude/hooks/setup-worktree.mjs
+++ b/.claude/hooks/setup-worktree.mjs
@@ -1,14 +1,15 @@
#!/usr/bin/env node
-// PreToolUse(Agent) — before a developer / simple-developer subagent starts,
-// create its git worktree (forked from the session integration branch) and
-// provision node_modules. Fires on the orchestrator's Agent dispatch, where the
-// dispatched identity (subagent_type, name, prompt) is available — unlike
-// SubagentStart, which in a parallel wave cannot tell which of N developers is
-// starting, so it cannot know the TASK_ID / worktree to create.
+// PreToolUse(Agent) — before a developer subagent starts, create its git
+// worktree (forked from the session integration branch) and provision
+// node_modules. Fires on the orchestrator's Agent dispatch, where the dispatched
+// identity (subagent_type, name, prompt) is available — unlike SubagentStart,
+// which in a parallel wave cannot tell which of N developers is starting, so it
+// cannot know the TASK_ID / worktree to create.
//
// Identity: a real TASK id (TASK-001) from the prompt's TASK_ID line or the
-// dispatch name (developer-TASK-001) → <base>/<TASK_ID>; a simple-developer with
-// no task → <base>/simple. Paths are derived from topology (authoritative),
+// dispatch name (developer-TASK-001) → <base>/<TASK_ID> (per-ticket wave); a
+// developer dispatch on the <short>/ops branch (rollback-conflict / migration,
+// no task) → <base>/ops. Paths are derived from topology (authoritative),
// matching the value the orchestrator substitutes into WORKTREE_PATH.
//
// Also resets stale review verdicts for a (re)dispatched developer, so a changed
@@ -32,11 +33,11 @@ import { getBaseBranch, getWorktreePaths, git } from "./lib/git.mjs";
import { REVIEW_ROLES, reviewFlag } from "./lib/reviews.mjs";
import { getFirstTaskId } from "./lib/teams.mjs";
import {
+ opsBranch,
+ opsWorktreePath,
sessionBaseBranch,
sessionBranch,
sessionWorktreePath,
- simpleBranch,
- simpleWorktreePath,
taskBranch,
taskWorktreePath,
} from "./lib/topology.mjs";
@@ -52,12 +53,18 @@ const input = JSON.parse(readFileSync(0, "utf8"));
const ctx = createHookContext(input, "setup-worktree");
const d = parseDispatch(input);
-// Only act on developer / simple-developer dispatches; reviewers, merger,
-// planner and documentator reuse (or never touch) a worktree.
-if (d.subagentType !== "developer" && d.subagentType !== "simple-developer") {
+// Only act on developer dispatches; reviewers, merger, planner and documentator
+// reuse (or never touch) a worktree.
+if (d.subagentType !== "developer") {
process.exit(0);
}
+// A developer dispatch whose branch/worktree is <short>/ops runs single-shot on
+// the shared <base>/ops worktree (rollback-conflict replay, deploy-time
+// migration) instead of a per-ticket one. The /ops branch is the discriminator;
+// every other developer dispatch is a per-ticket wave developer.
+const isOps = /\/ops$/.test(d.branchName) || /\/ops$/.test(d.worktreePath);
+
const taskId =
(/^TASK-\d+$/.test(d.taskId) && d.taskId) || getFirstTaskId(d.name);
@@ -66,9 +73,9 @@ let branchName;
if (taskId) {
worktreePath = taskWorktreePath(ctx, taskId);
branchName = taskBranch(ctx, taskId);
-} else if (d.subagentType === "simple-developer") {
- worktreePath = simpleWorktreePath(ctx);
- branchName = simpleBranch(ctx);
+} else if (isOps) {
+ worktreePath = opsWorktreePath(ctx);
+ branchName = opsBranch(ctx);
} else if (d.role === "promotion-conflict-resolver") {
// The sanctioned $REPO-on-main exception (see enforce-dev-dispatch /
// worktree-scope): it works directly in the repo under the promote lock and
@@ -78,18 +85,18 @@ if (taskId) {
);
} else {
// A developer that passed enforce-dev-dispatch (so it carries WORKTREE_PATH)
- // but whose TASK id can't be resolved from TASK_ID or the dispatch name. We
- // can't derive the canonical worktree path; accepting would let the developer
- // cd into a directory that was never created. Fail closed instead.
+ // but is neither a resolvable TASK-XXX nor an <short>/ops dispatch. We can't
+ // derive the canonical worktree path; accepting would let the developer cd into
+ // a directory that was never created. Fail closed instead.
ctx.fail(
- "developer dispatch carries WORKTREE_PATH but no resolvable TASK-XXX id (expected a 'TASK_ID: TASK-XXX' line or a 'developer-TASK-XXX' name). Use the STATE B dispatch template with a real ticket id.",
+ "developer dispatch carries WORKTREE_PATH but no resolvable TASK-XXX id and no <short>/ops branch (expected a 'TASK_ID: TASK-XXX' line, a 'developer-TASK-XXX' name, or 'BRANCH_NAME: <SESSION_SHORT_ID>/ops'). Use the STATE B dispatch template.",
{ log: "BLOCK unresolvable task id" },
);
}
mkdirSync(ctx.sessionDir, { recursive: true });
-// Serialise the git-mutation region per session: a COMPLEX wave dispatches N
+// Serialise the git-mutation region per session: a wave dispatches N
// developers in ONE orchestrator message, so N PreToolUse hooks can fire nearly
// together and race on session-branch / _session creation and git's internal
// worktree locks. A best-effort advisory lock (atomic mkdir + bounded spin,
@@ -179,7 +186,7 @@ if (taskId) {
}
ctx.log(
- `START agent=${d.subagentType} path=${worktreePath} branch=${branchName}`,
+ `START agent=${d.subagentType}${d.mode ? ` mode=${d.mode}` : ""} path=${worktreePath} branch=${branchName}`,
);
if (getWorktreePaths().includes(worktreePath)) {
diff --git a/.claude/hooks/test/bash-guard.test.mjs b/.claude/hooks/test/bash-guard.test.mjs
index 87c069cc..ee030a52 100644
--- a/.claude/hooks/test/bash-guard.test.mjs
+++ b/.claude/hooks/test/bash-guard.test.mjs
@@ -71,8 +71,8 @@ describe("bash-guard hook", () => {
const cases = [
["developer", "npm run typecheck"],
["developer", "npx tsc --noEmit"],
- ["simple-developer", "npx vitest run"],
- ["simple-developer", "npm run prettier:apply"],
+ ["developer", "npx vitest run"],
+ ["developer", "npm run prettier:apply"],
["quality-reviewer", "npx playwright test --headless"],
["quality-reviewer", "make lint"],
["developer", "npm run build"],
diff --git a/.claude/hooks/test/block-merger-without-review.test.mjs b/.claude/hooks/test/block-merger-without-review.test.mjs
index f0d35e79..06fdc619 100644
--- a/.claude/hooks/test/block-merger-without-review.test.mjs
+++ b/.claude/hooks/test/block-merger-without-review.test.mjs
@@ -1,7 +1,7 @@
// Tests for block-merger-without-review.mjs — the PreToolUse(Agent) gate that
// blocks a per-ticket merger until the quality-reviewer recorded APPROVED (flags
// under <sessionDir>/reviews/<TASK>-<role>, written by record-review-verdict.mjs). The
-// gate exits 2 to block and 0 to allow. Skipped for promotion-only / SIMPLE /
+// gate exits 2 to block and 0 to allow. Skipped for promotion-only / MIGRATION /
// ROLLBACK dispatches and when the ticket id can't be parsed (fail open).
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
@@ -64,9 +64,9 @@ describe("block-merger-without-review", () => {
expect(run(`ROLE: merger\nMODE: promote\nSESSION_SHORT_ID: ${SS}`)).toBe(0);
});
- test("ignores the SIMPLE merger (no per-ticket review)", () => {
+ test("ignores the MIGRATION merger (no per-ticket review)", () => {
expect(
- run(`ROLE: merger\nTASK_ID: SIMPLE\nBRANCH_NAME: ${SS}/simple`),
+ run(`ROLE: merger\nTASK_ID: MIGRATION\nBRANCH_NAME: ${SS}/ops`),
).toBe(0);
});
diff --git a/.claude/hooks/test/block-promote-unmerged.test.mjs b/.claude/hooks/test/block-promote-unmerged.test.mjs
index a19bcbd8..a423505b 100644
--- a/.claude/hooks/test/block-promote-unmerged.test.mjs
+++ b/.claude/hooks/test/block-promote-unmerged.test.mjs
@@ -102,14 +102,14 @@ describe("block-promote-unmerged", () => {
expect(run(PROMOTE)).toBe(0);
});
- test("ignores the <short>/simple branch even when ahead of the session branch", () => {
- // <short>/simple promotes straight to main (never into the session branch),
+ test("ignores the <short>/ops branch even when ahead of the session branch", () => {
+ // <short>/ops promotes straight to main (never into the session branch),
// so its commits are legitimately not on session/<short> and must NOT block a
- // COMPLEX promotion.
- g("checkout", "-q", "-b", `${SS}/simple`, "main");
- writeFileSync(join(APP_DIR, "simple.txt"), "s\n");
+ // wave promotion.
+ g("checkout", "-q", "-b", `${SS}/ops`, "main");
+ writeFileSync(join(APP_DIR, "ops.txt"), "s\n");
g("add", ".");
- g("commit", "-qm", "feat: a simple change");
+ g("commit", "-qm", "feat: an ops change");
g("checkout", "-q", "main");
expect(run(PROMOTE)).toBe(0);
});
diff --git a/.claude/hooks/test/dispatch-parse.test.mjs b/.claude/hooks/test/dispatch-parse.test.mjs
index c6fb021e..635e8186 100644
--- a/.claude/hooks/test/dispatch-parse.test.mjs
+++ b/.claude/hooks/test/dispatch-parse.test.mjs
@@ -32,11 +32,12 @@ describe("parseDispatch", () => {
expect(d.taskId).toBe("");
});
- test("recognises SIMPLE / ROLLBACK skip keys", () => {
+ test("recognises MIGRATION / ROLLBACK skip keys", () => {
expect(
- parseDispatch({ tool_input: { prompt: "ROLE: merger\nTASK_ID: SIMPLE" } })
- .taskId,
- ).toBe("SIMPLE");
+ parseDispatch({
+ tool_input: { prompt: "ROLE: merger\nTASK_ID: MIGRATION" },
+ }).taskId,
+ ).toBe("MIGRATION");
expect(
parseDispatch({
tool_input: { prompt: "ROLE: merger\nTASK_ID: ROLLBACK" },
diff --git a/.claude/hooks/test/setup-worktree.test.mjs b/.claude/hooks/test/setup-worktree.test.mjs
index e0b60a72..f8951c3a 100755
--- a/.claude/hooks/test/setup-worktree.test.mjs
+++ b/.claude/hooks/test/setup-worktree.test.mjs
@@ -38,8 +38,8 @@ const dispatch = ({
taskId = "",
name = "",
} = {}) => {
- const wp = taskId ? join(WB, taskId) : join(WB, "simple");
- const branch = taskId ? `${SS}/${taskId}` : `${SS}/simple`;
+ const wp = taskId ? join(WB, taskId) : join(WB, "ops");
+ const branch = taskId ? `${SS}/${taskId}` : `${SS}/ops`;
const prompt =
`ROLE: ${subagentType}\n` +
(taskId ? `TASK_ID: ${taskId}\n` : "") +
@@ -153,20 +153,20 @@ describe("setup-worktree session-branch topology (PreToolUse/Agent)", () => {
expect(existsSync(join(WB, "_session", ".git"))).toBe(true);
});
- test("simple-developer without WORKTREE_PATH derives the simple worktree", () => {
+ test("developer on the <short>/ops branch derives the ops worktree", () => {
spawnSync("node", [HOOK], {
input: JSON.stringify({
session_id: SESSION_ID,
tool_input: {
- subagent_type: "simple-developer",
- name: "simple-developer",
- prompt: "ROLE: simple-developer\nCHANGE_REQUEST: rename a button",
+ subagent_type: "developer",
+ name: "developer",
+ prompt: `ROLE: developer\nWORKTREE_PATH: ${join(WB, "ops")}\nBRANCH_NAME: ${SS}/ops`,
},
}),
env,
encoding: "utf8",
});
- expect(existsSync(join(WB, "simple"))).toBe(true);
+ expect(existsSync(join(WB, "ops"))).toBe(true);
});
test("developer with WORKTREE_PATH but unresolvable task id is blocked (exit 2)", () => {
diff --git a/.claude/hooks/test/validate-on-stop.test.mjs b/.claude/hooks/test/validate-on-stop.test.mjs
index 6078ea2a..fb5e58bd 100644
--- a/.claude/hooks/test/validate-on-stop.test.mjs
+++ b/.claude/hooks/test/validate-on-stop.test.mjs
@@ -18,7 +18,7 @@ afterAll(() => {
rmSync(tmpRoot, { recursive: true, force: true });
});
-const INPUT = '{"session_id":"test-1234","agent_type":"simple-developer"}';
+const INPUT = '{"session_id":"test-1234","agent_type":"developer"}';
const runHook = (dryRun) => {
const env = {
diff --git a/.claude/hooks/validate-on-stop.mjs b/.claude/hooks/validate-on-stop.mjs
index 4ee9effa..a2e0e807 100755
--- a/.claude/hooks/validate-on-stop.mjs
+++ b/.claude/hooks/validate-on-stop.mjs
@@ -7,7 +7,7 @@ import { git } from "./lib/git.mjs";
import { getFirstTaskId } from "./lib/teams.mjs";
import {
sessionBranch,
- simpleWorktreePath,
+ opsWorktreePath,
taskWorktreePath,
} from "./lib/topology.mjs";
import { runValidationSteps } from "./lib/validation.mjs";
@@ -21,18 +21,22 @@ try {
payload = {};
}
-// Scope validation to the stopping subagent's OWN worktree: developer-TASK-XXX
-// validates <base>/TASK-XXX, simple-developer validates <base>/simple. Avoids the
+// Scope validation to the stopping subagent's OWN worktree: a per-ticket
+// developer-TASK-XXX validates <base>/TASK-XXX, a single-shot ops developer (on
+// the <short>/ops branch — rollback / migration) validates <base>/ops. Avoids the
// "shared brakes" failure where one ticket's broken state blocks an unrelated
// developer and N stops each re-validate every session worktree. Falls back to
// all session worktrees when the identity can't be resolved.
const ids = [ctx.agentName, ctx.agentType].filter(Boolean);
-const isSimple = ids.some((n) => /simple-developer/.test(n));
let taskId = ids.map(getFirstTaskId).find(Boolean) || "";
+// A single-shot ops developer runs on the shared <base>/ops worktree; its agent
+// name carries no TASK suffix, so it's recovered from the dispatch prompt below.
+let isOps = false;
-// No suffixed agent name in this harness → recover TASK_ID from the dispatch
-// prompt in the transcript, to scope validation to this dev's worktree (not wt=all).
-if (!taskId && !isSimple) {
+// No suffixed agent name in this harness → recover the TASK_ID (or the single-shot
+// ops flow) from the dispatch prompt in the transcript, to scope validation to
+// this dev's worktree (not wt=all).
+if (!taskId) {
const tp = payload.agent_transcript_path || payload.transcript_path;
if (tp && existsSync(tp)) {
try {
@@ -45,6 +49,9 @@ if (!taskId && !isSimple) {
taskId = m[1];
break;
}
+ if (/BRANCH_NAME[:=\s]+\S+\/ops\b/.test(line)) {
+ isOps = true;
+ }
}
} catch {
// best-effort — fall back to all-worktree validation below
@@ -54,12 +61,16 @@ if (!taskId && !isSimple) {
const ownWorktree = taskId
? taskWorktreePath(ctx, taskId)
- : isSimple
- ? simpleWorktreePath(ctx)
+ : isOps
+ ? opsWorktreePath(ctx)
: "";
-// Diff each worktree against the branch it forked from (session/<short>), not the
-// repo's checked-out base branch, so validation sees the ticket's OWN change set.
+// Diff each worktree against session/<short>, not the repo's checked-out base
+// branch, so validation sees a per-ticket developer's OWN change set. (A
+// single-shot ops developer is the exception: resolving-rollback-conflicts does
+// `git reset --hard <BASE_BRANCH>`, re-forking <short>/ops onto the default
+// branch, so its diff against session/<short> can span unrelated files — accepted
+// noise, since the rollback's whole point is to diverge from the session.)
// Empty base → validation.mjs falls back to the repo base branch (e.g. before the
// session branch exists).
const sessionRef = sessionBranch(ctx);
diff --git a/.claude/rules/agent-output-format.md b/.claude/rules/agent-output-format.md
index 1f3614ef..a01d0814 100644
--- a/.claude/rules/agent-output-format.md
+++ b/.claude/rules/agent-output-format.md
@@ -19,7 +19,7 @@ Anything above the contract line is informational and discarded by the orchestra
Any other shape is treated by the orchestrator as `REJECTED: <malformed reviewer output>`.
-(The SIMPLE-flow single-shot quality-reviewer and the migration-review reviewer keep their own `APPROVED` / `BLOCKED:` text contract — see quality-reviewer.md. The orchestrator parses those in the SIMPLE / migration flow, not the COMPLEX-wave parser above.)
+(The single-shot `migration-review` reviewer keeps its own `APPROVED` / `BLOCKED:` text contract — see quality-reviewer.md. The orchestrator parses that in the migration round, not with the wave parser above.)
## Developer agent
@@ -32,15 +32,17 @@ When the spawn prompt includes a `RETRY_FEEDBACK=...` block, the developer is on
Any other shape is treated by the orchestrator as `FAILED`.
+(The two single-shot **ops-mode** developer dispatches define their OWN contract in their skill — these supersede the line above for that dispatch only: `writing-migrations` emits `DONE: branch=<short>/ops migration=<filename> summary=<...>` or `NO_MIGRATION_NEEDED`; `resolving-rollback-conflicts` emits `DONE: branch=<short>/ops files=[<...>]`. The orchestrator parses these in their respective states, PD-MIG-DEV / STATE RB-DEV.)
+
## Merger agent
Last line of output MUST be exactly one of:
-- `DONE: <TASK_ID> commit=<short_sha>` — `<TASK_ID>` matches the spawn prompt (e.g. `TASK-003`, or the literal `SIMPLE` / `ROLLBACK` / `PROMOTE`).
+- `DONE: <TASK_ID> commit=<short_sha>` — `<TASK_ID>` matches the spawn prompt (e.g. `TASK-003`, or the literal `MIGRATION` / `ROLLBACK` / `PROMOTE`).
- `FAILED: <TASK_ID> <one-line reason>`
Any other shape is treated by the orchestrator as `FAILED: <TASK_ID> <malformed merger output>`.
-## Status updates (COMPLEX flow only)
+## Status updates (wave flow only)
The merger updates `${TICKETS_DIR}/TASK-XXX.json` `status` to `merged` after a successful merge. The developer does not write the ticket file — its `DONE: ...` line is sufficient for the orchestrator.
diff --git a/.claude/rules/english-only.md b/.claude/rules/english-only.md
index fc5b9d9d..a9a7f041 100644
--- a/.claude/rules/english-only.md
+++ b/.claude/rules/english-only.md
@@ -20,7 +20,7 @@ English when it doesn't change the semantics.
## Speaking another language at runtime
Agents that converse with the user (chat-orchestrator, project-manager,
-simple-developer, etc.) MUST reply in the user's language at runtime.
+etc.) MUST reply in the user's language at runtime.
Achieve this with English instructions plus a directive like *"reply in
the user's language"* — never by hard-coding non-English templates inside
the agent prompt.
diff --git a/.claude/rules/validation-commands.md b/.claude/rules/validation-commands.md
index df3a2312..10e325a1 100644
--- a/.claude/rules/validation-commands.md
+++ b/.claude/rules/validation-commands.md
@@ -5,8 +5,8 @@ paths: []
# Validation commands — DO NOT RUN
Validation is automated:
-- The `validate-on-stop.mjs` SubagentStop hook runs the full chain (prettier auto-fix, typecheck, unit, e2e) after every developer (and simple-developer) stops. A failed validation rejects the stop, the developer's internal loop fixes the issue, and only a green stop returns control to the orchestrator.
-- The `bash-guard.mjs` PreToolUse hook blocks `developer`, `simple-developer`, `quality-reviewer` from running them manually.
+- The `validate-on-stop.mjs` SubagentStop hook runs the full chain (prettier auto-fix, typecheck, unit, e2e) after every developer stop (ticket or lightweight MODE). A failed validation rejects the stop, the developer's internal loop fixes the issue, and only a green stop returns control to the orchestrator.
+- The `bash-guard.mjs` PreToolUse hook blocks `developer`, `quality-reviewer` from running them manually.
- Prettier is auto-applied and committed by the validation chain — formatting never needs manual action unless a file has a syntax error.
## Forbidden commands (developer / quality-reviewer)
diff --git a/.claude/settings.json b/.claude/settings.json
index b20e7a74..34133029 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -115,7 +115,7 @@
]
},
{
- "matcher": "simple-developer|developer",
+ "matcher": "developer",
"hooks": [
{
"type": "command",
diff --git a/.claude/skills/adr-writing/SKILL.md b/.claude/skills/adr-writing/SKILL.md
index 59276f78..d5ae6877 100644
--- a/.claude/skills/adr-writing/SKILL.md
+++ b/.claude/skills/adr-writing/SKILL.md
@@ -29,7 +29,7 @@ Path: `<WORKTREE_PATH>/adr/ADR-<SESSION_SHORT_ID>-<TASK-XXX>-<slug>.md`
- `<slug>` is kebab-case, ASCII, ≤ 40 chars.
- One ADR per ticket is the common case. If the same ticket genuinely needs two ADRs, the distinct slugs keep them apart.
-**Why the session+ticket namespace**: in a COMPLEX wave, N developers run in parallel on worktrees branched from the same base. A monotonically-incremented `ADR-NNN-…` scheme makes every worker independently pick the same next number (e.g. all land on `ADR-003`); different slugs hide the collision from `git merge`, so duplicate numbers land in `$CLAUDE_PROJECT_DIR/adr/` silently. `<TASK-XXX>` removes the intra-wave collision; the `<SESSION_SHORT_ID>` prefix removes the cross-session one — ticket numbering restarts at TASK-001 each session, so two sessions both producing a `TASK-004` would otherwise overwrite each other's ADR in the shared `$CLAUDE_PROJECT_DIR/adr/`.
+**Why the session+ticket namespace**: in a wave, N developers run in parallel on worktrees branched from the same base. A monotonically-incremented `ADR-NNN-…` scheme makes every worker independently pick the same next number (e.g. all land on `ADR-003`); different slugs hide the collision from `git merge`, so duplicate numbers land in `$CLAUDE_PROJECT_DIR/adr/` silently. `<TASK-XXX>` removes the intra-wave collision; the `<SESSION_SHORT_ID>` prefix removes the cross-session one — ticket numbering restarts at TASK-001 each session, so two sessions both producing a `TASK-004` would otherwise overwrite each other's ADR in the shared `$CLAUDE_PROJECT_DIR/adr/`.
## Source-code reference
diff --git a/.claude/skills/resolving-rollback-conflicts/SKILL.md b/.claude/skills/resolving-rollback-conflicts/SKILL.md
new file mode 100644
index 00000000..1689f795
--- /dev/null
+++ b/.claude/skills/resolving-rollback-conflicts/SKILL.md
@@ -0,0 +1,158 @@
+---
+name: resolving-rollback-conflicts
+description: Replay a list of git-revert commits against the current base branch and resolve the conflicts, when the chat-service's automatic rollback hit a merge conflict it couldn't resolve. Load this when your developer dispatch asks you to resolve a rollback conflict (it carries BASE_BRANCH, FAILED_COMMIT, COMMITS_TO_REVERT). This is NOT a feature ticket — the workflow below replaces the normal ticket rules.
+---
+
+# Resolving rollback conflicts
+
+The chat-service's HTTP `/rollback` route attempted to `git revert -m 1 <sha>` each merge commit on the base branch, and one of them conflicted. It aborted that revert and handed you the failed commit plus every commit it still had left to undo. Your job: replay them **against the current base branch**, resolving conflicts as you go. You are dispatched **alone** — no team, no peers. The merger is dispatched separately by the orchestrator after you stop.
+
+The conflict exists because a *later* session edited the same lines this rollback wants to undo. That conflict only shows up against the current base branch — not against the stale `session/<SESSION_SHORT_ID>` your worktree was forked from. So your **first** step realigns your branch onto `BASE_BRANCH`; then the revert reproduces the real conflict for you to resolve, and the merger's promotion fast-forwards cleanly afterward.
+
+## Spawn prompt — what you receive
+
+```
+ROLE: developer
+WORKTREE_PATH: <WORKTREE_BASE>/ops
+BRANCH_NAME: <SESSION_SHORT_ID>/ops
+BASE_BRANCH: <the default branch, e.g. master — the promotion target>
+FAILED_COMMIT: <short sha> ("<subject>")
+COMMITS_TO_REVERT:
+ - <sha> # <subject>
+ - ...
+```
+
+**Working directory is `<WORKTREE_PATH>`** — the shared `<base>/ops` worktree the `setup-worktree` hook creates for you. Every Bash call must `cd <WORKTREE_PATH> && …` (shell state is stateless between calls). Do NOT touch `$CLAUDE_PROJECT_DIR/src/...` — that's the base branch.
+
+## Output contract
+
+Your very last line of output MUST be exactly one of:
+
+- `DONE: branch=<SESSION_SHORT_ID>/ops files=[<every file you touched, deduped>]`
+- `FAILED: <one-line, plain-English reason — say what was confusing>`
+
+The orchestrator's STATE RB-MERGE relies on those literal prefixes.
+
+## Workflow
+
+### Step 0 — Realign your branch onto the base branch (do this ONCE, first)
+
+Your worktree was forked from the stale `session/<SESSION_SHORT_ID>`, where the conflicting later changes don't exist — revert there and it applies cleanly but the conflict resurfaces, unresolved, at promotion. Reset your branch onto the current base branch so you replay the reverts against the exact state the HTTP route hit the conflict on:
+
+```bash
+cd <WORKTREE_PATH> && git reset --hard <BASE_BRANCH>
+```
+
+This is the only branch-moving command you may run, and only here. After it, proceed to the loop below.
+
+Then, for each SHA in `COMMITS_TO_REVERT`, in the order given:
+
+### Step 1 — Read the commit you're about to undo
+
+Before touching anything, get the canonical record of what this commit changed. This is the **ground truth** you'll use to resolve conflicts and to interpret empty reverts:
+
+```bash
+cd <WORKTREE_PATH> && git show --stat <sha> # which files, how big
+cd <WORKTREE_PATH> && git show <sha> # full diff
+```
+
+Read the diff. Identify, in your head, **exactly** what this commit added (the `+` lines on the "after" side) and what it replaced (the `-` lines). The revert's job is to remove the `+` and put back the `-` — nothing else.
+
+### Step 2 — Attempt the revert
+
+```bash
+cd <WORKTREE_PATH> && git revert --no-edit -m 1 <sha>
+```
+
+Three possible outcomes — match yours below.
+
+### Outcome A — Clean revert with real changes
+
+`git revert` exited 0 AND `git diff --name-only HEAD^ HEAD` is non-empty. Sanity-check: do the changed files / changed lines match what Step 1 told you to expect? If yes, go to next SHA.
+
+### Outcome B — Empty revert (clean exit, zero changes)
+
+`git revert` exited 0 BUT `git diff --name-only HEAD^ HEAD` is empty.
+
+This means a later commit on the base branch has **already removed or transformed** the lines your target commit added. Two sub-cases:
+
+- **B1 — Pure substitution** (e.g. target said `X → Y`, current main says `Z`): the user's intent — "undo X → Y" — can sometimes still be expressed as `Z → X`. Look at Step 1's `+` strings; grep current main for them; if they're absent but the file at the same location now has a different value, that's the later commit's overwrite. Edit the file to replace that later value with the original `-` strings from Step 1. Then commit **with the revert marker** so a future rollback knows this commit was already undone:
+ ```bash
+ cd <WORKTREE_PATH> && git add -A && git commit -m "revert: semantic revert of <sha-short>" -m "This reverts commit <FULL 40-char sha>."
+ ```
+ The second `-m` line is mandatory: the chat-service detects already-reverted commits by scanning for `This reverts commit <sha>`. Native `git revert` / `git revert --continue` write this marker automatically; a manual semantic revert must add it explicitly or the commit will be re-reverted on the next rollback. Re-check with `git diff --name-only HEAD^ HEAD` — it should be non-empty now.
+- **B2 — Target already fully absent** (the later commit removed the addition entirely, no equivalent value to swap): the target commit's effect is already gone from main. Nothing to revert.
+ ```bash
+ cd <WORKTREE_PATH> && git reset --hard HEAD^
+ ```
+ ```
+ FAILED: revert of <sha> produced no changes — its additions have already been removed by a later commit
+ ```
+
+If you're unsure which sub-case applies, prefer B2 (FAILED) — a confusing-but-honest failure is better than a hallucinated edit that touches files the user didn't expect.
+
+### Outcome C — Conflict (non-zero exit, unmerged paths)
+
+`git status` shows `You are currently reverting commit <sha>` plus `UU`/`AA`/`DU`/`UD` entries.
+
+```bash
+cd <WORKTREE_PATH> && git status --porcelain
+cd <WORKTREE_PATH> && git diff --diff-filter=U
+```
+
+For each conflict file, the markers look like:
+
+```
+<<<<<<< HEAD
+<current state on the base branch — includes whatever later commits added>
+=======
+<state after applying the revert — the target commit's additions are removed,
+ but later commits' additions on the SAME lines might also be missing here>
+>>>>>>> parent of <sha>...
+```
+
+**Goal**: produce a version where the target commit's `+` lines (from Step 1) are removed, but **every** later commit's contribution that you can identify is preserved.
+
+Heuristic, in order:
+
+1. **Read both sides side-by-side**. Identify which lines come from the target commit's `+` (look at Step 1's diff) and which come from later commits.
+2. **Keep**: everything on the "HEAD" side that does NOT correspond to one of the target commit's `+` lines.
+3. **Drop**: the target commit's `+` lines (and only those).
+4. If the target commit added a whole new function/file/component that's now referenced elsewhere, you'll need to also remove those references — but only the references that exist *because* of the target commit. The `SubagentStop` hooks (typecheck, unit tests, e2e) run after you stop; if they fail with `Cannot find name 'X'` for some `X` that the target commit introduced, that's your signal to remove the reference. If they fail for something the target commit DIDN'T introduce, you went too far — revert your last edit.
+
+After resolving every conflict file:
+
+```bash
+cd <WORKTREE_PATH> && git add -A && git revert --continue --no-edit
+```
+
+Then re-check `git diff --name-only HEAD^ HEAD`. If empty, apply the Outcome B logic. Otherwise, go to next SHA.
+
+### Step 3 — All SHAs processed
+
+Emit the output contract:
+
+```
+DONE: branch=<SESSION_SHORT_ID>/ops files=[<every file you touched, deduped>]
+```
+
+The orchestrator's STATE RB-MERGE will dispatch the single-shot merger to merge your branch back into the base.
+
+### Step 4 — Unrecoverable failure
+
+If at any point you can't make progress (a conflict you genuinely can't read, three rounds of validation hook failures with no fix in sight, etc.):
+
+```bash
+cd <WORKTREE_PATH> && git revert --abort 2>/dev/null || true
+```
+```
+FAILED: rollback merge failed: <one-line, plain-English reason — say what was confusing>
+```
+
+## NEVER while resolving a rollback conflict
+
+- ❌ Run `git merge`, `git push`, `git checkout`, `--no-verify`. The only branch-moving commands allowed are: `git reset --hard <BASE_BRANCH>` exactly once at Step 0, and `git reset --hard HEAD^` to undo your own empty revert as documented in Outcome B.
+- ❌ Edit anything outside `<WORKTREE_PATH>/`. Never edit `$CLAUDE_PROJECT_DIR/...` directly, never edit `.git/` internals.
+- ❌ Drive-by refactors, prettier formatting changes, or unrelated edits. Edits must be **caused** by the revert (target additions to remove) or by a typecheck/unit/e2e failure that the revert created.
+- ❌ Dispatch agents or `SendMessage` — you are solo here.
+- ❌ Stop without either `DONE:` or `FAILED:` — the orchestrator's STATE RB-MERGE relies on those literal prefixes.
diff --git a/.claude/skills/writing-migrations/SKILL.md b/.claude/skills/writing-migrations/SKILL.md
index 74729ab8..daa8ab3d 100644
--- a/.claude/skills/writing-migrations/SKILL.md
+++ b/.claude/skills/writing-migrations/SKILL.md
@@ -1,15 +1,21 @@
---
name: writing-migrations
-description: Generate Supabase SQL migrations at deploy time from the session branch diff. Used by simple-developer in the deploy-time migration round only.
+description: Generate Supabase SQL migrations at deploy time from the session branch diff. Load this when your developer dispatch asks you to generate the deploy-time migration (it points you at the shared <base>/ops worktree). This is NOT a feature ticket — the workflow below replaces the normal ticket rules: here you DO write SQL under supabase/migrations/, and you do not edit TS/TSX/CSS.
---
# Writing Migrations (deploy-time round)
-You are `simple-developer` in migration mode. Your worktree is
-`<WORKTREE_BASE>/simple` on `<SESSION_SHORT_ID>/simple`,
+You (the `developer`) have been asked to generate the deploy-time migration.
+Your worktree is `<WORKTREE_BASE>/ops` on `<SESSION_SHORT_ID>/ops`,
forked from `session/<SESSION_SHORT_ID>` (`<WORKTREE_BASE>` =
`/tmp/<$CLAUDE_PROJECT_DIR with every "/" replaced by "_">/<SESSION_ID>`). Produce SQL migrations that make the
-real Supabase schema match what this session's app expects — nothing more.
+real Supabase schema match what this session's app expects — nothing more. The
+"never write migrations / no schema" rule of normal ticket work does NOT apply
+here: writing SQL under `supabase/migrations/` is the whole job. Do not edit any
+TS/TSX/CSS — the schema diff already comes from the session branch; you only
+translate it to SQL.
+
+Every Bash call must `cd <WORKTREE_PATH> && …` (stateless shells).
## 1. Compute the session's net change
@@ -94,8 +100,20 @@ look prettier — schema drift breaks future `supabase db diff` generations.
## 6. Commit and hand off
-Commit the SQL on `<SESSION_SHORT_ID>/simple`. Stop. SubagentStop hooks
-(typecheck/prettier/unit/e2e) run automatically. The orchestrator then sends you
-to quality-reviewer (migration mode) and the merger.
+Commit the SQL on `<SESSION_SHORT_ID>/ops`:
+
+```bash
+cd <WORKTREE_PATH> && git add supabase/migrations && git commit -m "migration(<SESSION_SHORT_ID>): <slug>"
+```
+
+Then stop and emit the output contract as your very last line — one of:
+
+- `DONE: branch=<SESSION_SHORT_ID>/ops migration=<filename> summary=<what the SQL does>`
+- `NO_MIGRATION_NEEDED` — only after computing the diff (step 1) and confirming no schema impact.
+- `FAILED: <one-line reason>`
+
+SubagentStop hooks (typecheck/prettier/unit/e2e) run automatically; they should
+pass since you only touched SQL. The orchestrator then sends you to
+quality-reviewer (`MODE: migration-review`) and the merger.
For Postgres correctness you may load `Skill({skill: "supabase-postgres-best-practices"})`.
diff --git a/CLAUDE.md b/CLAUDE.md
index 15a3036a..7fd90958 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4,20 +4,17 @@
This project ships CRM changes through a coordinated agent team rather than a single implementer. Once a plan is approved (via `ExitPlanMode`), the main thread / orchestrator does not implement directly — it routes the work to the custom agents defined under `.claude/agents/`. Each agent's full contract lives in its own file; this section is the map of who does what, and in which order.
-## Routing: SIMPLE vs COMPLEX
+## Routing: one pipeline for every change
-The **chat-orchestrator** is the user-facing entry point. It routes, narrates progress, and never implements. It classifies each request:
+The **chat-orchestrator** is the user-facing entry point. It routes, narrates progress, and never implements. There is **no SIMPLE-vs-COMPLEX triage**: every request that changes the CRM code or schema — a one-line label rename just as much as a new entity with relations — runs the **same pipeline** below. A tiny change is simply a one-ticket wave. The orchestrator only branches away from this pipeline for non-code operational intents: SETUP (project scoping), MODE-SWITCH (demo/real data), MEMORY (capture a pattern), ROLLBACK-CONFLICT (resolve a failed automatic revert), and RECOVERY (resume after an interruption).
-- **SIMPLE** — one cosmetic edit, OR a single-field change on an existing entity (schema + view + type + form + show), OR one list filter that reuses existing components (no new custom React component). Dispatched straight to a **simple-developer** + **merger** — no team, no peer review. `SubagentStop` hooks validate; a deploy-time migration round runs only if a migration was written.
-- **COMPLEX** — everything else. Goes through the full planner → wave → review → merge pipeline below.
+## The pipeline
-## COMPLEX pipeline
-
-1. **planner** — decompose the approved plan into atomic, ordered tickets (JSON) with best-guess file paths and dependency waves. Skip only when the plan is already a single atomic deliverable (one file, one fix, one migration).
+1. **planner** — decompose the approved plan into atomic, ordered tickets (JSON) with best-guess file paths and dependency waves. Skip only when the plan is already a single atomic deliverable (one file, one fix).
2. **developer** (one per ticket) — implement + commit inside the ticket's git worktree. Tickets in the same wave (`parallel_safe: true`, no mutual dependency) are spawned concurrently as **foreground** subagents — a single message with multiple `Agent(...)` tool uses (no `run_in_background`); the orchestrator's turn resumes once they all return. Developers also write an ADR under `adr/` when a change introduces a structural decision, and never write SQL migrations (those are generated at deploy time).
3. **quality-reviewer** — the single reviewer: combined semantic code + security review (Parts A, B) plus QA / runtime validation — integration wiring, behavior-verifiable acceptance criteria, e2e presence (Part C). Never re-runs validation (hooks already do).
4. **merger** — `git merge --no-ff` only; never `git add` / `git commit`. One merger is dispatched per ticket (Stage A: feature branch → session branch); a final promotion merger (`MODE: promote`) moves the session branch onto `main` once the wave is done, serialised across sessions by a `flock` on the shared `.git`.
-5. **documentator** — auto-runs at the end of every COMPLEX session, appending business knowledge to `MEMORY.md` from the session diff. (Mode 1 also captures reusable rules/skills on explicit user request.)
+5. **documentator** — auto-runs at the end of every session, appending business knowledge to `MEMORY.md` from the session diff. (Mode 1 also captures reusable rules/skills on explicit user request.)
There is no cross-agent messaging: the orchestrator dispatches every agent as a **foreground subagent** (`Agent(...)`, no `run_in_background`) and drives the wave **synchronously within one continuous turn** (chat-orchestrator.md STATE B) — a foreground call blocks until the subagent returns, and several in one message run concurrently and return together. Each wave flows through three barriered stages: develop (concurrent) → review + bounded retry (concurrent) → merge (sequential, since per-ticket mergers share the session branch). This replaces an earlier event-driven background model, which stalled when a background completion woke the wrong subagent instead of the orchestrator. Each agent's last output line is an **output contract** (`DONE: …` / `FAILED: …` / `APPROVED` / `REJECTED: …`) that the orchestrator parses to choose the next dispatch (see `.claude/rules/agent-output-format.md`). PreToolUse/Agent hooks prepare the worktree (`setup-worktree`) and gate the flow (`enforce-dev-dispatch`, `block-merger-without-review`, `block-promote-unmerged`); SubagentStop hooks validate (`validate-on-stop`) and record review verdicts (`record-review-verdict`).
@@ -25,17 +22,16 @@ There is no cross-agent messaging: the orchestrator dispatches every agent as a
| Agent | Model | Role |
|---|---|---|
-| chat-orchestrator | sonnet | User-facing. Routes, narrates. SIMPLE flow dispatches simple-developer + merger directly (no team). |
+| chat-orchestrator | sonnet | User-facing. Routes every code change through the one pipeline; narrates progress; never implements. |
| planner | opus | Decomposes the plan into tickets JSON with waves + file hints. |
-| developer | sonnet | Implements + commits in a worktree. Applies the **Ponytail** minimization ladder (full mode) automatically on every ticket, via an inline prompt directive. Writes ADRs for structural decisions. Never writes SQL migrations (deploy-time only). |
-| simple-developer | sonnet | One cosmetic edit, one single-field entity change, or one filter reusing existing components. Applies the **Ponytail** ladder (full mode) automatically, via an inline prompt directive. No team, no review. |
+| developer | sonnet | One agent, no modes. Implements the ticket in `TICKET_FILE`: plans, commits in a per-ticket worktree, peer-reviewed, writes ADRs for structural decisions, never writes SQL migrations during tickets. Two session-level operations are handed to it as **skills** (loaded on dispatch, run on the shared `<base>/ops` worktree): `writing-migrations` (deploy-time SQL generation) and `resolving-rollback-conflicts` (replay merge-commit reverts). Applies the **Ponytail** minimization ladder (full mode) automatically via an inline prompt directive. |
| quality-reviewer | opus | Sole reviewer: combined semantic code + security review AND QA/runtime validation (integration wiring, behavior criteria, e2e presence). Never re-runs validation. |
| merger | haiku | `git merge --no-ff` only. Never `git add` / `git commit`. |
-| documentator | haiku | Mode 1 — captures rules/skills on request. Mode 2 — appends business knowledge to `MEMORY.md` at COMPLEX session end. |
+| documentator | haiku | Mode 1 — captures rules/skills on request. Mode 2 — appends business knowledge to `MEMORY.md` at session end. |
**planner** and **quality-reviewer** run on opus; everything else is sonnet or haiku.
-The **developer** and **simple-developer** apply the **Ponytail** minimization ladder (full mode) on every change, via inline directives in their prompts — the only mechanism that reaches `Agent`-dispatched subagents. Ponytail is also installed **natively** in-repo as on-demand skills (no plugin, no marketplace, no hooks): its skills live in `.claude/skills/ponytail*` and its `/ponytail*` commands in `.claude/commands/`, for interactive use in the main session (`/ponytail-review`, `/ponytail-audit`, …). These do not affect the dev agents, whose ladder comes from the inline directives above.
+The **developer** applies the **Ponytail** minimization ladder (full mode) on every change — in every mode — via inline directives in its prompt, the only mechanism that reaches `Agent`-dispatched subagents. Ponytail is also installed **natively** in-repo as on-demand skills (no plugin, no marketplace, no hooks): its skills live in `.claude/skills/ponytail*` and its `/ponytail*` commands in `.claude/commands/`, for interactive use in the main session (`/ponytail-review`, `/ponytail-audit`, …). These do not affect the dev agents, whose ladder comes from the inline directives above.
## The orchestrator's job between hand-offs