@jaggerxtrm/specialists 3.18.1 → 3.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1160 +1,1416 @@
1
1
  ---
2
2
  name: using-specialists
3
3
  description: >
4
- Use this skill whenever you're about to start a substantial task — pause first and
5
- route the work through specialists instead of doing discovery or implementation
6
- yourself. Consult before any: code review, security audit, deep bug investigation,
7
- test generation, multi-file refactor, architecture analysis, or multi-chain
8
- specialist orchestration. Also use for the mechanics of delegation: --bead
9
- workflow, --context-depth, background jobs, MCP tool (`use_specialist`),
10
- or specialists doctor. Don't wait for the user to say
11
- "use a specialist" — proactively evaluate whether delegation makes sense.
12
- version: 4.8
13
- synced_at: a58a4dda
4
+ Canonical specialist orchestration skill. Use proactively for substantial work
5
+ that should be delegated, tracked, reviewed, fixed, tested, or merged through
6
+ specialists: code review, debugging, implementation, planning, doc sync,
7
+ security checks, multi-step chains, integration-phase reconciliation,
8
+ debugger-restitch on conflicting chains, pre-dispatch conflict-cluster
9
+ mapping, test-failure-map epics, and questions about specialist workflow.
10
+ version: 3.7
14
11
  ---
15
12
 
16
- # Specialists Usage
13
+ # Using Specialists
17
14
 
18
- When this skill is loaded, you are an **orchestrator** think CEO or CTO. You set direction, route work, unblock specialists, and synthesize outcomes. You do not implement.
15
+ You are the orchestrator. Turn user intent into a strong bead contract, choose right specialist from live registry, launch chain, monitor it, consume results, drive fixes, and publish through specialist merge path.
19
16
 
20
- Specialists handle **99% of tasks**. The only things you do yourself are things that are genuinely trivial (one-liner, quick config) or require a global overview only you can provide. Everything else goes to a specialist. When in doubt, delegate.
17
+ Keep skill practical. Core behavior belongs here; volatile detail stays in live commands.
21
18
 
22
- Your job is routing, sequencing, monitoring, and synthesis not exploration or implementation. Do **ZERO implementation** yourself for substantial work: no file reads, no code writing, no docs, no self-investigation. If you catch yourself doing discovery, stop and dispatch explorer instead.
19
+ > **MANDATORYRun on skill load and before every new substantial task or epic:**
20
+ > ```bash
21
+ > specialists list --full
22
+ > ```
23
+ > Do not rely on remembered roles, models, or permissions. The registry is the source of truth.
24
+ > Run it again before dispatching any new chain or starting any epic — specialists change between sessions.
23
25
 
24
- > **Sleep timers**: When you dispatch a specialist for a longer task, set a sleep timer and step back. Don't poll manually — set a timer appropriate to the expected run time, sleep, then check results. This lets you work independently and iterate without babysitting jobs.
26
+ ## Specialist File Locations
25
27
 
26
- Specialists are autonomous AI agents that run independently — fresh context, different model, no prior bias. The reason isn't just speed it's quality. A specialist has no competing context, leaves a tracked record via beads, and can run in the background while you stay unblocked.
28
+ Specialists live in three layers. Know which layer you are reading or editing:
27
29
 
28
- > **Session start**: Run `sp --help` once to see the full command surface. `sp` is the short alias for `specialists` — `sp run`, `sp feed`, `sp resume` etc. all work. Also useful: `sp run --help`, `sp resume --help`, `sp feed --help` for flag details.
30
+ | Layer | Path | Purpose |
31
+ |-------|------|---------|
32
+ | Package (shipped) | `config/specialists/*.specialist.json` | Canonical role definitions; versioned with the repo |
33
+ | User override | `.specialists/user/*.specialist.json` | Per-project customizations; wins over package layer for same name |
34
+ | Default mirror | `.specialists/default/*.specialist.json` | Repo-managed mirror of package defaults; overrides package fallback |
29
35
 
30
- ---
36
+ The loader resolves in priority order: user → default-mirror → package. A same-name file in `.specialists/user/` fully replaces the package version for that specialist. When creating or editing a specialist, use `config/specialists/` for shipped roles and `.specialists/user/` for project-specific overrides. Never edit `.specialists/default/` by hand — it is managed by `update-specialists`.
31
37
 
32
- ## Response Style Policy
33
-
34
- - Be direct, concise, and professional.
35
- - Answer the user's actual question first, in the first sentence when possible.
36
- - Do not append conversational filler like:
37
- - "If you want, I can..."
38
- - "I can also..."
39
- - "Let me know if you want..."
40
- unless the user explicitly asked for options.
41
- - Do not restate context the user already provided unless needed to resolve ambiguity.
42
- - Prefer short conclusions over long explanatory structures.
43
- - Use bullets only when they improve clarity; otherwise respond in plain prose.
44
- - Do not hedge unnecessarily. If the answer is clear, state it plainly.
45
- - Do not give a recommendation section unless the user asked for recommendations or a decision.
46
- - Do not propose next steps automatically after every answer.
47
- - When reporting status, give:
48
- 1. current state
49
- 2. blocker or result
50
- 3. only the next action if action is already implied or necessary
51
- - Default to terse operational language, not coaching language.
52
-
53
- ## Hard Rules
54
-
55
- 1. **Zero implementation by orchestrator.** When this skill is active for substantial work, you do not implement the solution yourself.
56
- 2. **Never explore yourself.** All discovery, codebase mapping, and read-only investigation go through **explorer** (or **debugger** for root-cause analysis).
57
- 3. **Run explorer before executor when context is lacking.** If the bead already has clear scope — files, symbols, approach — send executor directly. Only run explorer first when the issue lacks a clear track.
58
- 4. **For tracked work, the bead is the prompt.** The bead description, notes, and parent context are the instruction surface.
59
- 5. **`--bead` is the only prompt.** Never use `--prompt`. If you need to refine instructions, update the bead notes first.
60
- 6. **Chains belong to epics.** A chain is a worktree lineage (executor → reviewer → fix). An epic is the merge-gated identity that owns chains. Use `sp epic merge <epic>` to publish — never merge individual chains that belong to an unresolved epic.
61
- 7. **Merge through epics, not manual git.** Use `sp epic merge <epic-id>` for wave-bound chains or `sp merge <chain-root-bead>` for standalone chains. Never use manual `git merge` for specialist work.
62
- 8. **No destructive operations by specialists.** No `rm -rf`, no force pushes, no database drops, no credential rotation, no mass deletes, no history rewrites. Surface destructive requirements to the user.
63
- 9. **Executor does not run tests.** Executor runs lint + tsc only. Tests are the reviewer's and test-runner's responsibility in the chained pipeline.
64
- 10. **Keep specialists alive through the review cycle.** Never `sp stop` an executor or debugger before the reviewer delivers its verdict. The specialist stays in `waiting` so you can `resume` it — to commit changes, apply fixes from reviewer feedback, or continue work. Only stop after final reviewer PASS and confirmed commit.
65
- 11. **Respect ownership layers and loader precedence.** Loader resolution order is `.specialists/user/*` > `.specialists/default/*` > package fallback `config/*`. Upstream source = package `config/*` (read-only for repo operators); managed mirror = `.specialists/default/*` (no hand edits); repo custom layer = `.specialists/user/*`; runtime/generated = `.specialists/{jobs,ready,db}`.
66
- 12. **Keep backlog-clean isolated.** Do not mix backlog-clean changes into specialist ownership/migration tasks.
67
-
68
- ## Mandatory-rules template sets
69
-
70
- Use template-driven mandatory rules for repeatable policy bundles.
71
-
72
- - Specialist config field: `specialist.mandatory_rules.template_sets`
73
- - Template source: `config/mandatory-rules/*.md`
74
- - Template format: YAML frontmatter + body content
75
- - Runtime behavior: runner resolves templates and injects rendered rules at end of prompt
38
+ `specialists list --full` shows the resolved set (which layer each specialist comes from) so you always know what will actually run.
76
39
 
77
- ---
40
+ ### Editing Specialist Fields: `sp edit` Is Required
78
41
 
79
- ## When to Use This Skill
42
+ Direct JSON editing is error-prone and bypasses schema validation. Use `sp edit` for all field changes — it validates dot-paths, handles array append/remove, and writes to the correct layer.
80
43
 
81
- **Default: always delegate.** Specialists handle 99% of tasks. The orchestrator only acts directly for things that are genuinely trivial (one-liner, quick config tweak) or require a global overview that only you can provide.
44
+ ```bash
45
+ # Read a field
46
+ sp edit executor --get specialist.execution.model
82
47
 
83
- **Do it yourself only when:**
84
- - It's a one-liner or formatting fix
85
- - It's a quick config change that needs no investigation
86
- - It genuinely requires high-level synthesis only you can do (e.g. reading results across multiple jobs and forming a next-step decision)
48
+ # Set a field (schema-validated)
49
+ sp edit executor specialist.execution.model <model-id>
87
50
 
88
- Everything else investigation, implementation, review, testing, docs, planning, design goes to a specialist.
51
+ # Set prompt.system or task_template from a file (required for multi-line content)
52
+ sp edit executor --set specialist.prompt.system _ --file ./my-system-prompt.txt
89
53
 
90
- ---
54
+ # Append or remove tags
55
+ sp edit executor --set specialist.metadata.tags review,security --append
56
+ sp edit executor --set specialist.metadata.tags old-tag --remove
91
57
 
92
- ## Canonical Workflow
58
+ # Apply a named preset (run sp edit --list-presets for current options)
59
+ sp edit executor --preset power
60
+ sp edit executor --preset cheap --dry-run # preview first
93
61
 
94
- ### CLI commands
62
+ # Target a specific scope when name exists in multiple layers
63
+ sp edit executor --scope user --set specialist.execution.model <model-id>
95
64
 
96
- ```bash
97
- # Discovery
98
- specialists list # discover available specialists
99
- specialists doctor # health check: hooks, MCP, zombie jobs
100
-
101
- # Running
102
- specialists run <name> --bead <id> # foreground run (streams output)
103
- specialists run <name> --bead <id> --background # background run
104
- specialists run <name> --bead <id> --worktree # isolated worktree (edit-capable specialists)
105
- specialists run <name> --bead <id> --job <job-id> # reuse another job's worktree
106
- specialists run <name> --bead <id> --epic <epic-id> # explicitly declare epic membership
107
- specialists run <name> --bead <id> --force-stale-base # bypass stale-base guard
108
- specialists run <name> --bead <id> --keep-alive # keep session alive after first turn
109
- specialists run <name> --bead <id> --context-depth 2 # inject parent bead context
110
-
111
- # Monitoring
112
- specialists ps # list all jobs (status, specialist, elapsed, bead, epic)
113
- specialists ps <job-id> # inspect single job (full detail + ctx% badge)
114
- specialists feed -f # tail merged feed (all jobs) — shows [ctx%] context window usage
115
- specialists feed <job-id> # events for a specific job
116
- specialists result <job-id> # final output text
117
- specialists status --job <job-id> # single-job detail view (legacy — prefer `sp ps <id>`)
118
-
119
- # Epic lifecycle (canonical publication path)
120
- specialists epic list [--unresolved] # list epics with lifecycle state
121
- specialists epic status <epic-id> # show chains, blockers, readiness
122
- specialists epic sync <epic-id> [--apply] # recompute derived readiness; repair drift
123
- specialists epic abandon <epic-id> --reason <text> [--force] # terminal transition for stuck epics
124
- specialists epic merge <epic-id> [--pr] # publish all epic-owned chains; auto-finalizes PASS chains
125
-
126
- # Merge (per-chain or standalone; PASS chains can merge inside an active epic)
127
- specialists merge <chain-root-bead> [--rebuild]
128
- specialists finalize <chain-root-bead> # manual recovery if PASS auto-finalize did not fire
129
-
130
- # Session close (chain-aware, epic-aware)
131
- specialists end [--pr] # close session, publish via merge or PR
132
-
133
- # Interaction
134
- specialists steer <job-id> "new direction" # redirect ANY running job mid-run
135
- specialists resume <job-id> "next task" # resume a waiting keep-alive job
136
- specialists stop <job-id> # cancel a job
137
- specialists stop <job-id> --force # 5s SIGTERM timeout, then pgroup kill + error status
138
-
139
- # Management
140
- specialists edit <name> # edit specialist config (dot-path, --preset)
141
- specialists edit <name> --fork-from <base> # fork non-user specialist into .specialists/user/ then edit
142
- specialists clean # purge old job dirs + worktree GC
143
- specialists clean --processes # kill all running/starting specialist jobs
144
- specialists db vacuum # compact SQLite storage (refuses if jobs running)
145
- specialists db prune --before <iso|duration> --dry-run|--apply # prune old events/results/terminal jobs
146
- specialists doctor orphans # integrity scan: orphan, stale-pointer, integrity-violation
147
- specialists init --sync-defaults # refresh specialists + mandatory-rules + nodes from canonical defaults
148
- specialists init --sync-skills # re-sync skills only (no full init)
149
- specialists init --no-xtrm-check # skip xtrm prerequisite check (CI/testing)
65
+ # Bulk read across all specialists
66
+ sp edit --all --get specialist.execution.model
150
67
  ```
151
68
 
152
- ---
69
+ **When `sp edit` is required vs. direct JSON edit:**
70
+ - Model, thinking level, timeout, tags, permission, description → always `sp edit`
71
+ - `prompt.system` or `task_template` longer than one line → `sp edit --file`
72
+ - Structural schema fields (execution flags, output_schema) → `sp edit` with dot-path
73
+ - Net-new specialist creation → `specialists-creator` skill, then `sp edit` for tuning
74
+ - Bulk cross-specialist reads → `sp edit --all --get <path>`
75
+ - Available presets → `sp edit --list-presets` (do not hardcode; varies by install)
153
76
 
154
- ## Taxonomy: Job | Chain | Epic
77
+ ## Orchestration Discipline (Paranoid Mode)
155
78
 
156
- The specialists orchestration model uses three levels:
79
+ You are an orchestrator, not a hero. Move slowly enough to be correct.
157
80
 
158
- | Term | Definition | Persisted? | Merge scope |
159
- |------|------------|:----------:|:-----------:|
160
- | **Job** | One specialist run (atomic execution unit) | Yes (SQLite + files) | |
161
- | **Chain** | Worktree lineage: all specialists sharing one workspace from first dispatch to merge (explorer executor reviewer fix) | Yes (`worktree_owner_job_id`) | `sp merge <chain-root>` |
162
- | **Epic** | Top merge-gated identity that owns chains across stages | Yes (`epic_runs` table) | `sp epic merge <epic>` |
163
- | **Wave** | Human shorthand for dispatch batches ("Wave 1", "Wave 2b") **speech only, NOT persisted** | No | — |
81
+ - Run `specialists list --full` and `sp help` again at the start of every new substantial task. Do not skip because "you remember." Roles, models, and flags drift between sessions.
82
+ - Re-read the bead before dispatch. If you cannot defend each contract field out loud, the bead is not ready.
83
+ - Never dispatch a chain you cannot describe end-to-end (which specialist, which bead, which workspace, which merge target).
84
+ - Verify worktree and job state before and after each dispatch with `sp ps` and `git worktree list`. Drift is silent until merge.
85
+ - Treat reviewer `PARTIAL` and seconder `FINDINGS` as mandatory fix loops, not advisory noise.
86
+ - When unsure, prefer extra explorer/debugger passes over an over-eager executor. Wrong code merged is more expensive than slow research.
164
87
 
165
- ### Key relationships
88
+ ## Project-Specific Specialists
166
89
 
167
- - **Chains belong to epics**: When `--bead` is used, the chain defaults to the bead's parent epic. Override with `--epic <id>`.
168
- - **Jobs belong to chains**: Jobs sharing a `worktree_owner_job_id` form one chain.
169
- - **Merge through epics**: `sp epic merge <epic-id>` is the **canonical publication path** for wave-bound chains.
170
- - **Standalone chains**: `sp merge <chain-root-bead>` works only for chains NOT belonging to an unresolved epic.
90
+ Users define their own specialists in `.specialists/user/*.specialist.json` to fit project shape (domain knowledge, language, framework, conventions). These override package defaults and may not match generic role descriptions.
171
91
 
172
- ### Epic lifecycle
92
+ - Always run `specialists list --full` to see the resolved set, including project-specific roles, before choosing.
93
+ - Read `sp help` and the specialist's description/tags to confirm fit. Do not assume a name maps to its package-default behavior — a `.specialists/user/` override may have a different prompt, model, or scope.
94
+ - Pick the project-specific specialist when its role matches the task shape. Do not fall back to a generic role just because it is more familiar.
95
+ - If the task does not match any project-specific role, use the package default and consider whether a new project-specific specialist would help (use `specialists-creator` skill).
173
96
 
174
- ```
175
- open → resolving → merge_ready → merged
176
- ↘ failed
177
- ↘ abandoned
178
- ```
179
-
180
- | State | Meaning | Chains mergeable? |
181
- |-------|---------|:-----------------:|
182
- | `open` | Epic created, chains not yet running | — |
183
- | `resolving` | Chains are actively running | ✗ |
184
- | `merge_ready` | All chains terminal, reviewer PASS | ✓ (via `sp epic merge`) |
185
- | `merged` | Publication complete | — |
186
- | `failed` | One or more chains failed | — |
187
- | `abandoned` | Cancelled without merge | — |
97
+ ## Mandatory Gates: Seconder, Obligations, Security (Iron-style)
188
98
 
189
- ### Migration from "waves" vocabulary
99
+ For any substantive production diff, the chain shape is the canonical pipeline from [`docs/design/chain-templates.md` §2](../../../docs/design/chain-templates.md#2-the-canonical-pipeline):
190
100
 
191
- **Old terminology → New terminology:**
101
+ ```
102
+ writer (executor/debugger) → seconder → test-engineer → test-runner → security-auditor (if surface) → obligations-scanner → reviewer → Release Checklist
103
+ ```
192
104
 
193
- | Old | New | Notes |
194
- |-----|-----|-------|
195
- | "Wave 1" | Stage 1 / Prep phase | Speech shorthand still works — just not persisted |
196
- | "Wave 2" | Implementation chains | Chains are the operative unit, grouped by epic |
197
- | "Between waves merge" | `sp epic merge` | Epic is the merge-gated identity |
198
- | "Parallel in wave" | Parallel chains under epic | Use `--epic` to declare membership explicitly |
105
+ Reviewer consumes final QA evidence together with Iron gates: test-engineer output, test-runner classification, smoke/E2E proof, telemetry/log assertions, obligations-scanner, and security-auditor when applicable.
199
106
 
200
- **Why this change?**
107
+ `seconder`, `test-engineer`, `test-runner`, `obligations-scanner`, and `reviewer` are mandatory on production diffs (shipped via Opp 14 / `unitAI-sfwe1` + Opp 15 / `unitAI-4e194`). `security-auditor` is mandatory when the diff touches a sensitive surface. Reviewer follows canon §2.2 SCRUTINY as a chain-property, not reviewer input.
201
108
 
202
- 1. **Waves had no identity**: "Wave 2" was just speech no code could track it.
203
- 2. **Merge gates were implicit**: Operators had to remember which chains to merge together.
204
- 3. **Epics are explicit**: An epic bead ID persists, enabling `sp epic status` and `sp epic merge`.
109
+ ### Seconder Gate`seconder`
205
110
 
206
- **Backward compatibility**: All existing workflows work unchanged. The new vocabulary is additive you can still think in waves, but the system tracks epics.
111
+ Mandatory READ_ONLY scope/compliance + smell/type-safety/simplicity dual-verdict gate (canon §2.3). Every change gets one cheap second pair of eyes before QA and reviewer. If `overall_verdict` is FAIL or UNCLEAR where not allowed, route back to writer.
207
112
 
208
- ---
113
+ - Skip permitted ONLY for: test-only diffs (entirely under `test/`, `tests/`, `__tests__/`, `*.spec.*`, `*.test.*`, `*.fixture.*`) or new-file-only diffs (no modifications to existing symbols).
114
+ - Any other skip = escalation event. Small diffs hide the worst regressions.
209
115
 
210
- ## Chained Bead Pipeline
116
+ ### Obligations Gate — `obligations-scanner`
211
117
 
212
- This is the **standard for ALL tracked work**. Every specialist run gets its own child bead.
213
- Each step's output accumulates on its bead. Downstream steps see upstream output automatically
214
- via `--context-depth 2`. The bead chain IS the context chain — zero manual wiring needed.
118
+ Mandatory READ_ONLY marker scan. Catches new TODO/FIXME/HACK/XXX/TEMP/WIP/NOTE(release) in production code that would otherwise leak unaccounted. Cheap (<30s, gpt-5.4-mini, bare).
215
119
 
216
- ```
217
- task-abc: "Fix auth token refresh"
218
- └── abc-exp: explorer (READ_ONLY auto-appends output to abc-exp notes)
219
- └── abc-impl: executor (self-appends output to abc-impl notes, closes bead)
220
- └── abc-rev: reviewer (auto-appends verdict to abc-rev notes via --job <exec-job>)
221
- └── abc-fix: executor (if reviewer PARTIAL — fix bead, same worktree via --job)
222
- ```
120
+ - Accepts structured `// TODO(<bead-id>): reason` markers if the linked bead exists and is in current bead's NON_GOALS.
121
+ - Rejects unstructured markers in production code → reviewer issues PARTIAL "obligation: must resolve or accept".
122
+ - Markers under test/fixture/mock/e2e/docs paths are noted but never block.
223
123
 
224
- **How context flows (`--context-depth 2` = own + parent + grandparent = 3 beads):**
124
+ The scanner produces JSON; the reviewer consumes its output directly via job feed.
225
125
 
226
- | Step | Specialist sees | Via |
227
- |------|----------------|-----|
228
- | abc-exp | abc-exp (own) + task-abc (parent) | `--bead abc-exp --context-depth 2` |
229
- | abc-impl | abc-impl (own) + abc-exp (explorer findings in notes) + task-abc | `--bead abc-impl --context-depth 2` |
230
- | abc-rev | abc-rev (own) + abc-impl (executor output in notes) + task-abc | `--bead abc-rev --job <exec-job> --context-depth 2` |
231
- | abc-fix | abc-fix (own) + abc-impl (executor output + reviewer verdict) + abc-exp | `--bead abc-fix --job <exec-job> --context-depth 2` |
126
+ ### Security Gate `security-auditor`
232
127
 
233
- - No copy-paste, no manual note injection between steps
234
- - Every step has a full audit trail on its own bead
235
- - The dep graph IS the context graph — self-documenting
128
+ Mandatory when diff touches: auth, secrets, input handling (user/network/file), dependency lockfiles, agent/MCP/config surfaces, token-storage paths, migrations, permissions/hooks. Scan-only; recommendations only; executor applies fixes.
236
129
 
237
- ### Complete flow example
130
+ - Never skip on sensitive-surface diff "because the diff looks small."
131
+ - Auto-triggered by reviewer's SCRUTINY auto-escalation table when surface patterns match.
238
132
 
239
- ```bash
240
- # 1. Create the task bead
241
- bd create --title "Fix auth token refresh bug" --type bug --priority 2
242
- # -> unitAI-abc
243
-
244
- # 2. Create chained child beads (create all upfront for clarity)
245
- bd create --title "Explore: map token refresh code paths" --type task --priority 2
246
- # -> unitAI-abc-exp
247
- bd dep add abc-exp abc
248
-
249
- bd create --title "Implement: fix token refresh retry on 401" --type task --priority 2
250
- # -> unitAI-abc-impl
251
- bd dep add abc-impl abc-exp
252
-
253
- # 3. Wave 1 — Explorer
254
- specialists run explorer --bead abc-exp --context-depth 2 --background
255
- # -> Job started: e1f2g3
256
- # Explorer output auto-appends to abc-exp notes (READ_ONLY behavior)
257
- specialists result e1f2g3
258
-
259
- # 4. [MERGE] Merge any worktree branches from Wave 1 into master
260
- # READ_ONLY waves have no worktrees to merge
261
-
262
- # 5. Wave 2 — Executor
263
- specialists run executor --worktree --bead abc-impl --context-depth 2 --background
264
- # -> Job started: a1b2c3
265
- # Executor sees: abc-impl + abc-exp (with explorer notes) + abc via context-depth
266
- # Executor self-appends output to abc-impl notes, closes abc-impl on completion
267
-
268
- # 6. [MERGE] Merge impl worktree branch into master
269
- sp merge abc-impl --rebuild
270
-
271
- # 7. Wave 3 — Reviewer (own bead, enters executor's worktree via --job)
272
- bd create --title "Review: token refresh fix" --type task --priority 2
273
- # -> unitAI-abc-rev
274
- bd dep add abc-rev abc-impl
275
-
276
- specialists run reviewer --bead abc-rev --job a1b2c3 --context-depth 2 --keep-alive --background
277
- # -> Job started: r4v5w6
278
- # Reviewer sees: abc-rev + abc-impl (with executor output in notes) + abc via context-depth
279
- # Reviewer auto-appends verdict to abc-rev notes
280
- specialists result r4v5w6
281
- # -> PASS: close task bead. PARTIAL/FAIL: go to step 8.
282
-
283
- # 8. If PARTIAL — fix loop (same worktree, new child bead)
284
- bd create --title "Fix: reviewer gaps on abc-impl" --type bug --priority 1
285
- # -> unitAI-abc-fix
286
- bd dep add abc-fix abc-impl
287
-
288
- specialists run executor --bead abc-fix --job a1b2c3 --context-depth 2 --background
289
- # Fixer runs in same worktree (via --job a1b2c3)
290
- # Sees: abc-fix + abc-impl (executor output + reviewer verdict) + abc-exp via context-depth
291
- # Repeat reviewer --job → fix loop until PASS
292
-
293
- # 9. Close when reviewer says PASS
294
- bd close abc --reason "Fixed: token refresh retries on 401. Reviewer PASS."
295
- ```
133
+ ### Dispatch mechanics for all three gates
296
134
 
297
- **Why chaining matters:**
298
- - Every step's output is preserved — full audit trail on each bead
299
- - `--context-depth 2` gives each specialist the previous step's findings automatically
300
- - No copy-pasting results between steps
301
- - The orchestrator only creates beads and dispatches — zero context injection
135
+ All run with their own bead and `--job <exec-job>` so they enter the executor workspace.
302
136
 
303
- ---
137
+ Routing across chain phases:
304
138
 
305
- ## --job, --worktree, and --epic Semantics
139
+ - **Per-chain dispatch**: gates run on the chain's job in canon order: seconder → test-engineer → test-runner → security-auditor (if surface) → obligations-scanner → reviewer. Seconder FAIL/UNCLEAR routes back to writer; test-runner misclassifications route to test-engineer or writer per canon §2.5.
140
+ - **Debugger-restitch**: same gate order on the debugger's job AFTER the restitch turn, BEFORE reviewer.
141
+ - **E2E smoke phase**: cross-cutting security-auditor on cumulative integrated diff if any landed chain touched a sensitive surface.
142
+ - **Reviewer rebuttal**: seconder OK and security-auditor "no findings" are legitimate evidence in reviewer rebuttals (cite the advisory job id).
306
143
 
307
- These flags control **workspace isolation** and **epic membership**. Executors run in isolated git worktrees so concurrent jobs don't corrupt shared files. Chains declare epic membership to enable merge-gated publication.
144
+ ## Monitoring Long-Running Jobs: Sleep Timers Are Mandatory
308
145
 
309
- | Flag | Semantics | Creates worktree? | Sets epic? |
310
- |------|-----------|:----------------:|:----------:|
311
- | `--worktree` | Provision a new isolated workspace; requires `--bead` | Yes | Inherited from bead.parent |
312
- | `--job <id>` | Reuse the workspace of an existing job | No | Inherited from target job |
313
- | `--epic <id>` | Explicitly declare epic membership | No | Yes (overrides default) |
146
+ Specialists run async. You will lose the chain if you do not actively monitor it.
314
147
 
315
- `--worktree` and `--job` are **mutually exclusive**. Specifying both exits with an error.
148
+ **`sp run` semantics — read carefully.** There is NO `--background` flag (older versions of this doc used it — it never existed).
316
149
 
317
- ### Epic membership
150
+ - **CLI form** (`sp run <role> --bead <id> ...`) prints `[job started: <id>]` on stderr AT THE START, but the process **keeps streaming stdout until the specialist finishes** — the shell call BLOCKS. This is async in the "job runs on the sp side" sense, not in the "your shell returns" sense.
151
+ - **MCP form** (`use_specialist`) is foreground and returns the result directly.
152
+ - **True background detach** requires shell-level `&` plus log redirect: `sp run <role> --bead <id> --prompt "..." > /tmp/job.log 2>&1 &`. Then `disown` if you want it to outlive the shell. Poll via the observability DB or `sp ps` afterward.
318
153
 
319
- When `--bead` is used, the chain defaults to the bead's parent epic (if parent is an epic-type bead). Override this with `--epic <id>`:
154
+ **Required pattern after every dispatch (interactive orchestrator, blocking shell OK):**
320
155
 
321
156
  ```bash
322
- # Chain inherits bead.parent as epic
323
- specialists run executor --worktree --bead unitAI-impl
324
- # → epic_id = bead.parent (if epic-type)
157
+ # tracked (bead-driven) — specialist reads the bead as its prompt
158
+ sp run <role> --bead <id> # blocks; streams output; returns when done
325
159
 
326
- # Explicit epic declaration (e.g., prep job with non-epic parent)
327
- specialists run explorer --bead prep-task.1 --epic unitAI-3f7b
328
- # → epic_id = unitAI-3f7b (explicit override)
160
+ # ad-hoc (no bead) arbitrary prompt
161
+ sp run <role> --prompt "..." # blocks; streams output; returns when done
329
162
  ```
330
163
 
331
- **Why explicit --epic?** Prep jobs (explorer, planner, overthinker) often have non-epic parents but need to belong to the epic for `sp ps` grouping and `sp epic status` visibility.
164
+ `--bead` and `--prompt` are **mutually exclusive**. Use `--bead` for tracked work (the default for chains); use `--prompt` only for ad-hoc off-board queries.
332
165
 
333
- ### `--worktree`
334
-
335
- Provisions a new git worktree + branch for the specialist run. Branch name is derived
336
- deterministically from the bead id: `feature/<beadId>-<specialist-slug>`.
166
+ **Required pattern for non-blocking dispatch (orchestrator wants to do other work while it runs):**
337
167
 
338
168
  ```bash
339
- specialists run executor --worktree --bead hgpu.3
340
- # stderr: [worktree created: /repo/.worktrees/hgpu.3/hgpu.3-executor branch: feature/hgpu.3-executor]
169
+ sp run <role> --bead <id> > /tmp/job-<id>.log 2>&1 &
170
+ JOB_PID=$!
171
+ sleep 10 && sp ps # confirm started
341
172
  ```
342
173
 
343
- If the worktree already exists (interrupted run), it is **reused**, not recreated.
174
+ **Pi runtime caveat (xtmux-19y):** dispatch `sp`/`xt`/`gh` via the **bash tool**, not pi's `process` tool. Pi's `process` tool spawns subprocesses with a stripped PATH that lacks `~/.nvm/.../bin` (or wherever npm globals live), so `sp run …` inside `process start` exits 127 (`command not found`). The bash tool inherits your PATH normally. If you must use `process` for a background dispatch, hand it an absolute path (`$(which sp)`) or wrap through `bash -lc '…'` to force a login shell.
344
175
 
345
- ### `--job <id>`
176
+ Then cycle sleeps based on average completion time per role, checking `sp ps` each cycle:
346
177
 
347
- Reads `worktree_path` from the target job's `status.json` and uses that directory as `cwd`.
348
- The caller's own `--bead` remains authoritative — `--job` only selects the workspace.
178
+ | Role | Typical duration | Initial sleep cycle |
179
+ |------|------------------|---------------------|
180
+ | sync-docs, changelog-keeper | 60–180s | `sleep 60` then `sleep 60` |
181
+ | seconder, security-auditor | 60–180s | `sleep 60` then `sleep 60` |
182
+ | reviewer | 90–240s | `sleep 90` then `sleep 60` |
183
+ | explorer, debugger, planner, overthinker | 120–300s | `sleep 120` then `sleep 90` |
184
+ | executor | 180–600s+ | `sleep 180` then `sleep 120` |
185
+ | test-runner | varies with suite | start at `sleep 120`, adjust |
349
186
 
350
- ```bash
351
- # Reviewer enters executor's worktree with its own bead
352
- specialists run reviewer --bead unitAI-rev --job 49adda --context-depth 2 --keep-alive --background
187
+ Rules:
188
+ - After dispatch, **always** `sleep 10 && sp ps` first to confirm the job is `running`, not stuck in `queued` or already `failed`.
189
+ - Then sleep again per the table; check `sp ps` each cycle.
190
+ - Do not poll faster than every 30s after the initial check — it wastes context.
191
+ - When status flips to `completed`, run `sp result <job-id>` immediately to consume output before context grows.
192
+ - If a job exceeds 2× its typical duration without completing, inspect with `sp feed <job-id>` before assuming hang.
353
193
 
354
- # Fix executor re-enters same worktree (--bead provides new fix bead, --job provides workspace)
355
- specialists run executor --bead hgpu.3-fix --job 49adda --context-depth 2 --background
356
- ```
194
+ You are not "done" until every dispatched job is `completed` or `failed` and consumed.
357
195
 
358
- **Concurrency guard (MEDIUM/HIGH specialists):**
196
+ ## Notification Via Observability DB (Preferred Over `sp ps` Polling)
359
197
 
360
- Blocked from entering while target job is `starting` or `running` prevents concurrent file corruption.
198
+ `sp ps` prints the same data the observability SQLite database holds. Query the DB directly instead of polling `sp ps` in a sleep loop — it is faster, structured, filterable, and survives session restarts. Works identically from Claude Code and Pi (both can shell out to `sqlite3` or `python3 -c "import sqlite3;..."`).
361
199
 
362
- | Target status | MEDIUM/HIGH | READ_ONLY/LOW |
363
- |---------------|:-----------:|:-------------:|
364
- | `starting` | ✗ Blocked | ✓ Allowed |
365
- | `running` | ✗ Blocked | ✓ Allowed |
366
- | `waiting` | ✓ Allowed | ✓ Allowed |
367
- | `done`/`error`/`cancelled` | ✓ Allowed | ✓ Allowed |
368
- | Unknown | ✗ Blocked (conservative) | ✓ Allowed |
200
+ **DB location**: `.specialists/db/observability.db` under the project root — always per-repo, never at `~/.specialists/`. Any 0-byte file at `~/.specialists/observability.db` is a placeholder, not a real DB; ignore it. Missing until the first `sp run` in that repo auto-provisions it. If missing, `sp ps` returns empty — same signal.
369
201
 
370
- **Bypass with `--force-job`:**
202
+ **Sanity check when DB seems empty:**
371
203
 
372
204
  ```bash
373
- specialists run executor --job 49adda --force-job --bead fix-123
205
+ DB="$(git rev-parse --show-toplevel 2>/dev/null)/.specialists/db/observability.db"
206
+ [ -s "$DB" ] || { echo "no DB in this repo yet — fall back to sp ps"; sp ps; }
374
207
  ```
375
208
 
376
- Use when the caller explicitly accepts concurrent write risk (e.g., target job known to be stalled but not yet terminal, emergency fix entry).
209
+ **Key table**: `specialist_jobs`. Columns of interest for notification:
210
+ - `job_id` — primary key
211
+ - `specialist` — role name
212
+ - `bead_id`, `epic_id`, `chain_id`, `chain_root_job_id`
213
+ - `status` — canonical values: `done`, `error`, `cancelled` (terminal); `queued`, `running` (in-flight); `waiting` (blocked on human/parent)
214
+ - `updated_at_ms` — epoch millis
215
+ - `last_output` — final assistant text
216
+ - `pr_url`, `pr_state`, `pr_classification` — chain outcomes
377
217
 
378
- ### When to use each flag
218
+ **Notification patterns:**
379
219
 
380
- | Scenario | Flag to use |
381
- |----------|------------|
382
- | First executor run for a task | `--worktree --bead <impl-bead>` |
383
- | Reviewer on executor's output | `--bead <review-bead> --job <exec-job-id> --context-depth 2` |
384
- | Fix executor after reviewer PARTIAL | `--bead <fix-bead> --job <exec-job-id>` |
385
- | Force entry to blocked worktree | `--bead <fix-bead> --job <exec-job-id> --force-job` |
386
- | Prep job belonging to epic (non-epic parent) | `--bead <prep-bead> --epic <epic-id>` |
387
- | Explorer (READ_ONLY) | Neither — explorers don't need worktrees |
388
- | Overthinker, planner, debugger | Neither — read-only and interactive specialists |
220
+ ```bash
221
+ DB="${SPECIALISTS_DB:-$PWD/.specialists/db/observability.db}"
389
222
 
390
- ---
223
+ # Just-completed jobs since a timestamp (dispatch time)
224
+ sqlite3 "$DB" "SELECT job_id, specialist, bead_id, status FROM specialist_jobs
225
+ WHERE status IN ('done','error','cancelled')
226
+ AND updated_at_ms > $SINCE_MS
227
+ ORDER BY updated_at_ms DESC"
391
228
 
392
- ### Worktree write-boundary enforcement
229
+ # Latest status for a specific bead (any specialist)
230
+ sqlite3 "$DB" "SELECT job_id, specialist, status, updated_at_ms FROM specialist_jobs
231
+ WHERE bead_id = '$BEAD' ORDER BY updated_at_ms DESC LIMIT 1"
393
232
 
394
- Specialists running in worktrees are **prevented from writing outside their boundary**. The session generates a Pi extension that hooks `tool_call` events and blocks `edit`/`write`/`multiEdit`/`notebookEdit` tools with absolute paths outside the worktree.
233
+ # All jobs in an epic (chain-scoped view)
234
+ sqlite3 "$DB" "SELECT specialist, status, pr_state FROM specialist_jobs
235
+ WHERE epic_id = '$EPIC' ORDER BY updated_at_ms DESC"
395
236
 
396
- **What's blocked:**
397
- - `edit` with `/absolute/path/outside/worktree/file.ts`
398
- - `write` with `/absolute/path/outside/worktree/new-file.ts`
237
+ # Waiting-on-you jobs (needs orchestrator/parent input)
238
+ sqlite3 "$DB" "SELECT job_id, specialist, bead_id, last_output FROM specialist_jobs
239
+ WHERE status = 'waiting'"
240
+ ```
399
241
 
400
- **What's allowed:**
401
- - Relative paths (`src/file.ts`) — resolve within worktree cwd
402
- - Absolute paths inside the worktree boundary
242
+ **When to use DB queries vs `sp ps`:**
403
243
 
404
- This enforcement is automatic when `--worktree` is used. No configuration required. If the extension fails to generate (tmpdir permissions), a warning is logged and the session proceeds without protection.
244
+ | Situation | Use |
245
+ |---|---|
246
+ | Waiting for one specific job/bead | DB query on `bead_id` or `job_id` |
247
+ | Multi-chain / epic-level view | DB query on `epic_id` |
248
+ | Detecting completions during a batch | DB query with `updated_at_ms > $SINCE_MS` (loop with sleep) |
249
+ | Human-readable status board | `sp ps` (formatted) |
250
+ | Debugging one job | `sp feed <job-id>` (event stream) |
405
251
 
406
- ---
252
+ **Rules:**
253
+ - Capture `SINCE_MS=$(date +%s%3N)` right before dispatch so subsequent queries filter noise.
254
+ - Prefer targeted queries (by `bead_id` / `epic_id`) over full scans — the DB grows unbounded.
255
+ - The DB is authoritative. If `sp ps` and the DB disagree, trust the DB.
256
+ - Applies to both Pi and Claude Code — same shell-out to `sqlite3`. Do not build a language-specific SDK.
407
257
 
408
- ## Dependency Mapping
258
+ Interactive coordinators (chain-coordinator role sessions launched via `xt pi --role` or `xt claude --role`) should prefer this pattern over `sp ps` polling because they escalate to the parent orchestrator via `message-send` only when a job actually transitions, not on every poll cycle. Full launcher-flag surface (`--reuse` / `--new-session` / `--parent` / `--child` / `--model` / `--thinking` / `--` passthrough), session-name shape (`role-<runtime>-<slug>[-<bead>]`), pane options + `XTMUX_AGENT_*` env vars, and address-space split (`@agent_parent_session` = tmux `#{session_id}`; poll `message-list --for $MY_SID`, not by session name) live in `/multiplexing` Pattern 7 — do not re-derive them here.
409
259
 
410
- Map bead dependencies to match the execution pipeline. The dep graph IS the wave plan.
260
+ ## Worktree Cleanup After Merge
261
+
262
+ Merge is now manual (see `Merge And Publication` below). You own cleanup after every merge.
263
+
264
+ After every merge, verify:
411
265
 
412
- ### Simple bug fix
413
- ```
414
- task → explore → impl → review
415
- └── fix (if PARTIAL) → child of impl
416
- ```
417
266
  ```bash
418
- bd dep add explore task
419
- bd dep add impl explore
420
- bd dep add review impl
421
- # reviewer: specialists run reviewer --bead review --job <impl-job> --context-depth 2
422
- # fix: bd dep add fix impl
267
+ git worktree list # any orphaned worktrees from this session?
268
+ sp ps # any leftover jobs?
269
+ git worktree prune # drop stale worktree metadata
423
270
  ```
424
271
 
425
- ### Complex feature (overthinker)
426
- ```
427
- task → explore → design → impl → review → [fix if PARTIAL]
428
- ```
272
+ Always remove the merged feature/epic worktree explicitly:
273
+
429
274
  ```bash
430
- bd dep add explore task
431
- bd dep add design explore
432
- bd dep add impl design
433
- bd dep add review impl
434
- # reviewer: specialists run reviewer --bead review --job <impl-job> --context-depth 2
275
+ git worktree remove <path>
276
+ git branch -d <merged-branch> # only after confirming merged into target
435
277
  ```
436
278
 
437
- ### Epic with N children
438
- Each child gets its own explore → impl chain. Reviewer runs via `--job` per impl.
279
+ `sp ps` must have no active jobs and no unresolved terminal problems before session close. If it only shows old terminal history that you have intentionally acknowledged, run `sp clean --ps --dry-run` and then `sp clean --ps` to soft-hide those rows from the default dashboard. This does not delete SQLite history or change job status; use `sp ps --include-cleaned` or `sp ps --all` for audit visibility. Stale worktrees and stale jobs both block future dispatches.
280
+
281
+ ## When To Delegate
282
+
283
+ Use specialists for substantial work: codebase exploration, debugging, implementation, review, test execution, planning, documentation sync, security/config audit, release publication, and multi-chain epics.
284
+
285
+ Do small deterministic edits directly when scope is already obvious and delegation would add ceremony. Do not self-investigate or self-implement a substantial task just because you can read files faster; audit trail and specialist review are part of workflow.
286
+
287
+ ## Non-Negotiable Rules
288
+
289
+ 1. `--bead` is prompt for tracked work.
290
+ 2. Do not dispatch until bead is usable task contract.
291
+ 3. Never use `--prompt` to supplement tracked work. Update bead instead.
292
+ 4. Choose by task shape, not habit. Check `specialists list --full` when roles may have changed.
293
+ 5. Explorer/debugger answer uncertainty before executor writes code.
294
+ 6. Executor starts only when scope, constraints, and validation are clear.
295
+ 7. Reviewer uses its own bead and executor workspace via `--job <exec-job>`.
296
+ 8. Keep executor/debugger jobs alive through review so they can be resumed.
297
+ 9. Merge specialist-owned work via the documented manual git workflow (Cherry-Pick Playbook / FF / `git merge --no-ff`). Do NOT use `sp merge` or `sp epic merge` — both are known broken and awaiting a separate rework epic. The skill does not document their usage; if you find them in `sp help` output, ignore.
298
+ 10. Specialists must not perform destructive or irreversible operations.
299
+ 11. Treat tests as evidence: classify failures as in-scope, pre-existing, or infrastructure before starting fix loop.
300
+ 12. Drive routine stages autonomously once task is clear. Escalate only for human judgment, destructive actions, repeated crashes, or reviewer `FAIL`.
301
+ 13. The orchestrator NEVER edits code directly. Conflict resolution, even mechanical, goes through a debugger or executor specialist. Manual conflict resolution always escalates to the operator. (Exception: epics that explicitly restructure the specialists themselves — bootstrapping via the specialists they restructure is circular. Such epics are operator-authorized manual-orchestrator-direct work and must say so up-front.)
302
+ 14. Before dispatching any chain whose work depends on prior chain output, verify git state per the Git State Precondition section: `git status` clean, HEAD contains prior chain commits, no orphaned worktrees. Stale-base dispatch produces guaranteed debugger-restitch loops downstream.
303
+ 15. Never dispatch a specialist against a bead tagged `contract:draft` (`bd state <id> contract` returns `draft` or nothing). Promote it first — see Draft Beads And The Promotion Gate. A draft is a sanctioned capture format, not a shortcut around bead quality.
304
+
305
+ ## Escalation Matrix
306
+
307
+ | Action | Default | Always escalate to operator |
308
+ |---|---|---|
309
+ | Code edit | Specialist only | (never orchestrator-direct) |
310
+ | Cherry-pick onto integration branch | Auto if non-overlapping | Conflict requiring manual edits |
311
+ | Manual conflict resolution | Never | Always |
312
+ | Force push | Never | Always |
313
+ | Branch delete | Never | Always |
314
+ | Stash pop where conflict expected | Auto | Stash conflict that destroys session-start state |
315
+ | `bd dolt fsck --revive-journal-with-data-loss` | Never | Always — explicit data-loss warning |
316
+ | `sp merge` / `sp epic merge` | Never (prohibited per rule #9; both known broken) | Always — if you reach for these, stop and use manual git workflow |
317
+ | Skip `seconder` (mandatory seconder) on production diff | Auto-skip only on test-only or new-file-only diffs | Always escalate on any other skip — seconder OK is reviewer pre-condition |
318
+ | Skip `obligations-scanner` on production diff | Auto-skip only on test-only or new-file-only diffs | Always escalate on any other skip |
319
+ | Skip `security-auditor` on diff touching auth/secrets/input/agent-config/lockfiles/migrations | Never | Always — sensitive-surface diffs always get the pass |
320
+ | Manual merge with conflicts | Never auto-resolve | Always escalate to operator (rule #13) |
321
+ | Dispatch chain on stale base (HEAD lacks prior chain commit) | Never | Always — fix base first per Git State Precondition |
322
+ | `sp stop <job>` | Auto when job is done/stale | Never on actively-running unless context blown |
323
+ | `git push origin <branch>` | Auto for chain branches | Force-push or delete-remote always |
324
+ | `npm publish` | Never | Always |
325
+ | Dependency bump | Auto for security-patch bumps | Major/minor bumps escalate |
326
+ | Config file schema-changing edit | Never | Always |
327
+ | Dispatch against `contract:draft` bead | Never (rule #15) | Always — promote first: explore + rewrite full 7-section contract + `bd set-state <id> contract=ready --reason "..."` |
328
+ | Interactive coordinator escalation to orchestrator (merge decisions, reviewer PARTIAL/FAIL, sensitive-surface findings) | Coordinator sends via `tmux-session-picker message-send --to $@agent_parent_session --bead <id> --text "..."` — orchestrator replies via `safe-send-pointer` to coordinator's `pane_id` with a `/tmp/reply.md` pointer | Any human-judgment call the coordinator's system prompt flags (see `/multiplexing` Pattern 7 Escalation Contract) |
329
+
330
+ ## Live Registry And Help
331
+
332
+ Use live registry for role details, permissions, current models, and skills:
333
+
334
+ ```bash
335
+ specialists list --full
439
336
  ```
440
- epic
441
- ├── child-1 explore-1 impl-1 → review-1 (reviewer --bead review-1 --job impl-1-job)
442
- ├── child-2 → explore-2 → impl-2 → review-2 (reviewer --bead review-2 --job impl-2-job)
443
- └── child-N → explore-N → impl-N → review-N (reviewer --bead review-N --job impl-N-job)
337
+
338
+ Use help for command flags and subcommands:
339
+
340
+ ```bash
341
+ sp help
342
+ sp run --help
343
+ sp ps --help
344
+ sp feed --help
345
+ sp result --help
346
+ sp resume --help
347
+ sp steer --help
348
+ sp stop --help
444
349
  ```
445
- Children (chains) within the same epic can run **in parallel** if they own disjoint files.
446
350
 
447
- ### Parallel chains (same stage)
448
- Chains in the same stage share no intra-stage dependencies. They depend on the previous stage's output (same epic parent), not on each other.
351
+ Do not rely on stale remembered flags when help is available. (Omitted: `sp finalize`, `sp merge`, `sp epic` — see rule #9. They exist in the binary but the skill prohibits their use.)
352
+
353
+ **`sp view <name> --raw` returns the MERGED effective spec** (package canonical + global user overrides + repo user overrides), same layer precedence as the runtime uses, without the missing-model gate. Since specialists PR #178 this is the correct way to inspect what a specialist will actually run as — the old canonical-only reading is gone. If you need the raw package canonical for debugging (rare), read `.specialist.json` from the specialists package on disk.
354
+
355
+ ## Writing Bead Contracts Well
356
+
357
+ Bead quality controls specialist quality. A title-only bead produces wandering output because specialist has no contract to optimize against. Write contract before dispatch. Tighten vague scope before launch.
358
+
359
+ Bad bead:
360
+
361
+ ```text
362
+ TITLE: Fix bug
363
+ PROBLEM: Something is broken.
364
+ SUCCESS: It works.
365
+ SCOPE: src/
366
+ NON_GOALS: N/A
367
+ CONSTRAINTS: Be careful.
368
+ VALIDATION: Tests pass.
369
+ OUTPUT: Done.
449
370
  ```
450
- # Stage 2 parallel executors (after shared Stage 1 explorer):
451
- bd dep add impl-a explore # impl-a depends on explore, NOT on impl-b
452
- bd dep add impl-b explore # impl-b depends on explore, NOT on impl-a
371
+
372
+ Good bead:
373
+
374
+ ```text
375
+ TITLE: Fix feed cursor regression in sp result
376
+ PROBLEM: specialists feed follow skips events after restart because cursor tracks count, not last seq.
377
+ SUCCESS: feed follow resumes from last seen seq; result still reads terminal output.
378
+ SCOPE: src/cli/feed.ts, src/cli/result.ts, tests/unit/cli/feed.test.ts
379
+ NON_GOALS: No new runtime format, no DB schema change, no unrelated poll changes.
380
+ CONSTRAINTS: Preserve existing job IDs, keep backwards-compatible CLI output, avoid file-based fallback drift.
381
+ VALIDATION: Add regression test for restart resume; run targeted CLI tests.
382
+ OUTPUT: Changed files, test evidence, residual risks.
453
383
  ```
454
- Each runs in its own `--worktree`. Merge via `sp epic merge <epic>` before Stage 3.
455
384
 
456
- ### Test beads (batched)
457
- Tests are **batched** — one test bead covers all impls in a stage, not per-impl.
458
- The test bead depends on **all** impl beads it covers.
385
+ Fix three bad smells fast:
386
+
387
+ - Title-only bead. Add problem, scope, validation, output.
388
+ - Vague SCOPE like `src/`. Name files, symbols, or bounded docs.
389
+ - Missing VALIDATION. Say what proves done, not just that work is “finished.”
390
+
391
+ What differs: orchestrator writes contract before dispatch, so specialist does less guessing and more useful work.
392
+
393
+ ## Draft Beads And The Promotion Gate
394
+
395
+ Full 7-section contracts are expensive to write for an idea you won't touch for weeks. Demanding that rigor for every captured thought is exactly what produces the other failure mode: skipping the bead entirely, or writing a one-liner. There is a third, sanctioned option — but it is a capture format, not an escape hatch.
396
+
397
+ **Draft state.** Tag a bead `contract:draft` at creation:
398
+
399
+ ```bash
400
+ bd create --title "..." --labels contract:draft --type task --priority 3 \
401
+ --description "PROBLEM: <2+ real sentences — why this matters, not a title restated>
402
+ SCOPE: <rough guess — 'somewhere in src/auth/, needs investigation' is fine>
403
+ SUCCESS: TBD — needs exploration
404
+ NON_GOALS: TBD — needs exploration
405
+ CONSTRAINTS: TBD — needs exploration
406
+ VALIDATION: TBD — needs exploration
407
+ OUTPUT: TBD — needs exploration"
459
408
  ```
460
- bd dep add tests impl-a
461
- bd dep add tests impl-b
462
- bd dep add tests impl-c
463
- # specialists run test-runner --bead tests --context-depth 2
409
+
410
+ **No one-liners, ever draft or not.** A draft still requires a real PROBLEM (why this exists, in prose) and a rough SCOPE. Every other section must be present and say `TBD — needs exploration` explicitly. A bare title, or a description that just restates the title, is never a valid bead — draft state lowers the bar on *completeness*, not on *honesty about what's missing*.
411
+
412
+ **The promotion gate (rule #15).** No specialist may be dispatched against a `contract:draft` bead. Before dispatch, the orchestrator must:
413
+
414
+ 1. Re-read the bead (`bd show <id>`).
415
+ 2. Actually explore — the same Phase 2 evidence-gathering the `planning` skill requires before writing a real contract (`gitnexus_query`/`gitnexus_context`/`gitnexus_impact`, or Serena symbol reads).
416
+ 3. Rewrite the bead in place to the full 7-section contract (`bd update <id> --description "..."`), replacing every `TBD` with real content grounded in what was just found.
417
+ 4. Flip the state: `bd set-state <id> contract=ready --reason "Explored via <what>; rewrote to full contract"`.
418
+
419
+ Check before any dispatch: `bd state <id> contract` — if it returns `draft` or nothing, stop and promote. This is a hard refuse (Escalation Matrix), not a warning — a stale draft wastes a full specialist turn on a contract the executor will have to guess at, which is the exact failure this rule exists to prevent.
420
+
421
+ **Current enforcement is a bridge.** This is orchestrator-discipline-enforced today, not yet a hard `sp run` pre-dispatch check — see `specialists-roadmap.md` §5.3 for the planned real enforcement (same class as the existing C1 cwd-mismatch hard-refuse). Follow the rule anyway; do not treat the absence of a hook as license to dispatch against a draft.
422
+
423
+ What differs: orchestrator has a sanctioned way to capture backlog ideas cheaply without either over-scoping them immediately or letting them decay into unusable one-liners.
424
+
425
+ ## Bead Title Convention (canonical)
426
+
427
+ Every bead dispatched to a specialist gets a title in the form:
428
+
429
+ ```text
430
+ <specialist-role>: <concise task description>
464
431
  ```
465
432
 
466
- ---
433
+ Examples: `explorer: map auth refresh path`, `executor: implement token refresh retry`, `reviewer: verify token refresh retry`, `seconder: sanity check token retry diff`, `security-auditor: scan token retry diff`, `test-runner: refresh <epic> failure map`.
434
+
435
+ Why: `bd list`, `bd ready`, `bd query`, and `sp ps` all show titles inline — a role-prefixed title makes the board scannable at a glance (which role owns which open work) without opening each bead. It also disambiguates same-named chains dispatched to different roles against the same parent (e.g. a `seconder:` and a `security-auditor:` bead both `validates`-linked to the same `executor:` bead).
467
436
 
468
- ## Review and Fix Loop
437
+ Rules:
469
438
 
470
- The review fix loop is the mechanism for iterative quality improvement within a single worktree.
439
+ - Prefix with the exact specialist name from `specialists list --full` (`explorer`, `debugger`, `executor`, `reviewer`, `seconder`, `security-auditor`, `test-runner`, `test-engineer`, `obligations-scanner`, `planner`, `overthinker`, `researcher`, `sync-docs`, `changelog-keeper`, `specialists-creator`), not a role synonym.
440
+ - Root task/epic beads that are not themselves dispatched to a single specialist (the umbrella bead a chain is built under) are exempt — keep those descriptive without a role prefix, e.g. `Epic: auth refresh hardening`, `Fix token refresh retry`.
441
+ - Combine with the nesting default above: a role-prefixed title on a `--parent`-nested bead gives both a scannable title and a scannable ID (`bd-x.2` = `seconder: ...`).
471
442
 
472
- ### Standard loop
443
+ What differs: orchestrator can `bd list`/`sp ps` and immediately tell which role owns which open work, instead of opening each bead to find out.
444
+
445
+ ## SCRUTINY taxonomy (Iron-style)
446
+
447
+ `SCRUTINY` is a chain-property from canon §2.2, not reviewer input and not a quality tier. Every substantive bead must declare it at creation. It modulates chain structure only; quality stays invariant. New beads without it are invalid unless read-only / none-chain work.
473
448
 
474
449
  ```
475
- 1. Executor provisions --worktree, implements, enters waiting.
476
- -> Job: exec-job (KEEP ALIVE — do not stop)
477
-
478
- 2. Reviewer enters same worktree via --bead <review-bead> --job exec-job --context-depth 2.
479
- -> sp ps shows the chain:
480
- feature/unitAI-impl-executor · unitAI-impl
481
- ◐ exec-job executor waiting
482
- └ ◐ rev-job reviewer starting
483
- -> Auto-appends verdict (PASS/PARTIAL/FAIL) to review bead notes.
484
-
485
- 3a. PASS:
486
- -> Verify auto-commit landed on branch (git log)
487
- -> Stop reviewer, then stop executor
488
- -> Merge via sp merge
489
-
490
- 3b. PARTIAL/FAIL:
491
- -> Resume the SAME executor: "Reviewer PARTIAL. Fix: <specific findings>"
492
- -> Executor retains full conversation context — no re-dispatch needed
493
- -> Executor applies fixes, enters waiting again
494
- -> Return to step 2 (new reviewer on same --job)
495
-
496
- 4. Repeat until PASS.
450
+ SCRUTINY: none | low | medium | high | critical
497
451
  ```
498
452
 
499
- ### Commands
453
+ | Level | Chain-structure modulation | When to use |
454
+ |---|---|---|
455
+ | `none` | Read-only / design chains only. No production-diff pipeline. | planning, premortem, research-only, triage, doc-sync, memory-hygiene |
456
+ | `low` | Minimal production diff. Keep pipeline light. | tiny isolated fixes |
457
+ | `medium` | Default production-diff chain. | most implementation beads |
458
+ | `high` | Heavier review / evidence floor. | cross-cutting, boundary, public API, persistence, orchestration |
459
+ | `critical` | Max structural gating. | auth, money, irreversible state, security-sensitive work |
460
+
461
+ Floor rule: author sets the minimum; dispatcher/reviewer can raise it on sensitive surfaces per canon §2.4, never lower it.
462
+
463
+ Cross-ref: [`docs/design/chain-templates.md` §2.2](../../../docs/design/chain-templates.md#22-scrutiny-is-a-chain-property--it-modulates-structure-not-quality), [`§2.3`](../../../docs/design/chain-templates.md#23-roles-in-the-canonical-pipeline), [`§2.5`](../../../docs/design/chain-templates.md#25-the-behavioral-validation-contract), [`§2.6`](../../../docs/design/chain-templates.md#26-the-release-checklist), roadmap Opp 15.
464
+
465
+ ## Git State Precondition (before any chain dispatch)
466
+
467
+ Specialist worktrees fork from the current HEAD of the orchestrator's branch at dispatch time. If prior chain edits aren't merged in yet, the new chain works on a stale base, will conflict at integration, and debugger-restitch becomes mandatory. The fix is upstream: don't dispatch until prior work has landed.
468
+
469
+ Required pre-flight before dispatching any chain that depends on prior chain output:
500
470
 
501
471
  ```bash
502
- # Step 1 — Executor with worktree (enters waiting after first turn)
503
- specialists run executor --worktree --bead unitAI-impl --context-depth 2 --background
504
- # -> Job started: exec-job (e.g. 49adda)
505
- # DO NOT sp stop — executor stays alive for the entire review cycle
506
-
507
- # Step 2 — Create reviewer bead and dispatch
508
- bd create --title "Review: impl changes" --type task --priority 2
509
- # -> unitAI-rev
510
- bd dep add rev impl
511
- specialists run reviewer --bead unitAI-rev --job 49adda --context-depth 2 --keep-alive --background
512
- # -> Job started: rev-job
513
- specialists result rev-job
514
-
515
- # Step 3a — PASS: verify auto-commit landed, then stop both
516
- # Executor auto-commits substantive changes on each turn completion
517
- # Verify with: git log feature/unitAI-impl-executor --oneline -1
518
- specialists stop rev-job
519
- specialists stop 49adda
520
- sp merge unitAI-impl --rebuild
521
-
522
- # Step 3b — PARTIAL: resume executor with fix instructions (same session, full context)
523
- specialists resume 49adda "Reviewer PARTIAL. Fix: <paste specific findings here>"
524
- # Executor applies fixes, enters waiting again
525
- # Dispatch new reviewer (new bead for each re-review):
526
- bd create --title "Re-review: impl after fix" --type task --priority 2
527
- # -> unitAI-rev2
528
- bd dep add rev2 impl
529
- specialists run reviewer --bead unitAI-rev2 --job 49adda --context-depth 2 --keep-alive --background
530
- # Repeat until PASS
531
-
532
- # After final PASS + commit + stop:
533
- bd close unitAI-task --reason "Reviewer PASS. All findings addressed."
534
- ```
472
+ # 1. Working tree clean no uncommitted edits to inherit or lose
473
+ git status # MUST report "working tree clean"
535
474
 
536
- ### Why resume instead of re-dispatch
475
+ # 2. HEAD contains prior chain's work
476
+ git log -1 --oneline # confirm latest commit
477
+ git log main..HEAD --oneline # confirm prior chain branch merged in
537
478
 
538
- Resuming the original executor/debugger is **always preferred** over dispatching a new fix executor:
479
+ # 3. No orphaned worktrees from prior chains
480
+ git worktree list # all prior chain worktrees should be removed
481
+ git worktree prune # drop stale metadata
539
482
 
540
- - **Full context**: the specialist remembers what it changed and why — no re-discovery
541
- - **No new bead needed**: no fix bead creation, no dep wiring overhead
542
- - **Same worktree**: no `--job` coordination needed, it's already there
543
- - **Cheaper**: one resumed turn vs a full new specialist session with context injection
483
+ # 4. If on an integration branch
484
+ git log integration/<date>..HEAD # MUST be empty (in sync with integration target)
485
+ ```
544
486
 
545
- Only dispatch a new fix executor when the original specialist is dead (crashed, stopped prematurely, or context exhausted at >80%).
487
+ Decision rule: if any of the four checks fail, finish the merge/commit/cleanup first. Do not dispatch. A specialist forked from a stale base produces conflict work that costs more turns than the time saved by dispatching early.
546
488
 
547
- ### Key invariants
548
- - **Never stop the executor/debugger before reviewer verdict.** The specialist stays in `waiting` throughout the review cycle. Stopping prematurely kills the resume path and risks uncommitted changes.
549
- - **Executors auto-commit substantive changes** on each turn completion (via `auto_commit: checkpoint_on_waiting`). After reviewer PASS, verify the commit landed on the branch before stopping.
550
- - Each fix iteration uses `resume` on the same executor — not a new child bead or new executor.
551
- - Multiple reviewer → resume → re-review cycles are expected. The worktree and specialist session are stable across all cycles.
552
- - Only stop after: (1) reviewer PASS, (2) auto-commit verified on branch.
489
+ Strictness by scenario:
553
490
 
554
- ---
491
+ | Scenario | Strictness |
492
+ |---|---|
493
+ | Sequential chains where child.B depends on child.A's edits | **Strict.** child.A merged before child.B dispatch. |
494
+ | Parallel chains in same epic with disjoint file scopes | Relaxed. Each dispatches off the shared base; integration reconciles. |
495
+ | Chain after orchestrator-direct edit (rule #13 exception epics) | **Strict.** Orchestrator commits + pushes their direct edits before dispatching any dependent chain. |
496
+ | Standalone chain (no upstream dependency) | Relaxed. Just `git status` clean. |
555
497
 
556
- ## Chain Lifecycle Members Are Alive Until Merge
498
+ ## Dependency Linking And Relationship Vocabulary
557
499
 
558
- A chain is not just a worktree it is a **living group of specialists** sharing one workspace. All members of a chain are alive (running or waiting) until the chain is merged or abandoned. Treat chain members as a unit.
500
+ Link beads with correct edge shape. The edge tells orchestrator what blocks execution, what only preserves context, which bead verifies another, and which issue has been replaced. Do not overload `blocks` for follow-ups, root-cause links, verification pairs, duplicates, or restitch replacements.
559
501
 
560
- ### Rules
502
+ Core commands:
561
503
 
562
- 1. **Never kill individual chain members prematurely.** A chain may include explorer, overthinker, executor, reviewer all sharing one worktree via `--job`. Do not `sp stop` any member while the chain is active, unless the member has crashed or is context-exhausted (>80%).
563
- 2. **The chain is alive until merge.** From first dispatch (even if it's a READ_ONLY explorer) through reviewer PASS and executor commit — the chain is one living unit. Members stay in `waiting` between turns.
564
- 3. **Resume, don't re-dispatch.** When a chain member needs to act again (executor fixing reviewer findings, overthinker answering follow-ups), use `sp resume` on the existing member. Only dispatch a replacement if the original is dead.
565
- 4. **Merge kills the chain.** When `sp merge` or `sp epic merge` publishes a chain's branch, all chain members become obsolete. *(Future: `sp merge` will auto-stop all chain members on successful merge no manual cleanup needed.)*
566
- 5. **Stop order matters (until auto-cleanup).** When manually stopping chain members after merge: stop dependents first (reviewer), then the chain owner (executor/explorer). This prevents race conditions with resume paths.
504
+ - `bd dep add <issue> <depends-on>`: issue depends on depends-on; depends-on blocks issue. Default type is `blocks`. Use only for hard sequencing. [source: bd dep add --help]
505
+ - `bd dep <blocker> --blocks <blocked>`: reverse phrasing of the same hard sequencing edge. [source: bd dep --help]
506
+ - `bd dep add <issue> <other> --type <type>`: store a typed relationship. Supported types: `blocks`, `tracks`, `related`, `parent-child`, `discovered-from`, `until`, `caused-by`, `validates`, `relates-to`, `supersedes`. [source: bd dep add --help]
507
+ - `bd dep relate <a> <b>` / `bd dep unrelate <a> <b>`: bidirectional non-blocking `relates_to` link. Use for context, not order. [source: bd dep --help]
508
+ - `bd create --parent <bead-id>`: hierarchical child edge; auto-names child `<parent>.1`, `<parent>.2`, and nests recursively a child's own child becomes `<parent>.1.1`. `<bead-id>` can be an epic, a plain task, or an already-nested child; bd does not restrict `--parent` by issue type (`bd create --help` describes it generically as "Parent issue ID for hierarchical child"). [source: bd create --help]
509
+ - `bd create --deps discovered-from:<id>` or `bd dep add <new> <source> --type discovered-from`: follow-up work discovered from a source bead.
510
+ - `bd duplicate <new> --of <canonical>`: close duplicate issue and point at canonical. Use when two beads describe the same required work.
511
+ - `bd duplicates` / `bd find-duplicates --status open --method ai --json`: find exact or semantic duplicates before dispatching parallel chains.
512
+ - `bd supersede <old> --with <new>` or `bd dep add <new> <old> --type supersedes`: mark a replacement when a better-scoped fix bead replaces an obsolete/abandoned one.
513
+ - `bd dep cycles`, `bd dep tree <id>`, and `bd graph <id>`: sanity-check the execution graph before merge/publication.
567
514
 
568
- ### Chain member states
515
+ **Default to nesting, not loose beads.** When a chain is dispatched to service an existing bead — a top-level task, an epic, or an already-nested child like `bd-x.1` — create the new bead with `bd create --parent <that-bead>` so it inherits the next sequential child ID (`bd-x.1`, or `bd-x.1.1` if the parent is itself a child). This applies uniformly, not only under epics — the common failure mode is orchestrators treating `--parent` as epic-only and defaulting every explorer/executor/reviewer/seconder/security bead spawned mid-chain to a loose top-level bead linked solely by a typed dep. `--parent` (hierarchy/ID) and a typed `bd dep add ... --type <blocks|validates|discovered-from>` edge (semantic relationship) are independent flags — combine both when the relationship needs naming beyond parentage. Only skip `--parent` when the new bead is a genuine standalone sibling concern, not work done on behalf of the bead it services.
569
516
 
570
- | Member state | Meaning | Action |
571
- |-------------|---------|--------|
572
- | `running` | Actively working | Wait or steer |
573
- | `waiting` | Idle, retains full context | Resume when needed |
574
- | `done` | Finished its turn, output appended | Leave alone — chain may still need it |
575
- | `error` | Crashed or failed | May need replacement dispatch |
517
+ Relationship vocabulary for specialist chains:
576
518
 
577
- ### What "don't kill" means in practice
519
+ | Relationship | Reach for it when | Example command |
520
+ | --- | --- | --- |
521
+ | `blocks` | Hard must-happen-before sequencing: planner before executor, implementation before reviewer, restitch before publish. | `bd dep add <impl> <plan> --type blocks` |
522
+ | `tracks` | A local bead mirrors upstream or cross-project work whose status matters but is not owned here. | `bd dep add <local> external:xtrm-tools:<capability> --type tracks` |
523
+ | `related` | Loose topical association when no direction or scheduling effect is intended. Prefer `bd dep relate` for bidirectional relation. | `bd dep add <a> <b> --type related` |
524
+ | `parent-child` | Any bead spawns tracked child work — epic owning chains, a task spawning its explorer/executor/reviewer, or an already-nested child spawning its own sub-chain. Prefer `bd create --parent <bead>` (not only `<epic>`) so IDs nest and parentage stays canonical instead of drifting into loose top-level beads. | `bd create --parent <bead-id> --title "executor: Impl auth retry" ...` |
525
+ | `discovered-from` | Reviewer, debugger, explorer, or test-runner surfaces new follow-up work from a run. | `bd dep add <follow-up> <reviewer-bead> --type discovered-from` |
526
+ | `until` | Time-bounded or event-bounded precondition that blocks only until a stated condition lands. | `bd dep add <chain> <precondition> --type until` |
527
+ | `caused-by` | Failure bead points to the root-cause bead/cluster that explains it. Makes test-failure-map epics navigable. | `bd dep add <failing-test> <root-cause> --type caused-by` |
528
+ | `validates` | Reviewer, test-runner, seconder, or security-auditor bead verifies an implementation/debugger bead. | `bd dep add <review> <impl> --type validates` |
529
+ | `relates-to` | Bidirectional context edge for conflict clusters, sibling designs, or rebuttal patterns. Prefer dedicated relate command. | `bd dep relate <chain-a> <chain-b>` |
530
+ | `supersedes` | New fix/design/restitch bead replaces an older bead that should no longer be executed or merged. Prefer `bd supersede`. | `bd supersede <old> --with <new>` |
531
+
532
+ Worked high-value patterns:
578
533
 
579
534
  ```bash
580
- # BAD killing executor before review cycle completes
581
- sp stop exec-job # kills resume path, risks uncommitted work
582
-
583
- # BAD — killing overthinker before executor uses its output
584
- sp stop overthinker-job # loses context if follow-up questions arise
585
-
586
- # GOOD chain completes naturally
587
- # verify auto-commit landed on branch...
588
- sp merge unitAI-impl # publishes branch
589
- # THEN stop members (future: auto-stopped by merge)
590
- sp stop rev-job
591
- sp stop exec-job
535
+ # Reviewer discovers a separate follow-up during review. Do not block the impl.
536
+ bd create --title "Follow up: tighten retry metrics" --type task --priority 3 --description "..."
537
+ bd dep add <follow-up> <review> --type discovered-from
538
+
539
+ # Test-failure-map root cause: many failures point at one underlying issue.
540
+ bd create --title "Root cause: stale fixture factory" --type bug --priority 2 --description "..."
541
+ bd dep add <failing-test-bead> <root-cause> --type caused-by
542
+
543
+ # Verification bead validates implementation. This is not a hard prerequisite edge.
544
+ bd dep add <test-runner-bead> <impl> --type validates
545
+ bd dep add <reviewer-bead> <impl> --type validates
546
+
547
+ # Replacement bead supersedes an abandoned or wrongly scoped implementation.
548
+ bd create --title "Restitch auth retry onto integration state" --type task --priority 2 --description "..."
549
+ bd supersede <old-impl> --with <restitch>
550
+
551
+ # Before merging an epic or integration branch, prove the graph is sane.
552
+ bd dep cycles
553
+ bd graph <epic> --compact
592
554
  ```
593
555
 
594
- ---
556
+ Use each form for a different reason:
595
557
 
596
- ## Merge Protocol Epic Publication
558
+ - `blocks` / `--blocks` for must-happen-before dependency only.
559
+ - `validates` for review, test, sanity, and security evidence.
560
+ - `discovered-from` for spawned follow-up beads.
561
+ - `caused-by` for failure-to-root-cause attribution.
562
+ - `relates-to` / `bd dep relate` for soft linkage with no schedule effect.
563
+ - `parent-child` / `--parent` for hierarchy and child naming — use for any bead spawned to do work on behalf of another bead, not only epic ownership. Nests recursively: a chain dispatched from an already-nested child (e.g. `bd-x.1`) becomes `bd-x.1.1`, not a new loose top-level bead.
564
+ - `supersedes` / `bd supersede` for replacement work; `duplicate` for same-work issues.
597
565
 
598
- The orchestrator owns merge timing, but **no longer performs manual git merges**. Use `sp epic merge` or `sp merge` instead.
566
+ Cross-repo consistency: keep this vocabulary aligned with the xtrm-tools triaging skill and sibling triage bead `xtrm-drkk`; both should use the same relationship names when rewiring issue graphs.
599
567
 
600
- ### The canonical path: `sp epic merge <epic-id>`
568
+ What differs: orchestrator chooses edge type deliberately, so graph stays correct for chain execution, epic publish, duplicate cleanup, root-cause navigation, verification evidence, and follow-up traceability.
601
569
 
602
- **This is the ONLY legal publication path for wave-bound chains.**
570
+ ## Bead Contract By Bead Type
603
571
 
604
- An epic is merge-gated: all chains must be terminal with reviewer PASS before publication. Use `sp epic merge` for:
572
+ Use shape that fits specialist.
605
573
 
606
- - Publishing multiple chains under one epic (topological order)
607
- - Ensuring merge gates are satisfied (no running jobs)
608
- - PR mode (`--pr`) for staged publication
574
+ > **SCRUTINY field is universal.** Every substantive bead should carry `SCRUTINY: none|low|medium|high|critical` at creation. It is a chain-property, not reviewer behavior; it controls chain structure and gate strictness per the SCRUTINY taxonomy section and canon §2.2. Reviewer may auto-escalate but never lower it. Canon refs: §2.2, §2.3, §2.5, §2.6.
609
575
 
610
- ```bash
611
- # Check epic readiness
612
- sp epic status unitAI-3f7b
613
- # Shows: chains, blockers, readiness state, reviewer verdicts
576
+ Task/epic bead:
577
+
578
+ ```text
579
+ PROBLEM: User-facing or project-facing objective.
580
+ SUCCESS: End-state across all child beads.
581
+ SCRUTINY: none|low|medium|high|critical # required at creation; chain-property, not reviewer input
582
+ SCOPE: Area of project affected.
583
+ REFERENCES: Optional files, skills, or docs specialist reads only if work needs them.
584
+ NON_GOALS: Boundaries for entire effort.
585
+ CONSTRAINTS: Sequencing, compatibility, branch/merge rules.
586
+ VALIDATION: Final checks before close.
587
+ OUTPUT: What orchestrator reports back.
588
+ ```
589
+
590
+ `SCOPE` is always loaded as context. `REFERENCES` is progressive disclosure: name what exists, but do not force load unless task needs it. Use this when a file would bloat payload today, like citing a huge skill file in scope and dragging in all lines before specialist even knows it must read them.
614
591
 
615
- # Publish all epic-owned chains
616
- sp epic merge unitAI-3f7b
617
- # → merges in topological order, tsc gate after each
592
+ Example:
618
593
 
619
- # PR mode (creates PR instead of direct merge)
620
- sp epic merge unitAI-3f7b --pr
594
+ ```text
595
+ SCOPE: config/skills/using-specialists/SKILL.md, docs/specialists/handoff-schema.md
596
+ REFERENCES: config/skills/prompt-improving/SKILL.md (xml_core conventions), sibling beads per-turn-handoff-schema and bead-id-verbatim once landed
621
597
  ```
622
598
 
623
- **What `sp epic merge` does:**
599
+ Explorer bead:
624
600
 
625
- 1. Reads epic state from observability SQLite
626
- 2. Checks all chains are terminal (`done`/`error`)
627
- 3. Verifies latest reviewer verdict is PASS
628
- 4. Topologically sorts chains by bead dependencies
629
- 5. For each chain: `git merge <branch> --no-ff --no-edit`
630
- 6. Runs `bunx tsc --noEmit` after each merge
631
- 7. Optionally creates PR with `--pr` flag
632
- 8. Updates epic state to `merged` on success
601
+ ```text
602
+ PROBLEM: What is unknown.
603
+ SUCCESS: Questions answered with evidence.
604
+ SCOPE: Code areas, docs, commands, or symbols to inspect.
605
+ NON_GOALS: No implementation, no broad audit outside scope.
606
+ CONSTRAINTS: READ_ONLY, cite files/symbols/flows.
607
+ VALIDATION: Findings cite evidence.
608
+ OUTPUT: Findings, risks, recommended implementation track, stop condition.
609
+ ```
633
610
 
634
- ### When NOT to merge: `sp merge <chain-root>` is blocked
611
+ Debugger bead:
635
612
 
636
- **Standalone chains only.** `sp merge <chain-root-bead>` works ONLY for chains NOT belonging to an unresolved epic:
613
+ ```text
614
+ PROBLEM: Symptom, regression, or failing test.
615
+ SUCCESS: Root cause plus minimal fix path.
616
+ SCOPE: Logs, reproduction, code paths, and related tests.
617
+ NON_GOALS: No broad refactor.
618
+ CONSTRAINTS: Preserve behavior outside fault line.
619
+ VALIDATION: Repro steps and diagnosis.
620
+ OUTPUT: Root cause, fix options, confidence, remaining unknowns.
621
+ ```
637
622
 
638
- ```bash
639
- # This FAILS if chain belongs to epic with status=open/resolving/merge_ready
640
- sp merge unitAI-impl
641
- # Error: Chain unitAI-impl belongs to unresolved epic unitAI-3f7b (status: resolving).
642
- # Use 'sp epic merge unitAI-3f7b' to publish all chains together.
623
+ Executor bead:
624
+
625
+ ```text
626
+ PROBLEM: Exact behavior or artifact to change.
627
+ SUCCESS: Observable acceptance criteria.
628
+ SCRUTINY: none|low|medium|high|critical # required at creation; chain-property, not reviewer input
629
+ SCOPE: Target files/symbols; include do-not-touch boundaries.
630
+ NON_GOALS: Related improvements explicitly excluded. (Include any accepted in-code obligation markers tracked in follow-up beads.)
631
+ CONSTRAINTS: API compatibility, style, migrations, safety.
632
+ VALIDATION: Lint/typecheck/tests or manual checks.
633
+ OUTPUT: Changed files, verification, residual risks.
643
634
  ```
644
635
 
645
- **Why this guard exists:**
636
+ Reviewer bead:
637
+
638
+ ```text
639
+ PROBLEM: Verify executor output against requirements.
640
+ SUCCESS: PASS only if requirements + validation + Release Checklist satisfied.
641
+ SCRUTINY: none|low|medium|high|critical # required at creation; chain-property, not reviewer input
642
+ SCOPE: Executor job, diff, task bead, acceptance criteria.
643
+ NON_GOALS: Do not rewrite unless explicitly asked.
644
+ CONSTRAINTS: Code-review mindset; findings first; emit Release Checklist.
645
+ VALIDATION: Run or inspect required checks; consume obligations-scanner output.
646
+ OUTPUT: PASS/PARTIAL/FAIL with file/line findings + Release Checklist block.
647
+ ```
646
648
 
647
- 1. **Merge gates are per-epic**: Publishing one chain without its siblings breaks the wave model.
648
- 2. **Topological order matters**: Chain A may depend on Chain B — merging A first breaks deps.
649
- 3. **Epics are explicit**: The epic bead ID is tracked in SQLite, enabling the guard.
649
+ Test bead:
650
650
 
651
- ### When to merge within a chain vs NOT
651
+ ```text
652
+ PROBLEM: Validate one or more implementation chains.
653
+ SUCCESS: Relevant tests/checks pass or failures are diagnosed.
654
+ SCOPE: Commands and implementation beads covered.
655
+ NON_GOALS: No broad unrelated suite expansion unless requested.
656
+ CONSTRAINTS: Avoid destructive cleanup; report flaky/infra failures separately.
657
+ VALIDATION: Command output and failure interpretation.
658
+ OUTPUT: Pass/fail summary, failing tests, likely owner.
659
+ ```
652
660
 
653
- **Do NOT merge within a chain.** A chain is a sequence of specialists sharing one worktree:
654
- executor → reviewer → fix → re-review. The worktree stays live throughout. No merge until
655
- the reviewer says PASS.
661
+ Sync-docs bead:
656
662
 
663
+ ```text
664
+ PROBLEM: Exactly one doc drifted from source truth.
665
+ SUCCESS: One doc updated and drift checked clean.
666
+ SCOPE: One doc only.
667
+ NON_GOALS: No source-code rewrite.
668
+ CONSTRAINTS: Keep doc and source aligned.
669
+ VALIDATION: Drift scan or bounded source cross-check.
670
+ OUTPUT: Updated doc, drift evidence, remaining doc gaps.
657
671
  ```
658
- executor --worktree --bead impl ← creates worktree
659
- reviewer --job <exec-job> ← enters same worktree (no merge)
660
- executor --bead fix --job <exec-job> ← re-enters same worktree (no merge)
661
- reviewer --job <exec-job> ← re-enters same worktree (no merge)
662
- PASS → NOW run sp epic merge <epic>
672
+
673
+ What differs: orchestrator gives each specialist a contract shape that matches job, so role stays narrow and reviewable.
674
+
675
+ For evidence-heavy or multi-item beads, let `SCOPE`, `CONSTRAINTS`, and `EXAMPLES` carry opt-in XML tags. Follow prompt-improving `xml_core` style: wrap only the subpart that needs structure, not whole bead. Example: a debugger bead can put stack trace lines in `<evidence>` and do-not-touch items in `<constraints>`, so specialist can scan facts fast without turning every field into markup.
676
+
677
+ ## Choosing The Specialist
678
+
679
+ Run `specialists list` if you need live registry. Choose by task, not habit.
680
+
681
+ | Need | Specialist | Use when |
682
+ | --- | --- | --- |
683
+ | Architecture/code mapping | `explorer` | Need evidence and scoped implementation track |
684
+ | Root-cause analysis | `debugger` | Symptom, stack trace, failing test, or regression |
685
+ | Planning/decomposition | `planner` | Need beads, dependencies, file scopes, sequencing |
686
+ | Design/tradeoffs | `overthinker` | Approach is risky, ambiguous, or needs critique |
687
+ | Implementation | `executor` | Contract is clear enough to write code or docs |
688
+ | Compliance/code review | `reviewer` | Executor/debugger produced changes that need final PASS/PARTIAL/FAIL |
689
+ | Seconder gate (mandatory) | `seconder` | Production diff — fused scope/compliance + quality gate; reviewer pre-condition |
690
+ | Obligations gate (mandatory) | `obligations-scanner` | Production diff — scans for unstructured TODO/FIXME/HACK/XXX/TEMP/WIP/NOTE(release) markers |
691
+ | Security/dependency audit | `security-auditor` | Diff touches auth/secrets/input/lockfiles/migrations/agent-config |
692
+ | Test execution | `test-runner` | Need suites run and failures interpreted |
693
+ | Docs audit/sync | `sync-docs` | Docs may be stale or need targeted synchronization |
694
+ | External/live research | `researcher` | Any library/API/framework/CLI question — dispatch BEFORE answering from training data |
695
+ | Specialist config | `specialists-creator` | Creating or changing specialist JSON/config |
696
+ | Release publication | `changelog-keeper` | New tag is being cut |
697
+
698
+ Selection rules:
699
+
700
+ - Explorer is READ_ONLY and should answer specific questions.
701
+ - Debugger beats explorer for failures because it traces causes and remediation.
702
+ - Planner shapes epic/task graph before executor starts.
703
+ - Overthinker defends risky design before code locks in. It is CoT specialist by design, so thinking-heavy turns and `<thinking>` tags fit there.
704
+ - Reviewer already uses structured evidence/gap matrices, which is CoT in disguise; keep that structure, do not add freeform `<thinking>` blocks.
705
+ - Executor, debugger, changelog-keeper, sync-docs, and test-runner should not carry mandatory `<thinking>` blocks. That bloats output without payoff and hides the real contract.
706
+ - Executor does not own full test validation; use reviewer/test-runner for that phase.
707
+ - Sync-docs is for audit/sync; executor is for heavy doc rewrites.
708
+ - Researcher is for current external info, not repo archaeology. **Dispatch BEFORE answering any library/API/framework/CLI question from training data** — your knowledge is stale by months and APIs drift silently. The cost is one CLI call; the alternative is shipping wrong API usage.
709
+ - Specialists-creator should precede specialist config/schema edits.
710
+ - `parallel-review` is deprecated — old design that doesn't fit current sp shape. Do not reach for it. Use `overthinker` for independent second opinion or queue a second `reviewer` turn manually if needed.
711
+
712
+ ## Bug Diagnosis Chain
713
+
714
+ For symptoms, errors, regressions, flakes, or failing tests where cause is unknown, start with diagnosis — not implementation. Do not dispatch executor while cause is unknown; executor is for clear implementation scope only.
715
+
716
+ Default chain:
717
+
718
+ 1. **test-runner** or **debugger** establishes a fast deterministic feedback loop. If no loop can be built, debugger reports the blocker — do not patch in the dark.
719
+ 2. **debugger** reproduces the symptom, writes 3–5 falsifiable hypotheses, and tests one variable at a time. Any temporary instrumentation must be tagged `[DEBUG-<id>]` and removed before completion.
720
+ 3. **debugger** applies the minimal root-cause fix on the fault line and verifies via targeted lint/typecheck plus the focused repro.
721
+ 4. **test-runner** reruns the original repro/regression command (full-suite validation is its job, not debugger's).
722
+ 5. **seconder** runs if the fix smells brittle, overcomplicated, or type-risky. **security-auditor** runs if the fix touches auth/session/secrets/input handling, dependency logic, or agent/MCP/hook config.
723
+ 6. **reviewer** gates the final diff against the bead contract.
724
+ 7. If no correct regression-test seam exists, route the architecture/testability finding to **overthinker** or **planner** — do not force a brittle test just to close the loop.
725
+
726
+ Explorer is useful before diagnosis only when no concrete symptom exists and architecture is unknown. For real bugs with a symptom, use debugger.
727
+
728
+ ## Seconder
729
+
730
+ The mandatory post-writer gate (canon §2.3): one READ_ONLY dual-verdict pass over the writer's diff that checks **scope/compliance** (does the diff satisfy the bead contract sections?) and **implementation quality** (complexity, duplication, type safety, brittle async/error handling) together, before test-engineer and reviewer.
731
+
732
+ Bead shape:
733
+
734
+ ```text
735
+ PROBLEM: Verify the writer diff satisfies the bead contract and is implementation-sound before expensive QA.
736
+ SUCCESS: Dual-verdict isolates any scope or quality issue, or confirms the diff is clean.
737
+ SCOPE: Writer diff, risky files, and any nearby helpers.
738
+ NON_GOALS: No edits, no broad refactor, no release blessing, no security audit, no broad reviewer phase-2.
739
+ CONSTRAINTS: READ_ONLY, keep feedback cheap, cite exact sections/lines/symbols.
740
+ VALIDATION: scope_verdict + quality_verdict + overall_verdict with concrete findings.
741
+ OUTPUT: JSON dual-verdict (scope_verdict / scope_findings / quality_verdict / quality_findings / overall_verdict).
663
742
  ```
664
743
 
665
- **DO merge between stages (via epic).** When the next stage's chains depend on this stage's code existing on master, merge the epic first. The dep graph tells you: beads connected by `--job` are one chain (same worktree, no merge). Beads connected by `bd dep add` across different file scopes are separate chains under the same epic.
744
+ The chain reducer reads `overall_verdict`: PASS advances to test-engineer; FAIL routes back to the writer. Hand findings back with `sp resume <exec-job> "Seconder overall_verdict=FAIL scope: ...; quality: ..."`.
666
745
 
667
- ### Planning context upfront
746
+ A seconder PASS is the upstream scope gate for the reviewer; it is not itself a reviewer PASS.
668
747
 
669
- Before dispatching any chains, identify:
670
- - **Epics** — the top merge-gated identity (create epic-type bead first)
671
- - **Chains** — worktree lineages that belong to the epic (use `--epic` for prep jobs)
672
- - **Stages** — batches of independent chains ("Stage 1" / "Stage 2" are orchestrator speech)
748
+ What differs: orchestrator uses seconder as cheap smell screen, not as merge gate.
673
749
 
674
- The dep graph encodes this. If bead B depends on bead A and they touch different files, they're separate chains under the same epic with a merge point between stages.
750
+ ## Security-auditor
675
751
 
676
- ### Epic lifecycle commands
752
+ Use security-auditor when diff touches auth, secrets, input handling, dependency logic, or agent/config surfaces. Keep it advisory and scan-only.
677
753
 
678
- ```bash
679
- # List epics with state
680
- sp epic list
681
- sp epic list --unresolved # show non-terminal epics
754
+ Bead shape:
755
+
756
+ ```text
757
+ PROBLEM: Diff may open auth, secrets, input, dependency, or agent-config risk.
758
+ SUCCESS: Findings isolate real security concern or confirm no obvious issue.
759
+ SCOPE: Executor diff, touched configs, and security-relevant paths.
760
+ NON_GOALS: No edits, no package updates, no destructive scans, no live exploit tests.
761
+ CONSTRAINTS: LOW permissions, scan-only, recommendations only.
762
+ VALIDATION: Findings cite risk surface and why it matters.
763
+ OUTPUT: Recommendations for executor to apply in a separate bead.
764
+ ```
765
+
766
+ Use `sp resume <exec-job> "Security findings: ..."` or `sp resume <exec-job> "Security scan clean; continue to reviewer."`.
767
+
768
+ No findings is not reviewer PASS. Executor still applies fixes if any, then reviewer decides publish.
682
769
 
683
- # Inspect one epic
684
- sp epic status unitAI-3f7b
685
- # Shows: derived readiness state, persisted state (audit only), chains[], blockers[], summary
770
+ What differs: orchestrator uses security-auditor to surface risk early, not to bless merge.
686
771
 
687
- # Publish (no manual state transition — readiness is derived live)
688
- sp epic merge unitAI-3f7b # batch publish all chains; auto-finalizes PASS chains
689
- sp epic merge unitAI-3f7b --pr # PR mode
772
+ ## Dependency Graph Shapes
690
773
 
691
- # Or per-chain (PASS chain inside active epic is allowed)
692
- sp merge <chain-root-bead>
693
- sp finalize <chain-root-bead> # manual recovery if PASS auto-finalize missed
774
+ Draw graph before dispatch.
775
+
776
+ Simple chain:
777
+
778
+ ```text
779
+ task -> explore -> impl -> review
694
780
  ```
695
781
 
696
- ### Conflict handling
782
+ Fix loop:
697
783
 
698
- If merge hits a conflict:
784
+ ```text
785
+ debug -> exec -> seconder? -> security-auditor? -> reviewer
786
+ ^ |
787
+ |------ resume PARTIAL --------------|
788
+ ```
699
789
 
700
- 1. Command fails with list of conflicting files
701
- 2. Resolve conflicts manually in your editor
702
- 3. Run `bunx tsc --noEmit` to verify
703
- 4. Continue with next chain (or re-run `sp epic merge <epic>` to resume)
790
+ Epic:
791
+
792
+ ```text
793
+ epic
794
+ ├─ prep/planner
795
+ ├─ impl-a
796
+ ├─ impl-b
797
+ ├─ test-batch
798
+ └─ merge/review chain(s)
799
+ ```
704
800
 
705
- **Common conflict pattern:** Parallel chains in the same stage may both create the same utility file (e.g. `job-root.ts`). This is expected — implementations should be identical. Keep one, delete the duplicate during conflict resolution.
801
+ What differs: orchestrator sees edge shape up front, so can pick sequential chain, fix loop, or multi-chain epic without graph drift.
706
802
 
707
- ---
803
+ ## Pre-Dispatch: Conflict Cluster Identification
708
804
 
709
- ## Bead-First Workflow (`--bead` is the prompt)
805
+ Before dispatching N parallel chains, build the file-overlap matrix:
710
806
 
711
- For tracked work, the bead is not just bookkeeping — it is the specialist's prompt.
712
- The specialist reads:
713
- - the bead title + description
714
- - bead notes (including output appended by previous specialists in the chain)
715
- - parent/ancestor bead context (controlled by `--context-depth`)
807
+ | Chain | Touches | Overlap with |
808
+ |-------|---------|--------------|
809
+ | chain-A | src/cli/update.ts | chain-B, chain-C |
810
+ | chain-B | src/cli/update.ts, src/cli/install.ts | chain-A, chain-C, chain-D |
811
+ | chain-C | src/cli/update.ts, src/cli/install.ts, src/cli/doctor.ts | chain-A, chain-B |
716
812
 
717
- **Automatic context injection**: Runner injects ~3800 tokens of project memory at spawn:
718
- - `.xtrm/memory.md` (SSOT: Do Not Repeat, How This Project Works, Active Context)
719
- - `bd prime` output (workflow rules + all bd memories dump)
720
- - GitNexus cheatsheet (when `.gitnexus/meta.json` exists — ~100 tokens)
813
+ For each cluster of overlapping chains, choose **one** of:
721
814
 
722
- This prevents specialists from rediscovering known gotchas on every run.
815
+ 1. **Serial dispatch** execute chains in dependency order, each waits for previous to land. Slowest but cleanest. Encode the order with `blocks`, not notes.
816
+ 2. **Unified bead** — collapse all chains into one bead/executor pass. Larger reviewer scope but no merge conflicts. Mark obsolete split beads with `bd supersede <old> --with <unified>`.
817
+ 3. **Parallel dispatch + debugger restitch at integration** — dispatch in parallel, plan for ~40% conflict rate (empirical), budget debugger-restitch passes during integration. Link overlapping siblings with `bd dep relate <chain-a> <chain-b>` so the future restitch has visible context without creating fake blockers.
723
818
 
724
- **Never use `--prompt`.** For tracked work, always use `--bead`. When you need to give a specialist
725
- specific instructions beyond what's in the bead description, update the bead notes first:
819
+ Example graph rewiring:
726
820
 
727
821
  ```bash
728
- bd update unitAI-abc --notes "INSTRUCTION: Rewrite docs/cli-reference.md from current
729
- source. Read every command in src/cli/ and src/index.ts. Document all flags and examples."
822
+ # soft conflict-cluster context; does not change schedule
823
+ bd dep relate <chain-a> <chain-b>
824
+
825
+ # serializing because both chains edit src/cli/update.ts
826
+ bd dep add <chain-b> <chain-a> --type blocks
730
827
 
731
- specialists run executor --bead unitAI-abc --context-depth 2 --background
828
+ # replacing scattered duplicate/split beads with one unified implementation
829
+ bd supersede <old-chain-a> --with <unified-chain>
830
+ bd supersede <old-chain-b> --with <unified-chain>
732
831
  ```
733
832
 
734
- **`--context-depth N`** how many levels of parent-bead context to inject (default: 1).
735
- Use **`--context-depth 2`** for all chained bead workflows. This gives each specialist its
736
- own bead + the immediate predecessor's output + one more level of context.
833
+ Default heuristic: if 3+ chains touch the same file, **serial-dispatch them**. Conflict-resolution time at integration usually exceeds the time saved by parallel dispatch. Run `bd find-duplicates --status open --method ai --json` before launching a large wave; merge or supersede duplicate work before specialists spend tokens on it.
737
834
 
738
- **`--no-beads`** — skip creating an auto-tracking sub-bead, but still reads the `--bead` input.
835
+ ## Pre-Epic: Test-Failure-Map Pattern
739
836
 
740
- **Edit gate access**: Specialists with `--bead` automatically set `bead-claim:<id>` KV key,
741
- enabling write access in worktrees without session-scoped claims. Cleared on run completion.
837
+ Use when:
838
+ - A test suite shows ~5 failures and the operator says "fix all"
839
+ - The failures span multiple files / subsystems
840
+ - Root causes are not yet attributed per failure
742
841
 
743
- ---
842
+ ### Step-by-step
843
+
844
+ 1. **Run the suite once**, save the full log. Do not interpret yet.
845
+ 2. **File one mapping bead** titled per the Bead Title Convention (e.g., `test-runner: refresh <epic> failure map`) with contract:
846
+ - `PROBLEM:` exact command + exit status + raw failure count.
847
+ - `SUCCESS:` cluster table grouping every failure by **likely shared root cause and file scope**, plus recommended fix-chain order.
848
+ - `SCOPE:` the log file path + bounded test files involved.
849
+ - `CONSTRAINTS:` READ_ONLY, no source/test edits, no fix attempts.
850
+ 3. **Dispatch test-runner / explorer / debugger** for this bead READ_ONLY (or fill inline by reading the log).
851
+ 4. **Build the cluster table**: cluster name | files (counts) | representative error | root-cause hypothesis | likely-owner area | targeted validation command. Save in bead notes.
852
+ 5. **Wire root-cause relationships** so the graph is navigable:
853
+ ```bash
854
+ bd dep add <failure-cluster-bead> <root-cause-bead> --type caused-by
855
+ bd dep add <test-runner-bead> <fix-bead> --type validates
856
+ ```
857
+ Use `caused-by` for attribution, not `blocks`; use `validates` for the evidence-producing test bead.
858
+ 6. **Plan fix chains** off the cluster table:
859
+ - One chain per cluster, file scopes disjoint where possible.
860
+ - Order by leverage (largest cluster first), then by simplicity.
861
+ - Debugger when root cause unclear; executor when bead constraint is concrete.
862
+ 7. **Save the topology insight as `bd remember`** — patterns about where a codebase's test fragility concentrates are reusable.
863
+
864
+ ### Why this beats dispatch-blind
744
865
 
745
- ## Choosing the Right Specialist
746
-
747
- Run `specialists list` to see what's available. Match by task type:
748
-
749
- | Task type | Best specialist | Why |
750
- |-----------|----------------|-----|
751
- | Architecture exploration / initial discovery | **explorer** (claude-haiku) | Fast codebase mapping, READ_ONLY. Output auto-appends to bead. |
752
- | Live docs / library lookup / code discovery | **researcher** (claude-haiku) | Targeted (ctx7/deepwiki) or discovery (ghgrep → deepwiki) modes. `--keep-alive`. |
753
- | Bug fix / feature implementation | **executor** (gpt-codex) | HIGH perms, writes code, runs lint+tsc, closes beads. `interactive: true` by default — enters `waiting` after first turn, orchestrator must stop explicitly. |
754
- | Bug investigation / "why is X broken" | **debugger** (claude-sonnet) | 4-phase debug-fix-verify cycle. HIGH perms, keep-alive. GitNexus-first. |
755
- | Complex design / tradeoff analysis | **overthinker** (gpt-4) | 4-phase: analysis → devil's advocate → synthesis → conclusion. `--keep-alive`. |
756
- | Code review / compliance | **reviewer** (claude-sonnet) | PASS/PARTIAL/FAIL verdict. Use via `--job <exec-job>`. `--keep-alive`. |
757
- | Multi-backend review | **parallel-review** (claude-sonnet) | Concurrent review across multiple backends |
758
- | Planning / scoping | **planner** (claude-sonnet) | Structured issue breakdown with deps |
759
- | Doc audit / drift detection / targeted sync | **sync-docs** (qwen3.5-plus) | 3-mode: targeted (named docs), area (time-window), full audit. MEDIUM perms, `--keep-alive`. |
760
- | Doc writing / updates | **executor** (gpt-codex) | For heavy doc rewrites; sync-docs handles targeted updates directly |
761
- | Test generation / suite execution | **test-runner** (claude-haiku) | Runs suites, interprets failures |
762
- | Specialist authoring | **specialists-creator** (claude-sonnet) | Guides JSON creation against schema |
763
-
764
- ### Specialist selection notes
765
-
766
- - **executor does not run tests** — it runs `lint + tsc` only. Tests belong to the reviewer or test-runner phase.
767
- - **executor enters `waiting` after first turn** — `interactive: true` is now default. **Never stop the executor before reviewer verdict.** Keep it alive so you can resume with fix instructions if reviewer says PARTIAL. Executors auto-commit substantive changes on each turn via `auto_commit: checkpoint_on_waiting`. Only `sp stop` after reviewer PASS and commit verified on the branch.
768
- - **explorer** is READ_ONLY — output auto-appends to the input bead's notes. No implementation.
769
- - **reviewer** always gets its own bead: `--bead <review-bead> --job <exec-job> --context-depth 2`. The reviewer sees the executor's output via auto-appended bead notes + context-depth. Never use `--prompt`.
770
- - **debugger** over **explorer** when you need root cause analysis — GitNexus call-chain tracing, ranked hypotheses, evidence-backed remediation.
771
- - **overthinker** before **executor** for any non-trivial task — surfaces edge cases, challenges assumptions, produces solution direction. Cheap relative to wrong implementation.
772
- - **researcher** is the docs specialist — never look up library docs yourself, delegate to researcher.
773
- - **sync-docs** is interactive — always `--keep-alive`, use `resume` to approve/deny after audit.
774
-
775
- ### Example dispatches
866
+ When 34 failures collapsed under 5 clusters in one observed run, 56% of failures shared a single root cause. A blind parallel dispatch would have over-dispatched 19 fixes instead of 1. Net specialist spend ~3× higher without the mapping pass.
867
+
868
+ ### Failure modes to watch for
869
+
870
+ - Clusters that look shared but aren't same error string in unrelated tests may hide different root causes. Confirm via stack traces, not error text alone.
871
+ - One cluster's fix introduces another's regression — each chain's VALIDATION must span all known-failing areas with "no regressions in other clusters."
872
+ - Pre-existing failures vs new regressions name pre-existing failures explicitly in each chain's NON_GOALS so reviewers don't FAIL on them.
873
+
874
+ ## Canonical Single-Chain Flow
875
+
876
+ Use for one implementation branch.
776
877
 
777
878
  ```bash
778
- specialists run explorer --bead unitAI-exp --context-depth 2 --background
779
- specialists run researcher --bead unitAI-research --context-depth 2 --keep-alive --background
780
- specialists run debugger --bead unitAI-bug --context-depth 2 --background
781
- specialists run planner --bead unitAI-scope --context-depth 2 --background
782
- specialists run overthinker --bead unitAI-design --context-depth 2 --keep-alive --background
783
- specialists run executor --worktree --bead unitAI-impl --context-depth 2 --background
784
- specialists run reviewer --bead unitAI-rev --job <exec-job-id> --context-depth 2 --keep-alive --background
785
- specialists run sync-docs --bead unitAI-docs --context-depth 2 --keep-alive --background
786
- specialists run test-runner --bead unitAI-tests --context-depth 2 --background
787
- specialists run specialists-creator --bead unitAI-skill --context-depth 2 --background
879
+ # 1. Create or claim root task bead with complete contract
880
+ bd create --title "Fix token refresh retry" --type task --priority 2 --description "PROBLEM: login and refresh flow have a retry bug when transient token refresh fails before backoff clears stale state. SUCCESS: token refresh retries once, login survives transient failure, and terminal failure stays clear. SCOPE: src/auth/refresh.ts, src/cli/login.ts, tests/unit/auth/refresh.test.ts. NON_GOALS: no auth provider redesign, no storage migration, no UI changes. CONSTRAINTS: preserve token format, keep error text backward-compatible, avoid broad retry changes outside auth flow. VALIDATION: add regression test for fail-then-succeed path and run targeted auth tests. OUTPUT: changed files, test proof, residual risks."
881
+ bd update <task> --claim
882
+
883
+ # 2. Optional discovery when path is unknown — nested under task (bd-x.1) + typed edge for relationship semantics
884
+ bd create --parent <task> --title "explorer: map auth refresh path" --type task --priority 2 --description "PROBLEM: token refresh retry path is undocumented and likely drifts on failure handling. SUCCESS: evidence-backed plan names exact files, symbols, and risk. SCOPE: src/auth/refresh.ts, src/cli/login.ts, tests/unit/auth/*.test.ts. NON_GOALS: no implementation, no broad audit. CONSTRAINTS: READ_ONLY, cite files/symbols/flows, stay within live repo evidence. VALIDATION: findings cite code path and recommended sequence. OUTPUT: tracked discovery plan with stop condition."
885
+ bd dep add <explore> <task> --type discovered-from
886
+ specialists run explorer --bead <explore> --context-depth 3
887
+ specialists result <explore-job>
888
+
889
+ # 3. Implementation — nested under task (bd-x.2)
890
+ bd create --parent <task> --title "executor: implement token refresh retry" --type task --priority 2 --description "PROBLEM: login fails after transient token refresh error because retry path returns before backoff and clear error state. SUCCESS: retry waits once, preserves session on success, and surfaces final failure clearly. SCOPE: src/auth/refresh.ts, src/cli/login.ts, tests/unit/auth/refresh.test.ts. NON_GOALS: no auth redesign, no storage migration, no UI refresh. CONSTRAINTS: preserve existing token format, keep backward-compatible error text, avoid broad retry changes elsewhere. VALIDATION: add regression test for transient failure then success; run targeted auth tests. OUTPUT: changed files, test evidence, residual risks."
891
+ bd dep add <impl> <explore-or-task> --type blocks
892
+ specialists run executor --bead <impl> --context-depth 3
893
+ specialists result <exec-job>
894
+
895
+ # 4. Advisory passes when diff smells risky — nested under impl (bd-x.2.1, bd-x.2.2), since they service impl's diff specifically
896
+ bd create --parent <impl> --title "seconder: sanity check token retry diff" --type task --priority 2 --description "PROBLEM: auth retry diff has control-flow and state-handling smell that could hide bug. SUCCESS: findings identify concrete simplification or confirm clean shape. SCOPE: executor diff in auth refresh and login flow. NON_GOALS: no edits, no merge gate decision. CONSTRAINTS: READ_ONLY, keep feedback cheap, cite exact lines or symbols. VALIDATION: findings name concrete improvement or say OK. OUTPUT: FINDINGS with severity or OK with caveats."
897
+ bd dep add <sanity-bead> <impl> --type validates
898
+ specialists run seconder --bead <sanity-bead> --job <exec-job> --context-depth 3
899
+
900
+ bd create --parent <impl> --title "security-auditor: scan token retry diff" --type task --priority 2 --description "PROBLEM: auth refresh code touches secrets and session handling, so security regression is possible. SUCCESS: findings isolate real risk surface or confirm no obvious issue. SCOPE: executor diff in auth, token storage, and login path. NON_GOALS: no edits, no package updates, no destructive scans, no live exploit tests. CONSTRAINTS: LOW permissions, scan-only, recommendations only. VALIDATION: findings cite auth/secrets/input surface and why it matters. OUTPUT: recommendations for executor to apply in separate bead."
901
+ bd dep add <security-bead> <impl> --type validates
902
+ specialists run security-auditor --bead <security-bead> --job <exec-job> --context-depth 3
903
+
904
+ # 5. Final review — nested under impl (bd-x.2.3)
905
+ bd create --parent <impl> --title "reviewer: verify token refresh retry" --type task --priority 2 --description "PROBLEM: verify executor output against auth retry requirements. SUCCESS: PASS only if retry behavior, error handling, and tests satisfy contract. SCOPE: executor job, diff, acceptance criteria, and target auth files. NON_GOALS: do not rewrite unless explicitly asked. CONSTRAINTS: code-review mindset; findings first; verify security and sanity findings were handled. VALIDATION: inspect targeted checks and regression coverage. OUTPUT: PASS/PARTIAL/FAIL with file/line findings."
906
+ bd dep add <review> <impl> --type validates
907
+ specialists run reviewer --bead <review> --job <exec-job> --context-depth 3
908
+ specialists result <review-job>
909
+
910
+ # 6. Close any waiting keep-alive specialists explicitly
911
+ sp ps # confirm which jobs are still waiting
912
+ sp stop <waiting-job-id> # repeat per waiting job
913
+
914
+ # 7. Publish via manual git merge (rule #9 — sp merge is prohibited)
915
+ git checkout master
916
+ git pull --ff-only origin master
917
+ git merge --no-ff feature/<impl-bead>-<slug> -m "Merge <impl-bead>: <summary>"
918
+ git push origin master
919
+ git worktree remove <chain-worktree-path>
920
+ git branch -d feature/<impl-bead>-<slug>
921
+ bd close <task> --reason "Reviewer PASS; merged to master."
788
922
  ```
789
923
 
790
- ### Overthinker-first pattern for complex tasks
924
+ Edit-capable specialists with `--bead` auto-provision a clean git worktree. This does **not** provision ignored project dependency artifacts (`node_modules/`, `.venv/`, build caches). If validation tools are missing inside that worktree, have the specialist run the repo's standard bootstrap command (`make bootstrap`, `just setup`, `npm ci`, `uv sync`, etc.) or report that bootstrap is required; do not solve it by tracking dependency directories. `--worktree` is accepted for clarity but usually unnecessary. Use `--job <exec-job>` for reviewer/fix passes that must enter existing executor workspace.
925
+
926
+ What differs: orchestrator carries full bead contract inline, so downstream specialists inherit the actual job shape, not a title.
927
+
928
+ ## Multi-Chain Epic Flow
929
+
930
+ Use epic when multiple implementation chains publish together.
791
931
 
792
932
  ```bash
793
- # Full chain: task → explore → design → impl
794
- bd create --title "Redesign auth middleware" --type feature --priority 2 # -> unitAI-task
795
- bd create --title "Explore: map auth middleware" --type task --priority 2 # -> unitAI-exp
796
- bd dep add exp task
797
- bd create --title "Design: auth middleware approach" --type task --priority 2 # -> unitAI-design
798
- bd dep add design exp
799
- bd create --title "Implement: auth middleware redesign" --type task --priority 2 # -> unitAI-impl
800
- bd dep add impl design
801
-
802
- # Wave 1: Explorer
803
- specialists run explorer --bead unitAI-exp --context-depth 2 --background
804
- # (output auto-appends to exp notes)
805
-
806
- # Wave 2: Overthinker (sees exp findings via context-depth)
807
- specialists run overthinker --bead unitAI-design --context-depth 2 --keep-alive --background
808
- # enters waiting after Phase 4
809
-
810
- specialists resume <job-id> "What about the edge case where X?"
811
- specialists resume <job-id> "Is option B safer than option A here?"
812
- specialists stop <job-id> # when satisfied
813
- # (overthinker output is on unitAI-design notes)
814
-
815
- # Wave 3: Executor (sees design + exp + task via context-depth no manual wiring)
816
- specialists run executor --worktree --bead unitAI-impl --context-depth 2 --background
933
+ # Epic bead
934
+ bd create --title "Epic: auth refresh hardening" --type epic --priority 2 --description "PROBLEM: login and refresh flow have retry drift, weak error surfacing, and unclear follow-up ownership. SUCCESS: epic closes with stable retry behavior, tests, docs, and clean publish. SCOPE: src/auth/*, src/cli/login.ts, tests/unit/auth/*, docs/auth-refresh.md. NON_GOALS: no auth provider swap, no storage migration, no unrelated session revamp. CONSTRAINTS: preserve token format, keep login compatible, sequence risky fixes before merge, use child beads for parallelizable slices. VALIDATION: targeted tests, seconder or security pass if risk appears, final reviewer PASS. OUTPUT: merged chain set with notes on remaining gaps."
935
+
936
+ # Planner bead bd-epic.1
937
+ bd create --parent <epic> --title "planner: plan auth refresh split" --type task --priority 2 --description "PROBLEM: epic needs disjoint chains before executor starts. SUCCESS: child beads, dependency edges, and file ownership split are explicit. SCOPE: auth refresh epic area. NON_GOALS: no code changes. CONSTRAINTS: keep chains disjoint, identify security-sensitive slice, name review order. VALIDATION: plan names beads and edges. OUTPUT: parallel-ready plan with risk notes."
938
+ specialists run planner --bead <plan> --context-depth 3
939
+
940
+ # Parallel impl beads — bd-epic.2, bd-epic.3
941
+ bd create --parent <epic> --title "executor: impl auth retry" --type task --priority 2 --description "PROBLEM: transient refresh failure breaks login flow. SUCCESS: retry path succeeds after one transient failure and preserves session state. SCOPE: src/auth/refresh.ts, tests/unit/auth/refresh.test.ts. NON_GOALS: no UI changes, no storage migration, no unrelated retry framework edits. CONSTRAINTS: preserve error text, keep backoff bounded, avoid side effects outside auth flow. VALIDATION: regression test for fail-then-succeed path. OUTPUT: code diff, test proof, residual risk list."
942
+ bd create --parent <epic> --title "executor: impl login handoff" --type task --priority 2 --description "PROBLEM: login CLI does not surface refresh outcome clearly enough for operators. SUCCESS: login shows clear success/failure handoff and no stale token state. SCOPE: src/cli/login.ts, tests/unit/cli/login.test.ts. NON_GOALS: no auth protocol redesign. CONSTRAINTS: preserve CLI flags and error codes, keep output terse. VALIDATION: CLI regression test. OUTPUT: login diff and test evidence."
943
+
944
+ specialists run executor --bead <impl-a> --context-depth 3
945
+ specialists run executor --bead <impl-b> --context-depth 3
946
+
947
+ # Per-chain review nested under each impl (bd-epic.2.1, bd-epic.3.1)
948
+ bd create --parent <impl-a> --title "reviewer: verify auth retry" --type task --priority 2 --description "..."
949
+ bd create --parent <impl-b> --title "reviewer: verify login handoff" --type task --priority 2 --description "..."
950
+ bd dep add <review-a> <impl-a> --type validates
951
+ bd dep add <review-b> <impl-b> --type validates
952
+ specialists run reviewer --bead <review-a> --job <exec-a-job> --context-depth 3
953
+ specialists run reviewer --bead <review-b> --job <exec-b-job> --context-depth 3
954
+
955
+ # Close waiting keep-alive specialists explicitly (per chain)
956
+ sp ps # see what's still waiting
957
+ sp stop <waiting-job-id> # repeat per waiting job in each chain
958
+
959
+ # Publish via Cherry-Pick Playbook (canonical multi-chain merge — see Integration Phase section)
960
+ bd dep cycles # stop if relationship rewiring introduced a cycle
961
+ git checkout -b integration/$(date +%Y%m%d)-$EPIC_TAG
962
+ # For each PASS chain in dependency order:
963
+ git merge --squash feature/<chain-bead>-<slug>
964
+ git restore --staged .beads .pi AGENTS.md CLAUDE.md # noise filter
965
+ git commit -m "<type>(<scope>): <summary> (<bead-id>)"
966
+ # Operator FF-merges integration → master when satisfied.
817
967
  ```
818
968
 
819
- ### Monitoring with `sp ps` and `sp list --live`
969
+ Use `--epic <id>` when job belongs to epic but bead is not direct child. Avoid parallel executors on same file; sequence them or consolidate work.
820
970
 
821
- Use `specialists ps` (alias `sp ps`) for job monitoring instead of manual JSON polling:
971
+ What differs: orchestrator splits graph first, then launches parallel work only when file scopes are provably disjoint.
822
972
 
823
- ```bash
824
- # Quick overview — all jobs
825
- specialists ps
826
- # Output: ID, status, specialist, elapsed, bead, [ctx%] badge
827
-
828
- # Inspect specific job
829
- specialists ps <job-id>
830
- # Shows: full status, worktree path, chain, ctx% (context window utilization)
831
-
832
- # The ctx% in `sp feed` and `sp ps` shows context window utilization:
833
- # - 0-40% = OK (plenty of room)
834
- # - 40-65% = MONITOR
835
- # - 65-80% = WARN (▲ indicator shown)
836
- # - >80% = CRITICAL (▲ indicator shown)
973
+ ## Review And Fix Loop
974
+
975
+ A chain stays alive until merged or abandoned.
976
+
977
+ ```text
978
+ executor/debugger -> waiting
979
+ optional seconder/security-auditor -> advisory findings
980
+ reviewer -> PASS | PARTIAL | FAIL
837
981
  ```
838
982
 
839
- **Live tmux session selector (`sp list --live`):**
983
+ - `PASS`: verify expected commit/diff + clean Release Checklist. Close any waiting keep-alive jobs explicitly with `sp stop <job-id>`. Then publish via manual git workflow (per-chain `git merge --no-ff` or Cherry-Pick Playbook for multi-chain epics).
984
+ - `PARTIAL`: resume same executor/debugger with exact findings, then re-review (`sp resume <reviewer-job>`).
985
+ - `FAIL`: stop and decide whether to replace chain, re-scope bead, or ask operator if judgment is required. If replacing a bad chain with a narrower one, use `bd supersede <failed-impl> --with <replacement>`; if reviewer discovered separate follow-up work, use `bd dep add <follow-up> <reviewer-bead> --type discovered-from`.
986
+
987
+ Prefer resume over new fix executor when original job is waiting and context is healthy:
840
988
 
841
989
  ```bash
842
- # Interactive selector for running/waiting tmux sessions
843
- specialists list --live
844
- # Shows: tmux session name, specialist, elapsed, status
845
- # Arrow keys to select, Enter to attach
846
-
847
- # Include dead sessions (PID or tmux gone)
848
- specialists list --live --show-dead
849
- # Dead sessions shown with 'dead' status instead of filtered out
990
+ sp resume <exec-job> "Reviewer PARTIAL. Fix only these findings: ..."
850
991
  ```
851
992
 
852
- Dead job detection (`is_dead`) is computed at read time never persisted to avoid stale state. A job is dead when:
853
- - PID no longer exists (`kill -0 <pid>` fails)
854
- - tmux session gone (`tmux has-session -t <name>` fails or times out)
993
+ Do not treat job completion, seconder OK, security no-findings, or test-runner pass as equivalent to reviewer PASS.
855
994
 
856
- ---
995
+ What differs: orchestrator uses PASS/PARTIAL/FAIL as real control flow, not just status labels.
857
996
 
858
- ### Pi extensions and packages
997
+ ## Mini-Flows For Under-Promoted Specialists
859
998
 
860
- Pi extensions are global at `~/.pi/agent/extensions/`. Pi packages are global npm installs.
861
- Specialists run with `--no-extensions` and selectively re-enable:
999
+ Planner:
1000
+ - Use when epic needs bead split, dependency graph, or file ownership before code starts.
1001
+ - Bead shape: task/epic contract with clear success criteria, child beads, and edge plan.
1002
+ - Chain position: first or pre-impl.
862
1003
 
863
- - `quality-gates` — lint/typecheck enforcement (non-READ_ONLY only)
864
- - `service-skills` service catalog activation
865
- - `pi-gitnexus` call-chain tracing, blast radius analysis (resolved from global npm)
866
- - `pi-serena-tools` token-efficient LSP reads/edits (resolved from global npm)
1004
+ Debugger:
1005
+ - Use when symptom exists and root cause is unclear.
1006
+ - Bead shape: reproduction, logs, expected vs actual, scope to investigate.
1007
+ - Chain position: before executor, or after a failing review when cause is unclear.
867
1008
 
868
- When gitnexus tools are used during a run, the supervisor accumulates a `gitnexus_summary`
869
- in the `run_complete` event: `files_touched`, `symbols_analyzed`, `highest_risk`,
870
- `tool_invocations`.
1009
+ Overthinker:
1010
+ - Use for risky design, cross-cutting tradeoffs, or premortem before lock-in.
1011
+ - Bead shape: options, risks, constraint conflicts, decision asked for.
1012
+ - Chain position: before planner/executor when design uncertainty is high.
871
1013
 
872
- ---
1014
+ Researcher:
1015
+ - Dispatch **BEFORE** answering any library/API/framework/CLI question from training data. Training is months stale; APIs change; cheap CLI lookups (`ctx7`, `deepwiki`, `ghgrep`) replace the guess.
1016
+ - Use for: API syntax checks, config options, version migrations, library-specific debugging, "how do others implement X", recent releases, public repo internals.
1017
+ - Anti-pattern to break: "I think Library X works like Y…" → instead dispatch researcher with the exact question. The cost (~30s, `openai-codex/gpt-5.4-mini` via tool mode) is far less than shipping wrong API usage.
1018
+ - Bead shape: source list (which libraries/repos), question set, required citations (library ID or `npx ctx7 docs /org/project "..."` output).
1019
+ - Chain position: before executor when outside facts matter; alongside explorer when a question mixes local code with external behavior.
1020
+ - Keep-alive: ask follow-ups in the same job rather than re-dispatching — researcher stays in waiting state after each turn.
873
1021
 
874
- ## Steering and Resume
1022
+ Three modes researcher picks automatically based on bead shape; you write the bead, not the mode:
875
1023
 
876
- ### Steer redirect any running job
1024
+ - **Targeted lookup** (most common): "How do I configure X in library Y v1.2?" / "What does Z.method() return now?" / "Are foo and bar still the canonical replacements for baz?" → researcher resolves library ID via `ctx7 library`, then `ctx7 docs /org/project "<intent-rich query>"`. For repo-specific internals (e.g. "How does Vite handle X internally?"), `deepwiki ask <owner/repo> "..."`.
1025
+ - **Discovery**: "How do production codebases handle X?" / "Find good examples of pattern Y" / "What does the ecosystem do for Z?" → `ghgrep "<literal pattern>" --lang <langs> --repo <maybe>`, scan results, drill into the best repos with `deepwiki toc` + `deepwiki ask`.
1026
+ - **Media / discussion-recency** (rare): YouTube transcripts, social-media trends. Triggers on URLs or "what are people saying about X right now". Researcher loads `last30days` skill on-demand for this — don't fold its setup into the bead.
877
1027
 
878
- `steer` sends a message to a running specialist. Delivered after the current tool call
879
- finishes, before the next LLM call.
1028
+ ### Dispatch triggers when the orchestrator should reach for researcher
880
1029
 
881
- ```bash
882
- specialists steer a1b2c3 "STOP what you are doing. Focus only on supervisor.ts"
883
- specialists steer a1b2c3 "Do NOT audit. Write the actual file to disk now."
884
- ```
1030
+ Concrete agent thoughts that MUST be replaced with a researcher dispatch:
885
1031
 
886
- ### Resume continue a keep-alive session
1032
+ | Agent thought | Researcher bead |
1033
+ |---|---|
1034
+ | "I think `useEffect` cleanup works like…" | `ctx7 docs /facebook/react "useEffect cleanup with async operations"` |
1035
+ | "Next.js app router middleware should be…" | `ctx7 docs /vercel/next.js "app router middleware patterns"` |
1036
+ | "Let me check if `--target` is a valid flag for tool X" | `ctx7 docs /org/tool-x "--target flag"` or `tool-x --help` (orchestrator-side if it's installed) |
1037
+ | "Production code probably handles X by…" | `ghgrep "<X-pattern>" --lang TypeScript --limit 5` then `deepwiki ask <best-repo> "<design question>"` |
1038
+ | "Library Y added feature Z in v3 (I think)" | `ctx7 library <Y> "Z"` → `ctx7 docs /org/Y/<version> "Z"` to verify version + behavior |
1039
+ | "Repo X's authentication architecture is…" | `deepwiki ask owner/X "How does the auth middleware work? What stores tokens? What controls expiry?"` |
1040
+ | "Cross-library: do A and B compose like Z?" | `deepwiki ask repo-A repo-B "How do these interact for use-case Z?"` |
887
1041
 
888
- `resume` sends a new prompt to a specialist in `waiting` state. Retains full conversation history.
1042
+ If you catch yourself making any of these claims without first dispatching researcher, you are about to ship stale information. Stop and dispatch.
889
1043
 
890
- **Specialists that always use `--keep-alive`:**
1044
+ ### Cost framing
891
1045
 
892
- | Specialist | Enters `waiting` after | What to send via `resume` |
893
- |-----------|----------------------|--------------------------|
894
- | **executor** | First turn completion (may be partial if bailed early) | "proceed, this is additive", "Reviewer PARTIAL. Fix: <findings>", or "Reviewer PASS. Git add and commit your changes." |
895
- | **researcher** | Delivering research findings | Follow-up question, new angle, or "done, thanks" |
896
- | **reviewer** | Delivering verdict (PASS/PARTIAL/FAIL) | Your response, clarification, or "accepted, close out" |
897
- | **overthinker** | Phase 4 conclusion | Follow-up question, counter-argument, or "done, thanks" |
898
- | **debugger** | Phase 3 fix attempt or Phase 4 verify result | Follow-up fix, "try different approach", "Reviewer PASS. Git add and commit your changes.", or "done" |
899
- | **sync-docs** | Audit report or targeted update result | "approve", "deny", or specific instructions |
1046
+ Researcher runs on `openai-codex/gpt-5.4-mini` via tool mode, keep-alive. Typical turn: 20-40s wall clock, ~$0.005-0.02 per call. The cost of shipping a wrong API call (debugger turn + executor fix + reviewer re-run, or worse, production regression) is orders of magnitude higher. Default to dispatch.
900
1047
 
901
- > **Warning:** A job in `waiting` looks identical to a stalled job. **Always check with `sp ps`
902
- > before killing a keep-alive job.**
1048
+ ### What researcher does NOT do
903
1049
 
904
- > **Critical:** Never stop an executor or debugger before the reviewer delivers its verdict.
905
- > Stopping prematurely: (1) kills the resume path for fix loops, and (2) forces dispatching a
906
- > new specialist instead of resuming. Executors auto-commit substantive changes on each turn.
1050
+ - Local code mapping use `explorer` (READ_ONLY, traces project code without external CLI cost).
1051
+ - Bug root-cause when symptoms are local use `debugger`.
1052
+ - Reading internal docs already in this repo use direct file read or `explorer`.
1053
+ - Security audit of third-party packages → use `security-auditor`; researcher's job is the API surface, not the threat model.
907
1054
 
908
- ```bash
909
- # Check before stopping
910
- specialists ps d4e5f6
911
- # -> status: waiting ← healthy, expecting input
1055
+ Test-runner:
1056
+ - Use when commands need to run and failures need classification, not fixes.
1057
+ - Bead shape: exact command list, suites, and expected failure taxonomy.
1058
+ - Chain position: after executor or between fix loops.
912
1059
 
913
- specialists resume d4e5f6 "What about backward compatibility?"
914
- specialists stop d4e5f6 # only when truly done iterating after reviewer PASS + commit verified
915
- ```
1060
+ Sync-docs:
1061
+ - Use when one doc drifts and must be synced to source truth.
1062
+ - Bead shape: one-doc scope, source cross-check, drift checks.
1063
+ - Chain position: parallel to code only when doc scope is isolated; otherwise after code settles.
916
1064
 
917
- ---
1065
+ What differs: orchestrator uses specialists beyond the common trio, so planning, diagnosis, research, tests, and docs do not collapse into executor work.
918
1066
 
919
- ## Chain and Epic Orchestration
1067
+ ## Specialist Rebuttal As Routine
920
1068
 
921
- For multi-step work, dispatch chains under an **epic**.
1069
+ Several specialists default to over-cautious verdicts when an evidence gate looks unsatisfied. The orchestrator's job is to challenge that verdict with cited evidence, not to accept it. Common rebuttal-worthy patterns:
922
1070
 
923
- A **chain** is a worktree lineage (executor → reviewer → fix → re-review). Chains within the same epic may run in parallel **only if they are independent** (disjoint file scopes). Stages are strictly sequential: **never start Stage N+1 before Stage N completes AND is merged via `sp epic merge`**.
1071
+ ### Overthinker
924
1072
 
925
- ### Chain rules
1073
+ - "Hold for operator decision" without specifying what decision is needed → push: "Cite file/line evidence for why this is a product decision rather than a mechanical resolution."
1074
+ - "Close as superseded by X" without verification → push: "Read the current state of `<file>` and check whether feature Y from this bead is actually present." If verified, record it structurally with `bd supersede <old> --with <new>` instead of burying the replacement in notes.
1075
+ - "Run separate small beads" or "run one big bead" without rationale → push: "Pick one and explain operationally — cost difference, conflict expectations, reviewer scope." If one big bead wins, mark replaced split beads with `bd supersede`; if the small beads remain parallel siblings, link overlap with `bd dep relate`, not `blocks`.
926
1076
 
927
- 1. **Sequence between stages.** Prep (explorer/planner) → implementation chains → review → tests → doc sync.
928
- 2. **Parallelize only within a stage.** Chains that don't depend on each other may run together.
929
- 3. **Do not overlap stages.** Wait for every chain job, read results, update beads, merge epic.
930
- 4. **Bead deps encode the pipeline.** The dependency graph should match stage order.
931
- 5. **`--context-depth 2` for all chained runs.** Each specialist sees parent + predecessor.
932
- 6. **Merge via `sp epic merge` is mandatory.** See Merge Protocol above.
1077
+ ### Reviewer
933
1078
 
934
- ### Polling chains
1079
+ - "PARTIAL — missing `gitnexus_impact` evidence" on a test-only diff → rebut: "Diff is entirely under `test/` (N files). `gitnexus_impact` analyzes runtime call graphs; test fixture mocks have no callers in the production graph. Bead's impact-gate constraint is conditional on modifying a runtime entrypoint, which did not happen here."
1080
+ - "PARTIAL — missing `gitnexus_impact`" on a small LOW-blast-radius production diff where executor used `gitnexus_detect_changes` instead → rebut: cite the executor's `impact_report.highest_risk: LOW`, the LOC count, single helper / single consumer scope. The reviewer prompt accepts `gitnexus_impact` OR `$gitnexus_summary` OR `gitnexus_detect_changes` OR LOW `impact_report` as evidence.
1081
+ - "FAIL — full suite shows N+1 fails" where one is a known concurrent-run flake → rebut: rerun the suspect test in isolation, paste clean output, resume reviewer with "Isolated rerun: P/P. Re-evaluate."
935
1082
 
936
- ```bash
937
- specialists ps # list all jobs — shows epic grouping, status, elapsed
938
- specialists ps abc123 # inspect specific job (full detail)
939
- specialists ps --follow # live dashboard with epic grouping
940
- ```
1083
+ ### General rule
941
1084
 
942
- `sp ps` shows epic-level grouping:
1085
+ Resume with explicit ammunition: file/line refs, exact rerun output, link to the bead memory documenting the rebuttal pattern. Don't argue from authority; argue from new evidence. **Findings from seconder / security-auditor are legitimate rebuttal evidence** — a clean seconder OK or a security-auditor "no findings" is concrete proof against a reviewer's "looks too complex" or "may have security risk" gate. Cite the advisory job id when rebutting on this axis.
943
1086
 
1087
+ **One rebuttal per reviewer is the limit.** Second FAIL after rebuttal means stop and report. After a successful rebuttal, save the rebuttal text to `bd remember "<key>"` so the next session inherits it.
1088
+
1089
+ ## Monitoring And Steering
1090
+
1091
+ Use `sp ps` for state and `sp result` for completed turns.
1092
+
1093
+ ```bash
1094
+ sp ps # active jobs + unresolved terminal problems
1095
+ sp ps --active # active jobs only
1096
+ sp ps --health # include detailed process tables
1097
+ sp ps --include-terminal # include uncleaned terminal history
1098
+ sp ps --include-cleaned # include rows hidden by sp clean --ps
1099
+ sp ps --all # full audit view, including cleaned/dead/history
1100
+ sp feed <job-id>
1101
+ sp result <job-id>
944
1102
  ```
945
- ◆ epic:unitAI-3f7b · merge_ready · state:resolving · prep done=2/2 · chains pass=3/3
946
- prep:exp-1 · done
947
- prep:plan-2 · done
948
- chain:impl-a (reviewer PASS) · branch:feature/unitAI-impl-a-executor
949
- chain:impl-b (reviewer PASS) · branch:feature/unitAI-impl-b-executor
950
- chain:impl-c (reviewer PASS) · branch:feature/unitAI-impl-c-executor
951
- ```
952
1103
 
953
- A stage is complete when every chain is terminal AND you have:
954
- 1. Read results: `specialists result <job-id>` for each
955
- 2. Updated/closed beads as needed
956
- 3. Published via `sp epic merge <epic-id>`
1104
+ Default `sp ps` is the actionable dashboard, not raw history. Error/cancelled terminal rows stay visible until an operator acknowledges them with `sp clean --ps`; cleaned rows remain in SQLite and are visible via `--include-cleaned`/`--all`.
1105
+
1106
+ If job is running, use `sp feed`. If it is waiting, use `sp result` and decide whether to resume, review, merge, or stop. Avoid tight polling; sleep based on task size, then check once.
957
1107
 
958
- ### Canonical multi-stage example
1108
+ Use `steer` for running jobs and `resume` for waiting jobs:
959
1109
 
960
1110
  ```bash
961
- # 0. Create epic bead (top merge-gated identity)
962
- bd create --title "Add worktree isolation to executor" --type epic --priority 1
963
- # -> unitAI-3f7b
964
-
965
- # 1. Create prep and impl beads as children of the epic
966
- bd create --title "Explore: map job run architecture" --type task --priority 2 # -> unitAI-exp
967
- bd dep add exp 3f7b
968
- bd create --title "Implement: worktree isolation" --type task --priority 2 # -> unitAI-impl
969
- bd dep add impl exp
970
- # Note: reviewer gets own bead, enters via --job, inherits epic from bead.parent
971
-
972
- # Stage 1 — Explorer (prep job, declares epic explicitly)
973
- specialists run explorer --bead unitAI-exp --epic unitAI-3f7b --context-depth 2 --background
974
- # -> Job started: job1
975
- specialists result job1
976
-
977
- # [NO MERGE] Prep stage has no worktrees to merge
978
-
979
- # Stage 2 — Executor (chain inherits epic from bead.parent)
980
- specialists run executor --worktree --bead unitAI-impl --context-depth 2 --background
981
- # -> Job started: job2 (worktree: .worktrees/unitAI-impl/unitAI-impl-executor)
982
- # epic_id = bead.parent (unitAI-3f7b)
983
- specialists result job2
984
-
985
- # Stage 3 — Reviewer (own bead, uses --job for same worktree)
986
- bd create --title "Review: worktree isolation impl" --type task --priority 2 # -> unitAI-rev
987
- bd dep add rev impl
988
- specialists run reviewer --bead unitAI-rev --job job2 --context-depth 2 --keep-alive --background
989
- # -> Job started: job3
990
- specialists result job3
991
- # PASS → ready for epic merge. PARTIAL → fix loop.
992
-
993
- # Stage 4 — Fix loop (if PARTIAL)
994
- bd create --title "Fix: reviewer gaps on impl" --type bug --priority 1 # -> unitAI-fix1
995
- bd dep add fix1 impl
996
- specialists run executor --bead fix1 --job job2 --context-depth 2 --background
997
- # Re-review (new reviewer bead)
998
- bd create --title "Re-review: impl after fix" --type task --priority 2 # -> unitAI-rev2
999
- bd dep add rev2 impl
1000
- specialists run reviewer --bead unitAI-rev2 --job job2 --context-depth 2 --keep-alive --background
1001
-
1002
- # [MERGE] Publish epic
1003
- sp epic status unitAI-3f7b # verify readiness: merge_ready, all chains PASS
1004
- sp epic merge unitAI-3f7b --rebuild
1005
-
1006
- # Close
1007
- bd close 3f7b --reason "Worktree isolation implemented. Reviewer PASS. Epic merged."
1111
+ sp steer <job-id> "Stop broad audit. Answer only the three bead questions."
1112
+ sp resume <job-id> "Continue with the next scoped fix. Do not refactor."
1008
1113
  ```
1009
1114
 
1010
- ### Within-stage parallelism (multiple chains)
1115
+ Context usage is an action signal when available:
1116
+
1117
+ - 0-40%: healthy.
1118
+ - 40-65%: monitor.
1119
+ - 65-80%: steer toward conclusion.
1120
+ - Above 80%: finish, summarize, or replace job.
1121
+
1122
+ Raw token totals are not context percentages.
1123
+
1124
+ ### Long autonomous runs — dual-mechanism monitoring
1125
+
1126
+ For sessions where the operator is offline (overnight, async windows), use both:
1127
+
1128
+ 1. **Bash sleep timers per dispatch**, sized per role (see Monitoring Long-Running Jobs above). Bash sleep waits for an expected completion.
1129
+ 2. **External cron loop** (Claude Code: `/loop 180s sp ps`) as a heartbeat at fixed cadence regardless of orchestrator's bash sleeps. Cron catches specialists that finished while the orchestrator was busy reading other results, and catches stalls.
1130
+
1131
+ The two complement: bash sleep waits for an expected completion; cron catches unexpected completions and stalls. Without the cron, the orchestrator can miss specialists that completed during a long bash poll cycle and waste turns re-polling.
1132
+
1133
+ ## Bead Lifecycle And Parallel Commit Ordering
1134
+
1135
+ The bd commit-gate is **project-wide**, not per-worktree. While **any** bead in the project is `in_progress`, **no** worktree can commit. Practical consequences for parallel-chain epics:
1136
+
1137
+ - You CAN dispatch two executors in parallel — they work in separate worktrees, no commit-time collision.
1138
+ - But once executor A returns and executor B is still running, you CANNOT commit A's worktree until B's bead is closed (or vice versa).
1139
+ - Workflow: close the finished chain's executor bead FIRST (memory-ack + `bd close`), THEN commit that chain's worktree, THEN wait on the other chain.
1140
+ - This forces a serial-tail on the commit step. Plan for it: parallel-dispatch saves time on the *thinking* step, not the commit step.
1141
+
1142
+ If the commit-gate blocks unexpectedly mid-orchestration, `bd query "status=in_progress"` reveals which claim is holding it open.
1143
+
1144
+ ### Memory-gate batch close
1145
+
1146
+ `bd close` is blocked until `memory-acked:<id>` exists. For batch-closing many orchestrator-internal beads (sanity beads, reviewer beads, decomposition trackers), use:
1011
1147
 
1012
1148
  ```bash
1013
- # Parallel executors disjoint files, same parent epic
1014
- bd create --title "Implement: component A" --type task --priority 2 # -> unitAI-impl-a
1015
- bd dep add impl-a exp
1016
- bd create --title "Implement: component B" --type task --priority 2 # -> unitAI-impl-b
1017
- bd dep add impl-b exp
1018
-
1019
- specialists run executor --worktree --bead unitAI-impl-a --context-depth 2 --background
1020
- specialists run executor --worktree --bead unitAI-impl-b --context-depth 2 --background
1021
- # Each runs in its own worktree, both belong to unitAI-3f7b (via bead.parent)
1022
-
1023
- # Do NOT start next stage until BOTH complete AND epic is merged
1024
- sp epic merge unitAI-3f7b
1149
+ for id in <impl> <sanity?> <review>; do
1150
+ bd kv set "memory-acked:$id" "saved:<chain-memory-key>" # OR "nothing novel: <reason>"
1151
+ done
1152
+ bd close <impl> <sanity?> <review> <parent> --reason "..."
1025
1153
  ```
1026
1154
 
1027
- ---
1155
+ The chain memory key holds the actual durable insight (one per real fix). Sanity/review beads get "nothing novel" — the parent insight covers them.
1156
+
1157
+ ## What Stays Out
1158
+
1159
+ - `memory-processor` — memory synthesis specialist; see `/documenting`.
1160
+ - `xt-merge`: deferred to xt-merge skill; this skill names specialist flow, not merge-wrapper internals.
1161
+ - Session-close reporting (report skeleton, CHANGELOG sync, push) — see `/session-close-report` skill; this skill mandates running it at session end but does not duplicate its content.
1162
+ - Release publication (version bump, build, tag, npm publish) — see `/releasing` skill.
1163
+
1164
+ ## At Session End — Mandatory Handoff
1165
+
1166
+ Before declaring the session done:
1167
+
1168
+ 1. Run the `/session-close-report` skill.
1169
+ 2. Fill every `<!-- FILL -->` marker in the generated skeleton.
1170
+ 3. Sync `CHANGELOG.md` for user-facing changes (the report skill drives this).
1171
+ 4. Re-run cleanup checks: `sp ps`, `git worktree list`, `ps -ef` for stale serena/gitnexus, `tmux ls` for `sp-*`.
1172
+ 5. Commit the report (and CHANGELOG if updated) before push.
1173
+
1174
+ A session that lands code but skips the close-report leaves the next agent cold-starting blind. That cost compounds across sessions.
1175
+
1176
+ ## Adjacent xt commands
1177
+
1178
+ Source: latest xt report + `xt --help`; keep commands here, not full CLI surface.
1179
+ - `xt report` — session report input for release synthesis; see `/session-close-report`.
1180
+ - `xt end` — close worktree session: push, PR, merge, cleanup; see `/xt-end`.
1181
+ - `xt claude` — launch Claude in sandboxed worktree; see `/using-xtrm`. `xt claude --role <name>` has full parity with `xt pi --role` (same flags, same scaffold, same session-name shape).
1182
+ - `xt pi` — launch pi in sandboxed worktree. `xt pi --role <specialist>` spawns an interactive specialist session (chain-coordinator, pr-reviewer, sre-triage, deploy-monitor); full flag surface + monitoring pattern in `/multiplexing` Pattern 7.
1183
+ - `xt update` — refresh xtrm-managed files in one repo or many; see `/update-xt`.
1184
+ - `xt doctor` — diagnose xtrm drift in current project; see `/update-xt`.
1185
+ - `xt init` — bootstrap xtrm in project; see xtrm-tools docs.
1186
+ - `xt release prepare/publish` — legacy release path; canonical flow is `/releasing`.
1187
+ - `bd prime` — refresh beads workflow context; see `CLAUDE.md`.
1188
+ - `memory-processor` — memory synthesis specialist; see `/documenting`.
1189
+ - `xt-merge` — defer merge-queue internals to `/xt-merge`.
1190
+
1191
+ ## Merge And Publication (manual git is canonical)
1028
1192
 
1029
- ## Coordinator Responsibilities
1193
+ > **Rule #9:** `sp merge` and `sp epic merge` are prohibited — known broken, awaiting a separate rework epic. Even if `sp help` shows them, do not use. The Cherry-Pick Playbook below is the canonical merge path for specialist-owned work.
1030
1194
 
1031
- ### 1. Route work don't explore or implement yourself
1032
- Discovery goes to **explorer** first; implementation goes to **executor** only after discovery is done.
1195
+ ### Per-chain merge (standalone or one chain at a time inside an epic)
1196
+
1197
+ After reviewer PASS on a chain whose work lives in `feature/<bead-id>-<slug>` worktree:
1033
1198
 
1034
- ### 2. Validate combined output after each stage
1035
1199
  ```bash
1036
- npm run lint # project quality gate
1037
- npx tsc --noEmit # type check
1038
- git diff --stat # review what changed
1200
+ # 1. Verify reviewer PASS verdict was recorded (Release Checklist clean)
1201
+ bd show <bead-id> # check notes for the verdict
1202
+
1203
+ # 2. Verify the chain's gates passed:
1204
+ # seconder OK | obligations-scanner CLEAN | security-auditor clean (if surface)
1205
+ # Reviewer's Release Checklist block enumerates these.
1206
+
1207
+ # 3. Switch to target branch (master or integration/<date>) and FF or merge
1208
+ git checkout <target>
1209
+ git pull --ff-only origin <target>
1210
+ git merge --no-ff feature/<bead-id>-<slug> -m "Merge <bead-id>: <summary>"
1211
+ git push origin <target>
1212
+
1213
+ # 4. Cleanup the chain worktree + branch
1214
+ git worktree remove <chain-worktree-path>
1215
+ git branch -d feature/<bead-id>-<slug>
1216
+ git worktree prune
1039
1217
  ```
1040
1218
 
1041
- ### 3. Handle failures don't silently fall back
1219
+ Use `git update-ref` for FF-equivalent when checkout is blocked by transient working-tree state (e.g., bd auto-export churn on `.beads/issues.jsonl`):
1220
+
1042
1221
  ```bash
1043
- specialists feed <job-id> # see what happened
1044
- specialists doctor # check for systemic issues
1222
+ git merge-base --is-ancestor <target> feature/<bead-id>-<slug> && \
1223
+ git update-ref refs/heads/<target> feature/<bead-id>-<slug> && \
1224
+ git push origin <target>
1045
1225
  ```
1046
1226
 
1047
- Options when a specialist fails:
1048
- - **Steer**: `specialists steer <id> "Focus on X instead"`
1049
- - **Switch**: e.g. sync-docs stallstry executor
1050
- - **Stop and report** to the user before doing it yourself
1227
+ ### Multi-chain epic merge
1228
+
1229
+ Use the Cherry-Pick Playbook (below). Each chain lands as one squash commit on an integration branch (visible to operator before main), then operator FF-merges integrationmain when satisfied.
1051
1230
 
1052
- ### 4. Merge via epic (CRITICAL)
1053
- See Merge Protocol above. Use `sp epic merge <epic-id>` — no exceptions.
1231
+ ### Closing the keep-alive specialists
1232
+
1233
+ If reviewer/executor jobs are still `waiting` after PASS:
1054
1234
 
1055
- ### 5. Run drift detection after doc-heavy sessions
1056
1235
  ```bash
1057
- python3 .xtrm/skills/default/sync-docs/scripts/drift_detector.py scan --json
1058
- python3 .xtrm/skills/default/sync-docs/scripts/drift_detector.py update-sync <file>
1236
+ sp stop <waiting-job-id> # explicit close per job; verify with sp ps before
1059
1237
  ```
1060
1238
 
1061
- ---
1239
+ No automatic cascade-finalizer. Close each waiting job explicitly. (Yes, this is more ceremony than `sp finalize` provided — but `sp finalize` lived inside the broken sp merge path.)
1062
1240
 
1063
- ## MCP Tools (Claude Code)
1241
+ ### Rules
1064
1242
 
1065
- | Tool | Purpose |
1066
- |------|---------|
1067
- | `use_specialist` | Foreground run; pass `bead_id` for tracked work, get final output in conversation context |
1243
+ - Merge only after reviewer PASS + clean Release Checklist unless operator explicitly accepts a draft.
1244
+ - Always use `git merge --no-ff` for chain merges to keep the chain branch visible in history.
1245
+ - If merge reports a dirty worktree on the target branch, inspect what's dirty. Revert generated noise (e.g., `.beads/issues.jsonl` churn) only when clearly unrelated; otherwise ask the operator.
1246
+ - After merge, always remove the chain worktree + delete the branch + prune.
1247
+ - Stale-base failures: per Git State Precondition section, dispatch chains only when target branch HEAD contains all prior dependent chains' commits.
1068
1248
 
1069
- MCP is intentionally minimal. Use CLI for orchestration, monitoring, steering, resume, and cancellation.
1249
+ ## Integration Phase Cherry-Pick Playbook (canonical multi-chain merge)
1070
1250
 
1071
- ---
1251
+ The canonical path for landing multiple specialist chains. Operator gets visibility on an integration branch before the work hits main.
1072
1252
 
1073
- ## Known Issues
1253
+ ### Step-by-step
1074
1254
 
1075
- - **All specialist output auto-appends** to the input bead notes on every `run_complete` (via Supervisor). Status-aware headers: `[WAITING]` vs `[DONE]`. Output also available via `specialists result`.
1076
- - **`--prompt` is deprecated for tracked work.** Always use `--bead`. Update bead notes for additional instructions: `bd update <id> --notes "INSTRUCTION: ..."`
1077
- - **Job in `waiting` now shows magenta status** with resume hint in `status`, WAIT banner in `feed`, and resume footer in `result`. Always check before stopping a keep-alive job.
1078
- - **Explorer (qwen) may produce empty output** — the model sometimes completes tool calls but fails to emit a final text summary. The bead notes will be empty. If this happens, either re-run with a different model or do the investigation yourself.
1079
- - **`specialists init` requires xtrm** `.xtrm/` directory and `xt` CLI must exist. Use `--no-xtrm-check` to bypass in CI/testing.
1080
- - **`specialists doctor` now detects skill drift** compares `config/skills/` hashes against `.xtrm/skills/default/` and validates symlink chains.
1255
+ 1. Stash uncommitted state on working branch: `git stash push -u -m "pre-integration"`.
1256
+ 2. Create integration branch off the working branch: `git checkout -b integration/<date>-orchestrator`.
1257
+ 3. For each non-overlapping chain (security/critical first, then test-baseline, then features):
1258
+ - `git merge --squash <chain-branch>`
1259
+ - Restore noise files (see "Chain noise filter checklist" below)
1260
+ - **Advisory passes** before commit: if the staged diff smells overcomplicated/duplicative/type-risky, dispatch `seconder --job <last-exec-job-of-chain>`; if it touches auth/secrets/input/agent-config, dispatch `security-auditor --job <last-exec-job-of-chain>`. Link those beads with `bd dep add <advisory-bead> <chain-bead> --type validates`. Apply findings or document why skipped.
1261
+ - `git commit -m "<type>(<scope>): <summary> (<bead-id>)"` — one squash commit per chain.
1262
+ 4. For each overlapping chain, add `bd dep relate <overlap-a> <overlap-b>` if not already linked, then switch to the **debugger-restitch** pattern (next section).
1263
+ 5. Before publication, run `bd dep cycles`; fix any accidental cycle before operator FF-merges integration → main.
1264
+ 6. After all chains land, run E2E smoke phase (below) before declaring done.
1265
+ 7. Operator FF-merges integration → main when satisfied.
1081
1266
 
1082
- ---
1267
+ ### Chain noise filter checklist
1268
+
1269
+ For manual cherry-pick / squash flows, unstage these before committing (otherwise the chain commit will carry orchestrator-bookkeeping noise):
1083
1270
 
1084
- ## Troubleshooting
1271
+ - `.pi/npm` — accidentally created by xt commands inside worktrees
1272
+ - `cli/pnpm-lock.yaml`, `cli/pnpm-workspace.yaml` — pnpm side-effects
1273
+ - `AGENTS.md`, `CLAUDE.md` — gitnexus stat-refresh hook noise
1274
+ - `.beads/issues.jsonl`, `.beads/interactions.jsonl` — bd state churn
1275
+ - `.specialists/executor-result.md` — transient specialist output
1085
1276
 
1086
1277
  ```bash
1087
- specialists doctor # health check: hooks, MCP, zombie jobs, skill drift detection
1088
- specialists doctor orphans # integrity scan for orphan/stale-pointer/integrity-violation
1089
- specialists edit <name> # edit specialist config (dot-path, --preset)
1090
- specialists clean --processes # kill stale/zombie specialist processes
1278
+ git restore --staged .beads .pi AGENTS.md CLAUDE.md
1279
+ git checkout HEAD -- .beads AGENTS.md CLAUDE.md
1280
+ rm -f .pi/npm
1091
1281
  ```
1092
1282
 
1093
- ## Stuck-State Recovery
1283
+ If a chain commits its own `.beads` symlink (older bd-in-worktree behavior), `rm -f .beads` then `git checkout HEAD -- .beads` to restore the real directory.
1094
1284
 
1095
- Use this flow when epic/job state disagrees with live runtime or close path loops.
1285
+ ## Debugger-Restitch Pattern
1096
1286
 
1097
- ### 1) Reconcile epic state first (safe default)
1287
+ When chain X conflicts with already-landed chain Y on shared files, raw `git cherry-pick` will revert Y's work. The debugger-restitch pattern preserves both, but only when the debugger gets an explicit "preserve already-landed work" contract.
1098
1288
 
1099
- ```bash
1100
- sp epic status <epic-id>
1101
- sp epic sync <epic-id> # dry-run default, inspect planned fixes
1102
- sp epic sync <epic-id> --apply # apply reconciliation after review
1103
- ```
1289
+ 1. **Reopen X**: `bd reopen <X> --reason="integration stitch onto post-Y state"`. If the old X chain is no longer publishable, create a restitch bead and mark replacement explicitly: `bd supersede <X> --with <X-restitch>`. Link X and Y with `bd dep relate <X-restitch> <Y>` for conflict context; use `caused-by` only when a concrete failure bead is attributable to Y's already-landed change.
1290
+ 2. **Strengthen the bead contract** with these fields:
1291
+ - `## CRITICAL CONSTRAINTS:` heading at the top.
1292
+ - "Fork off `integration/<date>-orchestrator`. Verify with `git log integration/...$..HEAD` empty before any commits."
1293
+ - List the symbols/lines from Y that MUST be preserved verbatim (with file paths).
1294
+ - "ADD X's intent ON TOP" with a numbered list of the additions.
1295
+ - "Reference original `feature/<X>-executor` for symbol shapes only — do NOT cherry-pick or merge. Re-implement on integration's current state."
1296
+ - `## VALIDATION:` includes both Y's tests passing AND X's new tests passing.
1297
+ - `## OUTPUT:` mandates a 5-line code excerpt showing both Y and X features coexisting.
1298
+ 3. **Dispatch debugger** with `--force-stale-base` if X is an epic child:
1299
+ ```bash
1300
+ sp run debugger --bead <X> --force-stale-base --keep-alive
1301
+ ```
1302
+ 4. **Sanity check the result**: when debugger reports back:
1303
+ ```bash
1304
+ git log integration/<date>..feature/<X>-debugger --oneline
1305
+ git diff integration/<date>...feature/<X>-debugger -- <key-files>
1306
+ ```
1307
+ Confirm the debugger's diff is **additive** — no reverts of Y's lines.
1308
+ 5. **Advisory passes**: before landing the restitch, dispatch `seconder --job <debugger-job>` if the restitch added control-flow complexity, and `security-auditor --job <debugger-job>` if it touched a sensitive surface. Link each advisory bead back with `bd dep add <advisory> <X-restitch-or-X> --type validates`. Restitched diffs are higher-risk than fresh executor diffs because the debugger had to thread around already-landed work.
1309
+ 6. **Land via FF or cherry-pick the named commit** (NOT the checkpoint commit). Look for the commit with the proper `<type>(<scope>):` message; ignore `checkpoint(debugger):` commits above it.
1310
+ 7. **Verify tests** before marking done.
1104
1311
 
1105
- `sp epic sync` is primary recovery command. It reconciles DB state against live job/worktree state.
1312
+ ### Failure mode to watch for
1106
1313
 
1107
- ### 2) Terminally abandon unrecoverable epic
1314
+ If the debugger forks off the OLD baseline (pre-Y) instead of integration, its commit will revert Y. Symptom: `git diff integration..feature/<X>-debugger -- <Y's-file>` shows DELETIONS of Y's symbols. Fix: resume the debugger with explicit "cd to a fresh worktree forked from `integration/<date>-orchestrator`" instruction. Re-verify with `git log integration..HEAD` empty. If the bad restitch became a tracked bead, supersede it with the corrected restitch bead so nobody merges the obsolete chain.
1315
+
1316
+ ## E2E Smoke Phase
1317
+
1318
+ Run **every** npm script + entry point that any chain added or modified. The smoke phase is the only way to catch missed chains, false-positive CI gates, missing intermediate files, and runtime regressions invisible to unit tests.
1319
+
1320
+ ### Procedure
1108
1321
 
1109
1322
  ```bash
1110
- sp epic abandon <epic-id> --reason "stuck chain with unrecoverable state"
1111
- # If guard blocks due to active pointers you intentionally want cleared:
1112
- sp epic abandon <epic-id> --reason "manual recovery" --force
1323
+ # Build sanity
1324
+ bun run build # or equivalent
1325
+
1326
+ # Test sanity — record PRE-baseline first
1327
+ git checkout <baseline-branch>
1328
+ bun test 2>&1 | tail -5 # record N failed / M passed
1329
+
1330
+ # Switch back and re-run
1331
+ git checkout integration/<date>-orchestrator
1332
+ bun test 2>&1 | tail -5 # MUST be ≥ baseline. Net regression is a stop-the-line.
1333
+
1334
+ # Run every check:* script the integration added
1335
+ for s in $(jq -r '.scripts | keys[] | select(startswith("check:"))' package.json); do
1336
+ echo "=== $s ==="
1337
+ npm run "$s" 2>&1 | tail -10
1338
+ done
1339
+
1340
+ # Targeted unit tests for chains touching the same files
1341
+ bunx vitest run <chain-test-files>
1113
1342
  ```
1114
1343
 
1115
- Use only when epic cannot be restored to valid resolving/merge path.
1344
+ For each smoke that fails, decide before continuing:
1345
+ - False positive (script flags itself) → file follow-up bead, document, continue
1346
+ - Missing dependency (vendor not run) → expected gate, document
1347
+ - Real regression → stop, dispatch debugger to fix, re-smoke
1348
+
1349
+ ### Cross-cutting security-auditor pass
1116
1350
 
1117
- ### 3) Restore DB hygiene after recovery
1351
+ If any landed chain in this integration touched auth, secrets, input handling, dependency lockfiles, or agent/MCP/config surfaces, dispatch one `security-auditor` on the cumulative integration diff BEFORE declaring smoke done:
1118
1352
 
1119
1353
  ```bash
1120
- sp doctor orphans
1121
- sp db vacuum
1122
- sp db prune --before 30d --dry-run
1123
- sp db prune --before 30d --apply
1354
+ git diff <baseline>..integration/<date>-orchestrator > /tmp/integration-diff.patch
1355
+ sp run security-auditor --bead <sec-bead> --context-depth 3
1124
1356
  ```
1125
1357
 
1126
- - `sp db vacuum` compacts SQLite file, refuses while jobs running.
1127
- - `sp db prune` removes old rows from events/results/terminal jobs; dry-run first.
1358
+ Per-chain security-auditor passes catch chain-local risks; this cross-cutting pass catches interaction risks that only appear once all chains coexist (e.g. one chain weakens an input validator that another newly relies on). Skipping this on a sensitive-surface integration is an escalation event.
1359
+
1360
+ Record all smoke results in the session-close-report under a `## Smoke test results` table (see `/session-close-report` skill).
1361
+
1362
+ ## Failure Recovery
1128
1363
 
1129
- ### 4) Hard-stop wedged jobs when normal stop fails
1364
+ When something fails:
1130
1365
 
1131
1366
  ```bash
1132
- sp stop <job-id>
1133
- sp stop <job-id> --force
1367
+ sp ps <job-id>
1368
+ sp feed <job-id>
1369
+ sp result <job-id>
1370
+ sp doctor
1134
1371
  ```
1135
1372
 
1136
- `--force` waits 5s for SIGTERM, then kills process group and records explicit error status.
1137
-
1138
- ### 5) `sp end` open-state loop fix
1139
-
1140
- If `sp end` detects open-state mismatch, tool surfaces the derived readiness summary (`sp epic status <epic-id>`) and the per-chain merge path. There is no `sp epic resolve` anymore — readiness is recomputed live from chain state.
1141
-
1142
- - **RPC timeout on worktree job start** (30s, `command id=1`) → pi runs `npm install` in fresh
1143
- worktrees if `.pi/settings.json` lists local packages. Root cause: worktree gets a stale copy
1144
- of `.pi/settings.json` from the branch point. Fix: ensure `.pi/settings.json` has
1145
- `"packages": []` (packages are global now). `provisionWorktree()` also symlinks
1146
- `.pi/npm/node_modules` to the main repo's as a safety net.
1147
- - **RPC timeout on non-worktree job** → check for: (1) zombie vitest/tinypool processes
1148
- (`ps aux | grep vitest`, then `kill`), (2) stale dist (`npm run build`),
1149
- (3) model provider issues (try a different model to isolate).
1150
- - **"specialist not found"** `specialists list` (project-scope only)
1151
- - **Job hangs** `specialists steer <id> "finish up"` or `specialists stop <id>`
1152
- - **Config skipped** stderr shows `[specialists] skipping <file>: <reason>`
1153
- - **Stall timeout** specialist hit 120s inactivity. Check `specialists feed <id>`, then retry or switch.
1154
- - **Never use `--prompt`** use bead notes: `bd update <id> --notes "INSTRUCTION: ..."` then `--bead` only.
1155
- - **Worktree already exists** it will be reused (not recreated). Safe to re-run.
1156
- - **`--job` fails: worktree_path missing** target job was not started with `--worktree`. Use `--worktree` on the next run.
1157
- - **`--job` without `--bead`** reviewer/executor requires `--bead`. Create a reviewer bead first, then use `--bead <review-bead> --job <exec-job> --context-depth 2`.
1158
- - **Stale specialist processes** SessionStart hook warns about old binary versions. Run `specialists clean --processes` to kill them all.
1159
- - **`specialists init` fails with xtrm error** → xtrm must be installed first: `npm install -g xtrm-tools && xt install`. Use `--no-xtrm-check` in CI.
1160
- - **Skill drift detected by doctor** Run `specialists init --sync-skills` to re-sync canonical skills to `.xtrm/skills/default/` and refresh active symlinks.
1373
+ Then choose one action:
1374
+
1375
+ - Resume waiting executor/debugger with exact findings.
1376
+ - Re-run with better bead if contract was weak.
1377
+ - Re-scope bead if scope was wrong.
1378
+ - Escalate if human decision is needed.
1379
+ - Replace specialist only if failure mode repeats.
1380
+
1381
+ ### Common failure patterns (and the canonical fix)
1382
+
1383
+ | Symptom | Cause | Fix |
1384
+ |---|---|---|
1385
+ | `git checkout <branch>` aborts with "would overwrite untracked/changes" mid-orchestration | bd auto-export keeps re-staging `.beads/issues.jsonl` after every bd op | Use `git update-ref refs/heads/<target> <source>` for FF-equivalent without checkout; or commit the .beads churn as a separate "chore(beads): export state" commit before switching |
1386
+ | Stale `.git/index.lock` blocks git commands | bd hooks or other tooling crashed mid-operation | Check no real git process is running (`ps -ef \| grep "git "`); if clear, `rm -f .git/index.lock` and retry |
1387
+ | `git add .beads/issues.jsonl` says "ignored by gitignore" but `git status` shows it modified | File is in `.git/info/exclude` but already tracked in the index | The staged change can still be committed directly (`git commit` without `git add`); don't fight the exclude |
1388
+ | Validation fails with `command not found`, `vitest: not found`, missing Python tools, or `ERR_MODULE_NOT_FOUND` in a fresh worktree | Normal git worktree behavior: ignored dependency dirs (`node_modules/`, `.venv/`) are not copied into new worktrees | Run the repo's standard bootstrap inside that worktree (`make bootstrap`, `just setup`, `npm ci`, `uv sync`, etc.) or report bootstrap-required. Do not track dependency artifacts. |
1389
+ | `sp ps` shows old terminal jobs after a session | Default dashboard keeps unresolved terminal problems visible until acknowledged | `sp clean --ps --dry-run`, then `sp clean --ps` to soft-hide from default ps; use `sp ps --include-cleaned`/`--all` for audit history |
1390
+ | Reviewer keeps returning PARTIAL on functional contracts already met | Reviewer demanding tool-event evidence typically obsoleted after the gate relaxation, but if it persists check the executor's `gitnexus_detect_changes` ran and use the rebuttal pattern (see Specialist Rebuttal As Routine) | Rebut with cited evidence; second FAIL = escalate |
1391
+ | Multiple `sp run` background launches drop silently under shell parallelism | Known launch-ceremony race | Re-check `sp ps` after each dispatch and retry the missing one; serialize when reliability matters |
1392
+ | `sp run` returns `Warning: job started but ID not yet available` and nothing appears in `sp ps --bead <id>` after 30s | Dispatch was refused by epic guard or base-staleness check; stderr now surfaces the refusal reason (see `sp run --background` post-fix) | Read the surfaced reason; retry with `--force-stale-base` if intentional, or fix the bead/lineage |
1393
+ | `sp feed <job-id>` returns short tail with no tool events | Confirms DB-backed replay is active; if you see ≤10 lines on a real run, the DB is missing events for that job verify with raw SQL on observability.db | If DB truly lacks events: re-run job; if DB has events but feed truncates: file bug bead — should not happen on current build |
1394
+ | bd "database not found" or per-project Dolt server respawn | bd has spawned a per-project Dolt instead of routing to the shared server | `ps aux \| grep "<repo>/.beads/dolt" \| awk '{print $2}' \| xargs -r kill -9`; ensure `.beads/config.yaml` contains `dolt.shared-server: true`; `bd ready` should now route to `~/.beads/shared-server/` |
1395
+ | Dolt journal corruption (`possible data loss detected at offset N`) | bd-internal | Operator-only — do NOT auto-recover. Stop bd writes, snapshot `~/.beads/shared-server/dolt`, run `dolt fsck` (read-only) first. Operator decides on `--revive-journal-with-data-loss` after reviewing the warning |
1396
+
1397
+ ## What Orchestrator Does Differently Because Of This Skill
1398
+
1399
+ - Writes bead contract before dispatch.
1400
+ - Nests specialist-dispatch beads under the bead they service via `--parent`, regardless of whether that bead is an epic, a task, or already a nested child — never defaults to loose top-level beads.
1401
+ - Titles every specialist-dispatch bead `<specialist-role>: <task>` so `bd list`/`sp ps` are scannable by role at a glance.
1402
+ - Chooses edge type before creating chain.
1403
+ - Uses specialist role by job shape, not by habit.
1404
+ - Keeps fix loops alive with resume, not re-spawn.
1405
+ - Treats reviewer PASS as only publish gate.
1406
+ - Maps file-overlap surface BEFORE dispatching parallel waves.
1407
+ - Files one READ_ONLY test-failure-map bead before fix chains when ≥5 failures span subsystems.
1408
+ - Uses overthinker and reviewer as conversation, not one-shot oracles — rebuts with cited evidence once, then escalates.
1409
+ - Smokes every npm script and entry point before declaring integration done; runs cross-cutting security-auditor on cumulative diff when sensitive surfaces were touched.
1410
+ - Commits debugger-restitch results via FF or cherry-pick of the named commit, not the checkpoint commit above it.
1411
+ - Closes finished chain's bead BEFORE committing that worktree when other chains still in_progress (project-wide commit-gate).
1412
+ - Applies SCRUTINY field on every substantive bead; lets reviewer auto-escalate.
1413
+ - Verifies Git State Precondition before every dependent-chain dispatch.
1414
+ - Merges specialist work via manual git workflow (Cherry-Pick Playbook); never `sp merge` / `sp epic merge` (rule #9 — known broken).
1415
+ - Runs `/session-close-report` at session end and only then declares done.
1416
+ - Keeps memory-processor, xt-merge, session-close-report, and releasing out of this skill on purpose — each has its own.