opencode-swarm 7.113.3 → 7.114.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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-wvv628sv.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-1qkybw79.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-wvv628sv.js"),
17590
+ import("./curator-llm-factory-awp6xgvt.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.114.0",
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",
@@ -17937,6 +18177,7 @@ var package_default = {
17937
18177
  "lint:ci": "biome ci .",
17938
18178
  "test:unit:ci": "bun scripts/ci/run-unit-tests-local.ts",
17939
18179
  "drift:check": "bun run scripts/drift-check.ts",
18180
+ "drift:fix": "bun run scripts/drift-check.ts --fix --confirm",
17940
18181
  format: "biome format . --write",
17941
18182
  check: "biome check --write .",
17942
18183
  dev: "bun run build && opencode",
@@ -18296,7 +18537,7 @@ function resolveCachePackageRoot(cachePath) {
18296
18537
  const nestedPackageRoot = path36.join(cachePath, "node_modules", "opencode-swarm");
18297
18538
  return existsSync23(nestedPackageRoot) ? nestedPackageRoot : cachePath;
18298
18539
  }
18299
- var _internals24 = {
18540
+ var _internals25 = {
18300
18541
  detectSandboxCapability: () => sandboxCapabilityProbe.detect(),
18301
18542
  getSandboxExecutor: getExecutor
18302
18543
  };
@@ -18880,9 +19121,9 @@ async function checkCurator(directory) {
18880
19121
  }
18881
19122
  async function getSandboxStatus() {
18882
19123
  try {
18883
- const capability = await _internals24.detectSandboxCapability();
19124
+ const capability = await _internals25.detectSandboxCapability();
18884
19125
  const mechanism = capability.mechanism ?? "none";
18885
- const executor = await _internals24.getSandboxExecutor();
19126
+ const executor = await _internals25.getSandboxExecutor();
18886
19127
  const hasExecutor = executor !== null;
18887
19128
  if (hasExecutor) {
18888
19129
  const executorStrength = executor?.strength;
@@ -19634,7 +19875,7 @@ function readPromotionEvidence(directory) {
19634
19875
  }
19635
19876
 
19636
19877
  // src/commands/epic.ts
19637
- var _internals25 = {
19878
+ var _internals26 = {
19638
19879
  loadPluginConfigWithMeta,
19639
19880
  loadPlanJsonOnly,
19640
19881
  getCoChangeData,
@@ -19656,7 +19897,7 @@ async function handleEpicCommand(directory, args, sessionID) {
19656
19897
  if (!sessionID || sessionID.trim() === "") {
19657
19898
  return "Error: No active session context. Epic Mode requires an active session. Use /swarm epic from within an OpenCode session.";
19658
19899
  }
19659
- const session = _internals25.ensureAgentSession(sessionID, undefined, directory);
19900
+ const session = _internals26.ensureAgentSession(sessionID, undefined, directory);
19660
19901
  const arg0 = args[0]?.toLowerCase();
19661
19902
  switch (arg0) {
19662
19903
  case "status":
@@ -19683,7 +19924,7 @@ Usage:
19683
19924
  }
19684
19925
  function enableAndAck(directory, sessionID, session) {
19685
19926
  try {
19686
- _internals25.enableEpicMode(directory, sessionID);
19927
+ _internals26.enableEpicMode(directory, sessionID);
19687
19928
  } catch (err) {
19688
19929
  return `Error enabling Epic Mode: ${err instanceof Error ? err.message : String(err)}`;
19689
19930
  }
@@ -19699,7 +19940,7 @@ function enableAndAck(directory, sessionID, session) {
19699
19940
  }
19700
19941
  function disableAndAck(directory, sessionID, session) {
19701
19942
  try {
19702
- _internals25.disableEpicMode(directory, sessionID);
19943
+ _internals26.disableEpicMode(directory, sessionID);
19703
19944
  } catch (err) {
19704
19945
  return `Error disabling Epic Mode: ${err instanceof Error ? err.message : String(err)}`;
19705
19946
  }
@@ -19708,12 +19949,12 @@ function disableAndAck(directory, sessionID, session) {
19708
19949
  }
19709
19950
  function renderStatus(directory, sessionID) {
19710
19951
  const lines = ["## Epic Mode \u2014 Status", ""];
19711
- if (_internals25.isStateUnreadable(directory)) {
19952
+ if (_internals26.isStateUnreadable(directory)) {
19712
19953
  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
19954
  return lines.join(`
19714
19955
  `);
19715
19956
  }
19716
- const state = _internals25.loadEpicSessionState(directory, sessionID);
19957
+ const state = _internals26.loadEpicSessionState(directory, sessionID);
19717
19958
  if (!state) {
19718
19959
  lines.push("Epic Mode has not been toggled for this session.");
19719
19960
  return lines.join(`
@@ -19765,7 +20006,7 @@ function formatGreenfieldDetail(input) {
19765
20006
  function renderLast(directory) {
19766
20007
  let records;
19767
20008
  try {
19768
- records = _internals25.readPromotionEvidence(directory);
20009
+ records = _internals26.readPromotionEvidence(directory);
19769
20010
  } catch (err) {
19770
20011
  return `Error reading epic-promotions.jsonl: ${err instanceof Error ? err.message : String(err)}`;
19771
20012
  }
@@ -19820,7 +20061,7 @@ function renderLast(directory) {
19820
20061
  `);
19821
20062
  }
19822
20063
  function renderCalibration(directory) {
19823
- if (_internals25.isCalibrationStateUnreadable(directory)) {
20064
+ if (_internals26.isCalibrationStateUnreadable(directory)) {
19824
20065
  return [
19825
20066
  "## Epic Mode \u2014 Calibration",
19826
20067
  "",
@@ -19832,11 +20073,11 @@ function renderCalibration(directory) {
19832
20073
  }
19833
20074
  let state;
19834
20075
  try {
19835
- state = _internals25.loadCalibrationState(directory);
20076
+ state = _internals26.loadCalibrationState(directory);
19836
20077
  } catch (err) {
19837
20078
  return `Error reading calibration state: ${err instanceof Error ? err.message : String(err)}`;
19838
20079
  }
19839
- const { config } = _internals25.loadPluginConfigWithMeta(directory);
20080
+ const { config } = _internals26.loadPluginConfigWithMeta(directory);
19840
20081
  const staticThreshold = config.turbo?.epic?.mode?.activation_threshold ?? 0.3;
19841
20082
  const calibrationCfg = config.turbo?.epic?.calibration;
19842
20083
  const loosenWindow = calibrationCfg?.loosen_window ?? 10;
@@ -19884,7 +20125,7 @@ function renderCalibration(directory) {
19884
20125
  lines.push("");
19885
20126
  let recentDivergent = [];
19886
20127
  try {
19887
- const all = _internals25.readDivergenceHistory(directory, { limit: 50 });
20128
+ const all = _internals26.readDivergenceHistory(directory, { limit: 50 });
19888
20129
  recentDivergent = all.filter((r) => !r.isClean).slice(-5);
19889
20130
  } catch {}
19890
20131
  lines.push("### Recent divergent tasks (tightened the threshold)");
@@ -19901,11 +20142,11 @@ function renderCalibration(directory) {
19901
20142
  `);
19902
20143
  }
19903
20144
  async function renderDecide(directory) {
19904
- const plan = await _internals25.loadPlanJsonOnly(directory);
20145
+ const plan = await _internals26.loadPlanJsonOnly(directory);
19905
20146
  if (!plan) {
19906
20147
  return "No plan found at `.swarm/plan.json`. Run `/swarm plan` first.";
19907
20148
  }
19908
- const { config } = _internals25.loadPluginConfigWithMeta(directory);
20149
+ const { config } = _internals26.loadPluginConfigWithMeta(directory);
19909
20150
  const modeCfg = config.turbo?.epic?.mode;
19910
20151
  const cochangeCfg = config.turbo?.epic?.cochange;
19911
20152
  const activationThreshold = modeCfg?.activation_threshold ?? 0.3;
@@ -19915,20 +20156,20 @@ async function renderDecide(directory) {
19915
20156
  const tasks = [];
19916
20157
  for (const phase of plan.phases) {
19917
20158
  for (const task of phase.tasks) {
19918
- const scopeFiles = _internals25.readTaskScopes(directory, task.id);
20159
+ const scopeFiles = _internals26.readTaskScopes(directory, task.id);
19919
20160
  const scope = scopeFiles ?? task.files_touched ?? [];
19920
20161
  tasks.push({ id: task.id, scope });
19921
20162
  }
19922
20163
  }
19923
- const { pairs, commitsObserved } = await _internals25.getCoChangeData(directory);
20164
+ const { pairs, commitsObserved } = await _internals26.getCoChangeData(directory);
19924
20165
  const isGitProject = (() => {
19925
20166
  try {
19926
- return _internals25.isGitRepo(directory);
20167
+ return _internals26.isGitRepo(directory);
19927
20168
  } catch {
19928
20169
  return false;
19929
20170
  }
19930
20171
  })();
19931
- const verdict = _internals25.decideEpicActivation(tasks, pairs, commitsObserved, {
20172
+ const verdict = _internals26.decideEpicActivation(tasks, pairs, commitsObserved, {
19932
20173
  activationThreshold,
19933
20174
  minCommitsForSignal,
19934
20175
  cochangeNpmiThreshold,
@@ -19972,7 +20213,7 @@ function formatVerdict(verdict) {
19972
20213
  }
19973
20214
 
19974
20215
  // src/services/evidence-service.ts
19975
- var _internals26 = {
20216
+ var _internals27 = {
19976
20217
  loadEvidence,
19977
20218
  listEvidenceTaskIds
19978
20219
  };
@@ -20017,7 +20258,7 @@ function getVerdictEmoji(verdict) {
20017
20258
  return getVerdictIcon(verdict);
20018
20259
  }
20019
20260
  async function getTaskEvidenceData(directory, taskId) {
20020
- const result = await _internals26.loadEvidence(directory, taskId);
20261
+ const result = await _internals27.loadEvidence(directory, taskId);
20021
20262
  if (result.status !== "found") {
20022
20263
  return {
20023
20264
  hasEvidence: false,
@@ -20040,13 +20281,13 @@ async function getTaskEvidenceData(directory, taskId) {
20040
20281
  };
20041
20282
  }
20042
20283
  async function getEvidenceListData(directory) {
20043
- const taskIds = await _internals26.listEvidenceTaskIds(directory);
20284
+ const taskIds = await _internals27.listEvidenceTaskIds(directory);
20044
20285
  if (taskIds.length === 0) {
20045
20286
  return { hasEvidence: false, tasks: [] };
20046
20287
  }
20047
20288
  const tasks = [];
20048
20289
  for (const taskId of taskIds) {
20049
- const result = await _internals26.loadEvidence(directory, taskId);
20290
+ const result = await _internals27.loadEvidence(directory, taskId);
20050
20291
  if (result.status === "found") {
20051
20292
  tasks.push({
20052
20293
  taskId,
@@ -20674,7 +20915,7 @@ function extractCurrentPhaseFromPlan(plan) {
20674
20915
  if (!plan) {
20675
20916
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
20676
20917
  }
20677
- if (!_internals27.validatePlanPhases(plan)) {
20918
+ if (!_internals28.validatePlanPhases(plan)) {
20678
20919
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
20679
20920
  }
20680
20921
  let currentPhase = null;
@@ -20816,9 +21057,9 @@ function extractPhaseMetrics(content) {
20816
21057
  async function getHandoffData(directory) {
20817
21058
  const now = new Date().toISOString();
20818
21059
  const sessionContent = await readSwarmFileAsync(directory, "session/state.json");
20819
- const sessionState = _internals27.parseSessionState(sessionContent);
21060
+ const sessionState = _internals28.parseSessionState(sessionContent);
20820
21061
  const plan = await loadPlanJsonOnly(directory);
20821
- const planInfo = _internals27.extractCurrentPhaseFromPlan(plan);
21062
+ const planInfo = _internals28.extractCurrentPhaseFromPlan(plan);
20822
21063
  if (!plan) {
20823
21064
  const planMdContent = await readSwarmFileAsync(directory, "plan.md");
20824
21065
  if (planMdContent) {
@@ -20837,8 +21078,8 @@ async function getHandoffData(directory) {
20837
21078
  }
20838
21079
  }
20839
21080
  const contextContent = await readSwarmFileAsync(directory, "context.md");
20840
- const recentDecisions = _internals27.extractDecisions(contextContent);
20841
- const rawPhaseMetrics = _internals27.extractPhaseMetrics(contextContent);
21081
+ const recentDecisions = _internals28.extractDecisions(contextContent);
21082
+ const rawPhaseMetrics = _internals28.extractPhaseMetrics(contextContent);
20842
21083
  const phaseMetrics = sanitizeString(rawPhaseMetrics, 1000);
20843
21084
  let delegationState = null;
20844
21085
  if (sessionState?.delegationState) {
@@ -21002,7 +21243,7 @@ ${lines.join(`
21002
21243
  `)}
21003
21244
  \`\`\``;
21004
21245
  }
21005
- var _internals27 = {
21246
+ var _internals28 = {
21006
21247
  getHandoffData,
21007
21248
  formatHandoffMarkdown,
21008
21249
  formatContinuationPrompt,
@@ -21151,15 +21392,15 @@ async function writeSnapshot(directory, state) {
21151
21392
  }
21152
21393
  function createSnapshotWriterHook(directory) {
21153
21394
  return (_input, _output) => {
21154
- _writeInFlight = _writeInFlight.then(() => _internals28.writeSnapshot(directory, swarmState), () => _internals28.writeSnapshot(directory, swarmState));
21395
+ _writeInFlight = _writeInFlight.then(() => _internals29.writeSnapshot(directory, swarmState), () => _internals29.writeSnapshot(directory, swarmState));
21155
21396
  return _writeInFlight;
21156
21397
  };
21157
21398
  }
21158
21399
  async function flushPendingSnapshot(directory) {
21159
- _writeInFlight = _writeInFlight.then(() => _internals28.writeSnapshot(directory, swarmState), () => _internals28.writeSnapshot(directory, swarmState));
21400
+ _writeInFlight = _writeInFlight.then(() => _internals29.writeSnapshot(directory, swarmState), () => _internals29.writeSnapshot(directory, swarmState));
21160
21401
  await _writeInFlight;
21161
21402
  }
21162
- var _internals28 = {
21403
+ var _internals29 = {
21163
21404
  writeSnapshot,
21164
21405
  createSnapshotWriterHook,
21165
21406
  flushPendingSnapshot
@@ -21367,7 +21608,7 @@ var IPV4_PRIVATE_192 = /^192\.168\./;
21367
21608
  var IPV4_ZERO_NETWORK = /^0\./;
21368
21609
  var IPV6_LINK_LOCAL = /^fe80:/i;
21369
21610
  var IPV6_UNIQUE_LOCAL = /^f[cd][0-9a-f]{2}:/i;
21370
- var _internals29 = {
21611
+ var _internals30 = {
21371
21612
  spawnSync: (cmd, args, options) => {
21372
21613
  const mergedEnv = mergeEnvForChild(options?.env, options?.envOverrides);
21373
21614
  return child_process6.spawnSync(cmd, args, {
@@ -21485,7 +21726,7 @@ function validateAndSanitizeGithubUrl(rawUrl, resource) {
21485
21726
  }
21486
21727
  function detectGitRemote(cwd, laneEnv) {
21487
21728
  try {
21488
- const result = _internals29.spawnSync("git", ["remote", "get-url", "origin"], {
21729
+ const result = _internals30.spawnSync("git", ["remote", "get-url", "origin"], {
21489
21730
  encoding: "utf-8",
21490
21731
  stdio: ["ignore", "pipe", "pipe"],
21491
21732
  timeout: 5000,
@@ -21662,7 +21903,7 @@ import * as path42 from "path";
21662
21903
  async function migrateKnowledgeToExternal(_directory, _config) {
21663
21904
  const externalSentinelPath = path42.join(_directory, ".swarm", ".knowledge-external-migrated");
21664
21905
  const contextPath = path42.join(_directory, ".swarm", "context.md");
21665
- if (_internals30.existsSync(externalSentinelPath)) {
21906
+ if (_internals31.existsSync(externalSentinelPath)) {
21666
21907
  return {
21667
21908
  migrated: false,
21668
21909
  entriesMigrated: 0,
@@ -21671,7 +21912,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
21671
21912
  skippedReason: "external-sentinel-exists"
21672
21913
  };
21673
21914
  }
21674
- if (!_internals30.existsSync(contextPath)) {
21915
+ if (!_internals31.existsSync(contextPath)) {
21675
21916
  return {
21676
21917
  migrated: false,
21677
21918
  entriesMigrated: 0,
@@ -21680,7 +21921,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
21680
21921
  skippedReason: "no-context-file"
21681
21922
  };
21682
21923
  }
21683
- const contextContent = await _internals30.readFile(contextPath, "utf-8");
21924
+ const contextContent = await _internals31.readFile(contextPath, "utf-8");
21684
21925
  if (contextContent.trim().length === 0) {
21685
21926
  return {
21686
21927
  migrated: false,
@@ -21698,7 +21939,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
21698
21939
  entriesCount++;
21699
21940
  }
21700
21941
  }
21701
- await _internals30.writeSentinel(externalSentinelPath, entriesCount, entriesCount);
21942
+ await _internals31.writeSentinel(externalSentinelPath, entriesCount, entriesCount);
21702
21943
  return {
21703
21944
  migrated: true,
21704
21945
  entriesMigrated: entriesCount,
@@ -21706,7 +21947,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
21706
21947
  entriesTotal: entriesCount
21707
21948
  };
21708
21949
  }
21709
- var _internals30 = {
21950
+ var _internals31 = {
21710
21951
  appendKnowledge,
21711
21952
  migrateContextToKnowledge,
21712
21953
  migrateKnowledgeToExternal,
@@ -21757,9 +21998,9 @@ async function migrateContextToKnowledge(directory, config) {
21757
21998
  skippedReason: "empty-context"
21758
21999
  };
21759
22000
  }
21760
- const rawEntries = _internals30.parseContextMd(contextContent);
22001
+ const rawEntries = _internals31.parseContextMd(contextContent);
21761
22002
  if (rawEntries.length === 0) {
21762
- await _internals30.writeSentinel(sentinelPath, 0, 0);
22003
+ await _internals31.writeSentinel(sentinelPath, 0, 0);
21763
22004
  return {
21764
22005
  migrated: true,
21765
22006
  entriesMigrated: 0,
@@ -21770,10 +22011,10 @@ async function migrateContextToKnowledge(directory, config) {
21770
22011
  const existing = await readKnowledge(knowledgePath);
21771
22012
  let migrated = 0;
21772
22013
  let dropped = 0;
21773
- const projectName = _internals30.inferProjectName(directory);
22014
+ const projectName = _internals31.inferProjectName(directory);
21774
22015
  for (const raw of rawEntries) {
21775
22016
  if (config.validation_enabled !== false) {
21776
- const category = raw.categoryHint ?? _internals30.inferCategoryFromText(raw.text);
22017
+ const category = raw.categoryHint ?? _internals31.inferCategoryFromText(raw.text);
21777
22018
  const result = validateLesson(raw.text, existing.map((e) => e.lesson), {
21778
22019
  category,
21779
22020
  scope: "global",
@@ -21793,8 +22034,8 @@ async function migrateContextToKnowledge(directory, config) {
21793
22034
  const entry = {
21794
22035
  id: randomUUID6(),
21795
22036
  tier: "swarm",
21796
- lesson: _internals30.truncateLesson(raw.text),
21797
- category: raw.categoryHint ?? _internals30.inferCategoryFromText(raw.text),
22037
+ lesson: _internals31.truncateLesson(raw.text),
22038
+ category: raw.categoryHint ?? _internals31.inferCategoryFromText(raw.text),
21798
22039
  tags: [...inferredTags, `migration:${raw.sourceSection}`],
21799
22040
  scope: "global",
21800
22041
  confidence: 0.3,
@@ -21817,7 +22058,7 @@ async function migrateContextToKnowledge(directory, config) {
21817
22058
  if (migrated > 0) {
21818
22059
  await rewriteKnowledge(knowledgePath, existing);
21819
22060
  }
21820
- await _internals30.writeSentinel(sentinelPath, migrated, dropped);
22061
+ await _internals31.writeSentinel(sentinelPath, migrated, dropped);
21821
22062
  log(`[knowledge-migrator] Migrated ${migrated} entries, dropped ${dropped}`);
21822
22063
  return {
21823
22064
  migrated: true,
@@ -21827,7 +22068,7 @@ async function migrateContextToKnowledge(directory, config) {
21827
22068
  };
21828
22069
  }
21829
22070
  async function migrateHiveKnowledgeLegacy(config) {
21830
- const legacyHivePath = _internals30.resolveLegacyHiveKnowledgePath();
22071
+ const legacyHivePath = _internals31.resolveLegacyHiveKnowledgePath();
21831
22072
  const canonicalHivePath = resolveHiveKnowledgePath();
21832
22073
  const sentinelPath = path42.join(path42.dirname(canonicalHivePath), ".hive-knowledge-migrated");
21833
22074
  if (existsSync28(sentinelPath)) {
@@ -21850,7 +22091,7 @@ async function migrateHiveKnowledgeLegacy(config) {
21850
22091
  }
21851
22092
  const legacyEntries = await readKnowledge(legacyHivePath);
21852
22093
  if (legacyEntries.length === 0) {
21853
- await _internals30.writeSentinel(sentinelPath, 0, 0);
22094
+ await _internals31.writeSentinel(sentinelPath, 0, 0);
21854
22095
  return {
21855
22096
  migrated: true,
21856
22097
  entriesMigrated: 0,
@@ -21898,7 +22139,7 @@ async function migrateHiveKnowledgeLegacy(config) {
21898
22139
  const newHiveEntry = {
21899
22140
  id: resolvedId,
21900
22141
  tier: "hive",
21901
- lesson: _internals30.truncateLesson(lesson),
22142
+ lesson: _internals31.truncateLesson(lesson),
21902
22143
  category,
21903
22144
  tags: ["migration:legacy-hive"],
21904
22145
  scope: scopeTag,
@@ -21917,7 +22158,7 @@ async function migrateHiveKnowledgeLegacy(config) {
21917
22158
  encounter_score: 1
21918
22159
  };
21919
22160
  try {
21920
- await _internals30.appendKnowledge(canonicalHivePath, newHiveEntry);
22161
+ await _internals31.appendKnowledge(canonicalHivePath, newHiveEntry);
21921
22162
  existingHiveEntries.push(newHiveEntry);
21922
22163
  migrated++;
21923
22164
  } catch (appendError) {
@@ -21933,7 +22174,7 @@ async function migrateHiveKnowledgeLegacy(config) {
21933
22174
  dropped++;
21934
22175
  }
21935
22176
  }
21936
- await _internals30.writeSentinel(sentinelPath, migrated, dropped);
22177
+ await _internals31.writeSentinel(sentinelPath, migrated, dropped);
21937
22178
  log(`[knowledge-migrator] Migrated ${migrated} legacy hive entries, dropped ${dropped}`);
21938
22179
  return {
21939
22180
  migrated: true,
@@ -21944,7 +22185,7 @@ async function migrateHiveKnowledgeLegacy(config) {
21944
22185
  };
21945
22186
  }
21946
22187
  function parseContextMd(content) {
21947
- const sections = _internals30.splitIntoSections(content);
22188
+ const sections = _internals31.splitIntoSections(content);
21948
22189
  const entries = [];
21949
22190
  const seen = new Set;
21950
22191
  const sectionPatterns = [
@@ -21960,7 +22201,7 @@ function parseContextMd(content) {
21960
22201
  const match = sectionPatterns.find((sp) => sp.pattern.test(section.heading));
21961
22202
  if (!match)
21962
22203
  continue;
21963
- const bullets = _internals30.extractBullets(section.body);
22204
+ const bullets = _internals31.extractBullets(section.body);
21964
22205
  for (const bullet of bullets) {
21965
22206
  if (bullet.length < 15)
21966
22207
  continue;
@@ -21969,9 +22210,9 @@ function parseContextMd(content) {
21969
22210
  continue;
21970
22211
  seen.add(normalized);
21971
22212
  entries.push({
21972
- text: _internals30.truncateLesson(bullet),
22213
+ text: _internals31.truncateLesson(bullet),
21973
22214
  sourceSection: match.sourceSection,
21974
- categoryHint: _internals30.inferCategoryFromText(bullet)
22215
+ categoryHint: _internals31.inferCategoryFromText(bullet)
21975
22216
  });
21976
22217
  }
21977
22218
  }
@@ -22061,8 +22302,8 @@ async function writeSentinel(sentinelPath, migrated, dropped) {
22061
22302
  schema_version: 1,
22062
22303
  migration_tool: "knowledge-migrator.ts"
22063
22304
  };
22064
- await _internals30.mkdir(path42.dirname(sentinelPath), { recursive: true });
22065
- await _internals30.writeFile(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
22305
+ await _internals31.mkdir(path42.dirname(sentinelPath), { recursive: true });
22306
+ await _internals31.writeFile(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
22066
22307
  }
22067
22308
  function resolveLegacyHiveKnowledgePath() {
22068
22309
  const platform = process.platform;
@@ -22443,7 +22684,7 @@ function timeoutMessage(timeoutMs) {
22443
22684
  async function computeWithTimeout(directory, currentPhase, timeoutMs) {
22444
22685
  const controller = new AbortController;
22445
22686
  let timeout;
22446
- const metricsPromise = _internals31.computeLearningMetrics(directory, {
22687
+ const metricsPromise = _internals32.computeLearningMetrics(directory, {
22447
22688
  currentPhase,
22448
22689
  signal: controller.signal
22449
22690
  });
@@ -22500,7 +22741,7 @@ ${JSON.stringify({
22500
22741
  return `Error computing learning metrics: ${message}. Run /swarm diagnose to check .swarm/ health.`;
22501
22742
  }
22502
22743
  }
22503
- var _internals31 = {
22744
+ var _internals32 = {
22504
22745
  computeLearningMetrics
22505
22746
  };
22506
22747
 
@@ -22702,7 +22943,7 @@ async function readLatestLoopState(directory) {
22702
22943
  return null;
22703
22944
  }
22704
22945
  }
22705
- var _internals32 = {
22946
+ var _internals33 = {
22706
22947
  readLatestLoopState
22707
22948
  };
22708
22949
  var USAGE7 = `Usage: /swarm loop <objective> [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]
@@ -22815,7 +23056,7 @@ ${USAGE7}`;
22815
23056
  }
22816
23057
  let autonomy = parsed.autonomy;
22817
23058
  if (parsed.resume && !parsed.autonomyExplicit) {
22818
- const state = await _internals32.readLatestLoopState(_directory);
23059
+ const state = await _internals33.readLatestLoopState(_directory);
22819
23060
  if (state?.autonomy && AUTONOMY_LEVELS.has(state.autonomy)) {
22820
23061
  autonomy = state.autonomy;
22821
23062
  }
@@ -22903,7 +23144,7 @@ async function rmTempRoot(tempRoot) {
22903
23144
  } catch (err) {
22904
23145
  if (attempt === 9)
22905
23146
  throw err;
22906
- await new Promise((resolve12) => setTimeout(resolve12, 50));
23147
+ await new Promise((resolve13) => setTimeout(resolve13, 50));
22907
23148
  }
22908
23149
  }
22909
23150
  }
@@ -23751,15 +23992,15 @@ function truncate(value, maxLength) {
23751
23992
  }
23752
23993
 
23753
23994
  // src/services/plan-service.ts
23754
- var _internals33 = {
23995
+ var _internals34 = {
23755
23996
  loadPlanJsonOnly,
23756
23997
  derivePlanMarkdown,
23757
23998
  readSwarmFileAsync
23758
23999
  };
23759
24000
  async function getPlanData(directory, phaseArg) {
23760
- const plan = await _internals33.loadPlanJsonOnly(directory);
24001
+ const plan = await _internals34.loadPlanJsonOnly(directory);
23761
24002
  if (plan) {
23762
- const fullMarkdown = _internals33.derivePlanMarkdown(plan);
24003
+ const fullMarkdown = _internals34.derivePlanMarkdown(plan);
23763
24004
  if (phaseArg === undefined || phaseArg === null || phaseArg === "") {
23764
24005
  return {
23765
24006
  hasPlan: true,
@@ -23802,7 +24043,7 @@ async function getPlanData(directory, phaseArg) {
23802
24043
  isLegacy: false
23803
24044
  };
23804
24045
  }
23805
- const planContent = await _internals33.readSwarmFileAsync(directory, "plan.md");
24046
+ const planContent = await _internals34.readSwarmFileAsync(directory, "plan.md");
23806
24047
  if (!planContent) {
23807
24048
  return {
23808
24049
  hasPlan: false,
@@ -23899,7 +24140,7 @@ async function handlePlanCommand(directory, args) {
23899
24140
  return formatPlanMarkdown(planData);
23900
24141
  }
23901
24142
  // src/commands/post-mortem.ts
23902
- var _internals34 = {
24143
+ var _internals35 = {
23903
24144
  createCuratorLLMDelegate,
23904
24145
  runCuratorPostMortem
23905
24146
  };
@@ -23947,10 +24188,10 @@ async function handlePostMortemCommand(directory, args, options) {
23947
24188
  };
23948
24189
  if (options?.sessionID) {
23949
24190
  try {
23950
- pmOptions.llmDelegate = _internals34.createCuratorLLMDelegate(directory, "postmortem", options.sessionID);
24191
+ pmOptions.llmDelegate = _internals35.createCuratorLLMDelegate(directory, "postmortem", options.sessionID);
23951
24192
  } catch {}
23952
24193
  }
23953
- const result = await _internals34.runCuratorPostMortem(directory, pmOptions);
24194
+ const result = await _internals35.runCuratorPostMortem(directory, pmOptions);
23954
24195
  const lines = [];
23955
24196
  if (result.success) {
23956
24197
  lines.push("## Post-Mortem Report Generated");
@@ -24186,7 +24427,7 @@ function formatMergeGroupStatus(status, conclusion, htmlUrl) {
24186
24427
  }
24187
24428
  return parts.join(" ");
24188
24429
  }
24189
- var _internals35 = {
24430
+ var _internals36 = {
24190
24431
  formatRelativeTime,
24191
24432
  formatMergeGroupStatus,
24192
24433
  listActive,
@@ -24194,7 +24435,7 @@ var _internals35 = {
24194
24435
  parseMergeGroupRuns
24195
24436
  };
24196
24437
  async function handlePrMonitorStatusCommand(directory, _args, sessionID, source) {
24197
- const allActive = await _internals35.listActive(directory);
24438
+ const allActive = await _internals36.listActive(directory);
24198
24439
  const allSessions = source === "cli";
24199
24440
  const subs = allSessions ? allActive : allActive.filter((record) => record.sessionID === sessionID);
24200
24441
  if (subs.length === 0) {
@@ -24210,7 +24451,7 @@ async function handlePrMonitorStatusCommand(directory, _args, sessionID, source)
24210
24451
  const index = i + 1;
24211
24452
  lines.push(` ${index}. ${sub.repoFullName}#${sub.prNumber}`);
24212
24453
  lines.push(` URL: ${sub.prUrl}`);
24213
- const mergeGroupRuns = await _internals35.listMergeGroupRuns(directory, sub.repoFullName, sub.prNumber);
24454
+ const mergeGroupRuns = await _internals36.listMergeGroupRuns(directory, sub.repoFullName, sub.prNumber);
24214
24455
  if (mergeGroupRuns.runs.length > 0) {
24215
24456
  lines.push(" Merge-group runs:");
24216
24457
  for (const run of mergeGroupRuns.runs) {
@@ -24350,7 +24591,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
24350
24591
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
24351
24592
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
24352
24593
  try {
24353
- const config = _internals36.loadPluginConfig(directory);
24594
+ const config = _internals37.loadPluginConfig(directory);
24354
24595
  const prMonitorConfig = config.pr_monitor;
24355
24596
  if (!prMonitorConfig?.enabled) {
24356
24597
  return [
@@ -24360,7 +24601,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
24360
24601
  ].join(`
24361
24602
  `);
24362
24603
  }
24363
- await _internals36.subscribe(directory, {
24604
+ await _internals37.subscribe(directory, {
24364
24605
  sessionID,
24365
24606
  prNumber: prInfo.number,
24366
24607
  repoFullName,
@@ -24388,7 +24629,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
24388
24629
  `);
24389
24630
  }
24390
24631
  }
24391
- var _internals36 = {
24632
+ var _internals37 = {
24392
24633
  loadPluginConfig,
24393
24634
  subscribe
24394
24635
  };
@@ -24411,9 +24652,9 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
24411
24652
  `);
24412
24653
  }
24413
24654
  const refToken = rest[0];
24414
- const prInfo = _internals37.parsePrRef(refToken, directory);
24655
+ const prInfo = _internals38.parsePrRef(refToken, directory);
24415
24656
  if (!prInfo) {
24416
- if (_internals37.looksLikePrRef(refToken)) {
24657
+ if (_internals38.looksLikePrRef(refToken)) {
24417
24658
  return [
24418
24659
  `Error: Could not resolve PR reference from "${refToken}".`,
24419
24660
  "",
@@ -24434,8 +24675,8 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
24434
24675
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
24435
24676
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
24436
24677
  try {
24437
- const correlationId = _internals37.buildCorrelationId(sessionID, repoFullName, prInfo.number);
24438
- const result = await _internals37.unsubscribe(directory, correlationId);
24678
+ const correlationId = _internals38.buildCorrelationId(sessionID, repoFullName, prInfo.number);
24679
+ const result = await _internals38.unsubscribe(directory, correlationId);
24439
24680
  if (!result) {
24440
24681
  return [
24441
24682
  `Not subscribed to ${prUrl}`,
@@ -24462,7 +24703,7 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
24462
24703
  `);
24463
24704
  }
24464
24705
  }
24465
- var _internals37 = {
24706
+ var _internals38 = {
24466
24707
  unsubscribe,
24467
24708
  buildCorrelationId,
24468
24709
  parsePrRef,
@@ -24780,7 +25021,7 @@ async function _detectAvailableLinter(_projectDir, biomeBin, eslintBin) {
24780
25021
  stderr: "pipe"
24781
25022
  });
24782
25023
  const biomeExit = biomeProc.exited;
24783
- const timeout = new Promise((resolve13) => setTimeout(() => resolve13("timeout"), DETECT_TIMEOUT));
25024
+ const timeout = new Promise((resolve14) => setTimeout(() => resolve14("timeout"), DETECT_TIMEOUT));
24784
25025
  const result = await Promise.race([biomeExit, timeout]);
24785
25026
  if (result === "timeout") {
24786
25027
  biomeProc.kill();
@@ -24794,7 +25035,7 @@ async function _detectAvailableLinter(_projectDir, biomeBin, eslintBin) {
24794
25035
  stderr: "pipe"
24795
25036
  });
24796
25037
  const eslintExit = eslintProc.exited;
24797
- const timeout = new Promise((resolve13) => setTimeout(() => resolve13("timeout"), DETECT_TIMEOUT));
25038
+ const timeout = new Promise((resolve14) => setTimeout(() => resolve14("timeout"), DETECT_TIMEOUT));
24798
25039
  const result = await Promise.race([eslintExit, timeout]);
24799
25040
  if (result === "timeout") {
24800
25041
  eslintProc.kill();
@@ -24944,15 +25185,15 @@ var lint = createSwarmTool({
24944
25185
  }
24945
25186
  const { mode } = args;
24946
25187
  const cwd = directory;
24947
- const linter = await _internals38.detectAvailableLinter(directory);
25188
+ const linter = await _internals39.detectAvailableLinter(directory);
24948
25189
  if (linter) {
24949
- const result = await _internals38.runLint(linter, mode, directory);
25190
+ const result = await _internals39.runLint(linter, mode, directory);
24950
25191
  return JSON.stringify(result, null, 2);
24951
25192
  }
24952
- const additionalLinter = _internals38.detectAdditionalLinter(cwd);
25193
+ const additionalLinter = _internals39.detectAdditionalLinter(cwd);
24953
25194
  if (additionalLinter) {
24954
25195
  warn(`[lint] Using ${additionalLinter} linter for this project`);
24955
- const result = await _internals38.runAdditionalLint(additionalLinter, mode, cwd);
25196
+ const result = await _internals39.runAdditionalLint(additionalLinter, mode, cwd);
24956
25197
  return JSON.stringify(result, null, 2);
24957
25198
  }
24958
25199
  const errorResult = {
@@ -24966,7 +25207,7 @@ For Rust: rustup component add clippy`
24966
25207
  return JSON.stringify(errorResult, null, 2);
24967
25208
  }
24968
25209
  });
24969
- var _internals38 = {
25210
+ var _internals39 = {
24970
25211
  detectAvailableLinter,
24971
25212
  runLint,
24972
25213
  detectAdditionalLinter,
@@ -25654,7 +25895,7 @@ var secretscan = createSwarmTool({
25654
25895
  });
25655
25896
  async function runSecretscan(directory) {
25656
25897
  try {
25657
- const result = await _internals39.secretscan.execute({ directory }, {});
25898
+ const result = await _internals40.secretscan.execute({ directory }, {});
25658
25899
  const jsonStr = typeof result === "string" ? result : result.output;
25659
25900
  return JSON.parse(jsonStr);
25660
25901
  } catch (e) {
@@ -25726,7 +25967,7 @@ async function runSecretscanOnFiles(files, directory) {
25726
25967
  };
25727
25968
  }
25728
25969
  }
25729
- var _internals39 = {
25970
+ var _internals40 = {
25730
25971
  secretscan,
25731
25972
  runSecretscan,
25732
25973
  runSecretscanOnFiles,
@@ -26002,7 +26243,7 @@ async function buildImpactMapInternal(cwd) {
26002
26243
  }
26003
26244
  return impactMap;
26004
26245
  }
26005
- var _internals40 = {
26246
+ var _internals41 = {
26006
26247
  validateProjectRoot,
26007
26248
  normalizePath: normalizePath2,
26008
26249
  isCacheStale,
@@ -26017,8 +26258,8 @@ var _internals40 = {
26017
26258
  _clearGoModuleCache
26018
26259
  };
26019
26260
  async function buildImpactMap(cwd) {
26020
- const impactMap = await _internals40.buildImpactMapInternal(cwd);
26021
- await _internals40.saveImpactMap(cwd, impactMap);
26261
+ const impactMap = await _internals41.buildImpactMapInternal(cwd);
26262
+ await _internals41.saveImpactMap(cwd, impactMap);
26022
26263
  return impactMap;
26023
26264
  }
26024
26265
  async function loadImpactMap(cwd, options) {
@@ -26032,7 +26273,7 @@ async function loadImpactMap(cwd, options) {
26032
26273
  const hasValidValues = Object.values(map).every((v) => Array.isArray(v) && v.every((item) => typeof item === "string"));
26033
26274
  if (hasValidValues) {
26034
26275
  const generatedAt = new Date(data.generatedAt).getTime();
26035
- if (!_internals40.isCacheStale(map, generatedAt)) {
26276
+ if (!_internals41.isCacheStale(map, generatedAt)) {
26036
26277
  return map;
26037
26278
  }
26038
26279
  if (options?.skipRebuild) {
@@ -26052,13 +26293,13 @@ async function loadImpactMap(cwd, options) {
26052
26293
  if (options?.skipRebuild) {
26053
26294
  return {};
26054
26295
  }
26055
- return _internals40.buildImpactMap(cwd);
26296
+ return _internals41.buildImpactMap(cwd);
26056
26297
  }
26057
26298
  async function saveImpactMap(cwd, impactMap) {
26058
26299
  if (!path50.isAbsolute(cwd)) {
26059
26300
  throw new Error(`saveImpactMap requires an absolute project root path, got: "${cwd}"`);
26060
26301
  }
26061
- _internals40.validateProjectRoot(cwd);
26302
+ _internals41.validateProjectRoot(cwd);
26062
26303
  const cacheDir2 = path50.join(cwd, ".swarm", "cache");
26063
26304
  const cachePath = path50.join(cacheDir2, "impact-map.json");
26064
26305
  if (!fs19.existsSync(cacheDir2)) {
@@ -26082,7 +26323,7 @@ async function analyzeImpact(changedFiles, cwd, budget) {
26082
26323
  };
26083
26324
  }
26084
26325
  const validFiles = changedFiles.filter((f) => typeof f === "string" && f.length > 0 && !f.includes("\x00"));
26085
- const impactMap = await _internals40.loadImpactMap(cwd);
26326
+ const impactMap = await _internals41.loadImpactMap(cwd);
26086
26327
  const impactedTestsSet = new Set;
26087
26328
  const untestedFiles = [];
26088
26329
  let visitedCount = 0;
@@ -26552,7 +26793,7 @@ function batchAppendTestRuns(records, workingDir) {
26552
26793
  }
26553
26794
  const historyPath = getHistoryPath(workingDir);
26554
26795
  const historyDir = path51.dirname(historyPath);
26555
- _internals41.validateProjectRoot(workingDir);
26796
+ _internals42.validateProjectRoot(workingDir);
26556
26797
  if (!fs20.existsSync(historyDir)) {
26557
26798
  fs20.mkdirSync(historyDir, { recursive: true });
26558
26799
  }
@@ -26675,7 +26916,7 @@ function getAllHistory(workingDir) {
26675
26916
  records.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
26676
26917
  return records;
26677
26918
  }
26678
- var _internals41 = {
26919
+ var _internals42 = {
26679
26920
  validateProjectRoot
26680
26921
  };
26681
26922
 
@@ -27944,9 +28185,9 @@ async function runTests(framework, scope, files, coverage, timeout_ms, cwd, bail
27944
28185
  stderr: "pipe",
27945
28186
  cwd
27946
28187
  });
27947
- const timeoutPromise = new Promise((resolve16) => setTimeout(() => {
28188
+ const timeoutPromise = new Promise((resolve17) => setTimeout(() => {
27948
28189
  proc.kill();
27949
- resolve16(-1);
28190
+ resolve17(-1);
27950
28191
  }, timeout_ms));
27951
28192
  const [exitCode, stdoutResult, stderrResult] = await Promise.all([
27952
28193
  Promise.race([proc.exited, timeoutPromise]),
@@ -28104,11 +28345,11 @@ function normalizeHistoryTestFile(testFile, workingDir) {
28104
28345
  const normalized = testFile.replace(/\\/g, "/");
28105
28346
  if (!path53.isAbsolute(testFile))
28106
28347
  return normalized;
28107
- const relative6 = path53.relative(workingDir, testFile);
28108
- if (relative6.startsWith("..") || path53.isAbsolute(relative6)) {
28348
+ const relative7 = path53.relative(workingDir, testFile);
28349
+ if (relative7.startsWith("..") || path53.isAbsolute(relative7)) {
28109
28350
  return normalized;
28110
28351
  }
28111
- return relative6.replace(/\\/g, "/");
28352
+ return relative7.replace(/\\/g, "/");
28112
28353
  }
28113
28354
  function combineAggregateResult(current, next) {
28114
28355
  if (current === "fail" || next === "fail")
@@ -28653,9 +28894,9 @@ function getVersionFileVersion(dir) {
28653
28894
  async function runVersionCheck(dir, _timeoutMs) {
28654
28895
  const startTime = Date.now();
28655
28896
  try {
28656
- const packageVersion = _internals42.getPackageVersion(dir);
28657
- const changelogVersion = _internals42.getChangelogVersion(dir);
28658
- const versionFileVersion = _internals42.getVersionFileVersion(dir);
28897
+ const packageVersion = _internals43.getPackageVersion(dir);
28898
+ const changelogVersion = _internals43.getChangelogVersion(dir);
28899
+ const versionFileVersion = _internals43.getVersionFileVersion(dir);
28659
28900
  const versions = [];
28660
28901
  if (packageVersion)
28661
28902
  versions.push(`package.json: ${packageVersion}`);
@@ -29019,7 +29260,7 @@ async function runPreflight(dir, phase, config) {
29019
29260
  const reportId = `preflight-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
29020
29261
  let validatedDir;
29021
29262
  try {
29022
- validatedDir = _internals42.validateDirectoryPath(dir);
29263
+ validatedDir = _internals43.validateDirectoryPath(dir);
29023
29264
  } catch (error2) {
29024
29265
  return {
29025
29266
  id: reportId,
@@ -29039,7 +29280,7 @@ async function runPreflight(dir, phase, config) {
29039
29280
  }
29040
29281
  let validatedTimeout;
29041
29282
  try {
29042
- validatedTimeout = _internals42.validateTimeout(config?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
29283
+ validatedTimeout = _internals43.validateTimeout(config?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
29043
29284
  } catch (error2) {
29044
29285
  return {
29045
29286
  id: reportId,
@@ -29080,12 +29321,12 @@ async function runPreflight(dir, phase, config) {
29080
29321
  });
29081
29322
  const checks = [];
29082
29323
  log("[Preflight] Running lint check...");
29083
- const lintResult = await _internals42.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
29324
+ const lintResult = await _internals43.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
29084
29325
  checks.push(lintResult);
29085
29326
  log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`);
29086
29327
  if (!cfg.skipTests) {
29087
29328
  log("[Preflight] Running tests check...");
29088
- const testsResult = await _internals42.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
29329
+ const testsResult = await _internals43.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
29089
29330
  checks.push(testsResult);
29090
29331
  log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`);
29091
29332
  } else {
@@ -29097,7 +29338,7 @@ async function runPreflight(dir, phase, config) {
29097
29338
  }
29098
29339
  if (!cfg.skipSecrets) {
29099
29340
  log("[Preflight] Running secrets check...");
29100
- const secretsResult = await _internals42.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
29341
+ const secretsResult = await _internals43.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
29101
29342
  checks.push(secretsResult);
29102
29343
  log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`);
29103
29344
  } else {
@@ -29109,7 +29350,7 @@ async function runPreflight(dir, phase, config) {
29109
29350
  }
29110
29351
  if (!cfg.skipEvidence) {
29111
29352
  log("[Preflight] Running evidence check...");
29112
- const evidenceResult = await _internals42.runEvidenceCheck(validatedDir);
29353
+ const evidenceResult = await _internals43.runEvidenceCheck(validatedDir);
29113
29354
  checks.push(evidenceResult);
29114
29355
  log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`);
29115
29356
  } else {
@@ -29120,12 +29361,12 @@ async function runPreflight(dir, phase, config) {
29120
29361
  });
29121
29362
  }
29122
29363
  log("[Preflight] Running requirement coverage check...");
29123
- const reqCoverageResult = await _internals42.runRequirementCoverageCheck(validatedDir, phase);
29364
+ const reqCoverageResult = await _internals43.runRequirementCoverageCheck(validatedDir, phase);
29124
29365
  checks.push(reqCoverageResult);
29125
29366
  log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`);
29126
29367
  if (!cfg.skipVersion) {
29127
29368
  log("[Preflight] Running version check...");
29128
- const versionResult = await _internals42.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
29369
+ const versionResult = await _internals43.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
29129
29370
  checks.push(versionResult);
29130
29371
  log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`);
29131
29372
  } else {
@@ -29188,10 +29429,10 @@ function formatPreflightMarkdown(report) {
29188
29429
  async function handlePreflightCommand(directory, _args) {
29189
29430
  const plan = await loadPlan(directory);
29190
29431
  const phase = plan?.current_phase ?? 1;
29191
- const report = await _internals42.runPreflight(directory, phase);
29192
- return _internals42.formatPreflightMarkdown(report);
29432
+ const report = await _internals43.runPreflight(directory, phase);
29433
+ return _internals43.formatPreflightMarkdown(report);
29193
29434
  }
29194
- var _internals42 = {
29435
+ var _internals43 = {
29195
29436
  runPreflight,
29196
29437
  formatPreflightMarkdown,
29197
29438
  handlePreflightCommand,
@@ -29427,13 +29668,13 @@ class CircuitBreaker {
29427
29668
  if (this.config.callTimeoutMs <= 0) {
29428
29669
  return fn();
29429
29670
  }
29430
- return new Promise((resolve17, reject) => {
29671
+ return new Promise((resolve18, reject) => {
29431
29672
  const timeout = setTimeout(() => {
29432
29673
  reject(new Error(`Call timeout after ${this.config.callTimeoutMs}ms`));
29433
29674
  }, this.config.callTimeoutMs);
29434
29675
  fn().then((result) => {
29435
29676
  clearTimeout(timeout);
29436
- resolve17(result);
29677
+ resolve18(result);
29437
29678
  }).catch((error2) => {
29438
29679
  clearTimeout(timeout);
29439
29680
  reject(error2);
@@ -29732,7 +29973,7 @@ class AutomationQueue {
29732
29973
 
29733
29974
  // src/background/worker.ts
29734
29975
  function sleep(ms) {
29735
- return new Promise((resolve17) => setTimeout(resolve17, ms));
29976
+ return new Promise((resolve18) => setTimeout(resolve18, ms));
29736
29977
  }
29737
29978
 
29738
29979
  class WorkerManager {
@@ -30697,7 +30938,7 @@ async function recordReplayEntry(artifactPath, sessionID, entry) {
30697
30938
  }
30698
30939
 
30699
30940
  // src/prm/index.ts
30700
- var _internals43 = {
30941
+ var _internals44 = {
30701
30942
  getAgentSession,
30702
30943
  readTrajectory,
30703
30944
  getInMemoryTrajectory,
@@ -30720,12 +30961,12 @@ function resetPrmSessionState(session, sessionId) {
30720
30961
  session.prmTrajectoryStep = 0;
30721
30962
  session.replayArtifactPath = null;
30722
30963
  if (sessionId) {
30723
- _internals43.clearTrajectoryCache(sessionId);
30964
+ _internals44.clearTrajectoryCache(sessionId);
30724
30965
  }
30725
30966
  }
30726
30967
 
30727
30968
  // src/commands/reset-session.ts
30728
- var _internals44 = {
30969
+ var _internals45 = {
30729
30970
  cleanupOrphanedBranches
30730
30971
  };
30731
30972
  function errorMessage(err) {
@@ -30791,7 +31032,7 @@ async function handleResetSessionCommand(directory, _args) {
30791
31032
  results.push(`\u26A0\uFE0F Failed to remove .swarm-worktrees/: ${errorMessage(err)}`);
30792
31033
  }
30793
31034
  try {
30794
- const branchResult = await _internals44.cleanupOrphanedBranches(directory, []);
31035
+ const branchResult = await _internals45.cleanupOrphanedBranches(directory, []);
30795
31036
  if (branchResult.removed.length > 0) {
30796
31037
  results.push(`\u2705 Removed ${branchResult.removed.length} orphan swarm-lane branch(es)`);
30797
31038
  }
@@ -31128,7 +31369,7 @@ async function handleRollbackCommand(directory, args) {
31128
31369
  // src/commands/sdd.ts
31129
31370
  import * as fs29 from "fs";
31130
31371
  import * as path61 from "path";
31131
- var _internals45 = {
31372
+ var _internals46 = {
31132
31373
  writeProjectedSpecSync
31133
31374
  };
31134
31375
  var SWARM_SPEC_REL = path61.join(".swarm", "spec.md");
@@ -31524,7 +31765,7 @@ ${USAGE9}`;
31524
31765
 
31525
31766
  ${USAGE9}`;
31526
31767
  }
31527
- const result2 = _internals45.writeProjectedSpecSync(directory, {
31768
+ const result2 = _internals46.writeProjectedSpecSync(directory, {
31528
31769
  source: "speckit",
31529
31770
  feature: resolution.feature,
31530
31771
  dryRun: parsed.dryRun,
@@ -31582,7 +31823,7 @@ ${formatList(result2.projection.warnings)}` : ""
31582
31823
  ].join(`
31583
31824
  `);
31584
31825
  }
31585
- const result = _internals45.writeProjectedSpecSync(directory, {
31826
+ const result = _internals46.writeProjectedSpecSync(directory, {
31586
31827
  changeId: parsed.changeId,
31587
31828
  dryRun: parsed.dryRun,
31588
31829
  overwrite: parsed.overwrite
@@ -31663,7 +31904,7 @@ async function handleSimulateCommand(directory, args) {
31663
31904
  }
31664
31905
  let darkMatterPairs;
31665
31906
  try {
31666
- darkMatterPairs = await _internals20.detectDarkMatter(directory, options);
31907
+ darkMatterPairs = await _internals21.detectDarkMatter(directory, options);
31667
31908
  } catch (err) {
31668
31909
  const errMsg = err instanceof Error ? err.message : String(err);
31669
31910
  return `## Simulate Report
@@ -31968,10 +32209,12 @@ var DEFAULT_CONTEXT_BUDGET_CONFIG = {
31968
32209
  };
31969
32210
 
31970
32211
  // src/services/status-service.ts
31971
- var _internals46 = {
32212
+ var _internals47 = {
31972
32213
  loadLeanTurboRunState,
31973
32214
  hasActiveLeanTurbo,
31974
- hasActiveFullAuto
32215
+ hasActiveFullAuto,
32216
+ getActiveFullAutoSessionID,
32217
+ loadFullAutoRunState
31975
32218
  };
31976
32219
  function readSpecStalenessSnapshot(directory) {
31977
32220
  try {
@@ -32069,11 +32312,26 @@ async function getStatusData(directory, agents) {
32069
32312
  status.pendingProposals = await countProposals(directory);
32070
32313
  status.unactionableQueueDepth = await safeLineCount(resolveUnactionablePath(directory));
32071
32314
  status.insightCandidatesPending = await safeLineCount(validateSwarmPath(directory, "insight-candidates.jsonl"));
32315
+ status.fullAutoActive = _internals47.hasActiveFullAuto();
32316
+ if (status.fullAutoActive) {
32317
+ const sid = _internals47.getActiveFullAutoSessionID();
32318
+ if (sid) {
32319
+ const runState = _internals47.loadFullAutoRunState(directory, sid);
32320
+ if (runState?.lastEscalation) {
32321
+ status.fullAutoEscalation = {
32322
+ reason: runState.lastEscalation.reason,
32323
+ interactionCount: runState.lastEscalation.interactionCount,
32324
+ deadlockCount: runState.lastEscalation.deadlockCount,
32325
+ phase: runState.lastEscalation.phase
32326
+ };
32327
+ }
32328
+ }
32329
+ }
32072
32330
  return enrichWithLeanTurbo(status, directory);
32073
32331
  }
32074
32332
  function enrichWithLeanTurbo(status, directory) {
32075
32333
  const turboMode = hasActiveTurboMode();
32076
- const leanActive = _internals46.hasActiveLeanTurbo();
32334
+ const leanActive = _internals47.hasActiveLeanTurbo();
32077
32335
  let turboStrategy = "off";
32078
32336
  if (leanActive) {
32079
32337
  turboStrategy = "lean";
@@ -32092,7 +32350,7 @@ function enrichWithLeanTurbo(status, directory) {
32092
32350
  }
32093
32351
  }
32094
32352
  if (leanSessionID) {
32095
- const runState = _internals46.loadLeanTurboRunState(directory, leanSessionID);
32353
+ const runState = _internals47.loadLeanTurboRunState(directory, leanSessionID);
32096
32354
  if (runState) {
32097
32355
  status.leanTurboPhase = runState.phase;
32098
32356
  status.leanMaxParallelCoders = runState.maxParallelCoders;
@@ -32124,7 +32382,6 @@ function enrichWithLeanTurbo(status, directory) {
32124
32382
  }
32125
32383
  }
32126
32384
  }
32127
- status.fullAutoActive = _internals46.hasActiveFullAuto();
32128
32385
  return status;
32129
32386
  }
32130
32387
  function formatStatusMarkdown(status) {
@@ -32165,13 +32422,19 @@ function formatStatusMarkdown(status) {
32165
32422
  } else {
32166
32423
  lines.push(`**Turbo**: standard`);
32167
32424
  }
32168
- if (status.fullAutoActive) {
32169
- lines.push(`**Full-Auto**: active`);
32170
- }
32171
32425
  } else if (status.turboStrategy === undefined && status.turboMode === true) {
32172
32426
  lines.push("");
32173
32427
  lines.push("**TURBO MODE**: active");
32174
32428
  }
32429
+ if (status.fullAutoActive) {
32430
+ lines.push("");
32431
+ lines.push("**Full-Auto**: active");
32432
+ if (status.fullAutoEscalation) {
32433
+ const e = status.fullAutoEscalation;
32434
+ const phaseStr = e.phase !== undefined ? ` | Phase ${e.phase}` : "";
32435
+ lines.push(` - Escalation: ${e.reason} (interactions=${e.interactionCount}, deadlocks=${e.deadlockCount}${phaseStr})`);
32436
+ }
32437
+ }
32175
32438
  if (status.contextBudgetPct !== null && status.contextBudgetPct > 0) {
32176
32439
  const pct = status.contextBudgetPct.toFixed(1);
32177
32440
  const budgetTokens = DEFAULT_CONTEXT_BUDGET_CONFIG.budgetTokens;
@@ -32278,7 +32541,7 @@ No active swarm plan found. Nothing to sync.`;
32278
32541
 
32279
32542
  // src/commands/turbo.ts
32280
32543
  init_logger();
32281
- var _internals47 = {
32544
+ var _internals48 = {
32282
32545
  loadPluginConfigWithMeta
32283
32546
  };
32284
32547
  async function handleTurboCommand(directory, args, sessionID) {
@@ -32338,7 +32601,7 @@ async function handleTurboCommand(directory, args, sessionID) {
32338
32601
  if (arg0 === "on") {
32339
32602
  let strategy = "standard";
32340
32603
  try {
32341
- const { config } = _internals47.loadPluginConfigWithMeta(directory);
32604
+ const { config } = _internals48.loadPluginConfigWithMeta(directory);
32342
32605
  if (config.turbo?.strategy === "lean") {
32343
32606
  strategy = "lean";
32344
32607
  }
@@ -32435,7 +32698,7 @@ function enableLeanTurbo(session, directory, sessionID) {
32435
32698
  let maxParallelCoders = 4;
32436
32699
  let conflictPolicy = "serialize";
32437
32700
  try {
32438
- const { config } = _internals47.loadPluginConfigWithMeta(directory);
32701
+ const { config } = _internals48.loadPluginConfigWithMeta(directory);
32439
32702
  const leanConfig = config.turbo?.lean;
32440
32703
  if (leanConfig) {
32441
32704
  maxParallelCoders = leanConfig.max_parallel_coders ?? 4;
@@ -32651,7 +32914,7 @@ function findSimilarCommands(query) {
32651
32914
  }
32652
32915
  const scored = VALID_COMMANDS.map((cmd) => {
32653
32916
  const cmdLower = cmd.toLowerCase();
32654
- const fullScore = _internals48.levenshteinDistance(q, cmdLower);
32917
+ const fullScore = _internals49.levenshteinDistance(q, cmdLower);
32655
32918
  let tokenScore = Infinity;
32656
32919
  if (cmd.includes(" ") || cmd.includes("-")) {
32657
32920
  const qTokens = q.split(/[\s-]+/);
@@ -32664,7 +32927,7 @@ function findSimilarCommands(query) {
32664
32927
  for (const ct of cmdTokens) {
32665
32928
  if (ct.length === 0)
32666
32929
  continue;
32667
- const dist = _internals48.levenshteinDistance(qt, ct);
32930
+ const dist = _internals49.levenshteinDistance(qt, ct);
32668
32931
  if (dist < minDist)
32669
32932
  minDist = dist;
32670
32933
  }
@@ -32674,7 +32937,7 @@ function findSimilarCommands(query) {
32674
32937
  }
32675
32938
  const dashStrippedQ = q.replace(/-/g, "");
32676
32939
  const dashStrippedCmd = cmdLower.replace(/-/g, "");
32677
- const dashScore = _internals48.levenshteinDistance(dashStrippedQ, dashStrippedCmd);
32940
+ const dashScore = _internals49.levenshteinDistance(dashStrippedQ, dashStrippedCmd);
32678
32941
  const score = Math.min(fullScore, tokenScore, dashScore);
32679
32942
  return { cmd, score };
32680
32943
  });
@@ -32709,16 +32972,16 @@ function buildDetailedHelp(commandName, entry) {
32709
32972
  async function handleHelpCommand(ctx) {
32710
32973
  const targetCommand = ctx.args.join(" ");
32711
32974
  if (!targetCommand) {
32712
- const { buildHelpText } = await import("./index-hw4tcxs9.js");
32975
+ const { buildHelpText } = await import("./index-p35ayncy.js");
32713
32976
  return buildHelpText();
32714
32977
  }
32715
32978
  const tokens = targetCommand.split(/\s+/);
32716
- const resolved = _internals48.resolveCommand(tokens);
32979
+ const resolved = _internals49.resolveCommand(tokens);
32717
32980
  if (resolved) {
32718
- return _internals48.buildDetailedHelp(resolved.key, resolved.entry);
32981
+ return _internals49.buildDetailedHelp(resolved.key, resolved.entry);
32719
32982
  }
32720
- const similar = _internals48.findSimilarCommands(targetCommand);
32721
- const { buildHelpText: fullHelp } = await import("./index-hw4tcxs9.js");
32983
+ const similar = _internals49.findSimilarCommands(targetCommand);
32984
+ const { buildHelpText: fullHelp } = await import("./index-p35ayncy.js");
32722
32985
  if (similar.length > 0) {
32723
32986
  return `Command '/swarm ${targetCommand}' not found.
32724
32987
 
@@ -32782,7 +33045,7 @@ var COMMAND_REGISTRY = {
32782
33045
  toolNoArgs: true
32783
33046
  },
32784
33047
  help: {
32785
- handler: (ctx) => _internals48.handleHelpCommand(ctx),
33048
+ handler: (ctx) => _internals49.handleHelpCommand(ctx),
32786
33049
  description: "Show help for swarm commands",
32787
33050
  category: "core",
32788
33051
  args: "[command]",
@@ -32851,7 +33114,7 @@ var COMMAND_REGISTRY = {
32851
33114
  },
32852
33115
  "guardrail explain": {
32853
33116
  handler: async (ctx) => {
32854
- const { handleGuardrailExplain } = await import("./guardrail-explain-kabd97j8.js");
33117
+ const { handleGuardrailExplain } = await import("./guardrail-explain-hhdtrm60.js");
32855
33118
  return handleGuardrailExplain(ctx.directory, ctx.args);
32856
33119
  },
32857
33120
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -32861,7 +33124,7 @@ var COMMAND_REGISTRY = {
32861
33124
  },
32862
33125
  "guardrail-explain": {
32863
33126
  handler: async (ctx) => {
32864
- const { handleGuardrailExplain } = await import("./guardrail-explain-kabd97j8.js");
33127
+ const { handleGuardrailExplain } = await import("./guardrail-explain-hhdtrm60.js");
32865
33128
  return handleGuardrailExplain(ctx.directory, ctx.args);
32866
33129
  },
32867
33130
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -33695,7 +33958,7 @@ function validateToolPolicy() {
33695
33958
  }
33696
33959
  return { valid: warnings.length === 0, warnings };
33697
33960
  }
33698
- var _internals48 = {
33961
+ var _internals49 = {
33699
33962
  handleHelpCommand,
33700
33963
  validateAliases,
33701
33964
  validateToolPolicy,
@@ -33705,16 +33968,16 @@ var _internals48 = {
33705
33968
  findSimilarCommands,
33706
33969
  buildDetailedHelp
33707
33970
  };
33708
- var validation = _internals48.validateAliases();
33971
+ var validation = _internals49.validateAliases();
33709
33972
  if (!validation.valid) {
33710
33973
  throw new Error(`COMMAND_REGISTRY alias validation failed:
33711
33974
  ${validation.errors.join(`
33712
33975
  `)}`);
33713
33976
  }
33714
- _internals48.emitValidationWarnings("COMMAND_REGISTRY alias warnings", validation.warnings);
33977
+ _internals49.emitValidationWarnings("COMMAND_REGISTRY alias warnings", validation.warnings);
33715
33978
  try {
33716
- const toolPolicyValidation = _internals48.validateToolPolicy();
33717
- _internals48.emitValidationWarnings("COMMAND_REGISTRY toolPolicy warnings", toolPolicyValidation.warnings);
33979
+ const toolPolicyValidation = _internals49.validateToolPolicy();
33980
+ _internals49.emitValidationWarnings("COMMAND_REGISTRY toolPolicy warnings", toolPolicyValidation.warnings);
33718
33981
  } catch (e) {
33719
33982
  warn(`COMMAND_REGISTRY toolPolicy validation failed (non-fatal): ${e.message}`);
33720
33983
  }
@@ -36397,7 +36660,7 @@ function formatCommandNotFound(tokens) {
36397
36660
  const attemptedCommand = tokens[0] || "";
36398
36661
  const MAX_DISPLAY = 100;
36399
36662
  const displayCommand = attemptedCommand.length > MAX_DISPLAY ? `${attemptedCommand.slice(0, MAX_DISPLAY)}...` : attemptedCommand;
36400
- const similar = _internals48.findSimilarCommands(attemptedCommand);
36663
+ const similar = _internals49.findSimilarCommands(attemptedCommand);
36401
36664
  const header = `Command \`/swarm ${displayCommand}\` not found.`;
36402
36665
  const suggestions = similar.length > 0 ? `Did you mean:
36403
36666
  ${similar.map((cmd) => ` - /swarm ${cmd}`).join(`
@@ -38070,11 +38333,11 @@ function markSuggested(sessionId) {
38070
38333
  _suggestedSessions.add(sessionId);
38071
38334
  }
38072
38335
  function countWorktrees(directory) {
38073
- return new Promise((resolve20) => {
38336
+ return new Promise((resolve21) => {
38074
38337
  try {
38075
38338
  const child = execFile3("git", ["-C", directory, "worktree", "list", "--porcelain"], { timeout: GIT_TIMEOUT_MS3, windowsHide: true, encoding: "utf-8" }, (err, stdout) => {
38076
38339
  if (err || typeof stdout !== "string") {
38077
- resolve20(0);
38340
+ resolve21(0);
38078
38341
  return;
38079
38342
  }
38080
38343
  let count = 0;
@@ -38083,14 +38346,14 @@ function countWorktrees(directory) {
38083
38346
  if (line.startsWith("worktree "))
38084
38347
  count++;
38085
38348
  }
38086
- resolve20(count);
38349
+ resolve21(count);
38087
38350
  });
38088
38351
  try {
38089
38352
  child.stdin?.end();
38090
38353
  } catch {}
38091
- child.on("error", () => resolve20(0));
38354
+ child.on("error", () => resolve21(0));
38092
38355
  } catch {
38093
- resolve20(0);
38356
+ resolve21(0);
38094
38357
  }
38095
38358
  });
38096
38359
  }
@@ -38314,10 +38577,10 @@ function startAgentSession(sessionId, agentName, staleDurationMs = STALE_SESSION
38314
38577
  }
38315
38578
  telemetry.sessionStarted(sessionId, agentName);
38316
38579
  swarmState.activeAgent.set(sessionId, agentName);
38317
- _internals51.applyRehydrationCache(sessionState);
38580
+ _internals52.applyRehydrationCache(sessionState);
38318
38581
  if (directory) {
38319
38582
  let rehydrationPromise;
38320
- rehydrationPromise = _internals51.rehydrateSessionFromDisk(directory, sessionState).then(async () => {
38583
+ rehydrationPromise = _internals52.rehydrateSessionFromDisk(directory, sessionState).then(async () => {
38321
38584
  try {
38322
38585
  sessionState.prSubscriptions = await rehydratePrSubscriptions(sessionId, directory);
38323
38586
  } catch (err) {
@@ -38498,7 +38761,7 @@ function ensureAgentSession(sessionId, agentName, directory) {
38498
38761
  maybeSweepStaleSessions();
38499
38762
  return session;
38500
38763
  }
38501
- _internals51.startAgentSession(sessionId, agentName ?? "unknown", 7200000, directory);
38764
+ _internals52.startAgentSession(sessionId, agentName ?? "unknown", 7200000, directory);
38502
38765
  session = swarmState.agentSessions.get(sessionId);
38503
38766
  if (!session) {
38504
38767
  throw new Error(`Failed to create guardrail session for ${sessionId}`);
@@ -38786,8 +39049,8 @@ function applyRehydrationCache(session) {
38786
39049
  }
38787
39050
  }
38788
39051
  async function rehydrateSessionFromDisk(directory, session) {
38789
- await _internals51.buildRehydrationCache(directory);
38790
- _internals51.applyRehydrationCache(session);
39052
+ await _internals52.buildRehydrationCache(directory);
39053
+ _internals52.applyRehydrationCache(session);
38791
39054
  }
38792
39055
  function hasActiveTurboMode(sessionID) {
38793
39056
  if (sessionID) {
@@ -38813,6 +39076,20 @@ function hasActiveFullAuto(sessionID) {
38813
39076
  }
38814
39077
  return false;
38815
39078
  }
39079
+ function getActiveFullAutoSessionID() {
39080
+ let activeId;
39081
+ let activeLastToolCall = -1;
39082
+ for (const [id, session] of swarmState.agentSessions) {
39083
+ if (session.fullAutoMode !== true)
39084
+ continue;
39085
+ const lastToolCall = session.lastToolCallTime ?? 0;
39086
+ if (activeId === undefined || lastToolCall > activeLastToolCall) {
39087
+ activeId = id;
39088
+ activeLastToolCall = lastToolCall;
39089
+ }
39090
+ }
39091
+ return activeId;
39092
+ }
38816
39093
  function hasActiveLeanTurbo(sessionID) {
38817
39094
  if (sessionID) {
38818
39095
  const session = swarmState.agentSessions.get(sessionID);
@@ -38861,7 +39138,7 @@ async function rehydratePrSubscriptions(sessionID, directory) {
38861
39138
  }
38862
39139
  return map;
38863
39140
  }
38864
- var _internals51 = {
39141
+ var _internals52 = {
38865
39142
  swarmState,
38866
39143
  resetSwarmState,
38867
39144
  ensureAgentSession,
@@ -39000,4 +39277,4 @@ function createCuratorLLMDelegate(directory, mode = "init", sessionId) {
39000
39277
  };
39001
39278
  }
39002
39279
 
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 };
39280
+ 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 };