opencode-swarm-plugin 0.44.2 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +277 -54
  2. package/bin/swarm.ts +1 -1
  3. package/dist/decision-trace-integration.d.ts +204 -0
  4. package/dist/decision-trace-integration.d.ts.map +1 -0
  5. package/dist/hive.d.ts.map +1 -1
  6. package/dist/hive.js +9 -9
  7. package/dist/index.d.ts +32 -2
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +535 -27
  10. package/dist/plugin.js +295 -27
  11. package/dist/query-tools.d.ts +20 -12
  12. package/dist/query-tools.d.ts.map +1 -1
  13. package/dist/swarm-decompose.d.ts +4 -4
  14. package/dist/swarm-decompose.d.ts.map +1 -1
  15. package/dist/swarm-prompts.d.ts.map +1 -1
  16. package/dist/swarm-prompts.js +220 -22
  17. package/dist/swarm-review.d.ts.map +1 -1
  18. package/dist/swarm-signature.d.ts +106 -0
  19. package/dist/swarm-signature.d.ts.map +1 -0
  20. package/dist/swarm-strategies.d.ts +16 -3
  21. package/dist/swarm-strategies.d.ts.map +1 -1
  22. package/dist/swarm.d.ts +4 -2
  23. package/dist/swarm.d.ts.map +1 -1
  24. package/examples/commands/swarm.md +745 -0
  25. package/examples/plugin-wrapper-template.ts +2611 -0
  26. package/examples/skills/hive-workflow/SKILL.md +212 -0
  27. package/examples/skills/skill-creator/SKILL.md +223 -0
  28. package/examples/skills/swarm-coordination/SKILL.md +292 -0
  29. package/global-skills/cli-builder/SKILL.md +344 -0
  30. package/global-skills/cli-builder/references/advanced-patterns.md +244 -0
  31. package/global-skills/learning-systems/SKILL.md +644 -0
  32. package/global-skills/skill-creator/LICENSE.txt +202 -0
  33. package/global-skills/skill-creator/SKILL.md +352 -0
  34. package/global-skills/skill-creator/references/output-patterns.md +82 -0
  35. package/global-skills/skill-creator/references/workflows.md +28 -0
  36. package/global-skills/swarm-coordination/SKILL.md +995 -0
  37. package/global-skills/swarm-coordination/references/coordinator-patterns.md +235 -0
  38. package/global-skills/swarm-coordination/references/strategies.md +138 -0
  39. package/global-skills/system-design/SKILL.md +213 -0
  40. package/global-skills/testing-patterns/SKILL.md +430 -0
  41. package/global-skills/testing-patterns/references/dependency-breaking-catalog.md +586 -0
  42. package/package.json +5 -2
@@ -0,0 +1,644 @@
1
+ ---
2
+ name: learning-systems
3
+ description: Implicit feedback scoring, confidence decay, and anti-pattern detection. Use when understanding how the swarm plugin learns from outcomes, implementing learning loops, or debugging why patterns are being promoted or deprecated. Unique to opencode-swarm-plugin.
4
+ ---
5
+
6
+ # Learning Systems
7
+
8
+ The swarm plugin learns from task outcomes to improve decomposition quality over time. Three interconnected systems track pattern effectiveness: implicit feedback scoring, confidence decay, and pattern maturity progression.
9
+
10
+ ## Implicit Feedback Scoring
11
+
12
+ Convert task outcomes into learning signals without explicit user feedback.
13
+
14
+ ### What Gets Scored
15
+
16
+ **Duration signals:**
17
+
18
+ - Fast (<5 min) = helpful (1.0)
19
+ - Medium (5-30 min) = neutral (0.6)
20
+ - Slow (>30 min) = harmful (0.2)
21
+
22
+ **Error signals:**
23
+
24
+ - 0 errors = helpful (1.0)
25
+ - 1-2 errors = neutral (0.6)
26
+ - 3+ errors = harmful (0.2)
27
+
28
+ **Retry signals:**
29
+
30
+ - 0 retries = helpful (1.0)
31
+ - 1 retry = neutral (0.7)
32
+ - 2+ retries = harmful (0.3)
33
+
34
+ **Success signal:**
35
+
36
+ - Success = 1.0 (40% weight)
37
+ - Failure = 0.0
38
+
39
+ ### Weighted Score Calculation
40
+
41
+ ```typescript
42
+ rawScore = success * 0.4 + duration * 0.2 + errors * 0.2 + retries * 0.2;
43
+ ```
44
+
45
+ **Thresholds:**
46
+
47
+ - rawScore >= 0.7 → helpful
48
+ - rawScore <= 0.4 → harmful
49
+ - 0.4 < rawScore < 0.7 → neutral
50
+
51
+ ### Recording Outcomes
52
+
53
+ Call `swarm_record_outcome` after subtask completion:
54
+
55
+ ```typescript
56
+ swarm_record_outcome({
57
+ bead_id: "bd-123.1",
58
+ duration_ms: 180000, // 3 minutes
59
+ error_count: 0,
60
+ retry_count: 0,
61
+ success: true,
62
+ files_touched: ["src/auth.ts"],
63
+ strategy: "file-based",
64
+ });
65
+ ```
66
+
67
+ **Fields tracked:**
68
+
69
+ - `bead_id` - subtask identifier
70
+ - `duration_ms` - time from start to completion
71
+ - `error_count` - errors encountered (from ErrorAccumulator)
72
+ - `retry_count` - number of retry attempts
73
+ - `success` - whether subtask completed successfully
74
+ - `files_touched` - modified file paths
75
+ - `strategy` - decomposition strategy used (optional)
76
+ - `failure_mode` - classification if success=false (optional)
77
+ - `failure_details` - error context (optional)
78
+
79
+ ## Confidence Decay
80
+
81
+ Evaluation criteria weights fade unless revalidated. Prevents stale patterns from dominating future decompositions.
82
+
83
+ ### Half-Life Formula
84
+
85
+ ```
86
+ decayed_value = raw_value * 0.5^(age_days / 90)
87
+ ```
88
+
89
+ **Decay timeline:**
90
+
91
+ - Day 0: 100% weight
92
+ - Day 90: 50% weight
93
+ - Day 180: 25% weight
94
+ - Day 270: 12.5% weight
95
+
96
+ ### Criterion Weight Calculation
97
+
98
+ Aggregate decayed feedback events:
99
+
100
+ ```typescript
101
+ helpfulSum = sum(helpful_events.map((e) => e.raw_value * decay(e.timestamp)));
102
+ harmfulSum = sum(harmful_events.map((e) => e.raw_value * decay(e.timestamp)));
103
+ weight = max(0.1, helpfulSum / (helpfulSum + harmfulSum));
104
+ ```
105
+
106
+ **Weight floor:** minimum 0.1 prevents complete zeroing
107
+
108
+ ### Revalidation
109
+
110
+ Recording new feedback resets decay timer for that criterion:
111
+
112
+ ```typescript
113
+ {
114
+ criterion: "type_safe",
115
+ weight: 0.85,
116
+ helpful_count: 12,
117
+ harmful_count: 3,
118
+ last_validated: "2024-12-12T00:00:00Z", // Reset on new feedback
119
+ half_life_days: 90,
120
+ }
121
+ ```
122
+
123
+ ### When Criteria Get Deprecated
124
+
125
+ ```typescript
126
+ total = helpful_count + harmful_count;
127
+ harmfulRatio = harmful_count / total;
128
+
129
+ if (total >= 3 && harmfulRatio > 0.3) {
130
+ // Deprecate criterion - reduce impact to 0
131
+ }
132
+ ```
133
+
134
+ ## Pattern Maturity States
135
+
136
+ Patterns progress through lifecycle based on feedback accumulation:
137
+
138
+ **candidate** → **established** → **proven** (or **deprecated**)
139
+
140
+ ### State Transitions
141
+
142
+ **candidate (initial state):**
143
+
144
+ - Total feedback < 3 events
145
+ - Not enough data to judge
146
+ - Multiplier: 0.5x
147
+
148
+ **established:**
149
+
150
+ - Total feedback >= 3 events
151
+ - Has track record but not proven
152
+ - Multiplier: 1.0x
153
+
154
+ **proven:**
155
+
156
+ - Decayed helpful >= 5 AND
157
+ - Harmful ratio < 15%
158
+ - Multiplier: 1.5x
159
+
160
+ **deprecated:**
161
+
162
+ - Harmful ratio > 30% AND
163
+ - Total feedback >= 3 events
164
+ - Multiplier: 0x (excluded)
165
+
166
+ ### Decay Applied to State Calculation
167
+
168
+ State determination uses decayed counts, not raw counts:
169
+
170
+ ```typescript
171
+ const { decayedHelpful, decayedHarmful } =
172
+ calculateDecayedCounts(feedbackEvents);
173
+ const total = decayedHelpful + decayedHarmful;
174
+ const harmfulRatio = decayedHarmful / total;
175
+
176
+ // State logic applies to decayed values
177
+ ```
178
+
179
+ Old feedback matters less. Pattern must maintain recent positive signal to stay proven.
180
+
181
+ ### Manual State Changes
182
+
183
+ **Promote to proven:**
184
+
185
+ ```typescript
186
+ promotePattern(maturity); // External validation confirms effectiveness
187
+ ```
188
+
189
+ **Deprecate:**
190
+
191
+ ```typescript
192
+ deprecatePattern(maturity, "Causes file conflicts in 80% of cases");
193
+ ```
194
+
195
+ Cannot promote deprecated patterns. Must reset.
196
+
197
+ ### Multipliers in Decomposition
198
+
199
+ Apply maturity multiplier to pattern scores:
200
+
201
+ ```typescript
202
+ const multipliers = {
203
+ candidate: 0.5,
204
+ established: 1.0,
205
+ proven: 1.5,
206
+ deprecated: 0,
207
+ };
208
+
209
+ pattern_score = base_score * multipliers[maturity.state];
210
+ ```
211
+
212
+ Proven patterns get 50% boost, deprecated patterns excluded entirely.
213
+
214
+ ## Anti-Pattern Inversion
215
+
216
+ Failed patterns auto-convert to anti-patterns at >60% failure rate.
217
+
218
+ ### Inversion Threshold
219
+
220
+ ```typescript
221
+ const total = pattern.success_count + pattern.failure_count;
222
+
223
+ if (total >= 3 && pattern.failure_count / total >= 0.6) {
224
+ invertToAntiPattern(pattern, reason);
225
+ }
226
+ ```
227
+
228
+ **Minimum observations:** 3 total (prevents hasty inversion)
229
+ **Failure ratio:** 60% (3+ failures in 5 attempts)
230
+
231
+ ### Inversion Process
232
+
233
+ **Original pattern:**
234
+
235
+ ```typescript
236
+ {
237
+ id: "pattern-123",
238
+ content: "Split by file type",
239
+ kind: "pattern",
240
+ is_negative: false,
241
+ success_count: 2,
242
+ failure_count: 5,
243
+ }
244
+ ```
245
+
246
+ **Inverted anti-pattern:**
247
+
248
+ ```typescript
249
+ {
250
+ id: "anti-pattern-123",
251
+ content: "AVOID: Split by file type. Failed 5/7 times (71% failure rate)",
252
+ kind: "anti_pattern",
253
+ is_negative: true,
254
+ success_count: 2,
255
+ failure_count: 5,
256
+ reason: "Failed 5/7 times (71% failure rate)",
257
+ }
258
+ ```
259
+
260
+ ### Recording Observations
261
+
262
+ Track pattern outcomes to accumulate success/failure counts:
263
+
264
+ ```typescript
265
+ recordPatternObservation(
266
+ pattern,
267
+ success: true, // or false
268
+ beadId: "bd-123.1",
269
+ )
270
+
271
+ // Returns:
272
+ {
273
+ pattern: updatedPattern,
274
+ inversion?: {
275
+ original: pattern,
276
+ inverted: antiPattern,
277
+ reason: "Failed 5/7 times (71% failure rate)",
278
+ }
279
+ }
280
+ ```
281
+
282
+ ### Pattern Extraction
283
+
284
+ Auto-detect strategies from decomposition descriptions:
285
+
286
+ ```typescript
287
+ extractPatternsFromDescription(
288
+ "We'll split by file type, one file per subtask",
289
+ );
290
+
291
+ // Returns: ["Split by file type", "One file per subtask"]
292
+ ```
293
+
294
+ **Detected strategies:**
295
+
296
+ - Split by file type
297
+ - Split by component
298
+ - Split by layer (UI/logic/data)
299
+ - Split by feature
300
+ - One file per subtask
301
+ - Handle shared types first
302
+ - Separate API routes
303
+ - Tests alongside implementation
304
+ - Tests in separate subtask
305
+ - Maximize parallelization
306
+ - Sequential execution order
307
+ - Respect dependency chain
308
+
309
+ ### Using Anti-Patterns in Prompts
310
+
311
+ Format for decomposition prompt inclusion:
312
+
313
+ ```typescript
314
+ formatAntiPatternsForPrompt(patterns);
315
+ ```
316
+
317
+ **Output:**
318
+
319
+ ```markdown
320
+ ## Anti-Patterns to Avoid
321
+
322
+ Based on past failures, avoid these decomposition strategies:
323
+
324
+ - AVOID: Split by file type. Failed 12/15 times (80% failure rate)
325
+ - AVOID: One file per subtask. Failed 8/10 times (80% failure rate)
326
+ ```
327
+
328
+ ## Error Accumulator
329
+
330
+ Track errors during subtask execution for retry prompts and outcome scoring.
331
+
332
+ ### Error Types
333
+
334
+ ```typescript
335
+ type ErrorType =
336
+ | "validation" // Schema/type errors
337
+ | "timeout" // Task exceeded time limit
338
+ | "conflict" // File reservation conflicts
339
+ | "tool_failure" // Tool invocation failed
340
+ | "unknown"; // Unclassified
341
+ ```
342
+
343
+ ### Recording Errors
344
+
345
+ ```typescript
346
+ errorAccumulator.recordError(
347
+ beadId: "bd-123.1",
348
+ errorType: "validation",
349
+ message: "Type error in src/auth.ts",
350
+ options: {
351
+ stack_trace: "...",
352
+ tool_name: "typecheck",
353
+ context: "After adding OAuth types",
354
+ }
355
+ )
356
+ ```
357
+
358
+ ### Generating Error Context
359
+
360
+ Format accumulated errors for retry prompts:
361
+
362
+ ```typescript
363
+ const context = await errorAccumulator.getErrorContext(
364
+ beadId: "bd-123.1",
365
+ includeResolved: false,
366
+ )
367
+ ```
368
+
369
+ **Output:**
370
+
371
+ ```markdown
372
+ ## Previous Errors
373
+
374
+ The following errors were encountered during execution:
375
+
376
+ ### validation (2 errors)
377
+
378
+ - **Type error in src/auth.ts**
379
+ - Context: After adding OAuth types
380
+ - Tool: typecheck
381
+ - Time: 12/12/2024, 10:30 AM
382
+
383
+ - **Missing import in src/session.ts**
384
+ - Tool: typecheck
385
+ - Time: 12/12/2024, 10:35 AM
386
+
387
+ **Action Required**: Address these errors before proceeding. Consider:
388
+
389
+ - What caused each error?
390
+ - How can you prevent similar errors?
391
+ - Are there patterns across error types?
392
+ ```
393
+
394
+ ### Resolving Errors
395
+
396
+ Mark errors resolved after fixing:
397
+
398
+ ```typescript
399
+ await errorAccumulator.resolveError(errorId);
400
+ ```
401
+
402
+ Resolved errors excluded from retry context by default.
403
+
404
+ ### Error Statistics
405
+
406
+ Get error counts for outcome tracking:
407
+
408
+ ```typescript
409
+ const stats = await errorAccumulator.getErrorStats("bd-123.1")
410
+
411
+ // Returns:
412
+ {
413
+ total: 5,
414
+ unresolved: 2,
415
+ by_type: {
416
+ validation: 3,
417
+ timeout: 1,
418
+ tool_failure: 1,
419
+ }
420
+ }
421
+ ```
422
+
423
+ Use `total` for `error_count` in outcome signals.
424
+
425
+ ## Using the Learning System
426
+
427
+ ### Integration Points
428
+
429
+ **1. During decomposition (swarm_plan_prompt):**
430
+
431
+ - Query CASS for similar tasks
432
+ - Load pattern maturity records
433
+ - Include proven patterns in prompt
434
+ - Exclude deprecated patterns
435
+
436
+ **2. During execution:**
437
+
438
+ - ErrorAccumulator tracks errors
439
+ - Record retry attempts
440
+ - Track duration from start to completion
441
+
442
+ **3. After completion (swarm_complete):**
443
+
444
+ - Record outcome signals
445
+ - Score implicit feedback
446
+ - Update pattern observations
447
+ - Check for anti-pattern inversions
448
+ - Update maturity states
449
+
450
+ ### Full Workflow Example
451
+
452
+ ```typescript
453
+ // 1. Decomposition phase
454
+ const cass_results = cass_search({ query: "user authentication", limit: 5 });
455
+ const patterns = loadPatterns(); // Get maturity records
456
+ const prompt = swarm_plan_prompt({
457
+ task: "Add OAuth",
458
+ context: formatPatternsWithMaturityForPrompt(patterns),
459
+ query_cass: true,
460
+ });
461
+
462
+ // 2. Execution phase
463
+ const errorAccumulator = new ErrorAccumulator();
464
+ const startTime = Date.now();
465
+
466
+ try {
467
+ // Work happens...
468
+ await implement_subtask();
469
+ } catch (error) {
470
+ await errorAccumulator.recordError(
471
+ bead_id,
472
+ classifyError(error),
473
+ error.message,
474
+ );
475
+ retryCount++;
476
+ }
477
+
478
+ // 3. Completion phase
479
+ const duration = Date.now() - startTime;
480
+ const errorStats = await errorAccumulator.getErrorStats(bead_id);
481
+
482
+ swarm_record_outcome({
483
+ bead_id,
484
+ duration_ms: duration,
485
+ error_count: errorStats.total,
486
+ retry_count: retryCount,
487
+ success: true,
488
+ files_touched: modifiedFiles,
489
+ strategy: "file-based",
490
+ });
491
+
492
+ // 4. Learning updates
493
+ const scored = scoreImplicitFeedback({
494
+ bead_id,
495
+ duration_ms: duration,
496
+ error_count: errorStats.total,
497
+ retry_count: retryCount,
498
+ success: true,
499
+ timestamp: new Date().toISOString(),
500
+ strategy: "file-based",
501
+ });
502
+
503
+ // Update patterns
504
+ for (const pattern of extractedPatterns) {
505
+ const { pattern: updated, inversion } = recordPatternObservation(
506
+ pattern,
507
+ scored.type === "helpful",
508
+ bead_id,
509
+ );
510
+
511
+ if (inversion) {
512
+ console.log(`Pattern inverted: ${inversion.reason}`);
513
+ storeAntiPattern(inversion.inverted);
514
+ }
515
+ }
516
+ ```
517
+
518
+ ### Configuration Tuning
519
+
520
+ Adjust thresholds based on project characteristics:
521
+
522
+ ```typescript
523
+ const learningConfig = {
524
+ halfLifeDays: 90, // Decay speed
525
+ minFeedbackForAdjustment: 3, // Min observations for weight adjustment
526
+ maxHarmfulRatio: 0.3, // Max harmful % before deprecating criterion
527
+ fastCompletionThresholdMs: 300000, // 5 min = fast
528
+ slowCompletionThresholdMs: 1800000, // 30 min = slow
529
+ maxErrorsForHelpful: 2, // Max errors before marking harmful
530
+ };
531
+
532
+ const antiPatternConfig = {
533
+ minObservations: 3, // Min before inversion
534
+ failureRatioThreshold: 0.6, // 60% failure triggers inversion
535
+ antiPatternPrefix: "AVOID: ",
536
+ };
537
+
538
+ const maturityConfig = {
539
+ minFeedback: 3, // Min for leaving candidate state
540
+ minHelpful: 5, // Decayed helpful threshold for proven
541
+ maxHarmful: 0.15, // Max 15% harmful for proven
542
+ deprecationThreshold: 0.3, // 30% harmful triggers deprecation
543
+ halfLifeDays: 90,
544
+ };
545
+ ```
546
+
547
+ ### Debugging Pattern Issues
548
+
549
+ **Why is pattern not proven?**
550
+
551
+ Check decayed counts:
552
+
553
+ ```typescript
554
+ const feedback = await getFeedback(patternId);
555
+ const { decayedHelpful, decayedHarmful } = calculateDecayedCounts(feedback);
556
+
557
+ console.log({ decayedHelpful, decayedHarmful });
558
+ // Need: decayedHelpful >= 5 AND harmfulRatio < 0.15
559
+ ```
560
+
561
+ **Why was pattern inverted?**
562
+
563
+ Check observation counts:
564
+
565
+ ```typescript
566
+ const total = pattern.success_count + pattern.failure_count;
567
+ const failureRatio = pattern.failure_count / total;
568
+
569
+ console.log({ total, failureRatio });
570
+ // Inverts if: total >= 3 AND failureRatio >= 0.6
571
+ ```
572
+
573
+ **Why is criterion weight low?**
574
+
575
+ Check feedback events:
576
+
577
+ ```typescript
578
+ const events = await getFeedbackByCriterion("type_safe");
579
+ const weight = calculateCriterionWeight(events);
580
+
581
+ console.log(weight);
582
+ // Shows: helpful vs harmful counts, last_validated date
583
+ ```
584
+
585
+ ## Storage Interfaces
586
+
587
+ ### FeedbackStorage
588
+
589
+ Persist feedback events for criterion weight calculation:
590
+
591
+ ```typescript
592
+ interface FeedbackStorage {
593
+ store(event: FeedbackEvent): Promise<void>;
594
+ getByCriterion(criterion: string): Promise<FeedbackEvent[]>;
595
+ getByBead(beadId: string): Promise<FeedbackEvent[]>;
596
+ getAll(): Promise<FeedbackEvent[]>;
597
+ }
598
+ ```
599
+
600
+ ### ErrorStorage
601
+
602
+ Persist errors for retry prompts:
603
+
604
+ ```typescript
605
+ interface ErrorStorage {
606
+ store(entry: ErrorEntry): Promise<void>;
607
+ getByBead(beadId: string): Promise<ErrorEntry[]>;
608
+ getUnresolvedByBead(beadId: string): Promise<ErrorEntry[]>;
609
+ markResolved(id: string): Promise<void>;
610
+ getAll(): Promise<ErrorEntry[]>;
611
+ }
612
+ ```
613
+
614
+ ### PatternStorage
615
+
616
+ Persist decomposition patterns:
617
+
618
+ ```typescript
619
+ interface PatternStorage {
620
+ store(pattern: DecompositionPattern): Promise<void>;
621
+ get(id: string): Promise<DecompositionPattern | null>;
622
+ getAll(): Promise<DecompositionPattern[]>;
623
+ getAntiPatterns(): Promise<DecompositionPattern[]>;
624
+ getByTag(tag: string): Promise<DecompositionPattern[]>;
625
+ findByContent(content: string): Promise<DecompositionPattern[]>;
626
+ }
627
+ ```
628
+
629
+ ### MaturityStorage
630
+
631
+ Persist pattern maturity records:
632
+
633
+ ```typescript
634
+ interface MaturityStorage {
635
+ store(maturity: PatternMaturity): Promise<void>;
636
+ get(patternId: string): Promise<PatternMaturity | null>;
637
+ getAll(): Promise<PatternMaturity[]>;
638
+ getByState(state: MaturityState): Promise<PatternMaturity[]>;
639
+ storeFeedback(feedback: MaturityFeedback): Promise<void>;
640
+ getFeedback(patternId: string): Promise<MaturityFeedback[]>;
641
+ }
642
+ ```
643
+
644
+ In-memory implementations provided for testing. Production should use persistent storage (file-based JSONL or SQLite).