opencode-swarm 6.80.2 → 6.81.1

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.
package/README.md CHANGED
@@ -27,10 +27,10 @@ Most AI coding tools let one model write code and ask that same model whether th
27
27
  ### Key Features
28
28
 
29
29
  - 🏗️ **11 specialized agents** — architect, coder, reviewer, test engineer, critic, critic_sounding_board, critic_drift_verifier, explorer, SME, docs, designer
30
- - 🔒 **Gated pipeline** — code never ships without reviewer + test engineer approval (bypassed in turbo mode)
31
- - 🔄 **Phase completion gates** — completion-verify and drift verifier gates enforced before phase completion (bypassed in turbo mode)
30
+ - 🔒 **Gated pipeline** — code never ships without reviewer + test engineer approval
31
+ - 🔄 **Phase completion gates** — completion-verify and drift verifier gates enforced before phase completion
32
32
  - 🔁 **Resumable sessions** — all state saved to `.swarm/`; pick up any project any day
33
- - 🌐 **20 languages** — TypeScript, TSX, Python, Go, Rust, Java, Kotlin, C, C++, C#, Ruby, Swift, Dart, PHP, JavaScript, CSS, Bash, PowerShell, INI, Regex
33
+ - 🌐 **20 languages** — TypeScript, Python, Go, Rust, Java, Kotlin, C/C++, C#, Ruby, Swift, Dart, PHP, JavaScript, CSS, Bash, PowerShell, INI, Regex
34
34
  - 🛡️ **Built-in security** — SAST, secrets scanning, dependency audit per task
35
35
  - 🆓 **Free tier** — works with OpenCode Zen's free model roster
36
36
  - ⚙️ **Fully configurable** — override any agent's model, disable agents, tune guardrails
@@ -60,1458 +60,282 @@ Swarm then:
60
60
  * automated checks run
61
61
  * reviewer checks correctness
62
62
  * test engineer writes and runs tests
63
- * architect runs regression sweep (scope:"graph" to find cross-task test regressions)
63
+ * architect runs regression sweep
64
64
  * failures loop back with structured feedback
65
65
 
66
66
  7. After each phase, docs and retrospectives are updated.
67
67
 
68
- All project state lives in `.swarm/`:
69
-
70
- ```text
71
- .swarm/
72
- ├── plan.md # Projected plan (generated from ledger)
73
- ├── plan.json # Projected plan data (generated from ledger)
74
- ├── plan-ledger.jsonl # Durable append-only ledger — authoritative source of truth (v6.44)
75
- ├── SWARM_PLAN.md # Export checkpoint artifact written on save_plan / phase_complete / close
76
- ├── SWARM_PLAN.json # Export checkpoint artifact (importable via importCheckpoint)
77
- ├── context.md # Technical decisions and SME guidance
78
- ├── spec.md # Feature specification (written by /swarm specify)
79
- ├── close-summary.md # Written by /swarm close with project summary
80
- ├── close-lessons.md # Optional: explicit session lessons for /swarm close to curate
81
- ├── doc-manifest.json # Documentation index built by doc_scan tool
82
- ├── events.jsonl # Event stream for diagnostics
83
- ├── evidence/ # Review/test evidence bundles per task
84
- ├── telemetry.jsonl # Session observability events (JSONL)
85
- ├── curator-summary.json # Curator system state
86
- ├── curator-briefing.md # Curator init briefing injected at session start
87
- └── drift-report-phase-N.json # Plan-vs-reality drift reports (Curator)
88
- ```
89
-
90
- > **Plan durability (v6.44):** `plan-ledger.jsonl` is the authoritative source of truth for plan state. `plan.json` and `plan.md` are projections derived from the ledger — if they are missing or stale, `loadPlan()` auto-rebuilds them from the ledger. `SWARM_PLAN.md` / `SWARM_PLAN.json` are export-only checkpoint artifacts written automatically — use `SWARM_PLAN.json` to restore if both `plan.json` and the ledger are lost.
91
-
92
- Swarm is resumable by design. If `.swarm/` already exists, the architect goes straight into **RESUME** → **EXECUTE** instead of repeating discovery.
68
+ All project state lives in `.swarm/` — plans, evidence, context, knowledge, and telemetry. Resumable by design. If `.swarm/` already exists, the architect goes straight into **RESUME** → **EXECUTE** instead of repeating discovery.
93
69
 
94
70
  ---
95
71
 
96
- ## Quick Start
97
-
98
- > **Prerequisites:** [OpenCode](https://opencode.ai) installed and working. An API key for at least one LLM provider (or use the free OpenCode Zen tier — no key required).
99
-
100
- ### Step 1 — Install
101
-
102
- ```bash
103
- npm install -g opencode-swarm
104
- ```
105
-
106
- ### Step 2 — Open your project in OpenCode
107
-
108
- ```bash
109
- cd /your/project
110
- opencode
111
- ```
112
-
113
- ### Step 3 — Select a Swarm architect and describe your goal
72
+ ## Execution Modes
114
73
 
115
- 1. In the OpenCode GUI, open the **agent/mode dropdown** and select a **Swarm architect** (e.g., `architect`).
116
- 2. Type what you want to build:
117
-
118
- ```text
119
- Build a REST API with user registration, login, and JWT auth.
120
- ```
74
+ Swarm has two independent mode systems:
121
75
 
122
- That's it. The architect coordinates all other agents automatically.
76
+ **Session modes** toggle per session with a slash command:
123
77
 
124
- > **First time?** Run `/swarm diagnose` to verify Swarm is healthy, `/swarm agents` to see registered agents, and `/swarm config` to see the resolved configuration.
78
+ | Mode | Safety | Speed | When to Use |
79
+ |------|--------|-------|------------|
80
+ | **Balanced** (default) | High | Medium | Everyday development |
81
+ | **Turbo** | Medium | Fast | Rapid iteration; skips Stage B gates for non-Tier-3 files |
82
+ | **Full-Auto** | Depends on critic | Fast | Unattended multi-interaction runs |
125
83
 
126
- ### Step 4 Monitor progress
84
+ **Project mode**persistent via `execution_mode` config key:
127
85
 
128
- ```text
129
- /swarm status # Current phase and task
130
- /swarm plan # Full project plan
131
- /swarm evidence # Review and test results per task
132
- ```
86
+ | Value | Effect |
87
+ |-------|--------|
88
+ | `strict` | Maximum safety — adds slop-detector and incremental-verify hooks |
89
+ | `balanced` (default) | Standard hooks |
90
+ | `fast` | Skips compaction service — for short sessions under context pressure |
133
91
 
134
- ### Step 5 Start over if needed
92
+ Switch session modes with `/swarm turbo [on|off]` or `/swarm full-auto [on|off]`. Set project mode in config. The two systems compose independently — see [docs/modes.md](docs/modes.md).
135
93
 
136
- ```text
137
- /swarm reset --confirm
138
- ```
139
-
140
- ### Step 6 — Configure models (optional)
141
-
142
- Swarm works with its defaults out of the box. To override models, create `.opencode/opencode-swarm.json`:
94
+ ---
143
95
 
144
- ```json
145
- {
146
- "agents": {
147
- "coder": { "model": "opencode/minimax-m2.5-free" },
148
- "reviewer": { "model": "opencode/big-pickle" }
149
- }
150
- }
151
- ```
96
+ ## Quick Start
152
97
 
153
- You only need to specify the agents you want to override. The `architect` inherits the model currently selected in the OpenCode UI unless you set it explicitly.
98
+ **→ For a complete first-run walkthrough, see [Getting Started](docs/getting-started.md).**
154
99
 
155
- See the [full configuration reference](#configuration-reference) and the [free-tier model setup](#free-tier-opencode-zen-models) for more options.
100
+ The 15-minute guide covers:
101
+ - Installation (`bunx opencode-swarm install`)
102
+ - Selecting the architect in OpenCode
103
+ - Running your first task
104
+ - Troubleshooting common issues
156
105
 
157
- ### Step 7 — Performance modes (optional)
106
+ ---
158
107
 
159
- Swarm runs optional quality hooks (slop detection, incremental verification, compaction) on every tool call. For faster iteration, you can skip these:
108
+ ## Commands
160
109
 
161
- **Via slash command** (session-wide):
162
- ```
163
- /swarm turbo
164
- ```
110
+ All 41 subcommands at a glance:
165
111
 
166
- **Via config** (persistent):
167
- ```json
168
- {
169
- "execution_mode": "fast"
170
- }
112
+ ```bash
113
+ /swarm status # Current phase and task
114
+ /swarm plan [N] # Full plan or filtered by phase
115
+ /swarm agents # Registered agents and models
116
+ /swarm diagnose # Health check
117
+ /swarm evidence [task] # Test and review results
118
+ /swarm reset --confirm # Clear swarm state
171
119
  ```
172
120
 
173
- | Mode | Behavior |
174
- |------|----------|
175
- | `strict` | Runs all quality hooks (slop detector, incremental verify, compaction). Maximum safety, highest overhead. |
176
- | `balanced` (default) | Skips optional quality hooks. Recommended for most workflows. |
177
- | `fast` | Same as balanced. Reserved for future more aggressive optimizations. |
178
-
179
- Use `strict` mode for critical security-sensitive changes. Switch to `balanced` for routine development.
121
+ See [docs/commands.md](docs/commands.md) for the full reference (41 commands).
180
122
 
181
123
  ---
182
124
 
183
- ## Common First-Run Questions
184
-
185
- ### "Do I need to select a Swarm architect?"
186
-
187
- **Yes.** You must explicitly choose a Swarm architect agent in the OpenCode GUI before starting your session. If you use the default OpenCode `Build` / `Plan` options, the plugin is bypassed entirely.
188
-
189
- ### "Why did the second run start coding immediately?"
190
-
191
- Because Swarm persists state in `.swarm/` and resumes from where it left off. Check `/swarm status` or `/swarm plan`.
192
-
193
- ### "How do I know Swarm is really active?"
125
+ ## The Agents
194
126
 
195
- Run:
127
+ Swarm has 11 specialized agents. You don't manually switch between them — the architect coordinates automatically.
196
128
 
197
- ```text
198
- /swarm diagnose
199
- /swarm agents
200
- /swarm config
201
- ```
129
+ | Agent | Role |
130
+ |---|---|
131
+ | **architect** | Orchestrates workflow, writes plans, enforces gates |
132
+ | **coder** | Implements one task at a time |
133
+ | **reviewer** | Checks correctness and security |
134
+ | **test_engineer** | Writes and runs tests |
135
+ | **critic** | Reviews plans and challenges findings |
136
+ | **explorer** | Scans codebase and gathers context |
137
+ | **sme** | Provides domain expertise guidance |
138
+ | **docs** | Updates documentation to match implementation |
139
+ | **designer** | Generates UI scaffolds and design tokens |
140
+ | **critic_sounding_board** | Pre-escalation pushback to the architect |
141
+ | **critic_drift_verifier** | Verifies implementation matches plan |
142
+
143
+ Run `/swarm status` and `/swarm agents` to see what's active.
202
144
 
203
- ### "How do I force a clean restart?"
145
+ ---
204
146
 
205
- Run:
147
+ ## How It Compares
206
148
 
207
- ```text
208
- /swarm reset --confirm
209
- ```
149
+ | Feature | Swarm | oh-my-opencode | get-shit-done |
150
+ |---|:-:|:-:|:-:|
151
+ | Multiple specialized agents | ✅ 11 agents | ❌ | ❌ |
152
+ | Plan reviewed before coding | ✅ | ❌ | ❌ |
153
+ | Every task reviewed + tested | ✅ | ❌ | ❌ |
154
+ | Different model for review vs. code | ✅ | ❌ | ❌ |
155
+ | Resumable sessions | ✅ | ❌ | ❌ |
156
+ | Built-in security scanning | ✅ | ❌ | ❌ |
157
+ | Learns from mistakes | ✅ | ❌ | ❌ |
210
158
 
211
159
  ---
212
160
 
213
161
  ## LLM Provider Guide
214
162
 
215
- Swarm works with any LLM provider supported by OpenCode. Different agents benefit from different models — the architect needs strong reasoning, the coder needs strong code generation, and the reviewer benefits from a model different from the coder (to catch blind spots).
163
+ Swarm works with any provider supported by OpenCode.
216
164
 
217
- ### Free Tier OpenCode Zen Models {#free-tier-opencode-zen-models}
165
+ ### Free Tier (OpenCode Zen)
218
166
 
219
- OpenCode Zen provides free models via the `opencode/` provider prefix. These are excellent starting points and require no API key:
167
+ No API key required. Excellent starting point:
220
168
 
221
169
  ```json
222
170
  {
223
171
  "agents": {
224
- "coder": { "model": "opencode/minimax-m2.5-free" },
225
- "reviewer": { "model": "opencode/big-pickle" },
226
- "test_engineer":{ "model": "opencode/gpt-5-nano" },
227
- "explorer": { "model": "opencode/trinity-large-preview-free" },
228
- "sme": { "model": "opencode/trinity-large-preview-free" },
229
- "critic": { "model": "opencode/trinity-large-preview-free" },
230
- "docs": { "model": "opencode/trinity-large-preview-free" },
231
- "designer": { "model": "opencode/trinity-large-preview-free" }
172
+ "coder": { "model": "opencode/minimax-m2.5-free" },
173
+ "reviewer": { "model": "opencode/big-pickle" },
174
+ "explorer": { "model": "opencode/trinity-large-preview-free" }
232
175
  }
233
176
  }
234
177
  ```
235
178
 
236
- > Save this configuration to `.opencode/opencode-swarm.json` in your project root (or `~/.config/opencode/opencode-swarm.json` for global config).
237
-
238
- > **Note:** The `architect` key is intentionally omitted — it inherits whatever model you have selected in the OpenCode UI for maximum reasoning quality.
239
-
240
179
  ### Paid Providers
241
180
 
242
- For production use, mix providers to maximize quality across writing vs. reviewing:
181
+ For production, mix providers by role:
243
182
 
244
- | Agent | Recommended Model | Why |
183
+ | Agent | Recommended | Why |
245
184
  |---|---|---|
246
- | `architect` | OpenCode UI selection | Needs strongest reasoning |
247
- | `coder` | `minimax-coding-plan/MiniMax-M2.5` | Fast, accurate code generation |
248
- | `reviewer` | `zai-coding-plan/glm-5` | Different training data from coder |
249
- | `test_engineer` | `minimax-coding-plan/MiniMax-M2.5` | Same strengths as coder |
250
- | `explorer` | `google/gemini-2.5-flash` | Fast read-heavy analysis |
251
- | `sme` | `kimi-for-coding/k2p5` | Strong domain expertise |
252
- | `critic` | `zai-coding-plan/glm-5` | Independent plan review |
253
- | `docs` | `zai-coding-plan/glm-4.7-flash` | Fast, cost-effective documentation generation |
254
- | `designer` | `kimi-for-coding/k2p5` | Strong UI/UX generation capabilities |
185
+ | architect | OpenCode UI selection | Needs strongest reasoning |
186
+ | coder | minimax-coding-plan/MiniMax-M2.5 | Fast, accurate code generation |
187
+ | reviewer | zai-coding-plan/glm-5 | Different training from coder |
188
+ | test_engineer | minimax-coding-plan/MiniMax-M2.5 | Same strengths as coder |
189
+ | explorer | google/gemini-2.5-flash | Fast read-heavy analysis |
190
+ | sme | kimi-for-coding/k2p5 | Strong domain expertise |
255
191
 
256
192
  ### Provider Formats
257
193
 
258
194
  | Provider | Format | Example |
259
195
  |---|---|---|
260
- | OpenCode Zen (free) | `opencode/<model>` | `opencode/trinity-large-preview-free` |
261
- | Anthropic | `anthropic/<model>` | `anthropic/claude-opus-4-6` |
196
+ | OpenCode Zen | `opencode/<model>` | `opencode/trinity-large-preview-free` |
197
+ | Anthropic | `anthropic/<model>` | `anthropic/claude-sonnet-4-20250514` |
262
198
  | Google | `google/<model>` | `google/gemini-2.5-flash` |
263
199
  | Z.ai | `zai-coding-plan/<model>` | `zai-coding-plan/glm-5` |
264
200
  | MiniMax | `minimax-coding-plan/<model>` | `minimax-coding-plan/MiniMax-M2.5` |
265
201
  | Kimi | `kimi-for-coding/<model>` | `kimi-for-coding/k2p5` |
266
202
 
267
- ### Model Fallback (v6.33)
268
-
269
- When a transient model error occurs (rate limit, 429, 503, timeout, overloaded, model not found), Swarm can automatically switch to a fallback model.
203
+ ### Model Fallback
270
204
 
271
- **Configuration:**
205
+ Automatic fallback to a secondary model on transient errors:
272
206
 
273
207
  ```json
274
208
  {
275
209
  "agents": {
276
210
  "coder": {
277
- "model": "anthropic/claude-opus-4-6",
278
- "fallback_models": [
279
- "anthropic/claude-sonnet-4-5",
280
- "opencode/gpt-5-nano"
281
- ]
211
+ "model": "anthropic/claude-sonnet-4-20250514",
212
+ "fallback_models": ["opencode/gpt-5-nano"]
282
213
  }
283
214
  }
284
215
  }
285
216
  ```
286
217
 
287
- - **`fallback_models`** — Optional array of up to 3 fallback model identifiers. When the primary model fails with a transient error, Swarm injects a `MODEL FALLBACK` advisory and the next retry uses the next fallback model in the list.
288
- - **Advisory injection** — When a transient error is detected, a `MODEL FALLBACK` advisory is injected into the architect's context: *"Transient model error detected (attempt N). The agent model may be rate-limited, overloaded, or temporarily unavailable. Consider retrying with a fallback model or waiting before retrying."*
289
- - **Exhaustion guard** — After exhausting all fallbacks (`modelFallbackExhausted = true`), further transient errors do not spam additional advisories.
290
- - **Reset on success** — Both `model_fallback_index` and `modelFallbackExhausted` reset to 0/false on the next successful tool execution.
291
-
292
- ### Bounded Coder Revisions (v6.33)
293
-
294
- When a task requires multiple coder attempts (e.g., reviewer rejections), Swarm tracks how many times the coder has been re-delegated for the same task and warns when limits are approached.
295
-
296
- **Configuration:**
297
-
298
- ```json
299
- {
300
- "guardrails": {
301
- "max_coder_revisions": 5
302
- }
303
- }
304
- ```
305
-
306
- | Parameter | Type | Default | Description |
307
- |-----------|------|---------|-------------|
308
- | `max_coder_revisions` | integer | `5` | Maximum coder re-delegations per task before advisory warning (1–20) |
309
-
310
- **Behavior:**
311
- - **`coderRevisions` counter** — Incremented each time the coder delegation completes for the same task (reset on new task)
312
- - **`revisionLimitHit` flag** — Set when `coderRevisions >= max_coder_revisions`
313
- - **Advisory injection** — When the limit is hit, a `CODER REVISION LIMIT` advisory is injected: *"Agent has been revised N times (max: M) for task X. Escalate to user or consider a fundamentally different approach."*
314
- - **Persistence** — Both `coderRevisions` and `revisionLimitHit` are serialized/deserialized in session snapshots
315
-
316
- ## Useful Commands
317
-
318
- | Command | What It Does |
319
- |---------|-------------|
320
- | `/swarm status` | Where am I? Current phase, task progress |
321
- | `/swarm plan` | Show the full project plan |
322
- | `/swarm diagnose` | Health check for swarm state, including config parsing, grammar files, checkpoint manifest, events stream integrity, and steering directive staleness |
323
- | `/swarm evidence 2.1` | Show review/test results for a specific task |
324
- | `/swarm history` | What's been completed so far |
325
- | `/swarm close [--prune-branches]` | Idempotent session close-out: writes retrospectives, curates lessons (reads `.swarm/close-lessons.md` if present), archives evidence, resets `context.md`, cleans config-backup files, optionally prunes merged branches |
326
- | `/swarm reset --confirm` | Start over (clears all swarm state) |
327
-
328
- ---
329
-
330
- ## The Agents
331
-
332
- Swarm has specialized internal agents, but you do **not** manually switch into them during normal use.
333
-
334
- The **architect** is the coordinator. It decides when to invoke the other agents and what they should do.
335
-
336
- That means the normal user workflow is:
337
-
338
- 1. open the project in OpenCode
339
- 2. describe what you want built or changed
340
- 3. let Swarm coordinate the internal pipeline
341
- 4. inspect progress with `/swarm status`, `/swarm plan`, and `/swarm evidence`
342
-
343
- Agent roles (see [Agent Categories](#agent-categories) for classification reference):
344
-
345
- | Agent | Role | When It Runs |
346
- |---|---|---|
347
- | `architect` | Coordinates the workflow, writes plans, enforces gates | Always |
348
- | `explorer` | Scans the codebase and gathers context | Before planning, after phase wrap |
349
- | `sme` | Provides domain guidance | During planning / consultation |
350
- | `critic` | Reviews the plan before execution and blocks coding until approved | Before coding starts (CRITIC-GATE mode) |
351
- | `critic_sounding_board` | Pre-escalation pushback — the architect consults this before contacting the user; returns UNNECESSARY / REPHRASE / APPROVED / RESOLVE | When architect hits an impasse |
352
- | `critic_drift_verifier` | **Phase-close drift detector**: verifies that the completed implementation still matches the original plan spec. Returns APPROVED or NEEDS_REVISION. When NEEDS_REVISION is returned, the phase is **blocked** — the architect must address deviations before calling `phase_complete`. After receiving the verdict, the architect calls `write_drift_evidence` to record the gate result. Bypassed in turbo mode. | Before `phase_complete` (PHASE-WRAP mode) |
353
- | `coder` | Implements one task at a time | During execution |
354
- | `reviewer` | Reviews correctness and security; receives AST semantic diff summary with blast radius | After each task |
355
- | `test_engineer` | Writes and runs tests | After each task |
356
- | `designer` | Generates UI scaffolds and design tokens when needed | UI-specific work |
357
- | `docs` | Updates docs to match what was actually built | After each phase |
358
-
359
- If you want to see what is active right now, run:
360
-
361
- ```text
362
- /swarm status
363
- /swarm agents
364
- ```
365
-
366
- ---
367
-
368
- ## How It Compares
369
-
370
- | | OpenCode Swarm | oh-my-opencode | get-shit-done |
371
- |---|:-:|:-:|:-:|
372
- | Multiple specialized agents | ✅ 11 agents | ❌ Prompt config | ❌ Single-agent macros |
373
- | Plan reviewed before coding starts | ✅ | ❌ | ❌ |
374
- | Every task reviewed + tested | ✅ | ❌ | ❌ |
375
- | Different model for review vs. coding | ✅ | ❌ | ❌ |
376
- | Saves state to disk, resumable | ✅ | ❌ | ❌ |
377
- | Security scanning built in | ✅ | ❌ | ❌ |
378
- | Learns from its own mistakes | ✅ (retrospectives) | ❌ | ❌ |
379
-
380
- ---
381
-
382
- ## Agent Categories
383
-
384
- Agents are classified into four categories for the monitor server `/metadata` endpoint:
385
-
386
- | Category | Agents |
387
- |----------|--------|
388
- | `orchestrator` | architect |
389
- | `pipeline` | explorer, coder, test_engineer |
390
- | `qa` | reviewer, critic, critic_sounding_board, critic_drift_verifier |
391
- | `support` | sme, docs, designer |
392
-
393
- Use `getAgentCategory(agentName)` from `src/config/agent-categories.ts` to resolve an agent's category at runtime.
218
+ See [docs/configuration.md](docs/configuration.md) for full configuration reference.
394
219
 
395
220
  ---
396
221
 
397
222
  <details>
398
- <summary><strong>Full Execution Pipeline (Technical Detail)</strong></summary>
223
+ <summary><strong>Advanced Topics (Technical Detail)</strong></summary>
399
224
 
400
- ### The Pipeline
225
+ ### Process Remediation Model (PRM)
401
226
 
402
- Every task goes through this sequence. No exceptions, no overrides.
403
-
404
- ```
405
- MODE: EXECUTE (per task)
406
-
407
- ├── 5a. @coder implements (ONE task only)
408
- ├── 5b. diff + imports (contract + dependency analysis + semantic diff context)
409
- │ └── @system-enhancer injects AST-based semantic diff summary with blast radius
410
- │ into @reviewer context (up to 10 files, conditional on declared scope)
411
- ├── 5c. syntax_check (parse validation)
412
- ├── 5d. placeholder_scan (catches TODOs, stubs, incomplete code)
413
- ├── 5e. lint fix → lint check
414
- ├── 5f. build_check (does it compile?)
415
- ├── 5g. pre_check_batch (4 parallel: lint, secretscan, SAST, quality budget)
416
- ├── 5h. @reviewer (correctness pass)
417
- ├── 5i. @reviewer (security pass, if security-sensitive files changed)
418
- ├── 5j. @test_engineer (verification tests + coverage ≥70%)
419
- ├── 5k. @test_engineer (adversarial tests)
420
- ├── 5l. architect regression sweep (scope:"graph" to find cross-task test regressions)
421
- ├── 5l-ter. test drift detection (conditional — fires when changes involve command behaviour,
422
- │ parsing/routing logic, user-visible output, public contracts, assertion-heavy areas,
423
- │ or helper lifecycle changes; validates tests still align with current behaviour)
424
- ├── 5m. ⛔ Pre-commit checklist (all 4 items required, no override)
425
- └── 5n. Task marked complete, evidence written
426
- ```
227
+ Swarm monitors agent trajectories and injects course-correction guidance before loops form. Detects five failure patterns:
427
228
 
428
- If any step fails, the coder gets structured feedback and retries. After 5 failures on the same task, it escalates to you.
229
+ 1. **Repetition Loop** Same agent performs the same action repeatedly
230
+ 2. **Ping-Pong** — Agents hand off back and forth without progress
231
+ 3. **Expansion Drift** — Plan scope grows beyond original task
232
+ 4. **Stuck-on-Test** — Coder and tests fail in a loop
233
+ 5. **Context Thrashing** — Agent requests increasingly large file sets
429
234
 
430
- ### Architect Workflow Modes
431
-
432
- The architect moves through these modes automatically:
433
-
434
- | Mode | What It Means |
435
- |---|---|
436
- | `RESUME` | Existing `.swarm/` state was found, so Swarm continues where it left off |
437
- | `CLARIFY` | Swarm asks for missing information it cannot infer |
438
- | `DISCOVER` | Explorer scans the codebase; co-change dark matter analysis runs automatically to detect hidden file couplings (v6.41) |
439
- | `CONSULT` | SME agents provide domain guidance |
440
- | `PLAN` | Architect writes or updates the phased plan (includes CODEBASE REALITY CHECK on brownfield projects) |
441
- | `CRITIC-GATE` | Critic reviews the plan before execution |
442
- | `EXECUTE` | Tasks are implemented one at a time through the QA pipeline |
443
- | `PHASE-WRAP` | A phase closes out, including: explorer rescan, docs update, `context.md` update, `write_retro`, evidence check, `sbom_generate`, **`@critic_drift_verifier` delegation** (drift check — blocking gate), `write_drift_evidence` call with verdict, mandatory gate evidence verification (`completion-verify.json` + `drift-verifier.json` both required), then `phase_complete` |
444
-
445
- > **CODEBASE REALITY CHECK (v6.29.2):** Before any planning, the Architect dispatches Explorer to verify the current state of every referenced item. Produces a CODEBASE REALITY REPORT with statuses: NOT STARTED, PARTIALLY DONE, ALREADY COMPLETE, or ASSUMPTION INCORRECT. This prevents planning against stale assumptions. Skipped for greenfield projects with no existing codebase references.
446
-
447
- > **Phase Completion Gates (v6.33.4):** Before a phase can be marked complete, two mandatory gates are enforced: (1) completion-verify — deterministic check that plan task identifiers exist in source files, and (2) critic_drift_verifier evidence — verification that the drift verifier approved the implementation. Both gates are automatically bypassed when turbo mode is active.
448
-
449
- ### Important
450
-
451
- A second or later run does **not** necessarily look like a first run.
452
-
453
- If `.swarm/plan.md` already exists, the architect may enter `RESUME` and then go directly into `EXECUTE`. That is expected and does **not** mean Swarm stopped using agents.
454
-
455
- Use `/swarm status` if you are unsure what Swarm is doing.
456
-
457
- Release automation uses release-please and requires conventional commit prefixes such as `fix:` or `feat:` on changes merged to `main`.
458
-
459
- </details>
460
-
461
- <details>
462
- <summary><strong>Persistent Memory (What's in .swarm/)</strong></summary>
235
+ When detected, escalation levels trigger:
236
+ - Level 1: Advisory guidance injected
237
+ - Level 2: Architect alert sent
238
+ - Level 3: Hard stop directive
463
239
 
464
- ### plan.md: Your Project Roadmap
465
-
466
- ```markdown
467
- # Project: Auth System
468
- Current Phase: 2
469
-
470
- ## Phase 1: Foundation [COMPLETE]
471
- - [x] Task 1.1: Create user model [SMALL]
472
- - [x] Task 1.2: Add password hashing [SMALL]
473
- - [x] Task 1.3: Database migrations [MEDIUM]
474
-
475
- ## Phase 2: Core Auth [IN PROGRESS]
476
- - [x] Task 2.1: Login endpoint [MEDIUM]
477
- - [ ] Task 2.2: JWT generation [MEDIUM] (depends: 2.1) ← CURRENT
478
- - Acceptance: Returns valid JWT with user claims, 15-minute expiry
479
- - Attempt 1: REJECTED — missing expiration claim
480
- - [ ] Task 2.3: Token validation middleware [MEDIUM]
481
- ```
482
-
483
- ### context.md: What's Been Decided
484
-
485
- ```markdown
486
- ## Technical Decisions
487
- - bcrypt cost factor: 12
488
- - JWT TTL: 15 minutes; refresh TTL: 7 days
489
-
490
- ## SME Guidance (cached, never re-asked)
491
- ### security (Phase 1)
492
- - Never log tokens or passwords
493
- - Rate-limit login: 5 attempts / 15 min per IP
494
-
495
- ### api (Phase 1)
496
- - Return 401 for invalid credentials (not 404)
497
- ```
498
-
499
- ### Evidence Bundles
500
-
501
- Every completed task writes structured evidence to `.swarm/evidence/`:
502
-
503
- | Type | What It Captures |
504
- |------|--------------------|
505
- | review | Verdict, risk level, specific issues |
506
- | test | Pass/fail counts, coverage %, failure messages |
507
- | diff | Files changed, additions/deletions |
508
- | retrospective | Phase metrics, lessons learned, error taxonomy classification (injected into next phase) |
509
- | secretscan | Secret scan results: findings count, files scanned, skipped files (v6.33) |
510
- | completion-verify | Deterministic gate: verifies plan task identifiers exist in source files (written automatically by `completion-verify` tool; required before `phase_complete`) |
511
- | drift-verifier | Phase-close drift gate: `critic_drift_verifier` verdict (APPROVED/NEEDS_REVISION) and summary (written by architect via `write_drift_evidence`; required before `phase_complete`) |
512
-
513
- ### telemetry.jsonl: Session Observability
514
-
515
- Swarm emits structured JSONL events to `.swarm/telemetry.jsonl` for observability tooling (dashboards, alerting, audit logs). Events are fire-and-forget — failures never affect execution.
516
-
517
- ```json
518
- {"timestamp":"2026-03-25T14:30:00.000Z","event":"session_started","sessionId":"abc123","agentName":"architect"}
519
- {"timestamp":"2026-03-25T14:30:05.000Z","event":"delegation_begin","sessionId":"abc123","agentName":"coder","taskId":"1.1"}
520
- {"timestamp":"2026-03-25T14:31:00.000Z","event":"delegation_end","sessionId":"abc123","agentName":"coder","taskId":"1.1","result":"success"}
521
- {"timestamp":"2026-03-25T14:31:10.000Z","event":"gate_passed","sessionId":"abc123","gate":"reviewer","taskId":"1.1"}
522
- {"timestamp":"2026-03-25T14:32:00.000Z","event":"phase_changed","sessionId":"abc123","oldPhase":1,"newPhase":2}
523
- ```
524
-
525
- | Event | When Emitted |
526
- |-------|-------------|
527
- | `session_started` | New agent session created |
528
- | `session_ended` | Session ends (reason: normal, timeout, error) |
529
- | `agent_activated` | Agent identity confirmed via chat.message |
530
- | `delegation_begin` | Task dispatched to a sub-agent |
531
- | `delegation_end` | Sub-agent returns (success, rejected, error) |
532
- | `task_state_changed` | Task workflow state transitions |
533
- | `gate_passed` | Evidence written to `.swarm/evidence/{taskId}.json` |
534
- | `gate_failed` | Gate check blocked task completion |
535
- | `phase_changed` | Phase completed and new phase started |
536
- | `budget_updated` | Context budget crossed warning/critical threshold |
537
- | `hard_limit_hit` | Tool call/duration/repetition limit reached |
538
- | `revision_limit_hit` | Coder revision limit exceeded |
539
- | `loop_detected` | Repetitive tool call pattern detected |
540
- | `scope_violation` | Architect wrote outside declared scope |
541
- | `qa_skip_violation` | QA gate skipped without valid reason |
542
- | `model_fallback` | Transient error triggered model fallback |
543
- | `heartbeat` | 30-second throttled keep-alive signal |
544
-
545
- File rotates automatically at 10MB to `.swarm/telemetry.jsonl.1`.
546
-
547
- </details>
548
-
549
- <details>
550
- <summary><strong>Save Plan Tool: Target Workspace Requirement</strong></summary>
551
-
552
- The `save_plan` tool requires an explicit target workspace path. It does **not** fall back to `process.cwd()`.
553
-
554
- ### Explicit Workspace Requirement
555
-
556
- - The `working_directory` parameter must be provided
557
- - Providing no value or relying on implicit directory resolution will result in deterministic failure
558
-
559
- ### Failure Conditions
560
-
561
- | Condition | Behavior |
562
- |-----------|----------|
563
- | Missing (`undefined` / `null`) | Fails with: "Target workspace is required" |
564
- | Empty or whitespace-only | Fails with: "Target workspace cannot be empty or whitespace" |
565
- | Path traversal (`..`) | Fails with: "Target workspace cannot contain path traversal" |
566
-
567
- ### Usage Contract
568
-
569
- When using `save_plan`, always pass a valid `working_directory`:
570
-
571
- ```typescript
572
- save_plan({
573
- title: "My Project",
574
- swarm_id: "mega",
575
- phases: [{ id: 1, name: "Setup", tasks: [{ id: "1.1", description: "Initialize project" }] }],
576
- working_directory: "/path/to/project" // Required - no fallback
577
- })
578
- ```
579
-
580
- </details>
581
-
582
- <details>
583
- <summary><strong>Guardrails and Circuit Breakers</strong></summary>
584
-
585
- Every agent runs inside a circuit breaker that kills runaway behavior before it burns your credits.
586
-
587
- | Signal | Default Limit | What Happens |
588
- |--------|:---:|-------------|
589
- | Tool calls | 200 | Agent is stopped |
590
- | Duration | 30 min | Agent is stopped |
591
- | Same tool repeated | 10x | Agent is warned, then stopped |
592
- | Consecutive errors | 5 | Agent is stopped |
593
-
594
- Limits reset per task. A coder working on Task 2.3 is not penalized for tool calls made during Task 2.2.
595
-
596
- #### Architect Self-Coding Block
597
-
598
- If the architect writes files directly instead of delegating to the coder, a hard block fires:
599
-
600
- | Write count | Behavior |
601
- |:-----------:|----------|
602
- | 1–2 | Warning injected into next architect message |
603
- | ≥ 3 | `Error` thrown with `SELF_CODING_BLOCK` — identifies file paths written and count |
604
-
605
- The counter resets only when a coder delegation is dispatched. This is a hard enforcement — not advisory.
606
-
607
- Per-agent overrides:
608
-
609
- ```json
610
- {
611
- "guardrails": {
612
- "profiles": {
613
- "coder": { "max_tool_calls": 500, "max_duration_minutes": 60 },
614
- "explorer": { "max_tool_calls": 50 }
615
- }
616
- }
617
- }
618
- ```
619
-
620
- </details>
621
-
622
- <details>
623
- <summary><strong>File Authority (Per-Agent Write Permissions)</strong></summary>
624
-
625
- Swarm enforces per-agent file write authority — each agent can only write to specific paths. By default, these rules are hardcoded, but you can override them via config.
626
-
627
- ### Default Rules
628
-
629
- | Agent | Can Write | Blocked | Zones |
630
- |-------|-----------|---------|-------|
631
- | `architect` | Everything (except plan files) | `.swarm/plan.md`, `.swarm/plan.json` | `generated` |
632
- | `coder` | `src/`, `tests/`, `docs/`, `scripts/` | `.swarm/` (entire directory) | `generated`, `config` |
633
- | `reviewer` | `.swarm/evidence/`, `.swarm/outputs/` | `src/`, `.swarm/plan.md`, `.swarm/plan.json` | `generated` |
634
- | `test_engineer` | `tests/`, `.swarm/evidence/` | `src/`, `.swarm/plan.md`, `.swarm/plan.json` | `generated` |
635
- | `explorer` | Read-only | Everything | — |
636
- | `sme` | Read-only | Everything | — |
637
- | `docs` | `docs/`, `.swarm/outputs/` | — | `generated` |
638
- | `designer` | `docs/`, `.swarm/outputs/` | — | `generated` |
639
- | `critic` | `.swarm/evidence/` | — | `generated` |
640
-
641
- ### Prefixed Agents
642
-
643
- Prefixed agents (e.g., `paid_coder`, `mega_reviewer`, `local_architect`) inherit defaults from their canonical base agent via `stripKnownSwarmPrefix`. The lookup order is:
644
-
645
- 1. Exact match for the prefixed name (if explicitly defined in user config)
646
- 2. Fall back to the canonical agent's defaults (e.g., `paid_coder` → `coder`)
240
+ Configure via:
647
241
 
648
242
  ```json
649
243
  {
650
- "authority": {
651
- "rules": {
652
- "coder": { "allowedPrefix": ["src/", "lib/"] },
653
- "paid_coder": { "allowedPrefix": ["vendor/", "plugins/"] }
654
- }
655
- }
656
- }
657
- ```
658
-
659
- In this example, `paid_coder` gets its own explicit rule, while other prefixed coders (e.g., `mega_coder`) fall back to `coder`.
660
-
661
- ### Runtime Enforcement
662
-
663
- Architect direct writes are enforced at runtime via `toolBefore` hook. This tracks writes to source code paths outside `.swarm/` and protects `.swarm/plan.md` and `.swarm/plan.json` from direct modification.
664
-
665
- ### Configuration
666
-
667
- Override default rules in `.opencode/opencode-swarm.json`:
668
-
669
- ```json
670
- {
671
- "authority": {
244
+ "prm": {
672
245
  "enabled": true,
673
- "rules": {
674
- "coder": {
675
- "allowedPrefix": ["src/", "lib/", "scripts/"],
676
- "blockedPrefix": [".swarm/"],
677
- "blockedZones": ["generated"]
678
- },
679
- "explorer": {
680
- "readOnly": false,
681
- "allowedPrefix": ["notes/", "scratch/"]
682
- }
246
+ "pattern_thresholds": {
247
+ "repetition_loop": 2,
248
+ "ping_pong": 4,
249
+ "expansion_drift": 3,
250
+ "stuck_on_test": 3,
251
+ "context_thrash": 5
683
252
  }
684
253
  }
685
254
  }
686
255
  ```
687
256
 
688
- ### Rule Fields
257
+ > **Note:** Some configuration fields (`max_trajectory_lines`, `escalation_enabled`) are defined in schema but not yet enforced at runtime.
689
258
 
690
- | Field | Type | Description |
691
- |-------|------|-------------|
692
- | `readOnly` | boolean | If `true`, agent cannot write anywhere |
693
- | `blockedExact` | string[] | Exact file paths that are blocked |
694
- | `allowedExact` | string[] | Exact file paths that are allowed (overrides prefix/glob restrictions) |
695
- | `blockedPrefix` | string[] | Path prefixes that are blocked (e.g., `.swarm/`) |
696
- | `allowedPrefix` | string[] | Only these path prefixes are allowed. Omit to remove restriction; set `[]` to deny all |
697
- | `blockedGlobs` | string[] | Glob patterns that are blocked (uses picomatch: `**`, `*`, `?`) |
698
- | `allowedGlobs` | string[] | Glob patterns that are allowed (uses picomatch: `**`, `*`, `?`) |
699
- | `blockedZones` | string[] | File zones to block: `production`, `test`, `config`, `generated`, `docs`, `build` |
259
+ ### Persistent Memory
700
260
 
701
- ### Merge Behavior
261
+ **`.swarm/plan-ledger.jsonl`** authoritative source of truth (v6.44 durability model)
702
262
 
703
- - User rules **override** hardcoded defaults for the specified agent
704
- - Scalar fields (`readOnly`) — user value replaces default
705
- - Array fields (`blockedPrefix`, `allowedPrefix`, etc.) — user array **replaces** entirely (not merged)
706
- - If a field is omitted in the user rule for a **known agent** (one with hardcoded defaults), the default value for that field is preserved
707
- - If a field is omitted in the user rule for a **custom agent** (not in the defaults list), that field is `undefined` — there are no defaults to inherit
708
- - `allowedPrefix: []` explicitly denies all writes; omitting `allowedPrefix` entirely means no allowlist restriction is applied (all paths are evaluated against blocklist rules only)
709
- - Setting `enabled: false` ignores all custom rules and uses hardcoded defaults
263
+ **`.swarm/context.md`** technical decisions and cached SME guidance
710
264
 
711
- ### Custom Agents
265
+ **`.swarm/evidence/`** review/test results per task
712
266
 
713
- Custom agents (not in the defaults list) start with no rules. Their write authority depends entirely on what you configure:
267
+ **`.swarm/telemetry.jsonl`** session observability events (fire-and-forget, never blocks execution)
714
268
 
715
- - **Not in config at all** agent is denied with `Unknown agent` (no rule exists; this is not the same as "blocked from all writes")
716
- - **In config without `allowedPrefix`** — no allowlist restriction applies; only any `blockedPrefix`, `blockedZones`, or `readOnly` rules you explicitly set will enforce limits
717
- - **In config with `allowedPrefix: []`** — all writes are denied
269
+ **`.swarm/curator-summary.json`**phase-level intelligence and drift reports
718
270
 
719
- To safely restrict a custom agent, always set `allowedPrefix` explicitly:
271
+ ### Guardrails & Circuit Breakers
720
272
 
721
- ```json
722
- {
723
- "authority": {
724
- "rules": {
725
- "my_custom_agent": {
726
- "allowedPrefix": ["plugins/", "extensions/"],
727
- "blockedZones": ["generated"]
728
- }
729
- }
730
- }
731
- }
732
- ```
273
+ Every agent runs inside a circuit breaker that prevents runaway behavior:
733
274
 
734
- ### Advanced Examples
275
+ | Signal | Default Limit |
276
+ |--------|:---:|
277
+ | Tool calls | 200 |
278
+ | Duration | 30 min |
279
+ | Same tool repeated | 10x |
280
+ | Consecutive errors | 5 |
735
281
 
736
- #### Glob Pattern Support
282
+ Limits reset per task. Per-agent overrides available in config.
737
283
 
738
- Use glob patterns for complex path matching:
284
+ ### File Authority (Per-Agent Write Permissions)
739
285
 
740
- ```json
741
- {
742
- "authority": {
743
- "rules": {
744
- "coder": {
745
- "allowedGlobs": ["src/**/*.ts", "tests/**/*.test.ts"],
746
- "blockedGlobs": ["src/**/*.generated.ts", "**/*.d.ts"],
747
- "allowedExact": ["src/index.ts", "package.json"]
748
- },
749
- "docs_agent": {
750
- "allowedGlobs": ["docs/**/*.md", "*.md"],
751
- "blockedExact": [".swarm/plan.md"]
752
- }
753
- }
754
- }
755
- }
756
- ```
286
+ Each agent can only write to specific paths:
757
287
 
758
- **Glob Pattern Features:**
759
- - `**`Match any number of directories: `src/**/*.ts` matches all TypeScript files in src/ and subdirectories
760
- - `*`Match any characters except path separators: `*.md` matches all Markdown files in current directory
761
- - `?`Match single character: `test?.js` matches `test1.js`, `testa.js`
762
- - Uses [picomatch](https://github.com/micromatch/picomatch) for cross-platform compatibility
763
-
764
- **Path Normalization and Symlinks:**
765
- Paths are resolved via `realpathSync` before matching, which resolves symlinks and prevents path-traversal escapes. However, if a symlink's target does not exist, `realpathSync` throws and the fallback returns the symlink's own path (unresolved). A dangling symlink inside an `allowedPrefix` directory will therefore pass prefix-based checks even if its intended target is outside the project. Use `blockedExact` or `blockedGlobs` to deny known dangling-symlink paths explicitly.
766
-
767
- **Evaluation Order:**
768
- 1. `readOnly` check (if true, deny all writes)
769
- 2. `blockedExact` (exact path matches, highest priority)
770
- 3. `blockedGlobs` (glob pattern matches)
771
- 4. `allowedExact` (exact path matches, overrides prefix/glob restrictions)
772
- 5. `allowedGlobs` (glob pattern matches)
773
- 6. `blockedPrefix` (prefix matches)
774
- 7. `allowedPrefix` (prefix matches)
775
- 8. `blockedZones` (zone classification)
288
+ - **architect** Everything (except `.swarm/plan.md`, `.swarm/plan.json`)
289
+ - **coder** — `src/`, `tests/`, `docs/`, `scripts/`
290
+ - **reviewer**`.swarm/evidence/`
291
+ - **test_engineer** — `tests/`, `.swarm/evidence/`
292
+ - **explorer, sme** Read-only
776
293
 
777
- </details>
294
+ Override via `authority.rules` in config.
778
295
 
779
- <details>
780
- <summary><strong>Context Budget Guard</strong></summary>
781
-
782
- The Context Budget Guard monitors how much context Swarm is injecting into the conversation. It helps prevent context overflow before it becomes a problem.
783
-
784
- ### Default Behavior
785
-
786
- - **Enabled automatically** — No setup required. Swarm starts tracking context usage right away.
787
- - **What it measures** — Only the context that Swarm injects (plan, context, evidence, retrospectives). It does **not** count your chat history or the model's responses.
788
- - **Warning threshold (0.7 ratio)** — When swarm-injected context reaches ~2800 tokens (70% of 4000), the architect receives a one-time advisory warning. This is informational — execution continues normally.
789
- - **Critical threshold (0.9 ratio)** — When context reaches ~3600 tokens (90% of 4000), the architect receives a critical alert with a recommendation to run `/swarm handoff`. This is also one-time only.
790
- - **Non-nagging** — Alerts fire once per session, not repeatedly. You won't be pestered every turn.
791
- - **Who sees warnings** — Only the architect receives these warnings. Other agents are unaware of the budget.
792
-
793
- To disable entirely, set `context_budget.enabled: false` in your swarm config.
794
-
795
- ### Configuration Reference
796
-
797
- | Key | Type | Default | Description |
798
- |-----|------|---------|-------------|
799
- | `context_budget.enabled` | boolean | `true` | Enable or disable the context budget guard entirely |
800
- | `context_budget.max_injection_tokens` | number | `4000` | Token budget for swarm-injected context per turn. This is NOT the model's context window — it's the swarm plugin's own contribution |
801
- | `context_budget.warn_threshold` | number | `0.7` | Ratio (0.0-1.0) of `max_injection_tokens` that triggers a warning advisory |
802
- | `context_budget.critical_threshold` | number | `0.9` | Ratio (0.0-1.0) of `max_injection_tokens` that triggers a critical alert with handoff recommendation |
803
- | `context_budget.enforce` | boolean | `true` | When true, enforces budget limits and may trigger handoffs |
804
- | `context_budget.prune_target` | number | `0.7` | Ratio (0.0-1.0) of context to preserve when pruning occurs |
805
- | `context_budget.preserve_last_n_turns` | number | `4` | Number of recent turns to preserve when pruning |
806
- | `context_budget.recent_window` | number | `10` | Number of turns to consider as "recent" for scoring |
807
- | `context_budget.tracked_agents` | string[] | `['architect']` | Agents to track for context budget warnings |
808
- | `context_budget.enforce_on_agent_switch` | boolean | `true` | Enforce budget limits when switching agents |
809
- | `context_budget.model_limits` | record | `{ default: 128000 }` | Per-model token limits (model name -> max tokens) |
810
- | `context_budget.tool_output_mask_threshold` | number | `2000` | Threshold for masking tool outputs (chars) |
811
- | `context_budget.scoring.enabled` | boolean | `false` | Enable context scoring/ranking |
812
- | `context_budget.scoring.max_candidates` | number | `100` | Maximum items to score (10-500) |
813
- | `context_budget.scoring.weights` | object | `{ recency: 0.3, ... }` | Scoring weights for priority |
814
- | `context_budget.scoring.decision_decay` | object | `{ mode: 'exponential', half_life_hours: 24 }` | Decision relevance decay |
815
- | `context_budget.scoring.token_ratios` | object | `{ prose: 0.25, code: 0.4, ... }` | Token cost multipliers |
816
-
817
- ### Example Configurations
818
-
819
- **Minimal (disable):**
820
- ```json
821
- {
822
- "context_budget": {
823
- "enabled": false
824
- }
825
- }
826
- ```
296
+ ### Quality Gates
827
297
 
828
- **Default (reference):**
829
- ```json
830
- {
831
- "context_budget": {
832
- "enabled": true,
833
- "max_injection_tokens": 4000,
834
- "warn_threshold": 0.7,
835
- "critical_threshold": 0.9,
836
- "enforce": true,
837
- "prune_target": 0.7,
838
- "preserve_last_n_turns": 4,
839
- "recent_window": 10,
840
- "tracked_agents": ["architect"],
841
- "enforce_on_agent_switch": true,
842
- "model_limits": { "default": 128000 },
843
- "tool_output_mask_threshold": 2000,
844
- "scoring": {
845
- "enabled": false,
846
- "max_candidates": 100,
847
- "weights": { "recency": 0.3, "relevance": 0.4, "importance": 0.3 },
848
- "decision_decay": { "mode": "exponential", "half_life_hours": 24 },
849
- "token_ratios": { "prose": 0.25, "code": 0.4, "json": 0.6, "logs": 0.1 }
850
- }
851
- }
852
- }
853
- ```
298
+ Built-in tools verify every task before it ships:
854
299
 
855
- **Aggressive (for long-running sessions):**
856
- ```json
857
- {
858
- "context_budget": {
859
- "enabled": true,
860
- "max_injection_tokens": 2000,
861
- "warn_threshold": 0.5,
862
- "critical_threshold": 0.75,
863
- "enforce": true,
864
- "prune_target": 0.6,
865
- "preserve_last_n_turns": 2,
866
- "recent_window": 5,
867
- "tracked_agents": ["architect"],
868
- "enforce_on_agent_switch": true,
869
- "model_limits": { "default": 128000 },
870
- "tool_output_mask_threshold": 1500,
871
- "scoring": {
872
- "enabled": true,
873
- "max_candidates": 50,
874
- "weights": { "recency": 0.5, "relevance": 0.3, "importance": 0.2 },
875
- "decision_decay": { "mode": "linear", "half_life_hours": 12 },
876
- "token_ratios": { "prose": 0.2, "code": 0.35, "json": 0.5, "logs": 0.05 }
877
- }
878
- }
879
- }
880
- ```
881
-
882
- ### What This Does NOT Do
883
-
884
- - **Does NOT prune chat history** — Your conversation with the model is untouched
885
- - **Does NOT modify tool outputs** — What tools return is unchanged
886
- - **Does NOT block execution** — The guard is advisory only; it warns but never stops the pipeline
887
- - **Does NOT interact with compaction.auto** — Separate feature with separate configuration
888
- - **Only measures swarm's injected context** — Not the full context window, just what Swarm adds
889
-
890
- </details>
891
-
892
- <details>
893
- <summary><strong>Quality Gates (Technical Detail)</strong></summary>
300
+ - **syntax_check** Tree-sitter validation (12 languages)
301
+ - **placeholder_scan** — Catches TODOs, stubs, incomplete code
302
+ - **sast_scan** — 63+ security rules, 9 languages (offline)
303
+ - **sbom_generate** — Dependency tracking (CycloneDX)
304
+ - **quality_budget** — Complexity, duplication, test ratio limits
894
305
 
895
- ### Built-in Tools
306
+ All tools run locally. No Docker, no network calls.
896
307
 
897
- | Tool | What It Does |
898
- |------|-------------|
899
- | syntax_check | Tree-sitter validation across 12 languages |
900
- | placeholder_scan | Catches TODOs, FIXMEs, stubs, placeholder text |
901
- | sast_scan | Offline security analysis, 63+ rules, 9 languages |
902
- | sbom_generate | CycloneDX dependency tracking, 8 ecosystems |
903
- | build_check | Runs your project's native build/typecheck |
904
- | incremental_verify | Post-coder typecheck for TS/JS, Go, Rust, C# (v6.29.2) |
905
- | quality_budget | Enforces complexity, duplication, and test ratio limits |
906
- | pre_check_batch | Runs lint, secretscan, SAST, and quality budget in parallel (~15s vs ~60s sequential) |
907
- | phase_complete | Enforces phase completion, verifies required agents, requires a valid retrospective evidence bundle, logs events, and resets state; appends to `events.jsonl` with file locking |
308
+ ### Context Budget Guard
908
309
 
310
+ Monitors how much context Swarm injects to prevent overflow:
909
311
 
910
- All tools run locally. No Docker, no network calls, no external APIs.
312
+ - **Warning threshold (70%)** Advisory when context reaches ~2800 tokens
313
+ - **Critical threshold (90%)** — Alert at ~3600 tokens with `/swarm handoff` recommendation
314
+ - **Non-nagging** — One-time alerts per session
911
315
 
912
- Optional enhancement: Semgrep (if on PATH).
316
+ Disable entirely with `context_budget.enabled: false`.
913
317
 
914
- ### Gate Configuration
318
+ ### File Locking for Concurrent Safety
915
319
 
916
- ```json
917
- {
918
- "gates": {
919
- "syntax_check": { "enabled": true },
920
- "placeholder_scan": { "enabled": true },
921
- "sast_scan": { "enabled": true },
922
- "quality_budget": {
923
- "enabled": true,
924
- "max_complexity_delta": 5,
925
- "min_test_to_code_ratio": 0.3
926
- }
927
- }
928
- }
929
- ```
320
+ Hard lock on `plan.json` (serialized writes), advisory lock on `events.jsonl` (append-only log). Stale locks auto-expire via `proper-lockfile`.
930
321
 
931
322
  </details>
932
323
 
933
- <details>
934
- <summary><strong>File Locking for Concurrent Write Safety</strong></summary>
935
-
936
- Swarm uses file locking to protect shared state files from concurrent write corruption. The locking strategy differs by file: `plan.json` uses hard locking (write blocked on contention), while `events.jsonl` uses advisory locking (write proceeds with a warning on contention).
937
-
938
- ### Locking Implementation
939
-
940
- - **Library**: `proper-lockfile` with `retries: 0` (fail-fast — no polling retries)
941
- - **Scope**: Each tool acquires an exclusive lock on the target file before writing
942
- - **Agents**: Lock is tagged with the current agent name and task context for diagnostics
943
-
944
- ### Protected Files
945
-
946
- | File | Tool | Lock Key |
947
- |------|------|----------|
948
- | `.swarm/plan.json` | `update_task_status` | `plan.json` |
949
- | `.swarm/events.jsonl` | `phase_complete` | `events.jsonl` |
950
-
951
- ### Lock Semantics
952
-
953
- The two protected tools use different strategies:
954
-
955
- **`update_task_status` — Hard lock on `plan.json`**
956
-
957
- When two calls contend for `plan.json`:
958
- 1. **Exactly one call wins** — only the first to acquire the lock proceeds
959
- 2. **Winner writes** — the lock holder writes to the file, then releases the lock
960
- 3. **Losers receive `success: false`** — with `recovery_guidance: "retry"` and an error message identifying the lock holder
961
-
962
- ```json
963
- {
964
- "success": false,
965
- "message": "Task status write blocked: plan.json is locked by architect (task: update-task-status-1.1-1234567890)",
966
- "errors": ["Concurrent plan write detected — retry after the current write completes"],
967
- "recovery_guidance": "Wait a moment and retry update_task_status. The lock will expire automatically if the holding agent fails."
968
- }
969
- ```
970
-
971
- **What the caller should do**: Retry `update_task_status` after a short delay.
972
-
973
- **`phase_complete` — Advisory lock on `events.jsonl`**
974
-
975
- When two calls contend for `events.jsonl`:
976
- 1. **Lock is attempted** — if acquired, write is serialized
977
- 2. **If lock unavailable** — a warning is added to the result and the write proceeds anyway
978
- 3. **Both callers return `success: true`** — duplicate concurrent appends are possible but `events.jsonl` is an append-only log and duplicate phase entries do not corrupt state
979
-
980
- This asymmetry is intentional: `plan.json` stores mutable structured JSON where concurrent overwrites produce malformed files; `events.jsonl` is an append-only log where a duplicate entry is a recoverable nuisance.
981
-
982
- ### Lock Recovery
983
-
984
- If a lock-holding agent crashes or hangs, the lock file will eventually expire (handled by `proper-lockfile` stale-lock cleanup). On the next retry, the call will succeed. Swarm does not auto-retry on lock contention — the architect receives the error and decides when to retry.
985
-
986
- </details>
987
-
988
- <details>
989
- <summary id="configuration-reference"><strong>Full Configuration Reference</strong></summary>
990
-
991
- Config file location: `~/.config/opencode/opencode-swarm.json` (global) or `.opencode/opencode-swarm.json` (project). Project config merges over global.
992
-
993
- ```json
994
- {
995
- "agents": {
996
- "architect": { "model": "anthropic/claude-opus-4-6" },
997
- "coder": { "model": "minimax-coding-plan/MiniMax-M2.5", "fallback_models": ["minimax-coding-plan/MiniMax-M2.1"] },
998
- "explorer": { "model": "minimax-coding-plan/MiniMax-M2.1" },
999
- "sme": { "model": "kimi-for-coding/k2p5" },
1000
- "critic": { "model": "zai-coding-plan/glm-5" },
1001
- "reviewer": { "model": "zai-coding-plan/glm-5", "fallback_models": ["opencode/big-pickle"] },
1002
- "test_engineer": { "model": "minimax-coding-plan/MiniMax-M2.5" },
1003
- "docs": { "model": "zai-coding-plan/glm-4.7-flash" },
1004
- "designer": { "model": "kimi-for-coding/k2p5" }
1005
- },
1006
- "guardrails": {
1007
- "max_tool_calls": 200,
1008
- "max_duration_minutes": 30,
1009
- "profiles": {
1010
- "coder": { "max_tool_calls": 500 }
1011
- }
1012
- },
1013
- "authority": {
1014
- "enabled": true,
1015
- "rules": {
1016
- "coder": {
1017
- "allowedPrefix": ["src/", "lib/"],
1018
- "blockedPrefix": [".swarm/"],
1019
- "blockedZones": ["generated"]
1020
- }
1021
- }
1022
- },
1023
- "review_passes": {
1024
- "always_security_review": false,
1025
- "security_globs": ["**/*auth*", "**/*crypto*", "**/*session*"]
1026
- },
1027
- "automation": {
1028
- "mode": "manual",
1029
- "capabilities": {
1030
- "plan_sync": true,
1031
- "phase_preflight": false,
1032
- "config_doctor_on_startup": false,
1033
- "config_doctor_autofix": false,
1034
- "evidence_auto_summaries": true,
1035
- "decision_drift_detection": true
1036
- }
1037
- },
1038
- "knowledge": {
1039
- "enabled": true,
1040
- "swarm_max_entries": 100,
1041
- "hive_max_entries": 1000,
1042
- "auto_promote_days": 30,
1043
- "max_inject_count": 5,
1044
- "dedup_threshold": 0.6,
1045
- "scope_filter": ["global"],
1046
- "hive_enabled": true,
1047
- "rejected_max_entries": 200,
1048
- "validation_enabled": true,
1049
- "evergreen_confidence": 0.8,
1050
- "evergreen_utility": 0.5,
1051
- "low_utility_threshold": 0.2,
1052
- "min_retrievals_for_utility": 3,
1053
- "schema_version": "v6.17"
1054
- }
1055
- }
1056
- ```
1057
-
1058
- ### Automation
1059
-
1060
- ## Mode Detection (v6.13)
1061
-
1062
- Swarm now explicitly distinguishes five architect modes:
1063
-
1064
- - **`DISCOVER`** — After the explorer finishes scanning the codebase.
1065
- - **`PLAN`** — When the architect writes or updates the plan.
1066
- - **`EXECUTE`** — During task implementation (the normal pipeline).
1067
- - **`PHASE-WRAP`** — After all tasks in a phase are completed, before docs are updated.
1068
- - **`UNKNOWN`** — Fallback when the current state does not match any known mode.
1069
-
1070
- Each mode determines which injection blocks are added to the LLM prompt (e.g., plan cursor is injected in `PLAN`, tool output truncation in `EXECUTE`, etc.).
1071
-
1072
- Default mode: `manual`. No background automation — all actions require explicit slash commands.
1073
-
1074
- Modes:
1075
-
1076
- - `manual` — No background automation. All actions via slash commands (default).
1077
- - `hybrid` — Background automation for safe operations, manual for sensitive ones.
1078
- - `auto` — Full background automation.
1079
-
1080
- Capability defaults:
1081
-
1082
- - `plan_sync`: `true` — Background plan synchronization using `fs.watch` with debounced writes (300ms) and 2-second polling fallback
1083
- - `phase_preflight`: `false` — Phase preflight checks before agent execution (opt-in)
1084
- - `config_doctor_on_startup`: `false` — Validate configuration on startup
1085
- - `config_doctor_autofix`: `false` — Auto-fix for config doctor (opt-in, security-sensitive)
1086
- - `evidence_auto_summaries`: `true` — Automatic summaries for evidence bundles
1087
- - `decision_drift_detection`: `true` — Detect drift between planned and actual decisions
1088
-
1089
- ## Plan Cursor (v6.13)
1090
-
1091
- The `plan_cursor` config compresses the plan that is injected into the LLM context.
1092
-
1093
- ```json
1094
- {
1095
- "plan_cursor": {
1096
- "enabled": true,
1097
- "max_tokens": 1500,
1098
- "lookahead_tasks": 2
1099
- }
1100
- }
1101
- ```
1102
-
1103
- - **enabled** – When `true` (default) Swarm injects a compact plan cursor instead of the full `plan.md`.
1104
- - **max_tokens** – Upper bound on the number of tokens emitted for the cursor (default 1500). The cursor contains the current phase summary, the full current task, and up to `lookahead_tasks` upcoming tasks. Earlier phases are reduced to one‑line summaries.
1105
- - **lookahead_tasks** – Number of future tasks to include in full detail (default 2). Set to `0` to show only the current task.
1106
-
1107
- Disabling (`"enabled": false`) falls back to the pre‑v6.13 behavior of injecting the entire plan text.
1108
-
1109
- ## Tool Output Truncation (v6.13)
1110
-
1111
- Control the size of tool outputs that are sent back to the LLM.
1112
-
1113
- ```json
1114
- {
1115
- "tool_output": {
1116
- "truncation_enabled": true,
1117
- "max_lines": 150,
1118
- "per_tool": {
1119
- "diff": 200,
1120
- "symbols": 100
1121
- }
1122
- }
1123
- }
1124
- ```
1125
-
1126
- - **truncation_enabled** – Global switch (default true).
1127
- - **max_lines** – Default line limit for any tool output.
1128
- - **per_tool** – Overrides `max_lines` for specific tools. The `diff` and `symbols` tools are truncated by default because their outputs can be very large.
1129
-
1130
- When truncation is active, a footer is appended:
1131
-
1132
- ```
1133
- ---
1134
- [output truncated to {maxLines} lines – use `tool_output.per_tool.<tool>` to adjust]
1135
- ```
1136
-
1137
- ## Summarization Settings
1138
-
1139
- Control how tool outputs are summarized for LLM context.
1140
-
1141
- ```json
1142
- {
1143
- "summaries": {
1144
- "threshold_bytes": 102400,
1145
- "exempt_tools": ["retrieve_summary", "task", "read"]
1146
- }
1147
- }
1148
- ```
1149
-
1150
- - **threshold_bytes** – Output size threshold in bytes before summarization is triggered (default 102400 = 100KB).
1151
- - **exempt_tools** – Tools whose outputs are never summarized. Defaults to `["retrieve_summary", "task", "read"]` to prevent re-summarization loops.
1152
-
1153
- > **Note:** The `retrieve_summary` tool supports paginated retrieval via `offset` and `limit` parameters to fetch large summarized outputs in chunks.
1154
-
1155
- ---
1156
-
1157
- ### Disabling Agents
1158
-
1159
- ```json
1160
- {
1161
- "sme": { "disabled": true },
1162
- "designer": { "disabled": true },
1163
- "test_engineer": { "disabled": true }
1164
- }
1165
- ```
1166
-
1167
- </details>
1168
-
1169
- <details>
1170
- <summary><strong>All Slash Commands</strong></summary>
1171
-
1172
- | Command | Description |
1173
- |---------|-------------|
1174
- | `/swarm status` | Current phase, task progress, agent count |
1175
- | `/swarm plan [N]` | Full plan or filtered by phase |
1176
- | `/swarm agents` | Registered agents with models and permissions |
1177
- | `/swarm history` | Completed phases with status |
1178
- | `/swarm config` | Current resolved configuration |
1179
- | `/swarm diagnose` | Health check for `.swarm/` files and config |
1180
- | `/swarm export` | Export plan and context as portable JSON |
1181
- | `/swarm evidence [task]` | Evidence bundles for a task or all tasks |
1182
- | `/swarm archive [--dry-run]` | Archive old evidence with retention policy |
1183
- | `/swarm benchmark` | Performance benchmarks |
1184
- | `/swarm retrieve [id]` | Retrieve auto-summarized tool outputs (supports offset/limit pagination) |
1185
- | `/swarm reset --confirm` | Clear swarm state files |
1186
- | `/swarm reset-session` | Clear session state files in `.swarm/session/` (preserves plan and context) |
1187
- | `/swarm preflight` | Run phase preflight checks |
1188
- | `/swarm config doctor [--fix]` | Config validation with optional auto-fix |
1189
- | `/swarm doctor tools` | Tool registration coherence and binary readiness check |
1190
- | `/swarm sync-plan` | Force plan.md regeneration from plan.json |
1191
- | `/swarm specify [description]` | Generate or import a feature specification |
1192
- | `/swarm clarify [topic]` | Clarify and refine an existing feature specification |
1193
- | `/swarm analyze` | Analyze spec.md vs plan.md for requirement coverage gaps |
1194
- | `/swarm close [--prune-branches]` | Idempotent session close-out: retrospectives, lesson curation, evidence archive, context.md reset, config-backup cleanup, optional branch pruning |
1195
- | `/swarm write-retro` | Write a phase retrospective manually |
1196
- | `/swarm handoff` | Generate a handoff summary for context-budget-critical sessions |
1197
- | `/swarm simulate` | Simulate plan execution without writing code |
1198
- | `/swarm promote` | Promote swarm-scoped knowledge to hive (global) knowledge |
1199
- | `/swarm evidence summary` | Generate a summary across all evidence bundles with completion ratio and blockers |
1200
- | `/swarm knowledge` | List knowledge entries |
1201
- | `/swarm knowledge migrate` | Migrate knowledge entries to the current format |
1202
- | `/swarm knowledge quarantine [id]` | Move a knowledge entry to quarantine |
1203
- | `/swarm knowledge restore [id]` | Restore a quarantined knowledge entry |
1204
- | `/swarm turbo` | Enable turbo mode for the current session (bypasses QA gates) |
1205
- | `/swarm full-auto` | Toggle Full-Auto Mode for the current session [on|off] |
1206
- | `/swarm checkpoint` | Save a git checkpoint for the current state |
1207
-
1208
- </details>
1209
-
1210
- ---
1211
-
1212
- ## Role-Scoped Tool Filtering
1213
-
1214
- Swarm limits which tools each agent can access based on their role. This prevents agents from using tools that aren't appropriate for their responsibilities, reducing errors and keeping agents focused.
1215
-
1216
- ### Default Tool Allocations
1217
-
1218
- | Agent | Tools | Count | Rationale |
1219
- |-------|-------|:---:|-----------|
1220
- | **architect** | All registered tools | — | Orchestrator needs full visibility |
1221
- | **reviewer** | diff, imports, lint, pkg_audit, pre_check_batch, secretscan, symbols, complexity_hotspots, retrieve_summary, extract_code_blocks, test_runner, suggest_patch, batch_symbols | 13 | Security-focused QA |
1222
- | **coder** | diff, imports, lint, symbols, extract_code_blocks, retrieve_summary, search | 7 | Write-focused, minimal read tools |
1223
- | **test_engineer** | test_runner, diff, symbols, extract_code_blocks, retrieve_summary, imports, complexity_hotspots, pkg_audit, search | 9 | Testing and verification |
1224
- | **explorer** | complexity_hotspots, detect_domains, extract_code_blocks, gitingest, imports, retrieve_summary, schema_drift, symbols, todo_extract, search, batch_symbols | 11 | Discovery and analysis |
1225
- | **sme** | complexity_hotspots, detect_domains, extract_code_blocks, imports, retrieve_summary, schema_drift, symbols | 7 | Domain expertise research |
1226
- | **critic** | complexity_hotspots, detect_domains, imports, retrieve_summary, symbols | 5 | Plan review, minimal toolset |
1227
- | **docs** | detect_domains, doc_extract, doc_scan, extract_code_blocks, gitingest, imports, retrieve_summary, schema_drift, symbols, todo_extract | 10 | Documentation synthesis and discovery |
1228
- | **designer** | extract_code_blocks, retrieve_summary, symbols | 3 | UI-focused, minimal toolset |
1229
-
1230
- ### Configuration
1231
-
1232
- Tool filtering is enabled by default. Customize it in your config:
1233
-
1234
- ```json
1235
- {
1236
- "tool_filter": {
1237
- "enabled": true,
1238
- "overrides": {
1239
- "coder": ["diff", "imports", "lint", "symbols", "test_runner"],
1240
- "reviewer": ["diff", "secretscan", "sast_scan", "symbols"]
1241
- }
1242
- }
1243
- }
1244
- ```
1245
-
1246
- | Option | Type | Default | Description |
1247
- |--------|------|---------|-------------|
1248
- | `enabled` | boolean | `true` | Enable tool filtering globally |
1249
- | `overrides` | Record<string, string[]> | `{}` | Per-agent tool whitelist. Empty array denies all tools. |
1250
-
1251
- ### Troubleshooting: Agent Missing a Tool
1252
-
1253
- If an agent reports it doesn't have access to a tool it needs:
1254
-
1255
- 1. Check if the tool is in the agent's default allocation (see table above)
1256
- 2. Add a custom override in your config:
1257
-
1258
- ```json
1259
- {
1260
- "tool_filter": {
1261
- "overrides": {
1262
- "coder": ["diff", "imports", "lint", "symbols", "extract_code_blocks", "retrieve_summary", "test_runner"]
1263
- }
1264
- }
1265
- }
1266
- ```
1267
-
1268
- 3. To completely disable filtering for all agents:
1269
-
1270
- ```json
1271
- {
1272
- "tool_filter": {
1273
- "enabled": false
1274
- }
1275
- }
1276
- ```
1277
-
1278
- ### Available Tools Reference
1279
-
1280
- The following tools can be assigned to agents via overrides:
1281
-
1282
- | Tool | Purpose |
1283
- |------|---------|
1284
- | `batch_symbols` | Extract exported symbols from multiple files in a single call; per-file error isolation; 75–98% call reduction vs sequential (v6.45); registered for architect, explorer, reviewer |
1285
- | `checkpoint` | Save/restore git checkpoints |
1286
- | `check_gate_status` | Read-only query of task gate status |
1287
- | `co_change_analyzer` | Scan git history for files that co-change frequently; generates dark matter architecture knowledge entries during DISCOVER mode (v6.41); architect-only |
1288
- | `complexity_hotspots` | Identify high-risk code areas |
1289
- | `declare_scope` | Pre-declare the file scope for the next coder delegation (architect-only); violations trigger warnings |
1290
- | `detect_domains` | Detect SME domains from text |
1291
- | `diff` | Analyze git diffs and changes |
1292
- | `doc_extract` | Extract actionable constraints from project documentation relevant to current task (Jaccard bigram scoring + dedup) |
1293
- | `doc_scan` | Scan project documentation and build index manifest at `.swarm/doc-manifest.json` (mtime-based caching) |
1294
- | `evidence_check` | Verify task evidence |
1295
- | `extract_code_blocks` | Extract code from markdown |
1296
- | `gitingest` | Ingest external repositories |
1297
- | `imports` | Analyze import relationships |
1298
- | `lint` | Run project linters |
1299
- | `phase_complete` | Enforces phase completion, verifies required agents, logs events, resets state; appends to `events.jsonl` with file locking |
1300
- | `pkg_audit` | Security audit of dependencies |
1301
- | `pre_check_batch` | Parallel pre-checks (lint, secrets, SAST, quality) |
1302
- | `retrieve_summary` | Retrieve summarized tool outputs |
1303
- | `save_plan` | Persist plan to `.swarm/plan.json`, `plan.md`, and ledger; also writes `SWARM_PLAN.md` / `SWARM_PLAN.json` checkpoint artifacts; requires explicit `working_directory` parameter |
1304
- | `schema_drift` | Detect OpenAPI/schema drift |
1305
- | `search` | Workspace-scoped ripgrep-style structured text search; literal and regex modes, glob filtering, result limits (v6.45); registered for architect, coder, reviewer, explorer, test_engineer |
1306
- | `secretscan` | Scan for secrets in code |
1307
- | `suggest_patch` | Generate contextual diff hunks without modifying files; read-only patch suggestions for reviewer→coder handoff (v6.45); registered for reviewer and architect |
1308
- | `symbols` | Extract exported symbols |
1309
- | `test_runner` | Run project tests |
1310
- | `update_task_status` | Mark plan tasks as pending/in_progress/completed/blocked; track phase progress; acquires lock on `plan.json` before writing |
1311
- | `todo_extract` | Extract TODO/FIXME comments |
1312
- | `write_retro` | Document phase retrospectives via the phase_complete workflow; capture lessons learned |
1313
- | `write_drift_evidence` | Write drift verification evidence after critic_drift_verifier completes; architect calls this after receiving the verifier’s verdict — the critic does not write files directly |
1314
-
1315
324
  ---
1316
325
 
1317
- <details>
1318
- <summary><strong>Recent Changes (v6.12 – v6.31+)</strong></summary>
1319
-
1320
- > For the complete version history, see [CHANGELOG.md](CHANGELOG.md) or [docs/releases/](docs/releases/).
1321
-
1322
- ### v6.47.0 — `/swarm close` Full Session Close-Out
1323
-
1324
- - **`/swarm close` expanded**: Now performs complete close-out: resets `context.md`, deletes stale `config-backup-*.json` files, supports plan-free sessions (PR reviews, investigations), and accepts `--prune-branches` to delete local branches whose remote tracking ref is `gone` (merged/deleted upstream).
1325
- - **Lesson injection**: If `.swarm/close-lessons.md` exists when `/swarm close` runs, the architect’s explicit lessons are curated into the knowledge base before the file is deleted.
1326
-
1327
- ### v6.45.0 — New Search, Patch, and Batch Tools
1328
-
1329
- - **`search` tool**: Workspace-scoped ripgrep-style structured search with literal/regex modes and glob filtering. Registered for architect, coder, reviewer, explorer, test_engineer.
1330
- - **`suggest_patch` tool**: Reviewer-safe context-anchored patch suggestion. Generates diff hunks without writing files. Registered for reviewer and architect.
1331
- - **`batch_symbols` tool**: Batched symbol extraction from multiple files in one call; per-file error isolation; 75–98% call reduction vs sequential single-file calls. Registered for architect, explorer, reviewer.
1332
- - **Step 5l-ter**: Test drift detection step added to the EXECUTE pipeline. Fires conditionally when changes involve command behaviour, parsing/routing logic, user-visible output, public contracts, assertion-heavy areas, or helper lifecycle changes.
1333
-
1334
- ### v6.44.0 — Durable Plan Ledger
1335
-
1336
- - **`plan-ledger.jsonl`**: Append-only JSONL ledger is now the authoritative source of truth for plan state. `plan.json` and `plan.md` are projections derived from the ledger. `loadPlan()` auto-rebuilds projections from the ledger on hash mismatch.
1337
- - **Checkpoint artifacts**: `writeCheckpoint()` writes `SWARM_PLAN.md` and `SWARM_PLAN.json` at the project root on every `save_plan`, `phase_complete`, and `/swarm close`. Use `SWARM_PLAN.json` to restore after data loss.
1338
- - **Auto-generated tool lists**: Architect prompt `YOUR TOOLS` and `Available Tools` sections are now generated from `AGENT_TOOL_MAP.architect` — no more hand-maintained lists that drift.
1339
- - See [docs/plan-durability.md](docs/plan-durability.md) for migration notes.
1340
-
1341
- ### v6.42.0 — Curator LLM Delegation Wired
1342
-
1343
- - **Curator now performs real LLM analysis**: Previously the LLM delegation was scaffolded but never connected — every call fell through to data-only mode. All three call sites now invoke the Explorer agent with curator-specific system prompts.
1344
- - **`curator.enabled` now defaults to `true`**: The curator falls back gracefully to data-only mode when no SDK client is available (e.g., in unit tests). If you relied on the previous `false` default, set `"curator": { "enabled": false }` explicitly.
1345
-
1346
- ### v6.41.0 — Dark Matter Detection + `/swarm close` + Drift Evidence Tool
1347
-
1348
- - **Dark matter detection pipeline**: During DISCOVER mode, automatically scans git history for files that frequently co-change. Results are stored as `architecture` knowledge entries and the architect is guided to consider co-change partners when declaring scope. Silently skips repos with fewer than 20 commits or no git history.
1349
- - **`/swarm close` command**: New idempotent close command. Writes retrospectives for in-progress phases, curates session lessons via the knowledge pipeline, archives evidence, marks phases/tasks as `closed`, writes `.swarm/close-summary.md`, and cleans state.
1350
- - **`write_drift_evidence` tool**: New architect tool for persisting drift verification evidence after critic_drift_verifier delegation
1351
- - Accepts phase number, verdict (APPROVED/NEEDS_REVISION), and summary
1352
- - Normalizes verdict automatically (APPROVED → approved, NEEDS_REVISION → rejected)
1353
- - Writes gate-contract formatted evidence to `.swarm/evidence/{phase}/drift-verifier.json`
1354
-
1355
- ### v6.31.0 — process.cwd() Cleanup + Watchdog + Knowledge Tools
1356
-
1357
- - **process.cwd() cleanup**: All 14 source files now use plugin-injected `directory` parameter. Five tools migrated to `createSwarmTool` wrapper.
1358
- - **`curator_analyze` tool**: Architect can now explicitly trigger phase analysis and apply curator recommendations.
1359
- - **Watchdog system**: `scope_guard` (blocks out-of-scope writes), `delegation_ledger` (tracks per-session tool calls), and loop-detector escalation.
1360
- - **Self-correcting workflow**: `self_review` advisory hook after task transitions; `checkStaleImports` heuristic for unused import detection.
1361
- - **Knowledge memory tools**: `knowledge_recall`, `knowledge_add`, `knowledge_remove` — any agent can now directly access the persistent knowledge base.
1362
-
1363
- ### v6.30.1 — Bug Fixes
1364
-
1365
- - **Package manager detection**: `incremental_verify` now detects bun/npm/pnpm/yarn from lockfiles instead of always using `bun`.
1366
- - **spawnAsync OOM fix**: 512KB output cap prevents infinite-output commands from OOM-crashing.
1367
- - **Windows spawn fix**: `npx.cmd`, `npm.cmd`, `pnpm.cmd`, `yarn.cmd` resolved correctly on Windows.
1368
- - **Curator config fix**: `applyCuratorKnowledgeUpdates` now receives fully-populated `KnowledgeConfig`.
1369
- - **Rehydration race guard**: Concurrent `loadSnapshot` calls no longer silently drop workflow state.
1370
-
1371
- ### v6.29.4 — Cross-Task Regression Sweep
1372
-
1373
- - **Regression sweep**: Architect dispatches `scope:"graph"` test runs after each task to catch cross-task regressions (found 15 in RAGAPPv2 retrospective).
1374
- - **Curator data pipeline**: Curator outputs now visible to the architect via advisory injection.
1375
- - **Full-suite opt-in**: Explicit flag unlocks full `bun test` execution when needed.
1376
-
1377
- ### v6.29.3 — Curator Visibility + Documentation Refresh
1378
-
1379
- - **Curator status in diagnose**: `/swarm diagnose` now reports whether Curator is enabled/disabled and validates `curator-summary.json`.
1380
- - **README and config docs refreshed**: Updated `.swarm/` directory tree, Curator configuration options, and drift report artifacts.
1381
-
1382
- ### v6.29.2 — Multi-Language Incremental Verify + Slop-Detector Hardening
1383
-
1384
- - **Multi-language incremental_verify**: Post-coder typecheck supports TypeScript/JavaScript, Go, Rust, and C#.
1385
- - **Slop-detector hardening**: Multi-language heuristics for placeholder code detection across Go/Rust/C#/Python.
1386
- - **CODEBASE REALITY CHECK**: Explorer verifies referenced items before planning (NOT STARTED / PARTIALLY DONE / ALREADY COMPLETE / ASSUMPTION INCORRECT).
1387
- - **Evidence schema fix**: Evidence bundles now correctly validate against schema.
1388
-
1389
- ### v6.29.1 — Advisory Hook Message Injection
1390
-
1391
- - **Advisory hook message injection**: Enhanced message formatting for self-coding detection, partial gate tracking, batch detection, and scope violation warnings.
1392
-
1393
- ### v6.26 through v6.28 — Session Durability + Turbo Mode
1394
-
1395
- - **Turbo Mode**: Accelerated task delegation for faster pipeline execution.
1396
- - **Session durability**: Directory-based evidence writes, task ID recovery from `plan.json` for cold/resumed sessions.
1397
- - **Gate recovery fix** (v6.26.1): `update_task_status(completed)` no longer blocks pure-verification tasks without a prior coder delegation.
1398
-
1399
- ### v6.22 — Curator Background Analysis + Session State Persistence
1400
-
1401
- This release adds the optional Curator system for phase-level intelligence and fixes session snapshot persistence for task workflow states.
1402
-
1403
- - **Curator system**: Background analysis system (`curator.enabled = false` by default in v6.22; **changed to `true` in v6.42**). After each phase, collects events, checks compliance, and writes drift reports to `.swarm/drift-report-phase-N.json`. Three integration points: init on first phase, phase analysis after each phase, and drift injection into architect context at phase start.
1404
- - **Drift reports**: `runCriticDriftCheck` compares planned vs. actual decisions and writes structured drift reports with alignment scores (`ALIGNED` / `MINOR_DRIFT` / `MAJOR_DRIFT` / `OFF_SPEC`). Latest drift summary is prepended to the architect's knowledge context each phase.
1405
- - **Issue #81 fix — taskWorkflowStates persistence**: Session snapshots now correctly serialize and restore the per-task state machine. Invalid state values are filtered to `idle` on deserialization. `reconcileTaskStatesFromPlan` seeds task states from `plan.json` on snapshot load (completed → `tests_run`, in-progress → `coder_delegated`).
1406
-
1407
- See the [Curator section](#curator) above for configuration details and the [v6.22 release notes](docs/releases/v6.22.0.md) for the full change list.
1408
-
1409
- ### v6.21 — Gate Enforcement Hardening
1410
-
1411
- This release replaces soft advisory warnings with hard runtime blocks and adds structural compliance tooling for all model tiers.
1412
-
1413
- #### Phase 1 — P0 Bug Fixes: Hard Blocks Replace Soft Warnings
1414
-
1415
- - **`qaSkipCount` reset fixed**: The skip-detection counter in `delegation-gate.ts` now resets only when **both** reviewer **and** test_engineer have been seen since the last coder entry — not when either one runs alone.
1416
- - **`update_task_status` reviewer gate check**: Accepting `status='completed'` now validates that the reviewer gate is present in the session's `gateLog` for the given task. Missing reviewer returns a structured error naming the absent gate.
1417
- - **Architect self-coding hard block**: `architectWriteCount ≥ 3` now throws an `Error` with message `SELF_CODING_BLOCK` (previously a warning only). Counts 1–2 remain advisory warnings. Counter resets on coder delegation.
1418
-
1419
- #### Phase 2 — Per-Task State Machine
1420
-
1421
- Every task now has a tracked workflow state in the session:
1422
-
1423
- | State | Meaning |
1424
- |-------|---------|
1425
- | `idle` | Task not started |
1426
- | `coder_delegated` | Coder has received the delegation |
1427
- | `pre_check_passed` | Automated gates (lint, SAST, secrets, quality) passed |
1428
- | `reviewer_run` | Reviewer agent has returned a verdict |
1429
- | `tests_run` | Test engineer has completed (verification + adversarial) |
1430
- | `complete` | `update_task_status` accepted the `completed` transition |
1431
-
1432
- Transitions are forward-only. `advanceTaskState()` throws `INVALID_TASK_STATE_TRANSITION` if an illegal jump is attempted. `getTaskState()` returns `'idle'` for unknown tasks.
1433
-
1434
- `session.lastGateOutcome` records the most recent gate result: `{ gate, taskId, passed, timestamp }`.
1435
-
1436
- #### Phase 3 — State Machine Integration
1437
-
1438
- - `update_task_status` now uses the state machine (not a raw `gateLog.has()` check): `status='completed'` is rejected unless the task is in `'tests_run'` or `'complete'` state.
1439
- - `delegation-gate.ts` protocol-violation check additionally verifies that the prior task's state has advanced past `'coder_delegated'` before allowing a new coder delegation.
1440
-
1441
- #### Phase 4 — Context Engineering
1442
-
1443
- - **Progressive task disclosure**: When >5 tasks are visible in the last user message, `delegation-gate.ts` trims to the current task ± a context window. A `[Task window: showing N of M tasks]` comment marks the trim point.
1444
- - **Deliberation preamble**: Each architect turn is prefixed with `[Last gate: {tool} {result} for task {taskId}]` sourced from `session.lastGateOutcome`, prompting the architect to identify the single next step.
1445
- - **Low-capability model detection**: `LOW_CAPABILITY_MODELS` constant (matches substrings `mini`, `nano`, `small`, `free`) and `isLowCapabilityModel(modelId)` helper added to `constants.ts`.
1446
- - **Behavioral guidance markers**: Three `<!-- BEHAVIORAL_GUIDANCE_START --> … <!-- BEHAVIORAL_GUIDANCE_END -->` pairs wrap the BATCHING DETECTION, ARCHITECT CODING BOUNDARIES, and QA gate behavioral sections in the architect prompt.
1447
- - **Tier-based prompt trimming**: When `session.activeModel` matches `isLowCapabilityModel()`, the behavioral guidance blocks are stripped from the architect prompt and replaced with `[Enforcement: programmatic gates active]`. Programmatic enforcement substitutes for verbose prompt instructions on smaller models.
1448
-
1449
- #### Phase 5 — Structural Scope Declaration (`declare_scope`)
1450
-
1451
- New architect-only tool and supporting runtime enforcement:
1452
-
1453
- - **`declare_scope` tool**: Pre-declares which files the coder is allowed to modify for a given task. Input: `{ taskId, files, whitelist?, working_directory? }`. Validates task ID format, plan membership, and non-`complete` state. On success, sets `session.declaredCoderScope`. Architect-only.
1454
- - **Automatic scope from FILE: directives**: When a coder delegation is detected, `delegation-gate.ts` extracts FILE: directive values and stores them as `session.declaredCoderScope` automatically — no explicit `declare_scope` call required.
1455
- - **Scope containment tracking**: `guardrails.ts` appends every file the architect writes to `session.modifiedFilesThisCoderTask`. On coder delegation start, the list resets to `[]`.
1456
- - **Violation detection**: After a coder task completes, `toolAfter` compares `modifiedFilesThisCoderTask` against `declaredCoderScope`. If >2 files are outside the declared scope, `session.lastScopeViolation` is set. The next architect message receives a scope violation warning.
1457
- - **`isInDeclaredScope(filePath, scopeEntries)`**: Module-level helper using `path.resolve()` + `path.relative()` for proper directory containment (not string matching).
1458
-
1459
- ### v6.13.2 — Pipeline Enforcement
1460
-
1461
- This release adds enforcement-layer tooling and self-healing guardrails:
1462
-
1463
- - **`phase_complete` tool**: Verifies all required agents were dispatched before a phase closes; emits events to `.swarm/events.jsonl`; configurable `enforce`/`warn` policy
1464
- - **Summarization loop fix**: `exempt_tools` config prevents `retrieve_summary` and `task` outputs from being re-summarized (fixes Issue #8)
1465
- - **Same-model adversarial detection**: Warns when coder and reviewer share the same model; `warn`/`gate`/`ignore` policy
1466
- - **Architect test guardrail (HF-1b)**: Prevents architect from running full `bun test` suite — must target specific files one at a time
1467
- - **Docs**: `docs/swarm-briefing.md` (LLM pipeline briefing), Task Field Reference in `docs/planning.md`
1468
-
1469
- ### v6.13.1 — Consolidation & Defaults Fix
1470
-
1471
- - **`consolidateSystemMessages`**: Merges multiple system messages into one at index 0
1472
- - **Test isolation helpers**: `createIsolatedTestEnv` and `assertSafeForWrite`
1473
- - **Coder self-verify guardrail (HF-1)**: Coder and test_engineer agents blocked from running build/test/lint
1474
- - **`/swarm` template fix**: `{{arguments}}` → `$ARGUMENTS`
1475
- - **DEFAULT_MODELS update**: `claude-sonnet-4-5` → `claude-sonnet-4-20250514`, `gemini-2.0-flash` → `gemini-2.5-flash`
1476
-
1477
- ### v6.13.0 — Context Efficiency
1478
-
1479
- This release focuses on reducing context usage and improving mode-conditional behavior:
1480
-
1481
- - **Role-Scoped Tool Filtering**: Agent tools filtered via AGENT_TOOL_MAP
1482
- - **Plan Cursor**: Compressed plan summary under 1,500 tokens
1483
- - **Mode Detection**: DISCOVER/PLAN/EXECUTE/PHASE-WRAP/UNKNOWN modes
1484
- - **Tool Output Truncation**: diff/symbols outputs truncated with footer
1485
- - **ZodError Fixes**: Optional current_phase, 'completed' status support
1486
-
1487
- ### v6.12.0 — Anti-Process-Violation Hardening
1488
-
1489
- This release adds runtime detection hooks to catch and warn about architect workflow violations:
1490
-
1491
- - **Self-coding detection**: Warns when the architect writes code directly instead of delegating
1492
- - **Partial gate tracking**: Detects when QA gates are skipped
1493
- - **Self-fix detection**: Warns when an agent fixes its own gate failure (should delegate to fresh agent)
1494
- - **Batch detection**: Catches "implement X and add Y" batching in task requests
1495
- - **Zero-delegation detection**: Warns when tasks complete without any coder delegation; supports parsing delegation envelopes from JSON or KEY: VALUE text format for validation.
1496
-
1497
- These hooks are advisory (warnings only) and help maintain workflow discipline during long sessions.
1498
-
1499
- ### v6.19 — Critic Sounding Board + Complexity-Scaled Review
326
+ ## Supported Languages
1500
327
 
1501
- - **Critic sounding board**: Before escalating to the user, the Architect consults the critic in SOUNDING_BOARD mode. Returns: UNNECESSARY, REPHRASE, APPROVED, or RESOLVE.
1502
- - **Escalation discipline**: Three-tier hierarchy self-resolve → critic consult → user escalation (requires critic APPROVED).
1503
- - **Retry circuit breaker**: After 3 coder rejections, the Architect simplifies the approach instead of adding more logic.
1504
- - **Intent reconstruction**: Reviewer reconstructs developer intent from task specs and diffs before evaluating changes.
1505
- - **Complexity-scaled review**: TRIVIAL → Tier 1 only; MODERATE → Tiers 1–2; COMPLEX → all three tiers.
1506
- - **`meta.summary` convention**: Agents include one-line summaries in state events for downstream agent consumption.
328
+ Full Tier-1 support: TypeScript, JavaScript, Python, Go, Rust
329
+ Tier-2 support: Java, Kotlin, C#, C/C++, Swift
330
+ Tier-3 support: Dart, Ruby, PHP/Laravel
1507
331
 
1508
- </details>
332
+ All binaries optional. Missing tools produce soft warnings, never hard-fail.
1509
333
 
1510
334
  ---
1511
335
 
1512
336
  ## Testing
1513
337
 
1514
- 6,000+ tests. Unit, integration, adversarial, and smoke. Zero additional test dependencies.
338
+ 6,000+ tests. Unit, integration, adversarial, and smoke. Run with:
1515
339
 
1516
340
  ```bash
1517
341
  bun test
@@ -1521,139 +345,26 @@ bun test
1521
345
 
1522
346
  ## Design Principles
1523
347
 
1524
- 1. **Plan before code.** The critic approves the plan before a single line is written.
1525
- 2. **One task at a time.** The coder gets one task and full context. Nothing else.
348
+ 1. **Plan before code.** Critic approves the plan before a single line is written.
349
+ 2. **One task at a time.** Coder gets one task and full context. Nothing else.
1526
350
  3. **Review everything immediately.** Correctness, security, tests, adversarial tests. Every task.
1527
- 4. **Different models catch different bugs.** The coder's blind spot is the reviewer's strength.
1528
- 5. **Save everything to disk.** Any session, any model, any day, pick up where you left off.
1529
- 6. **Document failures.** Rejections and retries are recorded. After 5 failures, it escalates to you.
1530
-
1531
- ---
1532
-
1533
- ## Supported Languages
1534
-
1535
- OpenCode Swarm v6.46+ ships with language profiles for 12 languages across three quality tiers. All tools use graceful degradation — if a binary is not on PATH, the tool skips with a soft warning rather than a hard failure.
1536
-
1537
- | Language | Tier | Syntax | Build | Test | Lint | Audit | SAST |
1538
- |---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
1539
- | TypeScript / JavaScript | 1 | ✅ | ✅ | ✅ | ✅ Biome / ESLint | ✅ npm audit | ✅ Semgrep |
1540
- | Python | 1 | ✅ | ✅ | ✅ pytest | ✅ ruff | ✅ pip-audit | ✅ Semgrep |
1541
- | Rust | 1 | ✅ | ✅ | ✅ cargo test | ✅ clippy | ✅ cargo audit | ✅ Semgrep |
1542
- | Go | 1 | ✅ | ✅ | ✅ go test | ✅ golangci-lint | ✅ govulncheck | ✅ Semgrep |
1543
- | Java | 2 | ✅ | ✅ Gradle / Maven | ✅ JUnit | ✅ Checkstyle | — | ✅ Semgrep |
1544
- | Kotlin | 2 | ✅ | ✅ Gradle | ✅ JUnit | ✅ ktlint | — | 🔶 Semgrep beta |
1545
- | C# / .NET | 2 | ✅ | ✅ dotnet build | ✅ dotnet test | ✅ dotnet format | ✅ dotnet list | ✅ Semgrep |
1546
- | C / C++ | 2 | ✅ | ✅ cmake / make | ✅ ctest | ✅ cppcheck | — | 🔶 Semgrep exp. |
1547
- | Swift | 2 | ✅ | ✅ swift build | ✅ swift test | ✅ swiftlint | — | 🔶 Semgrep exp. |
1548
- | Dart / Flutter | 3 | ✅ | ✅ dart pub | ✅ dart test | ✅ dart analyze | ✅ dart pub outdated | — |
1549
- | Ruby | 3 | ✅ | — | ✅ RSpec / minitest | ✅ RuboCop | ✅ bundle-audit | 🔶 Semgrep exp. |
1550
- | PHP / Laravel | 3 | ✅ | ✅ Composer install | ✅ PHPUnit / Pest / artisan test | ✅ Pint / PHP-CS-Fixer | ✅ composer audit | ✅ 10+ native rules |
1551
-
1552
- > **PHP + Laravel baseline**: PHP v6.49+ ships with deterministic Laravel project detection (multi-signal: `artisan` file, `laravel/framework` dependency, `config/app.php`). When detected, commands are automatically overridden to `php artisan test`, Pint formatting, and PHPStan static analysis. Laravel-specific SAST rules cover SQL injection via raw queries, mass-assignment vulnerabilities, and destructive migrations without rollback. `.blade.php` files are included in all scanning pipelines.
1553
-
1554
- **Tier definitions:**
1555
- - **Tier 1** — Full pipeline: all tools integrated and tested end-to-end.
1556
- - **Tier 2** — Strong coverage: most tools integrated; some optional (audit, SAST).
1557
- - **Tier 3** — Basic coverage: core tools integrated; advanced tooling limited.
1558
-
1559
- > All binaries are optional. Missing tools produce a soft warning and skip — the pipeline never hard-fails on a missing linter or auditor.
1560
-
1561
- ---
1562
-
1563
- ## Curator
1564
-
1565
- The Curator is a background analysis system that runs after each phase. It is **enabled by default** as of v6.42 (`curator.enabled = true`) and never blocks execution — all Curator operations are wrapped in try/catch. It falls back gracefully to data-only mode when no SDK client is available.
1566
-
1567
- Since v6.42, the Curator performs real LLM analysis by delegating to the Explorer agent with curator-specific prompts. Before v6.42, the LLM delegation was scaffolded but never wired.
1568
-
1569
- To disable, set `"curator": { "enabled": false }` in your config. When enabled, it writes `.swarm/curator-summary.json`, `.swarm/curator-briefing.md`, and `.swarm/drift-report-phase-N.json` files.
1570
-
1571
- ### What the Curator Does
1572
-
1573
- - **Init** (`phase-monitor.ts`): On the first phase, initializes a curator summary file at `.swarm/curator-summary.json` and persists the init briefing to `.swarm/curator-briefing.md`.
1574
- - **Phase analysis** (`phase-complete.ts`): After each phase completes, collects phase events, checks compliance, and optionally invokes the curator explorer to summarize findings.
1575
- - **Compliance surfacing** (`phase-complete.ts`): Compliance observations are surfaced in the return value's warnings array (unless `suppress_warnings` is true).
1576
- - **Knowledge updates** (`phase-complete.ts`): Merges curator findings into the knowledge base up to the configured `max_summary_tokens` cap.
1577
- - **Briefing injection** (`knowledge-injector.ts`): The curator-briefing.md content is injected into the architect's context at session start.
1578
- - **Drift injection** (`knowledge-injector.ts`): Prepends the latest drift report summary to the architect's knowledge context at phase start, up to `drift_inject_max_chars` characters. Drift reports now inject even when no knowledge entries exist.
1579
-
1580
- ### Configuration
1581
-
1582
- Add a `curator` block to `.opencode/opencode-swarm.json`:
1583
-
1584
- ```json
1585
- {
1586
- "curator": {
1587
- "enabled": true,
1588
- "init_enabled": true,
1589
- "phase_enabled": true,
1590
- "max_summary_tokens": 2000,
1591
- "min_knowledge_confidence": 0.7,
1592
- "compliance_report": true,
1593
- "suppress_warnings": true,
1594
- "drift_inject_max_chars": 500
1595
- }
1596
- }
1597
- ```
1598
-
1599
- | Field | Default | Description |
1600
- |-------|---------|-------------|
1601
- | `enabled` | `true` | Master switch. Set to `false` to disable the Curator pipeline. |
1602
- | `init_enabled` | `true` | Initialize curator summary on first phase (requires `enabled: true`). |
1603
- | `phase_enabled` | `true` | Run phase analysis and knowledge updates after each phase. |
1604
- | `max_summary_tokens` | `2000` | Maximum token budget for curator knowledge summaries. |
1605
- | `min_knowledge_confidence` | `0.7` | Minimum confidence threshold for curator knowledge entries. |
1606
- | `compliance_report` | `true` | Include phase compliance check results in curator summary. |
1607
- | `suppress_warnings` | `true` | Suppress non-critical curator warnings from the architect context. |
1608
- | `drift_inject_max_chars` | `500` | Maximum characters of drift report text injected into each phase context. |
1609
-
1610
- ### Drift Reports
1611
-
1612
- Drift reports are written to `.swarm/drift-report-phase-N.json` after each phase. The `knowledge-injector.ts` hook reads the latest report and prepends a summary to the architect's knowledge context for the next phase, helping the architect stay aware of plan vs. reality divergence.
1613
-
1614
- ### Issue #81 Hotfix — taskWorkflowStates Persistence
1615
-
1616
- v6.22 includes a fix for session snapshot persistence of per-task workflow states:
1617
-
1618
- - **`SerializedAgentSession.taskWorkflowStates`**: Task workflow states are now serialized as `Record<string, string>` in session snapshots and deserialized back to a `Map` on load. Invalid state values are filtered out and default to `idle`.
1619
- - **`reconcileTaskStatesFromPlan`**: On snapshot load, task states are reconciled against the current plan — tasks marked `completed` in the plan are seeded to `tests_run` state, and `in_progress` tasks are seeded to `coder_delegated` if currently `idle`. This is best-effort and never throws.
1620
-
1621
- See [CHANGELOG.md](CHANGELOG.md) for shipped features.
1622
-
1623
- ---
1624
-
1625
- ## FAQ
1626
-
1627
- ### Do I need to select a Swarm architect?
1628
-
1629
- **Yes.** You must explicitly choose a Swarm architect agent in the OpenCode GUI before starting your session. The architect name shown in OpenCode is config-driven — you can define multiple architects with different model assignments in your configuration.
1630
-
1631
- If you use the default OpenCode `Build` / `Plan` options without selecting a Swarm architect, the plugin is bypassed entirely.
1632
-
1633
- ### Why did Swarm start coding immediately on my second run?
1634
- Because Swarm resumes from `.swarm/` state when it exists. Check `/swarm status` to see the current mode.
1635
-
1636
- ### How do I know which agents and models are active?
1637
- Run `/swarm agents` and `/swarm config`.
1638
-
1639
- ### How do I start over?
1640
- Run `/swarm reset --confirm`.
351
+ 4. **Different models catch different bugs.** Blind spots of the coder are the reviewer's strength.
352
+ 5. **Save everything to disk.** Resume any project any day from `.swarm/` state.
353
+ 6. **Document failures.** Rejections and retries recorded. After 5 failures, escalate to you.
1641
354
 
1642
355
  ---
1643
356
 
1644
357
  ## Documentation
1645
358
 
1646
- - [Documentation Index](docs/index.md)
1647
- - [Getting Started](docs/getting-started.md)
1648
- - [Architecture Deep Dive](docs/architecture.md)
1649
- - [Design Rationale](docs/design-rationale.md)
1650
- - [Plan Durability & Ledger](docs/plan-durability.md)
1651
- - [Installation Guide](docs/installation.md)
1652
- - [Linux + Docker Desktop Install Guide](docs/installation-linux-docker.md)
1653
- - [LLM Operator Installation Guide](docs/installation-llm-operator.md)
1654
- - [Pre-Swarm Planning Guide](docs/planning.md)
1655
- - [Swarm Briefing for LLMs](docs/swarm-briefing.md)
1656
- - [Configuration](docs/configuration.md)
359
+ - [Getting Started](docs/getting-started.md) — 15-minute first-run guide
360
+ - [Documentation Index](docs/index.md) — navigate all docs
361
+ - [Installation Guide](docs/installation.md) — comprehensive reference
362
+ - [Architecture Deep Dive](docs/architecture.md) — control model, pipeline, tools
363
+ - [Design Rationale](docs/design-rationale.md) — why every major decision
364
+ - [Commands Reference](docs/commands.md) — all 41 `/swarm` subcommands
365
+ - [Modes Guide](docs/modes.md) — session modes (Turbo, Full-Auto) and project modes (strict/balanced/fast)
366
+ - [Configuration](docs/configuration.md) — all config keys and examples
367
+ - [Planning Guide](docs/planning.md) — task format, phase structure, sizing
1657
368
 
1658
369
  ---
1659
370