opencode-swarm-plugin 0.53.0 → 0.54.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.
@@ -12693,6 +12693,7 @@ var init_dist = __esm(() => {
12693
12693
  var exports_learning = {};
12694
12694
  __export(exports_learning, {
12695
12695
  shouldDeprecateCriterion: () => shouldDeprecateCriterion,
12696
+ scoreOutcome: () => scoreOutcome,
12696
12697
  scoreImplicitFeedback: () => scoreImplicitFeedback,
12697
12698
  outcomeToFeedback: () => outcomeToFeedback,
12698
12699
  learningSchemas: () => learningSchemas,
@@ -12800,6 +12801,14 @@ function scoreImplicitFeedback(signals, config2 = DEFAULT_LEARNING_CONFIG) {
12800
12801
  reasoning
12801
12802
  };
12802
12803
  }
12804
+ function scoreOutcome(signals, config2 = DEFAULT_LEARNING_CONFIG) {
12805
+ const scored = scoreImplicitFeedback(signals, config2);
12806
+ return {
12807
+ type: scored.type,
12808
+ score: scored.decayed_value,
12809
+ reasoning: scored.reasoning
12810
+ };
12811
+ }
12803
12812
  function outcomeToFeedback(outcome, criterion) {
12804
12813
  return {
12805
12814
  id: `${outcome.signals.bead_id}-${criterion}-${Date.now()}`,
@@ -18207,6 +18216,902 @@ echo "Project directory: $1"
18207
18216
  };
18208
18217
  });
18209
18218
 
18219
+ // src/anti-patterns.ts
18220
+ var exports_anti_patterns = {};
18221
+ __export(exports_anti_patterns, {
18222
+ shouldInvertPattern: () => shouldInvertPattern,
18223
+ recordPatternObservation: () => recordPatternObservation,
18224
+ invertToAntiPattern: () => invertToAntiPattern,
18225
+ formatSuccessfulPatternsForPrompt: () => formatSuccessfulPatternsForPrompt,
18226
+ formatAntiPatternsForPrompt: () => formatAntiPatternsForPrompt,
18227
+ extractPatternsFromDescription: () => extractPatternsFromDescription,
18228
+ createPattern: () => createPattern,
18229
+ antiPatternSchemas: () => antiPatternSchemas,
18230
+ PatternKindSchema: () => PatternKindSchema,
18231
+ PatternInversionResultSchema: () => PatternInversionResultSchema,
18232
+ InMemoryPatternStorage: () => InMemoryPatternStorage,
18233
+ DecompositionPatternSchema: () => DecompositionPatternSchema,
18234
+ DEFAULT_ANTI_PATTERN_CONFIG: () => DEFAULT_ANTI_PATTERN_CONFIG
18235
+ });
18236
+ function shouldInvertPattern(pattern, config2 = DEFAULT_ANTI_PATTERN_CONFIG) {
18237
+ if (pattern.kind === "anti_pattern") {
18238
+ return false;
18239
+ }
18240
+ const total = pattern.success_count + pattern.failure_count;
18241
+ if (total < config2.minObservations) {
18242
+ return false;
18243
+ }
18244
+ const failureRatio = pattern.failure_count / total;
18245
+ return failureRatio >= config2.failureRatioThreshold;
18246
+ }
18247
+ function invertToAntiPattern(pattern, reason, config2 = DEFAULT_ANTI_PATTERN_CONFIG) {
18248
+ const cleaned = pattern.content.replace(/^AVOID:\s*/i, "").replace(/^DO NOT:\s*/i, "").replace(/^NEVER:\s*/i, "");
18249
+ const inverted = {
18250
+ ...pattern,
18251
+ id: `anti-${pattern.id}`,
18252
+ content: `${config2.antiPatternPrefix}${cleaned}. ${reason}`,
18253
+ kind: "anti_pattern",
18254
+ is_negative: true,
18255
+ reason,
18256
+ updated_at: new Date().toISOString()
18257
+ };
18258
+ return {
18259
+ original: pattern,
18260
+ inverted,
18261
+ reason
18262
+ };
18263
+ }
18264
+ function recordPatternObservation(pattern, success2, beadId, config2 = DEFAULT_ANTI_PATTERN_CONFIG) {
18265
+ const updated = {
18266
+ ...pattern,
18267
+ success_count: success2 ? pattern.success_count + 1 : pattern.success_count,
18268
+ failure_count: success2 ? pattern.failure_count : pattern.failure_count + 1,
18269
+ updated_at: new Date().toISOString(),
18270
+ example_beads: beadId ? [...pattern.example_beads.slice(-(MAX_EXAMPLE_BEADS - 1)), beadId] : pattern.example_beads
18271
+ };
18272
+ if (shouldInvertPattern(updated, config2)) {
18273
+ const total = updated.success_count + updated.failure_count;
18274
+ const failureRatio = updated.failure_count / total;
18275
+ const reason = `Failed ${updated.failure_count}/${total} times (${Math.round(failureRatio * 100)}% failure rate)`;
18276
+ return {
18277
+ pattern: updated,
18278
+ inversion: invertToAntiPattern(updated, reason, config2)
18279
+ };
18280
+ }
18281
+ return { pattern: updated };
18282
+ }
18283
+ function extractPatternsFromDescription(description) {
18284
+ const patterns = [];
18285
+ const strategyPatterns = [
18286
+ {
18287
+ regex: /split(?:ting)?\s+by\s+file\s+type/i,
18288
+ pattern: "Split by file type"
18289
+ },
18290
+ {
18291
+ regex: /split(?:ting)?\s+by\s+component/i,
18292
+ pattern: "Split by component"
18293
+ },
18294
+ {
18295
+ regex: /split(?:ting)?\s+by\s+layer/i,
18296
+ pattern: "Split by layer (UI/logic/data)"
18297
+ },
18298
+ { regex: /split(?:ting)?\s+by\s+feature/i, pattern: "Split by feature" },
18299
+ {
18300
+ regex: /one\s+file\s+per\s+(?:sub)?task/i,
18301
+ pattern: "One file per subtask"
18302
+ },
18303
+ { regex: /shared\s+types?\s+first/i, pattern: "Handle shared types first" },
18304
+ { regex: /api\s+(?:routes?)?\s+separate/i, pattern: "Separate API routes" },
18305
+ {
18306
+ regex: /tests?\s+(?:with|alongside)\s+(?:code|implementation)/i,
18307
+ pattern: "Tests alongside implementation"
18308
+ },
18309
+ {
18310
+ regex: /tests?\s+(?:in\s+)?separate\s+(?:sub)?task/i,
18311
+ pattern: "Tests in separate subtask"
18312
+ },
18313
+ {
18314
+ regex: /parallel(?:ize)?\s+(?:all|everything)/i,
18315
+ pattern: "Maximize parallelization"
18316
+ },
18317
+ {
18318
+ regex: /sequential\s+(?:order|execution)/i,
18319
+ pattern: "Sequential execution order"
18320
+ },
18321
+ {
18322
+ regex: /dependency\s+(?:chain|order)/i,
18323
+ pattern: "Respect dependency chain"
18324
+ }
18325
+ ];
18326
+ for (const { regex, pattern } of strategyPatterns) {
18327
+ if (regex.test(description)) {
18328
+ patterns.push(pattern);
18329
+ }
18330
+ }
18331
+ return patterns;
18332
+ }
18333
+ function createPattern(content, tags = []) {
18334
+ const now = new Date().toISOString();
18335
+ return {
18336
+ id: `pattern-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
18337
+ content,
18338
+ kind: "pattern",
18339
+ is_negative: false,
18340
+ success_count: 0,
18341
+ failure_count: 0,
18342
+ created_at: now,
18343
+ updated_at: now,
18344
+ tags,
18345
+ example_beads: []
18346
+ };
18347
+ }
18348
+ function formatAntiPatternsForPrompt(patterns) {
18349
+ const antiPatterns = patterns.filter((p) => p.kind === "anti_pattern");
18350
+ if (antiPatterns.length === 0) {
18351
+ return "";
18352
+ }
18353
+ const lines = [
18354
+ "## Anti-Patterns to Avoid",
18355
+ "",
18356
+ "Based on past failures, avoid these decomposition strategies:",
18357
+ "",
18358
+ ...antiPatterns.map((p) => `- ${p.content}`),
18359
+ ""
18360
+ ];
18361
+ return lines.join(`
18362
+ `);
18363
+ }
18364
+ function formatSuccessfulPatternsForPrompt(patterns, minSuccessRate = 0.7) {
18365
+ const successful = patterns.filter((p) => {
18366
+ if (p.kind === "anti_pattern")
18367
+ return false;
18368
+ const total = p.success_count + p.failure_count;
18369
+ if (total < 2)
18370
+ return false;
18371
+ return p.success_count / total >= minSuccessRate;
18372
+ });
18373
+ if (successful.length === 0) {
18374
+ return "";
18375
+ }
18376
+ const lines = [
18377
+ "## Successful Patterns",
18378
+ "",
18379
+ "These decomposition strategies have worked well in the past:",
18380
+ "",
18381
+ ...successful.map((p) => {
18382
+ const total = p.success_count + p.failure_count;
18383
+ const rate = Math.round(p.success_count / total * 100);
18384
+ return `- ${p.content} (${rate}% success rate)`;
18385
+ }),
18386
+ ""
18387
+ ];
18388
+ return lines.join(`
18389
+ `);
18390
+ }
18391
+
18392
+ class InMemoryPatternStorage {
18393
+ patterns = new Map;
18394
+ async store(pattern) {
18395
+ this.patterns.set(pattern.id, pattern);
18396
+ }
18397
+ async get(id) {
18398
+ return this.patterns.get(id) ?? null;
18399
+ }
18400
+ async getAll() {
18401
+ return Array.from(this.patterns.values());
18402
+ }
18403
+ async getAntiPatterns() {
18404
+ return Array.from(this.patterns.values()).filter((p) => p.kind === "anti_pattern");
18405
+ }
18406
+ async getByTag(tag) {
18407
+ return Array.from(this.patterns.values()).filter((p) => p.tags.includes(tag));
18408
+ }
18409
+ async findByContent(content) {
18410
+ const lower = content.toLowerCase();
18411
+ return Array.from(this.patterns.values()).filter((p) => p.content.toLowerCase().includes(lower));
18412
+ }
18413
+ }
18414
+ var PatternKindSchema, DecompositionPatternSchema, PatternInversionResultSchema, MAX_EXAMPLE_BEADS = 10, DEFAULT_ANTI_PATTERN_CONFIG, antiPatternSchemas;
18415
+ var init_anti_patterns = __esm(() => {
18416
+ init_zod();
18417
+ PatternKindSchema = exports_external.enum(["pattern", "anti_pattern"]);
18418
+ DecompositionPatternSchema = exports_external.object({
18419
+ id: exports_external.string(),
18420
+ content: exports_external.string(),
18421
+ kind: PatternKindSchema,
18422
+ is_negative: exports_external.boolean(),
18423
+ success_count: exports_external.number().int().min(0).default(0),
18424
+ failure_count: exports_external.number().int().min(0).default(0),
18425
+ created_at: exports_external.string(),
18426
+ updated_at: exports_external.string(),
18427
+ reason: exports_external.string().optional(),
18428
+ tags: exports_external.array(exports_external.string()).default([]),
18429
+ example_beads: exports_external.array(exports_external.string()).default([])
18430
+ });
18431
+ PatternInversionResultSchema = exports_external.object({
18432
+ original: DecompositionPatternSchema,
18433
+ inverted: DecompositionPatternSchema,
18434
+ reason: exports_external.string()
18435
+ });
18436
+ DEFAULT_ANTI_PATTERN_CONFIG = {
18437
+ minObservations: 3,
18438
+ failureRatioThreshold: 0.6,
18439
+ antiPatternPrefix: "AVOID: "
18440
+ };
18441
+ antiPatternSchemas = {
18442
+ PatternKindSchema,
18443
+ DecompositionPatternSchema,
18444
+ PatternInversionResultSchema
18445
+ };
18446
+ });
18447
+
18448
+ // src/pattern-maturity.ts
18449
+ var exports_pattern_maturity = {};
18450
+ __export(exports_pattern_maturity, {
18451
+ updatePatternMaturity: () => updatePatternMaturity,
18452
+ promotePattern: () => promotePattern,
18453
+ maturitySchemas: () => maturitySchemas,
18454
+ getMaturityMultiplier: () => getMaturityMultiplier,
18455
+ formatPatternsWithMaturityForPrompt: () => formatPatternsWithMaturityForPrompt,
18456
+ formatMaturityForPrompt: () => formatMaturityForPrompt,
18457
+ deprecatePattern: () => deprecatePattern,
18458
+ createPatternMaturity: () => createPatternMaturity,
18459
+ calculateMaturityState: () => calculateMaturityState,
18460
+ calculateDecayedCounts: () => calculateDecayedCounts,
18461
+ PatternMaturitySchema: () => PatternMaturitySchema,
18462
+ MaturityStateSchema: () => MaturityStateSchema,
18463
+ MaturityFeedbackSchema: () => MaturityFeedbackSchema,
18464
+ InMemoryMaturityStorage: () => InMemoryMaturityStorage,
18465
+ DEFAULT_MATURITY_CONFIG: () => DEFAULT_MATURITY_CONFIG
18466
+ });
18467
+ function calculateDecayedCounts(feedbackEvents, config2 = DEFAULT_MATURITY_CONFIG, now = new Date) {
18468
+ let decayedHelpful = 0;
18469
+ let decayedHarmful = 0;
18470
+ for (const event of feedbackEvents) {
18471
+ const decay = calculateDecayedValue(event.timestamp, now, config2.halfLifeDays);
18472
+ const value = event.weight * decay;
18473
+ if (event.type === "helpful") {
18474
+ decayedHelpful += value;
18475
+ } else {
18476
+ decayedHarmful += value;
18477
+ }
18478
+ }
18479
+ return { decayedHelpful, decayedHarmful };
18480
+ }
18481
+ function calculateMaturityState(feedbackEvents, config2 = DEFAULT_MATURITY_CONFIG, now = new Date) {
18482
+ const { decayedHelpful, decayedHarmful } = calculateDecayedCounts(feedbackEvents, config2, now);
18483
+ const total = decayedHelpful + decayedHarmful;
18484
+ const safeTotal = total > FLOAT_EPSILON ? total : 0;
18485
+ const harmfulRatio = safeTotal > 0 ? decayedHarmful / safeTotal : 0;
18486
+ if (harmfulRatio > config2.deprecationThreshold && safeTotal >= config2.minFeedback - FLOAT_EPSILON) {
18487
+ return "deprecated";
18488
+ }
18489
+ if (safeTotal < config2.minFeedback - FLOAT_EPSILON) {
18490
+ return "candidate";
18491
+ }
18492
+ if (decayedHelpful >= config2.minHelpful - FLOAT_EPSILON && harmfulRatio < config2.maxHarmful) {
18493
+ return "proven";
18494
+ }
18495
+ return "established";
18496
+ }
18497
+ function createPatternMaturity(patternId) {
18498
+ return {
18499
+ pattern_id: patternId,
18500
+ state: "candidate",
18501
+ helpful_count: 0,
18502
+ harmful_count: 0,
18503
+ last_validated: new Date().toISOString()
18504
+ };
18505
+ }
18506
+ function updatePatternMaturity(maturity, feedbackEvents, config2 = DEFAULT_MATURITY_CONFIG) {
18507
+ const now = new Date;
18508
+ const newState = calculateMaturityState(feedbackEvents, config2, now);
18509
+ const helpfulCount = feedbackEvents.filter((e) => e.type === "helpful").length;
18510
+ const harmfulCount = feedbackEvents.filter((e) => e.type === "harmful").length;
18511
+ const updated = {
18512
+ ...maturity,
18513
+ state: newState,
18514
+ helpful_count: helpfulCount,
18515
+ harmful_count: harmfulCount,
18516
+ last_validated: now.toISOString()
18517
+ };
18518
+ if (newState === "proven" && maturity.state !== "proven") {
18519
+ updated.promoted_at = now.toISOString();
18520
+ }
18521
+ if (newState === "deprecated" && maturity.state !== "deprecated") {
18522
+ updated.deprecated_at = now.toISOString();
18523
+ }
18524
+ return updated;
18525
+ }
18526
+ function promotePattern(maturity) {
18527
+ if (maturity.state === "deprecated") {
18528
+ throw new Error("Cannot promote a deprecated pattern");
18529
+ }
18530
+ if (maturity.state === "proven") {
18531
+ console.warn(`[PatternMaturity] Pattern already proven: ${maturity.pattern_id}`);
18532
+ return maturity;
18533
+ }
18534
+ if (maturity.state === "candidate" && maturity.helpful_count < 3) {
18535
+ console.warn(`[PatternMaturity] Promoting candidate with insufficient data: ${maturity.pattern_id} (${maturity.helpful_count} helpful observations)`);
18536
+ }
18537
+ const now = new Date().toISOString();
18538
+ return {
18539
+ ...maturity,
18540
+ state: "proven",
18541
+ promoted_at: now,
18542
+ last_validated: now
18543
+ };
18544
+ }
18545
+ function deprecatePattern(maturity, _reason) {
18546
+ if (maturity.state === "deprecated") {
18547
+ return maturity;
18548
+ }
18549
+ const now = new Date().toISOString();
18550
+ return {
18551
+ ...maturity,
18552
+ state: "deprecated",
18553
+ deprecated_at: now,
18554
+ last_validated: now
18555
+ };
18556
+ }
18557
+ function getMaturityMultiplier(state) {
18558
+ const multipliers = {
18559
+ candidate: 0.5,
18560
+ established: 1,
18561
+ proven: 1.5,
18562
+ deprecated: 0
18563
+ };
18564
+ return multipliers[state];
18565
+ }
18566
+ function formatMaturityForPrompt(maturity) {
18567
+ const total = maturity.helpful_count + maturity.harmful_count;
18568
+ if (total < 3) {
18569
+ return `[LIMITED DATA - ${total} observation${total !== 1 ? "s" : ""}]`;
18570
+ }
18571
+ const harmfulRatio = total > 0 ? Math.round(maturity.harmful_count / total * 100) : 0;
18572
+ const helpfulRatio = total > 0 ? Math.round(maturity.helpful_count / total * 100) : 0;
18573
+ switch (maturity.state) {
18574
+ case "candidate":
18575
+ return `[CANDIDATE - ${total} observations, needs more data]`;
18576
+ case "established":
18577
+ return `[ESTABLISHED - ${helpfulRatio}% helpful, ${harmfulRatio}% harmful from ${total} observations]`;
18578
+ case "proven":
18579
+ return `[PROVEN - ${helpfulRatio}% helpful from ${total} observations]`;
18580
+ case "deprecated":
18581
+ return `[DEPRECATED - ${harmfulRatio}% harmful, avoid using]`;
18582
+ }
18583
+ }
18584
+ function formatPatternsWithMaturityForPrompt(patterns) {
18585
+ const proven = [];
18586
+ const established = [];
18587
+ const candidates = [];
18588
+ const deprecated = [];
18589
+ for (const [content, maturity] of patterns) {
18590
+ const formatted = `- ${content} ${formatMaturityForPrompt(maturity)}`;
18591
+ switch (maturity.state) {
18592
+ case "proven":
18593
+ proven.push(formatted);
18594
+ break;
18595
+ case "established":
18596
+ established.push(formatted);
18597
+ break;
18598
+ case "candidate":
18599
+ candidates.push(formatted);
18600
+ break;
18601
+ case "deprecated":
18602
+ deprecated.push(formatted);
18603
+ break;
18604
+ }
18605
+ }
18606
+ const sections = [];
18607
+ if (proven.length > 0) {
18608
+ sections.push(`## Proven Patterns
18609
+
18610
+ These patterns consistently work well:
18611
+
18612
+ ` + proven.join(`
18613
+ `));
18614
+ }
18615
+ if (established.length > 0) {
18616
+ sections.push(`## Established Patterns
18617
+
18618
+ These patterns have track records:
18619
+
18620
+ ` + established.join(`
18621
+ `));
18622
+ }
18623
+ if (candidates.length > 0) {
18624
+ sections.push(`## Candidate Patterns
18625
+
18626
+ These patterns need more validation:
18627
+
18628
+ ` + candidates.join(`
18629
+ `));
18630
+ }
18631
+ if (deprecated.length > 0) {
18632
+ sections.push(`## Deprecated Patterns
18633
+
18634
+ AVOID these patterns - they have poor track records:
18635
+
18636
+ ` + deprecated.join(`
18637
+ `));
18638
+ }
18639
+ return sections.join(`
18640
+
18641
+ `);
18642
+ }
18643
+
18644
+ class InMemoryMaturityStorage {
18645
+ maturities = new Map;
18646
+ feedback = [];
18647
+ async store(maturity) {
18648
+ this.maturities.set(maturity.pattern_id, maturity);
18649
+ }
18650
+ async get(patternId) {
18651
+ return this.maturities.get(patternId) ?? null;
18652
+ }
18653
+ async getAll() {
18654
+ return Array.from(this.maturities.values());
18655
+ }
18656
+ async getByState(state) {
18657
+ return Array.from(this.maturities.values()).filter((m) => m.state === state);
18658
+ }
18659
+ async storeFeedback(feedback) {
18660
+ this.feedback.push(feedback);
18661
+ }
18662
+ async getFeedback(patternId) {
18663
+ return this.feedback.filter((f) => f.pattern_id === patternId);
18664
+ }
18665
+ }
18666
+ var FLOAT_EPSILON = 0.01, MaturityStateSchema, PatternMaturitySchema, MaturityFeedbackSchema, DEFAULT_MATURITY_CONFIG, maturitySchemas;
18667
+ var init_pattern_maturity = __esm(() => {
18668
+ init_zod();
18669
+ init_learning();
18670
+ MaturityStateSchema = exports_external.enum([
18671
+ "candidate",
18672
+ "established",
18673
+ "proven",
18674
+ "deprecated"
18675
+ ]);
18676
+ PatternMaturitySchema = exports_external.object({
18677
+ pattern_id: exports_external.string(),
18678
+ state: MaturityStateSchema,
18679
+ helpful_count: exports_external.number().int().min(0),
18680
+ harmful_count: exports_external.number().int().min(0),
18681
+ last_validated: exports_external.string(),
18682
+ promoted_at: exports_external.string().optional(),
18683
+ deprecated_at: exports_external.string().optional()
18684
+ });
18685
+ MaturityFeedbackSchema = exports_external.object({
18686
+ pattern_id: exports_external.string(),
18687
+ type: exports_external.enum(["helpful", "harmful"]),
18688
+ timestamp: exports_external.string(),
18689
+ weight: exports_external.number().min(0).max(1).default(1)
18690
+ });
18691
+ DEFAULT_MATURITY_CONFIG = {
18692
+ minFeedback: 3,
18693
+ minHelpful: 5,
18694
+ maxHarmful: 0.15,
18695
+ deprecationThreshold: 0.3,
18696
+ halfLifeDays: 90
18697
+ };
18698
+ maturitySchemas = {
18699
+ MaturityStateSchema,
18700
+ PatternMaturitySchema,
18701
+ MaturityFeedbackSchema
18702
+ };
18703
+ });
18704
+
18705
+ // src/storage.ts
18706
+ var exports_storage = {};
18707
+ __export(exports_storage, {
18708
+ setStorage: () => setStorage,
18709
+ resetStorage: () => resetStorage,
18710
+ resetSessionStats: () => resetSessionStats,
18711
+ resetCommandCache: () => resetCommandCache,
18712
+ isSemanticMemoryAvailable: () => isSemanticMemoryAvailable,
18713
+ getTestCollectionName: () => getTestCollectionName,
18714
+ getStorage: () => getStorage,
18715
+ getSessionStats: () => getSessionStats,
18716
+ getResolvedCommand: () => getResolvedCommand,
18717
+ getDefaultStorageConfig: () => getDefaultStorageConfig,
18718
+ createStorageWithFallback: () => createStorageWithFallback,
18719
+ createStorage: () => createStorage,
18720
+ SemanticMemoryStorage: () => SemanticMemoryStorage,
18721
+ InMemoryStorage: () => InMemoryStorage,
18722
+ DEFAULT_STORAGE_CONFIG: () => DEFAULT_STORAGE_CONFIG
18723
+ });
18724
+ async function resolveSemanticMemoryCommand() {
18725
+ if (cachedCommand)
18726
+ return cachedCommand;
18727
+ const nativeResult = await Bun.$`which semantic-memory`.quiet().nothrow();
18728
+ if (nativeResult.exitCode === 0) {
18729
+ cachedCommand = ["semantic-memory"];
18730
+ return cachedCommand;
18731
+ }
18732
+ cachedCommand = ["bunx", "semantic-memory"];
18733
+ return cachedCommand;
18734
+ }
18735
+ async function execSemanticMemory(args) {
18736
+ try {
18737
+ const cmd = await resolveSemanticMemoryCommand();
18738
+ const fullCmd = [...cmd, ...args];
18739
+ const proc = Bun.spawn(fullCmd, {
18740
+ stdout: "pipe",
18741
+ stderr: "pipe"
18742
+ });
18743
+ try {
18744
+ const stdout = Buffer.from(await new Response(proc.stdout).arrayBuffer());
18745
+ const stderr = Buffer.from(await new Response(proc.stderr).arrayBuffer());
18746
+ const exitCode = await proc.exited;
18747
+ return { exitCode, stdout, stderr };
18748
+ } finally {
18749
+ proc.kill();
18750
+ }
18751
+ } catch (error45) {
18752
+ const errorMessage = error45 instanceof Error ? error45.message : String(error45);
18753
+ return {
18754
+ exitCode: 1,
18755
+ stdout: Buffer.from(""),
18756
+ stderr: Buffer.from(`Error executing semantic-memory: ${errorMessage}`)
18757
+ };
18758
+ }
18759
+ }
18760
+ function resetCommandCache() {
18761
+ cachedCommand = null;
18762
+ }
18763
+ function getTestCollectionName() {
18764
+ return `test-${Date.now()}`;
18765
+ }
18766
+ function getCollectionNames() {
18767
+ const base = {
18768
+ feedback: "swarm-feedback",
18769
+ patterns: "swarm-patterns",
18770
+ maturity: "swarm-maturity"
18771
+ };
18772
+ const testSuffix = process.env.TEST_SEMANTIC_MEMORY_COLLECTION;
18773
+ if (testSuffix) {
18774
+ return {
18775
+ feedback: `${base.feedback}-${testSuffix}`,
18776
+ patterns: `${base.patterns}-${testSuffix}`,
18777
+ maturity: `${base.maturity}-${testSuffix}`
18778
+ };
18779
+ }
18780
+ if (process.env.TEST_MEMORY_COLLECTIONS === "true") {
18781
+ return {
18782
+ feedback: `${base.feedback}-test`,
18783
+ patterns: `${base.patterns}-test`,
18784
+ maturity: `${base.maturity}-test`
18785
+ };
18786
+ }
18787
+ return base;
18788
+ }
18789
+ function getDefaultStorageConfig() {
18790
+ return {
18791
+ backend: "semantic-memory",
18792
+ collections: getCollectionNames(),
18793
+ useSemanticSearch: true
18794
+ };
18795
+ }
18796
+ function resetSessionStats() {
18797
+ sessionStats = {
18798
+ storesCount: 0,
18799
+ queriesCount: 0,
18800
+ sessionStart: Date.now(),
18801
+ lastAlertCheck: Date.now()
18802
+ };
18803
+ }
18804
+ function getSessionStats() {
18805
+ return { ...sessionStats };
18806
+ }
18807
+
18808
+ class SemanticMemoryStorage {
18809
+ config;
18810
+ constructor(config2 = {}) {
18811
+ this.config = { ...getDefaultStorageConfig(), ...config2 };
18812
+ }
18813
+ async checkLowUsageAlert() {
18814
+ const TEN_MINUTES = 10 * 60 * 1000;
18815
+ const now = Date.now();
18816
+ const sessionDuration = now - sessionStats.sessionStart;
18817
+ const timeSinceLastAlert = now - sessionStats.lastAlertCheck;
18818
+ if (sessionDuration >= TEN_MINUTES && sessionStats.storesCount < 1 && timeSinceLastAlert >= TEN_MINUTES) {
18819
+ console.warn(`[storage] LOW USAGE ALERT: ${sessionStats.storesCount} stores after ${Math.floor(sessionDuration / 60000)} minutes`);
18820
+ sessionStats.lastAlertCheck = now;
18821
+ }
18822
+ }
18823
+ async store(collection, data, metadata) {
18824
+ const content = typeof data === "string" ? data : JSON.stringify(data);
18825
+ const args = ["store", content, "--collection", collection];
18826
+ if (metadata) {
18827
+ args.push("--metadata", JSON.stringify(metadata));
18828
+ }
18829
+ sessionStats.storesCount++;
18830
+ const result = await execSemanticMemory(args);
18831
+ if (result.exitCode !== 0) {
18832
+ console.warn(`[storage] semantic-memory store() failed with exit code ${result.exitCode}: ${result.stderr.toString().trim()}`);
18833
+ }
18834
+ await this.checkLowUsageAlert();
18835
+ }
18836
+ async find(collection, query, limit = 10, useFts = false) {
18837
+ const args = [
18838
+ "find",
18839
+ query,
18840
+ "--collection",
18841
+ collection,
18842
+ "--limit",
18843
+ String(limit),
18844
+ "--json"
18845
+ ];
18846
+ if (useFts) {
18847
+ args.push("--fts");
18848
+ }
18849
+ sessionStats.queriesCount++;
18850
+ const result = await execSemanticMemory(args);
18851
+ if (result.exitCode !== 0) {
18852
+ console.warn(`[storage] semantic-memory find() failed with exit code ${result.exitCode}: ${result.stderr.toString().trim()}`);
18853
+ return [];
18854
+ }
18855
+ try {
18856
+ const output = result.stdout.toString().trim();
18857
+ if (!output)
18858
+ return [];
18859
+ const parsed = JSON.parse(output);
18860
+ const results = Array.isArray(parsed) ? parsed : parsed.results || [];
18861
+ return results.map((r) => {
18862
+ const content = r.content || r.information || "";
18863
+ try {
18864
+ return JSON.parse(content);
18865
+ } catch {
18866
+ return content;
18867
+ }
18868
+ });
18869
+ } catch (error45) {
18870
+ console.warn(`[storage] Failed to parse semantic-memory find() output: ${error45 instanceof Error ? error45.message : String(error45)}`);
18871
+ return [];
18872
+ }
18873
+ }
18874
+ async list(collection) {
18875
+ sessionStats.queriesCount++;
18876
+ const result = await execSemanticMemory([
18877
+ "list",
18878
+ "--collection",
18879
+ collection,
18880
+ "--json"
18881
+ ]);
18882
+ if (result.exitCode !== 0) {
18883
+ console.warn(`[storage] semantic-memory list() failed with exit code ${result.exitCode}: ${result.stderr.toString().trim()}`);
18884
+ return [];
18885
+ }
18886
+ try {
18887
+ const output = result.stdout.toString().trim();
18888
+ if (!output)
18889
+ return [];
18890
+ const parsed = JSON.parse(output);
18891
+ const items = Array.isArray(parsed) ? parsed : parsed.items || [];
18892
+ return items.map((item) => {
18893
+ const content = item.content || item.information || "";
18894
+ try {
18895
+ return JSON.parse(content);
18896
+ } catch {
18897
+ return content;
18898
+ }
18899
+ });
18900
+ } catch (error45) {
18901
+ console.warn(`[storage] Failed to parse semantic-memory list() output: ${error45 instanceof Error ? error45.message : String(error45)}`);
18902
+ return [];
18903
+ }
18904
+ }
18905
+ async storeFeedback(event) {
18906
+ await this.store(this.config.collections.feedback, event, {
18907
+ criterion: event.criterion,
18908
+ type: event.type,
18909
+ bead_id: event.bead_id || "",
18910
+ timestamp: event.timestamp
18911
+ });
18912
+ }
18913
+ async getFeedbackByCriterion(criterion) {
18914
+ return this.find(this.config.collections.feedback, criterion, 100, true);
18915
+ }
18916
+ async getFeedbackByBead(beadId) {
18917
+ return this.find(this.config.collections.feedback, beadId, 100, true);
18918
+ }
18919
+ async getAllFeedback() {
18920
+ return this.list(this.config.collections.feedback);
18921
+ }
18922
+ async findSimilarFeedback(query, limit = 10) {
18923
+ return this.find(this.config.collections.feedback, query, limit, !this.config.useSemanticSearch);
18924
+ }
18925
+ async storePattern(pattern) {
18926
+ await this.store(this.config.collections.patterns, pattern, {
18927
+ id: pattern.id,
18928
+ kind: pattern.kind,
18929
+ is_negative: pattern.is_negative,
18930
+ tags: pattern.tags.join(",")
18931
+ });
18932
+ }
18933
+ async getPattern(id) {
18934
+ const all = await this.list(this.config.collections.patterns);
18935
+ return all.find((p) => p.id === id) || null;
18936
+ }
18937
+ async getAllPatterns() {
18938
+ return this.list(this.config.collections.patterns);
18939
+ }
18940
+ async getAntiPatterns() {
18941
+ const all = await this.getAllPatterns();
18942
+ return all.filter((p) => p.kind === "anti_pattern");
18943
+ }
18944
+ async getPatternsByTag(tag) {
18945
+ const results = await this.find(this.config.collections.patterns, tag, 100, true);
18946
+ return results.filter((p) => p.tags.includes(tag));
18947
+ }
18948
+ async findSimilarPatterns(query, limit = 10) {
18949
+ return this.find(this.config.collections.patterns, query, limit, !this.config.useSemanticSearch);
18950
+ }
18951
+ async storeMaturity(maturity) {
18952
+ await this.store(this.config.collections.maturity, maturity, {
18953
+ pattern_id: maturity.pattern_id,
18954
+ state: maturity.state
18955
+ });
18956
+ }
18957
+ async getMaturity(patternId) {
18958
+ const all = await this.list(this.config.collections.maturity);
18959
+ return all.find((m) => m.pattern_id === patternId) || null;
18960
+ }
18961
+ async getAllMaturity() {
18962
+ return this.list(this.config.collections.maturity);
18963
+ }
18964
+ async getMaturityByState(state) {
18965
+ const all = await this.getAllMaturity();
18966
+ return all.filter((m) => m.state === state);
18967
+ }
18968
+ async storeMaturityFeedback(feedback) {
18969
+ await this.store(this.config.collections.maturity + "-feedback", feedback, {
18970
+ pattern_id: feedback.pattern_id,
18971
+ type: feedback.type,
18972
+ timestamp: feedback.timestamp
18973
+ });
18974
+ }
18975
+ async getMaturityFeedback(patternId) {
18976
+ const all = await this.list(this.config.collections.maturity + "-feedback");
18977
+ return all.filter((f) => f.pattern_id === patternId);
18978
+ }
18979
+ async close() {}
18980
+ }
18981
+
18982
+ class InMemoryStorage {
18983
+ feedback;
18984
+ patterns;
18985
+ maturity;
18986
+ constructor() {
18987
+ this.feedback = new InMemoryFeedbackStorage;
18988
+ this.patterns = new InMemoryPatternStorage;
18989
+ this.maturity = new InMemoryMaturityStorage;
18990
+ }
18991
+ async storeFeedback(event) {
18992
+ return this.feedback.store(event);
18993
+ }
18994
+ async getFeedbackByCriterion(criterion) {
18995
+ return this.feedback.getByCriterion(criterion);
18996
+ }
18997
+ async getFeedbackByBead(beadId) {
18998
+ return this.feedback.getByBead(beadId);
18999
+ }
19000
+ async getAllFeedback() {
19001
+ return this.feedback.getAll();
19002
+ }
19003
+ async findSimilarFeedback(query, limit = 10) {
19004
+ const all = await this.feedback.getAll();
19005
+ const lowerQuery = query.toLowerCase();
19006
+ const filtered = all.filter((event) => event.criterion.toLowerCase().includes(lowerQuery) || event.bead_id && event.bead_id.toLowerCase().includes(lowerQuery) || event.context && event.context.toLowerCase().includes(lowerQuery));
19007
+ return filtered.slice(0, limit);
19008
+ }
19009
+ async storePattern(pattern) {
19010
+ return this.patterns.store(pattern);
19011
+ }
19012
+ async getPattern(id) {
19013
+ return this.patterns.get(id);
19014
+ }
19015
+ async getAllPatterns() {
19016
+ return this.patterns.getAll();
19017
+ }
19018
+ async getAntiPatterns() {
19019
+ return this.patterns.getAntiPatterns();
19020
+ }
19021
+ async getPatternsByTag(tag) {
19022
+ return this.patterns.getByTag(tag);
19023
+ }
19024
+ async findSimilarPatterns(query, limit = 10) {
19025
+ const results = await this.patterns.findByContent(query);
19026
+ return results.slice(0, limit);
19027
+ }
19028
+ async storeMaturity(maturity) {
19029
+ return this.maturity.store(maturity);
19030
+ }
19031
+ async getMaturity(patternId) {
19032
+ return this.maturity.get(patternId);
19033
+ }
19034
+ async getAllMaturity() {
19035
+ return this.maturity.getAll();
19036
+ }
19037
+ async getMaturityByState(state) {
19038
+ return this.maturity.getByState(state);
19039
+ }
19040
+ async storeMaturityFeedback(feedback) {
19041
+ return this.maturity.storeFeedback(feedback);
19042
+ }
19043
+ async getMaturityFeedback(patternId) {
19044
+ return this.maturity.getFeedback(patternId);
19045
+ }
19046
+ async close() {}
19047
+ }
19048
+ function createStorage(config2 = {}) {
19049
+ const fullConfig = { ...getDefaultStorageConfig(), ...config2 };
19050
+ switch (fullConfig.backend) {
19051
+ case "semantic-memory":
19052
+ return new SemanticMemoryStorage(fullConfig);
19053
+ case "memory":
19054
+ return new InMemoryStorage;
19055
+ default:
19056
+ throw new Error(`Unknown storage backend: ${fullConfig.backend}`);
19057
+ }
19058
+ }
19059
+ async function isSemanticMemoryAvailable() {
19060
+ try {
19061
+ const result = await execSemanticMemory(["stats"]);
19062
+ return result.exitCode === 0;
19063
+ } catch {
19064
+ return false;
19065
+ }
19066
+ }
19067
+ async function getResolvedCommand() {
19068
+ return resolveSemanticMemoryCommand();
19069
+ }
19070
+ async function createStorageWithFallback(config2 = {}) {
19071
+ if (config2.backend === "memory") {
19072
+ return new InMemoryStorage;
19073
+ }
19074
+ const available = await isSemanticMemoryAvailable();
19075
+ if (available) {
19076
+ return new SemanticMemoryStorage(config2);
19077
+ }
19078
+ console.warn("semantic-memory not available, falling back to in-memory storage");
19079
+ return new InMemoryStorage;
19080
+ }
19081
+ async function getStorage() {
19082
+ if (!globalStoragePromise) {
19083
+ globalStoragePromise = createStorageWithFallback().then((storage) => {
19084
+ globalStorage = storage;
19085
+ return storage;
19086
+ });
19087
+ }
19088
+ return globalStoragePromise;
19089
+ }
19090
+ function setStorage(storage) {
19091
+ globalStorage = storage;
19092
+ globalStoragePromise = Promise.resolve(storage);
19093
+ }
19094
+ async function resetStorage() {
19095
+ if (globalStorage) {
19096
+ await globalStorage.close();
19097
+ globalStorage = null;
19098
+ }
19099
+ globalStoragePromise = null;
19100
+ }
19101
+ var cachedCommand = null, DEFAULT_STORAGE_CONFIG, sessionStats, globalStorage = null, globalStoragePromise = null;
19102
+ var init_storage = __esm(() => {
19103
+ init_learning();
19104
+ init_anti_patterns();
19105
+ init_pattern_maturity();
19106
+ DEFAULT_STORAGE_CONFIG = getDefaultStorageConfig();
19107
+ sessionStats = {
19108
+ storesCount: 0,
19109
+ queriesCount: 0,
19110
+ sessionStart: Date.now(),
19111
+ lastAlertCheck: Date.now()
19112
+ };
19113
+ });
19114
+
18210
19115
  // ../../node_modules/.bun/effect@3.19.12/node_modules/effect/dist/esm/Function.js
18211
19116
  function pipe2(a, ab, bc, cd, de, ef, fg, gh, hi) {
18212
19117
  switch (arguments.length) {
@@ -41682,6 +42587,89 @@ This will be recorded as a negative learning signal.`;
41682
42587
  reservationsReleaseError = error45 instanceof Error ? error45.message : String(error45);
41683
42588
  console.warn(`[swarm] Failed to release file reservations for ${args.agent_name}:`, error45);
41684
42589
  }
42590
+ let outcomeScored = false;
42591
+ let outcomeFeedbackType;
42592
+ let outcomeScore;
42593
+ let outcomeReasoning;
42594
+ try {
42595
+ const { scoreOutcome: scoreOutcome2, OutcomeSignalsSchema: OutcomeSignalsSchema2 } = await Promise.resolve().then(() => (init_learning(), exports_learning));
42596
+ const { getStorage: getStorage2 } = await Promise.resolve().then(() => (init_storage(), exports_storage));
42597
+ const { updatePatternMaturity: updatePatternMaturity2 } = await Promise.resolve().then(() => (init_pattern_maturity(), exports_pattern_maturity));
42598
+ const durationMs = args.start_time ? Date.now() - args.start_time : 0;
42599
+ const signals = OutcomeSignalsSchema2.parse({
42600
+ bead_id: args.bead_id,
42601
+ duration_ms: durationMs,
42602
+ error_count: args.error_count ?? 0,
42603
+ retry_count: args.retry_count ?? 0,
42604
+ success: true,
42605
+ files_touched: args.files_touched || [],
42606
+ timestamp: new Date().toISOString(),
42607
+ strategy: undefined
42608
+ });
42609
+ const outcome = scoreOutcome2(signals);
42610
+ outcomeScored = true;
42611
+ outcomeFeedbackType = outcome.type;
42612
+ outcomeScore = outcome.score;
42613
+ outcomeReasoning = outcome.reasoning;
42614
+ const storage = await getStorage2();
42615
+ const { outcomeToFeedback: outcomeToFeedback2, scoreImplicitFeedback: scoreImplicitFeedback2 } = await Promise.resolve().then(() => (init_learning(), exports_learning));
42616
+ const scoredOutcome = scoreImplicitFeedback2(signals);
42617
+ const feedbackEvent = outcomeToFeedback2(scoredOutcome, "task_completion");
42618
+ await storage.storeFeedback(feedbackEvent);
42619
+ if (signals.strategy) {
42620
+ const maturity = await storage.getMaturity(signals.strategy);
42621
+ if (maturity) {
42622
+ const allFeedback = await storage.getMaturityFeedback(signals.strategy);
42623
+ const updated = updatePatternMaturity2(maturity, allFeedback);
42624
+ await storage.storeMaturity(updated);
42625
+ }
42626
+ }
42627
+ } catch (error45) {
42628
+ console.warn(`[swarm_complete] Failed to score outcome (non-fatal): ${error45 instanceof Error ? error45.message : String(error45)}`);
42629
+ }
42630
+ const patternObservations = {
42631
+ extracted_patterns: [],
42632
+ recorded_count: 0,
42633
+ inversions: []
42634
+ };
42635
+ try {
42636
+ const {
42637
+ extractPatternsFromDescription: extractPatternsFromDescription2,
42638
+ recordPatternObservation: recordPatternObservation2,
42639
+ createPattern: createPattern2,
42640
+ InMemoryPatternStorage: InMemoryPatternStorage2
42641
+ } = await Promise.resolve().then(() => (init_anti_patterns(), exports_anti_patterns));
42642
+ const epicIdForPattern = cell.parent_id || (args.bead_id.includes(".") ? args.bead_id.split(".")[0] : args.bead_id);
42643
+ const epicCell = await adapter.getCell(args.project_key, epicIdForPattern);
42644
+ if (epicCell?.description) {
42645
+ const patterns = extractPatternsFromDescription2(epicCell.description);
42646
+ patternObservations.extracted_patterns = patterns;
42647
+ if (patterns.length > 0) {
42648
+ const patternStorage = new InMemoryPatternStorage2;
42649
+ for (const patternContent of patterns) {
42650
+ const existingPatterns = await patternStorage.findByContent(patternContent);
42651
+ let pattern = existingPatterns[0];
42652
+ if (!pattern) {
42653
+ pattern = createPattern2(patternContent, ["decomposition", "auto-detected"]);
42654
+ await patternStorage.store(pattern);
42655
+ }
42656
+ const result = recordPatternObservation2(pattern, true, args.bead_id);
42657
+ await patternStorage.store(result.pattern);
42658
+ patternObservations.recorded_count++;
42659
+ if (result.inversion) {
42660
+ await patternStorage.store(result.inversion.inverted);
42661
+ patternObservations.inversions.push({
42662
+ original: result.inversion.original.content,
42663
+ inverted: result.inversion.inverted.content,
42664
+ reason: result.inversion.reason
42665
+ });
42666
+ }
42667
+ }
42668
+ }
42669
+ }
42670
+ } catch (error45) {
42671
+ console.warn(`[swarm_complete] Failed to record pattern observations (non-fatal): ${error45 instanceof Error ? error45.message : String(error45)}`);
42672
+ }
41685
42673
  const epicId2 = args.bead_id.includes(".") ? args.bead_id.split(".")[0] : args.bead_id;
41686
42674
  const completionBody = [
41687
42675
  `## Subtask Complete: ${args.bead_id}`,
@@ -41758,6 +42746,16 @@ Files touched: ${args.files_touched?.join(", ") || "none recorded"}`,
41758
42746
  metadata: memoryInfo.metadata,
41759
42747
  note: memoryStored ? "Learning automatically stored in hivemind" : `Failed to store: ${memoryError}. Learning lost unless hivemind is available.`
41760
42748
  },
42749
+ outcome_scoring: outcomeScored ? {
42750
+ scored: true,
42751
+ feedback_type: outcomeFeedbackType,
42752
+ score: outcomeScore,
42753
+ reasoning: outcomeReasoning,
42754
+ note: "Outcome scored and stored for pattern maturity tracking"
42755
+ } : {
42756
+ scored: false,
42757
+ note: "Outcome scoring failed (non-fatal)"
42758
+ },
41761
42759
  contract_validation: contractValidation ? {
41762
42760
  validated: true,
41763
42761
  passed: contractValidation.valid,
@@ -41767,7 +42765,8 @@ Files touched: ${args.files_touched?.join(", ") || "none recorded"}`,
41767
42765
  } : {
41768
42766
  validated: false,
41769
42767
  reason: "No files_owned contract found (non-epic subtask or decomposition event missing)"
41770
- }
42768
+ },
42769
+ pattern_observations: patternObservations
41771
42770
  };
41772
42771
  try {
41773
42772
  const { captureSubtaskOutcome: captureSubtaskOutcome2 } = await Promise.resolve().then(() => (init_eval_capture(), exports_eval_capture));