opencode-swarm 7.46.1 → 7.46.2

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/dist/index.js CHANGED
@@ -69,7 +69,7 @@ var package_default;
69
69
  var init_package = __esm(() => {
70
70
  package_default = {
71
71
  name: "opencode-swarm",
72
- version: "7.46.1",
72
+ version: "7.46.2",
73
73
  description: "Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",
74
74
  main: "dist/index.js",
75
75
  types: "dist/index.d.ts",
@@ -59489,6 +59489,244 @@ var init_hive_promoter = __esm(() => {
59489
59489
  init_utils2();
59490
59490
  });
59491
59491
 
59492
+ // src/hooks/knowledge-events.ts
59493
+ import { randomUUID as randomUUID4 } from "node:crypto";
59494
+ import { existsSync as existsSync16 } from "node:fs";
59495
+ import { appendFile as appendFile5, mkdir as mkdir6, readFile as readFile7, writeFile as writeFile6 } from "node:fs/promises";
59496
+ import * as path28 from "node:path";
59497
+ function resolveKnowledgeEventsPath(directory) {
59498
+ return path28.join(directory, ".swarm", "knowledge-events.jsonl");
59499
+ }
59500
+ function resolveLegacyApplicationLogPath(directory) {
59501
+ return path28.join(directory, ".swarm", "knowledge-application.jsonl");
59502
+ }
59503
+ function newTraceId() {
59504
+ return randomUUID4();
59505
+ }
59506
+ function newEventId() {
59507
+ return randomUUID4();
59508
+ }
59509
+ function withDefaults(event) {
59510
+ return {
59511
+ schema_version: KNOWLEDGE_EVENT_SCHEMA_VERSION,
59512
+ ...event,
59513
+ event_id: event.event_id || newEventId(),
59514
+ timestamp: event.timestamp || new Date().toISOString()
59515
+ };
59516
+ }
59517
+ async function appendKnowledgeEvent(directory, event) {
59518
+ const populated = withDefaults(event);
59519
+ const filePath = resolveKnowledgeEventsPath(directory);
59520
+ const dirPath = path28.dirname(filePath);
59521
+ await mkdir6(dirPath, { recursive: true });
59522
+ let release;
59523
+ try {
59524
+ release = await import_proper_lockfile5.default.lock(dirPath, {
59525
+ retries: { retries: 200, minTimeout: 10, maxTimeout: 100 }
59526
+ });
59527
+ await appendFile5(filePath, `${JSON.stringify(populated)}
59528
+ `, "utf-8");
59529
+ try {
59530
+ const content = await readFile7(filePath, "utf-8");
59531
+ const lines = content.split(`
59532
+ `).filter((line) => line.trim().length > 0);
59533
+ if (lines.length > MAX_EVENT_LOG_ENTRIES) {
59534
+ const trimmed = lines.slice(lines.length - MAX_EVENT_LOG_ENTRIES);
59535
+ await writeFile6(filePath, `${trimmed.join(`
59536
+ `)}
59537
+ `, "utf-8");
59538
+ }
59539
+ } catch (err2) {
59540
+ warn(`[knowledge-events] local cap trim failed (non-fatal): ${err2 instanceof Error ? err2.message : String(err2)}`);
59541
+ }
59542
+ } finally {
59543
+ if (release)
59544
+ await release().catch(() => {});
59545
+ }
59546
+ return populated;
59547
+ }
59548
+ async function recordKnowledgeEvent(directory, event) {
59549
+ try {
59550
+ return await appendKnowledgeEvent(directory, event);
59551
+ } catch (err2) {
59552
+ warn(`[knowledge-events] recordKnowledgeEvent failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
59553
+ return null;
59554
+ }
59555
+ }
59556
+ async function readKnowledgeEvents(directory) {
59557
+ const filePath = resolveKnowledgeEventsPath(directory);
59558
+ if (!existsSync16(filePath))
59559
+ return [];
59560
+ const content = await readFile7(filePath, "utf-8");
59561
+ const out2 = [];
59562
+ for (const line of content.split(`
59563
+ `)) {
59564
+ const trimmed = line.trim();
59565
+ if (!trimmed)
59566
+ continue;
59567
+ try {
59568
+ out2.push(JSON.parse(trimmed));
59569
+ } catch {
59570
+ warn(`[knowledge-events] Skipping corrupted JSONL line in ${filePath}: ${trimmed.slice(0, 80)}`);
59571
+ }
59572
+ }
59573
+ return out2;
59574
+ }
59575
+ async function readLegacyApplicationRecords(directory) {
59576
+ const filePath = resolveLegacyApplicationLogPath(directory);
59577
+ if (!existsSync16(filePath))
59578
+ return [];
59579
+ const content = await readFile7(filePath, "utf-8");
59580
+ const out2 = [];
59581
+ for (const line of content.split(`
59582
+ `)) {
59583
+ const trimmed = line.trim();
59584
+ if (!trimmed)
59585
+ continue;
59586
+ try {
59587
+ out2.push(JSON.parse(trimmed));
59588
+ } catch {
59589
+ warn(`[knowledge-events] Skipping corrupted JSONL line in ${filePath}: ${trimmed.slice(0, 80)}`);
59590
+ }
59591
+ }
59592
+ return out2;
59593
+ }
59594
+ function emptyRollup() {
59595
+ return {
59596
+ shown_count: 0,
59597
+ acknowledged_count: 0,
59598
+ applied_explicit_count: 0,
59599
+ ignored_count: 0,
59600
+ violated_count: 0,
59601
+ contradicted_count: 0,
59602
+ succeeded_after_shown_count: 0,
59603
+ failed_after_shown_count: 0,
59604
+ partial_after_shown_count: 0
59605
+ };
59606
+ }
59607
+ function get(map3, id) {
59608
+ let r = map3.get(id);
59609
+ if (!r) {
59610
+ r = emptyRollup();
59611
+ map3.set(id, r);
59612
+ }
59613
+ return r;
59614
+ }
59615
+ function maxIso(current, candidate) {
59616
+ if (!current)
59617
+ return candidate;
59618
+ return candidate > current ? candidate : current;
59619
+ }
59620
+ function recomputeCounters(events, legacyRecords = []) {
59621
+ const map3 = new Map;
59622
+ const retrievedIds = new Set;
59623
+ for (const e of events) {
59624
+ switch (e.type) {
59625
+ case "retrieved": {
59626
+ for (const id of e.result_ids) {
59627
+ retrievedIds.add(id);
59628
+ get(map3, id).shown_count += 1;
59629
+ }
59630
+ break;
59631
+ }
59632
+ case "acknowledged": {
59633
+ const r = get(map3, e.knowledge_id);
59634
+ r.acknowledged_count += 1;
59635
+ r.last_acknowledged_at = maxIso(r.last_acknowledged_at, e.timestamp);
59636
+ break;
59637
+ }
59638
+ case "applied": {
59639
+ const r = get(map3, e.knowledge_id);
59640
+ r.applied_explicit_count += 1;
59641
+ r.last_applied_at = maxIso(r.last_applied_at, e.timestamp);
59642
+ break;
59643
+ }
59644
+ case "ignored":
59645
+ get(map3, e.knowledge_id).ignored_count += 1;
59646
+ break;
59647
+ case "violated":
59648
+ get(map3, e.knowledge_id).violated_count += 1;
59649
+ break;
59650
+ case "contradicted":
59651
+ get(map3, e.knowledge_id).contradicted_count += 1;
59652
+ break;
59653
+ case "outcome": {
59654
+ if (!e.knowledge_id)
59655
+ break;
59656
+ const r = get(map3, e.knowledge_id);
59657
+ if (e.outcome === "success")
59658
+ r.succeeded_after_shown_count += 1;
59659
+ else if (e.outcome === "failure")
59660
+ r.failed_after_shown_count += 1;
59661
+ else if (e.outcome === "partial")
59662
+ r.partial_after_shown_count += 1;
59663
+ break;
59664
+ }
59665
+ }
59666
+ }
59667
+ for (const rec of legacyRecords) {
59668
+ const r = get(map3, rec.knowledgeId);
59669
+ switch (rec.result) {
59670
+ case "shown":
59671
+ if (!retrievedIds.has(rec.knowledgeId))
59672
+ r.shown_count += 1;
59673
+ break;
59674
+ case "acknowledged":
59675
+ r.acknowledged_count += 1;
59676
+ r.last_acknowledged_at = maxIso(r.last_acknowledged_at, rec.timestamp);
59677
+ break;
59678
+ case "applied":
59679
+ r.applied_explicit_count += 1;
59680
+ r.last_applied_at = maxIso(r.last_applied_at, rec.timestamp);
59681
+ break;
59682
+ case "ignored":
59683
+ r.ignored_count += 1;
59684
+ break;
59685
+ case "violated":
59686
+ r.violated_count += 1;
59687
+ break;
59688
+ }
59689
+ }
59690
+ return map3;
59691
+ }
59692
+ async function readKnowledgeCounterRollups(directory) {
59693
+ try {
59694
+ const [events, legacyRecords] = await Promise.all([
59695
+ readKnowledgeEvents(directory),
59696
+ readLegacyApplicationRecords(directory)
59697
+ ]);
59698
+ return recomputeCounters(events, legacyRecords);
59699
+ } catch (err2) {
59700
+ warn(`[knowledge-events] readKnowledgeCounterRollups failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
59701
+ return new Map;
59702
+ }
59703
+ }
59704
+ function effectiveRetrievalOutcomes(stored, rollup) {
59705
+ const base = stored ?? {
59706
+ applied_count: 0,
59707
+ succeeded_after_count: 0,
59708
+ failed_after_count: 0
59709
+ };
59710
+ if (!rollup)
59711
+ return base;
59712
+ return {
59713
+ ...base,
59714
+ ...rollup
59715
+ };
59716
+ }
59717
+ var import_proper_lockfile5, KNOWLEDGE_EVENT_SCHEMA_VERSION = 1, MAX_EVENT_LOG_ENTRIES = 5000, RECEIPT_EVENT_TYPES;
59718
+ var init_knowledge_events = __esm(() => {
59719
+ init_logger();
59720
+ import_proper_lockfile5 = __toESM(require_proper_lockfile(), 1);
59721
+ RECEIPT_EVENT_TYPES = new Set([
59722
+ "acknowledged",
59723
+ "applied",
59724
+ "ignored",
59725
+ "contradicted",
59726
+ "violated"
59727
+ ]);
59728
+ });
59729
+
59492
59730
  // src/hooks/knowledge-curator.ts
59493
59731
  function pruneSeenRetroSections() {
59494
59732
  const cutoff = Date.now() - 86400000;
@@ -59730,11 +59968,12 @@ async function curateAndStoreSwarm(lessons, projectName, phaseInfo, directory, c
59730
59968
  async function runAutoPromotion(directory, config3) {
59731
59969
  const knowledgePath = resolveSwarmKnowledgePath(directory);
59732
59970
  const entries = await readKnowledge(knowledgePath) ?? [];
59971
+ const counterRollups = await readKnowledgeCounterRollups(directory);
59733
59972
  let changed = false;
59734
59973
  for (const entry of entries) {
59735
59974
  if (entry.status === "promoted")
59736
59975
  continue;
59737
- if (computeOutcomeSignal(entry.retrieval_outcomes) <= OUTCOME_PROMOTION_BLOCK) {
59976
+ if (computeOutcomeSignal(effectiveRetrievalOutcomes(entry.retrieval_outcomes, counterRollups.get(entry.id))) <= OUTCOME_PROMOTION_BLOCK) {
59738
59977
  continue;
59739
59978
  }
59740
59979
  const distinctPhases = new Set((entry.confirmed_by ?? []).map((c) => c.phase_number)).size;
@@ -59836,6 +60075,7 @@ function createKnowledgeCuratorHook(directory, config3) {
59836
60075
  }
59837
60076
  var seenRetroSections, OUTCOME_PROMOTION_BLOCK = -0.3, _internals21;
59838
60077
  var init_knowledge_curator = __esm(() => {
60078
+ init_knowledge_events();
59839
60079
  init_knowledge_store();
59840
60080
  init_knowledge_validator();
59841
60081
  init_utils2();
@@ -59958,11 +60198,11 @@ var init_skill_improver_llm_factory = __esm(() => {
59958
60198
  });
59959
60199
 
59960
60200
  // src/services/skill-improver-quota.ts
59961
- import { existsSync as existsSync16 } from "node:fs";
59962
- import { mkdir as mkdir6, readFile as readFile7, rename as rename4, writeFile as writeFile6 } from "node:fs/promises";
59963
- import * as path28 from "node:path";
60201
+ import { existsSync as existsSync17 } from "node:fs";
60202
+ import { mkdir as mkdir7, readFile as readFile8, rename as rename4, writeFile as writeFile7 } from "node:fs/promises";
60203
+ import * as path29 from "node:path";
59964
60204
  async function acquireLock(dir) {
59965
- const acquire = import_proper_lockfile5.default.lock(dir, LOCK_RETRY_OPTS);
60205
+ const acquire = import_proper_lockfile6.default.lock(dir, LOCK_RETRY_OPTS);
59966
60206
  let timer;
59967
60207
  const timeout = new Promise((_, reject) => {
59968
60208
  timer = setTimeout(() => {
@@ -59978,7 +60218,7 @@ async function acquireLock(dir) {
59978
60218
  }
59979
60219
  }
59980
60220
  function resolveQuotaPath(directory) {
59981
- return path28.join(directory, ".swarm", "skill-improver-quota.json");
60221
+ return path29.join(directory, ".swarm", "skill-improver-quota.json");
59982
60222
  }
59983
60223
  function todayKey(window2, now = new Date) {
59984
60224
  if (window2 === "utc") {
@@ -59990,10 +60230,10 @@ function todayKey(window2, now = new Date) {
59990
60230
  return `${yr}-${m}-${d}`;
59991
60231
  }
59992
60232
  async function readState(filePath) {
59993
- if (!existsSync16(filePath))
60233
+ if (!existsSync17(filePath))
59994
60234
  return null;
59995
60235
  try {
59996
- const raw = await readFile7(filePath, "utf-8");
60236
+ const raw = await readFile8(filePath, "utf-8");
59997
60237
  const parsed = JSON.parse(raw);
59998
60238
  if (typeof parsed.date !== "string" || typeof parsed.calls_used !== "number" || typeof parsed.max_calls !== "number" || parsed.window !== "utc" && parsed.window !== "local") {
59999
60239
  return null;
@@ -60004,9 +60244,9 @@ async function readState(filePath) {
60004
60244
  }
60005
60245
  }
60006
60246
  async function writeState(filePath, state) {
60007
- await mkdir6(path28.dirname(filePath), { recursive: true });
60247
+ await mkdir7(path29.dirname(filePath), { recursive: true });
60008
60248
  const tmp = `${filePath}.tmp-${process.pid}`;
60009
- await writeFile6(tmp, JSON.stringify(state, null, 2), "utf-8");
60249
+ await writeFile7(tmp, JSON.stringify(state, null, 2), "utf-8");
60010
60250
  await rename4(tmp, filePath);
60011
60251
  }
60012
60252
  async function getQuotaState(directory, opts) {
@@ -60027,10 +60267,10 @@ async function getQuotaState(directory, opts) {
60027
60267
  }
60028
60268
  async function reserveQuota(directory, opts) {
60029
60269
  const filePath = resolveQuotaPath(directory);
60030
- await mkdir6(path28.dirname(filePath), { recursive: true });
60270
+ await mkdir7(path29.dirname(filePath), { recursive: true });
60031
60271
  let release = null;
60032
60272
  try {
60033
- release = await acquireLock(path28.dirname(filePath));
60273
+ release = await acquireLock(path29.dirname(filePath));
60034
60274
  const state = await getQuotaState(directory, opts);
60035
60275
  if (state.calls_used + opts.nCalls > opts.maxCalls) {
60036
60276
  return {
@@ -60057,10 +60297,10 @@ async function reserveQuota(directory, opts) {
60057
60297
  }
60058
60298
  async function releaseQuota(directory, opts) {
60059
60299
  const filePath = resolveQuotaPath(directory);
60060
- await mkdir6(path28.dirname(filePath), { recursive: true });
60300
+ await mkdir7(path29.dirname(filePath), { recursive: true });
60061
60301
  let release = null;
60062
60302
  try {
60063
- release = await acquireLock(path28.dirname(filePath));
60303
+ release = await acquireLock(path29.dirname(filePath));
60064
60304
  const state = await getQuotaState(directory, opts);
60065
60305
  const next = {
60066
60306
  ...state,
@@ -60077,9 +60317,9 @@ async function releaseQuota(directory, opts) {
60077
60317
  }
60078
60318
  }
60079
60319
  }
60080
- var import_proper_lockfile5, LOCK_ACQUIRE_TIMEOUT_MS = 1e4, LOCK_RETRY_OPTS;
60320
+ var import_proper_lockfile6, LOCK_ACQUIRE_TIMEOUT_MS = 1e4, LOCK_RETRY_OPTS;
60081
60321
  var init_skill_improver_quota = __esm(() => {
60082
- import_proper_lockfile5 = __toESM(require_proper_lockfile(), 1);
60322
+ import_proper_lockfile6 = __toESM(require_proper_lockfile(), 1);
60083
60323
  LOCK_RETRY_OPTS = {
60084
60324
  retries: {
60085
60325
  retries: 30,
@@ -60092,22 +60332,22 @@ var init_skill_improver_quota = __esm(() => {
60092
60332
  });
60093
60333
 
60094
60334
  // src/services/skill-improver.ts
60095
- import { existsSync as existsSync17 } from "node:fs";
60096
- import { mkdir as mkdir7, rename as rename5, writeFile as writeFile7 } from "node:fs/promises";
60097
- import * as path29 from "node:path";
60335
+ import { existsSync as existsSync18 } from "node:fs";
60336
+ import { mkdir as mkdir8, rename as rename5, writeFile as writeFile8 } from "node:fs/promises";
60337
+ import * as path30 from "node:path";
60098
60338
  function timestampSlug(d) {
60099
60339
  return d.toISOString().replace(/[:.]/g, "-");
60100
60340
  }
60101
60341
  async function atomicWrite3(p, content) {
60102
- await mkdir7(path29.dirname(p), { recursive: true });
60342
+ await mkdir8(path30.dirname(p), { recursive: true });
60103
60343
  const tmp = `${p}.tmp-${process.pid}-${Date.now()}`;
60104
- await writeFile7(tmp, content, "utf-8");
60344
+ await writeFile8(tmp, content, "utf-8");
60105
60345
  await rename5(tmp, p);
60106
60346
  }
60107
60347
  async function gatherInventory(directory) {
60108
60348
  const swarm = await readKnowledge(resolveSwarmKnowledgePath(directory));
60109
60349
  const hivePath = resolveHiveKnowledgePath();
60110
- const hive = existsSync17(hivePath) ? await readKnowledge(hivePath) : [];
60350
+ const hive = existsSync18(hivePath) ? await readKnowledge(hivePath) : [];
60111
60351
  const archived = [...swarm, ...hive].filter((e) => e.status === "archived").length;
60112
60352
  const skills = await listSkills(directory);
60113
60353
  const matureCandidates = swarm.concat(hive).filter((e) => e.status !== "archived" && e.confidence >= 0.85 && !e.generated_skill_slug && (e.confirmed_by ?? []).length >= 2);
@@ -60380,8 +60620,8 @@ async function runSkillImprover(req) {
60380
60620
  }
60381
60621
  throw err2;
60382
60622
  }
60383
- const proposalDir = path29.join(req.directory, ".swarm", "skill-improver", "proposals");
60384
- const proposalFile = path29.join(proposalDir, `${timestampSlug(now)}.md`);
60623
+ const proposalDir = path30.join(req.directory, ".swarm", "skill-improver", "proposals");
60624
+ const proposalFile = path30.join(proposalDir, `${timestampSlug(now)}.md`);
60385
60625
  const finalBody = source === "llm" ? buildLLMProposalFrame({
60386
60626
  body: body2,
60387
60627
  targets,
@@ -60777,7 +61017,7 @@ var init_write_retro = __esm(() => {
60777
61017
 
60778
61018
  // src/commands/close.ts
60779
61019
  import { promises as fs17 } from "node:fs";
60780
- import path30 from "node:path";
61020
+ import path31 from "node:path";
60781
61021
  async function runAbortableSkillReview(req, timeoutMs) {
60782
61022
  const controller = new AbortController;
60783
61023
  let timeout;
@@ -60833,10 +61073,10 @@ function guaranteeAllPlansComplete(planData) {
60833
61073
  }
60834
61074
  async function handleCloseCommand(directory, args2, options = {}) {
60835
61075
  const planPath = validateSwarmPath(directory, "plan.json");
60836
- const swarmDir = path30.join(directory, ".swarm");
61076
+ const swarmDir = path31.join(directory, ".swarm");
60837
61077
  let planExists = false;
60838
61078
  let planData = {
60839
- title: path30.basename(directory) || "Ad-hoc session",
61079
+ title: path31.basename(directory) || "Ad-hoc session",
60840
61080
  phases: []
60841
61081
  };
60842
61082
  try {
@@ -60945,7 +61185,7 @@ async function handleCloseCommand(directory, args2, options = {}) {
60945
61185
  warnings.push(`Session retrospective write threw: ${retroError instanceof Error ? retroError.message : String(retroError)}`);
60946
61186
  }
60947
61187
  }
60948
- const lessonsFilePath = path30.join(swarmDir, "close-lessons.md");
61188
+ const lessonsFilePath = path31.join(swarmDir, "close-lessons.md");
60949
61189
  let explicitLessons = [];
60950
61190
  try {
60951
61191
  const lessonsText = await fs17.readFile(lessonsFilePath, "utf-8");
@@ -60954,11 +61194,11 @@ async function handleCloseCommand(directory, args2, options = {}) {
60954
61194
  } catch {}
60955
61195
  const retroLessons = [];
60956
61196
  try {
60957
- const evidenceDir = path30.join(swarmDir, "evidence");
61197
+ const evidenceDir = path31.join(swarmDir, "evidence");
60958
61198
  const evidenceEntries = await fs17.readdir(evidenceDir);
60959
61199
  const retroDirs = evidenceEntries.filter((e) => e.startsWith("retro-")).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
60960
61200
  for (const retroDir of retroDirs) {
60961
- const evidencePath = path30.join(evidenceDir, retroDir, "evidence.json");
61201
+ const evidencePath = path31.join(evidenceDir, retroDir, "evidence.json");
60962
61202
  try {
60963
61203
  const content = await fs17.readFile(evidencePath, "utf-8");
60964
61204
  const parsed = JSON.parse(content);
@@ -61093,7 +61333,7 @@ async function handleCloseCommand(directory, args2, options = {}) {
61093
61333
  }
61094
61334
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
61095
61335
  const suffix = Math.random().toString(36).slice(2, 8);
61096
- const archiveDir = path30.join(swarmDir, "archive", `swarm-${timestamp}-${suffix}`);
61336
+ const archiveDir = path31.join(swarmDir, "archive", `swarm-${timestamp}-${suffix}`);
61097
61337
  let archiveResult = "";
61098
61338
  let archivedFileCount = 0;
61099
61339
  const archivedActiveStateFiles = new Set;
@@ -61101,8 +61341,8 @@ async function handleCloseCommand(directory, args2, options = {}) {
61101
61341
  try {
61102
61342
  await fs17.mkdir(archiveDir, { recursive: true });
61103
61343
  for (const artifact of ARCHIVE_ARTIFACTS) {
61104
- const srcPath = path30.join(swarmDir, artifact);
61105
- const destPath = path30.join(archiveDir, artifact);
61344
+ const srcPath = path31.join(swarmDir, artifact);
61345
+ const destPath = path31.join(archiveDir, artifact);
61106
61346
  try {
61107
61347
  await fs17.copyFile(srcPath, destPath);
61108
61348
  archivedFileCount++;
@@ -61112,22 +61352,22 @@ async function handleCloseCommand(directory, args2, options = {}) {
61112
61352
  } catch {}
61113
61353
  }
61114
61354
  for (const dirName of ACTIVE_STATE_DIRS_TO_CLEAN) {
61115
- const srcDir = path30.join(swarmDir, dirName);
61116
- const destDir = path30.join(archiveDir, dirName);
61355
+ const srcDir = path31.join(swarmDir, dirName);
61356
+ const destDir = path31.join(archiveDir, dirName);
61117
61357
  try {
61118
61358
  const entries = await fs17.readdir(srcDir);
61119
61359
  if (entries.length > 0) {
61120
61360
  await fs17.mkdir(destDir, { recursive: true });
61121
61361
  for (const entry of entries) {
61122
- const srcEntry = path30.join(srcDir, entry);
61123
- const destEntry = path30.join(destDir, entry);
61362
+ const srcEntry = path31.join(srcDir, entry);
61363
+ const destEntry = path31.join(destDir, entry);
61124
61364
  try {
61125
61365
  const stat3 = await fs17.stat(srcEntry);
61126
61366
  if (stat3.isDirectory()) {
61127
61367
  await fs17.mkdir(destEntry, { recursive: true });
61128
61368
  const subEntries = await fs17.readdir(srcEntry);
61129
61369
  for (const sub of subEntries) {
61130
- await fs17.copyFile(path30.join(srcEntry, sub), path30.join(destEntry, sub)).catch(() => {});
61370
+ await fs17.copyFile(path31.join(srcEntry, sub), path31.join(destEntry, sub)).catch(() => {});
61131
61371
  }
61132
61372
  } else {
61133
61373
  await fs17.copyFile(srcEntry, destEntry);
@@ -61159,7 +61399,7 @@ async function handleCloseCommand(directory, args2, options = {}) {
61159
61399
  warnings.push(`Preserved ${artifact} because it was not successfully archived.`);
61160
61400
  continue;
61161
61401
  }
61162
- const filePath = path30.join(swarmDir, artifact);
61402
+ const filePath = path31.join(swarmDir, artifact);
61163
61403
  try {
61164
61404
  await fs17.unlink(filePath);
61165
61405
  cleanedFiles.push(artifact);
@@ -61172,7 +61412,7 @@ async function handleCloseCommand(directory, args2, options = {}) {
61172
61412
  if (!archivedActiveStateDirs.has(dirName)) {
61173
61413
  continue;
61174
61414
  }
61175
- const dirPath = path30.join(swarmDir, dirName);
61415
+ const dirPath = path31.join(swarmDir, dirName);
61176
61416
  try {
61177
61417
  await fs17.rm(dirPath, { recursive: true, force: true });
61178
61418
  cleanedFiles.push(`${dirName}/`);
@@ -61183,23 +61423,23 @@ async function handleCloseCommand(directory, args2, options = {}) {
61183
61423
  const configBackups = swarmFiles.filter((f) => f.startsWith("config-backup-") && f.endsWith(".json"));
61184
61424
  for (const backup of configBackups) {
61185
61425
  try {
61186
- await fs17.unlink(path30.join(swarmDir, backup));
61426
+ await fs17.unlink(path31.join(swarmDir, backup));
61187
61427
  configBackupsRemoved++;
61188
61428
  } catch {}
61189
61429
  }
61190
61430
  const ledgerSiblings = swarmFiles.filter((f) => (f.startsWith("plan-ledger.archived-") || f.startsWith("plan-ledger.backup-")) && f.endsWith(".jsonl"));
61191
61431
  for (const sibling of ledgerSiblings) {
61192
61432
  try {
61193
- await fs17.unlink(path30.join(swarmDir, sibling));
61433
+ await fs17.unlink(path31.join(swarmDir, sibling));
61194
61434
  } catch {}
61195
61435
  }
61196
61436
  } catch {}
61197
61437
  let swarmPlanFilesRemoved = 0;
61198
61438
  const candidates = [
61199
- path30.join(directory, ".swarm", "SWARM_PLAN.json"),
61200
- path30.join(directory, ".swarm", "SWARM_PLAN.md"),
61201
- path30.join(directory, "SWARM_PLAN.json"),
61202
- path30.join(directory, "SWARM_PLAN.md")
61439
+ path31.join(directory, ".swarm", "SWARM_PLAN.json"),
61440
+ path31.join(directory, ".swarm", "SWARM_PLAN.md"),
61441
+ path31.join(directory, "SWARM_PLAN.json"),
61442
+ path31.join(directory, "SWARM_PLAN.md")
61203
61443
  ];
61204
61444
  for (const candidate of candidates) {
61205
61445
  try {
@@ -61207,12 +61447,12 @@ async function handleCloseCommand(directory, args2, options = {}) {
61207
61447
  swarmPlanFilesRemoved++;
61208
61448
  } catch (err2) {
61209
61449
  if (err2?.code !== "ENOENT") {
61210
- warnings.push(`Failed to remove ${path30.basename(candidate)}: ${err2 instanceof Error ? err2.message : String(err2)}`);
61450
+ warnings.push(`Failed to remove ${path31.basename(candidate)}: ${err2 instanceof Error ? err2.message : String(err2)}`);
61211
61451
  }
61212
61452
  }
61213
61453
  }
61214
61454
  clearAllScopes(directory);
61215
- const contextPath = path30.join(swarmDir, "context.md");
61455
+ const contextPath = path31.join(swarmDir, "context.md");
61216
61456
  const contextContent = [
61217
61457
  "# Context",
61218
61458
  "",
@@ -61536,14 +61776,14 @@ var init_concurrency = __esm(() => {
61536
61776
 
61537
61777
  // src/commands/config.ts
61538
61778
  import * as os9 from "node:os";
61539
- import * as path31 from "node:path";
61779
+ import * as path32 from "node:path";
61540
61780
  function getUserConfigDir2() {
61541
- return process.env.XDG_CONFIG_HOME || path31.join(os9.homedir(), ".config");
61781
+ return process.env.XDG_CONFIG_HOME || path32.join(os9.homedir(), ".config");
61542
61782
  }
61543
61783
  async function handleConfigCommand(directory, _args) {
61544
61784
  const config3 = loadPluginConfig(directory);
61545
- const userConfigPath = path31.join(getUserConfigDir2(), "opencode", "opencode-swarm.json");
61546
- const projectConfigPath = path31.join(directory, ".opencode", "opencode-swarm.json");
61785
+ const userConfigPath = path32.join(getUserConfigDir2(), "opencode", "opencode-swarm.json");
61786
+ const projectConfigPath = path32.join(directory, ".opencode", "opencode-swarm.json");
61547
61787
  const lines = [
61548
61788
  "## Swarm Configuration",
61549
61789
  "",
@@ -61679,9 +61919,9 @@ __export(exports_co_change_analyzer, {
61679
61919
  _internals: () => _internals23
61680
61920
  });
61681
61921
  import * as child_process3 from "node:child_process";
61682
- import { randomUUID as randomUUID4 } from "node:crypto";
61683
- import { readdir as readdir2, readFile as readFile8, stat as stat3 } from "node:fs/promises";
61684
- import * as path32 from "node:path";
61922
+ import { randomUUID as randomUUID5 } from "node:crypto";
61923
+ import { readdir as readdir2, readFile as readFile9, stat as stat3 } from "node:fs/promises";
61924
+ import * as path33 from "node:path";
61685
61925
  import { promisify } from "node:util";
61686
61926
  function getExecFileAsync() {
61687
61927
  return promisify(child_process3.execFile);
@@ -61785,7 +62025,7 @@ async function scanSourceFiles(dir) {
61785
62025
  try {
61786
62026
  const entries = await readdir2(dir, { withFileTypes: true });
61787
62027
  for (const entry of entries) {
61788
- const fullPath = path32.join(dir, entry.name);
62028
+ const fullPath = path33.join(dir, entry.name);
61789
62029
  if (entry.isDirectory()) {
61790
62030
  if (skipDirs.has(entry.name)) {
61791
62031
  continue;
@@ -61793,7 +62033,7 @@ async function scanSourceFiles(dir) {
61793
62033
  const subFiles = await scanSourceFiles(fullPath);
61794
62034
  results.push(...subFiles);
61795
62035
  } else if (entry.isFile()) {
61796
- const ext = path32.extname(entry.name);
62036
+ const ext = path33.extname(entry.name);
61797
62037
  if ([".ts", ".tsx", ".js", ".jsx", ".mjs"].includes(ext)) {
61798
62038
  results.push(fullPath);
61799
62039
  }
@@ -61807,7 +62047,7 @@ async function getStaticEdges(directory) {
61807
62047
  const sourceFiles = await scanSourceFiles(directory);
61808
62048
  for (const sourceFile of sourceFiles) {
61809
62049
  try {
61810
- const content = await readFile8(sourceFile, "utf-8");
62050
+ const content = await readFile9(sourceFile, "utf-8");
61811
62051
  const importRegex = /(?:import|require)\s*(?:\(?\s*['"`]|.*?from\s+['"`])([^'"`]+)['"`]/g;
61812
62052
  for (let match = importRegex.exec(content);match !== null; match = importRegex.exec(content)) {
61813
62053
  const importPath = match[1].trim();
@@ -61815,8 +62055,8 @@ async function getStaticEdges(directory) {
61815
62055
  continue;
61816
62056
  }
61817
62057
  try {
61818
- const sourceDir = path32.dirname(sourceFile);
61819
- const resolvedPath = path32.resolve(sourceDir, importPath);
62058
+ const sourceDir = path33.dirname(sourceFile);
62059
+ const resolvedPath = path33.resolve(sourceDir, importPath);
61820
62060
  const extensions = [
61821
62061
  "",
61822
62062
  ".ts",
@@ -61841,8 +62081,8 @@ async function getStaticEdges(directory) {
61841
62081
  if (!targetFile) {
61842
62082
  continue;
61843
62083
  }
61844
- const relSource = path32.relative(directory, sourceFile).replace(/\\/g, "/");
61845
- const relTarget = path32.relative(directory, targetFile).replace(/\\/g, "/");
62084
+ const relSource = path33.relative(directory, sourceFile).replace(/\\/g, "/");
62085
+ const relTarget = path33.relative(directory, targetFile).replace(/\\/g, "/");
61846
62086
  const [key] = relSource < relTarget ? [`${relSource}::${relTarget}`, relSource, relTarget] : [`${relTarget}::${relSource}`, relTarget, relSource];
61847
62087
  edges.add(key);
61848
62088
  } catch {}
@@ -61854,7 +62094,7 @@ async function getStaticEdges(directory) {
61854
62094
  function isTestImplementationPair(fileA, fileB) {
61855
62095
  const testPatterns = [".test.ts", ".test.js", ".spec.ts", ".spec.js"];
61856
62096
  const getBaseName = (filePath) => {
61857
- const base = path32.basename(filePath);
62097
+ const base = path33.basename(filePath);
61858
62098
  for (const pattern of testPatterns) {
61859
62099
  if (base.endsWith(pattern)) {
61860
62100
  return base.slice(0, -pattern.length);
@@ -61864,16 +62104,16 @@ function isTestImplementationPair(fileA, fileB) {
61864
62104
  };
61865
62105
  const baseA = getBaseName(fileA);
61866
62106
  const baseB = getBaseName(fileB);
61867
- return baseA === baseB && baseA !== path32.basename(fileA) && baseA !== path32.basename(fileB);
62107
+ return baseA === baseB && baseA !== path33.basename(fileA) && baseA !== path33.basename(fileB);
61868
62108
  }
61869
62109
  function hasSharedPrefix(fileA, fileB) {
61870
- const dirA = path32.dirname(fileA);
61871
- const dirB = path32.dirname(fileB);
62110
+ const dirA = path33.dirname(fileA);
62111
+ const dirB = path33.dirname(fileB);
61872
62112
  if (dirA !== dirB) {
61873
62113
  return false;
61874
62114
  }
61875
- const baseA = path32.basename(fileA).replace(/\.(ts|js|tsx|jsx|mjs)$/, "");
61876
- const baseB = path32.basename(fileB).replace(/\.(ts|js|tsx|jsx|mjs)$/, "");
62115
+ const baseA = path33.basename(fileA).replace(/\.(ts|js|tsx|jsx|mjs)$/, "");
62116
+ const baseB = path33.basename(fileB).replace(/\.(ts|js|tsx|jsx|mjs)$/, "");
61877
62117
  if (baseA.startsWith(baseB) || baseB.startsWith(baseA)) {
61878
62118
  return true;
61879
62119
  }
@@ -61928,8 +62168,8 @@ function darkMatterToKnowledgeEntries(pairs, projectName) {
61928
62168
  const entries = [];
61929
62169
  const now = new Date().toISOString();
61930
62170
  for (const pair of pairs.slice(0, 10)) {
61931
- const baseA = path32.basename(pair.fileA);
61932
- const baseB = path32.basename(pair.fileB);
62171
+ const baseA = path33.basename(pair.fileA);
62172
+ const baseB = path33.basename(pair.fileB);
61933
62173
  let lesson = `Files ${pair.fileA} and ${pair.fileB} co-change with NPMI=${pair.npmi.toFixed(3)} but have no import relationship. This hidden coupling suggests a shared architectural concern — changes to one likely require changes to the other.`;
61934
62174
  if (lesson.length > 280) {
61935
62175
  lesson = `Files ${baseA} and ${baseB} co-change with NPMI=${pair.npmi.toFixed(3)} but have no import relationship. This hidden coupling suggests a shared architectural concern — changes to one likely require changes to the other.`;
@@ -61942,7 +62182,7 @@ function darkMatterToKnowledgeEntries(pairs, projectName) {
61942
62182
  }
61943
62183
  const confidence = Math.min(0.3 + 0.2 * Math.min(pair.coChangeCount / 10, 1), 0.5);
61944
62184
  entries.push({
61945
- id: randomUUID4(),
62185
+ id: randomUUID5(),
61946
62186
  tier: "swarm",
61947
62187
  lesson,
61948
62188
  category: "architecture",
@@ -62031,7 +62271,7 @@ var init_co_change_analyzer = __esm(() => {
62031
62271
  });
62032
62272
 
62033
62273
  // src/commands/dark-matter.ts
62034
- import path33 from "node:path";
62274
+ import path34 from "node:path";
62035
62275
  async function handleDarkMatterCommand(directory, args2) {
62036
62276
  const options = {};
62037
62277
  for (let i2 = 0;i2 < args2.length; i2++) {
@@ -62063,7 +62303,7 @@ Ensure this is a git repository with commit history.`;
62063
62303
  const output = formatDarkMatterOutput(pairs);
62064
62304
  if (pairs.length > 0) {
62065
62305
  try {
62066
- const projectName = path33.basename(path33.resolve(directory));
62306
+ const projectName = path34.basename(path34.resolve(directory));
62067
62307
  const entries = darkMatterToKnowledgeEntries(pairs, projectName);
62068
62308
  if (entries.length > 0) {
62069
62309
  const knowledgePath = resolveSwarmKnowledgePath(directory);
@@ -62200,26 +62440,26 @@ var init_deep_dive = __esm(() => {
62200
62440
 
62201
62441
  // src/config/cache-paths.ts
62202
62442
  import * as os10 from "node:os";
62203
- import * as path34 from "node:path";
62443
+ import * as path35 from "node:path";
62204
62444
  function getPluginConfigDir() {
62205
- return path34.join(process.env.XDG_CONFIG_HOME || path34.join(os10.homedir(), ".config"), "opencode");
62445
+ return path35.join(process.env.XDG_CONFIG_HOME || path35.join(os10.homedir(), ".config"), "opencode");
62206
62446
  }
62207
62447
  function getPluginCachePaths() {
62208
- const cacheBase = process.env.XDG_CACHE_HOME || path34.join(os10.homedir(), ".cache");
62448
+ const cacheBase = process.env.XDG_CACHE_HOME || path35.join(os10.homedir(), ".cache");
62209
62449
  const configDir = getPluginConfigDir();
62210
62450
  const paths = [
62211
- path34.join(cacheBase, "opencode", "node_modules", "opencode-swarm"),
62212
- path34.join(cacheBase, "opencode", "packages", "opencode-swarm@latest"),
62213
- path34.join(configDir, "node_modules", "opencode-swarm")
62451
+ path35.join(cacheBase, "opencode", "node_modules", "opencode-swarm"),
62452
+ path35.join(cacheBase, "opencode", "packages", "opencode-swarm@latest"),
62453
+ path35.join(configDir, "node_modules", "opencode-swarm")
62214
62454
  ];
62215
62455
  if (process.platform === "darwin") {
62216
- const libCaches = path34.join(os10.homedir(), "Library", "Caches");
62217
- paths.push(path34.join(libCaches, "opencode", "node_modules", "opencode-swarm"), path34.join(libCaches, "opencode", "packages", "opencode-swarm@latest"));
62456
+ const libCaches = path35.join(os10.homedir(), "Library", "Caches");
62457
+ paths.push(path35.join(libCaches, "opencode", "node_modules", "opencode-swarm"), path35.join(libCaches, "opencode", "packages", "opencode-swarm@latest"));
62218
62458
  }
62219
62459
  if (process.platform === "win32") {
62220
- const localAppData = process.env.LOCALAPPDATA || path34.join(os10.homedir(), "AppData", "Local");
62221
- const appData = process.env.APPDATA || path34.join(os10.homedir(), "AppData", "Roaming");
62222
- paths.push(path34.join(localAppData, "opencode", "node_modules", "opencode-swarm"), path34.join(localAppData, "opencode", "packages", "opencode-swarm@latest"), path34.join(appData, "opencode", "node_modules", "opencode-swarm"));
62460
+ const localAppData = process.env.LOCALAPPDATA || path35.join(os10.homedir(), "AppData", "Local");
62461
+ const appData = process.env.APPDATA || path35.join(os10.homedir(), "AppData", "Roaming");
62462
+ paths.push(path35.join(localAppData, "opencode", "node_modules", "opencode-swarm"), path35.join(localAppData, "opencode", "packages", "opencode-swarm@latest"), path35.join(appData, "opencode", "node_modules", "opencode-swarm"));
62223
62463
  }
62224
62464
  return paths;
62225
62465
  }
@@ -62339,81 +62579,6 @@ var init_gate_bridge = __esm(() => {
62339
62579
  };
62340
62580
  });
62341
62581
 
62342
- // src/hooks/knowledge-events.ts
62343
- import { randomUUID as randomUUID5 } from "node:crypto";
62344
- import { existsSync as existsSync18 } from "node:fs";
62345
- import { appendFile as appendFile5, mkdir as mkdir8, readFile as readFile9 } from "node:fs/promises";
62346
- import * as path35 from "node:path";
62347
- function resolveKnowledgeEventsPath(directory) {
62348
- return path35.join(directory, ".swarm", "knowledge-events.jsonl");
62349
- }
62350
- function newTraceId() {
62351
- return randomUUID5();
62352
- }
62353
- function newEventId() {
62354
- return randomUUID5();
62355
- }
62356
- function withDefaults(event) {
62357
- return {
62358
- schema_version: KNOWLEDGE_EVENT_SCHEMA_VERSION,
62359
- ...event,
62360
- event_id: event.event_id || newEventId(),
62361
- timestamp: event.timestamp || new Date().toISOString()
62362
- };
62363
- }
62364
- async function appendKnowledgeEvent(directory, event) {
62365
- const populated = withDefaults(event);
62366
- const filePath = resolveKnowledgeEventsPath(directory);
62367
- await mkdir8(path35.dirname(filePath), { recursive: true });
62368
- await appendFile5(filePath, `${JSON.stringify(populated)}
62369
- `, "utf-8");
62370
- try {
62371
- await enforceKnowledgeCap(filePath, MAX_EVENT_LOG_ENTRIES);
62372
- } catch (err2) {
62373
- warn(`[knowledge-events] enforceKnowledgeCap failed (non-fatal): ${err2 instanceof Error ? err2.message : String(err2)}`);
62374
- }
62375
- return populated;
62376
- }
62377
- async function recordKnowledgeEvent(directory, event) {
62378
- try {
62379
- return await appendKnowledgeEvent(directory, event);
62380
- } catch (err2) {
62381
- warn(`[knowledge-events] recordKnowledgeEvent failed: ${err2 instanceof Error ? err2.message : String(err2)}`);
62382
- return null;
62383
- }
62384
- }
62385
- async function readKnowledgeEvents(directory) {
62386
- const filePath = resolveKnowledgeEventsPath(directory);
62387
- if (!existsSync18(filePath))
62388
- return [];
62389
- const content = await readFile9(filePath, "utf-8");
62390
- const out2 = [];
62391
- for (const line of content.split(`
62392
- `)) {
62393
- const trimmed = line.trim();
62394
- if (!trimmed)
62395
- continue;
62396
- try {
62397
- out2.push(JSON.parse(trimmed));
62398
- } catch {
62399
- warn(`[knowledge-events] Skipping corrupted JSONL line in ${filePath}: ${trimmed.slice(0, 80)}`);
62400
- }
62401
- }
62402
- return out2;
62403
- }
62404
- var KNOWLEDGE_EVENT_SCHEMA_VERSION = 1, MAX_EVENT_LOG_ENTRIES = 5000, RECEIPT_EVENT_TYPES;
62405
- var init_knowledge_events = __esm(() => {
62406
- init_logger();
62407
- init_knowledge_store();
62408
- RECEIPT_EVENT_TYPES = new Set([
62409
- "acknowledged",
62410
- "applied",
62411
- "ignored",
62412
- "contradicted",
62413
- "violated"
62414
- ]);
62415
- });
62416
-
62417
62582
  // src/services/version-check.ts
62418
62583
  import { existsSync as existsSync19, mkdirSync as mkdirSync12, readFileSync as readFileSync8, writeFileSync as writeFileSync8 } from "node:fs";
62419
62584
  import { homedir as homedir6 } from "node:os";
@@ -66589,7 +66754,7 @@ function withStateLock(directory, fn2) {
66589
66754
  fs21.writeFileSync(lockTarget, `${JSON.stringify(seed, null, 2)}
66590
66755
  `, "utf-8");
66591
66756
  }
66592
- release = lockfile6.lockSync(lockTarget, {
66757
+ release = lockfile7.lockSync(lockTarget, {
66593
66758
  retries: { retries: 5, minTimeout: 5, maxTimeout: 50 },
66594
66759
  stale: 5000
66595
66760
  });
@@ -66889,12 +67054,12 @@ function shouldPauseForDenials(state, config3) {
66889
67054
  }
66890
67055
  return { pause: false };
66891
67056
  }
66892
- var import_proper_lockfile6, lockfile6, STATE_FILE = "full-auto-state.json", MAX_DENIAL_HISTORY = 100, stateUnreadable = false, stateUnreadableReason = "";
67057
+ var import_proper_lockfile7, lockfile7, STATE_FILE = "full-auto-state.json", MAX_DENIAL_HISTORY = 100, stateUnreadable = false, stateUnreadableReason = "";
66893
67058
  var init_state2 = __esm(() => {
66894
67059
  init_utils2();
66895
67060
  init_logger();
66896
- import_proper_lockfile6 = __toESM(require_proper_lockfile(), 1);
66897
- lockfile6 = import_proper_lockfile6.default;
67061
+ import_proper_lockfile7 = __toESM(require_proper_lockfile(), 1);
67062
+ lockfile7 = import_proper_lockfile7.default;
66898
67063
  });
66899
67064
 
66900
67065
  // src/commands/full-auto.ts
@@ -67920,7 +68085,7 @@ var KNOWLEDGE_SCHEMA_VERSION = 2;
67920
68085
  // src/hooks/knowledge-migrator.ts
67921
68086
  import { randomUUID as randomUUID6 } from "node:crypto";
67922
68087
  import { existsSync as existsSync26, readFileSync as readFileSync14 } from "node:fs";
67923
- import { mkdir as mkdir9, readFile as readFile11, writeFile as writeFile8 } from "node:fs/promises";
68088
+ import { mkdir as mkdir9, readFile as readFile11, writeFile as writeFile9 } from "node:fs/promises";
67924
68089
  import * as path42 from "node:path";
67925
68090
  async function migrateKnowledgeToExternal(_directory, _config) {
67926
68091
  return {
@@ -68151,7 +68316,7 @@ async function writeSentinel(sentinelPath, migrated, dropped) {
68151
68316
  migration_tool: "knowledge-migrator.ts"
68152
68317
  };
68153
68318
  await mkdir9(path42.dirname(sentinelPath), { recursive: true });
68154
- await writeFile8(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
68319
+ await writeFile9(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
68155
68320
  }
68156
68321
  var _internals29;
68157
68322
  var init_knowledge_migrator = __esm(() => {
@@ -69233,7 +69398,7 @@ import {
69233
69398
  mkdir as mkdir10,
69234
69399
  readFile as readFile12,
69235
69400
  rename as rename6,
69236
- writeFile as writeFile9
69401
+ writeFile as writeFile10
69237
69402
  } from "node:fs/promises";
69238
69403
  import * as path43 from "node:path";
69239
69404
 
@@ -69644,7 +69809,7 @@ async function writeJsonlAtomic(filePath, values) {
69644
69809
  const content = values.map((value) => JSON.stringify(value)).join(`
69645
69810
  `) + (values.length > 0 ? `
69646
69811
  ` : "");
69647
- await writeFile9(tmp, content, "utf-8");
69812
+ await writeFile10(tmp, content, "utf-8");
69648
69813
  await rename6(tmp, filePath);
69649
69814
  }
69650
69815
  var init_local_jsonl_provider = __esm(() => {
@@ -69739,7 +69904,7 @@ var init_prompt_block = __esm(() => {
69739
69904
 
69740
69905
  // src/memory/jsonl-migration.ts
69741
69906
  import { existsSync as existsSync28 } from "node:fs";
69742
- import { copyFile, mkdir as mkdir11, readFile as readFile13, stat as stat4, writeFile as writeFile10 } from "node:fs/promises";
69907
+ import { copyFile, mkdir as mkdir11, readFile as readFile13, stat as stat4, writeFile as writeFile11 } from "node:fs/promises";
69743
69908
  import * as path44 from "node:path";
69744
69909
  function resolveMemoryStorageDir(rootDirectory, config3 = {}) {
69745
69910
  const resolved = resolveConfig(config3);
@@ -69787,14 +69952,14 @@ async function writeJsonlExport(rootDirectory, config3, memories, proposals) {
69787
69952
  await mkdir11(exportDir, { recursive: true });
69788
69953
  const memoriesPath = path44.join(exportDir, "memories.jsonl");
69789
69954
  const proposalsPath = path44.join(exportDir, "proposals.jsonl");
69790
- await writeFile10(memoriesPath, toJsonl(memories), "utf-8");
69791
- await writeFile10(proposalsPath, toJsonl(proposals), "utf-8");
69955
+ await writeFile11(memoriesPath, toJsonl(memories), "utf-8");
69956
+ await writeFile11(proposalsPath, toJsonl(proposals), "utf-8");
69792
69957
  return { directory: exportDir, memoriesPath, proposalsPath };
69793
69958
  }
69794
69959
  async function writeMigrationReport(rootDirectory, report, config3 = {}) {
69795
69960
  const reportPath = path44.join(resolveMemoryStorageDir(rootDirectory, config3), "migration-report.json");
69796
69961
  await mkdir11(path44.dirname(reportPath), { recursive: true });
69797
- await writeFile10(reportPath, `${JSON.stringify(report, null, 2)}
69962
+ await writeFile11(reportPath, `${JSON.stringify(report, null, 2)}
69798
69963
  `, "utf-8");
69799
69964
  return reportPath;
69800
69965
  }
@@ -85706,7 +85871,7 @@ COVERAGE REPORTING:
85706
85871
  `;
85707
85872
 
85708
85873
  // src/agents/index.ts
85709
- import { mkdir as mkdir13, writeFile as writeFile11 } from "node:fs/promises";
85874
+ import { mkdir as mkdir13, writeFile as writeFile12 } from "node:fs/promises";
85710
85875
  import * as path71 from "node:path";
85711
85876
  function stripSwarmPrefix(agentName, swarmPrefix) {
85712
85877
  if (!swarmPrefix || !agentName)
@@ -86122,7 +86287,7 @@ function getAgentConfigs(config3, directory, sessionId, projectContext) {
86122
86287
  generatedAt: new Date().toISOString(),
86123
86288
  agents: agentToolSnapshot
86124
86289
  }, null, 2);
86125
- mkdir13(evidenceDir, { recursive: true }).then(() => writeFile11(path71.join(evidenceDir, filename), snapshotData)).catch(() => {});
86290
+ mkdir13(evidenceDir, { recursive: true }).then(() => writeFile12(path71.join(evidenceDir, filename), snapshotData)).catch(() => {});
86126
86291
  }
86127
86292
  return result;
86128
86293
  }
@@ -90661,7 +90826,7 @@ import {
90661
90826
  readFile as readFile16,
90662
90827
  realpath as realpath3,
90663
90828
  stat as stat7,
90664
- writeFile as writeFile13
90829
+ writeFile as writeFile14
90665
90830
  } from "node:fs/promises";
90666
90831
  import * as path95 from "node:path";
90667
90832
  function normalizeSeparators(filePath) {
@@ -90859,7 +91024,7 @@ async function scanDocIndex(directory) {
90859
91024
  };
90860
91025
  try {
90861
91026
  await mkdir16(path95.dirname(manifestPath), { recursive: true });
90862
- await writeFile13(manifestPath, JSON.stringify(manifest, null, 2), "utf-8");
91027
+ await writeFile14(manifestPath, JSON.stringify(manifest, null, 2), "utf-8");
90863
91028
  } catch {}
90864
91029
  return { manifest, cached: false };
90865
91030
  }
@@ -91073,7 +91238,7 @@ var init_doc_scan = __esm(() => {
91073
91238
 
91074
91239
  // src/hooks/knowledge-reader.ts
91075
91240
  import { existsSync as existsSync52 } from "node:fs";
91076
- import { mkdir as mkdir17, readFile as readFile17, writeFile as writeFile14 } from "node:fs/promises";
91241
+ import { mkdir as mkdir17, readFile as readFile17, writeFile as writeFile15 } from "node:fs/promises";
91077
91242
  import * as path96 from "node:path";
91078
91243
  function inferCategoriesFromPhase(phaseDescription) {
91079
91244
  const lower = phaseDescription.toLowerCase();
@@ -91130,7 +91295,7 @@ async function recordLessonsShown(directory, lessonIds, currentPhase) {
91130
91295
  const canonicalKey = phaseMatch ? `Phase ${phaseMatch[1]}` : currentPhase;
91131
91296
  shownData[canonicalKey] = lessonIds;
91132
91297
  await mkdir17(path96.dirname(shownFile), { recursive: true });
91133
- await writeFile14(shownFile, JSON.stringify(shownData, null, 2), "utf-8");
91298
+ await writeFile15(shownFile, JSON.stringify(shownData, null, 2), "utf-8");
91134
91299
  } catch {
91135
91300
  warn("[swarm] Knowledge: failed to record shown lessons");
91136
91301
  }
@@ -91263,7 +91428,7 @@ async function updateRetrievalOutcome(directory, phaseInfo, phaseSucceeded) {
91263
91428
  const remainingIds = shownIds.filter((id) => !foundInSwarm.has(id));
91264
91429
  if (remainingIds.length === 0) {
91265
91430
  delete shownData[phaseInfo];
91266
- await writeFile14(shownFile, JSON.stringify(shownData, null, 2), "utf-8");
91431
+ await writeFile15(shownFile, JSON.stringify(shownData, null, 2), "utf-8");
91267
91432
  return;
91268
91433
  }
91269
91434
  const hivePath = resolveHiveKnowledgePath();
@@ -91284,7 +91449,7 @@ async function updateRetrievalOutcome(directory, phaseInfo, phaseSucceeded) {
91284
91449
  await rewriteKnowledge(hivePath, hiveEntries);
91285
91450
  }
91286
91451
  delete shownData[phaseInfo];
91287
- await writeFile14(shownFile, JSON.stringify(shownData, null, 2), "utf-8");
91452
+ await writeFile15(shownFile, JSON.stringify(shownData, null, 2), "utf-8");
91288
91453
  } catch {
91289
91454
  warn("[swarm] Knowledge: failed to update retrieval outcomes");
91290
91455
  }
@@ -91401,6 +91566,7 @@ async function searchKnowledge(params) {
91401
91566
  let candidates = await readMergedKnowledge(directory, mergeConfig, projected, {
91402
91567
  skipScopeFilter: !applyScopeFilter
91403
91568
  });
91569
+ const counterRollups = await readKnowledgeCounterRollups(directory);
91404
91570
  candidates = candidates.filter((e) => {
91405
91571
  if (e.status === "quarantined")
91406
91572
  return false;
@@ -91425,15 +91591,21 @@ async function searchKnowledge(params) {
91425
91591
  const metaWeight = hasQuery ? META_WEIGHT : 1;
91426
91592
  const minConf = typeof config3.directive_min_confidence === "number" ? config3.directive_min_confidence : DIRECTIVE_BOOST_MIN_CONFIDENCE;
91427
91593
  const scored = candidates.map((entry) => {
91594
+ const retrievalOutcomes = effectiveRetrievalOutcomes(entry.retrieval_outcomes, counterRollups.get(entry.id));
91428
91595
  const textScore = queryBigrams ? jaccardBigram(queryBigrams, wordBigrams(normalize3(entryText(entry)))) : 0;
91429
91596
  const metaScore = entry.finalScore;
91430
91597
  const ds = context ? scoreDirectiveAgainstContext(entry, context) : { triggerHit: false, actionHit: false, agentHit: false, score: 0 };
91431
91598
  const confBoost = context && entry.confidence >= minConf && (ds.actionHit || ds.agentHit) ? 0.25 : 0;
91432
91599
  const generatedSkillBoost = entry.generated_skill_path && entry.status !== "archived" ? 0.05 : 0;
91433
- const outcomeBoost = computeOutcomeSignal(entry.retrieval_outcomes) * OUTCOME_RANK_WEIGHT;
91600
+ const outcomeBoost = computeOutcomeSignal(retrievalOutcomes) * OUTCOME_RANK_WEIGHT;
91434
91601
  const finalScore = Math.min(1, Math.max(0, textWeight * textScore + metaWeight * metaScore + ds.score + confBoost + generatedSkillBoost + outcomeBoost + (hasQuery ? statusBoost(entry.status) : 0)));
91435
91602
  const isCritical = entry.directive_priority === "critical" && (ds.triggerHit || ds.actionHit || ds.agentHit);
91436
- return { ...entry, finalScore, __critical: isCritical };
91603
+ return {
91604
+ ...entry,
91605
+ retrieval_outcomes: retrievalOutcomes,
91606
+ finalScore,
91607
+ __critical: isCritical
91608
+ };
91437
91609
  });
91438
91610
  scored.sort((a, b) => {
91439
91611
  const diff = b.finalScore - a.finalScore;
@@ -91828,7 +92000,7 @@ var init_curator_drift = __esm(() => {
91828
92000
  var exports_project_context = {};
91829
92001
  __export(exports_project_context, {
91830
92002
  buildProjectContext: () => buildProjectContext,
91831
- _internals: () => _internals67,
92003
+ _internals: () => _internals68,
91832
92004
  LANG_BACKEND_DETECTION_TIMEOUT_MS: () => LANG_BACKEND_DETECTION_TIMEOUT_MS
91833
92005
  });
91834
92006
  import * as fs117 from "node:fs";
@@ -91912,7 +92084,7 @@ function selectLintCommand(backend, directory) {
91912
92084
  return null;
91913
92085
  }
91914
92086
  async function buildProjectContext(directory) {
91915
- const backend = await _internals67.pickBackend(directory);
92087
+ const backend = await _internals68.pickBackend(directory);
91916
92088
  if (!backend)
91917
92089
  return null;
91918
92090
  const ctx = emptyProjectContext();
@@ -91943,16 +92115,16 @@ async function buildProjectContext(directory) {
91943
92115
  if (backend.prompts.reviewerChecklist.length > 0) {
91944
92116
  ctx.REVIEWER_CHECKLIST = bulletList(backend.prompts.reviewerChecklist);
91945
92117
  }
91946
- const profiles = _internals67.pickedProfiles(directory);
92118
+ const profiles = _internals68.pickedProfiles(directory);
91947
92119
  if (profiles.length > 1) {
91948
92120
  ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES = profiles.slice(1).map((p) => p.id).join(", ");
91949
92121
  }
91950
92122
  return ctx;
91951
92123
  }
91952
- var LANG_BACKEND_DETECTION_TIMEOUT_MS = 300, _internals67;
92124
+ var LANG_BACKEND_DETECTION_TIMEOUT_MS = 300, _internals68;
91953
92125
  var init_project_context = __esm(() => {
91954
92126
  init_dispatch();
91955
- _internals67 = {
92127
+ _internals68 = {
91956
92128
  pickBackend,
91957
92129
  pickedProfiles
91958
92130
  };
@@ -94546,9 +94718,9 @@ function createPhaseMonitorHook(directory, preflightManager, curatorRunner, dele
94546
94718
  const initResult = await runner(directory, curatorConfig, llmDelegate);
94547
94719
  if (initResult.briefing) {
94548
94720
  const briefingPath = path79.join(directory, ".swarm", "curator-briefing.md");
94549
- const { mkdir: mkdir14, writeFile: writeFile12 } = await import("node:fs/promises");
94721
+ const { mkdir: mkdir14, writeFile: writeFile13 } = await import("node:fs/promises");
94550
94722
  await mkdir14(path79.dirname(briefingPath), { recursive: true });
94551
- await writeFile12(briefingPath, initResult.briefing, "utf-8");
94723
+ await writeFile13(briefingPath, initResult.briefing, "utf-8");
94552
94724
  const { buildApprovedReceipt: buildApprovedReceipt2, persistReviewReceipt: persistReviewReceipt2 } = await Promise.resolve().then(() => (init_review_receipt(), exports_review_receipt));
94553
94725
  const initReceipt = buildApprovedReceipt2({
94554
94726
  agent: "curator",
@@ -102044,7 +102216,7 @@ import * as path101 from "node:path";
102044
102216
  // src/hooks/knowledge-application.ts
102045
102217
  init_logger();
102046
102218
  init_knowledge_store();
102047
- var import_proper_lockfile7 = __toESM(require_proper_lockfile(), 1);
102219
+ var import_proper_lockfile8 = __toESM(require_proper_lockfile(), 1);
102048
102220
  import { existsSync as existsSync56 } from "node:fs";
102049
102221
  import { appendFile as appendFile9, mkdir as mkdir18, readFile as readFile18 } from "node:fs/promises";
102050
102222
  import * as path100 from "node:path";
@@ -102463,10 +102635,12 @@ init_state();
102463
102635
  init_logger();
102464
102636
  init_curator_drift();
102465
102637
  init_extractors();
102638
+ init_knowledge_events();
102466
102639
  init_knowledge_store();
102467
102640
  init_search_knowledge();
102468
102641
  init_utils2();
102469
102642
  var INJECTION_SENTINEL = "‌[[KNOWLEDGE-INJECTED]]";
102643
+ var defaultSearchKnowledge = searchKnowledge;
102470
102644
  function buildKnowledgeBlock(entries, charBudget, cfg, currentProject) {
102471
102645
  if (entries.length === 0)
102472
102646
  return null;
@@ -102644,13 +102818,15 @@ function createKnowledgeInjectorHook(directory, config3) {
102644
102818
  projectName,
102645
102819
  currentPhase: phaseDescription
102646
102820
  };
102647
- const search = await searchKnowledge({
102821
+ const searchFn = _internals48.searchKnowledge === defaultSearchKnowledge ? searchKnowledge : _internals48.searchKnowledge;
102822
+ const search = await searchFn({
102648
102823
  directory,
102649
102824
  config: config3,
102650
102825
  context: retrievalCtx,
102651
102826
  mode: "auto_injection",
102652
102827
  agent: "architect",
102653
- sessionId: systemMsg?.info?.sessionID
102828
+ sessionId: systemMsg?.info?.sessionID,
102829
+ emitEvent: false
102654
102830
  });
102655
102831
  const entries = search.results;
102656
102832
  const filteredEntries = filterHighConfidenceKnowledge(entries);
@@ -102743,7 +102919,27 @@ ${freshPreamble}` : `<curator_briefing>${truncatedBriefing}</curator_briefing>`;
102743
102919
  }
102744
102920
  if (cachedShownIds.length > 0) {
102745
102921
  const phaseLabel = `Phase ${currentPhase}`;
102746
- recordKnowledgeShown(directory, cachedShownIds, {
102922
+ const scoreById = new Map(entries.map((e) => [e.id, e.finalScore]));
102923
+ const ranks = {};
102924
+ const scores = {};
102925
+ cachedShownIds.forEach((id, idx) => {
102926
+ ranks[id] = idx + 1;
102927
+ scores[id] = scoreById.get(id) ?? 0;
102928
+ });
102929
+ await _internals48.recordKnowledgeEvent(directory, {
102930
+ type: "retrieved",
102931
+ trace_id: search.trace_id,
102932
+ session_id: systemMsg?.info?.sessionID ?? "unknown",
102933
+ phase: retrievalCtx.currentPhase,
102934
+ task_id: retrievalCtx.taskId,
102935
+ agent: "architect",
102936
+ query: retrievalCtx.lastUserMessage ?? retrievalCtx.currentPhase ?? "",
102937
+ retrieval_mode: "auto_injection",
102938
+ result_ids: cachedShownIds,
102939
+ ranks,
102940
+ scores
102941
+ });
102942
+ _internals48.recordKnowledgeShown(directory, cachedShownIds, {
102747
102943
  phase: phaseLabel,
102748
102944
  tool: retrievalCtx.currentTool,
102749
102945
  action: retrievalCtx.currentAction,
@@ -102753,6 +102949,11 @@ ${freshPreamble}` : `<curator_briefing>${truncatedBriefing}</curator_briefing>`;
102753
102949
  }
102754
102950
  });
102755
102951
  }
102952
+ var _internals48 = {
102953
+ searchKnowledge,
102954
+ recordKnowledgeEvent,
102955
+ recordKnowledgeShown
102956
+ };
102756
102957
 
102757
102958
  // src/index.ts
102758
102959
  init_normalize_tool_name();
@@ -102896,7 +103097,7 @@ var TASK_DIVERSITY_WEIGHT = 0.05;
102896
103097
  var CONTEXT_WEIGHT = 0.2;
102897
103098
  var RECENCY_DECAY_MS = 30 * 24 * 60 * 60 * 1000;
102898
103099
  var SKILL_FRONTMATTER_READ_BYTES = 16 * 1024;
102899
- var _internals48 = {
103100
+ var _internals49 = {
102900
103101
  computeSkillRelevanceScore: null,
102901
103102
  rankSkillsForContext: null,
102902
103103
  getSkillStats: null,
@@ -103115,7 +103316,7 @@ function formatSkillIndexWithContext(skills, directory) {
103115
103316
  } catch {}
103116
103317
  if (!hasHistory) {
103117
103318
  return skills.map((sp) => {
103118
- const meta3 = _internals48.readSkillMetadata(sp, directory);
103319
+ const meta3 = _internals49.readSkillMetadata(sp, directory);
103119
103320
  return ` - file:${meta3.path} - ${meta3.name}: ${meta3.description}`;
103120
103321
  }).join(`
103121
103322
  `);
@@ -103123,7 +103324,7 @@ function formatSkillIndexWithContext(skills, directory) {
103123
103324
  const lines = [];
103124
103325
  for (const skillPath of skills) {
103125
103326
  const stats = getSkillStats(skillPath, directory);
103126
- const meta3 = _internals48.readSkillMetadata(skillPath, directory);
103327
+ const meta3 = _internals49.readSkillMetadata(skillPath, directory);
103127
103328
  const compliancePct = Math.round(stats.complianceRate * 100);
103128
103329
  const topAgentNames = stats.topAgents.slice(0, 3).map((a) => a.agent).join(", ");
103129
103330
  lines.push(` - file:${meta3.path} - ${meta3.name}: ${meta3.description} (used: ${stats.totalUsage}, compliance: ${compliancePct}%)` + (stats.topAgents.length > 0 ? ` → ${topAgentNames}` : ""));
@@ -103131,15 +103332,15 @@ function formatSkillIndexWithContext(skills, directory) {
103131
103332
  return lines.join(`
103132
103333
  `);
103133
103334
  }
103134
- _internals48.computeSkillRelevanceScore = computeSkillRelevanceScore;
103135
- _internals48.rankSkillsForContext = rankSkillsForContext;
103136
- _internals48.getSkillStats = getSkillStats;
103137
- _internals48.formatSkillIndexWithContext = formatSkillIndexWithContext;
103138
- _internals48.parseSkillFrontmatter = parseSkillFrontmatter;
103139
- _internals48.readSkillMetadata = readSkillMetadata;
103140
- _internals48.extractSkillName = extractSkillName;
103141
- _internals48.computeRecencyScore = computeRecencyScore;
103142
- _internals48.computeContextMatchScore = computeContextMatchScore;
103335
+ _internals49.computeSkillRelevanceScore = computeSkillRelevanceScore;
103336
+ _internals49.rankSkillsForContext = rankSkillsForContext;
103337
+ _internals49.getSkillStats = getSkillStats;
103338
+ _internals49.formatSkillIndexWithContext = formatSkillIndexWithContext;
103339
+ _internals49.parseSkillFrontmatter = parseSkillFrontmatter;
103340
+ _internals49.readSkillMetadata = readSkillMetadata;
103341
+ _internals49.extractSkillName = extractSkillName;
103342
+ _internals49.computeRecencyScore = computeRecencyScore;
103343
+ _internals49.computeContextMatchScore = computeContextMatchScore;
103143
103344
 
103144
103345
  // src/hooks/skill-propagation-gate.ts
103145
103346
  init_skill_usage_log();
@@ -103242,10 +103443,10 @@ function parseYamlValue(value) {
103242
103443
  }
103243
103444
  function loadRoutingSkills(directory, targetAgent) {
103244
103445
  const routingPath = path105.join(directory, ".opencode", "skill-routing.yaml");
103245
- if (!_internals49.existsSync(routingPath))
103446
+ if (!_internals50.existsSync(routingPath))
103246
103447
  return [];
103247
103448
  try {
103248
- const content = _internals49.readFileSync(routingPath, "utf-8");
103449
+ const content = _internals50.readFileSync(routingPath, "utf-8");
103249
103450
  const config3 = parseSimpleYaml(content);
103250
103451
  if (!config3?.routing)
103251
103452
  return [];
@@ -103272,7 +103473,7 @@ var SKILL_SEARCH_ROOTS = [
103272
103473
  ".claude/skills"
103273
103474
  ];
103274
103475
  var MAX_SCORING_SESSION_ENTRIES = 500;
103275
- var _internals49 = {
103476
+ var _internals50 = {
103276
103477
  readdirSync: fs67.readdirSync.bind(fs67),
103277
103478
  existsSync: fs67.existsSync.bind(fs67),
103278
103479
  statSync: fs67.statSync.bind(fs67),
@@ -103301,11 +103502,11 @@ function discoverAvailableSkills(directory) {
103301
103502
  const results = [];
103302
103503
  for (const root of SKILL_SEARCH_ROOTS) {
103303
103504
  const rootPath = path105.join(directory, root);
103304
- if (!_internals49.existsSync(rootPath))
103505
+ if (!_internals50.existsSync(rootPath))
103305
103506
  continue;
103306
103507
  let entries;
103307
103508
  try {
103308
- entries = _internals49.readdirSync(rootPath);
103509
+ entries = _internals50.readdirSync(rootPath);
103309
103510
  } catch {
103310
103511
  continue;
103311
103512
  }
@@ -103313,11 +103514,11 @@ function discoverAvailableSkills(directory) {
103313
103514
  if (entry.startsWith("."))
103314
103515
  continue;
103315
103516
  const skillDir = path105.join(rootPath, entry);
103316
- if (_internals49.existsSync(path105.join(skillDir, "retired.marker")))
103517
+ if (_internals50.existsSync(path105.join(skillDir, "retired.marker")))
103317
103518
  continue;
103318
103519
  const skillFile = path105.join(skillDir, "SKILL.md");
103319
103520
  try {
103320
- if (_internals49.statSync(skillDir).isDirectory() && _internals49.existsSync(skillFile)) {
103521
+ if (_internals50.statSync(skillDir).isDirectory() && _internals50.existsSync(skillFile)) {
103321
103522
  results.push(path105.join(root, entry, "SKILL.md").replace(/\\/g, "/"));
103322
103523
  }
103323
103524
  } catch (err2) {
@@ -103349,7 +103550,7 @@ function parseDelegationArgs(args2) {
103349
103550
  }
103350
103551
  if (!targetAgent)
103351
103552
  return null;
103352
- const skillsField = prompt ? _internals49.extractSkillsFieldFromPrompt(prompt) : "";
103553
+ const skillsField = prompt ? _internals50.extractSkillsFieldFromPrompt(prompt) : "";
103353
103554
  return { targetAgent, skillsField };
103354
103555
  }
103355
103556
  function extractSkillsFieldFromPrompt(prompt) {
@@ -103390,10 +103591,10 @@ function writeWarnEvent2(directory, record3) {
103390
103591
  const filePath = path105.join(directory, ".swarm", "events.jsonl");
103391
103592
  try {
103392
103593
  const dir = path105.dirname(filePath);
103393
- if (!_internals49.existsSync(dir)) {
103394
- _internals49.mkdirSync(dir, { recursive: true });
103594
+ if (!_internals50.existsSync(dir)) {
103595
+ _internals50.mkdirSync(dir, { recursive: true });
103395
103596
  }
103396
- _internals49.appendFileSync(filePath, `${JSON.stringify(record3)}
103597
+ _internals50.appendFileSync(filePath, `${JSON.stringify(record3)}
103397
103598
  `, "utf-8");
103398
103599
  } catch (err2) {
103399
103600
  warn(`[skill-propagation-gate] failed to write warning event: ${err2 instanceof Error ? err2.message : String(err2)}`);
@@ -103444,19 +103645,19 @@ async function skillPropagationGateBefore(directory, input, config3) {
103444
103645
  const baseAgent = stripKnownSwarmPrefix(agentRaw);
103445
103646
  if (baseAgent !== "architect")
103446
103647
  return { blocked: false, reason: null, recommendedSkills: undefined };
103447
- const parsed = _internals49.parseDelegationArgs(input.args);
103648
+ const parsed = _internals50.parseDelegationArgs(input.args);
103448
103649
  if (!parsed)
103449
103650
  return { blocked: false, reason: null, recommendedSkills: undefined };
103450
103651
  const targetBase = stripKnownSwarmPrefix(parsed.targetAgent);
103451
- if (!_internals49.SKILL_CAPABLE_AGENTS.has(targetBase))
103652
+ if (!_internals50.SKILL_CAPABLE_AGENTS.has(targetBase))
103452
103653
  return { blocked: false, reason: null, recommendedSkills: undefined };
103453
103654
  const sessionID = typeof input.sessionID === "string" ? input.sessionID : "unknown";
103454
- const availableSkills = _internals49.discoverAvailableSkills(directory);
103655
+ const availableSkills = _internals50.discoverAvailableSkills(directory);
103455
103656
  const skillsValue = parsed.skillsField.trim();
103456
103657
  if (skillsValue && skillsValue.toLowerCase() !== "none") {
103457
103658
  const prompt = typeof input.args?.prompt === "string" ? String(input.args.prompt) : "";
103458
- const taskId = _internals49.extractTaskIdFromPrompt(prompt);
103459
- const skillPaths = _internals49.parseSkillPaths(skillsValue);
103659
+ const taskId = _internals50.extractTaskIdFromPrompt(prompt);
103660
+ const skillPaths = _internals50.parseSkillPaths(skillsValue);
103460
103661
  let coderSkillPaths = [];
103461
103662
  if (prompt) {
103462
103663
  for (const line of prompt.split(`
@@ -103464,7 +103665,7 @@ async function skillPropagationGateBefore(directory, input, config3) {
103464
103665
  const trimmed = line.trim();
103465
103666
  if (trimmed.startsWith("SKILLS_USED_BY_CODER:")) {
103466
103667
  const fieldVal = trimmed.slice("SKILLS_USED_BY_CODER:".length).trim();
103467
- coderSkillPaths = _internals49.parseSkillPaths(fieldVal);
103668
+ coderSkillPaths = _internals50.parseSkillPaths(fieldVal);
103468
103669
  break;
103469
103670
  }
103470
103671
  }
@@ -103472,7 +103673,7 @@ async function skillPropagationGateBefore(directory, input, config3) {
103472
103673
  const allPaths = [...new Set([...skillPaths, ...coderSkillPaths])];
103473
103674
  for (const skillPath of allPaths) {
103474
103675
  try {
103475
- _internals49.appendSkillUsageEntry(directory, {
103676
+ _internals50.appendSkillUsageEntry(directory, {
103476
103677
  skillPath,
103477
103678
  agentName: targetBase,
103478
103679
  taskID: taskId,
@@ -103489,17 +103690,17 @@ async function skillPropagationGateBefore(directory, input, config3) {
103489
103690
  let scored = [];
103490
103691
  if (skillsValue && skillsValue.toLowerCase() !== "none" && availableSkills.length > 0) {
103491
103692
  try {
103492
- const sessionEntries = _internals49.readSkillUsageEntriesTail(directory, {
103693
+ const sessionEntries = _internals50.readSkillUsageEntriesTail(directory, {
103493
103694
  sessionID
103494
103695
  });
103495
- if (sessionEntries.length > _internals49.MAX_SCORING_SESSION_ENTRIES) {
103696
+ if (sessionEntries.length > _internals50.MAX_SCORING_SESSION_ENTRIES) {
103496
103697
  scoringSkipped = true;
103497
- warn(`[skill-propagation-gate] skipping scoring — session has ${sessionEntries.length} entries (limit: ${_internals49.MAX_SCORING_SESSION_ENTRIES})`);
103698
+ warn(`[skill-propagation-gate] skipping scoring — session has ${sessionEntries.length} entries (limit: ${_internals50.MAX_SCORING_SESSION_ENTRIES})`);
103498
103699
  } else {
103499
103700
  const prompt = typeof input.args?.prompt === "string" ? String(input.args.prompt) : "";
103500
103701
  scored = availableSkills.map((skillPath) => {
103501
103702
  const skillEntries = sessionEntries.filter((e) => e.skillPath === skillPath);
103502
- const score = _internals49.computeSkillRelevanceScore(skillPath, prompt, skillEntries);
103703
+ const score = _internals50.computeSkillRelevanceScore(skillPath, prompt, skillEntries);
103503
103704
  return { skillPath, score, usageCount: skillEntries.length };
103504
103705
  }).sort((a, b) => b.score - a.score || b.usageCount - a.usageCount);
103505
103706
  if (scored.length > 0) {
@@ -103513,12 +103714,12 @@ async function skillPropagationGateBefore(directory, input, config3) {
103513
103714
  }
103514
103715
  }
103515
103716
  try {
103516
- const routingPaths = _internals49.loadRoutingSkills(directory, targetBase);
103717
+ const routingPaths = _internals50.loadRoutingSkills(directory, targetBase);
103517
103718
  if (routingPaths.length > 0) {
103518
103719
  const existingPaths = new Set(scored.map((s) => s.skillPath));
103519
103720
  for (const routingPath of routingPaths) {
103520
103721
  const routedSkillDir = path105.dirname(path105.join(directory, routingPath));
103521
- if (_internals49.existsSync(path105.join(routedSkillDir, "retired.marker")))
103722
+ if (_internals50.existsSync(path105.join(routedSkillDir, "retired.marker")))
103522
103723
  continue;
103523
103724
  if (!existingPaths.has(routingPath)) {
103524
103725
  scored.push({
@@ -103544,12 +103745,12 @@ async function skillPropagationGateBefore(directory, input, config3) {
103544
103745
  } else if (typeof scored !== "undefined" && scored.length > 0) {
103545
103746
  skillsForIndex = scored.map((r) => r.skillPath);
103546
103747
  }
103547
- const formattedIndex = _internals49.formatSkillIndexWithContext(skillsForIndex, directory);
103748
+ const formattedIndex = _internals50.formatSkillIndexWithContext(skillsForIndex, directory);
103548
103749
  if (formattedIndex.length > 0) {
103549
103750
  const contextPath = path105.join(directory, ".swarm", "context.md");
103550
103751
  let existingContent = "";
103551
- if (_internals49.existsSync(contextPath)) {
103552
- existingContent = _internals49.readFileSync(contextPath, "utf-8");
103752
+ if (_internals50.existsSync(contextPath)) {
103753
+ existingContent = _internals50.readFileSync(contextPath, "utf-8");
103553
103754
  }
103554
103755
  const sectionHeader = "## Available Skills";
103555
103756
  const newSection = `${sectionHeader}
@@ -103569,10 +103770,10 @@ ${newSection}`;
103569
103770
  }
103570
103771
  }
103571
103772
  const swarmDir = path105.dirname(contextPath);
103572
- if (!_internals49.existsSync(swarmDir)) {
103573
- _internals49.mkdirSync(swarmDir, { recursive: true });
103773
+ if (!_internals50.existsSync(swarmDir)) {
103774
+ _internals50.mkdirSync(swarmDir, { recursive: true });
103574
103775
  }
103575
- _internals49.writeFileSync(contextPath, updatedContent, "utf-8");
103776
+ _internals50.writeFileSync(contextPath, updatedContent, "utf-8");
103576
103777
  }
103577
103778
  } catch (err2) {
103578
103779
  warn(`[skill-propagation-gate] failed to write skill index to context.md: ${err2 instanceof Error ? err2.message : String(err2)}`);
@@ -103598,7 +103799,7 @@ ${newSection}`;
103598
103799
  });
103599
103800
  const warningMsg = `Skill propagation warning: Delegating to ${targetBase} without SKILLS field. ` + `Available skills: ${skillNames.join(", ")}`;
103600
103801
  try {
103601
- _internals49.writeWarnEvent(directory, {
103802
+ _internals50.writeWarnEvent(directory, {
103602
103803
  type: "skill_propagation_warn",
103603
103804
  timestamp: new Date().toISOString(),
103604
103805
  tool: toolName,
@@ -103627,7 +103828,7 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
103627
103828
  let dedupKeys = new Set;
103628
103829
  let existingEntries = [];
103629
103830
  try {
103630
- existingEntries = _internals49.readSkillUsageEntriesTail(directory, {
103831
+ existingEntries = _internals50.readSkillUsageEntriesTail(directory, {
103631
103832
  sessionID
103632
103833
  });
103633
103834
  dedupKeys = new Set(existingEntries.map((e, i2) => {
@@ -103659,7 +103860,7 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
103659
103860
  `)) {
103660
103861
  const coderMatch = line.trim().match(CODER_SKILLS_PATTERN);
103661
103862
  if (coderMatch) {
103662
- const parsed = _internals49.parseSkillPaths(coderMatch[1]);
103863
+ const parsed = _internals50.parseSkillPaths(coderMatch[1]);
103663
103864
  skillPaths.push(...parsed);
103664
103865
  }
103665
103866
  }
@@ -103690,7 +103891,7 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
103690
103891
  if (isDuplicate(skillPath, "reviewer", resolvedTaskID))
103691
103892
  continue;
103692
103893
  try {
103693
- _internals49.appendSkillUsageEntry(directory, {
103894
+ _internals50.appendSkillUsageEntry(directory, {
103694
103895
  skillPath,
103695
103896
  agentName: "reviewer",
103696
103897
  taskID: resolvedTaskID,
@@ -103734,15 +103935,15 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
103734
103935
  skillsField = trimmed.slice("SKILLS:".length).trim();
103735
103936
  }
103736
103937
  if (currentTargetAgent && skillsField && skillsField.toLowerCase() !== "none") {
103737
- const skillPaths = _internals49.parseSkillPaths(skillsField);
103738
- const taskId = _internals49.extractTaskIdFromPrompt(text);
103938
+ const skillPaths = _internals50.parseSkillPaths(skillsField);
103939
+ const taskId = _internals50.extractTaskIdFromPrompt(text);
103739
103940
  for (const skillPath of skillPaths) {
103740
103941
  if (hadRecordingError)
103741
103942
  break;
103742
103943
  if (isDuplicate(skillPath, currentTargetAgent, taskId))
103743
103944
  continue;
103744
103945
  try {
103745
- _internals49.appendSkillUsageEntry(directory, {
103946
+ _internals50.appendSkillUsageEntry(directory, {
103746
103947
  skillPath,
103747
103948
  agentName: currentTargetAgent,
103748
103949
  taskID: taskId,
@@ -103762,16 +103963,16 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
103762
103963
  break;
103763
103964
  }
103764
103965
  }
103765
- _internals49.skillPropagationGateBefore = skillPropagationGateBefore;
103766
- _internals49.skillPropagationTransformScan = skillPropagationTransformScan;
103767
- _internals49.writeWarnEvent = writeWarnEvent2;
103768
- _internals49.discoverAvailableSkills = discoverAvailableSkills;
103769
- _internals49.parseDelegationArgs = parseDelegationArgs;
103770
- _internals49.parseSkillPaths = parseSkillPaths;
103771
- _internals49.extractTaskIdFromPrompt = extractTaskIdFromPrompt;
103772
- _internals49.extractSkillsFieldFromPrompt = extractSkillsFieldFromPrompt;
103773
- _internals49.formatSkillIndexWithContext = formatSkillIndexWithContext;
103774
- _internals49.loadRoutingSkills = loadRoutingSkills;
103966
+ _internals50.skillPropagationGateBefore = skillPropagationGateBefore;
103967
+ _internals50.skillPropagationTransformScan = skillPropagationTransformScan;
103968
+ _internals50.writeWarnEvent = writeWarnEvent2;
103969
+ _internals50.discoverAvailableSkills = discoverAvailableSkills;
103970
+ _internals50.parseDelegationArgs = parseDelegationArgs;
103971
+ _internals50.parseSkillPaths = parseSkillPaths;
103972
+ _internals50.extractTaskIdFromPrompt = extractTaskIdFromPrompt;
103973
+ _internals50.extractSkillsFieldFromPrompt = extractSkillsFieldFromPrompt;
103974
+ _internals50.formatSkillIndexWithContext = formatSkillIndexWithContext;
103975
+ _internals50.loadRoutingSkills = loadRoutingSkills;
103775
103976
 
103776
103977
  // src/index.ts
103777
103978
  init_skill_usage_log();
@@ -107063,7 +107264,7 @@ var EVIDENCE_DIR2 = ".swarm/evidence";
107063
107264
  var VALID_TASK_ID = /^\d+\.\d+(\.\d+)*$/;
107064
107265
  var COUNCIL_GATE_NAME = "council";
107065
107266
  var COUNCIL_AGENT_ID = "architect";
107066
- var _internals50 = {
107267
+ var _internals51 = {
107067
107268
  withTaskEvidenceLock
107068
107269
  };
107069
107270
  var FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
@@ -107098,7 +107299,7 @@ async function writeCouncilEvidence(workingDir, synthesis) {
107098
107299
  const dir = join95(workingDir, EVIDENCE_DIR2);
107099
107300
  mkdirSync28(dir, { recursive: true });
107100
107301
  const filePath = taskEvidencePath(workingDir, synthesis.taskId);
107101
- await _internals50.withTaskEvidenceLock(workingDir, synthesis.taskId, COUNCIL_AGENT_ID, async () => {
107302
+ await _internals51.withTaskEvidenceLock(workingDir, synthesis.taskId, COUNCIL_AGENT_ID, async () => {
107102
107303
  const existingRoot = Object.create(null);
107103
107304
  if (existsSync63(filePath)) {
107104
107305
  try {
@@ -110739,7 +110940,8 @@ var knowledge_receipt = createSwarmTool({
110739
110940
  for (const item of newLessons) {
110740
110941
  const raw = await knowledge_add.execute({ lesson: item.lesson, category: item.category }, ctx);
110741
110942
  try {
110742
- newLessonResults.push(JSON.parse(raw));
110943
+ const output = typeof raw === "string" ? raw : typeof raw === "object" && raw !== null && ("output" in raw) && typeof raw.output === "string" ? raw.output : "";
110944
+ newLessonResults.push(JSON.parse(output));
110743
110945
  } catch {
110744
110946
  newLessonResults.push({ success: false });
110745
110947
  }
@@ -111202,7 +111404,7 @@ function listLaneEvidenceSync(directory, phase) {
111202
111404
  }
111203
111405
  return laneIds;
111204
111406
  }
111205
- var _internals51 = {
111407
+ var _internals52 = {
111206
111408
  listActiveLocks,
111207
111409
  readPersisted: readPersisted2,
111208
111410
  readPlanJson: defaultReadPlanJson,
@@ -111263,7 +111465,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111263
111465
  reason: "Lean Turbo state unreadable or missing"
111264
111466
  };
111265
111467
  }
111266
- const persisted = _internals51.readPersisted(directory);
111468
+ const persisted = _internals52.readPersisted(directory);
111267
111469
  if (!persisted) {
111268
111470
  return {
111269
111471
  ok: false,
@@ -111327,7 +111529,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111327
111529
  }
111328
111530
  }
111329
111531
  if (runState.lanes.length > 0) {
111330
- const evidenceLaneIds = new Set(_internals51.listLaneEvidenceSync(directory, phase));
111532
+ const evidenceLaneIds = new Set(_internals52.listLaneEvidenceSync(directory, phase));
111331
111533
  for (const lane of runState.lanes) {
111332
111534
  if ((lane.status === "completed" || lane.status === "failed") && !evidenceLaneIds.has(lane.laneId)) {
111333
111535
  return {
@@ -111337,7 +111539,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111337
111539
  }
111338
111540
  }
111339
111541
  }
111340
- const activeLocks = _internals51.listActiveLocks(directory);
111542
+ const activeLocks = _internals52.listActiveLocks(directory);
111341
111543
  const phaseLaneIds = new Set(laneIds);
111342
111544
  for (const lock of activeLocks) {
111343
111545
  if (lock.laneId && phaseLaneIds.has(lock.laneId)) {
@@ -111357,7 +111559,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111357
111559
  }
111358
111560
  const serialDegradedTasks = runState.degradedTasks.filter((dt) => !laneTaskIds.has(dt.taskId));
111359
111561
  if (serialDegradedTasks.length > 0) {
111360
- const plan = _internals51.readPlanJson(directory);
111562
+ const plan = _internals52.readPlanJson(directory);
111361
111563
  if (!plan) {
111362
111564
  return {
111363
111565
  ok: false,
@@ -111401,7 +111603,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111401
111603
  }
111402
111604
  const serializedTasks = runState.serializedTasks;
111403
111605
  if (Array.isArray(serializedTasks) && serializedTasks.length > 0) {
111404
- const plan = _internals51.readPlanJson(directory);
111606
+ const plan = _internals52.readPlanJson(directory);
111405
111607
  if (!plan) {
111406
111608
  return {
111407
111609
  ok: false,
@@ -111460,7 +111662,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111460
111662
  }
111461
111663
  let reviewerVerdict = runState.lastReviewerVerdict;
111462
111664
  if (!reviewerVerdict) {
111463
- const evidence = _internals51.readReviewerEvidence(directory, phase);
111665
+ const evidence = _internals52.readReviewerEvidence(directory, phase);
111464
111666
  reviewerVerdict = evidence?.verdict ?? undefined;
111465
111667
  }
111466
111668
  if (mergedConfig.phase_reviewer) {
@@ -111473,7 +111675,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111473
111675
  }
111474
111676
  let criticVerdict = runState.lastCriticVerdict;
111475
111677
  if (!criticVerdict) {
111476
- const evidence = _internals51.readCriticEvidence(directory, phase);
111678
+ const evidence = _internals52.readCriticEvidence(directory, phase);
111477
111679
  criticVerdict = evidence?.verdict ?? undefined;
111478
111680
  }
111479
111681
  if (mergedConfig.phase_critic) {
@@ -112451,7 +112653,7 @@ Findings: ${details.join("; ")}` : "";
112451
112653
  phase_critic: leanConfig.phase_critic,
112452
112654
  integrated_diff_required: leanConfig.integrated_diff_required
112453
112655
  } : undefined;
112454
- const leanCheck = _internals51.verifyLeanTurboPhaseReady(dir, phase, sessionID, leanPhaseReadyConfig);
112656
+ const leanCheck = _internals52.verifyLeanTurboPhaseReady(dir, phase, sessionID, leanPhaseReadyConfig);
112455
112657
  if (!leanCheck.ok) {
112456
112658
  return JSON.stringify({
112457
112659
  success: false,
@@ -114669,11 +114871,11 @@ var quality_budget = createSwarmTool({
114669
114871
  }).optional().describe("Quality budget thresholds")
114670
114872
  },
114671
114873
  async execute(args2, directory) {
114672
- const result = await _internals52.qualityBudget(args2, directory);
114874
+ const result = await _internals53.qualityBudget(args2, directory);
114673
114875
  return JSON.stringify(result);
114674
114876
  }
114675
114877
  });
114676
- var _internals52 = {
114878
+ var _internals53 = {
114677
114879
  qualityBudget
114678
114880
  };
114679
114881
 
@@ -115402,7 +115604,7 @@ import * as path129 from "node:path";
115402
115604
  var semgrepAvailableCache = null;
115403
115605
  var DEFAULT_RULES_DIR = ".swarm/semgrep-rules";
115404
115606
  var DEFAULT_TIMEOUT_MS3 = 30000;
115405
- var _internals53 = {
115607
+ var _internals54 = {
115406
115608
  isSemgrepAvailable,
115407
115609
  checkSemgrepAvailable,
115408
115610
  resetSemgrepCache,
@@ -115427,7 +115629,7 @@ function isSemgrepAvailable() {
115427
115629
  }
115428
115630
  }
115429
115631
  async function checkSemgrepAvailable() {
115430
- return _internals53.isSemgrepAvailable();
115632
+ return _internals54.isSemgrepAvailable();
115431
115633
  }
115432
115634
  function resetSemgrepCache() {
115433
115635
  semgrepAvailableCache = null;
@@ -115524,12 +115726,12 @@ async function runSemgrep(options) {
115524
115726
  const timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS3;
115525
115727
  if (files.length === 0) {
115526
115728
  return {
115527
- available: _internals53.isSemgrepAvailable(),
115729
+ available: _internals54.isSemgrepAvailable(),
115528
115730
  findings: [],
115529
115731
  engine: "tier_a"
115530
115732
  };
115531
115733
  }
115532
- if (!_internals53.isSemgrepAvailable()) {
115734
+ if (!_internals54.isSemgrepAvailable()) {
115533
115735
  return {
115534
115736
  available: false,
115535
115737
  findings: [],
@@ -115688,7 +115890,7 @@ function assignOccurrenceIndices(findings, directory) {
115688
115890
  }
115689
115891
  const occIdx = countMap.get(baseKey) ?? 0;
115690
115892
  countMap.set(baseKey, occIdx + 1);
115691
- const fp = _internals54.fingerprintFinding(finding, directory, occIdx);
115893
+ const fp = _internals55.fingerprintFinding(finding, directory, occIdx);
115692
115894
  return {
115693
115895
  finding,
115694
115896
  index: occIdx,
@@ -115757,7 +115959,7 @@ async function captureOrMergeBaseline(directory, phase, findings, engine, scanne
115757
115959
  }
115758
115960
  } catch {}
115759
115961
  const scannedRelFiles = new Set(scannedFiles.map((f) => normalizeFindingPath(directory, f)));
115760
- const indexed = _internals54.assignOccurrenceIndices(findings, directory);
115962
+ const indexed = _internals55.assignOccurrenceIndices(findings, directory);
115761
115963
  if (existing && !opts?.force) {
115762
115964
  const prunedFingerprints = existing.fingerprints.filter((fp) => {
115763
115965
  const relFile = fp.slice(0, fp.indexOf("|"));
@@ -115897,7 +116099,7 @@ function loadBaseline(directory, phase) {
115897
116099
  };
115898
116100
  }
115899
116101
  }
115900
- var _internals54 = {
116102
+ var _internals55 = {
115901
116103
  fingerprintFinding,
115902
116104
  assignOccurrenceIndices,
115903
116105
  captureOrMergeBaseline,
@@ -116307,11 +116509,11 @@ var sast_scan = createSwarmTool({
116307
116509
  capture_baseline: safeArgs.capture_baseline,
116308
116510
  phase: safeArgs.phase
116309
116511
  };
116310
- const result = await _internals55.sastScan(input, directory);
116512
+ const result = await _internals56.sastScan(input, directory);
116311
116513
  return JSON.stringify(result, null, 2);
116312
116514
  }
116313
116515
  });
116314
- var _internals55 = {
116516
+ var _internals56 = {
116315
116517
  sastScan,
116316
116518
  sast_scan
116317
116519
  };
@@ -120234,7 +120436,7 @@ init_zod();
120234
120436
  init_config();
120235
120437
  init_schema();
120236
120438
  init_create_tool();
120237
- import { mkdir as mkdir23, rename as rename9, writeFile as writeFile17 } from "node:fs/promises";
120439
+ import { mkdir as mkdir23, rename as rename9, writeFile as writeFile18 } from "node:fs/promises";
120238
120440
  import * as path139 from "node:path";
120239
120441
  var MAX_SPEC_BYTES = 256 * 1024;
120240
120442
  var spec_write = createSwarmTool({
@@ -120296,7 +120498,7 @@ ${content}
120296
120498
  }
120297
120499
  } catch {}
120298
120500
  }
120299
- await writeFile17(tmp, finalContent, "utf-8");
120501
+ await writeFile18(tmp, finalContent, "utf-8");
120300
120502
  await rename9(tmp, target);
120301
120503
  return JSON.stringify({ written: true, path: target, bytes: finalContent.length }, null, 2);
120302
120504
  }
@@ -120728,7 +120930,7 @@ var swarm_memory_propose = createSwarmTool({
120728
120930
  evidenceRefs: exports_external.array(exports_external.string().min(1).max(500)).max(20).optional().describe("Evidence refs such as files, commits, test outputs, or URLs")
120729
120931
  },
120730
120932
  execute: async (args2, directory, ctx) => {
120731
- const { config: config3 } = _internals56.loadPluginConfigWithMeta(directory);
120933
+ const { config: config3 } = _internals57.loadPluginConfigWithMeta(directory);
120732
120934
  if (config3.memory?.enabled !== true) {
120733
120935
  return JSON.stringify({
120734
120936
  success: false,
@@ -120744,7 +120946,7 @@ var swarm_memory_propose = createSwarmTool({
120744
120946
  });
120745
120947
  }
120746
120948
  const agent = getContextAgent2(ctx);
120747
- const gateway = _internals56.createMemoryGateway({
120949
+ const gateway = _internals57.createMemoryGateway({
120748
120950
  directory,
120749
120951
  sessionID: ctx?.sessionID,
120750
120952
  agentRole: agent,
@@ -120769,7 +120971,7 @@ var swarm_memory_propose = createSwarmTool({
120769
120971
  }
120770
120972
  }
120771
120973
  });
120772
- var _internals56 = {
120974
+ var _internals57 = {
120773
120975
  loadPluginConfigWithMeta,
120774
120976
  createMemoryGateway
120775
120977
  };
@@ -120806,7 +121008,7 @@ var swarm_memory_recall = createSwarmTool({
120806
121008
  maxItems: exports_external.number().int().min(1).max(20).optional().describe("Maximum memories to return")
120807
121009
  },
120808
121010
  execute: async (args2, directory, ctx) => {
120809
- const { config: config3 } = _internals57.loadPluginConfigWithMeta(directory);
121011
+ const { config: config3 } = _internals58.loadPluginConfigWithMeta(directory);
120810
121012
  if (config3.memory?.enabled !== true) {
120811
121013
  return JSON.stringify({
120812
121014
  success: false,
@@ -120822,7 +121024,7 @@ var swarm_memory_recall = createSwarmTool({
120822
121024
  });
120823
121025
  }
120824
121026
  const agent = getContextAgent3(ctx);
120825
- const gateway = _internals57.createMemoryGateway({
121027
+ const gateway = _internals58.createMemoryGateway({
120826
121028
  directory,
120827
121029
  sessionID: ctx?.sessionID,
120828
121030
  agentRole: agent,
@@ -120855,7 +121057,7 @@ var RecallArgsSchema = exports_external.object({
120855
121057
  kinds: exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional(),
120856
121058
  maxItems: exports_external.number().int().min(1).max(20).optional()
120857
121059
  });
120858
- var _internals57 = {
121060
+ var _internals58 = {
120859
121061
  loadPluginConfigWithMeta,
120860
121062
  createMemoryGateway
120861
121063
  };
@@ -122100,7 +122302,7 @@ function resolveDefaultReviewerAgent(generatedAgentNames) {
122100
122302
  }
122101
122303
  async function compileReviewPackage(directory, phase, sessionID, requireDiffSummary) {
122102
122304
  const lanes = await listLaneEvidence(directory, phase);
122103
- const persisted = _internals58.readPersisted?.(directory) ?? null;
122305
+ const persisted = _internals59.readPersisted?.(directory) ?? null;
122104
122306
  if (persisted) {
122105
122307
  let matchingRunState = null;
122106
122308
  for (const sessionState of Object.values(persisted.sessions)) {
@@ -122292,7 +122494,7 @@ Be specific and evidence-based. Do not approve a phase with unresolved degraded
122292
122494
  client.session.delete({ path: { id: sessionId } }).catch(() => {});
122293
122495
  }
122294
122496
  }
122295
- var _internals58 = {
122497
+ var _internals59 = {
122296
122498
  compileReviewPackage,
122297
122499
  parseReviewerVerdict,
122298
122500
  writeReviewerEvidence,
@@ -122309,28 +122511,28 @@ async function dispatchPhaseReviewer(directory, phase, sessionID, config3) {
122309
122511
  };
122310
122512
  const generatedAgentNames = swarmState.generatedAgentNames;
122311
122513
  const agentName = mergedConfig.reviewerAgent || resolveDefaultReviewerAgent(generatedAgentNames);
122312
- const pkg = await _internals58.compileReviewPackage(directory, phase, sessionID, mergedConfig.requireDiffSummary);
122514
+ const pkg = await _internals59.compileReviewPackage(directory, phase, sessionID, mergedConfig.requireDiffSummary);
122313
122515
  let responseText;
122314
122516
  try {
122315
- responseText = await _internals58.dispatchReviewerAgent(directory, pkg, agentName, mergedConfig.timeoutMs);
122517
+ responseText = await _internals59.dispatchReviewerAgent(directory, pkg, agentName, mergedConfig.timeoutMs);
122316
122518
  } catch (error93) {
122317
- const evidencePath2 = await _internals58.writeReviewerEvidence(directory, phase, "REJECTED", error93 instanceof Error ? error93.message : String(error93));
122519
+ const evidencePath2 = await _internals59.writeReviewerEvidence(directory, phase, "REJECTED", error93 instanceof Error ? error93.message : String(error93));
122318
122520
  return {
122319
122521
  verdict: "REJECTED",
122320
122522
  reason: `Reviewer dispatch failed: ${error93 instanceof Error ? error93.message : String(error93)}`,
122321
122523
  evidencePath: evidencePath2
122322
122524
  };
122323
122525
  }
122324
- const parsed = _internals58.parseReviewerVerdict(responseText);
122526
+ const parsed = _internals59.parseReviewerVerdict(responseText);
122325
122527
  if (!parsed) {
122326
- const evidencePath2 = await _internals58.writeReviewerEvidence(directory, phase, "REJECTED", "Reviewer response could not be parsed");
122528
+ const evidencePath2 = await _internals59.writeReviewerEvidence(directory, phase, "REJECTED", "Reviewer response could not be parsed");
122327
122529
  return {
122328
122530
  verdict: "REJECTED",
122329
122531
  reason: "Reviewer response could not be parsed",
122330
122532
  evidencePath: evidencePath2
122331
122533
  };
122332
122534
  }
122333
- const evidencePath = await _internals58.writeReviewerEvidence(directory, phase, parsed.verdict, parsed.reason);
122535
+ const evidencePath = await _internals59.writeReviewerEvidence(directory, phase, parsed.verdict, parsed.reason);
122334
122536
  return {
122335
122537
  verdict: parsed.verdict,
122336
122538
  reason: parsed.reason,
@@ -122836,7 +123038,7 @@ ${fileList}
122836
123038
 
122837
123039
  // src/tools/lean-turbo-run-phase.ts
122838
123040
  init_create_tool();
122839
- var _internals59 = {
123041
+ var _internals60 = {
122840
123042
  LeanTurboRunner,
122841
123043
  loadPluginConfigWithMeta
122842
123044
  };
@@ -122846,9 +123048,9 @@ async function executeLeanTurboRunPhase(args2) {
122846
123048
  let runError = null;
122847
123049
  let runner = null;
122848
123050
  try {
122849
- const { config: config3 } = _internals59.loadPluginConfigWithMeta(directory);
123051
+ const { config: config3 } = _internals60.loadPluginConfigWithMeta(directory);
122850
123052
  const leanConfig = config3.turbo?.strategy === "lean" ? config3.turbo.lean : undefined;
122851
- runner = new _internals59.LeanTurboRunner({
123053
+ runner = new _internals60.LeanTurboRunner({
122852
123054
  directory,
122853
123055
  sessionID,
122854
123056
  opencodeClient: swarmState.opencodeClient ?? null,
@@ -123202,7 +123404,7 @@ function isStaticallyEquivalent(originalCode, mutatedCode) {
123202
123404
  const strippedMutated = stripCode(mutatedCode);
123203
123405
  return strippedOriginal === strippedMutated;
123204
123406
  }
123205
- var _internals60 = {
123407
+ var _internals61 = {
123206
123408
  isStaticallyEquivalent,
123207
123409
  checkEquivalence,
123208
123410
  batchCheckEquivalence
@@ -123242,7 +123444,7 @@ async function batchCheckEquivalence(patches, llmJudge) {
123242
123444
  const results = [];
123243
123445
  for (const { patch, originalCode, mutatedCode } of patches) {
123244
123446
  try {
123245
- const result = await _internals60.checkEquivalence(patch, originalCode, mutatedCode, llmJudge);
123447
+ const result = await _internals61.checkEquivalence(patch, originalCode, mutatedCode, llmJudge);
123246
123448
  results.push(result);
123247
123449
  } catch (err3) {
123248
123450
  results.push({
@@ -123261,7 +123463,7 @@ async function batchCheckEquivalence(patches, llmJudge) {
123261
123463
  var MUTATION_TIMEOUT_MS = 30000;
123262
123464
  var TOTAL_BUDGET_MS = 300000;
123263
123465
  var GIT_APPLY_TIMEOUT_MS = 5000;
123264
- var _internals61 = {
123466
+ var _internals62 = {
123265
123467
  executeMutation,
123266
123468
  computeReport,
123267
123469
  executeMutationSuite,
@@ -123293,7 +123495,7 @@ async function executeMutation(patch, testCommand, _testFiles, workingDir) {
123293
123495
  };
123294
123496
  }
123295
123497
  try {
123296
- const applyResult = _internals61.spawnSync("git", ["apply", "--", patchFile], {
123498
+ const applyResult = _internals62.spawnSync("git", ["apply", "--", patchFile], {
123297
123499
  cwd: workingDir,
123298
123500
  timeout: GIT_APPLY_TIMEOUT_MS,
123299
123501
  stdio: "pipe"
@@ -123322,7 +123524,7 @@ async function executeMutation(patch, testCommand, _testFiles, workingDir) {
123322
123524
  }
123323
123525
  let testPassed = false;
123324
123526
  try {
123325
- const spawnResult = _internals61.spawnSync(testCommand[0], testCommand.slice(1), {
123527
+ const spawnResult = _internals62.spawnSync(testCommand[0], testCommand.slice(1), {
123326
123528
  cwd: workingDir,
123327
123529
  timeout: MUTATION_TIMEOUT_MS,
123328
123530
  stdio: "pipe"
@@ -123355,7 +123557,7 @@ async function executeMutation(patch, testCommand, _testFiles, workingDir) {
123355
123557
  } finally {
123356
123558
  if (patchFile) {
123357
123559
  try {
123358
- const revertResult = _internals61.spawnSync("git", ["apply", "-R", "--", patchFile], {
123560
+ const revertResult = _internals62.spawnSync("git", ["apply", "-R", "--", patchFile], {
123359
123561
  cwd: workingDir,
123360
123562
  timeout: GIT_APPLY_TIMEOUT_MS,
123361
123563
  stdio: "pipe"
@@ -123548,7 +123750,7 @@ async function executeMutationSuite(patches, testCommand, testFiles, workingDir,
123548
123750
  }
123549
123751
 
123550
123752
  // src/mutation/gate.ts
123551
- var _internals62 = {
123753
+ var _internals63 = {
123552
123754
  evaluateMutationGate,
123553
123755
  buildTestImprovementPrompt,
123554
123756
  buildMessage
@@ -123569,8 +123771,8 @@ function evaluateMutationGate(report, passThreshold = PASS_THRESHOLD, warnThresh
123569
123771
  } else {
123570
123772
  verdict = "fail";
123571
123773
  }
123572
- const testImprovementPrompt = _internals62.buildTestImprovementPrompt(report, passThreshold, verdict);
123573
- const message = _internals62.buildMessage(verdict, adjustedKillRate, report.killed, report.totalMutants, report.equivalent, warnThreshold);
123774
+ const testImprovementPrompt = _internals63.buildTestImprovementPrompt(report, passThreshold, verdict);
123775
+ const message = _internals63.buildMessage(verdict, adjustedKillRate, report.killed, report.totalMutants, report.equivalent, warnThreshold);
123574
123776
  return {
123575
123777
  verdict,
123576
123778
  killRate: report.killRate,
@@ -124197,7 +124399,7 @@ import * as path152 from "node:path";
124197
124399
  init_bun_compat();
124198
124400
  import * as fs109 from "node:fs";
124199
124401
  import * as path151 from "node:path";
124200
- var _internals63 = { bunSpawn };
124402
+ var _internals64 = { bunSpawn };
124201
124403
  var _swarmGitExcludedChecked = false;
124202
124404
  function fileCoversSwarm(content) {
124203
124405
  for (const rawLine of content.split(`
@@ -124230,7 +124432,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
124230
124432
  checkIgnoreExitCode
124231
124433
  ] = await Promise.all([
124232
124434
  (async () => {
124233
- const proc = _internals63.bunSpawn(["git", "-C", directory, "rev-parse", "--show-toplevel"], GIT_SPAWN_OPTIONS);
124435
+ const proc = _internals64.bunSpawn(["git", "-C", directory, "rev-parse", "--show-toplevel"], GIT_SPAWN_OPTIONS);
124234
124436
  try {
124235
124437
  return await Promise.all([proc.exited, proc.stdout.text()]);
124236
124438
  } finally {
@@ -124240,7 +124442,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
124240
124442
  }
124241
124443
  })(),
124242
124444
  (async () => {
124243
- const proc = _internals63.bunSpawn(["git", "-C", directory, "rev-parse", "--git-path", "info/exclude"], GIT_SPAWN_OPTIONS);
124445
+ const proc = _internals64.bunSpawn(["git", "-C", directory, "rev-parse", "--git-path", "info/exclude"], GIT_SPAWN_OPTIONS);
124244
124446
  try {
124245
124447
  return await Promise.all([proc.exited, proc.stdout.text()]);
124246
124448
  } finally {
@@ -124250,7 +124452,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
124250
124452
  }
124251
124453
  })(),
124252
124454
  (async () => {
124253
- const proc = _internals63.bunSpawn(["git", "-C", directory, "check-ignore", "-q", ".swarm/.gitkeep"], GIT_SPAWN_OPTIONS);
124455
+ const proc = _internals64.bunSpawn(["git", "-C", directory, "check-ignore", "-q", ".swarm/.gitkeep"], GIT_SPAWN_OPTIONS);
124254
124456
  try {
124255
124457
  return await proc.exited;
124256
124458
  } finally {
@@ -124289,7 +124491,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
124289
124491
  }
124290
124492
  } catch {}
124291
124493
  }
124292
- const trackedProc = _internals63.bunSpawn(["git", "-C", directory, "ls-files", "--", ".swarm"], GIT_SPAWN_OPTIONS);
124494
+ const trackedProc = _internals64.bunSpawn(["git", "-C", directory, "ls-files", "--", ".swarm"], GIT_SPAWN_OPTIONS);
124293
124495
  let trackedExitCode;
124294
124496
  let trackedOutput;
124295
124497
  try {
@@ -124314,7 +124516,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
124314
124516
  }
124315
124517
 
124316
124518
  // src/hooks/diff-scope.ts
124317
- var _internals64 = { bunSpawn };
124519
+ var _internals65 = { bunSpawn };
124318
124520
  function getDeclaredScope(taskId, directory) {
124319
124521
  try {
124320
124522
  const planPath = path152.join(directory, ".swarm", "plan.json");
@@ -124349,7 +124551,7 @@ var GIT_DIFF_SPAWN_OPTIONS = {
124349
124551
  };
124350
124552
  async function getChangedFiles(directory) {
124351
124553
  try {
124352
- const proc = _internals64.bunSpawn(["git", "diff", "--name-only", "HEAD~1"], {
124554
+ const proc = _internals65.bunSpawn(["git", "diff", "--name-only", "HEAD~1"], {
124353
124555
  cwd: directory,
124354
124556
  ...GIT_DIFF_SPAWN_OPTIONS
124355
124557
  });
@@ -124366,7 +124568,7 @@ async function getChangedFiles(directory) {
124366
124568
  return stdout.trim().split(`
124367
124569
  `).map((f) => f.trim()).filter((f) => f.length > 0);
124368
124570
  }
124369
- const proc2 = _internals64.bunSpawn(["git", "diff", "--name-only", "HEAD"], {
124571
+ const proc2 = _internals65.bunSpawn(["git", "diff", "--name-only", "HEAD"], {
124370
124572
  cwd: directory,
124371
124573
  ...GIT_DIFF_SPAWN_OPTIONS
124372
124574
  });
@@ -124424,7 +124626,7 @@ init_telemetry();
124424
124626
  init_file_locks();
124425
124627
  import * as fs111 from "node:fs";
124426
124628
  import * as path153 from "node:path";
124427
- var _internals65 = {
124629
+ var _internals66 = {
124428
124630
  listActiveLocks,
124429
124631
  verifyLeanTurboTaskCompletion
124430
124632
  };
@@ -124566,7 +124768,7 @@ function verifyLeanTurboTaskCompletion(directory, taskId, sessionID) {
124566
124768
  }
124567
124769
  };
124568
124770
  }
124569
- const activeLocks = _internals65.listActiveLocks(directory);
124771
+ const activeLocks = _internals66.listActiveLocks(directory);
124570
124772
  const laneLocks = activeLocks.filter((lock) => lock.laneId === lane.laneId);
124571
124773
  if (laneLocks.length > 0) {
124572
124774
  return {
@@ -125495,7 +125697,7 @@ var web_search = createSwarmTool({
125495
125697
  });
125496
125698
  async function captureSearchEvidence(directory, query, results) {
125497
125699
  try {
125498
- const written = await _internals66.writeEvidenceDocuments(directory, results.map((result) => ({
125700
+ const written = await _internals67.writeEvidenceDocuments(directory, results.map((result) => ({
125499
125701
  sourceType: "web_search",
125500
125702
  query,
125501
125703
  title: result.title,
@@ -125523,7 +125725,7 @@ async function captureSearchEvidence(directory, query, results) {
125523
125725
  };
125524
125726
  }
125525
125727
  }
125526
- var _internals66 = {
125728
+ var _internals67 = {
125527
125729
  writeEvidenceDocuments
125528
125730
  };
125529
125731
  // src/tools/write-drift-evidence.ts