opencode-swarm-plugin 0.6.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,586 +3,252 @@
3
3
  [![npm version](https://img.shields.io/npm/v/opencode-swarm-plugin.svg)](https://www.npmjs.com/package/opencode-swarm-plugin)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
 
6
- Multi-agent swarm coordination for [OpenCode](https://opencode.ai) with learning capabilities, beads integration, and Agent Mail.
6
+ Multi-agent swarm coordination for [OpenCode](https://opencode.ai). Break complex tasks into parallel subtasks, spawn agents, coordinate via messaging. The plugin learns from outcomes to improve future decompositions.
7
7
 
8
- ## Overview
9
-
10
- This plugin provides intelligent, self-improving tools for multi-agent workflows in OpenCode:
11
-
12
- - **Type-safe beads operations** - Zod-validated wrappers around the `bd` CLI with proper error handling
13
- - **Agent Mail integration** - File reservations, async messaging, and thread coordination between agents
14
- - **Structured outputs** - Reliable JSON responses with schema validation and retry support
15
- - **Swarm primitives** - Task decomposition, status tracking, and parallel agent coordination
16
- - **Learning from outcomes** - Confidence decay, implicit feedback scoring, and pattern maturity tracking
17
- - **Anti-pattern detection** - Automatically learns what decomposition strategies fail and avoids them
18
- - **Pre-completion validation** - UBS bug scanning before marking tasks complete
19
- - **History-informed decomposition** - Queries CASS for similar past tasks to inform strategy
20
- - **Graceful degradation** - Works with whatever tools are available, degrades features when tools missing
21
- - **Swarm discipline** - Enforces beads tracking, aggressive planning, and agent communication
22
-
23
- ## Installation
8
+ ## Install
24
9
 
25
10
  ```bash
26
- npm install opencode-swarm-plugin
27
- # or
28
- bun add opencode-swarm-plugin
29
- # or
30
- pnpm add opencode-swarm-plugin
11
+ npm install -g opencode-swarm-plugin
12
+ swarm setup
31
13
  ```
32
14
 
33
- Copy the plugin to your OpenCode plugins directory:
15
+ That's it. The setup wizard handles everything:
34
16
 
35
- ```bash
36
- cp node_modules/opencode-swarm-plugin/dist/plugin.js ~/.config/opencode/plugin/swarm.js
17
+ ```
18
+ opencode-swarm-plugin v0.9.0
19
+
20
+ ◇ Checking dependencies...
21
+
22
+ ◆ OpenCode
23
+ ◆ Beads
24
+ ◆ Go
25
+ ▲ Agent Mail (optional)
26
+ ▲ Redis (optional)
27
+
28
+ ◆ Install optional dependencies?
29
+ │ ◻ Agent Mail - Multi-agent coordination
30
+ │ ◻ Redis - Rate limiting
31
+
32
+ ◇ Setting up OpenCode integration...
33
+
34
+ ◆ Plugin: ~/.config/opencode/plugins/swarm.ts
35
+ ◆ Command: ~/.config/opencode/commands/swarm.md
36
+ ◆ Agent: ~/.config/opencode/agents/swarm-planner.md
37
+
38
+ └ Setup complete!
37
39
  ```
38
40
 
39
- Plugins are automatically loaded from `~/.config/opencode/plugin/` - no config file changes needed.
41
+ Then in your project:
40
42
 
41
- > **Note:** The package has two entry points:
42
- >
43
- > - `dist/index.js` - Full library exports (schemas, errors, utilities, learning modules)
44
- > - `dist/plugin.js` - Plugin entry point that only exports the `plugin` function for OpenCode
43
+ ```bash
44
+ cd your-project
45
+ swarm init
46
+ ```
45
47
 
46
- ## Prerequisites
48
+ ## CLI
47
49
 
48
- | Requirement | Purpose |
49
- | ---------------- | ------------------------------------------- |
50
- | OpenCode 1.0+ | Plugin host |
51
- | Agent Mail MCP | Multi-agent coordination (`localhost:8765`) |
52
- | Beads CLI (`bd`) | Git-backed issue tracking |
50
+ ```
51
+ swarm setup Interactive installer - checks and installs all dependencies
52
+ swarm doctor Health check - shows status of all dependencies
53
+ swarm init Initialize beads in current project
54
+ swarm version Show version
55
+ swarm help Show help
56
+ ```
53
57
 
54
- ### Verify Agent Mail is running
58
+ ### swarm doctor
55
59
 
56
- ```bash
57
- curl http://127.0.0.1:8765/health/liveness
60
+ ```
61
+ ┌ swarm doctor v0.9.0
62
+
63
+ ◇ Required dependencies:
64
+
65
+ ◆ OpenCode v1.0.134
66
+ ◆ Beads v0.29.0
67
+
68
+ ◇ Optional dependencies:
69
+
70
+ ◆ Go v1.25.2 - Required for Agent Mail
71
+ ▲ Agent Mail - not found
72
+ ◆ Redis - Rate limiting
73
+
74
+ └ All required dependencies installed. 1 optional missing.
58
75
  ```
59
76
 
60
- ### Verify beads is installed
77
+ ### swarm init
61
78
 
62
- ```bash
63
- bd --version
79
+ ```
80
+ ┌ swarm init v0.9.0
81
+
82
+ ◇ Initializing beads...
83
+ ◆ Created .beads/ directory
84
+
85
+ ◆ Create your first bead?
86
+ │ ● Yes / ○ No
87
+
88
+ ◇ Bead title: Implement user authentication
89
+ ◇ Type: Feature
90
+
91
+ └ Project initialized!
64
92
  ```
65
93
 
66
- ## Tools Reference
67
-
68
- ### Beads Tools
69
-
70
- | Tool | Description |
71
- | ------------------- | ------------------------------------------------------------------- |
72
- | `beads_create` | Create a new bead with type-safe validation |
73
- | `beads_create_epic` | Create epic with subtasks in one atomic operation |
74
- | `beads_query` | Query beads with filters (replaces `bd list`, `bd ready`, `bd wip`) |
75
- | `beads_update` | Update bead status/description/priority |
76
- | `beads_close` | Close a bead with reason |
77
- | `beads_start` | Mark bead as in-progress (shortcut) |
78
- | `beads_ready` | Get next ready bead (unblocked, highest priority) |
79
- | `beads_sync` | Sync beads to git and push (MANDATORY at session end) |
80
- | `beads_link_thread` | Link bead to Agent Mail thread |
81
-
82
- ### Agent Mail Tools
83
-
84
- | Tool | Description |
85
- | ---------------------------- | ---------------------------------------------------- |
86
- | `agentmail_init` | Initialize session (ensure project + register agent) |
87
- | `agentmail_send` | Send message to other agents |
88
- | `agentmail_inbox` | Fetch inbox (CONTEXT-SAFE: bodies excluded, limit 5) |
89
- | `agentmail_read_message` | Fetch ONE message body by ID |
90
- | `agentmail_summarize_thread` | Summarize thread (PREFERRED over fetching all) |
91
- | `agentmail_reserve` | Reserve file paths for exclusive editing |
92
- | `agentmail_release` | Release file reservations |
93
- | `agentmail_ack` | Acknowledge a message |
94
- | `agentmail_search` | Search messages (FTS5 syntax) |
95
- | `agentmail_health` | Check if Agent Mail server is running |
94
+ ## Usage
96
95
 
97
- ## Rate Limiting
96
+ In OpenCode:
98
97
 
99
- Client-side, per-agent rate limits prevent abuse and ensure fair resource usage across agents. Uses Redis as primary store (`localhost:6379`) with automatic SQLite fallback (`~/.config/opencode/rate-limits.db`).
98
+ ```
99
+ /swarm "Add user authentication with OAuth"
100
+ ```
100
101
 
101
- ### Default Limits
102
+ Or invoke the planner directly:
102
103
 
103
- | Endpoint | Per Minute | Per Hour |
104
- | ------------------ | ---------- | -------- |
105
- | `send` | 20 | 200 |
106
- | `reserve` | 10 | 100 |
107
- | `release` | 10 | 100 |
108
- | `ack` | 20 | 200 |
109
- | `inbox` | 60 | 600 |
110
- | `read_message` | 60 | 600 |
111
- | `summarize_thread` | 30 | 300 |
112
- | `search` | 30 | 300 |
104
+ ```
105
+ @swarm-planner "Refactor all components to use hooks"
106
+ ```
113
107
 
114
- ### Configuration
108
+ ## Dependencies
115
109
 
116
- | Environment Variable | Description |
117
- | ----------------------------------------- | --------------------------------------------------------------------------- |
118
- | `OPENCODE_RATE_LIMIT_REDIS_URL` | Redis connection URL (default: `redis://localhost:6379`) |
119
- | `OPENCODE_RATE_LIMIT_SQLITE_PATH` | SQLite database path (default: `~/.config/opencode/rate-limits.db`) |
120
- | `OPENCODE_RATE_LIMIT_{ENDPOINT}_PER_MIN` | Per-minute limit for endpoint (e.g., `OPENCODE_RATE_LIMIT_SEND_PER_MIN=30`) |
121
- | `OPENCODE_RATE_LIMIT_{ENDPOINT}_PER_HOUR` | Per-hour limit for endpoint (e.g., `OPENCODE_RATE_LIMIT_SEND_PER_HOUR=300`) |
110
+ | Dependency | Purpose | Required |
111
+ | --------------------------------------------------------------- | ------------------------------------------- | -------- |
112
+ | [OpenCode](https://opencode.ai) | Plugin host | Yes |
113
+ | [Beads](https://github.com/steveyegge/beads) | Git-backed issue tracking | Yes |
114
+ | [Go](https://go.dev) | Required for Agent Mail | No |
115
+ | [Agent Mail](https://github.com/joelhooks/agent-mail) | Multi-agent coordination, file reservations | No |
116
+ | [CASS](https://github.com/Dicklesworthstone/cass) | Historical context from past sessions | No |
117
+ | [UBS](https://github.com/joelhooks/ubs) | Pre-completion bug scanning | No |
118
+ | [semantic-memory](https://github.com/joelhooks/semantic-memory) | Learning persistence | No |
119
+ | [Redis](https://redis.io) | Rate limiting (SQLite fallback available) | No |
122
120
 
123
- ### Troubleshooting
121
+ All dependencies are checked and can be installed via `swarm setup`.
124
122
 
125
- - **Rate limit exceeded errors** - Adjust limits via environment variables for your workload
126
- - **Redis unavailable** - Automatic SQLite fallback with warning logged; no action needed
127
- - **SQLite cleanup** - Expired entries cleaned automatically on init
123
+ ## Tools Reference
128
124
 
129
- ### Swarm Tools
125
+ ### Swarm
130
126
 
131
127
  | Tool | Description |
132
128
  | ------------------------------ | ------------------------------------------------------------------------ |
133
- | `swarm_init` | Check tool availability, report degraded features |
134
- | `swarm_select_strategy` | Analyze task and recommend decomposition strategy |
135
- | `swarm_plan_prompt` | Generate strategy-specific planning prompt with CASS integration |
136
- | `swarm_decompose` | Generate decomposition prompt, optionally queries CASS for similar tasks |
137
- | `swarm_validate_decomposition` | Validate decomposition response, detect instruction conflicts |
138
- | `swarm_status` | Get swarm status by epic ID |
139
- | `swarm_progress` | Report progress on a subtask |
140
- | `swarm_complete` | Mark subtask complete with UBS bug scan, release reservations |
141
- | `swarm_record_outcome` | Record outcome for implicit feedback (duration, errors, retries) |
142
- | `swarm_subtask_prompt` | Generate prompt for spawned subtask agent (V1 - includes coordination) |
143
- | `swarm_spawn_subtask` | Generate V2 prompt with Agent Mail/beads instructions for subagents |
144
- | `swarm_complete_subtask` | Handle subtask completion: close bead, create issue beads |
145
- | `swarm_evaluation_prompt` | Generate self-evaluation prompt |
146
-
147
- ### Structured Output Tools
148
-
149
- | Tool | Description |
150
- | -------------------------------- | -------------------------------------------------------- |
151
- | `structured_extract_json` | Extract JSON from markdown/text with multiple strategies |
152
- | `structured_validate` | Validate response against named schema |
153
- | `structured_parse_evaluation` | Parse and validate evaluation response |
154
- | `structured_parse_decomposition` | Parse and validate task decomposition |
155
- | `structured_parse_bead_tree` | Parse and validate bead tree for epic creation |
129
+ | `swarm_init` | Initialize swarm session |
130
+ | `swarm_select_strategy` | Analyze task, recommend decomposition strategy (file/feature/risk-based) |
131
+ | `swarm_plan_prompt` | Generate strategy-specific planning prompt with CASS history |
132
+ | `swarm_decompose` | Generate decomposition prompt |
133
+ | `swarm_validate_decomposition` | Validate response, detect file conflicts |
134
+ | `swarm_spawn_subtask` | Generate worker agent prompt with Agent Mail/beads instructions |
135
+ | `swarm_subtask_prompt` | Alias for spawn_subtask |
136
+ | `swarm_status` | Get swarm progress by epic ID |
137
+ | `swarm_progress` | Report subtask progress to coordinator |
138
+ | `swarm_complete` | Complete subtask - runs UBS scan, releases reservations |
139
+ | `swarm_record_outcome` | Record outcome for learning (duration, errors, retries) |
140
+
141
+ ### Beads
142
+
143
+ | Tool | Description |
144
+ | ------------------- | ---------------------------------------------- |
145
+ | `beads_create` | Create bead with type-safe validation |
146
+ | `beads_create_epic` | Create epic + subtasks atomically |
147
+ | `beads_query` | Query beads with filters (status, type, ready) |
148
+ | `beads_update` | Update status/description/priority |
149
+ | `beads_close` | Close bead with reason |
150
+ | `beads_start` | Mark bead as in-progress |
151
+ | `beads_ready` | Get next unblocked bead |
152
+ | `beads_sync` | Sync to git and push |
153
+ | `beads_link_thread` | Link bead to Agent Mail thread |
154
+
155
+ ### Agent Mail
156
+
157
+ | Tool | Description |
158
+ | ---------------------------- | ---------------------------------------------- |
159
+ | `agentmail_init` | Initialize session, register agent |
160
+ | `agentmail_send` | Send message to agents |
161
+ | `agentmail_inbox` | Fetch inbox (max 5, no bodies - context safe) |
162
+ | `agentmail_read_message` | Fetch single message body by ID |
163
+ | `agentmail_summarize_thread` | Summarize thread (preferred over fetching all) |
164
+ | `agentmail_reserve` | Reserve file paths for exclusive editing |
165
+ | `agentmail_release` | Release file reservations |
166
+ | `agentmail_ack` | Acknowledge message |
167
+ | `agentmail_search` | Search messages by keyword |
168
+ | `agentmail_health` | Check if Agent Mail server is running |
169
+
170
+ ### Structured Output
171
+
172
+ | Tool | Description |
173
+ | -------------------------------- | ----------------------------------------------------- |
174
+ | `structured_extract_json` | Extract JSON from markdown/text (multiple strategies) |
175
+ | `structured_validate` | Validate response against schema |
176
+ | `structured_parse_evaluation` | Parse self-evaluation response |
177
+ | `structured_parse_decomposition` | Parse task decomposition response |
178
+ | `structured_parse_bead_tree` | Parse bead tree for epic creation |
156
179
 
157
180
  ## Decomposition Strategies
158
181
 
159
- The plugin supports three decomposition strategies, auto-selected based on task keywords:
182
+ ### File-Based
160
183
 
161
- ### File-Based Strategy
162
-
163
- Best for: Refactoring, migrations, pattern changes across codebase
164
-
165
- **Keywords**: refactor, migrate, rename, update all, convert, upgrade
166
-
167
- **Guidelines**:
184
+ Best for: refactoring, migrations, pattern changes
168
185
 
169
186
  - Group files by directory or type
170
187
  - Handle shared types/utilities first
171
188
  - Minimize cross-directory dependencies
172
189
 
173
- ### Feature-Based Strategy
174
-
175
- Best for: New features, adding functionality
190
+ **Keywords**: refactor, migrate, rename, update all, replace
176
191
 
177
- **Keywords**: add, implement, build, create, feature, new
192
+ ### Feature-Based
178
193
 
179
- **Guidelines**:
194
+ Best for: new features, adding functionality
180
195
 
181
196
  - Each subtask is a complete vertical slice
182
197
  - Start with data layer, then logic, then UI
183
198
  - Keep related components together
184
199
 
185
- ### Risk-Based Strategy
200
+ **Keywords**: add, implement, build, create, feature
186
201
 
187
- Best for: Bug fixes, security issues, critical changes
202
+ ### Risk-Based
188
203
 
189
- **Keywords**: fix, bug, security, critical, urgent, hotfix
190
-
191
- **Guidelines**:
204
+ Best for: bug fixes, security issues
192
205
 
193
206
  - Write tests FIRST
194
207
  - Isolate risky changes
195
208
  - Audit similar code for same issue
196
209
 
197
- ### Strategy Selection
198
-
199
- Use `swarm_select_strategy` to see the recommended strategy:
200
-
201
- ```typescript
202
- swarm_select_strategy({ task: "Add user authentication" });
203
- // Returns: { strategy: "feature-based", confidence: 0.85, reasoning: "..." }
204
- ```
205
-
206
- Or let `swarm_plan_prompt` auto-select:
207
-
208
- ```typescript
209
- swarm_plan_prompt({ task: "Refactor all components to use hooks" });
210
- // Auto-selects file-based strategy
211
- ```
212
-
213
- ## Example Planner Agent
214
-
215
- The plugin includes an example planner agent at `examples/agents/swarm-planner.md`.
216
-
217
- Copy to your OpenCode agents directory:
218
-
219
- ```bash
220
- cp examples/agents/swarm-planner.md ~/.config/opencode/agents/
221
- ```
222
-
223
- Then invoke with:
224
-
225
- ```
226
- @swarm-planner "Add user authentication with OAuth"
227
- ```
228
-
229
- The planner uses `swarm_select_strategy` and `swarm_plan_prompt` internally to create optimal decompositions.
230
-
231
- ### Schemas (for structured outputs)
232
-
233
- The plugin exports Zod schemas for validated agent responses:
234
-
235
- | Schema | Purpose |
236
- | ---------------------------- | -------------------------------------------- |
237
- | `TaskDecompositionSchema` | Decompose task into parallelizable subtasks |
238
- | `EvaluationSchema` | Agent self-evaluation of completed work |
239
- | `WeightedEvaluationSchema` | Evaluation with confidence-weighted criteria |
240
- | `SwarmStatusSchema` | Swarm progress tracking |
241
- | `SwarmSpawnResultSchema` | Result of spawning agent swarm |
242
- | `BeadSchema` | Validated bead data |
243
- | `EpicCreateResultSchema` | Atomic epic creation result |
244
- | `FeedbackEventSchema` | Feedback event for learning |
245
- | `OutcomeSignalsSchema` | Implicit feedback from task outcomes |
246
- | `DecompositionPatternSchema` | Tracked decomposition pattern |
247
- | `PatternMaturitySchema` | Pattern maturity state tracking |
248
-
249
- ## Usage Examples
250
-
251
- ### Basic Bead Creation
252
-
253
- ```typescript
254
- // Create a bug report with priority
255
- await tools["beads_create"]({
256
- title: "Fix login redirect loop",
257
- type: "bug",
258
- priority: 1,
259
- description: "Users stuck in redirect after OAuth callback",
260
- });
261
- ```
262
-
263
- ### Atomic Epic with Subtasks
264
-
265
- ```typescript
266
- // Create epic and all subtasks atomically (with rollback hints on failure)
267
- const result = await tools["beads_create_epic"]({
268
- epic_title: "Implement user dashboard",
269
- epic_description: "New dashboard with metrics and activity feed",
270
- subtasks: [
271
- {
272
- title: "Create dashboard layout",
273
- priority: 2,
274
- files: ["src/components/Dashboard.tsx"],
275
- },
276
- {
277
- title: "Add metrics API endpoint",
278
- priority: 2,
279
- files: ["src/api/metrics.ts"],
280
- },
281
- {
282
- title: "Build activity feed component",
283
- priority: 3,
284
- files: ["src/components/ActivityFeed.tsx"],
285
- },
286
- ],
287
- });
288
- ```
289
-
290
- ### Agent Mail Coordination
291
-
292
- ```typescript
293
- // 1. Initialize session
294
- await tools["agentmail_init"]({
295
- project_path: "/Users/you/project",
296
- task_description: "Working on auth refactor",
297
- });
298
- // Returns: { agent: { name: "BlueLake", ... } }
299
-
300
- // 2. Reserve files before editing
301
- await tools["agentmail_reserve"]({
302
- paths: ["src/auth/**", "src/middleware/auth.ts"],
303
- reason: "bd-abc123: Auth refactor",
304
- ttl_seconds: 3600,
305
- });
306
-
307
- // 3. Check inbox (bodies excluded by default)
308
- const messages = await tools["agentmail_inbox"]({ limit: 5 });
309
-
310
- // 4. Send status update to other agents
311
- await tools["agentmail_send"]({
312
- to: ["RedStone", "GreenCastle"],
313
- subject: "Auth refactor complete",
314
- body: "Finished updating the auth middleware. Ready for review.",
315
- thread_id: "bd-abc123",
316
- });
317
-
318
- // 5. Release reservations when done
319
- await tools["agentmail_release"]({});
320
- ```
321
-
322
- ### Swarm Workflow
323
-
324
- ```typescript
325
- // 1. Create epic for the work
326
- const epic = await tools["beads_create_epic"]({
327
- epic_title: "Add export feature",
328
- subtasks: [
329
- { title: "Export to CSV", files: ["src/export/csv.ts"] },
330
- { title: "Export to JSON", files: ["src/export/json.ts"] },
331
- { title: "Export to PDF", files: ["src/export/pdf.ts"] },
332
- ],
333
- });
334
-
335
- // 2. Each parallel agent reserves its files
336
- // Agent 1 (BlueLake):
337
- await tools["agentmail_reserve"]({
338
- paths: ["src/export/csv.ts"],
339
- reason: `${epic.subtasks[0].id}: Export to CSV`,
340
- });
341
-
342
- // 3. Agents communicate via thread
343
- await tools["agentmail_send"]({
344
- to: ["Coordinator"],
345
- subject: "CSV export complete",
346
- body: "Implemented CSV export with streaming support.",
347
- thread_id: epic.epic.id,
348
- });
349
-
350
- // 4. Coordinator uses summarize_thread (not fetch all)
351
- const summary = await tools["agentmail_summarize_thread"]({
352
- thread_id: epic.epic.id,
353
- include_examples: true,
354
- });
355
- ```
356
-
357
- ## Learning Capabilities
358
-
359
- The plugin learns from swarm outcomes to improve future decompositions.
360
-
361
- ### Confidence Decay
362
-
363
- Evaluation criteria weights decay over time unless revalidated. If a criterion (e.g., `type_safe`) has been historically unreliable, its weight decreases.
364
-
365
- ```typescript
366
- import {
367
- calculateDecayedValue,
368
- calculateCriterionWeight,
369
- } from "opencode-swarm-plugin";
370
-
371
- // Value decays by 50% every 90 days (configurable half-life)
372
- const weight = calculateDecayedValue(timestamp, now, halfLifeDays);
210
+ **Keywords**: fix, bug, security, critical, urgent
373
211
 
374
- // Calculate criterion weight from feedback history
375
- const criterionWeight = calculateCriterionWeight(feedbackEvents);
376
- // { criterion: "type_safe", weight: 0.85, helpful_count: 10, harmful_count: 2 }
377
- ```
378
-
379
- ### Implicit Feedback Scoring
380
-
381
- The `swarm_record_outcome` tool tracks task outcomes and infers feedback:
382
-
383
- - **Fast completion + success** → helpful signal
384
- - **Slow completion + errors + retries** → harmful signal
385
-
386
- ```typescript
387
- // Record outcome after completing a subtask
388
- await tools["swarm_record_outcome"]({
389
- bead_id: "bd-abc123.1",
390
- duration_ms: 60000,
391
- error_count: 0,
392
- retry_count: 0,
393
- success: true,
394
- files_touched: ["src/auth.ts"],
395
- });
396
- // Returns feedback events for each criterion
397
- ```
398
-
399
- ### Anti-Pattern Learning
400
-
401
- Failed decomposition patterns are automatically inverted to anti-patterns:
402
-
403
- ```typescript
404
- import {
405
- recordPatternObservation,
406
- formatAntiPatternsForPrompt,
407
- } from "opencode-swarm-plugin";
408
-
409
- // Record pattern failure
410
- const result = recordPatternObservation(pattern, false, beadId);
411
- if (result.inversion) {
412
- // Pattern was inverted: "Split by file type" → "AVOID: Split by file type. Failed 4/5 times (80% failure rate)"
413
- }
414
-
415
- // Include anti-patterns in decomposition prompts
416
- const antiPatternContext = formatAntiPatternsForPrompt(patterns);
417
- ```
418
-
419
- ### Pattern Maturity
420
-
421
- Patterns progress through maturity states: `candidate` → `established` → `proven` (or `deprecated`).
212
+ ## Learning
422
213
 
423
- ```typescript
424
- import {
425
- calculateMaturityState,
426
- getMaturityMultiplier,
427
- } from "opencode-swarm-plugin";
214
+ The plugin learns from outcomes:
428
215
 
429
- // Calculate state from feedback
430
- const state = calculateMaturityState(feedbackEvents);
431
- // "candidate" | "established" | "proven" | "deprecated"
432
-
433
- // Get weight multiplier for pattern ranking
434
- const multiplier = getMaturityMultiplier("proven"); // 1.5
435
- ```
436
-
437
- ### UBS Pre-Completion Scan
438
-
439
- The `swarm_complete` tool runs UBS (Ultimate Bug Scanner) on modified files before marking complete:
440
-
441
- ```typescript
442
- await tools["swarm_complete"]({
443
- project_key: "/path/to/project",
444
- agent_name: "BlueLake",
445
- bead_id: "bd-abc123.1",
446
- summary: "Implemented auth flow",
447
- files_touched: ["src/auth.ts", "src/middleware.ts"],
448
- // skip_ubs_scan: true // Optional: bypass scan
449
- });
450
- // Blocks completion if critical bugs found
451
- ```
452
-
453
- ### CASS History Context
454
-
455
- The `swarm_decompose` tool queries CASS (Cross-Agent Session Search) for similar past tasks:
456
-
457
- ```typescript
458
- await tools["swarm_decompose"]({
459
- task: "Add user authentication with OAuth",
460
- max_subtasks: 5,
461
- query_cass: true, // Default: true
462
- cass_limit: 3, // Max results to include
463
- });
464
- // Includes successful patterns from past decompositions in context
465
- ```
216
+ | Mechanism | How It Works |
217
+ | ----------------- | ----------------------------------------------------------- |
218
+ | Confidence decay | Criteria weights fade unless revalidated (90-day half-life) |
219
+ | Implicit feedback | Fast + success = helpful signal, slow + errors = harmful |
220
+ | Pattern maturity | candidate established → proven (or deprecated) |
221
+ | Anti-patterns | Patterns with >60% failure rate auto-invert |
466
222
 
467
223
  ## Context Preservation
468
224
 
469
- **CRITICAL**: This plugin enforces context-safe defaults to prevent session exhaustion.
470
-
471
- ### Why These Constraints Exist
472
-
473
- | Constraint | Default | Reason |
474
- | -------------------- | ---------------------------- | -------------------------------------------------- |
475
- | Inbox limit | 5 messages | Fetching 20+ messages with bodies exhausts context |
476
- | Bodies excluded | `include_bodies: false` | Message bodies can be huge; fetch individually |
477
- | Summarize over fetch | `summarize_thread` preferred | Get key points, not raw message dump |
478
-
479
- ### The Pattern
480
-
481
- ```typescript
482
- // WRONG: This can dump thousands of tokens into context
483
- const messages = await tools["agentmail_inbox"]({
484
- limit: 20,
485
- include_bodies: true, // Plugin prevents this
486
- });
225
+ Hard limits to prevent context exhaustion:
487
226
 
488
- // RIGHT: Headers only, then fetch specific messages
489
- const headers = await tools["agentmail_inbox"]({ limit: 5 });
490
- const importantMessage = await tools["agentmail_read_message"]({
491
- message_id: headers[0].id,
492
- });
227
+ | Constraint | Default | Reason |
228
+ | ------------------- | ---------- | ------------------------------ |
229
+ | Inbox limit | 5 messages | Prevents token burn |
230
+ | Bodies excluded | Always | Fetch individually when needed |
231
+ | Summarize preferred | Yes | Key points, not raw dump |
493
232
 
494
- // BEST: Summarize threads instead of fetching all messages
495
- const summary = await tools["agentmail_summarize_thread"]({
496
- thread_id: "bd-abc123",
497
- });
498
- ```
499
-
500
- ### Hard Caps
501
-
502
- The plugin enforces these limits regardless of input:
503
-
504
- - `agentmail_inbox` - Max 5 messages, bodies always excluded
505
- - Thread summaries use LLM mode for concise output
506
- - File reservations auto-track for cleanup
507
-
508
- ## Custom Commands
509
-
510
- This plugin provides tools that work with OpenCode's [custom commands](https://opencode.ai/docs/commands). Create a `/swarm` command to orchestrate multi-agent work.
511
-
512
- ### Setup /swarm Command
513
-
514
- Copy the example command to your OpenCode config:
515
-
516
- ```bash
517
- cp examples/commands/swarm.md ~/.config/opencode/command/
518
- ```
519
-
520
- ### Usage
521
-
522
- ```
523
- /swarm "Add user authentication with OAuth providers"
524
- ```
525
-
526
- ### How It Works
527
-
528
- 1. **Decompose** - `swarm_decompose` breaks task into subtasks with file assignments
529
- 2. **Create beads** - `beads_create_epic` creates epic + subtasks atomically
530
- 3. **Spawn agents** - `swarm_spawn_subtask` generates prompts WITH Agent Mail/beads instructions
531
- 4. **Parallel work** - Subagents use Agent Mail to communicate, beads to track progress
532
- 5. **Coordination** - Agents report progress, ask questions, announce blockers via Agent Mail
533
- 6. **Completion** - Agents use `swarm_complete` when done
534
- 7. **Cleanup** - `beads_sync` pushes to git
535
-
536
- ### Subagent Capabilities
537
-
538
- Spawned subagents have **full access** to all plugin tools:
539
-
540
- - **Agent Mail** - `agentmail_send`, `agentmail_inbox`, `agentmail_reserve`, etc.
541
- - **Beads** - `beads_update`, `beads_create`, `swarm_complete`
542
- - All standard OpenCode tools
543
-
544
- The prompts tell agents to actively communicate and coordinate.
545
-
546
- ## Error Handling
233
+ ## Rate Limiting
547
234
 
548
- The plugin provides typed errors for robust error handling:
235
+ Client-side limits (Redis primary, SQLite fallback):
549
236
 
550
- ```typescript
551
- import {
552
- BeadError,
553
- BeadValidationError,
554
- AgentMailError,
555
- AgentMailNotInitializedError,
556
- FileReservationConflictError,
557
- } from "opencode-swarm-plugin";
237
+ | Endpoint | Per Minute | Per Hour |
238
+ | -------- | ---------- | -------- |
239
+ | send | 20 | 200 |
240
+ | reserve | 10 | 100 |
241
+ | inbox | 60 | 600 |
558
242
 
559
- try {
560
- await tools["agentmail_reserve"]({ paths: ["src/index.ts"] });
561
- } catch (error) {
562
- if (error instanceof FileReservationConflictError) {
563
- console.log("Conflicts:", error.conflicts);
564
- // [{ path: "src/index.ts", holders: ["RedStone"] }]
565
- }
566
- }
567
- ```
243
+ Configure via `OPENCODE_RATE_LIMIT_{ENDPOINT}_PER_MIN` env vars.
568
244
 
569
245
  ## Development
570
246
 
571
247
  ```bash
572
- # Install dependencies
573
248
  bun install
574
-
575
- # Type check
576
249
  bun run typecheck
577
-
578
- # Run tests
579
250
  bun test
580
-
581
- # Build for distribution
582
251
  bun run build
583
-
584
- # Clean build artifacts
585
- bun run clean
586
252
  ```
587
253
 
588
254
  ## License