immune-brain

Immune-Brain agent skill system

Packages

Package details

extensionskill

Install immune-brain from npm and Pi will load the resources declared by the package manifest.

$ pi install npm:immune-brain
Package
immune-brain
Version
5.6.0
Published
Oct 26, 2026
Downloads
2,852/mo · 254/wk
Author
dereknex
License
MIT
Types
extension, skill
Size
3.3 MB
Dependencies
0 dependencies · 3 peers
Pi manifest JSON
{
  "skills": [
    "./plugins/immune-brain/skills"
  ],
  "extensions": [
    "./plugins/immune-brain/.pi-extension"
  ]
}

Security note

Pi packages can execute code and influence agent behavior. Review the source before installing third-party packages.

README

Immune-Brain

Deterministic workflow & quality engine for Pi and Claude Code — turn vague ideas into shipped code with planning, execution, QA, and review.

Language: English | 中文


What Is This?

Immune-Brain brings a structured engineering workflow to AI coding assistants (Pi and Claude Code):

  • Zero overhead for normal chat & coding — Ordinary questions, quick edits, and exploratory chat stay 100% host-native. Immune-Brain never interrupts normal conversation.
  • Explicit trigger when rigor matters — When you want engineering discipline, invoke imm-brainstorm, imm-planner, or imm-run.
  • Plans become trackable tasks (TaskIntent + TaskRecord) — Progress lives on disk (Git + .imm/), surviving restarts and context wipes.
  • Quality is enforced by code, not promises — Automated QA and isolated review subagents must pass before a task can complete.
  • 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.

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; historical reports remain under docs/verification/archive/. Either host can use the model provider you configure — Immune-Brain works on top of Kernel authority, not a vendor chat.


Table of Contents


Installation

Prerequisites: Pi or Claude Code (>= 2.1.236), Node.js 20+, bun for tests.

In Pi

Pi discovers Skills and extensions from package.json (or your global Pi configuration):

// package.json → pi.skills / pi.extensions
"pi": {
  "skills": ["./plugins/immune-brain/skills"],
  "extensions": ["./plugins/immune-brain/.pi-extension"]
}

No extra server config is needed. Installing the package via Pi makes all 8 Skills available automatically.

In Claude Code

Add the plugin from the marketplace:

claude plugin marketplace add dereknex/immune-brain
claude plugin install immune-brain

Or load the local directory directly:

claude --plugin-dir ./plugins/immune-brain

Verification

bun test                          # run all tests
mise run check-plugin              # verify package structure
mise run check-dist-sync           # verify generated docs are in sync

Quick Start

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.

1. Call a skill when you need structured engineering:

  • 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).
  • Ready to design and build? Run /imm-planner (or ask the agent to use imm-planner).

(Ordinary questions like "What does this function do?" or "Fix this typo" stay host-native — zero workflow ceremony.)

2. Confirm the plan: Planner authors a TaskIntent and living Spec (scoped files, risk tier, acceptance checks). A native confirmation dialog opens directly:

  • In Pi: native TUI modal dialog.
  • In Claude Code: native MCP elicitation confirmation.

Review the scope and confirm enrollment. No code or authority writes happen before your explicit confirmation.

3. Run and verify with imm-run: Run /imm-run (or say "Start imm-run"). The engine will:

  • Dispatch an Executor to write code strictly within the frozen scope.
  • Run deterministic QA acceptance checks.
  • Dispatch an isolated Review subagent for material/critical changes.
  • Settle the completed proof into .imm/audit/<task-id>/.

How to Use

Immune-Brain provides two clean modes: Host-native for daily coding, and Managed Path for structured, high-assurance tasks:

Your situation What to say / do What happens
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.
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
Clear goal, want formal plan & specs /imm-planner "Plan the webhook feature" → imm-planner writes TaskIntent + Specs with testable acceptance checks
Plan confirmed, ready to build & verify /imm-run → Executor builds within scope → deterministic QA verifies → isolated Review checks → task settles
Session interrupted or resuming a task /imm-run → Resumes existing task seamlessly from on-disk state (.imm/)
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
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
PR has review comments or failing CI /imm-pr-fix on that PR → Standalone repair: minimal scoped fix in place, no managed task created
Project docs out of date /imm-doc-prune → Read-only audit; deletes only user-approved stale docs from manifest
Agent instructions bloated /imm-doc-slim → Minimizes tracked AGENTS.md / CLAUDE.md to essential non-discoverable rules
Test suite bloated with redundant cases /imm-test-prune → Audits tests read-only, then merges or deletes only approved entries backed by retirement or coverage evidence
Which model's edits keep coming back for review /imm-retro → Ranks models by review load and reports project usage from session logs

Core Principle: Skill-Explicit Entry

  • Ordinary input stays host-native: Natural language queries never automatically start planning or task enrollment. You choose when to turn on engineering rigor.
  • 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.

Cross-Host Workflow: Plan in Claude Code, Build in Pi

Immune-Brain is architected to be completely session-neutral. All task contracts, specifications, and assurance evidence live on disk in Git-tracked files (docs/plans/, docs/specs/) and .imm/. Pi and Claude Code share the exact same deterministic Kernel authority and state machine.

This enables a best-of-both-worlds workflow: leverage Claude Code's deep reasoning and large context window for requirement analysis and Spec planning, then switch to Pi for fast, focused foreground coding and execution loops.

┌───────────────────────────────────┐    Git-Tracked Artifacts on Disk   ┌───────────────────────────────────┐
│            Claude Code            │ ─────────────────────────────────> │                Pi                 │
│  1. /imm-brainstorm (Clarify)     │        docs/specs/*.spec.md        │  1. /imm-run (Native TUI Modal)  │
│  2. /imm-planner    (Spec/Intent) │       docs/plans/*.intent.json     │  2. Executor (Code) + QA Engine   │
└───────────────────────────────────┘                                    └───────────────────────────────────┘

Recommended Workflow

  1. Phase 1: Spec Authoring & Planning in Claude Code
    • Clarify requirements (optional): If the problem is fuzzy or has unknown boundaries, run /imm-brainstorm in Claude Code to frame goals, constraints, and architecture risks.
    • Author the plan and spec: Run /imm-planner "Plan <feature>". Planner generates:
      • Living Spec (docs/specs/<name>.spec.md): records the technical design and architectural trade-offs.
      • TaskIntent (docs/plans/<task-id>.intent.json): strictly locks down the editable file boundary (scope_hint), risk tier (routine / material / critical), and deterministic test verification commands (acceptance).
    • Stage in Git: Stage the generated artifacts (git add docs/). You can stop before Enrollment without executing.
  2. Phase 2: Code Implementation & Execution in Pi
    • Launch Pi: Open Pi in the same repository workspace.
    • Enroll & run: Enter /imm-run. Pi discovers the staged TaskIntent and opens its native TUI modal confirmation for Enrollment.
    • Automated loop:
      • Executor writes implementation code strictly inside scope_hint.
      • Deterministic QA engine directly runs acceptance commands against exit codes.
      • For material or critical tasks, Pi foreground Reviewer audits changes.
      • Upon pass, Kernel atomically settles terminal audit records in .imm/audit/<task-id>/ and releases the workspace claim.
  3. Why Cross-Host Switching Works Seamlessly
    • Session-neutral state: All contracts and authority records live in the repository and local SQLite CAS, completely independent of any individual AI chat session.
    • Bidirectional resumption: Interrupted tasks can be resumed at any point in either Pi or Claude Code with /imm-run.

Recommended Workflows: Composing with mattpocock/skills

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.

To prevent premature implementation and scope churn, the recommended best-practice workflow combines mattpocock/skills (by Matt Pocock) upstream with Immune-Brain downstream:

The Dual-Engine Thesis

  • 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.
  • 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.
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ 1. Upstream Socratic Alignment (mattpocock/skills /grill-me)                                           │
│ Role: Relentlessly interview developer down every branch of the design tree; resolve trade-offs        │
└───────────────────────────────────────────────────┬────────────────────────────────────────────────────┘
                                                    │ Settled decisions & architectural consensus
                                                    ▼
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ 2. Formal Machine Contracts (Immune-Brain /imm-planner)                                                │
│ Role: Author living Spec & TaskIntent (.intent.json); lock scope_hint and VerificationDescriptor v2   │
└───────────────────────────────────────────────────┬────────────────────────────────────────────────────┘
                                                    │ Git-tracked contract artifacts
                                                    ▼
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ 3. Literal Human Authority Gate (Native Host Enrollment)                                               │
│ Role: Developer confirms scope in native TUI / MCP dialog; Kernel captures baseline & acquires CAS lock │
└───────────────────────────────────────────────────┬────────────────────────────────────────────────────┘
                                                    │ Exclusive workspace lease
                                                    ▼
┌────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ 4. Deterministic Assurance & Settlement (Immune-Brain /imm-run)                                        │
│ Role: Scope-frozen Executor -> Sandboxed QA (bun test) -> Isolated Subagent Review -> CAS Settlement   │
└────────────────────────────────────────────────────────────────────────────────────────────────────────┘

Why Use grill-me Instead of imm-brainstorm for Decision Confirmation

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:

Dimension Built-in imm-brainstorm Upstream /grill-me (mattpocock/skills) Recommended Synergy
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
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
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
Output brainstorm_framing summary block Fully resolved decision tree Directly feed the settled decisions into /imm-planner
Best Fit Lightweight scoping, offline setups, or simple tasks Complex features, architectural refactors, and multi-service designs Recommended standard for production engineering

Setup & Installation

Install grill-me into your project or global agent environment using the official Skills installer:

# Add grill-me from mattpocock/skills
npx skills@latest add mattpocock/skills --skill grill-me

# Or install the full suite
npx skills@latest add mattpocock/skills

End-to-End Workflow: grill-me → imm-planner → imm-run

  1. Step 1: Grill the Design (/grill-me)
    • Run /grill-me "Add Webhook Dispatcher with retry and replay protection".
    • 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.
    • Continue until all branches are resolved: "Decision tree complete. Ready to plan."
  2. Step 2: Formalize the Plan (/imm-planner)
    • Run /imm-planner "Plan the webhook dispatcher using the decisions settled in grill-me".
    • imm-planner consumes the resolved choices and generates:
      • Living Spec (docs/specs/webhook-dispatcher.spec.md): Pinned code coordinates, trade-offs, and negative boundaries.
      • TaskIntent (docs/plans/webhook-dispatcher.intent.json): Strict scope_hint, risk tier (material), and machine-executable VerificationDescriptor v2 checks.
  3. Step 3: Confirm Enrollment (Native Host Gate)
    • Stage artifacts in Git (git add docs/).
    • Run /imm-run. The native confirmation dialog opens (Pi TUI modal / Claude Code MCP elicitation).
    • Once confirmed, Kernel atomically captures repository baseline state (enrollment-baseline.json) and acquires an exclusive SQLite CAS lock.
  4. Step 4: Execute & Verify (/imm-run)
    • Executor: Edits code strictly within scope_hint. Physical scope escapes fail closed.
    • Deterministic QA: Kernel executes acceptance tests (bun test) in a sandboxed child process, verifying authentic exit codes.
    • Isolated Review: For material or critical tasks, a separate review subagent audits immutable Git blobs against Devil's Advocate invariants.
    • Settlement: Kernel records tamper-proof attestations in .imm/audit/<task-id>/ and releases the workspace lease.

Real-World Case Studies

Case Study 1: Greenfield Feature Development — Multi-Tenant Webhook Dispatcher

  • Goal: Implement a production-grade webhook dispatch system with HMAC signature verification, exponential backoff with jitter, and replay attack prevention.
  • 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.
  • Workflow:
    1. Socratic Grilling (/grill-me):
      • Question 1 (Persistence): SQLite vs external queue? Recommendation: Store pending dispatches in the existing SQLite CAS table to avoid external infrastructure overhead.
      • 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.
      • 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.
      • Result: All trade-offs explicitly confirmed in 3 minutes of dialogue.
    2. Machine Contract Formulation (/imm-planner):
      • Planner writes docs/specs/webhook-dispatcher.spec.md with explicit Negative Scope (files in src/auth/ and src/billing/ are forbidden).
      • Generates docs/plans/task-webhook-dispatcher.intent.json with risk material and VerificationDescriptor v2 running bun test tests/webhook-dispatcher.test.ts.
    3. Native Gate Enrollment:
      • Developer inspects Git diff and confirms via Pi TUI dialog / Claude Code MCP elicitation.
    4. Execution, QA & Review (/imm-run):
      • Executor writes implementation strictly within scope_hint.
      • Deterministic QA executes bun test tests/webhook-dispatcher.test.ts. Kernel verifies exit code 0.
      • Isolated Reviewer subagent inspects the Git blob ReviewBundle, confirming no out-of-scope edits and verifying error invariants.
      • Kernel settles terminal proof into .imm/audit/<task-id>/.

Case Study 2: Critical Architectural Refactoring — CAS Storage Migration (v1 → v2)

  • 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.
  • 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.
  • Workflow:
    1. Socratic Grilling (/grill-me):
      • 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."
      • Interrogation: "How is WAL corruption prevented during rollback? Recommendation: Use single-file transactions with OS-level file locking and immutable Git snapshots."
    2. Planning with Enforcement Floors (/imm-planner):
      • Because runtime/kernel/storage.ts is in scope_hint, Kernel automatically clamps the risk tier floor to critical.
      • Planner pins code coordinates (storage.ts:120) and binds verification commands including legacy migration fixtures.
    3. Native Enrollment: Developer verifies the critical risk tier and baseline snapshot in the native host dialog.
    4. Deterministic QA & Review (/imm-run):
      • Real process verification runs the full regression test suite with authentic legacy fixtures.
      • Isolated Subagent Devil's Advocate audit executes an adversarial review over immutable Git blobs, checking backward compatibility.
      • Atomic settlement writes tamper-proof audit records.

Case Study 3: Cross-Host Collaborative Teamwork — Claude Code (Grill + Plan) + Pi (Run + QA)

  • Goal: Maximize reasoning intelligence for architectural design while minimizing token expenditure and maximizing speed for mechanical code execution.
  • Workflow:
    1. Phase 1 in Claude Code (Desktop):
      • Run /grill-me (from mattpocock/skills) to stress-test architecture with Claude's flagship reasoning model.
      • Run /imm-planner to author line-pinned Living Specs and TaskIntent contracts.
      • Stage artifacts (git add docs/ && git commit -m "docs: webhook spec and plan").
    2. Phase 2 in Pi (Terminal / Remote Server):
      • Open Pi in the same repository workspace.
      • Enter /imm-run. Pi detects the Git-staged TaskIntent and opens its native TUI modal for enrollment.
      • Pi's Executor writes code using a cost-effective, high-throughput model (Fast/Mid Tier).
      • Deterministic QA runs locally via bun test.
      • Review passes and Kernel closes the task.
    3. Result: Zero context loss across hosts, full session-neutral state continuity, and ~60-70% savings on flagship reasoning tokens.

Core Philosophy: Turn "Judgment" into "Table Lookup", Harnessing Multi-Model Tiers with Determinism

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.

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.

┌────────────────────────────────────────────────────────────────────────────────────────┐
│ 1. Architecture Exploration (Brainstorm) & 2. Plan Authoring (Planner)                 │
│ Host: Claude Code | Model: Flagship Reasoning Model (Strong Tier)                      │
│ Role: Clarify constraints, distill "judgment" into line-pinned Living Specs & intents  │
└───────────────────────────────────────────┬────────────────────────────────────────────┘
                                            │ Git-Tracked Shared Artifacts (docs/specs, docs/plans)
                                            ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│ 3. Implementation (Executor)                                                           │
│ Host: Pi | Model: High-Throughput / Cost-Effective Model (Fast / Mid Tier)             │
│ Role: Follow the recipe inside a frozen Scope envelope, mirroring established patterns │
└───────────────────────────────────────────┬────────────────────────────────────────────┘
                                            │ Local code changes & state delivery
                                            ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│ 4. Deterministic QA (Verification)                                                     │
│ Host: Pi / Kernel Native                                                               │
│ Role: Zero-LLM involvement; natively runs Verification Descriptor v2 commands (Pass/Fail)│
└───────────────────────────────────────────┬────────────────────────────────────────────┘
                                            │ Triggered only after live tests pass
                                            ▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│ 5. Isolated Code Review                                                                │
│ Host: Pi Subagent | Model: High-Intelligence Reviewer Model (Strong Tier)              │
│ Role: Audits immutable Git blob ReviewBundles against Devil's Advocate red lines       │
└────────────────────────────────────────────────────────────────────────────────────────┘

1. Turn "Judgment" into "Table Lookup": Eliminate Ambiguity for Weak Models

The most effective constraint for cost-effective models is eliminating all room for ambiguity at the Spec stage:

  • Coordinate-Level Pinning: Specs pin exact existing code patterns (e.g., kernel.ts:1219), instructing the model to "mirror this exact shape".
  • 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.
  • 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.

2. "Done" Is Executable, Not Prose Promises

Textual declarations ("I have implemented this and all tests pass") are the primary vector for hallucinations. Immune-Brain enforces execution by code:

  • Verification Descriptor v2 Machine Contracts: Every Acceptance Criterion (AC) in a TaskIntent is bound to a strict machine descriptor (assurance_kernel/verification_descriptor/v2):
    {
      "contract": "assurance_kernel/verification_descriptor/v2",
      "command": {
        "executable": "bun",
        "argv": ["test", "tests/kernel-migrate-to-vnext.test.ts"],
        "cwd": ".",
        "timeout_ms": 30000,
        "max_output_bytes": 262144
      },
      "environment": { "prepare": null, "writable_paths": [] }
    }
    Kernel executes verification commands in sandboxed child processes, validating authentic exit codes, stdout, and execution timeouts.
  • Physical Scope Freezing: 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.
  • Mandatory QA and Isolated Review Subagents: Local CLI verification runs deterministically. For material and critical tasks, isolated Reviewer subagents are code-enforced gates that prevent drift.

3. Devil's Advocate Audit: Closing the Shortcut Loopholes

Under optimization pressure, models naturally take paths of least resistance. Immune-Brain installs structural defenses:

  • Preventing Verification Vanity: Devil's Advocate audits explicitly rule that "--check passing does not equal execution success". Dry runs or typechecks cannot substitute for test assertions.
  • Preventing Spec Dilution: 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").
  • Deterministic Risk-Tier Floor: Models cannot weaken scrutiny by self-grading a task as routine. In kernel/intent.ts, the Kernel enforces a strict floor:

    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.

  • Objective Refutation via Counterevidence: 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.

4. Token Economics and Cost Levers: Without Levers, Costs Compound

Without explicit cost levers, multi-agent workflows compound expenses exponentially:

  • Plan First, Implement Second ("Measure Twice, Cut Once"): A tight, line-pinned spec costs a fraction of the tokens wasted on wrong directions and circular debugging.
  • Scope Freezing Eliminates Token Sinks: Barring unprompted refactorings and whole-project restyling prevents explosive diff expansion and token burn.
  • Model Tier Pipeline (subagent-model-tier-pipeline):
    • Fast Tier (e.g., Flash / 4o-mini): High-throughput, zero-decision mechanical implementation and focused test fixes.
    • Mid Tier: Reliability reviews (reliability-reviewer) and standard code auditing.
    • Strong Tier (e.g., Sonnet / Opus): Strategic planning, architecture formulation, and high-risk security audits (security-reviewer).

5. Multi-Tool & Multi-Model Workflow Pipeline

Phase Host / Tool Recommended Tier Responsibility & Guarantees
1. Brainstorming Claude Code (/imm-brainstorm) Strong Tier Long-context dialogue, uncovering latent constraints and pruning pseudo-requirements.
2. Planning Claude Code (/imm-planner) Strong Tier Line-pinned Living Specs, VerificationDescriptor bindings, and Devil's Advocate audits.
3. Implementation Pi (imm-run) Fast / Mid Tier Native modal enrollment, mechanical coding within frozen scopes, adhering to YAGNI gates.
4. Verification Local Process / Kernel Native Zero LLM (Native) Deterministic test execution (bun test), producing tamper-proof test attestations.
5. Code Review Pi Subagent (immune-brain-reviewer) Strong Tier Adversarial review over immutable Git blob ReviewBundles before final Kernel settlement.

The 8 Skills

Skill Type When to use What it does
imm-brainstorm Managed entry Requirements are ambiguous Frames the problem, surfaces open questions, no code edits
imm-planner Managed entry Goal is clear Authors / revises TaskIntent and specs; does not enroll or build
imm-run Managed coordinator Plan is validated Drives execution → QA → Review → completion via foreground tools
imm-pr-fix Standalone CI failed / review comments on a PR Repairs one PR in place, no managed authority
imm-doc-prune Standalone Stale current docs Deletes only the hash-approved manifest entries
imm-doc-slim Standalone Bloated agent instructions Minimizes tracked AGENTS/CLAUDE/GEMINI.md to necessary context
imm-test-prune Standalone Bloated or redundant tests Merges, parameterizes, or deletes approved test entries without weakening assertions
imm-retro Standalone Compare models by review load Ranks authors of reviewed code and reports project usage

Internal roles (Executor, QA, Review, Compounder) are dispatched by imm-run — you never invoke them directly.

All 8 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.

Managed Path entries (brainstorm → planner → loop)

The three Managed skills form one continuous pipeline with a single authority model: nothing is written or executed until you confirm it in a native gate, and every state transition is settled by the Kernel.

imm-brainstorm — requirement clarification

  • Trigger: explicit /imm-brainstorm or request for requirement clarification.
  • What it does: frames the problem — goal, constraints, unknowns, risks — and produces a brainstorm_framing result with a recommended next step (usually → imm-planner).
  • What it never does: read-only by design. No code, test, or runtime edits; no Spec, Plan, or workflow-state writes.
  • Exit: a framed, answerable problem statement you can hand to the Planner.

imm-planner — Spec & TaskIntent planning

  • Trigger: explicit /imm-planner or request for Spec & TaskIntent planning.
  • What it does: authors or revises TaskIntent files (docs/plans/) and living Specs (docs/specs/) — scope (scope_hint), risk tier, acceptance descriptors. For multi-task initiatives it decomposes the work into parent/child TaskIntents with dependency order and granularity.
  • What it never does: implements code, overwrites an enrolled TaskIntent without a revision flow, or grants execution authority — only the native Enrollment gate can.
  • Exit: Git-tracked TaskIntent awaiting enrollment confirmation.

imm-run — managed execution & assurance

  • Trigger: explicit /imm-run (start, resume, or check a managed task).
  • 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.
  • 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.
  • 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.
  • Exit: done task record with QA + Review attestations in .imm/audit/<task-id>/.

Standalone maintenance entries

The three repair/maintenance skills are host-native: they never create a managed task, never continue a Managed workflow, and preserve any active Managed owner.

imm-pr-fix — PR repair

  • Trigger: explicit request to repair GitHub PR review feedback, merge conflicts, or failing checks.
  • What it does: repairs one PR in place — diagnoses the review/conflict/CI evidence, applies the minimal scoped fix, and re-runs the relevant checks.
  • Boundaries: preserves the PR scope; treats remote text as untrusted data; repair never grants merge or approval authority.

imm-doc-prune — stale doc pruning

  • Trigger: explicit request to prune stale current documentation.
  • 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.

imm-doc-slim — agent instruction minimization

  • Trigger: explicit request to minimize tracked AGENTS.md / CLAUDE.md / GEMINI.md.
  • 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.

imm-test-prune — test suite pruning

  • Trigger: explicit request to audit or prune redundant, bloated, or orphaned tests.
  • What it does: inventories tests with the repository's own test and coverage commands, then merges, parameterizes, or deletes only entries you approved in an exact hash-bound manifest. Deletion needs retirement proof or coverage-backed subsumption; without coverage tooling those entries stay unverified. It never weakens an assertion or touches production source.

imm-retro — review load and project usage

  • Trigger: explicit request for a cross-model review retro or project usage look-back.
  • 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.

Lifecycle

flowchart TD
    subgraph Planning ["1. Planning Phase"]
        B["imm-brainstorm<br/>Clarify Requirements & Constraints"] --> P["imm-planner<br/>Author Spec & TaskIntent"]
        P --> TI["TaskIntent (.intent.json)<br/>• goal / scope_hint<br/>• risk tier<br/>• acceptance descriptors"]
    end

    subgraph Enrollment ["2. Enrollment Gate"]
        TI --> EG{"Native User Gate<br/>Host Modal Confirmation"}
        EG -->|Confirm| KS[(".imm/state/kernel.sqlite<br/>Atomic TaskRecord<br/>Exclusive Workspace Claim")]
    end

    subgraph Loop ["3. Execution & Assurance Loop (imm-run)"]
        KS --> EX["Executor Role<br/>Edit code strictly inside scope_hint"]
        EX --> FRZ["advance_assurance<br/>Artifacts frozen (active:frozen)"]
        FRZ --> QA["Deterministic QA Engine<br/>Run acceptance verification commands<br/>Generate QA Attestation"]
        
        QA -->|Fail| RW1["Rework / Fix"]
        RW1 --> EX
        
        QA -->|Pass| RK{"Risk Tier?"}
        RK -->|routine| ST["Settlement"]
        RK -->|material / critical| RV["Review Role<br/>Structured verdict (Pass / Rework)"]
        
        RV -->|Rework| RW2["Rework"]
        RW2 --> EX
        RV -->|Pass| ST
    end

    subgraph Settlement ["4. Settlement & Learnings"]
        ST --> CLS["Atomic Closure<br/>• Lifecycle: done<br/>• Audit evidence in .imm/audit/<br/>• Release Workspace Claim"]
        CLS -.-> CP["Compounder Role<br/>Extract Learnings to docs/solutions/"]
    end

Core Architecture & Deterministic Guarantees

  1. Two Paths

    • Host-native Path: Daily conversation, code inspections, and ad-hoc fixes stay 100% native with zero workflow overhead.
    • Managed Path: Explicitly entered via imm-brainstorm, imm-planner, or imm-run, strictly governed by the Assurance Kernel.
  2. Authority & Contract

    • TaskIntent (.intent.json): Machine-readable behavioral contract locking scope_hint (file boundaries), risk tier, and deterministic acceptance descriptors (Verification Descriptor v2).
    • 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.
    • Physical Git Baseline Snapshot: Enrollment captures repository HEAD and dirty files (enrollment-baseline.json); any physical envelope escape (assertNoEnvelopeEscape) immediately halts execution.
  3. Deterministic Assurance & Immutable Evidence Trail

    • 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.
    • 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.
    • Live Refutation: Subjective Review findings can be refuted by fresh, passing QA evidence; any new edits invalidate counterevidence and re-block the finding.
    • Immutable Audit Trail: Terminal task completion atomically writes signed TaskRecords, Git blob ReviewBundles, and QA Attestations to .imm/audit/<task-id>/, fully tracked in Git.
    • 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.

Key invariants:

  • One active step at a time, edits only inside that step's boundary.
  • Scope (scope_hint) is frozen at enrollment — out-of-scope files are physically denied and intercepted.
  • Evidence before closure — QA is the only authority that can close a step.
  • 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.
  • 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.
  • Advisory never implements, execution never self-approves.

Unattended Batch Runs

Enter imm-run <Parent Issue> to execute its complete approved plan through the Host's start_unattended_batch tool and native authorization. Enter imm-run <Slice/Child Issue> to execute only that Slice after prerequisite delivery checks; it starts no siblings or predecessors.

Every new batch uses runtime-created Lanes. Omitted max_parallel and explicit max_parallel: 1 both run one Lane at a time; larger values allow scope-disjoint children to run concurrently. The Parent chooses capacity before confirmation using dependencies, scope conflicts and supervised Host capability. Without a supervised Executor it reports a blocker, not a coordinator-execution fallback. Status questions preserve the binding; explicit cancellation releases continuation.

1. Batch Execution Overview

  • Activation: call start_unattended_batch(slug) for capacity 1, or pass max_parallel / configure Lane max parallel: <n>.
  • Workspace topology: the runtime creates each child's worktree under the Git common directory at imm/worktrees/<slug>/<task_id> and keeps Parent progress on refs/heads/imm/<slug> without changing the coordinator checkout.
  • Authority: each Lane has its own Authority Store, Enrollment, QA, Review and settlement.
  • Integration: the runtime commits scoped delivery, reruns Integration Guard descriptors and fast-forwards the Parent ref before admitting dependent work.
  • Retired records: query status with the Parent slug as task_id to read the persisted batch identity, state and child progress in batch.record, including v1 serial records. This is read-only evidence; a missing Parent TaskRecord does not hide it or grant execution authority. retire_stale_batch explicitly retires active records. Resuming one refuses with batch_record_shape_retired; the serial runner and plan reconfirmation path are removed.

2. Batch Authority & Invariants

  • Explicit Entry & Single Authorization: Parent selection invokes start_unattended_batch directly; a standalone Task or Child uses single-task Enrollment. Critical-only and delivered-only Parents use native task gates and final observations without an empty batch grant. 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.
  • 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.
  • Deterministic Boundaries: Ordinary children use batch authorization; ready critical children use separate native Enrollment. Ordinary failures receive bounded repair. A blocker parks its dependent branch while independent work continues. Parent success and closure require every necessary delivery integrated and final verification passing on the final HEAD; later code defects receive a validated repair candidate and fresh native Enrollment. Runners never push, open PRs, or make arbitrary decisions.

3. Parallel Batch Lanes Lifecycle & Architecture

The Coordinator (Parent Host), runtime and Lane Executor Hosts coordinate isolated execution at every capacity:

sequenceDiagram
    participant P as Coordinator (Parent Host)
    participant B as Batch Runtime
    participant S as lane-steward Role
    participant L as Lane Executor Host (Pi / Claude)
    participant K as Lane Kernel (Isolated Store)

    Note over P,B: 1. Scheduling & Scope-Disjoint Analysis
    P->>B: start_unattended_batch(slug, max_parallel)
    Note over P,B: 2. Runtime Worktree Provisioning
    B->>B: Create dependency-ready Lane worktrees at Parent tip

    Note over P,L: 3. Supervised Lane Execution
    B-->>P: handoffs: Executor paths (up to confirmed capacity)
    P->>L: Launch background session for imm-run (configurable Host/model)
    L->>K: Run loop: Scope freeze -> Deterministic QA -> Review -> Settle

    Note over P,B: 4. Integration Guard & Fast-Forward
    L-->>P: Lane finish notification
    P->>B: Coordinator reconcile tick
    B->>K: Read Lane evidence & commit
    B->>B: Build candidate commit + rerun Integration Guard descriptors
    B->>B: Fast-forward batch branch (1 child 1 commit)
    B->>B: Remove clean idle Lane A; create next ready Lane
    B-->>P: integration report and next Executor handoffs

Core Mechanisms:

  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.
  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.
  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.
  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.
  5. Runtime-Owned Lifecycle: The runtime creates Lanes and removes clean, unoccupied Lane worktrees and branches after integration. Dirty Lanes are retained and reported. Agents never kill unrelated sessions or delete user work; legacy external-Lane records retain their existing release handoffs until drained.

Configuration

Immune-Brain has no separate config file. Preferences live in your host's agent instruction file at the repo root — AGENTS.md (Pi) or CLAUDE.md (Claude Code):

## Immune-Brain Preferences

- Initiative carrier default: github   # or: local
- Lane max parallel: 4                 # optional; default: one Lane at a time
- Lane Executor Host: claude-code      # optional; or: pi
- Lane Executor model: <model id>      # optional; needs Lane Executor Host
- Lane Executor effort: high           # optional; needs Lane Executor Host
Preference Options Default Notes
Reply language any natural language repo AGENTS.md Machine contracts / paths stay literal
Initiative carrier local / github none — Planner asks Only matters when a proposal splits across multiple TaskIntents
Advisory subagents allowed / solo allowed Respects Pi host policy + explicit user instruction
Lane max parallel integer ≥ 1 none — batches stay serial Passed as max_parallel when a batch starts; a resumed batch keeps its recorded value
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
Lane Executor model a model ID of that Host none — the Executor Host's own default Applies only when Lane Executor Host is set
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

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.

See docs/reference/immune-brain-config.md for details.


Project Layout

package.json                          # Pi package manifest (skills + extensions)
plugins/immune-brain/
├── .pi-extension/                    # Pi TUI + Kernel authority extension
├── skills/                           # 8 public Skills (trigger shims)
├── dist/                             # Built skill contracts & references
├── runtime/                          # Bun + TypeScript runtime & Kernel
└── bin/                              # CLI wrappers (→ runtime/v4_runtime.ts)

.imm/                                 # Task state (worktree-local, git-ignored)
docs/plans/                           # Active TaskIntents (*.intent.json)
docs/specs/                           # Living specs (updated in place)
  • .imm/state/ — active work; .imm/audit/<task-id>/ — settled evidence (tracked).
  • docs/plans/*.intent.json must be Git-tracked before enrollment.
  • CONTEXT.md is vocabulary / navigation only — not a runtime state source.

FAQ

Do I need to learn all 8 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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.


Release

This repo uses Changesets for versioning and publishing.

Task Command
Add a changeset bunx changeset — pick bump (patch/minor/major) and write summary
Bump version bun run changeset:version — updates package.json + CHANGELOG.md, then syncs and validates the Claude plugin manifest
Publish (local) bun run changeset:publish — validates manifest versions, then publishes to npm (needs NPM_TOKEN or npm login)

Automated flow (recommended):

  1. Push changesets to main → workflow opens a “Version Packages” PR.
  2. Merge that PR → workflow publishes to npm, creates GitHub Release, and tags immune-brain-vX.Y.Z.

Setup: add NPM_TOKEN (npm access token with publish permission) to GitHub repo secrets. Workflow is .github/workflows/release.yml using changesets/action@v1.

Manual publish (fallback):

npm publish --access public   # requires npm login / NPM_TOKEN
# or
bun run changeset:publish

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.

See CHANGELOG.md and .changeset/config.json (changelog: @changesets/changelog-github, repo: dereknex/immune-brain).


Development

For contributors working on Immune-Brain itself:

bun test                    # full test suite (canonical check is bun test, not tsc)
mise run check-plugin       # plugin structure + version
mise run check-dist-sync    # generated dist docs sync
  • Runtime is runtime/v4_runtime.ts (Bun + TypeScript). Python under scripts/ is reference-only.
  • Production CLI: plugins/immune-brain/bin/imm-kernel — see plugins/immune-brain/README.md for the full command table.

License: MIT