opencode-swarm 7.46.1 → 7.46.3

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.3",
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
  }
@@ -90498,7 +90663,7 @@ __export(exports_runtime, {
90498
90663
  getSupportedLanguages: () => getSupportedLanguages,
90499
90664
  getInitializedLanguages: () => getInitializedLanguages,
90500
90665
  clearParserCache: () => clearParserCache,
90501
- _internals: () => _internals43
90666
+ _internals: () => _internals45
90502
90667
  });
90503
90668
  import * as path93 from "node:path";
90504
90669
  import { fileURLToPath as fileURLToPath3 } from "node:url";
@@ -90508,10 +90673,10 @@ async function initTreeSitter() {
90508
90673
  const thisDir = path93.dirname(fileURLToPath3(import.meta.url));
90509
90674
  const isSource = thisDir.replace(/\\/g, "/").endsWith("/src/lang");
90510
90675
  if (isSource) {
90511
- await _internals43.parserInit();
90676
+ await _internals45.parserInit();
90512
90677
  } else {
90513
90678
  const grammarsDir = getGrammarsDirAbsolute();
90514
- await _internals43.parserInit({
90679
+ await _internals45.parserInit({
90515
90680
  locateFile(scriptName) {
90516
90681
  return path93.join(grammarsDir, scriptName);
90517
90682
  }
@@ -90613,12 +90778,12 @@ function getInitializedLanguages() {
90613
90778
  function getSupportedLanguages() {
90614
90779
  return Object.keys(LANGUAGE_WASM_MAP);
90615
90780
  }
90616
- var parserCache, initializedLanguages, treeSitterInitPromise = null, _internals43, LANGUAGE_WASM_MAP;
90781
+ var parserCache, initializedLanguages, treeSitterInitPromise = null, _internals45, LANGUAGE_WASM_MAP;
90617
90782
  var init_runtime = __esm(() => {
90618
90783
  init_tree_sitter();
90619
90784
  parserCache = new Map;
90620
90785
  initializedLanguages = new Set;
90621
- _internals43 = {
90786
+ _internals45 = {
90622
90787
  parserInit: Parser.init
90623
90788
  };
90624
90789
  LANGUAGE_WASM_MAP = {
@@ -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;
@@ -91498,9 +91670,9 @@ var init_search_knowledge = __esm(() => {
91498
91670
  var exports_knowledge_recall = {};
91499
91671
  __export(exports_knowledge_recall, {
91500
91672
  knowledge_recall: () => knowledge_recall,
91501
- _internals: () => _internals44
91673
+ _internals: () => _internals46
91502
91674
  });
91503
- var knowledge_recall, _internals44;
91675
+ var knowledge_recall, _internals46;
91504
91676
  var init_knowledge_recall = __esm(() => {
91505
91677
  init_zod();
91506
91678
  init_config();
@@ -91581,7 +91753,7 @@ var init_knowledge_recall = __esm(() => {
91581
91753
  return JSON.stringify(result);
91582
91754
  }
91583
91755
  });
91584
- _internals44 = {
91756
+ _internals46 = {
91585
91757
  knowledge_recall
91586
91758
  };
91587
91759
  });
@@ -91636,7 +91808,7 @@ __export(exports_curator_drift, {
91636
91808
  runDeterministicDriftCheck: () => runDeterministicDriftCheck,
91637
91809
  readPriorDriftReports: () => readPriorDriftReports,
91638
91810
  buildDriftInjectionText: () => buildDriftInjectionText,
91639
- _internals: () => _internals47
91811
+ _internals: () => _internals49
91640
91812
  });
91641
91813
  import * as fs65 from "node:fs";
91642
91814
  import * as path102 from "node:path";
@@ -91685,7 +91857,7 @@ async function runDeterministicDriftCheck(directory, phase, curatorResult, confi
91685
91857
  try {
91686
91858
  const planMd = await readSwarmFileAsync(directory, "plan.md");
91687
91859
  const specMd = await readSwarmFileAsync(directory, "spec.md");
91688
- const priorReports = await _internals47.readPriorDriftReports(directory);
91860
+ const priorReports = await _internals49.readPriorDriftReports(directory);
91689
91861
  const complianceCount = curatorResult.compliance.length;
91690
91862
  const warningCompliance = curatorResult.compliance.filter((obs) => obs.severity === "warning");
91691
91863
  let alignment = "ALIGNED";
@@ -91748,7 +91920,7 @@ async function runDeterministicDriftCheck(directory, phase, curatorResult, confi
91748
91920
  scope_additions: [],
91749
91921
  injection_summary: injectionSummary
91750
91922
  };
91751
- const reportPath = await _internals47.writeDriftReport(directory, report);
91923
+ const reportPath = await _internals49.writeDriftReport(directory, report);
91752
91924
  getGlobalEventBus().publish("curator.drift.completed", {
91753
91925
  phase,
91754
91926
  alignment,
@@ -91811,12 +91983,12 @@ function buildDriftInjectionText(report, maxChars) {
91811
91983
  }
91812
91984
  return text.slice(0, maxChars);
91813
91985
  }
91814
- var DRIFT_REPORT_PREFIX = "drift-report-phase-", _internals47;
91986
+ var DRIFT_REPORT_PREFIX = "drift-report-phase-", _internals49;
91815
91987
  var init_curator_drift = __esm(() => {
91816
91988
  init_event_bus();
91817
91989
  init_logger();
91818
91990
  init_utils2();
91819
- _internals47 = {
91991
+ _internals49 = {
91820
91992
  readPriorDriftReports,
91821
91993
  writeDriftReport,
91822
91994
  runDeterministicDriftCheck,
@@ -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: () => _internals70,
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 _internals70.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 = _internals70.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, _internals70;
91953
92125
  var init_project_context = __esm(() => {
91954
92126
  init_dispatch();
91955
- _internals67 = {
92127
+ _internals70 = {
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",
@@ -94683,14 +94855,13 @@ ${originalText}`;
94683
94855
  }
94684
94856
  // src/hooks/repo-graph-builder.ts
94685
94857
  init_constants();
94686
- import { realpathSync as realpathSync11 } from "node:fs";
94687
94858
  import * as path86 from "node:path";
94688
94859
 
94689
94860
  // src/tools/repo-graph/builder.ts
94690
94861
  init_logger();
94691
94862
  init_path_security();
94692
94863
  import * as fsSync4 from "node:fs";
94693
- import { existsSync as existsSync48, realpathSync as realpathSync9 } from "node:fs";
94864
+ import { existsSync as existsSync48, realpathSync as realpathSync10 } from "node:fs";
94694
94865
  import * as fsPromises5 from "node:fs/promises";
94695
94866
  import * as os13 from "node:os";
94696
94867
  import * as path82 from "node:path";
@@ -95053,6 +95224,19 @@ var symbols = createSwarmTool({
95053
95224
  }
95054
95225
  });
95055
95226
 
95227
+ // src/tools/repo-graph/safe-realpath.ts
95228
+ import { realpathSync as realpathSync9 } from "node:fs";
95229
+ function safeRealpathSync(targetPath, fallback, realpathResolver = realpathSync9) {
95230
+ try {
95231
+ return realpathResolver(targetPath);
95232
+ } catch (error93) {
95233
+ if (error93 instanceof Error && error93.code === "ENOENT") {
95234
+ return fallback;
95235
+ }
95236
+ return null;
95237
+ }
95238
+ }
95239
+
95056
95240
  // src/tools/repo-graph/types.ts
95057
95241
  import * as path81 from "node:path";
95058
95242
  var REPO_GRAPH_FILENAME = "repo-graph.json";
@@ -95174,6 +95358,9 @@ function validateGraphEdge(edge) {
95174
95358
  }
95175
95359
 
95176
95360
  // src/tools/repo-graph/builder.ts
95361
+ var _internals43 = {
95362
+ safeRealpathSync
95363
+ };
95177
95364
  var SKIP_DIRECTORIES2 = new Set([
95178
95365
  "node_modules",
95179
95366
  ".git",
@@ -95240,17 +95427,14 @@ function resolveModuleSpecifier(workspaceRoot, sourceFile, specifier) {
95240
95427
  if (specifier.startsWith(".")) {
95241
95428
  const sourceDir = path82.dirname(sourceFile);
95242
95429
  let resolved = path82.resolve(sourceDir, specifier);
95243
- let realResolved;
95244
- try {
95245
- realResolved = realpathSync9(resolved);
95246
- } catch {
95247
- realResolved = resolved;
95430
+ const initialRealResolved = _internals43.safeRealpathSync(resolved, resolved);
95431
+ if (initialRealResolved === null) {
95432
+ return null;
95248
95433
  }
95249
- let realRoot;
95250
- try {
95251
- realRoot = realpathSync9(workspaceRoot);
95252
- } catch {
95253
- realRoot = path82.normalize(workspaceRoot);
95434
+ let realResolved = initialRealResolved;
95435
+ const realRoot = _internals43.safeRealpathSync(workspaceRoot, path82.normalize(workspaceRoot));
95436
+ if (realRoot === null) {
95437
+ return null;
95254
95438
  }
95255
95439
  if (!existsSync48(resolved)) {
95256
95440
  const EXTENSIONS = [
@@ -95272,11 +95456,11 @@ function resolveModuleSpecifier(workspaceRoot, sourceFile, specifier) {
95272
95456
  }
95273
95457
  }
95274
95458
  if (found) {
95275
- try {
95276
- realResolved = realpathSync9(found);
95277
- } catch {
95278
- realResolved = found;
95459
+ const foundRealPath = _internals43.safeRealpathSync(found, found);
95460
+ if (foundRealPath === null) {
95461
+ return null;
95279
95462
  }
95463
+ realResolved = foundRealPath;
95280
95464
  resolved = found;
95281
95465
  } else {
95282
95466
  return null;
@@ -95297,7 +95481,7 @@ function resolveModuleSpecifier(workspaceRoot, sourceFile, specifier) {
95297
95481
  function isRefusedWorkspaceRoot(target) {
95298
95482
  let resolved;
95299
95483
  try {
95300
- resolved = realpathSync9(target);
95484
+ resolved = realpathSync10(target);
95301
95485
  } catch {
95302
95486
  resolved = path82.resolve(target);
95303
95487
  }
@@ -95605,9 +95789,12 @@ import * as path85 from "node:path";
95605
95789
  init_utils2();
95606
95790
  init_logger();
95607
95791
  init_path_security();
95608
- import { constants as constants4, existsSync as existsSync49, realpathSync as realpathSync10 } from "node:fs";
95792
+ import { constants as constants4, existsSync as existsSync49 } from "node:fs";
95609
95793
  import * as fsPromises6 from "node:fs/promises";
95610
95794
  import * as path84 from "node:path";
95795
+ var _internals44 = {
95796
+ safeRealpathSync
95797
+ };
95611
95798
  var WINDOWS_RENAME_MAX_RETRIES2 = 3;
95612
95799
  var WINDOWS_RENAME_RETRY_DELAY_MS2 = 50;
95613
95800
  function getGraphPath(workspace) {
@@ -95713,18 +95900,14 @@ async function saveGraph(workspace, graph, options) {
95713
95900
  throw new Error("Graph must have edges array");
95714
95901
  }
95715
95902
  const normalizedWorkspace = path84.normalize(workspace);
95716
- let realWorkspace;
95717
- try {
95718
- realWorkspace = realpathSync10(workspace);
95719
- } catch {
95720
- realWorkspace = normalizedWorkspace;
95903
+ const realWorkspace = _internals44.safeRealpathSync(workspace, normalizedWorkspace);
95904
+ if (realWorkspace === null) {
95905
+ throw new Error(`Workspace realpath security check failed (non-ENOENT): ${workspace}`);
95721
95906
  }
95722
95907
  const normalizedGraphRoot = path84.normalize(graph.workspaceRoot);
95723
- let realGraphRoot;
95724
- try {
95725
- realGraphRoot = realpathSync10(graph.workspaceRoot);
95726
- } catch {
95727
- realGraphRoot = normalizedGraphRoot;
95908
+ const realGraphRoot = _internals44.safeRealpathSync(graph.workspaceRoot, normalizedGraphRoot);
95909
+ if (realGraphRoot === null) {
95910
+ throw new Error(`Graph workspaceRoot realpath security check failed (non-ENOENT): ${graph.workspaceRoot}`);
95728
95911
  }
95729
95912
  if (path84.normalize(realWorkspace) !== path84.normalize(realGraphRoot)) {
95730
95913
  throw new Error(`Graph workspaceRoot mismatch: graph was built for "${graph.workspaceRoot}" but save was called for "${workspace}"`);
@@ -95900,6 +96083,7 @@ function createRepoGraphBuilderHook(workspaceRoot, deps) {
95900
96083
  const _buildWorkspaceGraph = deps?.buildWorkspaceGraph ?? buildWorkspaceGraphAsync;
95901
96084
  const _saveGraph = deps?.saveGraph ?? saveGraph;
95902
96085
  const _updateGraphForFiles = deps?.updateGraphForFiles ?? updateGraphForFiles;
96086
+ const _safeRealpathSync = deps?.safeRealpathSync ?? safeRealpathSync;
95903
96087
  let initStarted = false;
95904
96088
  let initPromise = Promise.resolve();
95905
96089
  let consecutiveFailures = 0;
@@ -95940,23 +96124,13 @@ function createRepoGraphBuilderHook(workspaceRoot, deps) {
95940
96124
  if (!isSupportedSourceFile(filePath))
95941
96125
  return;
95942
96126
  const absoluteFilePath = path86.isAbsolute(filePath) ? filePath : path86.resolve(workspaceRoot, filePath);
95943
- let realFilePath;
95944
- try {
95945
- realFilePath = realpathSync11(absoluteFilePath);
95946
- } catch (error93) {
95947
- if (!(error93 instanceof Error) || error93.code !== "ENOENT") {
95948
- return;
95949
- }
95950
- realFilePath = absoluteFilePath;
96127
+ const realFilePath = _safeRealpathSync(absoluteFilePath, absoluteFilePath);
96128
+ if (realFilePath === null) {
96129
+ return;
95951
96130
  }
95952
- let realWorkspace;
95953
- try {
95954
- realWorkspace = realpathSync11(workspaceRoot);
95955
- } catch (error93) {
95956
- if (!(error93 instanceof Error) || error93.code !== "ENOENT") {
95957
- return;
95958
- }
95959
- realWorkspace = workspaceRoot;
96131
+ const realWorkspace = _safeRealpathSync(workspaceRoot, workspaceRoot);
96132
+ if (realWorkspace === null) {
96133
+ return;
95960
96134
  }
95961
96135
  const normalizedAbsolute = realFilePath.replace(/\\/g, "/");
95962
96136
  const normalizedWorkspace = realWorkspace.replace(/\\/g, "/");
@@ -102044,7 +102218,7 @@ import * as path101 from "node:path";
102044
102218
  // src/hooks/knowledge-application.ts
102045
102219
  init_logger();
102046
102220
  init_knowledge_store();
102047
- var import_proper_lockfile7 = __toESM(require_proper_lockfile(), 1);
102221
+ var import_proper_lockfile8 = __toESM(require_proper_lockfile(), 1);
102048
102222
  import { existsSync as existsSync56 } from "node:fs";
102049
102223
  import { appendFile as appendFile9, mkdir as mkdir18, readFile as readFile18 } from "node:fs/promises";
102050
102224
  import * as path100 from "node:path";
@@ -102205,7 +102379,7 @@ async function knowledgeApplicationGateBefore(directory, input, config3) {
102205
102379
  if (config3.mode === "enforce") {
102206
102380
  throw new Error("KNOWLEDGE_ENFORCE_GATE_DENY: missing sessionID on tool.execute.before; refusing to evaluate critical-directive ack state");
102207
102381
  }
102208
- _internals45.writeWarnEvent(directory, {
102382
+ _internals47.writeWarnEvent(directory, {
102209
102383
  timestamp: new Date().toISOString(),
102210
102384
  event: "knowledge_application_gate_warn",
102211
102385
  tool: toolName,
@@ -102288,7 +102462,7 @@ async function knowledgeApplicationTransformScan(directory, output, sessionID) {
102288
102462
  }
102289
102463
  }
102290
102464
  }
102291
- var _internals45 = {
102465
+ var _internals47 = {
102292
102466
  knowledgeApplicationGateBefore,
102293
102467
  knowledgeApplicationTransformScan,
102294
102468
  HIGH_RISK_TOOLS,
@@ -102412,10 +102586,10 @@ async function getRunMemorySummary(directory) {
102412
102586
  if (entries.length === 0) {
102413
102587
  return null;
102414
102588
  }
102415
- const groups = _internals46.groupByTaskId(entries);
102589
+ const groups = _internals48.groupByTaskId(entries);
102416
102590
  const summaries = [];
102417
102591
  for (const [taskId, taskEntries] of groups) {
102418
- const summary = _internals46.summarizeTask(taskId, taskEntries);
102592
+ const summary = _internals48.summarizeTask(taskId, taskEntries);
102419
102593
  if (summary) {
102420
102594
  summaries.push(summary);
102421
102595
  }
@@ -102448,7 +102622,7 @@ Use this data to avoid repeating known failure patterns.`;
102448
102622
  }
102449
102623
  return prefix + summaryText + suffix;
102450
102624
  }
102451
- var _internals46 = {
102625
+ var _internals48 = {
102452
102626
  generateTaskFingerprint,
102453
102627
  recordOutcome,
102454
102628
  getTaskHistory,
@@ -102463,10 +102637,12 @@ init_state();
102463
102637
  init_logger();
102464
102638
  init_curator_drift();
102465
102639
  init_extractors();
102640
+ init_knowledge_events();
102466
102641
  init_knowledge_store();
102467
102642
  init_search_knowledge();
102468
102643
  init_utils2();
102469
102644
  var INJECTION_SENTINEL = "‌[[KNOWLEDGE-INJECTED]]";
102645
+ var defaultSearchKnowledge = searchKnowledge;
102470
102646
  function buildKnowledgeBlock(entries, charBudget, cfg, currentProject) {
102471
102647
  if (entries.length === 0)
102472
102648
  return null;
@@ -102644,13 +102820,15 @@ function createKnowledgeInjectorHook(directory, config3) {
102644
102820
  projectName,
102645
102821
  currentPhase: phaseDescription
102646
102822
  };
102647
- const search = await searchKnowledge({
102823
+ const searchFn = _internals50.searchKnowledge === defaultSearchKnowledge ? searchKnowledge : _internals50.searchKnowledge;
102824
+ const search = await searchFn({
102648
102825
  directory,
102649
102826
  config: config3,
102650
102827
  context: retrievalCtx,
102651
102828
  mode: "auto_injection",
102652
102829
  agent: "architect",
102653
- sessionId: systemMsg?.info?.sessionID
102830
+ sessionId: systemMsg?.info?.sessionID,
102831
+ emitEvent: false
102654
102832
  });
102655
102833
  const entries = search.results;
102656
102834
  const filteredEntries = filterHighConfidenceKnowledge(entries);
@@ -102743,7 +102921,27 @@ ${freshPreamble}` : `<curator_briefing>${truncatedBriefing}</curator_briefing>`;
102743
102921
  }
102744
102922
  if (cachedShownIds.length > 0) {
102745
102923
  const phaseLabel = `Phase ${currentPhase}`;
102746
- recordKnowledgeShown(directory, cachedShownIds, {
102924
+ const scoreById = new Map(entries.map((e) => [e.id, e.finalScore]));
102925
+ const ranks = {};
102926
+ const scores = {};
102927
+ cachedShownIds.forEach((id, idx) => {
102928
+ ranks[id] = idx + 1;
102929
+ scores[id] = scoreById.get(id) ?? 0;
102930
+ });
102931
+ await _internals50.recordKnowledgeEvent(directory, {
102932
+ type: "retrieved",
102933
+ trace_id: search.trace_id,
102934
+ session_id: systemMsg?.info?.sessionID ?? "unknown",
102935
+ phase: retrievalCtx.currentPhase,
102936
+ task_id: retrievalCtx.taskId,
102937
+ agent: "architect",
102938
+ query: retrievalCtx.lastUserMessage ?? retrievalCtx.currentPhase ?? "",
102939
+ retrieval_mode: "auto_injection",
102940
+ result_ids: cachedShownIds,
102941
+ ranks,
102942
+ scores
102943
+ });
102944
+ _internals50.recordKnowledgeShown(directory, cachedShownIds, {
102747
102945
  phase: phaseLabel,
102748
102946
  tool: retrievalCtx.currentTool,
102749
102947
  action: retrievalCtx.currentAction,
@@ -102753,6 +102951,11 @@ ${freshPreamble}` : `<curator_briefing>${truncatedBriefing}</curator_briefing>`;
102753
102951
  }
102754
102952
  });
102755
102953
  }
102954
+ var _internals50 = {
102955
+ searchKnowledge,
102956
+ recordKnowledgeEvent,
102957
+ recordKnowledgeShown
102958
+ };
102756
102959
 
102757
102960
  // src/index.ts
102758
102961
  init_normalize_tool_name();
@@ -102896,7 +103099,7 @@ var TASK_DIVERSITY_WEIGHT = 0.05;
102896
103099
  var CONTEXT_WEIGHT = 0.2;
102897
103100
  var RECENCY_DECAY_MS = 30 * 24 * 60 * 60 * 1000;
102898
103101
  var SKILL_FRONTMATTER_READ_BYTES = 16 * 1024;
102899
- var _internals48 = {
103102
+ var _internals51 = {
102900
103103
  computeSkillRelevanceScore: null,
102901
103104
  rankSkillsForContext: null,
102902
103105
  getSkillStats: null,
@@ -103115,7 +103318,7 @@ function formatSkillIndexWithContext(skills, directory) {
103115
103318
  } catch {}
103116
103319
  if (!hasHistory) {
103117
103320
  return skills.map((sp) => {
103118
- const meta3 = _internals48.readSkillMetadata(sp, directory);
103321
+ const meta3 = _internals51.readSkillMetadata(sp, directory);
103119
103322
  return ` - file:${meta3.path} - ${meta3.name}: ${meta3.description}`;
103120
103323
  }).join(`
103121
103324
  `);
@@ -103123,7 +103326,7 @@ function formatSkillIndexWithContext(skills, directory) {
103123
103326
  const lines = [];
103124
103327
  for (const skillPath of skills) {
103125
103328
  const stats = getSkillStats(skillPath, directory);
103126
- const meta3 = _internals48.readSkillMetadata(skillPath, directory);
103329
+ const meta3 = _internals51.readSkillMetadata(skillPath, directory);
103127
103330
  const compliancePct = Math.round(stats.complianceRate * 100);
103128
103331
  const topAgentNames = stats.topAgents.slice(0, 3).map((a) => a.agent).join(", ");
103129
103332
  lines.push(` - file:${meta3.path} - ${meta3.name}: ${meta3.description} (used: ${stats.totalUsage}, compliance: ${compliancePct}%)` + (stats.topAgents.length > 0 ? ` → ${topAgentNames}` : ""));
@@ -103131,15 +103334,15 @@ function formatSkillIndexWithContext(skills, directory) {
103131
103334
  return lines.join(`
103132
103335
  `);
103133
103336
  }
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;
103337
+ _internals51.computeSkillRelevanceScore = computeSkillRelevanceScore;
103338
+ _internals51.rankSkillsForContext = rankSkillsForContext;
103339
+ _internals51.getSkillStats = getSkillStats;
103340
+ _internals51.formatSkillIndexWithContext = formatSkillIndexWithContext;
103341
+ _internals51.parseSkillFrontmatter = parseSkillFrontmatter;
103342
+ _internals51.readSkillMetadata = readSkillMetadata;
103343
+ _internals51.extractSkillName = extractSkillName;
103344
+ _internals51.computeRecencyScore = computeRecencyScore;
103345
+ _internals51.computeContextMatchScore = computeContextMatchScore;
103143
103346
 
103144
103347
  // src/hooks/skill-propagation-gate.ts
103145
103348
  init_skill_usage_log();
@@ -103242,10 +103445,10 @@ function parseYamlValue(value) {
103242
103445
  }
103243
103446
  function loadRoutingSkills(directory, targetAgent) {
103244
103447
  const routingPath = path105.join(directory, ".opencode", "skill-routing.yaml");
103245
- if (!_internals49.existsSync(routingPath))
103448
+ if (!_internals52.existsSync(routingPath))
103246
103449
  return [];
103247
103450
  try {
103248
- const content = _internals49.readFileSync(routingPath, "utf-8");
103451
+ const content = _internals52.readFileSync(routingPath, "utf-8");
103249
103452
  const config3 = parseSimpleYaml(content);
103250
103453
  if (!config3?.routing)
103251
103454
  return [];
@@ -103272,7 +103475,7 @@ var SKILL_SEARCH_ROOTS = [
103272
103475
  ".claude/skills"
103273
103476
  ];
103274
103477
  var MAX_SCORING_SESSION_ENTRIES = 500;
103275
- var _internals49 = {
103478
+ var _internals52 = {
103276
103479
  readdirSync: fs67.readdirSync.bind(fs67),
103277
103480
  existsSync: fs67.existsSync.bind(fs67),
103278
103481
  statSync: fs67.statSync.bind(fs67),
@@ -103301,11 +103504,11 @@ function discoverAvailableSkills(directory) {
103301
103504
  const results = [];
103302
103505
  for (const root of SKILL_SEARCH_ROOTS) {
103303
103506
  const rootPath = path105.join(directory, root);
103304
- if (!_internals49.existsSync(rootPath))
103507
+ if (!_internals52.existsSync(rootPath))
103305
103508
  continue;
103306
103509
  let entries;
103307
103510
  try {
103308
- entries = _internals49.readdirSync(rootPath);
103511
+ entries = _internals52.readdirSync(rootPath);
103309
103512
  } catch {
103310
103513
  continue;
103311
103514
  }
@@ -103313,11 +103516,11 @@ function discoverAvailableSkills(directory) {
103313
103516
  if (entry.startsWith("."))
103314
103517
  continue;
103315
103518
  const skillDir = path105.join(rootPath, entry);
103316
- if (_internals49.existsSync(path105.join(skillDir, "retired.marker")))
103519
+ if (_internals52.existsSync(path105.join(skillDir, "retired.marker")))
103317
103520
  continue;
103318
103521
  const skillFile = path105.join(skillDir, "SKILL.md");
103319
103522
  try {
103320
- if (_internals49.statSync(skillDir).isDirectory() && _internals49.existsSync(skillFile)) {
103523
+ if (_internals52.statSync(skillDir).isDirectory() && _internals52.existsSync(skillFile)) {
103321
103524
  results.push(path105.join(root, entry, "SKILL.md").replace(/\\/g, "/"));
103322
103525
  }
103323
103526
  } catch (err2) {
@@ -103349,7 +103552,7 @@ function parseDelegationArgs(args2) {
103349
103552
  }
103350
103553
  if (!targetAgent)
103351
103554
  return null;
103352
- const skillsField = prompt ? _internals49.extractSkillsFieldFromPrompt(prompt) : "";
103555
+ const skillsField = prompt ? _internals52.extractSkillsFieldFromPrompt(prompt) : "";
103353
103556
  return { targetAgent, skillsField };
103354
103557
  }
103355
103558
  function extractSkillsFieldFromPrompt(prompt) {
@@ -103390,10 +103593,10 @@ function writeWarnEvent2(directory, record3) {
103390
103593
  const filePath = path105.join(directory, ".swarm", "events.jsonl");
103391
103594
  try {
103392
103595
  const dir = path105.dirname(filePath);
103393
- if (!_internals49.existsSync(dir)) {
103394
- _internals49.mkdirSync(dir, { recursive: true });
103596
+ if (!_internals52.existsSync(dir)) {
103597
+ _internals52.mkdirSync(dir, { recursive: true });
103395
103598
  }
103396
- _internals49.appendFileSync(filePath, `${JSON.stringify(record3)}
103599
+ _internals52.appendFileSync(filePath, `${JSON.stringify(record3)}
103397
103600
  `, "utf-8");
103398
103601
  } catch (err2) {
103399
103602
  warn(`[skill-propagation-gate] failed to write warning event: ${err2 instanceof Error ? err2.message : String(err2)}`);
@@ -103444,19 +103647,19 @@ async function skillPropagationGateBefore(directory, input, config3) {
103444
103647
  const baseAgent = stripKnownSwarmPrefix(agentRaw);
103445
103648
  if (baseAgent !== "architect")
103446
103649
  return { blocked: false, reason: null, recommendedSkills: undefined };
103447
- const parsed = _internals49.parseDelegationArgs(input.args);
103650
+ const parsed = _internals52.parseDelegationArgs(input.args);
103448
103651
  if (!parsed)
103449
103652
  return { blocked: false, reason: null, recommendedSkills: undefined };
103450
103653
  const targetBase = stripKnownSwarmPrefix(parsed.targetAgent);
103451
- if (!_internals49.SKILL_CAPABLE_AGENTS.has(targetBase))
103654
+ if (!_internals52.SKILL_CAPABLE_AGENTS.has(targetBase))
103452
103655
  return { blocked: false, reason: null, recommendedSkills: undefined };
103453
103656
  const sessionID = typeof input.sessionID === "string" ? input.sessionID : "unknown";
103454
- const availableSkills = _internals49.discoverAvailableSkills(directory);
103657
+ const availableSkills = _internals52.discoverAvailableSkills(directory);
103455
103658
  const skillsValue = parsed.skillsField.trim();
103456
103659
  if (skillsValue && skillsValue.toLowerCase() !== "none") {
103457
103660
  const prompt = typeof input.args?.prompt === "string" ? String(input.args.prompt) : "";
103458
- const taskId = _internals49.extractTaskIdFromPrompt(prompt);
103459
- const skillPaths = _internals49.parseSkillPaths(skillsValue);
103661
+ const taskId = _internals52.extractTaskIdFromPrompt(prompt);
103662
+ const skillPaths = _internals52.parseSkillPaths(skillsValue);
103460
103663
  let coderSkillPaths = [];
103461
103664
  if (prompt) {
103462
103665
  for (const line of prompt.split(`
@@ -103464,7 +103667,7 @@ async function skillPropagationGateBefore(directory, input, config3) {
103464
103667
  const trimmed = line.trim();
103465
103668
  if (trimmed.startsWith("SKILLS_USED_BY_CODER:")) {
103466
103669
  const fieldVal = trimmed.slice("SKILLS_USED_BY_CODER:".length).trim();
103467
- coderSkillPaths = _internals49.parseSkillPaths(fieldVal);
103670
+ coderSkillPaths = _internals52.parseSkillPaths(fieldVal);
103468
103671
  break;
103469
103672
  }
103470
103673
  }
@@ -103472,7 +103675,7 @@ async function skillPropagationGateBefore(directory, input, config3) {
103472
103675
  const allPaths = [...new Set([...skillPaths, ...coderSkillPaths])];
103473
103676
  for (const skillPath of allPaths) {
103474
103677
  try {
103475
- _internals49.appendSkillUsageEntry(directory, {
103678
+ _internals52.appendSkillUsageEntry(directory, {
103476
103679
  skillPath,
103477
103680
  agentName: targetBase,
103478
103681
  taskID: taskId,
@@ -103489,17 +103692,17 @@ async function skillPropagationGateBefore(directory, input, config3) {
103489
103692
  let scored = [];
103490
103693
  if (skillsValue && skillsValue.toLowerCase() !== "none" && availableSkills.length > 0) {
103491
103694
  try {
103492
- const sessionEntries = _internals49.readSkillUsageEntriesTail(directory, {
103695
+ const sessionEntries = _internals52.readSkillUsageEntriesTail(directory, {
103493
103696
  sessionID
103494
103697
  });
103495
- if (sessionEntries.length > _internals49.MAX_SCORING_SESSION_ENTRIES) {
103698
+ if (sessionEntries.length > _internals52.MAX_SCORING_SESSION_ENTRIES) {
103496
103699
  scoringSkipped = true;
103497
- warn(`[skill-propagation-gate] skipping scoring — session has ${sessionEntries.length} entries (limit: ${_internals49.MAX_SCORING_SESSION_ENTRIES})`);
103700
+ warn(`[skill-propagation-gate] skipping scoring — session has ${sessionEntries.length} entries (limit: ${_internals52.MAX_SCORING_SESSION_ENTRIES})`);
103498
103701
  } else {
103499
103702
  const prompt = typeof input.args?.prompt === "string" ? String(input.args.prompt) : "";
103500
103703
  scored = availableSkills.map((skillPath) => {
103501
103704
  const skillEntries = sessionEntries.filter((e) => e.skillPath === skillPath);
103502
- const score = _internals49.computeSkillRelevanceScore(skillPath, prompt, skillEntries);
103705
+ const score = _internals52.computeSkillRelevanceScore(skillPath, prompt, skillEntries);
103503
103706
  return { skillPath, score, usageCount: skillEntries.length };
103504
103707
  }).sort((a, b) => b.score - a.score || b.usageCount - a.usageCount);
103505
103708
  if (scored.length > 0) {
@@ -103513,12 +103716,12 @@ async function skillPropagationGateBefore(directory, input, config3) {
103513
103716
  }
103514
103717
  }
103515
103718
  try {
103516
- const routingPaths = _internals49.loadRoutingSkills(directory, targetBase);
103719
+ const routingPaths = _internals52.loadRoutingSkills(directory, targetBase);
103517
103720
  if (routingPaths.length > 0) {
103518
103721
  const existingPaths = new Set(scored.map((s) => s.skillPath));
103519
103722
  for (const routingPath of routingPaths) {
103520
103723
  const routedSkillDir = path105.dirname(path105.join(directory, routingPath));
103521
- if (_internals49.existsSync(path105.join(routedSkillDir, "retired.marker")))
103724
+ if (_internals52.existsSync(path105.join(routedSkillDir, "retired.marker")))
103522
103725
  continue;
103523
103726
  if (!existingPaths.has(routingPath)) {
103524
103727
  scored.push({
@@ -103544,12 +103747,12 @@ async function skillPropagationGateBefore(directory, input, config3) {
103544
103747
  } else if (typeof scored !== "undefined" && scored.length > 0) {
103545
103748
  skillsForIndex = scored.map((r) => r.skillPath);
103546
103749
  }
103547
- const formattedIndex = _internals49.formatSkillIndexWithContext(skillsForIndex, directory);
103750
+ const formattedIndex = _internals52.formatSkillIndexWithContext(skillsForIndex, directory);
103548
103751
  if (formattedIndex.length > 0) {
103549
103752
  const contextPath = path105.join(directory, ".swarm", "context.md");
103550
103753
  let existingContent = "";
103551
- if (_internals49.existsSync(contextPath)) {
103552
- existingContent = _internals49.readFileSync(contextPath, "utf-8");
103754
+ if (_internals52.existsSync(contextPath)) {
103755
+ existingContent = _internals52.readFileSync(contextPath, "utf-8");
103553
103756
  }
103554
103757
  const sectionHeader = "## Available Skills";
103555
103758
  const newSection = `${sectionHeader}
@@ -103569,10 +103772,10 @@ ${newSection}`;
103569
103772
  }
103570
103773
  }
103571
103774
  const swarmDir = path105.dirname(contextPath);
103572
- if (!_internals49.existsSync(swarmDir)) {
103573
- _internals49.mkdirSync(swarmDir, { recursive: true });
103775
+ if (!_internals52.existsSync(swarmDir)) {
103776
+ _internals52.mkdirSync(swarmDir, { recursive: true });
103574
103777
  }
103575
- _internals49.writeFileSync(contextPath, updatedContent, "utf-8");
103778
+ _internals52.writeFileSync(contextPath, updatedContent, "utf-8");
103576
103779
  }
103577
103780
  } catch (err2) {
103578
103781
  warn(`[skill-propagation-gate] failed to write skill index to context.md: ${err2 instanceof Error ? err2.message : String(err2)}`);
@@ -103598,7 +103801,7 @@ ${newSection}`;
103598
103801
  });
103599
103802
  const warningMsg = `Skill propagation warning: Delegating to ${targetBase} without SKILLS field. ` + `Available skills: ${skillNames.join(", ")}`;
103600
103803
  try {
103601
- _internals49.writeWarnEvent(directory, {
103804
+ _internals52.writeWarnEvent(directory, {
103602
103805
  type: "skill_propagation_warn",
103603
103806
  timestamp: new Date().toISOString(),
103604
103807
  tool: toolName,
@@ -103627,7 +103830,7 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
103627
103830
  let dedupKeys = new Set;
103628
103831
  let existingEntries = [];
103629
103832
  try {
103630
- existingEntries = _internals49.readSkillUsageEntriesTail(directory, {
103833
+ existingEntries = _internals52.readSkillUsageEntriesTail(directory, {
103631
103834
  sessionID
103632
103835
  });
103633
103836
  dedupKeys = new Set(existingEntries.map((e, i2) => {
@@ -103659,7 +103862,7 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
103659
103862
  `)) {
103660
103863
  const coderMatch = line.trim().match(CODER_SKILLS_PATTERN);
103661
103864
  if (coderMatch) {
103662
- const parsed = _internals49.parseSkillPaths(coderMatch[1]);
103865
+ const parsed = _internals52.parseSkillPaths(coderMatch[1]);
103663
103866
  skillPaths.push(...parsed);
103664
103867
  }
103665
103868
  }
@@ -103690,7 +103893,7 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
103690
103893
  if (isDuplicate(skillPath, "reviewer", resolvedTaskID))
103691
103894
  continue;
103692
103895
  try {
103693
- _internals49.appendSkillUsageEntry(directory, {
103896
+ _internals52.appendSkillUsageEntry(directory, {
103694
103897
  skillPath,
103695
103898
  agentName: "reviewer",
103696
103899
  taskID: resolvedTaskID,
@@ -103734,15 +103937,15 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
103734
103937
  skillsField = trimmed.slice("SKILLS:".length).trim();
103735
103938
  }
103736
103939
  if (currentTargetAgent && skillsField && skillsField.toLowerCase() !== "none") {
103737
- const skillPaths = _internals49.parseSkillPaths(skillsField);
103738
- const taskId = _internals49.extractTaskIdFromPrompt(text);
103940
+ const skillPaths = _internals52.parseSkillPaths(skillsField);
103941
+ const taskId = _internals52.extractTaskIdFromPrompt(text);
103739
103942
  for (const skillPath of skillPaths) {
103740
103943
  if (hadRecordingError)
103741
103944
  break;
103742
103945
  if (isDuplicate(skillPath, currentTargetAgent, taskId))
103743
103946
  continue;
103744
103947
  try {
103745
- _internals49.appendSkillUsageEntry(directory, {
103948
+ _internals52.appendSkillUsageEntry(directory, {
103746
103949
  skillPath,
103747
103950
  agentName: currentTargetAgent,
103748
103951
  taskID: taskId,
@@ -103762,16 +103965,16 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
103762
103965
  break;
103763
103966
  }
103764
103967
  }
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;
103968
+ _internals52.skillPropagationGateBefore = skillPropagationGateBefore;
103969
+ _internals52.skillPropagationTransformScan = skillPropagationTransformScan;
103970
+ _internals52.writeWarnEvent = writeWarnEvent2;
103971
+ _internals52.discoverAvailableSkills = discoverAvailableSkills;
103972
+ _internals52.parseDelegationArgs = parseDelegationArgs;
103973
+ _internals52.parseSkillPaths = parseSkillPaths;
103974
+ _internals52.extractTaskIdFromPrompt = extractTaskIdFromPrompt;
103975
+ _internals52.extractSkillsFieldFromPrompt = extractSkillsFieldFromPrompt;
103976
+ _internals52.formatSkillIndexWithContext = formatSkillIndexWithContext;
103977
+ _internals52.loadRoutingSkills = loadRoutingSkills;
103775
103978
 
103776
103979
  // src/index.ts
103777
103980
  init_skill_usage_log();
@@ -107063,7 +107266,7 @@ var EVIDENCE_DIR2 = ".swarm/evidence";
107063
107266
  var VALID_TASK_ID = /^\d+\.\d+(\.\d+)*$/;
107064
107267
  var COUNCIL_GATE_NAME = "council";
107065
107268
  var COUNCIL_AGENT_ID = "architect";
107066
- var _internals50 = {
107269
+ var _internals53 = {
107067
107270
  withTaskEvidenceLock
107068
107271
  };
107069
107272
  var FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
@@ -107098,7 +107301,7 @@ async function writeCouncilEvidence(workingDir, synthesis) {
107098
107301
  const dir = join95(workingDir, EVIDENCE_DIR2);
107099
107302
  mkdirSync28(dir, { recursive: true });
107100
107303
  const filePath = taskEvidencePath(workingDir, synthesis.taskId);
107101
- await _internals50.withTaskEvidenceLock(workingDir, synthesis.taskId, COUNCIL_AGENT_ID, async () => {
107304
+ await _internals53.withTaskEvidenceLock(workingDir, synthesis.taskId, COUNCIL_AGENT_ID, async () => {
107102
107305
  const existingRoot = Object.create(null);
107103
107306
  if (existsSync63(filePath)) {
107104
107307
  try {
@@ -110739,7 +110942,8 @@ var knowledge_receipt = createSwarmTool({
110739
110942
  for (const item of newLessons) {
110740
110943
  const raw = await knowledge_add.execute({ lesson: item.lesson, category: item.category }, ctx);
110741
110944
  try {
110742
- newLessonResults.push(JSON.parse(raw));
110945
+ const output = typeof raw === "string" ? raw : typeof raw === "object" && raw !== null && ("output" in raw) && typeof raw.output === "string" ? raw.output : "";
110946
+ newLessonResults.push(JSON.parse(output));
110743
110947
  } catch {
110744
110948
  newLessonResults.push({ success: false });
110745
110949
  }
@@ -111202,7 +111406,7 @@ function listLaneEvidenceSync(directory, phase) {
111202
111406
  }
111203
111407
  return laneIds;
111204
111408
  }
111205
- var _internals51 = {
111409
+ var _internals54 = {
111206
111410
  listActiveLocks,
111207
111411
  readPersisted: readPersisted2,
111208
111412
  readPlanJson: defaultReadPlanJson,
@@ -111263,7 +111467,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111263
111467
  reason: "Lean Turbo state unreadable or missing"
111264
111468
  };
111265
111469
  }
111266
- const persisted = _internals51.readPersisted(directory);
111470
+ const persisted = _internals54.readPersisted(directory);
111267
111471
  if (!persisted) {
111268
111472
  return {
111269
111473
  ok: false,
@@ -111327,7 +111531,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111327
111531
  }
111328
111532
  }
111329
111533
  if (runState.lanes.length > 0) {
111330
- const evidenceLaneIds = new Set(_internals51.listLaneEvidenceSync(directory, phase));
111534
+ const evidenceLaneIds = new Set(_internals54.listLaneEvidenceSync(directory, phase));
111331
111535
  for (const lane of runState.lanes) {
111332
111536
  if ((lane.status === "completed" || lane.status === "failed") && !evidenceLaneIds.has(lane.laneId)) {
111333
111537
  return {
@@ -111337,7 +111541,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111337
111541
  }
111338
111542
  }
111339
111543
  }
111340
- const activeLocks = _internals51.listActiveLocks(directory);
111544
+ const activeLocks = _internals54.listActiveLocks(directory);
111341
111545
  const phaseLaneIds = new Set(laneIds);
111342
111546
  for (const lock of activeLocks) {
111343
111547
  if (lock.laneId && phaseLaneIds.has(lock.laneId)) {
@@ -111357,7 +111561,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111357
111561
  }
111358
111562
  const serialDegradedTasks = runState.degradedTasks.filter((dt) => !laneTaskIds.has(dt.taskId));
111359
111563
  if (serialDegradedTasks.length > 0) {
111360
- const plan = _internals51.readPlanJson(directory);
111564
+ const plan = _internals54.readPlanJson(directory);
111361
111565
  if (!plan) {
111362
111566
  return {
111363
111567
  ok: false,
@@ -111401,7 +111605,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111401
111605
  }
111402
111606
  const serializedTasks = runState.serializedTasks;
111403
111607
  if (Array.isArray(serializedTasks) && serializedTasks.length > 0) {
111404
- const plan = _internals51.readPlanJson(directory);
111608
+ const plan = _internals54.readPlanJson(directory);
111405
111609
  if (!plan) {
111406
111610
  return {
111407
111611
  ok: false,
@@ -111460,7 +111664,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111460
111664
  }
111461
111665
  let reviewerVerdict = runState.lastReviewerVerdict;
111462
111666
  if (!reviewerVerdict) {
111463
- const evidence = _internals51.readReviewerEvidence(directory, phase);
111667
+ const evidence = _internals54.readReviewerEvidence(directory, phase);
111464
111668
  reviewerVerdict = evidence?.verdict ?? undefined;
111465
111669
  }
111466
111670
  if (mergedConfig.phase_reviewer) {
@@ -111473,7 +111677,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
111473
111677
  }
111474
111678
  let criticVerdict = runState.lastCriticVerdict;
111475
111679
  if (!criticVerdict) {
111476
- const evidence = _internals51.readCriticEvidence(directory, phase);
111680
+ const evidence = _internals54.readCriticEvidence(directory, phase);
111477
111681
  criticVerdict = evidence?.verdict ?? undefined;
111478
111682
  }
111479
111683
  if (mergedConfig.phase_critic) {
@@ -112451,7 +112655,7 @@ Findings: ${details.join("; ")}` : "";
112451
112655
  phase_critic: leanConfig.phase_critic,
112452
112656
  integrated_diff_required: leanConfig.integrated_diff_required
112453
112657
  } : undefined;
112454
- const leanCheck = _internals51.verifyLeanTurboPhaseReady(dir, phase, sessionID, leanPhaseReadyConfig);
112658
+ const leanCheck = _internals54.verifyLeanTurboPhaseReady(dir, phase, sessionID, leanPhaseReadyConfig);
112455
112659
  if (!leanCheck.ok) {
112456
112660
  return JSON.stringify({
112457
112661
  success: false,
@@ -114669,11 +114873,11 @@ var quality_budget = createSwarmTool({
114669
114873
  }).optional().describe("Quality budget thresholds")
114670
114874
  },
114671
114875
  async execute(args2, directory) {
114672
- const result = await _internals52.qualityBudget(args2, directory);
114876
+ const result = await _internals55.qualityBudget(args2, directory);
114673
114877
  return JSON.stringify(result);
114674
114878
  }
114675
114879
  });
114676
- var _internals52 = {
114880
+ var _internals55 = {
114677
114881
  qualityBudget
114678
114882
  };
114679
114883
 
@@ -115402,7 +115606,7 @@ import * as path129 from "node:path";
115402
115606
  var semgrepAvailableCache = null;
115403
115607
  var DEFAULT_RULES_DIR = ".swarm/semgrep-rules";
115404
115608
  var DEFAULT_TIMEOUT_MS3 = 30000;
115405
- var _internals53 = {
115609
+ var _internals56 = {
115406
115610
  isSemgrepAvailable,
115407
115611
  checkSemgrepAvailable,
115408
115612
  resetSemgrepCache,
@@ -115427,7 +115631,7 @@ function isSemgrepAvailable() {
115427
115631
  }
115428
115632
  }
115429
115633
  async function checkSemgrepAvailable() {
115430
- return _internals53.isSemgrepAvailable();
115634
+ return _internals56.isSemgrepAvailable();
115431
115635
  }
115432
115636
  function resetSemgrepCache() {
115433
115637
  semgrepAvailableCache = null;
@@ -115524,12 +115728,12 @@ async function runSemgrep(options) {
115524
115728
  const timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS3;
115525
115729
  if (files.length === 0) {
115526
115730
  return {
115527
- available: _internals53.isSemgrepAvailable(),
115731
+ available: _internals56.isSemgrepAvailable(),
115528
115732
  findings: [],
115529
115733
  engine: "tier_a"
115530
115734
  };
115531
115735
  }
115532
- if (!_internals53.isSemgrepAvailable()) {
115736
+ if (!_internals56.isSemgrepAvailable()) {
115533
115737
  return {
115534
115738
  available: false,
115535
115739
  findings: [],
@@ -115688,7 +115892,7 @@ function assignOccurrenceIndices(findings, directory) {
115688
115892
  }
115689
115893
  const occIdx = countMap.get(baseKey) ?? 0;
115690
115894
  countMap.set(baseKey, occIdx + 1);
115691
- const fp = _internals54.fingerprintFinding(finding, directory, occIdx);
115895
+ const fp = _internals57.fingerprintFinding(finding, directory, occIdx);
115692
115896
  return {
115693
115897
  finding,
115694
115898
  index: occIdx,
@@ -115757,7 +115961,7 @@ async function captureOrMergeBaseline(directory, phase, findings, engine, scanne
115757
115961
  }
115758
115962
  } catch {}
115759
115963
  const scannedRelFiles = new Set(scannedFiles.map((f) => normalizeFindingPath(directory, f)));
115760
- const indexed = _internals54.assignOccurrenceIndices(findings, directory);
115964
+ const indexed = _internals57.assignOccurrenceIndices(findings, directory);
115761
115965
  if (existing && !opts?.force) {
115762
115966
  const prunedFingerprints = existing.fingerprints.filter((fp) => {
115763
115967
  const relFile = fp.slice(0, fp.indexOf("|"));
@@ -115897,7 +116101,7 @@ function loadBaseline(directory, phase) {
115897
116101
  };
115898
116102
  }
115899
116103
  }
115900
- var _internals54 = {
116104
+ var _internals57 = {
115901
116105
  fingerprintFinding,
115902
116106
  assignOccurrenceIndices,
115903
116107
  captureOrMergeBaseline,
@@ -116307,11 +116511,11 @@ var sast_scan = createSwarmTool({
116307
116511
  capture_baseline: safeArgs.capture_baseline,
116308
116512
  phase: safeArgs.phase
116309
116513
  };
116310
- const result = await _internals55.sastScan(input, directory);
116514
+ const result = await _internals58.sastScan(input, directory);
116311
116515
  return JSON.stringify(result, null, 2);
116312
116516
  }
116313
116517
  });
116314
- var _internals55 = {
116518
+ var _internals58 = {
116315
116519
  sastScan,
116316
116520
  sast_scan
116317
116521
  };
@@ -120234,7 +120438,7 @@ init_zod();
120234
120438
  init_config();
120235
120439
  init_schema();
120236
120440
  init_create_tool();
120237
- import { mkdir as mkdir23, rename as rename9, writeFile as writeFile17 } from "node:fs/promises";
120441
+ import { mkdir as mkdir23, rename as rename9, writeFile as writeFile18 } from "node:fs/promises";
120238
120442
  import * as path139 from "node:path";
120239
120443
  var MAX_SPEC_BYTES = 256 * 1024;
120240
120444
  var spec_write = createSwarmTool({
@@ -120296,7 +120500,7 @@ ${content}
120296
120500
  }
120297
120501
  } catch {}
120298
120502
  }
120299
- await writeFile17(tmp, finalContent, "utf-8");
120503
+ await writeFile18(tmp, finalContent, "utf-8");
120300
120504
  await rename9(tmp, target);
120301
120505
  return JSON.stringify({ written: true, path: target, bytes: finalContent.length }, null, 2);
120302
120506
  }
@@ -120728,7 +120932,7 @@ var swarm_memory_propose = createSwarmTool({
120728
120932
  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
120933
  },
120730
120934
  execute: async (args2, directory, ctx) => {
120731
- const { config: config3 } = _internals56.loadPluginConfigWithMeta(directory);
120935
+ const { config: config3 } = _internals59.loadPluginConfigWithMeta(directory);
120732
120936
  if (config3.memory?.enabled !== true) {
120733
120937
  return JSON.stringify({
120734
120938
  success: false,
@@ -120744,7 +120948,7 @@ var swarm_memory_propose = createSwarmTool({
120744
120948
  });
120745
120949
  }
120746
120950
  const agent = getContextAgent2(ctx);
120747
- const gateway = _internals56.createMemoryGateway({
120951
+ const gateway = _internals59.createMemoryGateway({
120748
120952
  directory,
120749
120953
  sessionID: ctx?.sessionID,
120750
120954
  agentRole: agent,
@@ -120769,7 +120973,7 @@ var swarm_memory_propose = createSwarmTool({
120769
120973
  }
120770
120974
  }
120771
120975
  });
120772
- var _internals56 = {
120976
+ var _internals59 = {
120773
120977
  loadPluginConfigWithMeta,
120774
120978
  createMemoryGateway
120775
120979
  };
@@ -120806,7 +121010,7 @@ var swarm_memory_recall = createSwarmTool({
120806
121010
  maxItems: exports_external.number().int().min(1).max(20).optional().describe("Maximum memories to return")
120807
121011
  },
120808
121012
  execute: async (args2, directory, ctx) => {
120809
- const { config: config3 } = _internals57.loadPluginConfigWithMeta(directory);
121013
+ const { config: config3 } = _internals60.loadPluginConfigWithMeta(directory);
120810
121014
  if (config3.memory?.enabled !== true) {
120811
121015
  return JSON.stringify({
120812
121016
  success: false,
@@ -120822,7 +121026,7 @@ var swarm_memory_recall = createSwarmTool({
120822
121026
  });
120823
121027
  }
120824
121028
  const agent = getContextAgent3(ctx);
120825
- const gateway = _internals57.createMemoryGateway({
121029
+ const gateway = _internals60.createMemoryGateway({
120826
121030
  directory,
120827
121031
  sessionID: ctx?.sessionID,
120828
121032
  agentRole: agent,
@@ -120855,7 +121059,7 @@ var RecallArgsSchema = exports_external.object({
120855
121059
  kinds: exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional(),
120856
121060
  maxItems: exports_external.number().int().min(1).max(20).optional()
120857
121061
  });
120858
- var _internals57 = {
121062
+ var _internals60 = {
120859
121063
  loadPluginConfigWithMeta,
120860
121064
  createMemoryGateway
120861
121065
  };
@@ -122100,7 +122304,7 @@ function resolveDefaultReviewerAgent(generatedAgentNames) {
122100
122304
  }
122101
122305
  async function compileReviewPackage(directory, phase, sessionID, requireDiffSummary) {
122102
122306
  const lanes = await listLaneEvidence(directory, phase);
122103
- const persisted = _internals58.readPersisted?.(directory) ?? null;
122307
+ const persisted = _internals61.readPersisted?.(directory) ?? null;
122104
122308
  if (persisted) {
122105
122309
  let matchingRunState = null;
122106
122310
  for (const sessionState of Object.values(persisted.sessions)) {
@@ -122292,7 +122496,7 @@ Be specific and evidence-based. Do not approve a phase with unresolved degraded
122292
122496
  client.session.delete({ path: { id: sessionId } }).catch(() => {});
122293
122497
  }
122294
122498
  }
122295
- var _internals58 = {
122499
+ var _internals61 = {
122296
122500
  compileReviewPackage,
122297
122501
  parseReviewerVerdict,
122298
122502
  writeReviewerEvidence,
@@ -122309,28 +122513,28 @@ async function dispatchPhaseReviewer(directory, phase, sessionID, config3) {
122309
122513
  };
122310
122514
  const generatedAgentNames = swarmState.generatedAgentNames;
122311
122515
  const agentName = mergedConfig.reviewerAgent || resolveDefaultReviewerAgent(generatedAgentNames);
122312
- const pkg = await _internals58.compileReviewPackage(directory, phase, sessionID, mergedConfig.requireDiffSummary);
122516
+ const pkg = await _internals61.compileReviewPackage(directory, phase, sessionID, mergedConfig.requireDiffSummary);
122313
122517
  let responseText;
122314
122518
  try {
122315
- responseText = await _internals58.dispatchReviewerAgent(directory, pkg, agentName, mergedConfig.timeoutMs);
122519
+ responseText = await _internals61.dispatchReviewerAgent(directory, pkg, agentName, mergedConfig.timeoutMs);
122316
122520
  } catch (error93) {
122317
- const evidencePath2 = await _internals58.writeReviewerEvidence(directory, phase, "REJECTED", error93 instanceof Error ? error93.message : String(error93));
122521
+ const evidencePath2 = await _internals61.writeReviewerEvidence(directory, phase, "REJECTED", error93 instanceof Error ? error93.message : String(error93));
122318
122522
  return {
122319
122523
  verdict: "REJECTED",
122320
122524
  reason: `Reviewer dispatch failed: ${error93 instanceof Error ? error93.message : String(error93)}`,
122321
122525
  evidencePath: evidencePath2
122322
122526
  };
122323
122527
  }
122324
- const parsed = _internals58.parseReviewerVerdict(responseText);
122528
+ const parsed = _internals61.parseReviewerVerdict(responseText);
122325
122529
  if (!parsed) {
122326
- const evidencePath2 = await _internals58.writeReviewerEvidence(directory, phase, "REJECTED", "Reviewer response could not be parsed");
122530
+ const evidencePath2 = await _internals61.writeReviewerEvidence(directory, phase, "REJECTED", "Reviewer response could not be parsed");
122327
122531
  return {
122328
122532
  verdict: "REJECTED",
122329
122533
  reason: "Reviewer response could not be parsed",
122330
122534
  evidencePath: evidencePath2
122331
122535
  };
122332
122536
  }
122333
- const evidencePath = await _internals58.writeReviewerEvidence(directory, phase, parsed.verdict, parsed.reason);
122537
+ const evidencePath = await _internals61.writeReviewerEvidence(directory, phase, parsed.verdict, parsed.reason);
122334
122538
  return {
122335
122539
  verdict: parsed.verdict,
122336
122540
  reason: parsed.reason,
@@ -122836,7 +123040,7 @@ ${fileList}
122836
123040
 
122837
123041
  // src/tools/lean-turbo-run-phase.ts
122838
123042
  init_create_tool();
122839
- var _internals59 = {
123043
+ var _internals62 = {
122840
123044
  LeanTurboRunner,
122841
123045
  loadPluginConfigWithMeta
122842
123046
  };
@@ -122846,9 +123050,9 @@ async function executeLeanTurboRunPhase(args2) {
122846
123050
  let runError = null;
122847
123051
  let runner = null;
122848
123052
  try {
122849
- const { config: config3 } = _internals59.loadPluginConfigWithMeta(directory);
123053
+ const { config: config3 } = _internals62.loadPluginConfigWithMeta(directory);
122850
123054
  const leanConfig = config3.turbo?.strategy === "lean" ? config3.turbo.lean : undefined;
122851
- runner = new _internals59.LeanTurboRunner({
123055
+ runner = new _internals62.LeanTurboRunner({
122852
123056
  directory,
122853
123057
  sessionID,
122854
123058
  opencodeClient: swarmState.opencodeClient ?? null,
@@ -123202,7 +123406,7 @@ function isStaticallyEquivalent(originalCode, mutatedCode) {
123202
123406
  const strippedMutated = stripCode(mutatedCode);
123203
123407
  return strippedOriginal === strippedMutated;
123204
123408
  }
123205
- var _internals60 = {
123409
+ var _internals63 = {
123206
123410
  isStaticallyEquivalent,
123207
123411
  checkEquivalence,
123208
123412
  batchCheckEquivalence
@@ -123242,7 +123446,7 @@ async function batchCheckEquivalence(patches, llmJudge) {
123242
123446
  const results = [];
123243
123447
  for (const { patch, originalCode, mutatedCode } of patches) {
123244
123448
  try {
123245
- const result = await _internals60.checkEquivalence(patch, originalCode, mutatedCode, llmJudge);
123449
+ const result = await _internals63.checkEquivalence(patch, originalCode, mutatedCode, llmJudge);
123246
123450
  results.push(result);
123247
123451
  } catch (err3) {
123248
123452
  results.push({
@@ -123261,7 +123465,7 @@ async function batchCheckEquivalence(patches, llmJudge) {
123261
123465
  var MUTATION_TIMEOUT_MS = 30000;
123262
123466
  var TOTAL_BUDGET_MS = 300000;
123263
123467
  var GIT_APPLY_TIMEOUT_MS = 5000;
123264
- var _internals61 = {
123468
+ var _internals64 = {
123265
123469
  executeMutation,
123266
123470
  computeReport,
123267
123471
  executeMutationSuite,
@@ -123293,7 +123497,7 @@ async function executeMutation(patch, testCommand, _testFiles, workingDir) {
123293
123497
  };
123294
123498
  }
123295
123499
  try {
123296
- const applyResult = _internals61.spawnSync("git", ["apply", "--", patchFile], {
123500
+ const applyResult = _internals64.spawnSync("git", ["apply", "--", patchFile], {
123297
123501
  cwd: workingDir,
123298
123502
  timeout: GIT_APPLY_TIMEOUT_MS,
123299
123503
  stdio: "pipe"
@@ -123322,7 +123526,7 @@ async function executeMutation(patch, testCommand, _testFiles, workingDir) {
123322
123526
  }
123323
123527
  let testPassed = false;
123324
123528
  try {
123325
- const spawnResult = _internals61.spawnSync(testCommand[0], testCommand.slice(1), {
123529
+ const spawnResult = _internals64.spawnSync(testCommand[0], testCommand.slice(1), {
123326
123530
  cwd: workingDir,
123327
123531
  timeout: MUTATION_TIMEOUT_MS,
123328
123532
  stdio: "pipe"
@@ -123355,7 +123559,7 @@ async function executeMutation(patch, testCommand, _testFiles, workingDir) {
123355
123559
  } finally {
123356
123560
  if (patchFile) {
123357
123561
  try {
123358
- const revertResult = _internals61.spawnSync("git", ["apply", "-R", "--", patchFile], {
123562
+ const revertResult = _internals64.spawnSync("git", ["apply", "-R", "--", patchFile], {
123359
123563
  cwd: workingDir,
123360
123564
  timeout: GIT_APPLY_TIMEOUT_MS,
123361
123565
  stdio: "pipe"
@@ -123548,7 +123752,7 @@ async function executeMutationSuite(patches, testCommand, testFiles, workingDir,
123548
123752
  }
123549
123753
 
123550
123754
  // src/mutation/gate.ts
123551
- var _internals62 = {
123755
+ var _internals65 = {
123552
123756
  evaluateMutationGate,
123553
123757
  buildTestImprovementPrompt,
123554
123758
  buildMessage
@@ -123569,8 +123773,8 @@ function evaluateMutationGate(report, passThreshold = PASS_THRESHOLD, warnThresh
123569
123773
  } else {
123570
123774
  verdict = "fail";
123571
123775
  }
123572
- const testImprovementPrompt = _internals62.buildTestImprovementPrompt(report, passThreshold, verdict);
123573
- const message = _internals62.buildMessage(verdict, adjustedKillRate, report.killed, report.totalMutants, report.equivalent, warnThreshold);
123776
+ const testImprovementPrompt = _internals65.buildTestImprovementPrompt(report, passThreshold, verdict);
123777
+ const message = _internals65.buildMessage(verdict, adjustedKillRate, report.killed, report.totalMutants, report.equivalent, warnThreshold);
123574
123778
  return {
123575
123779
  verdict,
123576
123780
  killRate: report.killRate,
@@ -124197,7 +124401,7 @@ import * as path152 from "node:path";
124197
124401
  init_bun_compat();
124198
124402
  import * as fs109 from "node:fs";
124199
124403
  import * as path151 from "node:path";
124200
- var _internals63 = { bunSpawn };
124404
+ var _internals66 = { bunSpawn };
124201
124405
  var _swarmGitExcludedChecked = false;
124202
124406
  function fileCoversSwarm(content) {
124203
124407
  for (const rawLine of content.split(`
@@ -124230,7 +124434,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
124230
124434
  checkIgnoreExitCode
124231
124435
  ] = await Promise.all([
124232
124436
  (async () => {
124233
- const proc = _internals63.bunSpawn(["git", "-C", directory, "rev-parse", "--show-toplevel"], GIT_SPAWN_OPTIONS);
124437
+ const proc = _internals66.bunSpawn(["git", "-C", directory, "rev-parse", "--show-toplevel"], GIT_SPAWN_OPTIONS);
124234
124438
  try {
124235
124439
  return await Promise.all([proc.exited, proc.stdout.text()]);
124236
124440
  } finally {
@@ -124240,7 +124444,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
124240
124444
  }
124241
124445
  })(),
124242
124446
  (async () => {
124243
- const proc = _internals63.bunSpawn(["git", "-C", directory, "rev-parse", "--git-path", "info/exclude"], GIT_SPAWN_OPTIONS);
124447
+ const proc = _internals66.bunSpawn(["git", "-C", directory, "rev-parse", "--git-path", "info/exclude"], GIT_SPAWN_OPTIONS);
124244
124448
  try {
124245
124449
  return await Promise.all([proc.exited, proc.stdout.text()]);
124246
124450
  } finally {
@@ -124250,7 +124454,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
124250
124454
  }
124251
124455
  })(),
124252
124456
  (async () => {
124253
- const proc = _internals63.bunSpawn(["git", "-C", directory, "check-ignore", "-q", ".swarm/.gitkeep"], GIT_SPAWN_OPTIONS);
124457
+ const proc = _internals66.bunSpawn(["git", "-C", directory, "check-ignore", "-q", ".swarm/.gitkeep"], GIT_SPAWN_OPTIONS);
124254
124458
  try {
124255
124459
  return await proc.exited;
124256
124460
  } finally {
@@ -124289,7 +124493,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
124289
124493
  }
124290
124494
  } catch {}
124291
124495
  }
124292
- const trackedProc = _internals63.bunSpawn(["git", "-C", directory, "ls-files", "--", ".swarm"], GIT_SPAWN_OPTIONS);
124496
+ const trackedProc = _internals66.bunSpawn(["git", "-C", directory, "ls-files", "--", ".swarm"], GIT_SPAWN_OPTIONS);
124293
124497
  let trackedExitCode;
124294
124498
  let trackedOutput;
124295
124499
  try {
@@ -124314,7 +124518,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
124314
124518
  }
124315
124519
 
124316
124520
  // src/hooks/diff-scope.ts
124317
- var _internals64 = { bunSpawn };
124521
+ var _internals67 = { bunSpawn };
124318
124522
  function getDeclaredScope(taskId, directory) {
124319
124523
  try {
124320
124524
  const planPath = path152.join(directory, ".swarm", "plan.json");
@@ -124349,7 +124553,7 @@ var GIT_DIFF_SPAWN_OPTIONS = {
124349
124553
  };
124350
124554
  async function getChangedFiles(directory) {
124351
124555
  try {
124352
- const proc = _internals64.bunSpawn(["git", "diff", "--name-only", "HEAD~1"], {
124556
+ const proc = _internals67.bunSpawn(["git", "diff", "--name-only", "HEAD~1"], {
124353
124557
  cwd: directory,
124354
124558
  ...GIT_DIFF_SPAWN_OPTIONS
124355
124559
  });
@@ -124366,7 +124570,7 @@ async function getChangedFiles(directory) {
124366
124570
  return stdout.trim().split(`
124367
124571
  `).map((f) => f.trim()).filter((f) => f.length > 0);
124368
124572
  }
124369
- const proc2 = _internals64.bunSpawn(["git", "diff", "--name-only", "HEAD"], {
124573
+ const proc2 = _internals67.bunSpawn(["git", "diff", "--name-only", "HEAD"], {
124370
124574
  cwd: directory,
124371
124575
  ...GIT_DIFF_SPAWN_OPTIONS
124372
124576
  });
@@ -124424,7 +124628,7 @@ init_telemetry();
124424
124628
  init_file_locks();
124425
124629
  import * as fs111 from "node:fs";
124426
124630
  import * as path153 from "node:path";
124427
- var _internals65 = {
124631
+ var _internals68 = {
124428
124632
  listActiveLocks,
124429
124633
  verifyLeanTurboTaskCompletion
124430
124634
  };
@@ -124566,7 +124770,7 @@ function verifyLeanTurboTaskCompletion(directory, taskId, sessionID) {
124566
124770
  }
124567
124771
  };
124568
124772
  }
124569
- const activeLocks = _internals65.listActiveLocks(directory);
124773
+ const activeLocks = _internals68.listActiveLocks(directory);
124570
124774
  const laneLocks = activeLocks.filter((lock) => lock.laneId === lane.laneId);
124571
124775
  if (laneLocks.length > 0) {
124572
124776
  return {
@@ -125495,7 +125699,7 @@ var web_search = createSwarmTool({
125495
125699
  });
125496
125700
  async function captureSearchEvidence(directory, query, results) {
125497
125701
  try {
125498
- const written = await _internals66.writeEvidenceDocuments(directory, results.map((result) => ({
125702
+ const written = await _internals69.writeEvidenceDocuments(directory, results.map((result) => ({
125499
125703
  sourceType: "web_search",
125500
125704
  query,
125501
125705
  title: result.title,
@@ -125523,7 +125727,7 @@ async function captureSearchEvidence(directory, query, results) {
125523
125727
  };
125524
125728
  }
125525
125729
  }
125526
- var _internals66 = {
125730
+ var _internals69 = {
125527
125731
  writeEvidenceDocuments
125528
125732
  };
125529
125733
  // src/tools/write-drift-evidence.ts