immune-brain 4.6.0 → 5.1.0

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.
Files changed (75) hide show
  1. package/README.md +374 -46
  2. package/README.zh-CN.md +384 -47
  3. package/package.json +2 -1
  4. package/plugins/immune-brain/.claude-plugin/plugin.json +1 -1
  5. package/plugins/immune-brain/.pi-extension/imm-canary-enroll.ts +42 -44
  6. package/plugins/immune-brain/.pi-extension/imm-canary-work.ts +143 -474
  7. package/plugins/immune-brain/.pi-extension/imm-unattended-batch.ts +78 -87
  8. package/plugins/immune-brain/.pi-extension/pi-canary-assurance-progression.ts +7 -2
  9. package/plugins/immune-brain/.pi-extension/tsconfig.json +2 -2
  10. package/plugins/immune-brain/agents/immune-brain-advisory-reviewer.md +23 -0
  11. package/plugins/immune-brain/agents/immune-brain-qa.md +42 -0
  12. package/plugins/immune-brain/agents/immune-brain-reviewer.md +90 -1
  13. package/plugins/immune-brain/agents/immune-brain-ui-review.md +21 -0
  14. package/plugins/immune-brain/dist/BASELINE.md +4 -4
  15. package/plugins/immune-brain/dist/claude/mcp-server.mjs +8601 -6975
  16. package/plugins/immune-brain/dist/docs/reference/immune-brain-config.md +27 -0
  17. package/plugins/immune-brain/dist/docs/reference/planning-quality-gate.md +3 -3
  18. package/plugins/immune-brain/dist/docs/reference/subagent-dispatch-protocol.md +30 -1
  19. package/plugins/immune-brain/dist/imm-brainstorm.md +1 -1
  20. package/plugins/immune-brain/dist/imm-doc-prune.md +2 -2
  21. package/plugins/immune-brain/dist/{imm-agent-doc-maintain.md → imm-doc-slim.md} +9 -9
  22. package/plugins/immune-brain/dist/imm-planner.md +23 -8
  23. package/plugins/immune-brain/dist/imm-pr-fix.md +1 -1
  24. package/plugins/immune-brain/dist/{imm-review-retro.md → imm-retro.md} +26 -13
  25. package/plugins/immune-brain/dist/{imm-loop.md → imm-run.md} +231 -10
  26. package/plugins/immune-brain/dist/registry.yaml +9 -9
  27. package/plugins/immune-brain/dist/role-prompts/code-review.md +7 -0
  28. package/plugins/immune-brain/dist/role-prompts/executor.md +35 -2
  29. package/plugins/immune-brain/dist/role-prompts/lane-steward.md +44 -0
  30. package/plugins/immune-brain/runtime/assurance/coordinator.ts +83 -67
  31. package/plugins/immune-brain/runtime/assurance/host_port.ts +20 -0
  32. package/plugins/immune-brain/runtime/assurance/qa.ts +2 -2
  33. package/plugins/immune-brain/runtime/assurance/verdict_authority.ts +347 -0
  34. package/plugins/immune-brain/runtime/claude/interaction.ts +6 -0
  35. package/plugins/immune-brain/runtime/claude/kernel_ports.ts +78 -373
  36. package/plugins/immune-brain/runtime/claude/mcp_server.ts +26 -2
  37. package/plugins/immune-brain/runtime/claude/review_host.ts +48 -16
  38. package/plugins/immune-brain/runtime/claude/role_agents.ts +84 -0
  39. package/plugins/immune-brain/runtime/commands/kernel.ts +3 -6
  40. package/plugins/immune-brain/runtime/kernel/application.ts +6 -3
  41. package/plugins/immune-brain/runtime/kernel/assurance_projection.ts +15 -8
  42. package/plugins/immune-brain/runtime/kernel/canary_application.ts +5 -3
  43. package/plugins/immune-brain/runtime/kernel/enrollment.ts +149 -5
  44. package/plugins/immune-brain/runtime/kernel/index.ts +3 -1
  45. package/plugins/immune-brain/runtime/kernel/storage.ts +170 -11
  46. package/plugins/immune-brain/runtime/kernel/storage_paths.ts +13 -0
  47. package/plugins/immune-brain/runtime/local_initiative.ts +94 -0
  48. package/plugins/immune-brain/runtime/loop_contract.ts +77 -24
  49. package/plugins/immune-brain/runtime/plugin_version.ts +1 -1
  50. package/plugins/immune-brain/runtime/prompts/code-review.md +7 -0
  51. package/plugins/immune-brain/runtime/prompts/executor.md +35 -2
  52. package/plugins/immune-brain/runtime/prompts/lane-steward.md +44 -0
  53. package/plugins/immune-brain/runtime/role_prompt_bridge.ts +42 -2
  54. package/plugins/immune-brain/runtime/unattended/batch_git.ts +57 -27
  55. package/plugins/immune-brain/runtime/unattended/batch_integration.ts +387 -0
  56. package/plugins/immune-brain/runtime/unattended/batch_kernel_port.ts +106 -0
  57. package/plugins/immune-brain/runtime/unattended/batch_lanes.ts +909 -0
  58. package/plugins/immune-brain/runtime/unattended/batch_plan.ts +36 -11
  59. package/plugins/immune-brain/runtime/unattended/batch_preflight.ts +53 -36
  60. package/plugins/immune-brain/runtime/unattended/batch_reconfirmation.ts +34 -29
  61. package/plugins/immune-brain/runtime/unattended/batch_runner.ts +46 -91
  62. package/plugins/immune-brain/runtime/unattended/batch_schedule.ts +162 -0
  63. package/plugins/immune-brain/runtime/unattended/batch_state.ts +356 -8
  64. package/plugins/immune-brain/runtime/unattended/types.ts +21 -2
  65. package/plugins/immune-brain/runtime/workspace_scope.ts +34 -0
  66. package/plugins/immune-brain/skills/BASELINE.md +4 -4
  67. package/plugins/immune-brain/skills/imm-doc-prune/SKILL.md +1 -1
  68. package/plugins/immune-brain/skills/{imm-agent-doc-maintain → imm-doc-slim}/SKILL.md +9 -9
  69. package/plugins/immune-brain/skills/imm-planner/SKILL.md +4 -2
  70. package/plugins/immune-brain/skills/imm-pr-fix/SKILL.md +1 -1
  71. package/plugins/immune-brain/skills/{imm-review-retro → imm-retro}/SKILL.md +7 -7
  72. package/plugins/immune-brain/skills/{imm-review-retro → imm-retro}/scripts/review_retro.ts +46 -21
  73. package/plugins/immune-brain/skills/{imm-loop → imm-run}/SKILL.md +11 -7
  74. package/plugins/immune-brain/skills/registry.yaml +9 -9
  75. package/plugins/immune-brain/.pi-extension/runtime-stub.ts +0 -581
package/README.md CHANGED
@@ -11,10 +11,10 @@
11
11
  Immune-Brain brings a structured engineering workflow to AI coding assistants (**Pi** and **Claude Code**):
12
12
 
13
13
  - **Zero overhead for normal chat & coding** — Ordinary questions, quick edits, and exploratory chat stay 100% host-native. Immune-Brain never interrupts normal conversation.
14
- - **Explicit trigger when rigor matters** — When you want engineering discipline, invoke `imm-brainstorm`, `imm-planner`, or `imm-loop`.
14
+ - **Explicit trigger when rigor matters** — When you want engineering discipline, invoke `imm-brainstorm`, `imm-planner`, or `imm-run`.
15
15
  - **Plans become trackable tasks** (`TaskIntent` + `TaskRecord`) — Progress lives on disk (Git + `.imm/`), surviving restarts and context wipes.
16
16
  - **Quality is enforced by code, not promises** — Automated QA and isolated review subagents must pass before a task can complete.
17
- - **Ready Initiatives can run as a batch** — One confirmed batch authorization lets `imm-loop` work through a published Initiative's children serially, while every child is still enrolled, QA'd, reviewed, and settled on its own.
17
+ - **Ready Initiatives can run as a batch (serial or parallel lanes)** — One confirmed batch authorization lets the batch advance published children without manual handoffs per task; supports default serial progression or opt-in parallel lanes (Git worktree physical isolation, scope-disjoint scheduling, and integration verification guards), while every child is still enrolled, QA'd, reviewed, and settled on its own.
18
18
 
19
19
  Pi and Claude Code are the supported hosts. Undeclared adapters remain unsupported. Minimum Claude Code is `2.1.236`, the lowest version verified with interactive server-initiated MCP elicitation. Current real-Host evidence is recorded in [Claude native elicitation conformance](docs/verification/claude-native-elicitation-authority-conformance.md); historical reports remain under [docs/verification/archive/](docs/verification/archive/). Either host can use the model provider you configure — Immune-Brain works on top of Kernel authority, not a vendor chat.
20
20
 
@@ -25,6 +25,9 @@ Pi and Claude Code are the supported hosts. Undeclared adapters remain unsupport
25
25
  - [Installation](#installation)
26
26
  - [Quick Start](#quick-start)
27
27
  - [How to Use](#how-to-use)
28
+ - [Recommended Workflows: Composing with mattpocock/skills](#recommended-workflows-composing-with-mattpocockskills)
29
+ - [Real-World Case Studies](#real-world-case-studies)
30
+ - [Core Philosophy: Turn "Judgment" into "Table Lookup"](#core-philosophy-turn-judgment-into-table-lookup-harnessing-multi-model-tiers-with-determinism)
28
31
  - [The 7 Skills](#the-7-skills)
29
32
  - [Lifecycle](#lifecycle)
30
33
  - [Unattended Batch Runs](#unattended-batch-runs)
@@ -51,7 +54,7 @@ Pi discovers Skills and extensions from `package.json` (or your global Pi config
51
54
  }
52
55
  ```
53
56
 
54
- No extra server config is needed. Installing the package via Pi makes all 6 Skills available automatically.
57
+ No extra server config is needed. Installing the package via Pi makes all 7 Skills available automatically.
55
58
 
56
59
  ### In Claude Code
57
60
 
@@ -83,7 +86,7 @@ mise run check-dist-sync # verify generated docs are in sync
83
86
  Immune-Brain follows a **Skill-explicit** model: ordinary conversation is just standard, lightweight AI coding. The managed workflow activates **only when you explicitly invoke a skill**.
84
87
 
85
88
  **1. Call a skill when you need structured engineering**:
86
- - Fuzzy idea that needs scoping? Run `/imm-brainstorm` (or ask the agent to use `imm-brainstorm`).
89
+ - Fuzzy idea, ambiguous design, or high-stakes feature? Run `/grill-me` (from `mattpocock/skills`, recommended) for relentless Socratic design interrogation (or use built-in `/imm-brainstorm` for lightweight framing).
87
90
  - Ready to design and build? Run `/imm-planner` (or ask the agent to use `imm-planner`).
88
91
 
89
92
  *(Ordinary questions like "What does this function do?" or "Fix this typo" stay host-native — zero workflow ceremony.)*
@@ -95,8 +98,8 @@ Planner authors a `TaskIntent` and living Spec (scoped files, risk tier, accepta
95
98
 
96
99
  Review the scope and confirm enrollment. No code or authority writes happen before your explicit confirmation.
97
100
 
98
- **3. Run and verify with `imm-loop`**:
99
- Run `/imm-loop` (or say "Start imm-loop"). The engine will:
101
+ **3. Run and verify with `imm-run`**:
102
+ Run `/imm-run` (or say "Start imm-run"). The engine will:
100
103
  - Dispatch an Executor to write code strictly within the frozen scope.
101
104
  - Run deterministic QA acceptance checks.
102
105
  - Dispatch an isolated Review subagent for material/critical changes.
@@ -111,20 +114,20 @@ Immune-Brain provides two clean modes: **Host-native** for daily coding, and **M
111
114
  | Your situation | What to say / do | What happens |
112
115
  |---|---|---|
113
116
  | Daily coding, quick fix, general Q&A | Normal conversation ("Fix typo in README", "Explain this function") | **Host-native**: Standard Pi / Claude Code behavior. Zero workflow overhead. |
114
- | Fuzzy idea, needs scoping & risk analysis | `/imm-brainstorm` "Help me think through webhook support" | → `imm-brainstorm` frames requirements, constraints, and risks (read-only, no code edits) |
117
+ | Fuzzy idea, needs architectural stress-testing & scoping | `/grill-me` (recommended) or `/imm-brainstorm` | → `/grill-me` interviews you through the design tree to lock decisions; `/imm-brainstorm` provides built-in read-only problem framing |
115
118
  | Clear goal, want formal plan & specs | `/imm-planner` "Plan the webhook feature" | → `imm-planner` writes `TaskIntent` + Specs with testable acceptance checks |
116
- | Plan confirmed, ready to build & verify | `/imm-loop` | → Executor builds within scope → deterministic QA verifies → isolated Review checks → task settles |
117
- | Session interrupted or resuming a task | `/imm-loop` | → Resumes existing task seamlessly from on-disk state (`.imm/`) |
118
- | Ready Initiative to run unattended | "Run initiative `<slug>` unattended" | → Host's `start_unattended_batch`: one native confirmation covers ordered plan digest, children run serially |
119
- | Cross-host workflow (Claude plan + Pi code) | Run `/imm-planner` in Claude Code, switch to Pi and run `/imm-loop` | → Staged Spec & TaskIntent are shared on disk; Pi confirms via native TUI and executes loop |
119
+ | Plan confirmed, ready to build & verify | `/imm-run` | → Executor builds within scope → deterministic QA verifies → isolated Review checks → task settles |
120
+ | Session interrupted or resuming a task | `/imm-run` | → Resumes existing task seamlessly from on-disk state (`.imm/`) |
121
+ | Ready Initiative to run unattended (serial or parallel lanes) | "Run initiative `<slug>` unattended" (optionally with `--max-parallel 4` or `Lane max parallel`) | → Host's `start_unattended_batch`: one native confirmation binds the plan digest. Runs serially by default, or opt-in parallel Git worktree lanes with `max_parallel` |
122
+ | Cross-host workflow (Claude plan + Pi code) | Run `/imm-planner` in Claude Code, switch to Pi and run `/imm-run` | → Staged Spec & TaskIntent are shared on disk; Pi confirms via native TUI and executes loop |
120
123
  | PR has review comments or failing CI | `/imm-pr-fix` on that PR | → Standalone repair: minimal scoped fix in place, no managed task created |
121
124
  | Project docs out of date | `/imm-doc-prune` | → Read-only audit; deletes only user-approved stale docs from manifest |
122
- | Agent instructions bloated | `/imm-agent-doc-maintain` | → Minimizes tracked `AGENTS.md` / `CLAUDE.md` to essential non-discoverable rules |
123
- | Which model's edits keep coming back for review | `/imm-review-retro` | → Ranks models by review load and reports project usage from session logs |
125
+ | Agent instructions bloated | `/imm-doc-slim` | → Minimizes tracked `AGENTS.md` / `CLAUDE.md` to essential non-discoverable rules |
126
+ | Which model's edits keep coming back for review | `/imm-retro` | → Ranks models by review load and reports project usage from session logs |
124
127
 
125
128
  > **Core Principle: Skill-Explicit Entry**
126
129
  > - **Ordinary input stays host-native**: Natural language queries never automatically start planning or task enrollment. You choose when to turn on engineering rigor.
127
- > - **Managed work starts with explicit skills**: Use `imm-brainstorm` to clarify, `imm-planner` to plan, and `imm-loop` to execute and resume.
130
+ > - **Managed work starts with explicit skills**: Use `/grill-me` (or `imm-brainstorm`) to clarify decisions, `imm-planner` to plan, and `imm-run` to execute and resume.
128
131
 
129
132
  ### Cross-Host Workflow: Plan in Claude Code, Build in Pi
130
133
 
@@ -135,7 +138,7 @@ This enables a best-of-both-worlds workflow: **leverage Claude Code's deep reaso
135
138
  ```text
136
139
  ┌───────────────────────────────────┐ Git-Tracked Artifacts on Disk ┌───────────────────────────────────┐
137
140
  │ Claude Code │ ─────────────────────────────────> │ Pi │
138
- │ 1. /imm-brainstorm (Clarify) │ docs/specs/*.spec.md │ 1. /imm-loop (Native TUI Modal) │
141
+ │ 1. /imm-brainstorm (Clarify) │ docs/specs/*.spec.md │ 1. /imm-run (Native TUI Modal) │
139
142
  │ 2. /imm-planner (Spec/Intent) │ docs/plans/*.intent.json │ 2. Executor (Code) + QA Engine │
140
143
  └───────────────────────────────────┘ └───────────────────────────────────┘
141
144
  ```
@@ -150,7 +153,7 @@ This enables a best-of-both-worlds workflow: **leverage Claude Code's deep reaso
150
153
  - **Stage in Git**: Stage the generated artifacts (`git add docs/`). You can stop before Enrollment without executing.
151
154
  2. **Phase 2: Code Implementation & Execution in Pi**
152
155
  - **Launch Pi**: Open Pi in the same repository workspace.
153
- - **Enroll & run**: Enter `/imm-loop`. Pi discovers the staged `TaskIntent` and opens its native TUI modal confirmation for Enrollment.
156
+ - **Enroll & run**: Enter `/imm-run`. Pi discovers the staged `TaskIntent` and opens its native TUI modal confirmation for Enrollment.
154
157
  - **Automated loop**:
155
158
  - **Executor** writes implementation code strictly inside `scope_hint`.
156
159
  - **Deterministic QA engine** directly runs acceptance commands against exit codes.
@@ -158,7 +161,254 @@ This enables a best-of-both-worlds workflow: **leverage Claude Code's deep reaso
158
161
  - Upon pass, Kernel atomically settles terminal audit records in `.imm/audit/<task-id>/` and releases the workspace claim.
159
162
  3. **Why Cross-Host Switching Works Seamlessly**
160
163
  - **Session-neutral state**: All contracts and authority records live in the repository and local SQLite CAS, completely independent of any individual AI chat session.
161
- - **Bidirectional resumption**: Interrupted tasks can be resumed at any point in either Pi or Claude Code with `/imm-loop`.
164
+ - **Bidirectional resumption**: Interrupted tasks can be resumed at any point in either Pi or Claude Code with `/imm-run`.
165
+
166
+ ---
167
+
168
+ ## Recommended Workflows: Composing with mattpocock/skills
169
+
170
+ While Immune-Brain provides deterministic execution and quality enforcement once work begins, engineering failures frequently originate upstream: **models jump into code before the design tree is fully explored, trade-offs are evaluated, and edge cases are surfaced.**
171
+
172
+ To prevent premature implementation and scope churn, the recommended best-practice workflow combines **`mattpocock/skills`** (by Matt Pocock) upstream with **Immune-Brain** downstream:
173
+
174
+ > **The Dual-Engine Thesis**
175
+ > - **Upstream Socratic Friction (`grill-me`)**: Deliberately slows down thinking. The AI acts as a relentless interviewer, forcing explicit decisions on every branch of the design tree before any code or spec is committed.
176
+ > - **Downstream Deterministic Rigor (`imm-planner` + `imm-run`)**: Translates those decisions into tamper-proof machine contracts (`TaskIntent` + living Spec), enforces native human enrollment, freezes editable file boundaries, and verifies code via sandboxed child processes and isolated reviewer subagents.
177
+
178
+ ```text
179
+ ┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
180
+ │ 1. Upstream Socratic Alignment (mattpocock/skills /grill-me) │
181
+ │ Role: Relentlessly interview developer down every branch of the design tree; resolve trade-offs │
182
+ └───────────────────────────────────────────────────┬────────────────────────────────────────────────────┘
183
+ │ Settled decisions & architectural consensus
184
+ ▼
185
+ ┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
186
+ │ 2. Formal Machine Contracts (Immune-Brain /imm-planner) │
187
+ │ Role: Author living Spec & TaskIntent (.intent.json); lock scope_hint and VerificationDescriptor v2 │
188
+ └───────────────────────────────────────────────────┬────────────────────────────────────────────────────┘
189
+ │ Git-tracked contract artifacts
190
+ ▼
191
+ ┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
192
+ │ 3. Literal Human Authority Gate (Native Host Enrollment) │
193
+ │ Role: Developer confirms scope in native TUI / MCP dialog; Kernel captures baseline & acquires CAS lock │
194
+ └───────────────────────────────────────────────────┬────────────────────────────────────────────────────┘
195
+ │ Exclusive workspace lease
196
+ ▼
197
+ ┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
198
+ │ 4. Deterministic Assurance & Settlement (Immune-Brain /imm-run) │
199
+ │ Role: Scope-frozen Executor -> Sandboxed QA (bun test) -> Isolated Subagent Review -> CAS Settlement │
200
+ └────────────────────────────────────────────────────────────────────────────────────────────────────────┘
201
+ ```
202
+
203
+ ### Why Use `grill-me` Instead of `imm-brainstorm` for Decision Confirmation
204
+
205
+ Immune-Brain includes a built-in `imm-brainstorm` skill, but for non-trivial features, architectural pivots, and security-sensitive boundaries, **`/grill-me` is the recommended choice**:
206
+
207
+ | Dimension | Built-in `imm-brainstorm` | Upstream `/grill-me` (`mattpocock/skills`) | Recommended Synergy |
208
+ |---|---|---|---|
209
+ | **Ecosystem & Setup** | Built into Immune-Brain (zero install) | Ecosystem skill from `mattpocock/skills` (`npx skills@latest add mattpocock/skills --skill grill-me`) | Use `/grill-me` as the upstream decision partner; let Immune-Brain handle execution |
210
+ | **Interview Style** | Structured problem framing; batched questions; read-only summary | Relentless, iterative 1-by-1 Socratic grilling; explores every decision branch | `/grill-me` actively challenges developer assumptions and refuses to let ambiguities slide |
211
+ | **Exploration Discipline** | Explores codebase first, surfaces high-level goals & risks | Explores codebase first, proposes opinionated recommended answers for each branch | Eliminates "vibe coding" and locks down architectural consensus before any planning |
212
+ | **Output** | `brainstorm_framing` summary block | Fully resolved decision tree | Directly feed the settled decisions into `/imm-planner` |
213
+ | **Best Fit** | Lightweight scoping, offline setups, or simple tasks | Complex features, architectural refactors, and multi-service designs | **Recommended standard** for production engineering |
214
+
215
+ ### Setup & Installation
216
+
217
+ Install `grill-me` into your project or global agent environment using the official Skills installer:
218
+
219
+ ```bash
220
+ # Add grill-me from mattpocock/skills
221
+ npx skills@latest add mattpocock/skills --skill grill-me
222
+
223
+ # Or install the full suite
224
+ npx skills@latest add mattpocock/skills
225
+ ```
226
+
227
+ ### End-to-End Workflow: `grill-me` → `imm-planner` → `imm-run`
228
+
229
+ 1. **Step 1: Grill the Design (`/grill-me`)**
230
+ - Run `/grill-me "Add Webhook Dispatcher with retry and replay protection"`.
231
+ - The agent reads existing codebase patterns first, then interviews you across the decision tree (storage choices, idempotency strategy, backoff policies, failure modes), presenting a recommended answer for each step.
232
+ - Continue until all branches are resolved: *"Decision tree complete. Ready to plan."*
233
+ 2. **Step 2: Formalize the Plan (`/imm-planner`)**
234
+ - Run `/imm-planner "Plan the webhook dispatcher using the decisions settled in grill-me"`.
235
+ - `imm-planner` consumes the resolved choices and generates:
236
+ - **Living Spec** (`docs/specs/webhook-dispatcher.spec.md`): Pinned code coordinates, trade-offs, and negative boundaries.
237
+ - **TaskIntent** (`docs/plans/webhook-dispatcher.intent.json`): Strict `scope_hint`, risk tier (`material`), and machine-executable `VerificationDescriptor v2` checks.
238
+ 3. **Step 3: Confirm Enrollment (Native Host Gate)**
239
+ - Stage artifacts in Git (`git add docs/`).
240
+ - Run `/imm-run`. The native confirmation dialog opens (Pi TUI modal / Claude Code MCP elicitation).
241
+ - Once confirmed, Kernel atomically captures repository baseline state (`enrollment-baseline.json`) and acquires an exclusive SQLite CAS lock.
242
+ 4. **Step 4: Execute & Verify (`/imm-run`)**
243
+ - **Executor**: Edits code strictly within `scope_hint`. Physical scope escapes fail closed.
244
+ - **Deterministic QA**: Kernel executes acceptance tests (`bun test`) in a sandboxed child process, verifying authentic exit codes.
245
+ - **Isolated Review**: For `material` or `critical` tasks, a separate review subagent audits immutable Git blobs against Devil's Advocate invariants.
246
+ - **Settlement**: Kernel records tamper-proof attestations in `.imm/audit/<task-id>/` and releases the workspace lease.
247
+
248
+ ---
249
+
250
+ ## Real-World Case Studies
251
+
252
+ ### Case Study 1: Greenfield Feature Development — Multi-Tenant Webhook Dispatcher
253
+
254
+ - **Goal**: Implement a production-grade webhook dispatch system with HMAC signature verification, exponential backoff with jitter, and replay attack prevention.
255
+ - **Problem without this pipeline**: An AI agent typically starts writing files immediately, pulls in arbitrary dependencies, forgets timestamp replay bounds, leaks in-memory timers, and claims "implementation complete" without verifying HTTP timeout handling.
256
+ - **Workflow**:
257
+ 1. **Socratic Grilling (`/grill-me`)**:
258
+ - *Question 1 (Persistence)*: SQLite vs external queue? *Recommendation*: Store pending dispatches in the existing SQLite CAS table to avoid external infrastructure overhead.
259
+ - *Question 2 (Security)*: How to prevent replay attacks? *Recommendation*: Require an `X-Webhook-Timestamp` header with a 5-minute clock-skew tolerance window and HMAC-SHA256 signature.
260
+ - *Question 3 (Resilience)*: What is the backoff curve and timeout? *Recommendation*: Exponential backoff with full jitter up to 5 attempts, with a hard 10s timeout via `AbortController`.
261
+ - *Result*: All trade-offs explicitly confirmed in 3 minutes of dialogue.
262
+ 2. **Machine Contract Formulation (`/imm-planner`)**:
263
+ - Planner writes `docs/specs/webhook-dispatcher.spec.md` with explicit Negative Scope (files in `src/auth/` and `src/billing/` are forbidden).
264
+ - Generates `docs/plans/task-webhook-dispatcher.intent.json` with risk `material` and `VerificationDescriptor v2` running `bun test tests/webhook-dispatcher.test.ts`.
265
+ 3. **Native Gate Enrollment**:
266
+ - Developer inspects Git diff and confirms via Pi TUI dialog / Claude Code MCP elicitation.
267
+ 4. **Execution, QA & Review (`/imm-run`)**:
268
+ - Executor writes implementation strictly within `scope_hint`.
269
+ - Deterministic QA executes `bun test tests/webhook-dispatcher.test.ts`. Kernel verifies exit code `0`.
270
+ - Isolated Reviewer subagent inspects the Git blob `ReviewBundle`, confirming no out-of-scope edits and verifying error invariants.
271
+ - Kernel settles terminal proof into `.imm/audit/<task-id>/`.
272
+
273
+ ### Case Study 2: Critical Architectural Refactoring — CAS Storage Migration (v1 → v2)
274
+
275
+ - **Goal**: Migrate the persistence layer from legacy JSON files to an atomic SQLite CAS engine while maintaining zero-downtime rollback and legacy read-only audit inspection.
276
+ - **Problem without this pipeline**: Agents performing low-level database refactoring frequently introduce silent schema corruption, delete legacy fallback paths, and pass tests by weakening assertions.
277
+ - **Workflow**:
278
+ 1. **Socratic Grilling (`/grill-me`)**:
279
+ - *Interrogation*: "What happens to active v1 tasks during migration? Recommendation: Enforce a strict drain check (`drain_required`); refuse dual-write and abort if an active v1 task is in progress."
280
+ - *Interrogation*: "How is WAL corruption prevented during rollback? Recommendation: Use single-file transactions with OS-level file locking and immutable Git snapshots."
281
+ 2. **Planning with Enforcement Floors (`/imm-planner`)**:
282
+ - Because `runtime/kernel/storage.ts` is in `scope_hint`, Kernel automatically clamps the risk tier floor to `critical`.
283
+ - Planner pins code coordinates (`storage.ts:120`) and binds verification commands including legacy migration fixtures.
284
+ 3. **Native Enrollment**: Developer verifies the `critical` risk tier and baseline snapshot in the native host dialog.
285
+ 4. **Deterministic QA & Review (`/imm-run`)**:
286
+ - Real process verification runs the full regression test suite with authentic legacy fixtures.
287
+ - Isolated Subagent Devil's Advocate audit executes an adversarial review over immutable Git blobs, checking backward compatibility.
288
+ - Atomic settlement writes tamper-proof audit records.
289
+
290
+ ### Case Study 3: Cross-Host Collaborative Teamwork — Claude Code (Grill + Plan) + Pi (Run + QA)
291
+
292
+ - **Goal**: Maximize reasoning intelligence for architectural design while minimizing token expenditure and maximizing speed for mechanical code execution.
293
+ - **Workflow**:
294
+ 1. **Phase 1 in Claude Code (Desktop)**:
295
+ - Run `/grill-me` (from `mattpocock/skills`) to stress-test architecture with Claude's flagship reasoning model.
296
+ - Run `/imm-planner` to author line-pinned Living Specs and `TaskIntent` contracts.
297
+ - Stage artifacts (`git add docs/ && git commit -m "docs: webhook spec and plan"`).
298
+ 2. **Phase 2 in Pi (Terminal / Remote Server)**:
299
+ - Open Pi in the same repository workspace.
300
+ - Enter `/imm-run`. Pi detects the Git-staged `TaskIntent` and opens its native TUI modal for enrollment.
301
+ - Pi's Executor writes code using a cost-effective, high-throughput model (Fast/Mid Tier).
302
+ - Deterministic QA runs locally via `bun test`.
303
+ - Review passes and Kernel closes the task.
304
+ 3. **Result**: Zero context loss across hosts, full session-neutral state continuity, and ~60-70% savings on flagship reasoning tokens.
305
+
306
+ ---
307
+
308
+ ## Core Philosophy: Turn "Judgment" into "Table Lookup", Harnessing Multi-Model Tiers with Determinism
309
+
310
+ Large language models—especially lightweight, cost-effective Fast Tier models—fail in real-world software engineering not because of syntax, but because of **semantic ambiguity, scope creep, and evasive verification**.
311
+
312
+ Immune-Brain's foundational thesis is: **Never ask weak models to make architectural design decisions; turn them into deterministic table-lookup executors. Enforce all critical gates, verification, and reviews via code-level invariants and flagship models.**
313
+
314
+ ```text
315
+ ┌────────────────────────────────────────────────────────────────────────────────────────┐
316
+ │ 1. Architecture Exploration (Brainstorm) & 2. Plan Authoring (Planner) │
317
+ │ Host: Claude Code | Model: Flagship Reasoning Model (Strong Tier) │
318
+ │ Role: Clarify constraints, distill "judgment" into line-pinned Living Specs & intents │
319
+ └───────────────────────────────────────────┬────────────────────────────────────────────┘
320
+ │ Git-Tracked Shared Artifacts (docs/specs, docs/plans)
321
+ ▼
322
+ ┌────────────────────────────────────────────────────────────────────────────────────────┐
323
+ │ 3. Implementation (Executor) │
324
+ │ Host: Pi | Model: High-Throughput / Cost-Effective Model (Fast / Mid Tier) │
325
+ │ Role: Follow the recipe inside a frozen Scope envelope, mirroring established patterns │
326
+ └───────────────────────────────────────────┬────────────────────────────────────────────┘
327
+ │ Local code changes & state delivery
328
+ ▼
329
+ ┌────────────────────────────────────────────────────────────────────────────────────────┐
330
+ │ 4. Deterministic QA (Verification) │
331
+ │ Host: Pi / Kernel Native │
332
+ │ Role: Zero-LLM involvement; natively runs Verification Descriptor v2 commands (Pass/Fail)│
333
+ └───────────────────────────────────────────┬────────────────────────────────────────────┘
334
+ │ Triggered only after live tests pass
335
+ ▼
336
+ ┌────────────────────────────────────────────────────────────────────────────────────────┐
337
+ │ 5. Isolated Code Review │
338
+ │ Host: Pi Subagent | Model: High-Intelligence Reviewer Model (Strong Tier) │
339
+ │ Role: Audits immutable Git blob ReviewBundles against Devil's Advocate red lines │
340
+ └────────────────────────────────────────────────────────────────────────────────────────┘
341
+ ```
342
+
343
+ ### 1. Turn "Judgment" into "Table Lookup": Eliminate Ambiguity for Weak Models
344
+
345
+ The most effective constraint for cost-effective models is eliminating all room for ambiguity at the Spec stage:
346
+
347
+ - **Coordinate-Level Pinning**: Specs pin exact existing code patterns (e.g., `kernel.ts:1219`), instructing the model to *"mirror this exact shape"*.
348
+ - **Zero-Freedom Machine Contracts**: Error messages, status codes, and error exceptions must mirror existing conventions exactly (e.g., re-using `throw new VerificationDescriptorError(...)` with only command names swapped), leaving no leeway for ad-hoc abstraction.
349
+ - **Explicit Negative Scope (Exclusion List)**: The Scope section mandates clear negative boundaries (which directories must never be touched, which receipt paths cannot be re-used). Weak models need zero architecture guessing—they simply follow the recipe.
350
+
351
+ ### 2. "Done" Is Executable, Not Prose Promises
352
+
353
+ Textual declarations ("I have implemented this and all tests pass") are the primary vector for hallucinations. Immune-Brain enforces execution by code:
354
+
355
+ - **Verification Descriptor v2 Machine Contracts**:
356
+ Every Acceptance Criterion (AC) in a `TaskIntent` is bound to a strict machine descriptor (`assurance_kernel/verification_descriptor/v2`):
357
+ ```json
358
+ {
359
+ "contract": "assurance_kernel/verification_descriptor/v2",
360
+ "command": {
361
+ "executable": "bun",
362
+ "argv": ["test", "tests/kernel-migrate-to-vnext.test.ts"],
363
+ "cwd": ".",
364
+ "timeout_ms": 30000,
365
+ "max_output_bytes": 262144
366
+ },
367
+ "environment": { "prepare": null, "writable_paths": [] }
368
+ }
369
+ ```
370
+ Kernel executes verification commands in sandboxed child processes, validating authentic exit codes, stdout, and execution timeouts.
371
+ - **Physical Scope Freezing**:
372
+ At Enrollment, Kernel captures baseline Git snapshots (`captureGitWorkspaceSnapshot`). If dirty files exist prior to enrollment, or if Executor touches files outside `scope_hint` (`assertNoEnvelopeEscape`), Kernel fails-closed and blocks execution.
373
+ - **Mandatory QA and Isolated Review Subagents**:
374
+ Local CLI verification runs deterministically. For `material` and `critical` tasks, isolated Reviewer subagents are code-enforced gates that prevent drift.
375
+
376
+ ### 3. Devil's Advocate Audit: Closing the Shortcut Loopholes
377
+
378
+ Under optimization pressure, models naturally take paths of least resistance. Immune-Brain installs structural defenses:
379
+
380
+ - **Preventing Verification Vanity**:
381
+ Devil's Advocate audits explicitly rule that *"`--check` passing does not equal execution success"*. Dry runs or typechecks cannot substitute for test assertions.
382
+ - **Preventing Spec Dilution**:
383
+ Models are barred from silently pruning hard requirements or fabricating fake compatibility layers (e.g., *"never fabricate v1→v2 migration logic without authentic v1 test fixtures"*).
384
+ - **Deterministic Risk-Tier Floor**:
385
+ Models cannot weaken scrutiny by self-grading a task as `routine`. In `kernel/intent.ts`, the Kernel enforces a strict floor:
386
+ > Touching `kernel/`, `assurance/`, `claude/`, or `.pi-extension` automatically clamps the risk tier to at least `material`, regardless of author claims, physically forcing isolated subagent review.
387
+ - **Objective Refutation via Counterevidence**:
388
+ Subjective Reviewer hallucinations cannot hold up delivery. If a Reviewer claims an acceptance failure, but fresh deterministic QA evidence exists for the current `diff_hash` and `intent_hash`, Kernel marks the finding as `refuted` and allows settlement; once edits dirty the diff, the finding re-blocks automatically.
389
+
390
+ ### 4. Token Economics and Cost Levers: Without Levers, Costs Compound
391
+
392
+ Without explicit cost levers, multi-agent workflows compound expenses exponentially:
393
+
394
+ - **Plan First, Implement Second ("Measure Twice, Cut Once")**:
395
+ A tight, line-pinned spec costs a fraction of the tokens wasted on wrong directions and circular debugging.
396
+ - **Scope Freezing Eliminates Token Sinks**:
397
+ Barring unprompted refactorings and whole-project restyling prevents explosive diff expansion and token burn.
398
+ - **Model Tier Pipeline (`subagent-model-tier-pipeline`)**:
399
+ - **Fast Tier** (e.g., Flash / 4o-mini): High-throughput, zero-decision mechanical implementation and focused test fixes.
400
+ - **Mid Tier**: Reliability reviews (`reliability-reviewer`) and standard code auditing.
401
+ - **Strong Tier** (e.g., Sonnet / Opus): Strategic planning, architecture formulation, and high-risk security audits (`security-reviewer`).
402
+
403
+ ### 5. Multi-Tool & Multi-Model Workflow Pipeline
404
+
405
+ | Phase | Host / Tool | Recommended Tier | Responsibility & Guarantees |
406
+ |---|---|---|---|
407
+ | **1. Brainstorming** | Claude Code (`/imm-brainstorm`) | **Strong Tier** | Long-context dialogue, uncovering latent constraints and pruning pseudo-requirements. |
408
+ | **2. Planning** | Claude Code (`/imm-planner`) | **Strong Tier** | Line-pinned Living Specs, `VerificationDescriptor` bindings, and Devil's Advocate audits. |
409
+ | **3. Implementation** | Pi (`imm-run`) | **Fast / Mid Tier** | Native modal enrollment, mechanical coding within frozen scopes, adhering to YAGNI gates. |
410
+ | **4. Verification** | Local Process / Kernel Native | **Zero LLM (Native)** | Deterministic test execution (`bun test`), producing tamper-proof test attestations. |
411
+ | **5. Code Review** | Pi Subagent (`immune-brain-reviewer`) | **Strong Tier** | Adversarial review over immutable Git blob `ReviewBundle`s before final Kernel settlement. |
162
412
 
163
413
  ---
164
414
 
@@ -168,15 +418,15 @@ This enables a best-of-both-worlds workflow: **leverage Claude Code's deep reaso
168
418
  |---|---|---|---|
169
419
  | `imm-brainstorm` | Managed entry | Requirements are ambiguous | Frames the problem, surfaces open questions, no code edits |
170
420
  | `imm-planner` | Managed entry | Goal is clear | Authors / revises `TaskIntent` and specs; does not enroll or build |
171
- | `imm-loop` | Managed coordinator | Plan is validated | Drives execution → QA → Review → completion via foreground tools |
421
+ | `imm-run` | Managed coordinator | Plan is validated | Drives execution → QA → Review → completion via foreground tools |
172
422
  | `imm-pr-fix` | Standalone | CI failed / review comments on a PR | Repairs one PR in place, no managed authority |
173
423
  | `imm-doc-prune` | Standalone | Stale current docs | Deletes only the hash-approved manifest entries |
174
- | `imm-agent-doc-maintain` | Standalone | Bloated agent instructions | Minimizes tracked AGENTS/CLAUDE/GEMINI.md to necessary context |
175
- | `imm-review-retro` | Standalone | Compare models by review load | Ranks authors of reviewed code and reports project usage |
424
+ | `imm-doc-slim` | Standalone | Bloated agent instructions | Minimizes tracked AGENTS/CLAUDE/GEMINI.md to necessary context |
425
+ | `imm-retro` | Standalone | Compare models by review load | Ranks authors of reviewed code and reports project usage |
176
426
 
177
- Internal roles (Executor, QA, Review, Compounder) are dispatched by `imm-loop` — you never invoke them directly.
427
+ Internal roles (Executor, QA, Review, Compounder) are dispatched by `imm-run` — you never invoke them directly.
178
428
 
179
- All 7 skills are invoked explicitly. For new features, start with `imm-brainstorm` (if requirements are uncertain) or `imm-planner` (if requirements are clear), then proceed to `imm-loop` once enrolled.
429
+ All 7 skills are invoked explicitly. For new features, start with `imm-brainstorm` (if requirements are uncertain) or `imm-planner` (if requirements are clear), then proceed to `imm-run` once enrolled.
180
430
 
181
431
  ### Managed Path entries (brainstorm → planner → loop)
182
432
 
@@ -196,9 +446,9 @@ The three Managed skills form one continuous pipeline with a single authority mo
196
446
  - **What it never does:** implements code, overwrites an enrolled TaskIntent without a revision flow, or grants execution authority — only the native Enrollment gate can.
197
447
  - **Exit:** Git-tracked `TaskIntent` awaiting enrollment confirmation.
198
448
 
199
- #### `imm-loop` — managed execution & assurance
449
+ #### `imm-run` — managed execution & assurance
200
450
 
201
- - **Trigger:** explicit `/imm-loop` (start, resume, or check a managed task).
451
+ - **Trigger:** explicit `/imm-run` (start, resume, or check a managed task).
202
452
  - **What it does:** drives one task end to end through foreground tools — Executor edits inside the frozen scope, deterministic QA executes every acceptance descriptor, an isolated Review subagent audits material/critical tasks, and the Kernel settles terminal evidence. Interrupted workflows resume from on-disk state; the Kernel projection is authoritative.
203
453
  - **What it never does:** skips or weakens a failing check, runs without your Enrollment/revision/authorization gates, or continues after lineage or authority drift — it fails closed.
204
454
  - **Finding evidence:** every Review finding carries machine-checkable provenance (`trigger`, `caller_chain`, `violated`). A claim that fresh passing QA evidence already contradicts is recorded as `refuted` and only blocks again if that evidence goes stale.
@@ -219,12 +469,12 @@ The three repair/maintenance skills are host-native: they never create a managed
219
469
  - **Trigger:** explicit request to prune stale current documentation.
220
470
  - **What it does:** audits documentation staleness read-only, then deletes only entries you approved in an exact hash-bound manifest, with immediate revalidation after each mutation.
221
471
 
222
- #### `imm-agent-doc-maintain` — agent instruction minimization
472
+ #### `imm-doc-slim` — agent instruction minimization
223
473
 
224
474
  - **Trigger:** explicit request to minimize tracked `AGENTS.md` / `CLAUDE.md` / `GEMINI.md`.
225
475
  - **What it does:** keeps only the necessary non-discoverable rules in agent instruction files, under the same read-only-audit + hash-bound-manifest-approval model as `imm-doc-prune`.
226
476
 
227
- #### `imm-review-retro` — review load and project usage
477
+ #### `imm-retro` — review load and project usage
228
478
 
229
479
  - **Trigger:** explicit request for a cross-model review retro or project usage look-back.
230
480
  - **What it does:** ranks models by how much review their own edits triggered, plus sessions/turns/edits/tool mix, from pi session logs. Read-only. Not a diff review.
@@ -245,7 +495,7 @@ flowchart TD
245
495
  EG -->|Confirm| KS[(".imm/state/kernel.sqlite<br/>Atomic TaskRecord<br/>Exclusive Workspace Claim")]
246
496
  end
247
497
 
248
- subgraph Loop ["3. Execution & Assurance Loop (imm-loop)"]
498
+ subgraph Loop ["3. Execution & Assurance Loop (imm-run)"]
249
499
  KS --> EX["Executor Role<br/>Edit code strictly inside scope_hint"]
250
500
  EX --> FRZ["advance_assurance<br/>Artifacts frozen (active:frozen)"]
251
501
  FRZ --> QA["Deterministic QA Engine<br/>Run acceptance verification commands<br/>Generate QA Attestation"]
@@ -268,25 +518,28 @@ flowchart TD
268
518
  end
269
519
  ```
270
520
 
271
- ### Core Logic: Three Pillars
521
+ ### Core Architecture & Deterministic Guarantees
272
522
 
273
523
  1. **Two Paths**
274
524
  - **Host-native Path**: Daily conversation, code inspections, and ad-hoc fixes stay 100% native with zero workflow overhead.
275
- - **Managed Path**: Explicitly entered via `imm-brainstorm`, `imm-planner`, or `imm-loop`, strictly governed by the Assurance Kernel.
525
+ - **Managed Path**: Explicitly entered via `imm-brainstorm`, `imm-planner`, or `imm-run`, strictly governed by the Assurance Kernel.
276
526
 
277
527
  2. **Authority & Contract**
278
- - **TaskIntent (`.intent.json`)**: Machine-readable behavioral contract locking `scope_hint` (file boundaries), `risk` tier, and `acceptance` descriptors.
528
+ - **TaskIntent (`.intent.json`)**: Machine-readable behavioral contract locking `scope_hint` (file boundaries), `risk` tier, and deterministic `acceptance` descriptors (Verification Descriptor v2).
279
529
  - **Native Gate (Enrollment)**: The single human-authority confirmation gate; Kernel atomically acquires exclusive workspace ownership (`.imm/state/kernel.sqlite` CAS) to prevent concurrency conflicts and scope drift.
530
+ - **Physical Git Baseline Snapshot**: Enrollment captures repository HEAD and dirty files (`enrollment-baseline.json`); any physical envelope escape (`assertNoEnvelopeEscape`) immediately halts execution.
280
531
 
281
- 3. **Deterministic Assurance**
282
- - **QA-First**: The Kernel directly runs verification commands and checks exit codes/byte bounds; never relies on conversational claims.
283
- - **Risk-Tiered Gates**: `routine` tasks complete upon QA pass; `material` and `critical` tasks require an isolated Review subagent to issue a structured verdict.
284
- - **Unattended Batch**: Serial execution driven by GitHub Issues and bound by `plan_digest`, where each child independently completes its own Enrollment → QA → Review → Commit cycle.
532
+ 3. **Deterministic Assurance & Immutable Evidence Trail**
533
+ - **QA-First & Real Process Execution**: The Kernel directly launches sandboxed child processes to run test commands and evaluates exit codes, stdout, and byte bounds; never relies on conversational claims.
534
+ - **Risk-Tiered Gates with Enforcement Floors**: `routine` tasks complete upon QA pass; `material` and `critical` tasks require an isolated Review subagent. Touching kernel or authority paths is forced to at least `material`.
535
+ - **Live Refutation**: Subjective Review findings can be refuted by fresh, passing QA evidence; any new edits invalidate counterevidence and re-block the finding.
536
+ - **Immutable Audit Trail**: Terminal task completion atomically writes signed `TaskRecord`s, Git blob `ReviewBundle`s, and QA Attestations to `.imm/audit/<task-id>/`, fully tracked in Git.
537
+ - **Unattended Batch & Parallel Lanes**: Progresses via GitHub Issues bound by `plan_digest`. Supports default single-branch serial execution or physical multi-Lane parallel execution; in lane mode, the Coordinator schedules scope-disjoint Git worktrees, and Integration Guard reruns deterministic descriptors on candidate commits before fast-forwarding the batch branch, preventing concurrency contamination.
285
538
 
286
539
  Key invariants:
287
540
 
288
541
  - **One active step at a time**, edits only inside that step's boundary.
289
- - **Scope (`scope_hint`) is frozen at enrollment** — out-of-scope files are ignored.
542
+ - **Scope (`scope_hint`) is frozen at enrollment** — out-of-scope files are physically denied and intercepted.
290
543
  - **Evidence before closure** — QA is the only authority that can close a step.
291
544
  - **Findings carry evidence** — a refuted Review finding suppresses work only while the QA evidence bound to it stays fresh for the current revision, intent hash, and diff; when that evidence goes stale the finding blocks again, and nothing stored is rewritten by the invalidation.
292
545
  - **Batches are opt-in and bounded** — an unattended batch exists only after you confirm the Host's `start_unattended_batch`; each child keeps its own enrollment, QA, review, and settlement.
@@ -296,13 +549,70 @@ Key invariants:
296
549
 
297
550
  ## Unattended Batch Runs
298
551
 
299
- When an Initiative has several ready children, you can run them as one serial batch instead of task by task.
552
+ When an Initiative contains multiple ready children, developers can run the entire batch unattended via the Host's privileged `start_unattended_batch` tool without manually driving `imm-run` for each child task.
553
+
554
+ Immune-Brain supports two batch execution modes: **Default Serial Mode** and **Parallel Batch Lanes**.
555
+
556
+ ### 1. Batch Execution Modes Overview
557
+
558
+ | Dimension | Serial Batch (Default) | Parallel Batch Lanes |
559
+ |---|---|---|
560
+ | **Activation** | Call `start_unattended_batch(slug)` directly | Pass `max_parallel` or configure `Lane max parallel: <n>` |
561
+ | **Workspace Topology** | Shared single batch branch (`imm-batch/<slug>`) | Coordinator manages batch branch; each concurrent task owns a Git worktree (`imm-lane/<task-id>`) |
562
+ | **Scheduling** | Strict sequential execution ordered by dependency layers | Scope-disjoint children execute concurrently in parallel Lanes |
563
+ | **Authority Boundaries** | Single local Authority Store advanced sequentially | Each Lane owns its own local Authority Store, running isolated with zero global CAS contention |
564
+ | **Integration** | Direct commit on batch branch after task QA/Review passes | Reconciles via Git plumbing, reruns Integration Guard descriptors, then fast-forwards batch branch |
565
+ | **Ideal For** | Small initiatives, tight file coupling, resource-constrained environments | Medium/large initiatives, decoupled modules, high-compute environments |
566
+
567
+ ### 2. Batch Authority & Invariants
568
+
569
+ - **Explicit Entry & Single Authorization:** No batch state or branch exists before calling `start_unattended_batch`; without it, `imm-run` behaves identically to single-task enrollment. The native gate (Pi TUI dialog or Claude MCP elicitation) displays the ordered child list and global `plan_digest`; this single user confirmation constitutes complete Batch Authorization.
570
+ - **Child Authority Invariance:** A batch merely bundles authorization scope without weakening engineering rigor. Every child is still individually enrolled, scope-frozen, QA-verified via authentic child processes, reviewed in isolation, and settled with its own `TaskRecord`. A batch is a scope of authorization, not a new authority layer.
571
+ - **Deterministic Boundaries:** Only runs published, non-`critical` children. Any required human decision (`needs_human`), budget/timeout interruption, or integration error halts the batch safely, marking dependent children as `skipped_blocked` rather than reordering. Runners never push, open PRs, or make arbitrary decisions.
572
+
573
+ ### 3. Parallel Batch Lanes Lifecycle & Architecture
574
+
575
+ In parallel lane mode, the Coordinator (Parent Host), `lane-steward` internal role, and Lane Executor Hosts coordinate to provide physical concurrency isolation:
576
+
577
+ ```mermaid
578
+ sequenceDiagram
579
+ participant P as Coordinator (Parent Host)
580
+ participant B as Batch Runtime
581
+ participant S as lane-steward Role
582
+ participant L as Lane Executor Host (Pi / Claude)
583
+ participant K as Lane Kernel (Isolated Store)
584
+
585
+ Note over P,B: 1. Scheduling & Scope-Disjoint Analysis
586
+ P->>B: start_unattended_batch(slug, max_parallel)
587
+ B-->>P: handoffs: provision Lane A, Lane B
588
+
589
+ Note over P,S: 2. Physical Worktree Provisioning (Provision & Admit)
590
+ P->>S: Provision worktree (branch imm-lane/..., base batch base)
591
+ S-->>P: Return isolated worktree paths
592
+ P->>B: Submit lane_offers admission check (cleanliness, branch, base)
593
+
594
+ Note over P,L: 3. Supervised Parallel Execution
595
+ B-->>P: handoffs: launch Executor A, Executor B
596
+ P->>L: Launch background session for imm-run (configurable Host/model)
597
+ L->>K: Run loop: Scope freeze -> Deterministic QA -> Review -> Settle
598
+
599
+ Note over P,B: 4. Integration Guard & Fast-Forward
600
+ L-->>P: Lane finish notification
601
+ P->>B: Coordinator reconcile tick
602
+ B->>K: Read Lane evidence & commit
603
+ B->>B: Build candidate commit + rerun Integration Guard descriptors
604
+ B->>B: Fast-forward batch branch (1 child 1 commit)
605
+ B-->>P: handoffs: release Lane A / provision Lane C
606
+ ```
607
+
608
+ #### Core Mechanisms:
609
+
610
+ 1. **Scope-Disjoint Scheduling:** The Coordinator dynamically computes dependency layers and path overlap. A child is scheduled only when its prerequisites are integrated and its `scope_hint` is provably disjoint from all in-flight Lanes. Overlapping children wait until conflicting Lanes integrate.
611
+ 2. **Supervised Host Sessions:** The Parent Host launches an independent Executor Host process for each Lane (configurable across Hosts, models, and effort tiers, such as Pi or Claude Code). The Parent is reactively notified on session completion, polling nothing. When running inside Herdr, it opens one tab per Lane and never answers trust/login dialogs on behalf of the user.
612
+ 3. **Integration Guard:** To eliminate silent semantic conflicts, settled deliveries are not blindly merged. The Coordinator constructs candidate commits via Git plumbing and reruns deterministic descriptors for both the candidate child and all sibling tasks integrated since the lane's base. Fast-forward proceeds only if all tests pass.
613
+ 4. **Fault Isolation:** If a Lane encounters a QA failure, review rejection, or integration conflict, the batch branch stays untouched (zero-write). The failing child is parked as `needs_human`, its dependents are marked `skipped_blocked`, while independent sibling Lanes proceed unaffected.
614
+ 5. **Agents Only Create:** The Parent and `lane-steward` provision Lanes and terminal tabs but never kill sessions or delete worktrees. Once integrated, the system reports safe-to-release Lanes for the developer to inspect and clean up.
300
615
 
301
- - **Entry is explicit:** the Host's privileged `start_unattended_batch` tool, taking the Initiative slug. Nothing batch-related exists until it is called — without it, `imm-loop` behaves exactly like per-task enrollment and creates no batch state, branch, or authorization.
302
- - **One confirmation, one digest:** the native gate (Pi TUI dialog or Claude MCP elicitation) shows the ordered child list and the shared plan digest; that single literal-user act is the whole Batch Authorization.
303
- - **Per-child authority survives:** every child is still enrolled, frozen, QA'd, reviewed, and settled by the Kernel on its own `TaskRecord`. The batch is the scope of one authorization, never a new authority layer.
304
- - **Closeout is automatic:** when a child reaches `done` in the foreground, the same call commits it and enrolls the next child, or marks the batch `completed`, with no new gate. A parked or stopped child is never committed for you, and a failed continuation is reported beside the result with `start_unattended_batch` as the retry. A fast-forward commit you add to the batch branch is adopted; any other HEAD movement still stops the run.
305
- - **Bounds:** only published, non-`critical` children run, serially on a dedicated batch branch. The run parks when a child needs a human decision or a budget, authorization, or commit failure stops it; the budget is a child count and a QA failure limit, and nothing expires with time, and dependents of a blocked child are skipped rather than reordered. The runner never pushes, opens PRs, resolves user decisions, or creates, switches, or deletes Git worktrees.
306
616
 
307
617
  ---
308
618
 
@@ -314,6 +624,10 @@ Immune-Brain has **no separate config file**. Preferences live in your host's ag
314
624
  ## Immune-Brain Preferences
315
625
 
316
626
  - Initiative carrier default: github # or: local
627
+ - Lane max parallel: 4 # optional; enables lane mode
628
+ - Lane Executor Host: claude-code # optional; or: pi
629
+ - Lane Executor model: <model id> # optional; needs Lane Executor Host
630
+ - Lane Executor effort: high # optional; needs Lane Executor Host
317
631
  ```
318
632
 
319
633
  | Preference | Options | Default | Notes |
@@ -321,6 +635,10 @@ Immune-Brain has **no separate config file**. Preferences live in your host's ag
321
635
  | Reply language | any natural language | repo `AGENTS.md` | Machine contracts / paths stay literal |
322
636
  | Initiative carrier | `local` / `github` | none — Planner asks | Only matters when a proposal splits across multiple TaskIntents |
323
637
  | Advisory subagents | allowed / solo | allowed | Respects Pi host policy + explicit user instruction |
638
+ | Lane max parallel | integer ≥ 1 | none — batches stay serial | Passed as `max_parallel` when a batch starts; a resumed batch keeps its recorded value |
639
+ | Lane Executor Host | `claude-code` / `pi` | none — prefers the Parent's own Host type | Every Lane uses this Host, with no fallback to the other one |
640
+ | Lane Executor model | a model ID of that Host | none — the Executor Host's own default | Applies only when `Lane Executor Host` is set |
641
+ | Lane Executor effort | an effort level of that Host | none — the Executor Host's own default | Applies only when `Lane Executor Host` is set; `--effort` on Claude Code, `--thinking` on Pi |
324
642
 
325
643
  Precedence: **current message > repo agent instruction file > user-level agent instruction file > ask**. Skills read these files directly, so a preference works even when the host does not auto-load that file.
326
644
 
@@ -352,19 +670,29 @@ docs/specs/ # Living specs (updated in place)
352
670
 
353
671
  ## FAQ
354
672
 
355
- **Do I need to learn all 6 skills?** No. Most of the time you only need `/imm-planner` (to plan and enroll a task) and `/imm-loop` (to build and verify it). Use `imm-brainstorm` when requirements need clarifying first, and the maintenance skills (`imm-pr-fix`, etc.) only when specific repair needs arise. Ordinary chat and simple edits don't need any skills at all.
673
+ **Do I need to learn all 7 skills?** No. Most of the time you only need `/imm-planner` (to plan and enroll a task) and `/imm-run` (to build and verify it). Use `imm-brainstorm` when requirements need clarifying first, and the maintenance skills (`imm-pr-fix`, etc.) only when specific repair needs arise. Ordinary chat and simple edits don't need any skills at all.
356
674
 
357
- **What if I interrupt or close the session mid-task?** State is safely stored on disk (`.imm/` + TaskIntent). In Pi or Claude Code, simply re-enter `/imm-loop` to resume — the Kernel projection is authoritative.
675
+ **What if I interrupt or close the session mid-task?** State is safely stored on disk (`.imm/` + TaskIntent). In Pi or Claude Code, simply re-enter `/imm-run` to resume — the Kernel projection is authoritative.
358
676
 
359
677
  **Why does enrollment show a confirmation dialog?** All risk levels (`routine`/`material`/`critical`) require explicit human confirmation before execution authority is granted. In Pi, this is a native TUI modal dialog; in Claude Code, it is a native MCP elicitation gate. It binds the staged digest so you see exactly what will be tracked.
360
678
 
361
- **QA failed — what now?** QA returns `rework` or `replan_required`. `imm-loop` routes back to the executor or to `imm-planner` for scope changes. No manual reset needed.
679
+ **QA failed — what now?** QA returns `rework` or `replan_required`. `imm-run` routes back to the executor or to `imm-planner` for scope changes. No manual reset needed.
362
680
 
363
681
  **A review finding stopped blocking — why?** It was refuted: fresh deterministic QA evidence shows the acceptance it names passes. The refutation is bound to that exact evidence, so the finding blocks again the moment the evidence goes stale for the current revision, intent hash, or diff.
364
682
 
365
683
  **Can it run a whole Initiative without me?** Only as far as you authorize. Confirm `start_unattended_batch` with the Initiative slug and the runner works through the published, non-`critical` children serially on one batch branch — parking as soon as a child needs a human decision or the run hits a budget, authorization, or commit failure. A parked run waits for you indefinitely: neither the confirmation dialog nor the authorization it grants times out. It never pushes, opens PRs, or settles user decisions for you.
366
684
 
367
- **Can I switch between hosts (e.g. plan in Claude Code, code in Pi)?** Yes. Immune-Brain's contracts and state live entirely on disk in the repository, decoupled from conversation sessions. You can leverage Claude Code for deep architectural thinking and Spec planning, then switch to Pi to run `imm-loop` for code execution and deterministic QA. Interrupted tasks can be resumed in either host at any time.
685
+ **Can I switch between hosts (e.g. plan in Claude Code, code in Pi)?** Yes. Immune-Brain's contracts and state live entirely on disk in the repository, decoupled from conversation sessions. You can leverage Claude Code for deep architectural thinking and Spec planning, then switch to Pi to run `imm-run` for code execution and deterministic QA. Interrupted tasks can be resumed in either host at any time.
686
+
687
+ **What if the task discovers the scope is insufficient mid-execution?** The Executor adheres strictly to a fail-closed YAGNI red-line and is physically barred from modifying out-of-scope files. When an expansion is truly required, the Executor aborts and yields a `replan_required` route; `imm-planner` then revises the Spec and `TaskIntent`, presenting a new native confirmation dialog before execution resumes.
688
+
689
+ **Where is the terminal Audit Trail stored and how is it verified?** Settled records are saved to `.imm/audit/<task-id>/` and tracked in Git. Each directory contains the immutable `TaskRecord`, the bound `diff_hash`, raw QA process exit-code attestations, and the Reviewer's signed verdict bundle.
690
+
691
+ **Why are preferences kept in AGENTS.md / CLAUDE.md instead of an external config.toml?** Immune-Brain embraces host-native simplicity with zero external configuration files. Declaring preferences (such as Initiative carriers and communication instructions) in tracked agent instruction files ensures that configuration is version-controlled, visible across all collaborators, and free from environment drift.
692
+
693
+ **Why do you recommend `grill-me` instead of `imm-brainstorm` for complex tasks?** `imm-brainstorm` is a lightweight, built-in tool designed for quick problem framing without external dependencies. However, `grill-me` (from `mattpocock/skills`) provides an active, relentless Socratic interview that explores every branch of your design tree with opinionated recommendations. For non-trivial features, architectural refactors, or security boundaries, grilling the design with `grill-me` before passing the settled decisions to `imm-planner` produces significantly tighter specifications and prevents downstream rework.
694
+
695
+ **Do I need to install `mattpocock/skills` to use Immune-Brain?** No. Immune-Brain is completely self-contained and functions out of the box with built-in `imm-brainstorm`. Composing with `mattpocock/skills` is an optional, highly recommended power workflow for teams seeking maximal engineering discipline.
368
696
 
369
697
  **Which AI coding assistants are supported?** Pi and Claude Code are the supported hosts (Claude Code version >= `2.1.236`). Both hosts run on the exact same Kernel authority, assurance guarantees, and multi-skill pipeline.
370
698
 
@@ -392,7 +720,7 @@ npm publish --access public # requires npm login / NPM_TOKEN
392
720
  # or
393
721
  bun run changeset:publish
394
722
  ```
395
- The package publishes to npm as `immune-brain` (current release `3.6.7`) with `publishConfig.access=public` already set. After the initial publish, all future releases go through changesets.
723
+ The package publishes to npm as `immune-brain` (current release `4.6.0`) with `publishConfig.access=public` already set. After the initial publish, all future releases go through changesets.
396
724
 
397
725
  See `CHANGELOG.md` and `.changeset/config.json` (changelog: `@changesets/changelog-github`, repo: `dereknex/immune-brain`).
398
726