opencode-swarm 7.113.3 → 7.113.4

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.
@@ -8235,6 +8235,11 @@ var _internals11 = {
8235
8235
  parseKnowledgeRecommendationsWithDiagnostics,
8236
8236
  readCuratorSummary,
8237
8237
  writeCuratorSummary,
8238
+ appendCuratorRecommendation,
8239
+ mergeCuratorPhaseSummary,
8240
+ readCuratorSummaryState,
8241
+ writeCuratorSummaryState,
8242
+ transactFile,
8238
8243
  filterPhaseEvents,
8239
8244
  checkPhaseCompliance,
8240
8245
  normalizeAgentName,
@@ -8288,8 +8293,39 @@ function capPhaseDigests(digests) {
8288
8293
  function capComplianceObservations(observations) {
8289
8294
  return observations.slice(-MAX_CURATOR_COMPLIANCE_OBSERVATIONS);
8290
8295
  }
8291
- function capKnowledgeRecommendations(recommendations) {
8292
- return recommendations.slice(-MAX_CURATOR_RECOMMENDATIONS);
8296
+ function canonicalizeJson(value) {
8297
+ if (Array.isArray(value))
8298
+ return value.map(canonicalizeJson);
8299
+ if (value === null || typeof value !== "object")
8300
+ return value;
8301
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, nested]) => [key, canonicalizeJson(nested)]));
8302
+ }
8303
+ function recommendationIdentity(recommendation) {
8304
+ const stable = { ...recommendation };
8305
+ if (recommendation.action === "promote" && recommendation.lesson.startsWith("Hive promotion:")) {
8306
+ try {
8307
+ const parsedReason = JSON.parse(recommendation.reason);
8308
+ if (parsedReason !== null && typeof parsedReason === "object" && !Array.isArray(parsedReason)) {
8309
+ const { timestamp: _volatileTimestamp, ...stableReason } = parsedReason;
8310
+ stable.reason = stableReason;
8311
+ }
8312
+ } catch {}
8313
+ }
8314
+ return JSON.stringify(canonicalizeJson(stable));
8315
+ }
8316
+ function normalizeKnowledgeRecommendations(recommendations) {
8317
+ const input = Array.isArray(recommendations) ? recommendations.filter((entry) => entry !== null && typeof entry === "object" && typeof entry.action === "string" && typeof entry.lesson === "string" && typeof entry.reason === "string") : [];
8318
+ const seen = new Set;
8319
+ const newestUnique = [];
8320
+ for (let index = input.length - 1;index >= 0; index--) {
8321
+ const recommendation = input[index];
8322
+ const identity = recommendationIdentity(recommendation);
8323
+ if (seen.has(identity))
8324
+ continue;
8325
+ seen.add(identity);
8326
+ newestUnique.push(recommendation);
8327
+ }
8328
+ return newestUnique.reverse().slice(-MAX_CURATOR_RECOMMENDATIONS);
8293
8329
  }
8294
8330
  function buildDigestFromPhaseDigests(digests) {
8295
8331
  return digests.map((digest) => `### Phase ${digest.phase}
@@ -8564,27 +8600,166 @@ function clampConf(v) {
8564
8600
  return 1;
8565
8601
  return v;
8566
8602
  }
8567
- async function readCuratorSummary(directory) {
8568
- const content = await readSwarmFileAsync(directory, "curator-summary.json");
8569
- if (content === null) {
8570
- return null;
8603
+ function normalizeCuratorSummary(summary) {
8604
+ const recommendations = normalizeKnowledgeRecommendations(summary.knowledge_recommendations);
8605
+ const original = Array.isArray(summary.knowledge_recommendations) ? summary.knowledge_recommendations : [];
8606
+ const changed = !Array.isArray(summary.knowledge_recommendations) || original.length !== recommendations.length || original.some((entry, index) => entry !== recommendations[index]);
8607
+ return {
8608
+ summary: changed ? { ...summary, knowledge_recommendations: recommendations } : summary,
8609
+ changed
8610
+ };
8611
+ }
8612
+ async function readCuratorSummaryState(filePath) {
8613
+ let content;
8614
+ try {
8615
+ content = await fs6.promises.readFile(filePath, "utf-8");
8616
+ } catch (error2) {
8617
+ if (error2.code === "ENOENT") {
8618
+ return { summary: null, dirty: false };
8619
+ }
8620
+ throw error2;
8571
8621
  }
8622
+ return parseCuratorSummaryContent(content);
8623
+ }
8624
+ function parseCuratorSummaryContent(content) {
8572
8625
  try {
8573
8626
  const parsed = JSON.parse(content);
8574
8627
  if (parsed.schema_version !== 1) {
8575
8628
  warn(`Curator summary has unsupported schema version: ${parsed.schema_version}. Expected 1.`);
8576
- return null;
8629
+ return { summary: null, dirty: false };
8577
8630
  }
8578
- return parsed;
8631
+ const normalized = normalizeCuratorSummary(parsed);
8632
+ return { summary: normalized.summary, dirty: normalized.changed };
8579
8633
  } catch {
8580
8634
  warn("Failed to parse curator-summary.json: invalid JSON");
8635
+ return { summary: null, dirty: false };
8636
+ }
8637
+ }
8638
+ async function writeCuratorSummaryState(filePath, state) {
8639
+ if (!state.summary)
8640
+ return;
8641
+ await bunWrite(filePath, JSON.stringify(state.summary, null, 2));
8642
+ }
8643
+ async function transactCuratorSummary(directory, mutate) {
8644
+ const resolvedPath = validateSwarmPath(directory, "curator-summary.json");
8645
+ let invoked = false;
8646
+ let mutationResult;
8647
+ await _internals11.transactFile(resolvedPath, _internals11.readCuratorSummaryState, _internals11.writeCuratorSummaryState, (state) => {
8648
+ invoked = true;
8649
+ const mutation = mutate(state.summary);
8650
+ mutationResult = mutation.result;
8651
+ if (mutation.next === null)
8652
+ return null;
8653
+ const candidate = mutation.next ?? state.summary;
8654
+ if (!candidate)
8655
+ return null;
8656
+ const normalized = normalizeCuratorSummary(candidate).summary;
8657
+ const explicitlyChanged = mutation.next !== undefined && JSON.stringify(normalized) !== JSON.stringify(state.summary);
8658
+ if (!state.dirty && !explicitlyChanged)
8659
+ return null;
8660
+ return { summary: normalized, dirty: false };
8661
+ });
8662
+ return { invoked, result: mutationResult };
8663
+ }
8664
+ async function readCuratorSummary(directory) {
8665
+ const content = await readSwarmFileAsync(directory, "curator-summary.json");
8666
+ if (content === null)
8581
8667
  return null;
8668
+ const initial = parseCuratorSummaryContent(content);
8669
+ if (!initial.summary || !initial.dirty)
8670
+ return initial.summary;
8671
+ let normalized = initial.summary;
8672
+ try {
8673
+ await transactCuratorSummary(directory, (summary) => {
8674
+ if (summary)
8675
+ normalized = summary;
8676
+ return { result: normalized };
8677
+ });
8678
+ } catch (error2) {
8679
+ warn(`Failed to persist curator-summary cleanup: ${error2 instanceof Error ? error2.message : String(error2)}`);
8582
8680
  }
8681
+ return normalized;
8583
8682
  }
8584
8683
  async function writeCuratorSummary(directory, summary) {
8585
- const resolvedPath = validateSwarmPath(directory, "curator-summary.json");
8586
- fs6.mkdirSync(path16.dirname(resolvedPath), { recursive: true });
8587
- await bunWrite(resolvedPath, JSON.stringify(summary, null, 2));
8684
+ const transaction = await transactCuratorSummary(directory, () => ({
8685
+ next: summary,
8686
+ result: undefined
8687
+ }));
8688
+ if (!transaction.invoked) {
8689
+ throw new Error("Failed to persist curator summary");
8690
+ }
8691
+ }
8692
+ async function appendCuratorRecommendation(directory, recommendation) {
8693
+ const transaction = await transactCuratorSummary(directory, (summary) => {
8694
+ if (!summary)
8695
+ return { next: null, result: false };
8696
+ const recommendations = normalizeKnowledgeRecommendations([
8697
+ ...normalizeKnowledgeRecommendations(summary.knowledge_recommendations),
8698
+ recommendation
8699
+ ]);
8700
+ const current = normalizeKnowledgeRecommendations(summary.knowledge_recommendations);
8701
+ const changed = current.length !== recommendations.length || current.some((entry, index) => entry !== recommendations[index]);
8702
+ if (!changed)
8703
+ return { result: false };
8704
+ return {
8705
+ next: {
8706
+ ...summary,
8707
+ last_updated: new Date().toISOString(),
8708
+ knowledge_recommendations: recommendations
8709
+ },
8710
+ result: true
8711
+ };
8712
+ });
8713
+ return transaction.invoked ? transaction.result ?? false : false;
8714
+ }
8715
+ async function mergeCuratorPhaseSummary(directory, merge) {
8716
+ const transaction = await transactCuratorSummary(directory, (current) => {
8717
+ if (current?.phase_digests?.some((digest) => digest.phase === merge.phase)) {
8718
+ return { result: false };
8719
+ }
8720
+ if (current) {
8721
+ const phaseDigests2 = capPhaseDigests([
8722
+ ...Array.isArray(current.phase_digests) ? current.phase_digests : [],
8723
+ merge.phaseDigest
8724
+ ]);
8725
+ return {
8726
+ next: {
8727
+ ...current,
8728
+ last_updated: merge.timestamp,
8729
+ last_phase_covered: Math.max(typeof current.last_phase_covered === "number" ? current.last_phase_covered : 0, merge.phase),
8730
+ digest: buildDigestFromPhaseDigests(phaseDigests2),
8731
+ phase_digests: phaseDigests2,
8732
+ compliance_observations: capComplianceObservations([
8733
+ ...Array.isArray(current.compliance_observations) ? current.compliance_observations : [],
8734
+ ...merge.complianceObservations
8735
+ ]),
8736
+ knowledge_recommendations: normalizeKnowledgeRecommendations([
8737
+ ...normalizeKnowledgeRecommendations(current.knowledge_recommendations),
8738
+ ...merge.knowledgeRecommendations
8739
+ ])
8740
+ },
8741
+ result: true
8742
+ };
8743
+ }
8744
+ const phaseDigests = capPhaseDigests([merge.phaseDigest]);
8745
+ return {
8746
+ next: {
8747
+ schema_version: 1,
8748
+ session_id: merge.sessionId,
8749
+ last_updated: merge.timestamp,
8750
+ last_phase_covered: merge.phase,
8751
+ digest: buildDigestFromPhaseDigests(phaseDigests),
8752
+ phase_digests: phaseDigests,
8753
+ compliance_observations: capComplianceObservations(merge.complianceObservations),
8754
+ knowledge_recommendations: normalizeKnowledgeRecommendations(merge.knowledgeRecommendations)
8755
+ },
8756
+ result: true
8757
+ };
8758
+ });
8759
+ if (!transaction.invoked) {
8760
+ throw new Error("Failed to persist curator phase summary");
8761
+ }
8762
+ return transaction.result ?? false;
8588
8763
  }
8589
8764
  function normalizeAgentName(name) {
8590
8765
  const registry = swarmState.generatedAgentNames.length > 0 ? swarmState.generatedAgentNames : undefined;
@@ -8984,41 +9159,14 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
8984
9159
  }
8985
9160
  const sessionId = `session-${Date.now()}`;
8986
9161
  const now = new Date().toISOString();
8987
- let updatedSummary;
8988
- if (priorSummary) {
8989
- const phaseDigests = capPhaseDigests([
8990
- ...priorSummary.phase_digests,
8991
- phaseDigest
8992
- ]);
8993
- updatedSummary = {
8994
- ...priorSummary,
8995
- last_updated: now,
8996
- last_phase_covered: Math.max(priorSummary.last_phase_covered, phase),
8997
- digest: buildDigestFromPhaseDigests(phaseDigests),
8998
- phase_digests: phaseDigests,
8999
- compliance_observations: capComplianceObservations([
9000
- ...priorSummary.compliance_observations,
9001
- ...complianceObservations
9002
- ]),
9003
- knowledge_recommendations: capKnowledgeRecommendations([
9004
- ...priorSummary.knowledge_recommendations,
9005
- ...knowledgeRecommendations
9006
- ])
9007
- };
9008
- } else {
9009
- const phaseDigests = capPhaseDigests([phaseDigest]);
9010
- updatedSummary = {
9011
- schema_version: 1,
9012
- session_id: sessionId,
9013
- last_updated: now,
9014
- last_phase_covered: phase,
9015
- digest: buildDigestFromPhaseDigests(phaseDigests),
9016
- phase_digests: phaseDigests,
9017
- compliance_observations: capComplianceObservations(complianceObservations),
9018
- knowledge_recommendations: capKnowledgeRecommendations(knowledgeRecommendations)
9019
- };
9020
- }
9021
- await _internals11.writeCuratorSummary(directory, updatedSummary);
9162
+ const summaryUpdated = await _internals11.mergeCuratorPhaseSummary(directory, {
9163
+ phase,
9164
+ phaseDigest,
9165
+ complianceObservations,
9166
+ knowledgeRecommendations,
9167
+ sessionId,
9168
+ timestamp: now
9169
+ });
9022
9170
  if (knowledgeApplicationFindings.length > 0) {
9023
9171
  try {
9024
9172
  const evidenceDir = path16.join(directory, ".swarm", "evidence", String(phase));
@@ -9163,14 +9311,14 @@ ${summary}`;
9163
9311
  digest: phaseDigest,
9164
9312
  compliance: complianceObservations,
9165
9313
  knowledge_recommendations: knowledgeRecommendations,
9166
- summary_updated: true,
9314
+ summary_updated: summaryUpdated,
9167
9315
  knowledge_application_findings: knowledgeApplicationFindings,
9168
9316
  skill_candidates: skillCandidates
9169
9317
  };
9170
9318
  getGlobalEventBus().publish("curator.phase.completed", {
9171
9319
  phase,
9172
9320
  compliance_count: complianceObservations.length,
9173
- summary_updated: true
9321
+ summary_updated: summaryUpdated
9174
9322
  });
9175
9323
  return result;
9176
9324
  } catch (err) {
@@ -10284,11 +10432,11 @@ var _internals12 = {
10284
10432
  return KnowledgeConfigSchema2.parse({});
10285
10433
  },
10286
10434
  applyCuratorKnowledgeUpdates: async (directory, recommendations, knowledgeConfig) => {
10287
- const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-ckzb8ww4.js");
10435
+ const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-nh9raf1a.js");
10288
10436
  return applyCuratorKnowledgeUpdates2(directory, recommendations, knowledgeConfig);
10289
10437
  },
10290
10438
  checkHivePromotions: async (entries, knowledgeConfig) => {
10291
- const { checkHivePromotions } = await import("./hive-promoter-h21wzpsr.js");
10439
+ const { checkHivePromotions } = await import("./hive-promoter-c0fd3j02.js");
10292
10440
  return checkHivePromotions(entries, knowledgeConfig);
10293
10441
  },
10294
10442
  applyProposalTriage: async (directory, triage) => {
@@ -10516,31 +10664,33 @@ async function checkHivePromotions(swarmEntries, config) {
10516
10664
  total_hive_entries: hiveEntries.length
10517
10665
  };
10518
10666
  }
10667
+ var _internals13 = {
10668
+ readSwarmEntries: (directory) => readKnowledge(resolveSwarmKnowledgePath(directory)),
10669
+ checkHivePromotions,
10670
+ readCuratorSummary,
10671
+ appendCuratorRecommendation
10672
+ };
10519
10673
  function createHivePromoterHook(directory, config) {
10520
10674
  const hook = async (_input, _output) => {
10521
- const swarmEntries = await readKnowledge(resolveSwarmKnowledgePath(directory));
10522
- const promotionSummary = await checkHivePromotions(swarmEntries, config);
10523
- const curatorSummary = await readCuratorSummary(directory);
10524
- if (curatorSummary) {
10525
- const existingRecommendations = Array.isArray(curatorSummary.knowledge_recommendations) ? curatorSummary.knowledge_recommendations : [];
10526
- const recommendation = {
10527
- action: "promote",
10528
- lesson: `Hive promotion: ${promotionSummary.new_promotions} new, ${promotionSummary.encounters_incremented} encounters, ${promotionSummary.advancements} advancements, ${promotionSummary.total_hive_entries} total entries`,
10529
- reason: JSON.stringify({
10530
- timestamp: promotionSummary.timestamp,
10531
- new_promotions: promotionSummary.new_promotions,
10532
- encounters_incremented: promotionSummary.encounters_incremented,
10533
- advancements: promotionSummary.advancements,
10534
- total_hive_entries: promotionSummary.total_hive_entries
10535
- })
10536
- };
10537
- const updatedSummary = {
10538
- ...curatorSummary,
10539
- knowledge_recommendations: [...existingRecommendations, recommendation],
10540
- last_updated: new Date().toISOString()
10541
- };
10542
- await writeCuratorSummary(directory, updatedSummary);
10543
- }
10675
+ const swarmEntries = await _internals13.readSwarmEntries(directory);
10676
+ const promotionSummary = await _internals13.checkHivePromotions(swarmEntries, config);
10677
+ const curatorSummary = await _internals13.readCuratorSummary(directory);
10678
+ if (!curatorSummary)
10679
+ return;
10680
+ const hasActivity = promotionSummary.new_promotions > 0 || promotionSummary.encounters_incremented > 0 || promotionSummary.advancements > 0;
10681
+ if (!hasActivity)
10682
+ return;
10683
+ await _internals13.appendCuratorRecommendation(directory, {
10684
+ action: "promote",
10685
+ lesson: `Hive promotion: ${promotionSummary.new_promotions} new, ${promotionSummary.encounters_incremented} encounters, ${promotionSummary.advancements} advancements, ${promotionSummary.total_hive_entries} total entries`,
10686
+ reason: JSON.stringify({
10687
+ timestamp: promotionSummary.timestamp,
10688
+ new_promotions: promotionSummary.new_promotions,
10689
+ encounters_incremented: promotionSummary.encounters_incremented,
10690
+ advancements: promotionSummary.advancements,
10691
+ total_hive_entries: promotionSummary.total_hive_entries
10692
+ })
10693
+ });
10544
10694
  };
10545
10695
  return safeHook(hook);
10546
10696
  }
@@ -10629,7 +10779,13 @@ async function promoteFromSwarm(directory, lessonId) {
10629
10779
  // src/hooks/knowledge-curator.ts
10630
10780
  import { createHash as createHash4 } from "crypto";
10631
10781
  import { existsSync as existsSync14 } from "fs";
10632
- import { appendFile as appendFile2, mkdir as mkdir6, readFile as readFile7, writeFile as writeFile7 } from "fs/promises";
10782
+ import {
10783
+ appendFile as appendFile2,
10784
+ mkdir as mkdir6,
10785
+ readFile as readFile7,
10786
+ realpath,
10787
+ writeFile as writeFile7
10788
+ } from "fs/promises";
10633
10789
  import * as path23 from "path";
10634
10790
 
10635
10791
  // src/services/synonym-map.ts
@@ -10865,7 +11021,7 @@ var SKILL_AUDIENCE_RUNNER_PATTERN = /^runner:(opencode|claude|codex)$/;
10865
11021
  var WORKFLOW_BOOST_MIN_CONTEXT = 0.05;
10866
11022
  var RECENCY_DECAY_MS = 30 * 24 * 60 * 60 * 1000;
10867
11023
  var SKILL_FRONTMATTER_READ_BYTES = 16 * 1024;
10868
- var _internals13 = {
11024
+ var _internals14 = {
10869
11025
  computeSkillRelevanceScore: null,
10870
11026
  rankSkillsForContext: null,
10871
11027
  getSkillStats: null,
@@ -11232,7 +11388,7 @@ function rankSkillsForContext(skills, taskContext, directory) {
11232
11388
  const results = [];
11233
11389
  for (const skillPath of skills) {
11234
11390
  const skillEntries = allEntries.filter((e) => e.skillPath === skillPath);
11235
- const metadata = _internals13.readSkillMetadata(skillPath, directory);
11391
+ const metadata = _internals14.readSkillMetadata(skillPath, directory);
11236
11392
  const score = computeSkillRelevanceScore(skillPath, taskContext, skillEntries, metadata);
11237
11393
  const entriesWithVerdict = skillEntries.filter((e) => e.complianceVerdict !== undefined && e.complianceVerdict !== "not_checked");
11238
11394
  const compliantCount = entriesWithVerdict.filter((e) => e.complianceVerdict === "compliant").length;
@@ -11291,7 +11447,7 @@ function formatSkillIndexWithContext(skills, directory, metadataBySkillPath) {
11291
11447
  } catch {}
11292
11448
  if (!hasHistory) {
11293
11449
  return skills.map((sp) => {
11294
- const meta = metadataBySkillPath?.get(sp) ?? _internals13.readSkillMetadata(sp, directory);
11450
+ const meta = metadataBySkillPath?.get(sp) ?? _internals14.readSkillMetadata(sp, directory);
11295
11451
  return ` - file:${meta.path} - ${meta.name}: ${meta.description}`;
11296
11452
  }).join(`
11297
11453
  `);
@@ -11299,7 +11455,7 @@ function formatSkillIndexWithContext(skills, directory, metadataBySkillPath) {
11299
11455
  const lines = [];
11300
11456
  for (const skillPath of skills) {
11301
11457
  const stats = getSkillStats(skillPath, directory);
11302
- const meta = metadataBySkillPath?.get(skillPath) ?? _internals13.readSkillMetadata(skillPath, directory);
11458
+ const meta = metadataBySkillPath?.get(skillPath) ?? _internals14.readSkillMetadata(skillPath, directory);
11303
11459
  const compliancePct = Math.round(stats.complianceRate * 100);
11304
11460
  const topAgentNames = stats.topAgents.slice(0, 3).map((a) => a.agent).join(", ");
11305
11461
  lines.push(` - file:${meta.path} - ${meta.name}: ${meta.description} (used: ${stats.totalUsage}, compliance: ${compliancePct}%)` + (stats.topAgents.length > 0 ? ` \u2192 ${topAgentNames}` : ""));
@@ -11307,16 +11463,16 @@ function formatSkillIndexWithContext(skills, directory, metadataBySkillPath) {
11307
11463
  return lines.join(`
11308
11464
  `);
11309
11465
  }
11310
- _internals13.computeSkillRelevanceScore = computeSkillRelevanceScore;
11311
- _internals13.rankSkillsForContext = rankSkillsForContext;
11312
- _internals13.getSkillStats = getSkillStats;
11313
- _internals13.formatSkillIndexWithContext = formatSkillIndexWithContext;
11314
- _internals13.parseSkillFrontmatter = parseSkillFrontmatter;
11315
- _internals13.readSkillMetadata = readSkillMetadata;
11316
- _internals13.extractSkillName = extractSkillName;
11317
- _internals13.computeRecencyScore = computeRecencyScore;
11318
- _internals13.computeContextMatchScore = computeContextMatchScore;
11319
- _internals13.computeTriggerMatchBoost = computeTriggerMatchBoost;
11466
+ _internals14.computeSkillRelevanceScore = computeSkillRelevanceScore;
11467
+ _internals14.rankSkillsForContext = rankSkillsForContext;
11468
+ _internals14.getSkillStats = getSkillStats;
11469
+ _internals14.formatSkillIndexWithContext = formatSkillIndexWithContext;
11470
+ _internals14.parseSkillFrontmatter = parseSkillFrontmatter;
11471
+ _internals14.readSkillMetadata = readSkillMetadata;
11472
+ _internals14.extractSkillName = extractSkillName;
11473
+ _internals14.computeRecencyScore = computeRecencyScore;
11474
+ _internals14.computeContextMatchScore = computeContextMatchScore;
11475
+ _internals14.computeTriggerMatchBoost = computeTriggerMatchBoost;
11320
11476
 
11321
11477
  // src/hooks/skill-propagation-gate.ts
11322
11478
  function parseSimpleYaml(content) {
@@ -11418,10 +11574,10 @@ function parseYamlValue(value) {
11418
11574
  }
11419
11575
  function loadRoutingSkills(directory, targetAgent) {
11420
11576
  const routingPath = path21.join(directory, ".opencode", "skill-routing.yaml");
11421
- if (!_internals14.existsSync(routingPath))
11577
+ if (!_internals15.existsSync(routingPath))
11422
11578
  return [];
11423
11579
  try {
11424
- const content = _internals14.readFileSync(routingPath, "utf-8");
11580
+ const content = _internals15.readFileSync(routingPath, "utf-8");
11425
11581
  const config = parseSimpleYaml(content);
11426
11582
  if (!config?.routing)
11427
11583
  return [];
@@ -11448,7 +11604,7 @@ var SKILL_SEARCH_ROOTS = [
11448
11604
  ".claude/skills"
11449
11605
  ];
11450
11606
  var MAX_SCORING_SESSION_ENTRIES = 500;
11451
- var _internals14 = {
11607
+ var _internals15 = {
11452
11608
  readdirSync: fs8.readdirSync.bind(fs8),
11453
11609
  existsSync: fs8.existsSync.bind(fs8),
11454
11610
  statSync: fs8.statSync.bind(fs8),
@@ -11481,11 +11637,11 @@ function discoverAvailableSkills(directory) {
11481
11637
  const results = [];
11482
11638
  for (const root of SKILL_SEARCH_ROOTS) {
11483
11639
  const rootPath = path21.join(directory, root);
11484
- if (!_internals14.existsSync(rootPath))
11640
+ if (!_internals15.existsSync(rootPath))
11485
11641
  continue;
11486
11642
  let entries;
11487
11643
  try {
11488
- entries = _internals14.readdirSync(rootPath);
11644
+ entries = _internals15.readdirSync(rootPath);
11489
11645
  } catch {
11490
11646
  continue;
11491
11647
  }
@@ -11493,11 +11649,11 @@ function discoverAvailableSkills(directory) {
11493
11649
  if (entry.startsWith("."))
11494
11650
  continue;
11495
11651
  const skillDir = path21.join(rootPath, entry);
11496
- if (_internals14.existsSync(path21.join(skillDir, "retired.marker")) || _internals14.existsSync(path21.join(skillDir, "stale.marker")))
11652
+ if (_internals15.existsSync(path21.join(skillDir, "retired.marker")) || _internals15.existsSync(path21.join(skillDir, "stale.marker")))
11497
11653
  continue;
11498
11654
  const skillFile = path21.join(skillDir, "SKILL.md");
11499
11655
  try {
11500
- if (_internals14.statSync(skillDir).isDirectory() && _internals14.existsSync(skillFile)) {
11656
+ if (_internals15.statSync(skillDir).isDirectory() && _internals15.existsSync(skillFile)) {
11501
11657
  results.push(path21.join(root, entry, "SKILL.md").replace(/\\/g, "/"));
11502
11658
  }
11503
11659
  } catch (err) {
@@ -11529,7 +11685,7 @@ function parseDelegationArgs(args) {
11529
11685
  }
11530
11686
  if (!targetAgent)
11531
11687
  return null;
11532
- const skillsField = prompt ? _internals14.extractSkillsFieldFromPrompt(prompt) : "";
11688
+ const skillsField = prompt ? _internals15.extractSkillsFieldFromPrompt(prompt) : "";
11533
11689
  return { targetAgent, skillsField };
11534
11690
  }
11535
11691
  function extractSkillsFieldFromPrompt(prompt) {
@@ -11570,10 +11726,10 @@ function writeWarnEvent(directory, record) {
11570
11726
  const filePath = path21.join(directory, ".swarm", "events.jsonl");
11571
11727
  try {
11572
11728
  const dir = path21.dirname(filePath);
11573
- if (!_internals14.existsSync(dir)) {
11574
- _internals14.mkdirSync(dir, { recursive: true });
11729
+ if (!_internals15.existsSync(dir)) {
11730
+ _internals15.mkdirSync(dir, { recursive: true });
11575
11731
  }
11576
- _internals14.appendFileSync(filePath, `${JSON.stringify(record)}
11732
+ _internals15.appendFileSync(filePath, `${JSON.stringify(record)}
11577
11733
  `, "utf-8");
11578
11734
  } catch (err) {
11579
11735
  warn(`[skill-propagation-gate] failed to write warning event: ${err instanceof Error ? err.message : String(err)}`);
@@ -11628,7 +11784,7 @@ function validateSkillReference(directory, reference, context, options) {
11628
11784
  };
11629
11785
  }
11630
11786
  try {
11631
- const root = _internals14.realpathSync(directory);
11787
+ const root = _internals15.realpathSync(directory);
11632
11788
  const lexicalPath = path21.resolve(root, withoutPrefix);
11633
11789
  if (!isWithinRoot(root, lexicalPath)) {
11634
11790
  return {
@@ -11636,10 +11792,10 @@ function validateSkillReference(directory, reference, context, options) {
11636
11792
  reason: "skill path resolves outside the project"
11637
11793
  };
11638
11794
  }
11639
- if (!_internals14.existsSync(lexicalPath) || !_internals14.statSync(lexicalPath).isFile()) {
11795
+ if (!_internals15.existsSync(lexicalPath) || !_internals15.statSync(lexicalPath).isFile()) {
11640
11796
  return { valid: false, reason: "skill file does not exist" };
11641
11797
  }
11642
- const realPath = _internals14.realpathSync(lexicalPath);
11798
+ const realPath = _internals15.realpathSync(lexicalPath);
11643
11799
  if (!isWithinRoot(root, realPath)) {
11644
11800
  return {
11645
11801
  valid: false,
@@ -11648,7 +11804,7 @@ function validateSkillReference(directory, reference, context, options) {
11648
11804
  }
11649
11805
  const normalizedPath = withoutPrefix.replace(/^\.\//, "");
11650
11806
  const validatedMetadataPath = path21.relative(root, realPath).replace(/\\/g, "/");
11651
- const metadata = _internals14.readSkillMetadata(validatedMetadataPath, root);
11807
+ const metadata = _internals15.readSkillMetadata(validatedMetadataPath, root);
11652
11808
  if (metadata.frontmatterStatus !== "valid" && metadata.frontmatterStatus !== "absent") {
11653
11809
  return {
11654
11810
  valid: false,
@@ -11680,18 +11836,18 @@ async function validateExplicitSkillReferencesBefore(directory, input, config) {
11680
11836
  if (!agentRaw || stripKnownSwarmPrefix(agentRaw) !== "architect") {
11681
11837
  return { blocked: false, reason: null };
11682
11838
  }
11683
- const parsed = _internals14.parseDelegationArgs(input.args);
11839
+ const parsed = _internals15.parseDelegationArgs(input.args);
11684
11840
  if (!parsed)
11685
11841
  return { blocked: false, reason: null };
11686
11842
  const targetBase = stripKnownSwarmPrefix(parsed.targetAgent);
11687
- if (!_internals14.SKILL_CAPABLE_AGENTS.has(targetBase)) {
11843
+ if (!_internals15.SKILL_CAPABLE_AGENTS.has(targetBase)) {
11688
11844
  return { blocked: false, reason: null };
11689
11845
  }
11690
11846
  const skillsValue = parsed.skillsField.trim();
11691
11847
  if (!skillsValue || skillsValue.toLowerCase() === "none") {
11692
11848
  return { blocked: false, reason: null };
11693
11849
  }
11694
- const fileReferences = _internals14.extractFileSkillReferences(skillsValue);
11850
+ const fileReferences = _internals15.extractFileSkillReferences(skillsValue);
11695
11851
  if (fileReferences.length === 0) {
11696
11852
  return { blocked: false, reason: null, validatedSkillPaths: [] };
11697
11853
  }
@@ -11704,7 +11860,7 @@ async function validateExplicitSkillReferencesBefore(directory, input, config) {
11704
11860
  const context = resolveSkillAudienceContext(config);
11705
11861
  const validatedSkillPaths = [];
11706
11862
  for (const reference of fileReferences) {
11707
- const result = _internals14.validateSkillReference(directory, reference, context, {
11863
+ const result = _internals15.validateSkillReference(directory, reference, context, {
11708
11864
  enforceAudience: true
11709
11865
  });
11710
11866
  if (!result.valid) {
@@ -11749,18 +11905,18 @@ async function skillPropagationGateBefore(directory, input, config) {
11749
11905
  const baseAgent = stripKnownSwarmPrefix(agentRaw);
11750
11906
  if (baseAgent !== "architect")
11751
11907
  return { blocked: false, reason: null, recommendedSkills: undefined };
11752
- const parsed = _internals14.parseDelegationArgs(input.args);
11908
+ const parsed = _internals15.parseDelegationArgs(input.args);
11753
11909
  if (!parsed)
11754
11910
  return { blocked: false, reason: null, recommendedSkills: undefined };
11755
11911
  const targetBase = stripKnownSwarmPrefix(parsed.targetAgent);
11756
- if (!_internals14.SKILL_CAPABLE_AGENTS.has(targetBase))
11912
+ if (!_internals15.SKILL_CAPABLE_AGENTS.has(targetBase))
11757
11913
  return { blocked: false, reason: null, recommendedSkills: undefined };
11758
11914
  const sessionID = typeof input.sessionID === "string" ? input.sessionID : "unknown";
11759
11915
  const audienceContext = resolveSkillAudienceContext(config);
11760
11916
  const availableSkills = [];
11761
11917
  const metadataBySkillPath = new Map;
11762
- for (const skillPath of _internals14.discoverAvailableSkills(directory)) {
11763
- const validation = _internals14.validateSkillReference(directory, skillPath, audienceContext, { enforceAudience: true, requireFilePrefix: false });
11918
+ for (const skillPath of _internals15.discoverAvailableSkills(directory)) {
11919
+ const validation = _internals15.validateSkillReference(directory, skillPath, audienceContext, { enforceAudience: true, requireFilePrefix: false });
11764
11920
  if (!validation.valid || !validation.skillPath)
11765
11921
  continue;
11766
11922
  availableSkills.push(validation.skillPath);
@@ -11771,7 +11927,7 @@ async function skillPropagationGateBefore(directory, input, config) {
11771
11927
  const skillsValue = parsed.skillsField.trim();
11772
11928
  if (skillsValue && skillsValue.toLowerCase() !== "none") {
11773
11929
  const prompt = typeof input.args?.prompt === "string" ? String(input.args.prompt) : "";
11774
- const taskId = _internals14.extractTaskIdFromPrompt(prompt);
11930
+ const taskId = _internals15.extractTaskIdFromPrompt(prompt);
11775
11931
  const skillPaths = explicitIntegrity.validatedSkillPaths ?? [];
11776
11932
  let coderSkillPaths = [];
11777
11933
  if (prompt) {
@@ -11780,19 +11936,19 @@ async function skillPropagationGateBefore(directory, input, config) {
11780
11936
  const trimmed = line.trim();
11781
11937
  if (trimmed.startsWith("SKILLS_USED_BY_CODER:")) {
11782
11938
  const fieldVal = trimmed.slice("SKILLS_USED_BY_CODER:".length).trim();
11783
- coderSkillPaths = _internals14.parseSkillPaths(fieldVal);
11939
+ coderSkillPaths = _internals15.parseSkillPaths(fieldVal);
11784
11940
  break;
11785
11941
  }
11786
11942
  }
11787
11943
  }
11788
11944
  const safeCoderSkillPaths = coderSkillPaths.flatMap((skillPath) => {
11789
- const validation = _internals14.validateSkillReference(directory, skillPath, audienceContext, { enforceAudience: false });
11945
+ const validation = _internals15.validateSkillReference(directory, skillPath, audienceContext, { enforceAudience: false });
11790
11946
  return validation.valid && validation.skillPath ? [validation.skillPath] : [];
11791
11947
  });
11792
11948
  const allPaths = [...new Set([...skillPaths, ...safeCoderSkillPaths])];
11793
11949
  for (const skillPath of allPaths) {
11794
11950
  try {
11795
- _internals14.appendSkillUsageEntry(directory, {
11951
+ _internals15.appendSkillUsageEntry(directory, {
11796
11952
  skillPath,
11797
11953
  agentName: targetBase,
11798
11954
  taskID: taskId,
@@ -11809,18 +11965,18 @@ async function skillPropagationGateBefore(directory, input, config) {
11809
11965
  let scored = [];
11810
11966
  if (skillsValue.toLowerCase() !== "none" && availableSkills.length > 0) {
11811
11967
  try {
11812
- const sessionEntries = _internals14.readSkillUsageEntriesTail(directory, {
11968
+ const sessionEntries = _internals15.readSkillUsageEntriesTail(directory, {
11813
11969
  sessionID
11814
11970
  });
11815
- if (sessionEntries.length > _internals14.MAX_SCORING_SESSION_ENTRIES) {
11971
+ if (sessionEntries.length > _internals15.MAX_SCORING_SESSION_ENTRIES) {
11816
11972
  scoringSkipped = true;
11817
- warn(`[skill-propagation-gate] skipping scoring \u2014 tail window has ${sessionEntries.length} session entries (limit: ${_internals14.MAX_SCORING_SESSION_ENTRIES})`);
11973
+ warn(`[skill-propagation-gate] skipping scoring \u2014 tail window has ${sessionEntries.length} session entries (limit: ${_internals15.MAX_SCORING_SESSION_ENTRIES})`);
11818
11974
  } else {
11819
11975
  const prompt = typeof input.args?.prompt === "string" ? String(input.args.prompt) : "";
11820
11976
  scored = availableSkills.map((skillPath) => {
11821
11977
  const skillEntries = sessionEntries.filter((e) => e.skillPath === skillPath);
11822
- const metadata = metadataBySkillPath.get(skillPath) ?? _internals14.readSkillMetadata(skillPath, directory);
11823
- const score = _internals14.computeSkillRelevanceScore(skillPath, prompt, skillEntries, metadata);
11978
+ const metadata = metadataBySkillPath.get(skillPath) ?? _internals15.readSkillMetadata(skillPath, directory);
11979
+ const score = _internals15.computeSkillRelevanceScore(skillPath, prompt, skillEntries, metadata);
11824
11980
  return { skillPath, score, usageCount: skillEntries.length };
11825
11981
  }).sort((a, b) => b.score - a.score || b.usageCount - a.usageCount);
11826
11982
  if (scored.length > 0) {
@@ -11834,11 +11990,11 @@ async function skillPropagationGateBefore(directory, input, config) {
11834
11990
  }
11835
11991
  }
11836
11992
  try {
11837
- const routingPaths = _internals14.loadRoutingSkills(directory, targetBase);
11993
+ const routingPaths = _internals15.loadRoutingSkills(directory, targetBase);
11838
11994
  if (routingPaths.length > 0) {
11839
11995
  const existingPaths = new Set(scored.map((s) => s.skillPath));
11840
11996
  for (const routingPath of routingPaths) {
11841
- const validation = _internals14.validateSkillReference(directory, routingPath, audienceContext, { enforceAudience: true, requireFilePrefix: false });
11997
+ const validation = _internals15.validateSkillReference(directory, routingPath, audienceContext, { enforceAudience: true, requireFilePrefix: false });
11842
11998
  if (!validation.valid || !validation.skillPath)
11843
11999
  continue;
11844
12000
  const eligibleRoutingPath = validation.skillPath;
@@ -11846,7 +12002,7 @@ async function skillPropagationGateBefore(directory, input, config) {
11846
12002
  metadataBySkillPath.set(eligibleRoutingPath, validation.metadata);
11847
12003
  }
11848
12004
  const routedSkillDir = path21.dirname(path21.join(directory, eligibleRoutingPath));
11849
- if (_internals14.existsSync(path21.join(routedSkillDir, "retired.marker")) || _internals14.existsSync(path21.join(routedSkillDir, "stale.marker")))
12005
+ if (_internals15.existsSync(path21.join(routedSkillDir, "retired.marker")) || _internals15.existsSync(path21.join(routedSkillDir, "stale.marker")))
11850
12006
  continue;
11851
12007
  if (!existingPaths.has(eligibleRoutingPath)) {
11852
12008
  scored.push({
@@ -11872,12 +12028,12 @@ async function skillPropagationGateBefore(directory, input, config) {
11872
12028
  } else if (typeof scored !== "undefined" && scored.length > 0) {
11873
12029
  skillsForIndex = scored.map((r) => r.skillPath);
11874
12030
  }
11875
- const formattedIndex = _internals14.formatSkillIndexWithContext(skillsForIndex, directory, metadataBySkillPath);
12031
+ const formattedIndex = _internals15.formatSkillIndexWithContext(skillsForIndex, directory, metadataBySkillPath);
11876
12032
  if (formattedIndex.length > 0) {
11877
12033
  const contextPath = path21.join(directory, ".swarm", "context.md");
11878
12034
  let existingContent = "";
11879
- if (_internals14.existsSync(contextPath)) {
11880
- existingContent = _internals14.readFileSync(contextPath, "utf-8");
12035
+ if (_internals15.existsSync(contextPath)) {
12036
+ existingContent = _internals15.readFileSync(contextPath, "utf-8");
11881
12037
  }
11882
12038
  const sectionHeader = "## Available Skills";
11883
12039
  const newSection = `${sectionHeader}
@@ -11897,10 +12053,10 @@ ${newSection}`;
11897
12053
  }
11898
12054
  }
11899
12055
  const swarmDir = path21.dirname(contextPath);
11900
- if (!_internals14.existsSync(swarmDir)) {
11901
- _internals14.mkdirSync(swarmDir, { recursive: true });
12056
+ if (!_internals15.existsSync(swarmDir)) {
12057
+ _internals15.mkdirSync(swarmDir, { recursive: true });
11902
12058
  }
11903
- _internals14.writeFileSync(contextPath, updatedContent, "utf-8");
12059
+ _internals15.writeFileSync(contextPath, updatedContent, "utf-8");
11904
12060
  }
11905
12061
  } catch (err) {
11906
12062
  warn(`[skill-propagation-gate] failed to write skill index to context.md: ${err instanceof Error ? err.message : String(err)}`);
@@ -11926,7 +12082,7 @@ ${newSection}`;
11926
12082
  });
11927
12083
  const warningMsg = `Skill propagation warning: Delegating to ${targetBase} without SKILLS field. ` + `Available skills: ${skillNames.join(", ")}`;
11928
12084
  try {
11929
- _internals14.writeWarnEvent(directory, {
12085
+ _internals15.writeWarnEvent(directory, {
11930
12086
  type: "skill_propagation_warn",
11931
12087
  timestamp: new Date().toISOString(),
11932
12088
  tool: toolName,
@@ -11958,17 +12114,17 @@ async function skillPropagationTransformScan(directory, output, sessionID, confi
11958
12114
  const validatedProvenancePaths = (fieldValue) => {
11959
12115
  if (remainingProvenanceValidationBudget <= 0)
11960
12116
  return [];
11961
- const references = _internals14.parseSkillPaths(fieldValue).slice(0, remainingProvenanceValidationBudget);
12117
+ const references = _internals15.parseSkillPaths(fieldValue).slice(0, remainingProvenanceValidationBudget);
11962
12118
  remainingProvenanceValidationBudget -= references.length;
11963
12119
  return references.flatMap((reference) => {
11964
- const validation = _internals14.validateSkillReference(directory, reference, audienceContext, { enforceAudience: true });
12120
+ const validation = _internals15.validateSkillReference(directory, reference, audienceContext, { enforceAudience: true });
11965
12121
  return validation.valid && validation.skillPath ? [validation.skillPath] : [];
11966
12122
  });
11967
12123
  };
11968
12124
  let dedupKeys = new Set;
11969
12125
  let existingEntries = [];
11970
12126
  try {
11971
- existingEntries = _internals14.readSkillUsageEntriesTail(directory, {
12127
+ existingEntries = _internals15.readSkillUsageEntriesTail(directory, {
11972
12128
  sessionID
11973
12129
  });
11974
12130
  dedupKeys = new Set(existingEntries.map((e, i) => {
@@ -12039,7 +12195,7 @@ async function skillPropagationTransformScan(directory, output, sessionID, confi
12039
12195
  if (isDuplicate(skillPath, "reviewer", resolvedTaskID))
12040
12196
  continue;
12041
12197
  try {
12042
- _internals14.appendSkillUsageEntry(directory, {
12198
+ _internals15.appendSkillUsageEntry(directory, {
12043
12199
  skillPath,
12044
12200
  agentName: "reviewer",
12045
12201
  taskID: resolvedTaskID,
@@ -12084,14 +12240,14 @@ async function skillPropagationTransformScan(directory, output, sessionID, confi
12084
12240
  }
12085
12241
  if (currentTargetAgent && skillsField && skillsField.toLowerCase() !== "none") {
12086
12242
  const skillPaths = validatedProvenancePaths(skillsField);
12087
- const taskId = _internals14.extractTaskIdFromPrompt(text);
12243
+ const taskId = _internals15.extractTaskIdFromPrompt(text);
12088
12244
  for (const skillPath of skillPaths) {
12089
12245
  if (hadRecordingError)
12090
12246
  break;
12091
12247
  if (isDuplicate(skillPath, currentTargetAgent, taskId))
12092
12248
  continue;
12093
12249
  try {
12094
- _internals14.appendSkillUsageEntry(directory, {
12250
+ _internals15.appendSkillUsageEntry(directory, {
12095
12251
  skillPath,
12096
12252
  agentName: currentTargetAgent,
12097
12253
  taskID: taskId,
@@ -12111,18 +12267,18 @@ async function skillPropagationTransformScan(directory, output, sessionID, confi
12111
12267
  break;
12112
12268
  }
12113
12269
  }
12114
- _internals14.skillPropagationGateBefore = skillPropagationGateBefore;
12115
- _internals14.skillPropagationTransformScan = skillPropagationTransformScan;
12116
- _internals14.writeWarnEvent = writeWarnEvent;
12117
- _internals14.discoverAvailableSkills = discoverAvailableSkills;
12118
- _internals14.parseDelegationArgs = parseDelegationArgs;
12119
- _internals14.parseSkillPaths = parseSkillPaths;
12120
- _internals14.extractFileSkillReferences = extractFileSkillReferences;
12121
- _internals14.validateSkillReference = validateSkillReference;
12122
- _internals14.extractTaskIdFromPrompt = extractTaskIdFromPrompt;
12123
- _internals14.extractSkillsFieldFromPrompt = extractSkillsFieldFromPrompt;
12124
- _internals14.formatSkillIndexWithContext = formatSkillIndexWithContext;
12125
- _internals14.loadRoutingSkills = loadRoutingSkills;
12270
+ _internals15.skillPropagationGateBefore = skillPropagationGateBefore;
12271
+ _internals15.skillPropagationTransformScan = skillPropagationTransformScan;
12272
+ _internals15.writeWarnEvent = writeWarnEvent;
12273
+ _internals15.discoverAvailableSkills = discoverAvailableSkills;
12274
+ _internals15.parseDelegationArgs = parseDelegationArgs;
12275
+ _internals15.parseSkillPaths = parseSkillPaths;
12276
+ _internals15.extractFileSkillReferences = extractFileSkillReferences;
12277
+ _internals15.validateSkillReference = validateSkillReference;
12278
+ _internals15.extractTaskIdFromPrompt = extractTaskIdFromPrompt;
12279
+ _internals15.extractSkillsFieldFromPrompt = extractSkillsFieldFromPrompt;
12280
+ _internals15.formatSkillIndexWithContext = formatSkillIndexWithContext;
12281
+ _internals15.loadRoutingSkills = loadRoutingSkills;
12126
12282
 
12127
12283
  // src/hooks/micro-reflector.ts
12128
12284
  var REFLECT_OUTCOMES = new Set([
@@ -12160,6 +12316,8 @@ async function readTaskTrajectory(directory, taskId) {
12160
12316
  // src/hooks/knowledge-curator.ts
12161
12317
  var seenRetroSections = new Map;
12162
12318
  var MAX_TRACKED_RETRO_SECTIONS = 500;
12319
+ var MAX_IN_FLIGHT_EVIDENCE_ENTRIES = 500;
12320
+ var inFlightEvidenceEntries = new Set;
12163
12321
  function pruneSeenRetroSections() {
12164
12322
  const cutoff = Date.now() - 86400000;
12165
12323
  for (const [key, entry] of seenRetroSections) {
@@ -12184,6 +12342,81 @@ function recordSeenRetroSection(key, value, timestamp) {
12184
12342
  function hashContent(content) {
12185
12343
  return createHash4("sha1").update(content).digest("hex");
12186
12344
  }
12345
+ async function canonicalExistingPath(candidate) {
12346
+ let resolved = path23.resolve(candidate);
12347
+ try {
12348
+ resolved = await _internals16.realpath(resolved);
12349
+ } catch {}
12350
+ return resolved;
12351
+ }
12352
+ function isPathContained(root, candidate) {
12353
+ const relative3 = path23.relative(root, candidate);
12354
+ return relative3 === "" || !relative3.startsWith(`..${path23.sep}`) && relative3 !== ".." && !path23.isAbsolute(relative3);
12355
+ }
12356
+ function physicalPathIdentity(candidate) {
12357
+ const normalized = candidate.replaceAll("\\", "/").normalize("NFC");
12358
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
12359
+ }
12360
+ async function resolveEvidencePathScope(directory, relativeEvidencePath) {
12361
+ const projectRoot = await canonicalExistingPath(directory);
12362
+ const swarmRoot = await canonicalExistingPath(path23.join(projectRoot, ".swarm"));
12363
+ if (!isPathContained(projectRoot, swarmRoot))
12364
+ return null;
12365
+ const evidenceRoot = await canonicalExistingPath(path23.join(swarmRoot, "evidence"));
12366
+ if (!isPathContained(swarmRoot, evidenceRoot))
12367
+ return null;
12368
+ const evidenceTarget = await canonicalExistingPath(path23.join(swarmRoot, ...relativeEvidencePath.split("/")));
12369
+ if (!isPathContained(evidenceRoot, evidenceTarget))
12370
+ return null;
12371
+ return {
12372
+ projectIdentity: hashContent(physicalPathIdentity(projectRoot)),
12373
+ evidenceIdentity: hashContent(physicalPathIdentity(evidenceTarget))
12374
+ };
12375
+ }
12376
+ function sanitizeEvidenceLessons(value) {
12377
+ if (!Array.isArray(value))
12378
+ return [];
12379
+ return value.filter((lesson) => typeof lesson === "string").map((lesson) => lesson.trim()).filter((lesson) => lesson.length > 0 && lesson.length <= 280);
12380
+ }
12381
+ function evidenceProjectName(entry, root) {
12382
+ const metadata = isRecord2(entry.metadata) ? entry.metadata : null;
12383
+ return typeof entry.project_name === "string" ? entry.project_name : typeof metadata?.project_name === "string" ? metadata.project_name : typeof root.project_name === "string" ? root.project_name : "unknown";
12384
+ }
12385
+ function evidencePhaseNumber(entry, root) {
12386
+ return typeof entry.phase_number === "number" ? entry.phase_number : typeof root.phase_number === "number" ? root.phase_number : 1;
12387
+ }
12388
+ function extractEvidenceLessonBatches(evidenceData) {
12389
+ const rawEntries = Array.isArray(evidenceData.entries) ? evidenceData.entries : [evidenceData];
12390
+ const batches = [];
12391
+ for (const rawEntry of rawEntries) {
12392
+ if (!isRecord2(rawEntry))
12393
+ continue;
12394
+ if (Object.hasOwn(rawEntry, "type") && rawEntry.type !== "retrospective") {
12395
+ continue;
12396
+ }
12397
+ const lessons = sanitizeEvidenceLessons(rawEntry.lessons_learned);
12398
+ if (lessons.length === 0)
12399
+ continue;
12400
+ const phaseNumber = evidencePhaseNumber(rawEntry, evidenceData);
12401
+ const projectName = evidenceProjectName(rawEntry, evidenceData);
12402
+ const identity = hashContent(JSON.stringify([
12403
+ rawEntry.type ?? "legacy-retrospective",
12404
+ rawEntry.task_id ?? evidenceData.task_id ?? "",
12405
+ rawEntry.timestamp ?? "",
12406
+ rawEntry.agent ?? "",
12407
+ phaseNumber,
12408
+ projectName,
12409
+ lessons
12410
+ ]));
12411
+ batches.push({
12412
+ identity,
12413
+ lessons,
12414
+ projectName,
12415
+ phaseNumber
12416
+ });
12417
+ }
12418
+ return batches;
12419
+ }
12187
12420
  function isWriteToEvidenceFile(input) {
12188
12421
  const trigger = normalizeWriteTrigger(input);
12189
12422
  return isEvidencePath(trigger?.filePath);
@@ -12893,9 +13126,9 @@ async function curateAndStoreSwarm(lessons, projectName, phaseInfo, directory, c
12893
13126
  } catch {}
12894
13127
  }
12895
13128
  if (!options?.skipAutoPromotion) {
12896
- await _internals15.runAutoPromotion(directory, config);
13129
+ await _internals16.runAutoPromotion(directory, config);
12897
13130
  if (phaseInfo.phase_number > 0) {
12898
- await _internals15.runAutoDemotion(directory, config, phaseInfo.phase_number);
13131
+ await _internals16.runAutoDemotion(directory, config, phaseInfo.phase_number);
12899
13132
  }
12900
13133
  }
12901
13134
  return { stored, reinforced, skipped, rejected, quarantined };
@@ -12984,9 +13217,11 @@ function createKnowledgeCuratorHook(directory, config, options = {}) {
12984
13217
  if (!isPlanTrigger && !isEvidenceTrigger)
12985
13218
  return;
12986
13219
  if (isEvidenceTrigger) {
12987
- const relativeEvidencePath = trigger.filePath.replace(/^.*\.swarm\//, "");
12988
- const evidenceKey = `evidence:${trigger.sessionID}:${relativeEvidencePath}`;
12989
- const lastSeenEvidence = seenRetroSections.get(evidenceKey);
13220
+ const relativeEvidencePath = trigger.filePath.replaceAll("\\", "/").replace(/^.*\.swarm\//i, "");
13221
+ const canonicalRelativeEvidencePath = path23.posix.normalize(relativeEvidencePath);
13222
+ const evidenceScope = await resolveEvidencePathScope(directory, canonicalRelativeEvidencePath);
13223
+ if (!evidenceScope)
13224
+ return;
12990
13225
  const evidenceContent = await readSwarmFileAsync(directory, relativeEvidencePath);
12991
13226
  if (!evidenceContent)
12992
13227
  return;
@@ -12996,28 +13231,29 @@ function createKnowledgeCuratorHook(directory, config, options = {}) {
12996
13231
  } catch {
12997
13232
  return;
12998
13233
  }
12999
- let lessons = [];
13000
- if (Array.isArray(evidenceData.entries) && evidenceData.entries.length > 0) {
13001
- const firstEntry = evidenceData.entries[0];
13002
- if (Array.isArray(firstEntry.lessons_learned)) {
13003
- lessons = firstEntry.lessons_learned;
13234
+ const batches = extractEvidenceLessonBatches(evidenceData);
13235
+ for (const batch of batches) {
13236
+ const evidenceKey = `evidence:${evidenceScope.projectIdentity}:${evidenceScope.evidenceIdentity}:entry:${batch.identity}`;
13237
+ if (seenRetroSections.has(evidenceKey) || inFlightEvidenceEntries.has(evidenceKey)) {
13238
+ continue;
13239
+ }
13240
+ if (inFlightEvidenceEntries.size >= MAX_IN_FLIGHT_EVIDENCE_ENTRIES) {
13241
+ warn(`Evidence curation overload: ${MAX_IN_FLIGHT_EVIDENCE_ENTRIES} entries already in flight; retrying ${relativeEvidencePath} on a later trigger`);
13242
+ continue;
13243
+ }
13244
+ inFlightEvidenceEntries.add(evidenceKey);
13245
+ try {
13246
+ await _internals16.curateAndStoreSwarm(batch.lessons, batch.projectName, { phase_number: batch.phaseNumber }, directory, config, {
13247
+ llmDelegate: options.llmDelegateFactory?.(trigger.sessionID),
13248
+ enrichmentQuota: options.enrichmentQuota
13249
+ });
13250
+ recordSeenRetroSection(evidenceKey, batch.identity, Date.now());
13251
+ } catch (err) {
13252
+ warn(`Evidence curation failed for entry ${batch.identity}, will retry on next trigger: ${err instanceof Error ? err.message : String(err)}`);
13253
+ } finally {
13254
+ inFlightEvidenceEntries.delete(evidenceKey);
13004
13255
  }
13005
- } else if (Array.isArray(evidenceData.lessons_learned)) {
13006
- lessons = evidenceData.lessons_learned;
13007
- }
13008
- if (lessons.length === 0)
13009
- return;
13010
- const evidenceHash = hashContent(JSON.stringify(lessons));
13011
- if (lastSeenEvidence?.value === evidenceHash) {
13012
- return;
13013
13256
  }
13014
- recordSeenRetroSection(evidenceKey, evidenceHash, Date.now());
13015
- const projectName2 = evidenceData.project_name ?? "unknown";
13016
- const phaseNumber2 = typeof evidenceData.phase_number === "number" ? evidenceData.phase_number : 1;
13017
- await _internals15.curateAndStoreSwarm(lessons, projectName2, { phase_number: phaseNumber2 }, directory, config, {
13018
- llmDelegate: options.llmDelegateFactory?.(trigger.sessionID),
13019
- enrichmentQuota: options.enrichmentQuota
13020
- });
13021
13257
  return;
13022
13258
  }
13023
13259
  const planContent = await readSwarmFileAsync(directory, "plan.md");
@@ -13039,14 +13275,14 @@ function createKnowledgeCuratorHook(directory, config, options = {}) {
13039
13275
  const projectName = projectNameMatch ? projectNameMatch[1].trim() : "unknown";
13040
13276
  const phaseMatch = /^Phase:\s*(\d+)/m.exec(planContent);
13041
13277
  const phaseNumber = phaseMatch ? parseInt(phaseMatch[1], 10) : 1;
13042
- await _internals15.curateAndStoreSwarm(normalLessons, projectName, { phase_number: phaseNumber }, directory, config, {
13278
+ await _internals16.curateAndStoreSwarm(normalLessons, projectName, { phase_number: phaseNumber }, directory, config, {
13043
13279
  llmDelegate: options.llmDelegateFactory?.(trigger.sessionID),
13044
13280
  enrichmentQuota: options.enrichmentQuota
13045
13281
  });
13046
13282
  };
13047
13283
  return safeHook(handler);
13048
13284
  }
13049
- var _internals15 = {
13285
+ var _internals16 = {
13050
13286
  isWriteToEvidenceFile,
13051
13287
  curateAndStoreSwarm,
13052
13288
  runAutoPromotion,
@@ -13056,7 +13292,11 @@ var _internals15 = {
13056
13292
  recordSeenRetroSection,
13057
13293
  hashContent,
13058
13294
  capSeenRetroSections,
13059
- MAX_TRACKED_RETRO_SECTIONS
13295
+ MAX_TRACKED_RETRO_SECTIONS,
13296
+ inFlightEvidenceEntries,
13297
+ MAX_IN_FLIGHT_EVIDENCE_ENTRIES,
13298
+ extractEvidenceLessonBatches,
13299
+ realpath
13060
13300
  };
13061
13301
 
13062
13302
  // src/memory/finalize-reward-sweep.ts
@@ -13081,7 +13321,7 @@ async function runFinalizeRewardSweep(args) {
13081
13321
  return result;
13082
13322
  }
13083
13323
  const timestamp = args.timestamp ?? new Date().toISOString();
13084
- const provider = _internals16.createConfiguredMemoryProvider(directory, memoryConfig);
13324
+ const provider = _internals17.createConfiguredMemoryProvider(directory, memoryConfig);
13085
13325
  try {
13086
13326
  result.swept = true;
13087
13327
  for (const taskId of taskIds) {
@@ -13101,7 +13341,7 @@ async function runFinalizeRewardSweep(args) {
13101
13341
  }
13102
13342
  let taskRewarded = 0;
13103
13343
  for (const runId of runIds) {
13104
- const { memoriesRewarded } = await _internals16.applyCouncilReward(provider, {
13344
+ const { memoriesRewarded } = await _internals17.applyCouncilReward(provider, {
13105
13345
  runId,
13106
13346
  unitId: taskId,
13107
13347
  reward: FINALIZE_NEGATIVE_TERMINAL_REWARD,
@@ -13127,7 +13367,7 @@ async function runFinalizeRewardSweep(args) {
13127
13367
  }
13128
13368
  return result;
13129
13369
  }
13130
- var _internals16 = {
13370
+ var _internals17 = {
13131
13371
  createConfiguredMemoryProvider,
13132
13372
  applyCouncilReward
13133
13373
  };
@@ -14154,7 +14394,7 @@ async function reconcileStaleActiveSkills(directory, options = {}) {
14154
14394
  continue;
14155
14395
  }
14156
14396
  try {
14157
- const regen = await _internals17.regenerateSkill(directory, skill.slug, {
14397
+ const regen = await _internals18.regenerateSkill(directory, skill.slug, {
14158
14398
  evaluate: false
14159
14399
  });
14160
14400
  if (regen.regenerated) {
@@ -14404,7 +14644,7 @@ async function runSkillImprover(req) {
14404
14644
  autoApply
14405
14645
  };
14406
14646
  }
14407
- var _internals17 = {
14647
+ var _internals18 = {
14408
14648
  runSkillImprover,
14409
14649
  buildDeterministicProposal,
14410
14650
  buildLLMProposalFrame,
@@ -14807,13 +15047,13 @@ var write_retro = createSwarmTool({
14807
15047
  task_id: args.task_id !== undefined ? String(args.task_id) : undefined,
14808
15048
  metadata: args.metadata
14809
15049
  };
14810
- return await _internals18.executeWriteRetro(writeRetroArgs, directory);
15050
+ return await _internals19.executeWriteRetro(writeRetroArgs, directory);
14811
15051
  } catch {
14812
15052
  return JSON.stringify({ success: false, phase: rawPhase, message: "Invalid arguments" }, null, 2);
14813
15053
  }
14814
15054
  }
14815
15055
  });
14816
- var _internals18 = {
15056
+ var _internals19 = {
14817
15057
  executeWriteRetro,
14818
15058
  write_retro
14819
15059
  };
@@ -15112,8 +15352,8 @@ async function runFinalizeStage(ctx) {
15112
15352
  ];
15113
15353
  ctx.curationSucceeded = false;
15114
15354
  try {
15115
- ctx.curationResult = await _internals19.curateAndStoreSwarm(ctx.allLessons, ctx.projectName, { phase_number: 0 }, ctx.directory, ctx.config, {
15116
- llmDelegate: _internals19.createCuratorLLMDelegate(ctx.directory, "phase", ctx.options.sessionID),
15355
+ ctx.curationResult = await _internals20.curateAndStoreSwarm(ctx.allLessons, ctx.projectName, { phase_number: 0 }, ctx.directory, ctx.config, {
15356
+ llmDelegate: _internals20.createCuratorLLMDelegate(ctx.directory, "phase", ctx.options.sessionID),
15117
15357
  enrichmentQuota: {
15118
15358
  maxCalls: ctx.config.enrichment.max_calls_per_day,
15119
15359
  window: ctx.config.enrichment.quota_window
@@ -15132,7 +15372,7 @@ async function runFinalizeStage(ctx) {
15132
15372
  if (ctx.config.hive_enabled === false) {} else {
15133
15373
  try {
15134
15374
  const entries = await readKnowledge(resolveSwarmKnowledgePath(ctx.directory));
15135
- const result = await _internals19.checkHivePromotions(entries, ctx.config);
15375
+ const result = await _internals20.checkHivePromotions(entries, ctx.config);
15136
15376
  ctx.hivePromoted = result.new_promotions;
15137
15377
  } catch (hiveErr) {
15138
15378
  const msg = hiveErr instanceof Error ? hiveErr.message : String(hiveErr);
@@ -15153,7 +15393,7 @@ async function runFinalizeStage(ctx) {
15153
15393
  ctx.knowledgeSkillHint = ctx.sessionKnowledgeCreated > 0 ? `${ctx.sessionKnowledgeCreated} knowledge entries created this session. Consider running skill_improve or skill_generate to compile mature entries into skills.` : "";
15154
15394
  if (ctx.runSkillReview) {
15155
15395
  try {
15156
- const { config: loadedConfig } = _internals19.loadPluginConfigWithMeta(ctx.directory);
15396
+ const { config: loadedConfig } = _internals20.loadPluginConfigWithMeta(ctx.directory);
15157
15397
  const skillImproverConfig = SkillImproverConfigSchema.parse(loadedConfig.skill_improver ?? {});
15158
15398
  const skillReviewResult = await runAbortableSkillReview({
15159
15399
  directory: ctx.directory,
@@ -15216,7 +15456,7 @@ async function runFinalizeStage(ctx) {
15216
15456
  }
15217
15457
  if (!ctx.planAlreadyDone || ctx.guaranteeResult.closedPhaseIds.length > 0 || ctx.guaranteeResult.closedTaskIds.length > 0) {
15218
15458
  try {
15219
- await _internals19.closePlanTerminalState(ctx.directory, ctx.planData, {
15459
+ await _internals20.closePlanTerminalState(ctx.directory, ctx.planData, {
15220
15460
  closedPhaseIds: ctx.guaranteeResult.closedPhaseIds,
15221
15461
  closedTaskIds: ctx.guaranteeResult.closedTaskIds,
15222
15462
  originalStatuses: ctx.originalStatuses
@@ -15233,11 +15473,11 @@ async function runFinalizeStage(ctx) {
15233
15473
  }
15234
15474
  try {
15235
15475
  const { CuratorConfigSchema: CCS } = await import("./schema-e5kd993s.js");
15236
- const { config: pmLoadedConfig } = _internals19.loadPluginConfigWithMeta(ctx.directory);
15476
+ const { config: pmLoadedConfig } = _internals20.loadPluginConfigWithMeta(ctx.directory);
15237
15477
  const curatorCfg = CCS.parse(pmLoadedConfig.curator ?? {});
15238
15478
  if (curatorCfg.enabled && curatorCfg.postmortem_enabled) {
15239
- const pmResult = await _internals19.runCuratorPostMortem(ctx.directory, {
15240
- llmDelegate: _internals19.createCuratorLLMDelegate(ctx.directory, "postmortem", ctx.options.sessionID),
15479
+ const pmResult = await _internals20.runCuratorPostMortem(ctx.directory, {
15480
+ llmDelegate: _internals20.createCuratorLLMDelegate(ctx.directory, "postmortem", ctx.options.sessionID),
15241
15481
  scope: "project",
15242
15482
  sessionID: ctx.options.sessionID
15243
15483
  });
@@ -15263,7 +15503,7 @@ async function copySqliteSafe(srcPath, destPath, laneEnv) {
15263
15503
  }
15264
15504
  let checkpointVerified = false;
15265
15505
  try {
15266
- const result = _internals19.spawnSync("sqlite3", [srcPath, "PRAGMA wal_checkpoint(TRUNCATE);"], {
15506
+ const result = _internals20.spawnSync("sqlite3", [srcPath, "PRAGMA wal_checkpoint(TRUNCATE);"], {
15267
15507
  cwd: path29.dirname(srcPath),
15268
15508
  encoding: "utf-8",
15269
15509
  stdio: ["ignore", "pipe", "pipe"],
@@ -15434,7 +15674,7 @@ async function runArchiveEvidenceRetention(ctx) {
15434
15674
  let maxAgeDays = 30;
15435
15675
  let maxBundles = 10;
15436
15676
  try {
15437
- const { config: evidenceLoadedConfig } = _internals19.loadPluginConfigWithMeta(ctx.directory);
15677
+ const { config: evidenceLoadedConfig } = _internals20.loadPluginConfigWithMeta(ctx.directory);
15438
15678
  const evidenceCfg = evidenceLoadedConfig.evidence ?? {};
15439
15679
  if (typeof evidenceCfg.max_age_days === "number") {
15440
15680
  maxAgeDays = evidenceCfg.max_age_days;
@@ -15444,7 +15684,7 @@ async function runArchiveEvidenceRetention(ctx) {
15444
15684
  }
15445
15685
  } catch {}
15446
15686
  try {
15447
- await _internals19.archiveEvidence(ctx.directory, maxAgeDays, maxBundles);
15687
+ await _internals20.archiveEvidence(ctx.directory, maxAgeDays, maxBundles);
15448
15688
  } catch (error2) {
15449
15689
  const msg = error2 instanceof Error ? error2.message : String(error2);
15450
15690
  ctx.warnings.push(`Evidence retention archive failed: ${msg}`);
@@ -15645,9 +15885,9 @@ async function runAlignStage(ctx) {
15645
15885
  const pruneBranches = ctx.args.includes("--prune-branches");
15646
15886
  let gitAlignResult = "";
15647
15887
  const prunedBranches = [];
15648
- const gitStatus = _internals19.getGitRepositoryStatus(ctx.directory);
15888
+ const gitStatus = _internals20.getGitRepositoryStatus(ctx.directory);
15649
15889
  if (gitStatus.isRepo) {
15650
- const aggressiveResult = await _internals19.resetToMainAfterMerge(ctx.directory, {
15890
+ const aggressiveResult = await _internals20.resetToMainAfterMerge(ctx.directory, {
15651
15891
  pruneBranches
15652
15892
  });
15653
15893
  if (aggressiveResult.success) {
@@ -15659,7 +15899,7 @@ async function runAlignStage(ctx) {
15659
15899
  ctx.warnings.push("Uncommitted changes were discarded during git alignment");
15660
15900
  }
15661
15901
  } else {
15662
- const alignResult = await _internals19.resetToRemoteBranch(ctx.directory, {
15902
+ const alignResult = await _internals20.resetToRemoteBranch(ctx.directory, {
15663
15903
  pruneBranches
15664
15904
  });
15665
15905
  gitAlignResult = alignResult.message;
@@ -15719,7 +15959,7 @@ async function handleCloseCommand(directory, args, options = {}) {
15719
15959
  let finalizeLock = {
15720
15960
  acquired: false
15721
15961
  };
15722
- finalizeLock = await _internals19.acquireFinalizeLock(directory);
15962
+ finalizeLock = await _internals20.acquireFinalizeLock(directory);
15723
15963
  if (!finalizeLock.acquired) {
15724
15964
  return `\u274C Another /swarm finalize is already running for this project. If you are certain no other run is active, wait for the lock to expire or remove the stale lock and retry.`;
15725
15965
  }
@@ -15750,7 +15990,7 @@ This project was already finalized in a previous /swarm close run. The plan has
15750
15990
  if (planExists) {
15751
15991
  planAlreadyDone = phases.length > 0 && phases.every((p) => p.status === "complete" || p.status === "completed" || p.status === "blocked" || p.status === "closed");
15752
15992
  }
15753
- const { config: loadedConfig } = _internals19.loadPluginConfigWithMeta(directory);
15993
+ const { config: loadedConfig } = _internals20.loadPluginConfigWithMeta(directory);
15754
15994
  const config = KnowledgeConfigSchema.parse(loadedConfig.knowledge ?? {});
15755
15995
  const ctx = {
15756
15996
  directory,
@@ -15794,7 +16034,7 @@ This project was already finalized in a previous /swarm close run. The plan has
15794
16034
  args
15795
16035
  };
15796
16036
  await runFinalizeStage(ctx);
15797
- await _internals19.runFinalizeRewardSweep({
16037
+ await _internals20.runFinalizeRewardSweep({
15798
16038
  directory,
15799
16039
  closedTaskIds: ctx.guaranteeResult.closedTaskIds,
15800
16040
  memoryConfig: loadedConfig.memory
@@ -15875,9 +16115,9 @@ This project was already finalized in a previous /swarm close run. The plan has
15875
16115
  }
15876
16116
  const sessionIdsToEnd = [...swarmState.agentSessions.keys()];
15877
16117
  for (const sessionId of sessionIdsToEnd) {
15878
- _internals19.endAgentSession(sessionId);
16118
+ _internals20.endAgentSession(sessionId);
15879
16119
  }
15880
- _internals19.resetSwarmStatePreservingSingletons();
16120
+ _internals20.resetSwarmStatePreservingSingletons();
15881
16121
  const retroWarnings = ctx.warnings.filter((w) => w.includes("Retrospective write") || w.includes("retrospective write") || w.includes("Session retrospective"));
15882
16122
  const otherWarnings = ctx.warnings.filter((w) => !w.includes("Retrospective write") && !w.includes("retrospective write") && !w.includes("Session retrospective"));
15883
16123
  let warningMsg = "";
@@ -15946,7 +16186,7 @@ async function acquireFinalizeLock(directory) {
15946
16186
  }
15947
16187
  return { acquired: false };
15948
16188
  }
15949
- var _internals19 = {
16189
+ var _internals20 = {
15950
16190
  ACTIVE_STATE_DIRS_TO_CLEAN,
15951
16191
  countSessionKnowledgeEntries,
15952
16192
  CLOSE_SKILL_REVIEW_TIMEOUT_MS,
@@ -16793,9 +17033,9 @@ async function detectDarkMatter(directory, options) {
16793
17033
  } catch {
16794
17034
  return [];
16795
17035
  }
16796
- const commitMap = await _internals20.parseGitLog(directory, maxCommitsToAnalyze);
16797
- const matrix = _internals20.buildCoChangeMatrix(commitMap, maxFilesPerCommit);
16798
- const staticEdges = await _internals20.getStaticEdges(directory);
17036
+ const commitMap = await _internals21.parseGitLog(directory, maxCommitsToAnalyze);
17037
+ const matrix = _internals21.buildCoChangeMatrix(commitMap, maxFilesPerCommit);
17038
+ const staticEdges = await _internals21.getStaticEdges(directory);
16799
17039
  const results = [];
16800
17040
  for (const entry of matrix.values()) {
16801
17041
  const key = `${entry.fileA}::${entry.fileB}`;
@@ -16911,11 +17151,11 @@ var co_change_analyzer = createSwarmTool({
16911
17151
  npmiThreshold,
16912
17152
  maxCommitsToAnalyze
16913
17153
  };
16914
- const pairs = await _internals20.detectDarkMatter(directory, options);
16915
- return _internals20.formatDarkMatterOutput(pairs);
17154
+ const pairs = await _internals21.detectDarkMatter(directory, options);
17155
+ return _internals21.formatDarkMatterOutput(pairs);
16916
17156
  }
16917
17157
  });
16918
- var _internals20 = {
17158
+ var _internals21 = {
16919
17159
  parseGitLog,
16920
17160
  buildCoChangeMatrix,
16921
17161
  getStaticEdges,
@@ -16932,7 +17172,7 @@ var DEFAULT_MAX_COMMITS = 500;
16932
17172
  var cache = new Map;
16933
17173
  async function readGitHead(directory) {
16934
17174
  try {
16935
- const { stdout } = await _internals21.execFile("git", ["rev-parse", "HEAD"], {
17175
+ const { stdout } = await _internals22.execFile("git", ["rev-parse", "HEAD"], {
16936
17176
  cwd: directory,
16937
17177
  timeout: GIT_HEAD_TIMEOUT_MS
16938
17178
  });
@@ -16958,9 +17198,9 @@ async function getCoChangeData(directory, options) {
16958
17198
  let entries;
16959
17199
  let commitsObserved;
16960
17200
  try {
16961
- const commitMap = await _internals21.parseGitLog(directory, maxCommits);
17201
+ const commitMap = await _internals22.parseGitLog(directory, maxCommits);
16962
17202
  commitsObserved = commitMap.size;
16963
- const matrix = _internals21.buildCoChangeMatrix(commitMap);
17203
+ const matrix = _internals22.buildCoChangeMatrix(commitMap);
16964
17204
  entries = Array.from(matrix.values());
16965
17205
  } catch {
16966
17206
  return { pairs: [], commitsObserved: 0 };
@@ -16984,10 +17224,10 @@ async function getCoChangePairs(directory, options) {
16984
17224
  const data = await getCoChangeData(directory, options);
16985
17225
  return data.pairs;
16986
17226
  }
16987
- var _internals21 = {
17227
+ var _internals22 = {
16988
17228
  execFile: execFileAsync,
16989
- parseGitLog: _internals20.parseGitLog,
16990
- buildCoChangeMatrix: _internals20.buildCoChangeMatrix
17229
+ parseGitLog: _internals21.parseGitLog,
17230
+ buildCoChangeMatrix: _internals21.buildCoChangeMatrix
16991
17231
  };
16992
17232
 
16993
17233
  // src/turbo/epic/cochange-conflict.ts
@@ -17269,7 +17509,7 @@ async function handleCouplingCommand(directory, args) {
17269
17509
 
17270
17510
  Usage: /swarm coupling [--phase <n>] [--threshold <-1..1>] [--min-co-changes <n>] [--format markdown|json] [--persist]`;
17271
17511
  }
17272
- const plan = await _internals22.loadPlanJsonOnly(directory);
17512
+ const plan = await _internals23.loadPlanJsonOnly(directory);
17273
17513
  if (plan === null) {
17274
17514
  return "No plan found at `.swarm/plan.json`. Run `/swarm plan` to create one before measuring coupling.";
17275
17515
  }
@@ -17293,7 +17533,7 @@ Usage: /swarm coupling [--phase <n>] [--threshold <-1..1>] [--min-co-changes <n>
17293
17533
  const scope = scopeFiles ?? task.files_touched ?? [];
17294
17534
  return { id: task.id, scope };
17295
17535
  });
17296
- const cochangePairs = await _internals22.getCoChangePairs(directory);
17536
+ const cochangePairs = await _internals23.getCoChangePairs(directory);
17297
17537
  const report = computeCouplingReport(tasks, cochangePairs, {
17298
17538
  npmi: parsed.threshold,
17299
17539
  minCoChanges: parsed.minCoChanges
@@ -17332,13 +17572,13 @@ _Warning: failed to persist report (${persistStatus.error})._`;
17332
17572
  }
17333
17573
  return `${formatCouplingReportMarkdown(report)}${persistTrailer}`;
17334
17574
  }
17335
- var _internals22 = {
17575
+ var _internals23 = {
17336
17576
  loadPlanJsonOnly,
17337
17577
  getCoChangePairs
17338
17578
  };
17339
17579
 
17340
17580
  // src/commands/curate.ts
17341
- var _internals23 = {
17581
+ var _internals24 = {
17342
17582
  checkHivePromotions,
17343
17583
  readKnowledge,
17344
17584
  resolveSwarmKnowledgePath,
@@ -17346,8 +17586,8 @@ var _internals23 = {
17346
17586
  loadCuratorDeps: async () => {
17347
17587
  const [{ CuratorConfigSchema }, curator, { createCuratorLLMDelegate: createCuratorLLMDelegate2 }] = await Promise.all([
17348
17588
  import("./schema-e5kd993s.js"),
17349
- import("./curator-ckzb8ww4.js"),
17350
- import("./curator-llm-factory-mhjcpy1s.js")
17589
+ import("./curator-nh9raf1a.js"),
17590
+ import("./curator-llm-factory-b3g0g0cd.js")
17351
17591
  ]);
17352
17592
  return { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 };
17353
17593
  }
@@ -17355,15 +17595,15 @@ var _internals23 = {
17355
17595
  async function handleCurateCommand(directory, _args, options) {
17356
17596
  try {
17357
17597
  const config = KnowledgeConfigSchema.parse({});
17358
- const swarmPath = _internals23.resolveSwarmKnowledgePath(directory);
17359
- const swarmEntries = await _internals23.readKnowledge(swarmPath) ?? [];
17360
- const summary = await _internals23.checkHivePromotions(swarmEntries, config);
17598
+ const swarmPath = _internals24.resolveSwarmKnowledgePath(directory);
17599
+ const swarmEntries = await _internals24.readKnowledge(swarmPath) ?? [];
17600
+ const summary = await _internals24.checkHivePromotions(swarmEntries, config);
17361
17601
  if (options?.sessionID) {
17362
17602
  let onDemandPhase = 1;
17363
17603
  try {
17364
- const { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 } = await _internals23.loadCuratorDeps();
17604
+ const { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 } = await _internals24.loadCuratorDeps();
17365
17605
  const curatorConfig = CuratorConfigSchema.parse({});
17366
- const priorSummary = await _internals23.readSwarmFileAsync(directory, "curator-summary.json");
17606
+ const priorSummary = await _internals24.readSwarmFileAsync(directory, "curator-summary.json");
17367
17607
  if (priorSummary) {
17368
17608
  try {
17369
17609
  const parsed = JSON.parse(priorSummary);
@@ -17374,7 +17614,7 @@ async function handleCurateCommand(directory, _args, options) {
17374
17614
  }
17375
17615
  let planPhaseCount = Infinity;
17376
17616
  try {
17377
- const planRaw = await _internals23.readSwarmFileAsync(directory, "plan.json");
17617
+ const planRaw = await _internals24.readSwarmFileAsync(directory, "plan.json");
17378
17618
  if (planRaw) {
17379
17619
  const plan = JSON.parse(planRaw);
17380
17620
  if (Array.isArray(plan.phases))
@@ -17393,8 +17633,8 @@ async function handleCurateCommand(directory, _args, options) {
17393
17633
  summary.knowledge_skipped = applied.skipped;
17394
17634
  summary.curator_phase = onDemandPhase;
17395
17635
  try {
17396
- const updatedEntries = await _internals23.readKnowledge(swarmPath) ?? [];
17397
- const postUpdateHive = await _internals23.checkHivePromotions(updatedEntries, config);
17636
+ const updatedEntries = await _internals24.readKnowledge(swarmPath) ?? [];
17637
+ const postUpdateHive = await _internals24.checkHivePromotions(updatedEntries, config);
17398
17638
  summary.new_promotions += postUpdateHive.new_promotions;
17399
17639
  summary.encounters_incremented += postUpdateHive.encounters_incremented;
17400
17640
  summary.advancements += postUpdateHive.advancements;
@@ -17459,7 +17699,7 @@ async function handleDarkMatterCommand(directory, args) {
17459
17699
  }
17460
17700
  let pairs;
17461
17701
  try {
17462
- pairs = await _internals20.detectDarkMatter(directory, options);
17702
+ pairs = await _internals21.detectDarkMatter(directory, options);
17463
17703
  } catch (err) {
17464
17704
  const errMsg = err instanceof Error ? err.message : String(err);
17465
17705
  return `## Dark Matter Analysis Failed
@@ -17843,7 +18083,7 @@ import { fileURLToPath } from "url";
17843
18083
  // package.json
17844
18084
  var package_default = {
17845
18085
  name: "opencode-swarm",
17846
- version: "7.113.3",
18086
+ version: "7.113.4",
17847
18087
  description: "Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",
17848
18088
  main: "dist/index.js",
17849
18089
  types: "dist/index.d.ts",
@@ -18296,7 +18536,7 @@ function resolveCachePackageRoot(cachePath) {
18296
18536
  const nestedPackageRoot = path36.join(cachePath, "node_modules", "opencode-swarm");
18297
18537
  return existsSync23(nestedPackageRoot) ? nestedPackageRoot : cachePath;
18298
18538
  }
18299
- var _internals24 = {
18539
+ var _internals25 = {
18300
18540
  detectSandboxCapability: () => sandboxCapabilityProbe.detect(),
18301
18541
  getSandboxExecutor: getExecutor
18302
18542
  };
@@ -18880,9 +19120,9 @@ async function checkCurator(directory) {
18880
19120
  }
18881
19121
  async function getSandboxStatus() {
18882
19122
  try {
18883
- const capability = await _internals24.detectSandboxCapability();
19123
+ const capability = await _internals25.detectSandboxCapability();
18884
19124
  const mechanism = capability.mechanism ?? "none";
18885
- const executor = await _internals24.getSandboxExecutor();
19125
+ const executor = await _internals25.getSandboxExecutor();
18886
19126
  const hasExecutor = executor !== null;
18887
19127
  if (hasExecutor) {
18888
19128
  const executorStrength = executor?.strength;
@@ -19634,7 +19874,7 @@ function readPromotionEvidence(directory) {
19634
19874
  }
19635
19875
 
19636
19876
  // src/commands/epic.ts
19637
- var _internals25 = {
19877
+ var _internals26 = {
19638
19878
  loadPluginConfigWithMeta,
19639
19879
  loadPlanJsonOnly,
19640
19880
  getCoChangeData,
@@ -19656,7 +19896,7 @@ async function handleEpicCommand(directory, args, sessionID) {
19656
19896
  if (!sessionID || sessionID.trim() === "") {
19657
19897
  return "Error: No active session context. Epic Mode requires an active session. Use /swarm epic from within an OpenCode session.";
19658
19898
  }
19659
- const session = _internals25.ensureAgentSession(sessionID, undefined, directory);
19899
+ const session = _internals26.ensureAgentSession(sessionID, undefined, directory);
19660
19900
  const arg0 = args[0]?.toLowerCase();
19661
19901
  switch (arg0) {
19662
19902
  case "status":
@@ -19683,7 +19923,7 @@ Usage:
19683
19923
  }
19684
19924
  function enableAndAck(directory, sessionID, session) {
19685
19925
  try {
19686
- _internals25.enableEpicMode(directory, sessionID);
19926
+ _internals26.enableEpicMode(directory, sessionID);
19687
19927
  } catch (err) {
19688
19928
  return `Error enabling Epic Mode: ${err instanceof Error ? err.message : String(err)}`;
19689
19929
  }
@@ -19699,7 +19939,7 @@ function enableAndAck(directory, sessionID, session) {
19699
19939
  }
19700
19940
  function disableAndAck(directory, sessionID, session) {
19701
19941
  try {
19702
- _internals25.disableEpicMode(directory, sessionID);
19942
+ _internals26.disableEpicMode(directory, sessionID);
19703
19943
  } catch (err) {
19704
19944
  return `Error disabling Epic Mode: ${err instanceof Error ? err.message : String(err)}`;
19705
19945
  }
@@ -19708,12 +19948,12 @@ function disableAndAck(directory, sessionID, session) {
19708
19948
  }
19709
19949
  function renderStatus(directory, sessionID) {
19710
19950
  const lines = ["## Epic Mode \u2014 Status", ""];
19711
- if (_internals25.isStateUnreadable(directory)) {
19951
+ if (_internals26.isStateUnreadable(directory)) {
19712
19952
  lines.push("**Epic Mode state is unreadable** (`.swarm/epic-state.json` is corrupt or has an unexpected shape). Status cannot be reported until the file is repaired or removed. The fail-closed marker means `epic_decide_phase` will refuse to compute a verdict in this state.");
19713
19953
  return lines.join(`
19714
19954
  `);
19715
19955
  }
19716
- const state = _internals25.loadEpicSessionState(directory, sessionID);
19956
+ const state = _internals26.loadEpicSessionState(directory, sessionID);
19717
19957
  if (!state) {
19718
19958
  lines.push("Epic Mode has not been toggled for this session.");
19719
19959
  return lines.join(`
@@ -19765,7 +20005,7 @@ function formatGreenfieldDetail(input) {
19765
20005
  function renderLast(directory) {
19766
20006
  let records;
19767
20007
  try {
19768
- records = _internals25.readPromotionEvidence(directory);
20008
+ records = _internals26.readPromotionEvidence(directory);
19769
20009
  } catch (err) {
19770
20010
  return `Error reading epic-promotions.jsonl: ${err instanceof Error ? err.message : String(err)}`;
19771
20011
  }
@@ -19820,7 +20060,7 @@ function renderLast(directory) {
19820
20060
  `);
19821
20061
  }
19822
20062
  function renderCalibration(directory) {
19823
- if (_internals25.isCalibrationStateUnreadable(directory)) {
20063
+ if (_internals26.isCalibrationStateUnreadable(directory)) {
19824
20064
  return [
19825
20065
  "## Epic Mode \u2014 Calibration",
19826
20066
  "",
@@ -19832,11 +20072,11 @@ function renderCalibration(directory) {
19832
20072
  }
19833
20073
  let state;
19834
20074
  try {
19835
- state = _internals25.loadCalibrationState(directory);
20075
+ state = _internals26.loadCalibrationState(directory);
19836
20076
  } catch (err) {
19837
20077
  return `Error reading calibration state: ${err instanceof Error ? err.message : String(err)}`;
19838
20078
  }
19839
- const { config } = _internals25.loadPluginConfigWithMeta(directory);
20079
+ const { config } = _internals26.loadPluginConfigWithMeta(directory);
19840
20080
  const staticThreshold = config.turbo?.epic?.mode?.activation_threshold ?? 0.3;
19841
20081
  const calibrationCfg = config.turbo?.epic?.calibration;
19842
20082
  const loosenWindow = calibrationCfg?.loosen_window ?? 10;
@@ -19884,7 +20124,7 @@ function renderCalibration(directory) {
19884
20124
  lines.push("");
19885
20125
  let recentDivergent = [];
19886
20126
  try {
19887
- const all = _internals25.readDivergenceHistory(directory, { limit: 50 });
20127
+ const all = _internals26.readDivergenceHistory(directory, { limit: 50 });
19888
20128
  recentDivergent = all.filter((r) => !r.isClean).slice(-5);
19889
20129
  } catch {}
19890
20130
  lines.push("### Recent divergent tasks (tightened the threshold)");
@@ -19901,11 +20141,11 @@ function renderCalibration(directory) {
19901
20141
  `);
19902
20142
  }
19903
20143
  async function renderDecide(directory) {
19904
- const plan = await _internals25.loadPlanJsonOnly(directory);
20144
+ const plan = await _internals26.loadPlanJsonOnly(directory);
19905
20145
  if (!plan) {
19906
20146
  return "No plan found at `.swarm/plan.json`. Run `/swarm plan` first.";
19907
20147
  }
19908
- const { config } = _internals25.loadPluginConfigWithMeta(directory);
20148
+ const { config } = _internals26.loadPluginConfigWithMeta(directory);
19909
20149
  const modeCfg = config.turbo?.epic?.mode;
19910
20150
  const cochangeCfg = config.turbo?.epic?.cochange;
19911
20151
  const activationThreshold = modeCfg?.activation_threshold ?? 0.3;
@@ -19915,20 +20155,20 @@ async function renderDecide(directory) {
19915
20155
  const tasks = [];
19916
20156
  for (const phase of plan.phases) {
19917
20157
  for (const task of phase.tasks) {
19918
- const scopeFiles = _internals25.readTaskScopes(directory, task.id);
20158
+ const scopeFiles = _internals26.readTaskScopes(directory, task.id);
19919
20159
  const scope = scopeFiles ?? task.files_touched ?? [];
19920
20160
  tasks.push({ id: task.id, scope });
19921
20161
  }
19922
20162
  }
19923
- const { pairs, commitsObserved } = await _internals25.getCoChangeData(directory);
20163
+ const { pairs, commitsObserved } = await _internals26.getCoChangeData(directory);
19924
20164
  const isGitProject = (() => {
19925
20165
  try {
19926
- return _internals25.isGitRepo(directory);
20166
+ return _internals26.isGitRepo(directory);
19927
20167
  } catch {
19928
20168
  return false;
19929
20169
  }
19930
20170
  })();
19931
- const verdict = _internals25.decideEpicActivation(tasks, pairs, commitsObserved, {
20171
+ const verdict = _internals26.decideEpicActivation(tasks, pairs, commitsObserved, {
19932
20172
  activationThreshold,
19933
20173
  minCommitsForSignal,
19934
20174
  cochangeNpmiThreshold,
@@ -19972,7 +20212,7 @@ function formatVerdict(verdict) {
19972
20212
  }
19973
20213
 
19974
20214
  // src/services/evidence-service.ts
19975
- var _internals26 = {
20215
+ var _internals27 = {
19976
20216
  loadEvidence,
19977
20217
  listEvidenceTaskIds
19978
20218
  };
@@ -20017,7 +20257,7 @@ function getVerdictEmoji(verdict) {
20017
20257
  return getVerdictIcon(verdict);
20018
20258
  }
20019
20259
  async function getTaskEvidenceData(directory, taskId) {
20020
- const result = await _internals26.loadEvidence(directory, taskId);
20260
+ const result = await _internals27.loadEvidence(directory, taskId);
20021
20261
  if (result.status !== "found") {
20022
20262
  return {
20023
20263
  hasEvidence: false,
@@ -20040,13 +20280,13 @@ async function getTaskEvidenceData(directory, taskId) {
20040
20280
  };
20041
20281
  }
20042
20282
  async function getEvidenceListData(directory) {
20043
- const taskIds = await _internals26.listEvidenceTaskIds(directory);
20283
+ const taskIds = await _internals27.listEvidenceTaskIds(directory);
20044
20284
  if (taskIds.length === 0) {
20045
20285
  return { hasEvidence: false, tasks: [] };
20046
20286
  }
20047
20287
  const tasks = [];
20048
20288
  for (const taskId of taskIds) {
20049
- const result = await _internals26.loadEvidence(directory, taskId);
20289
+ const result = await _internals27.loadEvidence(directory, taskId);
20050
20290
  if (result.status === "found") {
20051
20291
  tasks.push({
20052
20292
  taskId,
@@ -20674,7 +20914,7 @@ function extractCurrentPhaseFromPlan(plan) {
20674
20914
  if (!plan) {
20675
20915
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
20676
20916
  }
20677
- if (!_internals27.validatePlanPhases(plan)) {
20917
+ if (!_internals28.validatePlanPhases(plan)) {
20678
20918
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
20679
20919
  }
20680
20920
  let currentPhase = null;
@@ -20816,9 +21056,9 @@ function extractPhaseMetrics(content) {
20816
21056
  async function getHandoffData(directory) {
20817
21057
  const now = new Date().toISOString();
20818
21058
  const sessionContent = await readSwarmFileAsync(directory, "session/state.json");
20819
- const sessionState = _internals27.parseSessionState(sessionContent);
21059
+ const sessionState = _internals28.parseSessionState(sessionContent);
20820
21060
  const plan = await loadPlanJsonOnly(directory);
20821
- const planInfo = _internals27.extractCurrentPhaseFromPlan(plan);
21061
+ const planInfo = _internals28.extractCurrentPhaseFromPlan(plan);
20822
21062
  if (!plan) {
20823
21063
  const planMdContent = await readSwarmFileAsync(directory, "plan.md");
20824
21064
  if (planMdContent) {
@@ -20837,8 +21077,8 @@ async function getHandoffData(directory) {
20837
21077
  }
20838
21078
  }
20839
21079
  const contextContent = await readSwarmFileAsync(directory, "context.md");
20840
- const recentDecisions = _internals27.extractDecisions(contextContent);
20841
- const rawPhaseMetrics = _internals27.extractPhaseMetrics(contextContent);
21080
+ const recentDecisions = _internals28.extractDecisions(contextContent);
21081
+ const rawPhaseMetrics = _internals28.extractPhaseMetrics(contextContent);
20842
21082
  const phaseMetrics = sanitizeString(rawPhaseMetrics, 1000);
20843
21083
  let delegationState = null;
20844
21084
  if (sessionState?.delegationState) {
@@ -21002,7 +21242,7 @@ ${lines.join(`
21002
21242
  `)}
21003
21243
  \`\`\``;
21004
21244
  }
21005
- var _internals27 = {
21245
+ var _internals28 = {
21006
21246
  getHandoffData,
21007
21247
  formatHandoffMarkdown,
21008
21248
  formatContinuationPrompt,
@@ -21151,15 +21391,15 @@ async function writeSnapshot(directory, state) {
21151
21391
  }
21152
21392
  function createSnapshotWriterHook(directory) {
21153
21393
  return (_input, _output) => {
21154
- _writeInFlight = _writeInFlight.then(() => _internals28.writeSnapshot(directory, swarmState), () => _internals28.writeSnapshot(directory, swarmState));
21394
+ _writeInFlight = _writeInFlight.then(() => _internals29.writeSnapshot(directory, swarmState), () => _internals29.writeSnapshot(directory, swarmState));
21155
21395
  return _writeInFlight;
21156
21396
  };
21157
21397
  }
21158
21398
  async function flushPendingSnapshot(directory) {
21159
- _writeInFlight = _writeInFlight.then(() => _internals28.writeSnapshot(directory, swarmState), () => _internals28.writeSnapshot(directory, swarmState));
21399
+ _writeInFlight = _writeInFlight.then(() => _internals29.writeSnapshot(directory, swarmState), () => _internals29.writeSnapshot(directory, swarmState));
21160
21400
  await _writeInFlight;
21161
21401
  }
21162
- var _internals28 = {
21402
+ var _internals29 = {
21163
21403
  writeSnapshot,
21164
21404
  createSnapshotWriterHook,
21165
21405
  flushPendingSnapshot
@@ -21367,7 +21607,7 @@ var IPV4_PRIVATE_192 = /^192\.168\./;
21367
21607
  var IPV4_ZERO_NETWORK = /^0\./;
21368
21608
  var IPV6_LINK_LOCAL = /^fe80:/i;
21369
21609
  var IPV6_UNIQUE_LOCAL = /^f[cd][0-9a-f]{2}:/i;
21370
- var _internals29 = {
21610
+ var _internals30 = {
21371
21611
  spawnSync: (cmd, args, options) => {
21372
21612
  const mergedEnv = mergeEnvForChild(options?.env, options?.envOverrides);
21373
21613
  return child_process6.spawnSync(cmd, args, {
@@ -21485,7 +21725,7 @@ function validateAndSanitizeGithubUrl(rawUrl, resource) {
21485
21725
  }
21486
21726
  function detectGitRemote(cwd, laneEnv) {
21487
21727
  try {
21488
- const result = _internals29.spawnSync("git", ["remote", "get-url", "origin"], {
21728
+ const result = _internals30.spawnSync("git", ["remote", "get-url", "origin"], {
21489
21729
  encoding: "utf-8",
21490
21730
  stdio: ["ignore", "pipe", "pipe"],
21491
21731
  timeout: 5000,
@@ -21662,7 +21902,7 @@ import * as path42 from "path";
21662
21902
  async function migrateKnowledgeToExternal(_directory, _config) {
21663
21903
  const externalSentinelPath = path42.join(_directory, ".swarm", ".knowledge-external-migrated");
21664
21904
  const contextPath = path42.join(_directory, ".swarm", "context.md");
21665
- if (_internals30.existsSync(externalSentinelPath)) {
21905
+ if (_internals31.existsSync(externalSentinelPath)) {
21666
21906
  return {
21667
21907
  migrated: false,
21668
21908
  entriesMigrated: 0,
@@ -21671,7 +21911,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
21671
21911
  skippedReason: "external-sentinel-exists"
21672
21912
  };
21673
21913
  }
21674
- if (!_internals30.existsSync(contextPath)) {
21914
+ if (!_internals31.existsSync(contextPath)) {
21675
21915
  return {
21676
21916
  migrated: false,
21677
21917
  entriesMigrated: 0,
@@ -21680,7 +21920,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
21680
21920
  skippedReason: "no-context-file"
21681
21921
  };
21682
21922
  }
21683
- const contextContent = await _internals30.readFile(contextPath, "utf-8");
21923
+ const contextContent = await _internals31.readFile(contextPath, "utf-8");
21684
21924
  if (contextContent.trim().length === 0) {
21685
21925
  return {
21686
21926
  migrated: false,
@@ -21698,7 +21938,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
21698
21938
  entriesCount++;
21699
21939
  }
21700
21940
  }
21701
- await _internals30.writeSentinel(externalSentinelPath, entriesCount, entriesCount);
21941
+ await _internals31.writeSentinel(externalSentinelPath, entriesCount, entriesCount);
21702
21942
  return {
21703
21943
  migrated: true,
21704
21944
  entriesMigrated: entriesCount,
@@ -21706,7 +21946,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
21706
21946
  entriesTotal: entriesCount
21707
21947
  };
21708
21948
  }
21709
- var _internals30 = {
21949
+ var _internals31 = {
21710
21950
  appendKnowledge,
21711
21951
  migrateContextToKnowledge,
21712
21952
  migrateKnowledgeToExternal,
@@ -21757,9 +21997,9 @@ async function migrateContextToKnowledge(directory, config) {
21757
21997
  skippedReason: "empty-context"
21758
21998
  };
21759
21999
  }
21760
- const rawEntries = _internals30.parseContextMd(contextContent);
22000
+ const rawEntries = _internals31.parseContextMd(contextContent);
21761
22001
  if (rawEntries.length === 0) {
21762
- await _internals30.writeSentinel(sentinelPath, 0, 0);
22002
+ await _internals31.writeSentinel(sentinelPath, 0, 0);
21763
22003
  return {
21764
22004
  migrated: true,
21765
22005
  entriesMigrated: 0,
@@ -21770,10 +22010,10 @@ async function migrateContextToKnowledge(directory, config) {
21770
22010
  const existing = await readKnowledge(knowledgePath);
21771
22011
  let migrated = 0;
21772
22012
  let dropped = 0;
21773
- const projectName = _internals30.inferProjectName(directory);
22013
+ const projectName = _internals31.inferProjectName(directory);
21774
22014
  for (const raw of rawEntries) {
21775
22015
  if (config.validation_enabled !== false) {
21776
- const category = raw.categoryHint ?? _internals30.inferCategoryFromText(raw.text);
22016
+ const category = raw.categoryHint ?? _internals31.inferCategoryFromText(raw.text);
21777
22017
  const result = validateLesson(raw.text, existing.map((e) => e.lesson), {
21778
22018
  category,
21779
22019
  scope: "global",
@@ -21793,8 +22033,8 @@ async function migrateContextToKnowledge(directory, config) {
21793
22033
  const entry = {
21794
22034
  id: randomUUID6(),
21795
22035
  tier: "swarm",
21796
- lesson: _internals30.truncateLesson(raw.text),
21797
- category: raw.categoryHint ?? _internals30.inferCategoryFromText(raw.text),
22036
+ lesson: _internals31.truncateLesson(raw.text),
22037
+ category: raw.categoryHint ?? _internals31.inferCategoryFromText(raw.text),
21798
22038
  tags: [...inferredTags, `migration:${raw.sourceSection}`],
21799
22039
  scope: "global",
21800
22040
  confidence: 0.3,
@@ -21817,7 +22057,7 @@ async function migrateContextToKnowledge(directory, config) {
21817
22057
  if (migrated > 0) {
21818
22058
  await rewriteKnowledge(knowledgePath, existing);
21819
22059
  }
21820
- await _internals30.writeSentinel(sentinelPath, migrated, dropped);
22060
+ await _internals31.writeSentinel(sentinelPath, migrated, dropped);
21821
22061
  log(`[knowledge-migrator] Migrated ${migrated} entries, dropped ${dropped}`);
21822
22062
  return {
21823
22063
  migrated: true,
@@ -21827,7 +22067,7 @@ async function migrateContextToKnowledge(directory, config) {
21827
22067
  };
21828
22068
  }
21829
22069
  async function migrateHiveKnowledgeLegacy(config) {
21830
- const legacyHivePath = _internals30.resolveLegacyHiveKnowledgePath();
22070
+ const legacyHivePath = _internals31.resolveLegacyHiveKnowledgePath();
21831
22071
  const canonicalHivePath = resolveHiveKnowledgePath();
21832
22072
  const sentinelPath = path42.join(path42.dirname(canonicalHivePath), ".hive-knowledge-migrated");
21833
22073
  if (existsSync28(sentinelPath)) {
@@ -21850,7 +22090,7 @@ async function migrateHiveKnowledgeLegacy(config) {
21850
22090
  }
21851
22091
  const legacyEntries = await readKnowledge(legacyHivePath);
21852
22092
  if (legacyEntries.length === 0) {
21853
- await _internals30.writeSentinel(sentinelPath, 0, 0);
22093
+ await _internals31.writeSentinel(sentinelPath, 0, 0);
21854
22094
  return {
21855
22095
  migrated: true,
21856
22096
  entriesMigrated: 0,
@@ -21898,7 +22138,7 @@ async function migrateHiveKnowledgeLegacy(config) {
21898
22138
  const newHiveEntry = {
21899
22139
  id: resolvedId,
21900
22140
  tier: "hive",
21901
- lesson: _internals30.truncateLesson(lesson),
22141
+ lesson: _internals31.truncateLesson(lesson),
21902
22142
  category,
21903
22143
  tags: ["migration:legacy-hive"],
21904
22144
  scope: scopeTag,
@@ -21917,7 +22157,7 @@ async function migrateHiveKnowledgeLegacy(config) {
21917
22157
  encounter_score: 1
21918
22158
  };
21919
22159
  try {
21920
- await _internals30.appendKnowledge(canonicalHivePath, newHiveEntry);
22160
+ await _internals31.appendKnowledge(canonicalHivePath, newHiveEntry);
21921
22161
  existingHiveEntries.push(newHiveEntry);
21922
22162
  migrated++;
21923
22163
  } catch (appendError) {
@@ -21933,7 +22173,7 @@ async function migrateHiveKnowledgeLegacy(config) {
21933
22173
  dropped++;
21934
22174
  }
21935
22175
  }
21936
- await _internals30.writeSentinel(sentinelPath, migrated, dropped);
22176
+ await _internals31.writeSentinel(sentinelPath, migrated, dropped);
21937
22177
  log(`[knowledge-migrator] Migrated ${migrated} legacy hive entries, dropped ${dropped}`);
21938
22178
  return {
21939
22179
  migrated: true,
@@ -21944,7 +22184,7 @@ async function migrateHiveKnowledgeLegacy(config) {
21944
22184
  };
21945
22185
  }
21946
22186
  function parseContextMd(content) {
21947
- const sections = _internals30.splitIntoSections(content);
22187
+ const sections = _internals31.splitIntoSections(content);
21948
22188
  const entries = [];
21949
22189
  const seen = new Set;
21950
22190
  const sectionPatterns = [
@@ -21960,7 +22200,7 @@ function parseContextMd(content) {
21960
22200
  const match = sectionPatterns.find((sp) => sp.pattern.test(section.heading));
21961
22201
  if (!match)
21962
22202
  continue;
21963
- const bullets = _internals30.extractBullets(section.body);
22203
+ const bullets = _internals31.extractBullets(section.body);
21964
22204
  for (const bullet of bullets) {
21965
22205
  if (bullet.length < 15)
21966
22206
  continue;
@@ -21969,9 +22209,9 @@ function parseContextMd(content) {
21969
22209
  continue;
21970
22210
  seen.add(normalized);
21971
22211
  entries.push({
21972
- text: _internals30.truncateLesson(bullet),
22212
+ text: _internals31.truncateLesson(bullet),
21973
22213
  sourceSection: match.sourceSection,
21974
- categoryHint: _internals30.inferCategoryFromText(bullet)
22214
+ categoryHint: _internals31.inferCategoryFromText(bullet)
21975
22215
  });
21976
22216
  }
21977
22217
  }
@@ -22061,8 +22301,8 @@ async function writeSentinel(sentinelPath, migrated, dropped) {
22061
22301
  schema_version: 1,
22062
22302
  migration_tool: "knowledge-migrator.ts"
22063
22303
  };
22064
- await _internals30.mkdir(path42.dirname(sentinelPath), { recursive: true });
22065
- await _internals30.writeFile(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
22304
+ await _internals31.mkdir(path42.dirname(sentinelPath), { recursive: true });
22305
+ await _internals31.writeFile(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
22066
22306
  }
22067
22307
  function resolveLegacyHiveKnowledgePath() {
22068
22308
  const platform = process.platform;
@@ -22443,7 +22683,7 @@ function timeoutMessage(timeoutMs) {
22443
22683
  async function computeWithTimeout(directory, currentPhase, timeoutMs) {
22444
22684
  const controller = new AbortController;
22445
22685
  let timeout;
22446
- const metricsPromise = _internals31.computeLearningMetrics(directory, {
22686
+ const metricsPromise = _internals32.computeLearningMetrics(directory, {
22447
22687
  currentPhase,
22448
22688
  signal: controller.signal
22449
22689
  });
@@ -22500,7 +22740,7 @@ ${JSON.stringify({
22500
22740
  return `Error computing learning metrics: ${message}. Run /swarm diagnose to check .swarm/ health.`;
22501
22741
  }
22502
22742
  }
22503
- var _internals31 = {
22743
+ var _internals32 = {
22504
22744
  computeLearningMetrics
22505
22745
  };
22506
22746
 
@@ -22702,7 +22942,7 @@ async function readLatestLoopState(directory) {
22702
22942
  return null;
22703
22943
  }
22704
22944
  }
22705
- var _internals32 = {
22945
+ var _internals33 = {
22706
22946
  readLatestLoopState
22707
22947
  };
22708
22948
  var USAGE7 = `Usage: /swarm loop <objective> [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]
@@ -22815,7 +23055,7 @@ ${USAGE7}`;
22815
23055
  }
22816
23056
  let autonomy = parsed.autonomy;
22817
23057
  if (parsed.resume && !parsed.autonomyExplicit) {
22818
- const state = await _internals32.readLatestLoopState(_directory);
23058
+ const state = await _internals33.readLatestLoopState(_directory);
22819
23059
  if (state?.autonomy && AUTONOMY_LEVELS.has(state.autonomy)) {
22820
23060
  autonomy = state.autonomy;
22821
23061
  }
@@ -22903,7 +23143,7 @@ async function rmTempRoot(tempRoot) {
22903
23143
  } catch (err) {
22904
23144
  if (attempt === 9)
22905
23145
  throw err;
22906
- await new Promise((resolve12) => setTimeout(resolve12, 50));
23146
+ await new Promise((resolve13) => setTimeout(resolve13, 50));
22907
23147
  }
22908
23148
  }
22909
23149
  }
@@ -23751,15 +23991,15 @@ function truncate(value, maxLength) {
23751
23991
  }
23752
23992
 
23753
23993
  // src/services/plan-service.ts
23754
- var _internals33 = {
23994
+ var _internals34 = {
23755
23995
  loadPlanJsonOnly,
23756
23996
  derivePlanMarkdown,
23757
23997
  readSwarmFileAsync
23758
23998
  };
23759
23999
  async function getPlanData(directory, phaseArg) {
23760
- const plan = await _internals33.loadPlanJsonOnly(directory);
24000
+ const plan = await _internals34.loadPlanJsonOnly(directory);
23761
24001
  if (plan) {
23762
- const fullMarkdown = _internals33.derivePlanMarkdown(plan);
24002
+ const fullMarkdown = _internals34.derivePlanMarkdown(plan);
23763
24003
  if (phaseArg === undefined || phaseArg === null || phaseArg === "") {
23764
24004
  return {
23765
24005
  hasPlan: true,
@@ -23802,7 +24042,7 @@ async function getPlanData(directory, phaseArg) {
23802
24042
  isLegacy: false
23803
24043
  };
23804
24044
  }
23805
- const planContent = await _internals33.readSwarmFileAsync(directory, "plan.md");
24045
+ const planContent = await _internals34.readSwarmFileAsync(directory, "plan.md");
23806
24046
  if (!planContent) {
23807
24047
  return {
23808
24048
  hasPlan: false,
@@ -23899,7 +24139,7 @@ async function handlePlanCommand(directory, args) {
23899
24139
  return formatPlanMarkdown(planData);
23900
24140
  }
23901
24141
  // src/commands/post-mortem.ts
23902
- var _internals34 = {
24142
+ var _internals35 = {
23903
24143
  createCuratorLLMDelegate,
23904
24144
  runCuratorPostMortem
23905
24145
  };
@@ -23947,10 +24187,10 @@ async function handlePostMortemCommand(directory, args, options) {
23947
24187
  };
23948
24188
  if (options?.sessionID) {
23949
24189
  try {
23950
- pmOptions.llmDelegate = _internals34.createCuratorLLMDelegate(directory, "postmortem", options.sessionID);
24190
+ pmOptions.llmDelegate = _internals35.createCuratorLLMDelegate(directory, "postmortem", options.sessionID);
23951
24191
  } catch {}
23952
24192
  }
23953
- const result = await _internals34.runCuratorPostMortem(directory, pmOptions);
24193
+ const result = await _internals35.runCuratorPostMortem(directory, pmOptions);
23954
24194
  const lines = [];
23955
24195
  if (result.success) {
23956
24196
  lines.push("## Post-Mortem Report Generated");
@@ -24186,7 +24426,7 @@ function formatMergeGroupStatus(status, conclusion, htmlUrl) {
24186
24426
  }
24187
24427
  return parts.join(" ");
24188
24428
  }
24189
- var _internals35 = {
24429
+ var _internals36 = {
24190
24430
  formatRelativeTime,
24191
24431
  formatMergeGroupStatus,
24192
24432
  listActive,
@@ -24194,7 +24434,7 @@ var _internals35 = {
24194
24434
  parseMergeGroupRuns
24195
24435
  };
24196
24436
  async function handlePrMonitorStatusCommand(directory, _args, sessionID, source) {
24197
- const allActive = await _internals35.listActive(directory);
24437
+ const allActive = await _internals36.listActive(directory);
24198
24438
  const allSessions = source === "cli";
24199
24439
  const subs = allSessions ? allActive : allActive.filter((record) => record.sessionID === sessionID);
24200
24440
  if (subs.length === 0) {
@@ -24210,7 +24450,7 @@ async function handlePrMonitorStatusCommand(directory, _args, sessionID, source)
24210
24450
  const index = i + 1;
24211
24451
  lines.push(` ${index}. ${sub.repoFullName}#${sub.prNumber}`);
24212
24452
  lines.push(` URL: ${sub.prUrl}`);
24213
- const mergeGroupRuns = await _internals35.listMergeGroupRuns(directory, sub.repoFullName, sub.prNumber);
24453
+ const mergeGroupRuns = await _internals36.listMergeGroupRuns(directory, sub.repoFullName, sub.prNumber);
24214
24454
  if (mergeGroupRuns.runs.length > 0) {
24215
24455
  lines.push(" Merge-group runs:");
24216
24456
  for (const run of mergeGroupRuns.runs) {
@@ -24350,7 +24590,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
24350
24590
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
24351
24591
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
24352
24592
  try {
24353
- const config = _internals36.loadPluginConfig(directory);
24593
+ const config = _internals37.loadPluginConfig(directory);
24354
24594
  const prMonitorConfig = config.pr_monitor;
24355
24595
  if (!prMonitorConfig?.enabled) {
24356
24596
  return [
@@ -24360,7 +24600,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
24360
24600
  ].join(`
24361
24601
  `);
24362
24602
  }
24363
- await _internals36.subscribe(directory, {
24603
+ await _internals37.subscribe(directory, {
24364
24604
  sessionID,
24365
24605
  prNumber: prInfo.number,
24366
24606
  repoFullName,
@@ -24388,7 +24628,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
24388
24628
  `);
24389
24629
  }
24390
24630
  }
24391
- var _internals36 = {
24631
+ var _internals37 = {
24392
24632
  loadPluginConfig,
24393
24633
  subscribe
24394
24634
  };
@@ -24411,9 +24651,9 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
24411
24651
  `);
24412
24652
  }
24413
24653
  const refToken = rest[0];
24414
- const prInfo = _internals37.parsePrRef(refToken, directory);
24654
+ const prInfo = _internals38.parsePrRef(refToken, directory);
24415
24655
  if (!prInfo) {
24416
- if (_internals37.looksLikePrRef(refToken)) {
24656
+ if (_internals38.looksLikePrRef(refToken)) {
24417
24657
  return [
24418
24658
  `Error: Could not resolve PR reference from "${refToken}".`,
24419
24659
  "",
@@ -24434,8 +24674,8 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
24434
24674
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
24435
24675
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
24436
24676
  try {
24437
- const correlationId = _internals37.buildCorrelationId(sessionID, repoFullName, prInfo.number);
24438
- const result = await _internals37.unsubscribe(directory, correlationId);
24677
+ const correlationId = _internals38.buildCorrelationId(sessionID, repoFullName, prInfo.number);
24678
+ const result = await _internals38.unsubscribe(directory, correlationId);
24439
24679
  if (!result) {
24440
24680
  return [
24441
24681
  `Not subscribed to ${prUrl}`,
@@ -24462,7 +24702,7 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
24462
24702
  `);
24463
24703
  }
24464
24704
  }
24465
- var _internals37 = {
24705
+ var _internals38 = {
24466
24706
  unsubscribe,
24467
24707
  buildCorrelationId,
24468
24708
  parsePrRef,
@@ -24780,7 +25020,7 @@ async function _detectAvailableLinter(_projectDir, biomeBin, eslintBin) {
24780
25020
  stderr: "pipe"
24781
25021
  });
24782
25022
  const biomeExit = biomeProc.exited;
24783
- const timeout = new Promise((resolve13) => setTimeout(() => resolve13("timeout"), DETECT_TIMEOUT));
25023
+ const timeout = new Promise((resolve14) => setTimeout(() => resolve14("timeout"), DETECT_TIMEOUT));
24784
25024
  const result = await Promise.race([biomeExit, timeout]);
24785
25025
  if (result === "timeout") {
24786
25026
  biomeProc.kill();
@@ -24794,7 +25034,7 @@ async function _detectAvailableLinter(_projectDir, biomeBin, eslintBin) {
24794
25034
  stderr: "pipe"
24795
25035
  });
24796
25036
  const eslintExit = eslintProc.exited;
24797
- const timeout = new Promise((resolve13) => setTimeout(() => resolve13("timeout"), DETECT_TIMEOUT));
25037
+ const timeout = new Promise((resolve14) => setTimeout(() => resolve14("timeout"), DETECT_TIMEOUT));
24798
25038
  const result = await Promise.race([eslintExit, timeout]);
24799
25039
  if (result === "timeout") {
24800
25040
  eslintProc.kill();
@@ -24944,15 +25184,15 @@ var lint = createSwarmTool({
24944
25184
  }
24945
25185
  const { mode } = args;
24946
25186
  const cwd = directory;
24947
- const linter = await _internals38.detectAvailableLinter(directory);
25187
+ const linter = await _internals39.detectAvailableLinter(directory);
24948
25188
  if (linter) {
24949
- const result = await _internals38.runLint(linter, mode, directory);
25189
+ const result = await _internals39.runLint(linter, mode, directory);
24950
25190
  return JSON.stringify(result, null, 2);
24951
25191
  }
24952
- const additionalLinter = _internals38.detectAdditionalLinter(cwd);
25192
+ const additionalLinter = _internals39.detectAdditionalLinter(cwd);
24953
25193
  if (additionalLinter) {
24954
25194
  warn(`[lint] Using ${additionalLinter} linter for this project`);
24955
- const result = await _internals38.runAdditionalLint(additionalLinter, mode, cwd);
25195
+ const result = await _internals39.runAdditionalLint(additionalLinter, mode, cwd);
24956
25196
  return JSON.stringify(result, null, 2);
24957
25197
  }
24958
25198
  const errorResult = {
@@ -24966,7 +25206,7 @@ For Rust: rustup component add clippy`
24966
25206
  return JSON.stringify(errorResult, null, 2);
24967
25207
  }
24968
25208
  });
24969
- var _internals38 = {
25209
+ var _internals39 = {
24970
25210
  detectAvailableLinter,
24971
25211
  runLint,
24972
25212
  detectAdditionalLinter,
@@ -25654,7 +25894,7 @@ var secretscan = createSwarmTool({
25654
25894
  });
25655
25895
  async function runSecretscan(directory) {
25656
25896
  try {
25657
- const result = await _internals39.secretscan.execute({ directory }, {});
25897
+ const result = await _internals40.secretscan.execute({ directory }, {});
25658
25898
  const jsonStr = typeof result === "string" ? result : result.output;
25659
25899
  return JSON.parse(jsonStr);
25660
25900
  } catch (e) {
@@ -25726,7 +25966,7 @@ async function runSecretscanOnFiles(files, directory) {
25726
25966
  };
25727
25967
  }
25728
25968
  }
25729
- var _internals39 = {
25969
+ var _internals40 = {
25730
25970
  secretscan,
25731
25971
  runSecretscan,
25732
25972
  runSecretscanOnFiles,
@@ -26002,7 +26242,7 @@ async function buildImpactMapInternal(cwd) {
26002
26242
  }
26003
26243
  return impactMap;
26004
26244
  }
26005
- var _internals40 = {
26245
+ var _internals41 = {
26006
26246
  validateProjectRoot,
26007
26247
  normalizePath: normalizePath2,
26008
26248
  isCacheStale,
@@ -26017,8 +26257,8 @@ var _internals40 = {
26017
26257
  _clearGoModuleCache
26018
26258
  };
26019
26259
  async function buildImpactMap(cwd) {
26020
- const impactMap = await _internals40.buildImpactMapInternal(cwd);
26021
- await _internals40.saveImpactMap(cwd, impactMap);
26260
+ const impactMap = await _internals41.buildImpactMapInternal(cwd);
26261
+ await _internals41.saveImpactMap(cwd, impactMap);
26022
26262
  return impactMap;
26023
26263
  }
26024
26264
  async function loadImpactMap(cwd, options) {
@@ -26032,7 +26272,7 @@ async function loadImpactMap(cwd, options) {
26032
26272
  const hasValidValues = Object.values(map).every((v) => Array.isArray(v) && v.every((item) => typeof item === "string"));
26033
26273
  if (hasValidValues) {
26034
26274
  const generatedAt = new Date(data.generatedAt).getTime();
26035
- if (!_internals40.isCacheStale(map, generatedAt)) {
26275
+ if (!_internals41.isCacheStale(map, generatedAt)) {
26036
26276
  return map;
26037
26277
  }
26038
26278
  if (options?.skipRebuild) {
@@ -26052,13 +26292,13 @@ async function loadImpactMap(cwd, options) {
26052
26292
  if (options?.skipRebuild) {
26053
26293
  return {};
26054
26294
  }
26055
- return _internals40.buildImpactMap(cwd);
26295
+ return _internals41.buildImpactMap(cwd);
26056
26296
  }
26057
26297
  async function saveImpactMap(cwd, impactMap) {
26058
26298
  if (!path50.isAbsolute(cwd)) {
26059
26299
  throw new Error(`saveImpactMap requires an absolute project root path, got: "${cwd}"`);
26060
26300
  }
26061
- _internals40.validateProjectRoot(cwd);
26301
+ _internals41.validateProjectRoot(cwd);
26062
26302
  const cacheDir2 = path50.join(cwd, ".swarm", "cache");
26063
26303
  const cachePath = path50.join(cacheDir2, "impact-map.json");
26064
26304
  if (!fs19.existsSync(cacheDir2)) {
@@ -26082,7 +26322,7 @@ async function analyzeImpact(changedFiles, cwd, budget) {
26082
26322
  };
26083
26323
  }
26084
26324
  const validFiles = changedFiles.filter((f) => typeof f === "string" && f.length > 0 && !f.includes("\x00"));
26085
- const impactMap = await _internals40.loadImpactMap(cwd);
26325
+ const impactMap = await _internals41.loadImpactMap(cwd);
26086
26326
  const impactedTestsSet = new Set;
26087
26327
  const untestedFiles = [];
26088
26328
  let visitedCount = 0;
@@ -26552,7 +26792,7 @@ function batchAppendTestRuns(records, workingDir) {
26552
26792
  }
26553
26793
  const historyPath = getHistoryPath(workingDir);
26554
26794
  const historyDir = path51.dirname(historyPath);
26555
- _internals41.validateProjectRoot(workingDir);
26795
+ _internals42.validateProjectRoot(workingDir);
26556
26796
  if (!fs20.existsSync(historyDir)) {
26557
26797
  fs20.mkdirSync(historyDir, { recursive: true });
26558
26798
  }
@@ -26675,7 +26915,7 @@ function getAllHistory(workingDir) {
26675
26915
  records.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
26676
26916
  return records;
26677
26917
  }
26678
- var _internals41 = {
26918
+ var _internals42 = {
26679
26919
  validateProjectRoot
26680
26920
  };
26681
26921
 
@@ -27944,9 +28184,9 @@ async function runTests(framework, scope, files, coverage, timeout_ms, cwd, bail
27944
28184
  stderr: "pipe",
27945
28185
  cwd
27946
28186
  });
27947
- const timeoutPromise = new Promise((resolve16) => setTimeout(() => {
28187
+ const timeoutPromise = new Promise((resolve17) => setTimeout(() => {
27948
28188
  proc.kill();
27949
- resolve16(-1);
28189
+ resolve17(-1);
27950
28190
  }, timeout_ms));
27951
28191
  const [exitCode, stdoutResult, stderrResult] = await Promise.all([
27952
28192
  Promise.race([proc.exited, timeoutPromise]),
@@ -28104,11 +28344,11 @@ function normalizeHistoryTestFile(testFile, workingDir) {
28104
28344
  const normalized = testFile.replace(/\\/g, "/");
28105
28345
  if (!path53.isAbsolute(testFile))
28106
28346
  return normalized;
28107
- const relative6 = path53.relative(workingDir, testFile);
28108
- if (relative6.startsWith("..") || path53.isAbsolute(relative6)) {
28347
+ const relative7 = path53.relative(workingDir, testFile);
28348
+ if (relative7.startsWith("..") || path53.isAbsolute(relative7)) {
28109
28349
  return normalized;
28110
28350
  }
28111
- return relative6.replace(/\\/g, "/");
28351
+ return relative7.replace(/\\/g, "/");
28112
28352
  }
28113
28353
  function combineAggregateResult(current, next) {
28114
28354
  if (current === "fail" || next === "fail")
@@ -28653,9 +28893,9 @@ function getVersionFileVersion(dir) {
28653
28893
  async function runVersionCheck(dir, _timeoutMs) {
28654
28894
  const startTime = Date.now();
28655
28895
  try {
28656
- const packageVersion = _internals42.getPackageVersion(dir);
28657
- const changelogVersion = _internals42.getChangelogVersion(dir);
28658
- const versionFileVersion = _internals42.getVersionFileVersion(dir);
28896
+ const packageVersion = _internals43.getPackageVersion(dir);
28897
+ const changelogVersion = _internals43.getChangelogVersion(dir);
28898
+ const versionFileVersion = _internals43.getVersionFileVersion(dir);
28659
28899
  const versions = [];
28660
28900
  if (packageVersion)
28661
28901
  versions.push(`package.json: ${packageVersion}`);
@@ -29019,7 +29259,7 @@ async function runPreflight(dir, phase, config) {
29019
29259
  const reportId = `preflight-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
29020
29260
  let validatedDir;
29021
29261
  try {
29022
- validatedDir = _internals42.validateDirectoryPath(dir);
29262
+ validatedDir = _internals43.validateDirectoryPath(dir);
29023
29263
  } catch (error2) {
29024
29264
  return {
29025
29265
  id: reportId,
@@ -29039,7 +29279,7 @@ async function runPreflight(dir, phase, config) {
29039
29279
  }
29040
29280
  let validatedTimeout;
29041
29281
  try {
29042
- validatedTimeout = _internals42.validateTimeout(config?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
29282
+ validatedTimeout = _internals43.validateTimeout(config?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
29043
29283
  } catch (error2) {
29044
29284
  return {
29045
29285
  id: reportId,
@@ -29080,12 +29320,12 @@ async function runPreflight(dir, phase, config) {
29080
29320
  });
29081
29321
  const checks = [];
29082
29322
  log("[Preflight] Running lint check...");
29083
- const lintResult = await _internals42.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
29323
+ const lintResult = await _internals43.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
29084
29324
  checks.push(lintResult);
29085
29325
  log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`);
29086
29326
  if (!cfg.skipTests) {
29087
29327
  log("[Preflight] Running tests check...");
29088
- const testsResult = await _internals42.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
29328
+ const testsResult = await _internals43.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
29089
29329
  checks.push(testsResult);
29090
29330
  log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`);
29091
29331
  } else {
@@ -29097,7 +29337,7 @@ async function runPreflight(dir, phase, config) {
29097
29337
  }
29098
29338
  if (!cfg.skipSecrets) {
29099
29339
  log("[Preflight] Running secrets check...");
29100
- const secretsResult = await _internals42.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
29340
+ const secretsResult = await _internals43.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
29101
29341
  checks.push(secretsResult);
29102
29342
  log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`);
29103
29343
  } else {
@@ -29109,7 +29349,7 @@ async function runPreflight(dir, phase, config) {
29109
29349
  }
29110
29350
  if (!cfg.skipEvidence) {
29111
29351
  log("[Preflight] Running evidence check...");
29112
- const evidenceResult = await _internals42.runEvidenceCheck(validatedDir);
29352
+ const evidenceResult = await _internals43.runEvidenceCheck(validatedDir);
29113
29353
  checks.push(evidenceResult);
29114
29354
  log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`);
29115
29355
  } else {
@@ -29120,12 +29360,12 @@ async function runPreflight(dir, phase, config) {
29120
29360
  });
29121
29361
  }
29122
29362
  log("[Preflight] Running requirement coverage check...");
29123
- const reqCoverageResult = await _internals42.runRequirementCoverageCheck(validatedDir, phase);
29363
+ const reqCoverageResult = await _internals43.runRequirementCoverageCheck(validatedDir, phase);
29124
29364
  checks.push(reqCoverageResult);
29125
29365
  log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`);
29126
29366
  if (!cfg.skipVersion) {
29127
29367
  log("[Preflight] Running version check...");
29128
- const versionResult = await _internals42.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
29368
+ const versionResult = await _internals43.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
29129
29369
  checks.push(versionResult);
29130
29370
  log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`);
29131
29371
  } else {
@@ -29188,10 +29428,10 @@ function formatPreflightMarkdown(report) {
29188
29428
  async function handlePreflightCommand(directory, _args) {
29189
29429
  const plan = await loadPlan(directory);
29190
29430
  const phase = plan?.current_phase ?? 1;
29191
- const report = await _internals42.runPreflight(directory, phase);
29192
- return _internals42.formatPreflightMarkdown(report);
29431
+ const report = await _internals43.runPreflight(directory, phase);
29432
+ return _internals43.formatPreflightMarkdown(report);
29193
29433
  }
29194
- var _internals42 = {
29434
+ var _internals43 = {
29195
29435
  runPreflight,
29196
29436
  formatPreflightMarkdown,
29197
29437
  handlePreflightCommand,
@@ -29427,13 +29667,13 @@ class CircuitBreaker {
29427
29667
  if (this.config.callTimeoutMs <= 0) {
29428
29668
  return fn();
29429
29669
  }
29430
- return new Promise((resolve17, reject) => {
29670
+ return new Promise((resolve18, reject) => {
29431
29671
  const timeout = setTimeout(() => {
29432
29672
  reject(new Error(`Call timeout after ${this.config.callTimeoutMs}ms`));
29433
29673
  }, this.config.callTimeoutMs);
29434
29674
  fn().then((result) => {
29435
29675
  clearTimeout(timeout);
29436
- resolve17(result);
29676
+ resolve18(result);
29437
29677
  }).catch((error2) => {
29438
29678
  clearTimeout(timeout);
29439
29679
  reject(error2);
@@ -29732,7 +29972,7 @@ class AutomationQueue {
29732
29972
 
29733
29973
  // src/background/worker.ts
29734
29974
  function sleep(ms) {
29735
- return new Promise((resolve17) => setTimeout(resolve17, ms));
29975
+ return new Promise((resolve18) => setTimeout(resolve18, ms));
29736
29976
  }
29737
29977
 
29738
29978
  class WorkerManager {
@@ -30697,7 +30937,7 @@ async function recordReplayEntry(artifactPath, sessionID, entry) {
30697
30937
  }
30698
30938
 
30699
30939
  // src/prm/index.ts
30700
- var _internals43 = {
30940
+ var _internals44 = {
30701
30941
  getAgentSession,
30702
30942
  readTrajectory,
30703
30943
  getInMemoryTrajectory,
@@ -30720,12 +30960,12 @@ function resetPrmSessionState(session, sessionId) {
30720
30960
  session.prmTrajectoryStep = 0;
30721
30961
  session.replayArtifactPath = null;
30722
30962
  if (sessionId) {
30723
- _internals43.clearTrajectoryCache(sessionId);
30963
+ _internals44.clearTrajectoryCache(sessionId);
30724
30964
  }
30725
30965
  }
30726
30966
 
30727
30967
  // src/commands/reset-session.ts
30728
- var _internals44 = {
30968
+ var _internals45 = {
30729
30969
  cleanupOrphanedBranches
30730
30970
  };
30731
30971
  function errorMessage(err) {
@@ -30791,7 +31031,7 @@ async function handleResetSessionCommand(directory, _args) {
30791
31031
  results.push(`\u26A0\uFE0F Failed to remove .swarm-worktrees/: ${errorMessage(err)}`);
30792
31032
  }
30793
31033
  try {
30794
- const branchResult = await _internals44.cleanupOrphanedBranches(directory, []);
31034
+ const branchResult = await _internals45.cleanupOrphanedBranches(directory, []);
30795
31035
  if (branchResult.removed.length > 0) {
30796
31036
  results.push(`\u2705 Removed ${branchResult.removed.length} orphan swarm-lane branch(es)`);
30797
31037
  }
@@ -31128,7 +31368,7 @@ async function handleRollbackCommand(directory, args) {
31128
31368
  // src/commands/sdd.ts
31129
31369
  import * as fs29 from "fs";
31130
31370
  import * as path61 from "path";
31131
- var _internals45 = {
31371
+ var _internals46 = {
31132
31372
  writeProjectedSpecSync
31133
31373
  };
31134
31374
  var SWARM_SPEC_REL = path61.join(".swarm", "spec.md");
@@ -31524,7 +31764,7 @@ ${USAGE9}`;
31524
31764
 
31525
31765
  ${USAGE9}`;
31526
31766
  }
31527
- const result2 = _internals45.writeProjectedSpecSync(directory, {
31767
+ const result2 = _internals46.writeProjectedSpecSync(directory, {
31528
31768
  source: "speckit",
31529
31769
  feature: resolution.feature,
31530
31770
  dryRun: parsed.dryRun,
@@ -31582,7 +31822,7 @@ ${formatList(result2.projection.warnings)}` : ""
31582
31822
  ].join(`
31583
31823
  `);
31584
31824
  }
31585
- const result = _internals45.writeProjectedSpecSync(directory, {
31825
+ const result = _internals46.writeProjectedSpecSync(directory, {
31586
31826
  changeId: parsed.changeId,
31587
31827
  dryRun: parsed.dryRun,
31588
31828
  overwrite: parsed.overwrite
@@ -31663,7 +31903,7 @@ async function handleSimulateCommand(directory, args) {
31663
31903
  }
31664
31904
  let darkMatterPairs;
31665
31905
  try {
31666
- darkMatterPairs = await _internals20.detectDarkMatter(directory, options);
31906
+ darkMatterPairs = await _internals21.detectDarkMatter(directory, options);
31667
31907
  } catch (err) {
31668
31908
  const errMsg = err instanceof Error ? err.message : String(err);
31669
31909
  return `## Simulate Report
@@ -31968,7 +32208,7 @@ var DEFAULT_CONTEXT_BUDGET_CONFIG = {
31968
32208
  };
31969
32209
 
31970
32210
  // src/services/status-service.ts
31971
- var _internals46 = {
32211
+ var _internals47 = {
31972
32212
  loadLeanTurboRunState,
31973
32213
  hasActiveLeanTurbo,
31974
32214
  hasActiveFullAuto
@@ -32073,7 +32313,7 @@ async function getStatusData(directory, agents) {
32073
32313
  }
32074
32314
  function enrichWithLeanTurbo(status, directory) {
32075
32315
  const turboMode = hasActiveTurboMode();
32076
- const leanActive = _internals46.hasActiveLeanTurbo();
32316
+ const leanActive = _internals47.hasActiveLeanTurbo();
32077
32317
  let turboStrategy = "off";
32078
32318
  if (leanActive) {
32079
32319
  turboStrategy = "lean";
@@ -32092,7 +32332,7 @@ function enrichWithLeanTurbo(status, directory) {
32092
32332
  }
32093
32333
  }
32094
32334
  if (leanSessionID) {
32095
- const runState = _internals46.loadLeanTurboRunState(directory, leanSessionID);
32335
+ const runState = _internals47.loadLeanTurboRunState(directory, leanSessionID);
32096
32336
  if (runState) {
32097
32337
  status.leanTurboPhase = runState.phase;
32098
32338
  status.leanMaxParallelCoders = runState.maxParallelCoders;
@@ -32124,7 +32364,7 @@ function enrichWithLeanTurbo(status, directory) {
32124
32364
  }
32125
32365
  }
32126
32366
  }
32127
- status.fullAutoActive = _internals46.hasActiveFullAuto();
32367
+ status.fullAutoActive = _internals47.hasActiveFullAuto();
32128
32368
  return status;
32129
32369
  }
32130
32370
  function formatStatusMarkdown(status) {
@@ -32278,7 +32518,7 @@ No active swarm plan found. Nothing to sync.`;
32278
32518
 
32279
32519
  // src/commands/turbo.ts
32280
32520
  init_logger();
32281
- var _internals47 = {
32521
+ var _internals48 = {
32282
32522
  loadPluginConfigWithMeta
32283
32523
  };
32284
32524
  async function handleTurboCommand(directory, args, sessionID) {
@@ -32338,7 +32578,7 @@ async function handleTurboCommand(directory, args, sessionID) {
32338
32578
  if (arg0 === "on") {
32339
32579
  let strategy = "standard";
32340
32580
  try {
32341
- const { config } = _internals47.loadPluginConfigWithMeta(directory);
32581
+ const { config } = _internals48.loadPluginConfigWithMeta(directory);
32342
32582
  if (config.turbo?.strategy === "lean") {
32343
32583
  strategy = "lean";
32344
32584
  }
@@ -32435,7 +32675,7 @@ function enableLeanTurbo(session, directory, sessionID) {
32435
32675
  let maxParallelCoders = 4;
32436
32676
  let conflictPolicy = "serialize";
32437
32677
  try {
32438
- const { config } = _internals47.loadPluginConfigWithMeta(directory);
32678
+ const { config } = _internals48.loadPluginConfigWithMeta(directory);
32439
32679
  const leanConfig = config.turbo?.lean;
32440
32680
  if (leanConfig) {
32441
32681
  maxParallelCoders = leanConfig.max_parallel_coders ?? 4;
@@ -32651,7 +32891,7 @@ function findSimilarCommands(query) {
32651
32891
  }
32652
32892
  const scored = VALID_COMMANDS.map((cmd) => {
32653
32893
  const cmdLower = cmd.toLowerCase();
32654
- const fullScore = _internals48.levenshteinDistance(q, cmdLower);
32894
+ const fullScore = _internals49.levenshteinDistance(q, cmdLower);
32655
32895
  let tokenScore = Infinity;
32656
32896
  if (cmd.includes(" ") || cmd.includes("-")) {
32657
32897
  const qTokens = q.split(/[\s-]+/);
@@ -32664,7 +32904,7 @@ function findSimilarCommands(query) {
32664
32904
  for (const ct of cmdTokens) {
32665
32905
  if (ct.length === 0)
32666
32906
  continue;
32667
- const dist = _internals48.levenshteinDistance(qt, ct);
32907
+ const dist = _internals49.levenshteinDistance(qt, ct);
32668
32908
  if (dist < minDist)
32669
32909
  minDist = dist;
32670
32910
  }
@@ -32674,7 +32914,7 @@ function findSimilarCommands(query) {
32674
32914
  }
32675
32915
  const dashStrippedQ = q.replace(/-/g, "");
32676
32916
  const dashStrippedCmd = cmdLower.replace(/-/g, "");
32677
- const dashScore = _internals48.levenshteinDistance(dashStrippedQ, dashStrippedCmd);
32917
+ const dashScore = _internals49.levenshteinDistance(dashStrippedQ, dashStrippedCmd);
32678
32918
  const score = Math.min(fullScore, tokenScore, dashScore);
32679
32919
  return { cmd, score };
32680
32920
  });
@@ -32709,16 +32949,16 @@ function buildDetailedHelp(commandName, entry) {
32709
32949
  async function handleHelpCommand(ctx) {
32710
32950
  const targetCommand = ctx.args.join(" ");
32711
32951
  if (!targetCommand) {
32712
- const { buildHelpText } = await import("./index-hw4tcxs9.js");
32952
+ const { buildHelpText } = await import("./index-5yzr9fk6.js");
32713
32953
  return buildHelpText();
32714
32954
  }
32715
32955
  const tokens = targetCommand.split(/\s+/);
32716
- const resolved = _internals48.resolveCommand(tokens);
32956
+ const resolved = _internals49.resolveCommand(tokens);
32717
32957
  if (resolved) {
32718
- return _internals48.buildDetailedHelp(resolved.key, resolved.entry);
32958
+ return _internals49.buildDetailedHelp(resolved.key, resolved.entry);
32719
32959
  }
32720
- const similar = _internals48.findSimilarCommands(targetCommand);
32721
- const { buildHelpText: fullHelp } = await import("./index-hw4tcxs9.js");
32960
+ const similar = _internals49.findSimilarCommands(targetCommand);
32961
+ const { buildHelpText: fullHelp } = await import("./index-5yzr9fk6.js");
32722
32962
  if (similar.length > 0) {
32723
32963
  return `Command '/swarm ${targetCommand}' not found.
32724
32964
 
@@ -32782,7 +33022,7 @@ var COMMAND_REGISTRY = {
32782
33022
  toolNoArgs: true
32783
33023
  },
32784
33024
  help: {
32785
- handler: (ctx) => _internals48.handleHelpCommand(ctx),
33025
+ handler: (ctx) => _internals49.handleHelpCommand(ctx),
32786
33026
  description: "Show help for swarm commands",
32787
33027
  category: "core",
32788
33028
  args: "[command]",
@@ -32851,7 +33091,7 @@ var COMMAND_REGISTRY = {
32851
33091
  },
32852
33092
  "guardrail explain": {
32853
33093
  handler: async (ctx) => {
32854
- const { handleGuardrailExplain } = await import("./guardrail-explain-kabd97j8.js");
33094
+ const { handleGuardrailExplain } = await import("./guardrail-explain-wpv5eskq.js");
32855
33095
  return handleGuardrailExplain(ctx.directory, ctx.args);
32856
33096
  },
32857
33097
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -32861,7 +33101,7 @@ var COMMAND_REGISTRY = {
32861
33101
  },
32862
33102
  "guardrail-explain": {
32863
33103
  handler: async (ctx) => {
32864
- const { handleGuardrailExplain } = await import("./guardrail-explain-kabd97j8.js");
33104
+ const { handleGuardrailExplain } = await import("./guardrail-explain-wpv5eskq.js");
32865
33105
  return handleGuardrailExplain(ctx.directory, ctx.args);
32866
33106
  },
32867
33107
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -33695,7 +33935,7 @@ function validateToolPolicy() {
33695
33935
  }
33696
33936
  return { valid: warnings.length === 0, warnings };
33697
33937
  }
33698
- var _internals48 = {
33938
+ var _internals49 = {
33699
33939
  handleHelpCommand,
33700
33940
  validateAliases,
33701
33941
  validateToolPolicy,
@@ -33705,16 +33945,16 @@ var _internals48 = {
33705
33945
  findSimilarCommands,
33706
33946
  buildDetailedHelp
33707
33947
  };
33708
- var validation = _internals48.validateAliases();
33948
+ var validation = _internals49.validateAliases();
33709
33949
  if (!validation.valid) {
33710
33950
  throw new Error(`COMMAND_REGISTRY alias validation failed:
33711
33951
  ${validation.errors.join(`
33712
33952
  `)}`);
33713
33953
  }
33714
- _internals48.emitValidationWarnings("COMMAND_REGISTRY alias warnings", validation.warnings);
33954
+ _internals49.emitValidationWarnings("COMMAND_REGISTRY alias warnings", validation.warnings);
33715
33955
  try {
33716
- const toolPolicyValidation = _internals48.validateToolPolicy();
33717
- _internals48.emitValidationWarnings("COMMAND_REGISTRY toolPolicy warnings", toolPolicyValidation.warnings);
33956
+ const toolPolicyValidation = _internals49.validateToolPolicy();
33957
+ _internals49.emitValidationWarnings("COMMAND_REGISTRY toolPolicy warnings", toolPolicyValidation.warnings);
33718
33958
  } catch (e) {
33719
33959
  warn(`COMMAND_REGISTRY toolPolicy validation failed (non-fatal): ${e.message}`);
33720
33960
  }
@@ -36397,7 +36637,7 @@ function formatCommandNotFound(tokens) {
36397
36637
  const attemptedCommand = tokens[0] || "";
36398
36638
  const MAX_DISPLAY = 100;
36399
36639
  const displayCommand = attemptedCommand.length > MAX_DISPLAY ? `${attemptedCommand.slice(0, MAX_DISPLAY)}...` : attemptedCommand;
36400
- const similar = _internals48.findSimilarCommands(attemptedCommand);
36640
+ const similar = _internals49.findSimilarCommands(attemptedCommand);
36401
36641
  const header = `Command \`/swarm ${displayCommand}\` not found.`;
36402
36642
  const suggestions = similar.length > 0 ? `Did you mean:
36403
36643
  ${similar.map((cmd) => ` - /swarm ${cmd}`).join(`
@@ -38070,11 +38310,11 @@ function markSuggested(sessionId) {
38070
38310
  _suggestedSessions.add(sessionId);
38071
38311
  }
38072
38312
  function countWorktrees(directory) {
38073
- return new Promise((resolve20) => {
38313
+ return new Promise((resolve21) => {
38074
38314
  try {
38075
38315
  const child = execFile3("git", ["-C", directory, "worktree", "list", "--porcelain"], { timeout: GIT_TIMEOUT_MS3, windowsHide: true, encoding: "utf-8" }, (err, stdout) => {
38076
38316
  if (err || typeof stdout !== "string") {
38077
- resolve20(0);
38317
+ resolve21(0);
38078
38318
  return;
38079
38319
  }
38080
38320
  let count = 0;
@@ -38083,14 +38323,14 @@ function countWorktrees(directory) {
38083
38323
  if (line.startsWith("worktree "))
38084
38324
  count++;
38085
38325
  }
38086
- resolve20(count);
38326
+ resolve21(count);
38087
38327
  });
38088
38328
  try {
38089
38329
  child.stdin?.end();
38090
38330
  } catch {}
38091
- child.on("error", () => resolve20(0));
38331
+ child.on("error", () => resolve21(0));
38092
38332
  } catch {
38093
- resolve20(0);
38333
+ resolve21(0);
38094
38334
  }
38095
38335
  });
38096
38336
  }
@@ -38314,10 +38554,10 @@ function startAgentSession(sessionId, agentName, staleDurationMs = STALE_SESSION
38314
38554
  }
38315
38555
  telemetry.sessionStarted(sessionId, agentName);
38316
38556
  swarmState.activeAgent.set(sessionId, agentName);
38317
- _internals51.applyRehydrationCache(sessionState);
38557
+ _internals52.applyRehydrationCache(sessionState);
38318
38558
  if (directory) {
38319
38559
  let rehydrationPromise;
38320
- rehydrationPromise = _internals51.rehydrateSessionFromDisk(directory, sessionState).then(async () => {
38560
+ rehydrationPromise = _internals52.rehydrateSessionFromDisk(directory, sessionState).then(async () => {
38321
38561
  try {
38322
38562
  sessionState.prSubscriptions = await rehydratePrSubscriptions(sessionId, directory);
38323
38563
  } catch (err) {
@@ -38498,7 +38738,7 @@ function ensureAgentSession(sessionId, agentName, directory) {
38498
38738
  maybeSweepStaleSessions();
38499
38739
  return session;
38500
38740
  }
38501
- _internals51.startAgentSession(sessionId, agentName ?? "unknown", 7200000, directory);
38741
+ _internals52.startAgentSession(sessionId, agentName ?? "unknown", 7200000, directory);
38502
38742
  session = swarmState.agentSessions.get(sessionId);
38503
38743
  if (!session) {
38504
38744
  throw new Error(`Failed to create guardrail session for ${sessionId}`);
@@ -38786,8 +39026,8 @@ function applyRehydrationCache(session) {
38786
39026
  }
38787
39027
  }
38788
39028
  async function rehydrateSessionFromDisk(directory, session) {
38789
- await _internals51.buildRehydrationCache(directory);
38790
- _internals51.applyRehydrationCache(session);
39029
+ await _internals52.buildRehydrationCache(directory);
39030
+ _internals52.applyRehydrationCache(session);
38791
39031
  }
38792
39032
  function hasActiveTurboMode(sessionID) {
38793
39033
  if (sessionID) {
@@ -38861,7 +39101,7 @@ async function rehydratePrSubscriptions(sessionID, directory) {
38861
39101
  }
38862
39102
  return map;
38863
39103
  }
38864
- var _internals51 = {
39104
+ var _internals52 = {
38865
39105
  swarmState,
38866
39106
  resetSwarmState,
38867
39107
  ensureAgentSession,
@@ -39000,4 +39240,4 @@ function createCuratorLLMDelegate(directory, mode = "init", sessionId) {
39000
39240
  };
39001
39241
  }
39002
39242
 
39003
- export { package_default, handleAcknowledgeSpecDriftCommand, handleAgentsCommand, handleAnalyzeCommand, handleArchiveCommand, DC_SAFE_TARGETS, dcNormalizeCommand, dcUnwrapWrappers, dcSplitSegments, dcValidateTargets, dcCheckJunctionCreation, dcExtractWindowsCmdTargets, dcExtractPowerShellTargets, normalizeSwarmCommandInput, canonicalCommandKey, formatCommandNotFound, executeSwarmCommand, SWARM_COMMAND_TOOL_COMMANDS, SWARM_COMMAND_TOOL_ALLOWLIST, HUMAN_ONLY_SWARM_COMMANDS, classifySwarmCommandToolUse, classifySwarmCommandChatFallbackUse, detectPosixWrites, detectWindowsWrites, resolveWriteTargets, handleAutoProceedCommand, handleBenchmarkCommand, handleBrainstormCommand, handleCheckpointCommand, handleCiSimulateCommand, handleClarifyCommand, createCuratorLLMDelegate, _internals11 as _internals, normalizeRecommendationEntryIdToken, parseKnowledgeRecommendations, parseKnowledgeRecommendationsWithDiagnostics, parseStructuredCuratorBlocks, readCuratorSummary, writeCuratorSummary, filterPhaseEvents, checkPhaseCompliance, runCuratorInit, runCuratorPhase, applyCuratorKnowledgeUpdates, isHiveEligible, checkHivePromotions, createHivePromoterHook, promoteToHive, promoteFromSwarm, handleCloseCommand, handleCodebaseReviewCommand, handleConcurrencyCommand, handleConfigCommand, handleConsolidateCommand, handleCostsCommand, handleCouncilCommand, handleCurateCommand, handleDarkMatterCommand, handleDeepDiveCommand, handleDeepResearchCommand, getPluginConfigDir, getPluginCachePaths, getPluginLockFilePaths, handleDiagnoseCommand, handleDoctorCommand, handleEvidenceCommand, handleEvidenceSummaryCommand, handleExportCommand, handleFullAutoCommand, handleHandoffCommand, handleHistoryCommand, handleKnowledgeQuarantineCommand, handleKnowledgeRestoreCommand, handleKnowledgeMigrateCommand, handleKnowledgeListCommand, handleKnowledgeUnactionableCommand, handleKnowledgeRetryHardeningCommand, handleLearningCommand, handleLinkCommand, handleMemoryCommand, handleMemoryStatusCommand, handleMemoryValueLogCommand, handleMemoryMigrateCommand, handleMemoryImportCommand, handleMemoryExportCommand, handlePlanCommand, handlePreflightCommand, handlePromoteCommand, handleQaGatesCommand, handleResetCommand, handleResetSessionCommand, handleRetrieveCommand, handleRollbackCommand, handleSddStatusCommand, handleSddValidateCommand, handleSddProjectCommand, handleSddCommand, handleSimulateCommand, handleSpecifyCommand, handleStatusCommand, handleSyncPlanCommand, handleTurboCommand, handleUnlinkCommand, handleWriteRetroCommand, handleHelpCommand, COMMAND_REGISTRY, VALID_COMMANDS, _internals48 as _internals1, resolveCommand };
39243
+ export { package_default, handleAcknowledgeSpecDriftCommand, handleAgentsCommand, handleAnalyzeCommand, handleArchiveCommand, DC_SAFE_TARGETS, dcNormalizeCommand, dcUnwrapWrappers, dcSplitSegments, dcValidateTargets, dcCheckJunctionCreation, dcExtractWindowsCmdTargets, dcExtractPowerShellTargets, normalizeSwarmCommandInput, canonicalCommandKey, formatCommandNotFound, executeSwarmCommand, SWARM_COMMAND_TOOL_COMMANDS, SWARM_COMMAND_TOOL_ALLOWLIST, HUMAN_ONLY_SWARM_COMMANDS, classifySwarmCommandToolUse, classifySwarmCommandChatFallbackUse, detectPosixWrites, detectWindowsWrites, resolveWriteTargets, handleAutoProceedCommand, handleBenchmarkCommand, handleBrainstormCommand, handleCheckpointCommand, handleCiSimulateCommand, handleClarifyCommand, createCuratorLLMDelegate, _internals11 as _internals, normalizeRecommendationEntryIdToken, parseKnowledgeRecommendations, parseKnowledgeRecommendationsWithDiagnostics, parseStructuredCuratorBlocks, readCuratorSummary, writeCuratorSummary, appendCuratorRecommendation, mergeCuratorPhaseSummary, filterPhaseEvents, checkPhaseCompliance, runCuratorInit, runCuratorPhase, applyCuratorKnowledgeUpdates, isHiveEligible, checkHivePromotions, _internals13 as _internals1, createHivePromoterHook, promoteToHive, promoteFromSwarm, handleCloseCommand, handleCodebaseReviewCommand, handleConcurrencyCommand, handleConfigCommand, handleConsolidateCommand, handleCostsCommand, handleCouncilCommand, handleCurateCommand, handleDarkMatterCommand, handleDeepDiveCommand, handleDeepResearchCommand, getPluginConfigDir, getPluginCachePaths, getPluginLockFilePaths, handleDiagnoseCommand, handleDoctorCommand, handleEvidenceCommand, handleEvidenceSummaryCommand, handleExportCommand, handleFullAutoCommand, handleHandoffCommand, handleHistoryCommand, handleKnowledgeQuarantineCommand, handleKnowledgeRestoreCommand, handleKnowledgeMigrateCommand, handleKnowledgeListCommand, handleKnowledgeUnactionableCommand, handleKnowledgeRetryHardeningCommand, handleLearningCommand, handleLinkCommand, handleMemoryCommand, handleMemoryStatusCommand, handleMemoryValueLogCommand, handleMemoryMigrateCommand, handleMemoryImportCommand, handleMemoryExportCommand, handlePlanCommand, handlePreflightCommand, handlePromoteCommand, handleQaGatesCommand, handleResetCommand, handleResetSessionCommand, handleRetrieveCommand, handleRollbackCommand, handleSddStatusCommand, handleSddValidateCommand, handleSddProjectCommand, handleSddCommand, handleSimulateCommand, handleSpecifyCommand, handleStatusCommand, handleSyncPlanCommand, handleTurboCommand, handleUnlinkCommand, handleWriteRetroCommand, handleHelpCommand, COMMAND_REGISTRY, VALID_COMMANDS, _internals49 as _internals2, resolveCommand };