opencode-swarm 7.99.3 → 7.99.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -69,7 +69,7 @@ var package_default;
69
69
  var init_package = __esm(() => {
70
70
  package_default = {
71
71
  name: "opencode-swarm",
72
- version: "7.99.3",
72
+ version: "7.99.5",
73
73
  description: "Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",
74
74
  main: "dist/index.js",
75
75
  types: "dist/index.d.ts",
@@ -20525,6 +20525,25 @@ async function getLatestLedgerHash(directory) {
20525
20525
  return "";
20526
20526
  }
20527
20527
  }
20528
+ async function surfaceLedgerStaleIfPersisted(directory, plan) {
20529
+ const resolvedWorkspace = path13.resolve(directory);
20530
+ if (!ledgerStaleWorkspaces.has(resolvedWorkspace)) {
20531
+ return plan;
20532
+ }
20533
+ try {
20534
+ const planHash = computePlanHash(plan);
20535
+ const ledgerHash = await getLatestLedgerHash(directory);
20536
+ if (ledgerHash !== "" && planHash === ledgerHash) {
20537
+ ledgerStaleWorkspaces.delete(resolvedWorkspace);
20538
+ return plan;
20539
+ }
20540
+ } catch {}
20541
+ plan._ledgerReplayStale = true;
20542
+ if (typeof plan._ledgerReplayStaleReason !== "string" || plan._ledgerReplayStaleReason.length === 0) {
20543
+ plan._ledgerReplayStaleReason = "plan.json still hash-mismatches the ledger after a startup ledger-replay failure (replay could not be applied and no critic-approved snapshot was available). Run /swarm reset-session if this persists.";
20544
+ }
20545
+ return plan;
20546
+ }
20528
20547
  async function parsePlanJsonCached(directory) {
20529
20548
  const planJsonPath = path13.resolve(directory, ".swarm", "plan.json");
20530
20549
  return readCachedParsedFile(planJsonPath, PLAN_JSON_CACHE_NAMESPACE, () => readSwarmFileAsync(directory, "plan.json"), (planJsonContent) => {
@@ -20583,7 +20602,7 @@ async function isPlanMdInSync(directory, plan, cache) {
20583
20602
  if (normalizedActual === normalizedExpected) {
20584
20603
  return true;
20585
20604
  }
20586
- return normalizedActual.includes(normalizedExpected) || normalizedExpected.includes(normalizedActual.replace(/^#.*$/gm, "").trim());
20605
+ return false;
20587
20606
  }
20588
20607
  async function regeneratePlanMarkdown(directory, plan) {
20589
20608
  const swarmDir = path13.resolve(directory, ".swarm");
@@ -20664,6 +20683,12 @@ async function loadPlan(directory, cache) {
20664
20683
  return approved.plan;
20665
20684
  }
20666
20685
  } catch {}
20686
+ {
20687
+ const runtimeStale = validated;
20688
+ runtimeStale._ledgerReplayStale = true;
20689
+ runtimeStale._ledgerReplayStaleReason = `Ledger replay failed during hash-mismatch rebuild and no approved snapshot was available: ${replayError instanceof Error ? replayError.message : String(replayError)}`;
20690
+ ledgerStaleWorkspaces.add(resolvedWorkspace);
20691
+ }
20667
20692
  warn(`[loadPlan] Ledger replay failed during hash-mismatch rebuild: ${replayError instanceof Error ? replayError.message : String(replayError)}. Returning stale plan.json. To recover: check .swarm/plan-export/SWARM_PLAN.md for a checkpoint, or run /swarm reset-session.`);
20668
20693
  }
20669
20694
  }
@@ -20708,7 +20733,7 @@ async function loadPlan(directory, cache) {
20708
20733
  } catch {}
20709
20734
  }
20710
20735
  }
20711
- return validated;
20736
+ return await surfaceLedgerStaleIfPersisted(directory, validated);
20712
20737
  }
20713
20738
  } catch (error49) {
20714
20739
  warn(`[loadPlan] plan.json validation failed: ${error49 instanceof Error ? error49.message : String(error49)}. Attempting rebuild from ledger. If rebuild fails, check .swarm/plan-export/SWARM_PLAN.md for a checkpoint.`);
@@ -21646,7 +21671,7 @@ function migrateLegacyPlan(planContent, swarmId) {
21646
21671
  };
21647
21672
  return plan;
21648
21673
  }
21649
- var PlanConcurrentModificationError, PlanTaskRemovalNotAcknowledgedError, startupLedgerCheckedWorkspaces, recoveryMutexes, PLAN_JSON_CACHE_NAMESPACE = "plan-json:validated:v1", _internals8, CAS_BACKOFF_START_MS = 5, CAS_BACKOFF_CAP_MS = 250, CAS_BACKOFF_JITTER = 0.25, CAS_MAX_RETRIES = 3;
21674
+ var PlanConcurrentModificationError, PlanTaskRemovalNotAcknowledgedError, startupLedgerCheckedWorkspaces, ledgerStaleWorkspaces, recoveryMutexes, PLAN_JSON_CACHE_NAMESPACE = "plan-json:validated:v1", _internals8, CAS_BACKOFF_START_MS = 5, CAS_BACKOFF_CAP_MS = 250, CAS_BACKOFF_JITTER = 0.25, CAS_MAX_RETRIES = 3;
21650
21675
  var init_manager = __esm(() => {
21651
21676
  init_plan_schema();
21652
21677
  init_branch();
@@ -21678,6 +21703,7 @@ var init_manager = __esm(() => {
21678
21703
  }
21679
21704
  };
21680
21705
  startupLedgerCheckedWorkspaces = new Set;
21706
+ ledgerStaleWorkspaces = new Set;
21681
21707
  recoveryMutexes = new Map;
21682
21708
  _internals8 = {
21683
21709
  loadPlan,
@@ -47088,6 +47114,7 @@ var init_pr_subscriptions = __esm(() => {
47088
47114
  var exports_state = {};
47089
47115
  __export(exports_state, {
47090
47116
  updateAgentEventTime: () => updateAgentEventTime,
47117
+ sweepStaleSessions: () => sweepStaleSessions,
47091
47118
  swarmState: () => swarmState,
47092
47119
  startAgentSession: () => startAgentSession,
47093
47120
  setSessionEnvironment: () => setSessionEnvironment,
@@ -47099,6 +47126,7 @@ __export(exports_state, {
47099
47126
  recordStageBCompletion: () => recordStageBCompletion,
47100
47127
  recordPhaseAgentDispatch: () => recordPhaseAgentDispatch,
47101
47128
  pruneOldWindows: () => pruneOldWindows,
47129
+ maybeSweepStaleSessions: () => maybeSweepStaleSessions,
47102
47130
  isCouncilGateActive: () => isCouncilGateActive,
47103
47131
  hasBothStageBCompletions: () => hasBothStageBCompletions,
47104
47132
  hasActiveTurboMode: () => hasActiveTurboMode,
@@ -47144,6 +47172,7 @@ function resetSwarmState() {
47144
47172
  swarmState.pendingEvents = 0;
47145
47173
  swarmState.lastBudgetPct = 0;
47146
47174
  swarmState.agentSessions.clear();
47175
+ _lastIdleSweepAtMs = 0;
47147
47176
  clearTrajectoryCache();
47148
47177
  clearTrajectoryStepCounters();
47149
47178
  swarmState.pendingRehydrations.clear();
@@ -47185,8 +47214,7 @@ function resetSwarmStatePreservingSingletons() {
47185
47214
  swarmState.specWriterAgentNames = preservedSpecWriterAgentNames;
47186
47215
  swarmState.generatedAgentNames = preservedGeneratedAgentNames;
47187
47216
  }
47188
- function startAgentSession(sessionId, agentName, staleDurationMs = 7200000, directory) {
47189
- const now = Date.now();
47217
+ function sweepStaleSessions(staleDurationMs = STALE_SESSION_TTL_MS, now = Date.now()) {
47190
47218
  const staleIds = [];
47191
47219
  for (const [id, session] of swarmState.agentSessions) {
47192
47220
  if (now - session.lastToolCallTime > staleDurationMs) {
@@ -47195,7 +47223,20 @@ function startAgentSession(sessionId, agentName, staleDurationMs = 7200000, dire
47195
47223
  }
47196
47224
  for (const id of staleIds) {
47197
47225
  swarmState.agentSessions.delete(id);
47226
+ swarmState.delegationChains.delete(id);
47198
47227
  }
47228
+ return staleIds;
47229
+ }
47230
+ function maybeSweepStaleSessions(staleDurationMs = STALE_SESSION_TTL_MS, now = Date.now()) {
47231
+ if (now - _lastIdleSweepAtMs < IDLE_SWEEP_COOLDOWN_MS) {
47232
+ return [];
47233
+ }
47234
+ _lastIdleSweepAtMs = now;
47235
+ return sweepStaleSessions(staleDurationMs, now);
47236
+ }
47237
+ function startAgentSession(sessionId, agentName, staleDurationMs = STALE_SESSION_TTL_MS, directory) {
47238
+ const now = Date.now();
47239
+ sweepStaleSessions(staleDurationMs, now);
47199
47240
  const sessionState = {
47200
47241
  agentName,
47201
47242
  lastToolCallTime: now,
@@ -47446,6 +47487,7 @@ function ensureAgentSession(sessionId, agentName, directory) {
47446
47487
  session.prSubscriptions = new Map;
47447
47488
  }
47448
47489
  session.lastToolCallTime = now;
47490
+ maybeSweepStaleSessions();
47449
47491
  return session;
47450
47492
  }
47451
47493
  _internals25.startAgentSession(sessionId, agentName ?? "unknown", 7200000, directory);
@@ -47930,7 +47972,7 @@ async function rehydratePrSubscriptions(sessionID, directory) {
47930
47972
  }
47931
47973
  return map2;
47932
47974
  }
47933
- var _rehydrationCache = null, _councilDisagreementWarned, STATE_ORDER, _toolAggregates, defaultRunContext, _runContexts, swarmState, MAX_TRACKED_CRITICAL_SHOWN = 500, MAX_TRACKED_KNOWLEDGE_ACKS = 5000, _internals25;
47975
+ var _rehydrationCache = null, _councilDisagreementWarned, STATE_ORDER, _toolAggregates, defaultRunContext, _runContexts, swarmState, STALE_SESSION_TTL_MS = 7200000, IDLE_SWEEP_COOLDOWN_MS = 60000, _lastIdleSweepAtMs = 0, MAX_TRACKED_CRITICAL_SHOWN = 500, MAX_TRACKED_KNOWLEDGE_ACKS = 5000, _internals25;
47934
47976
  var init_state2 = __esm(() => {
47935
47977
  init_constants();
47936
47978
  init_plan_schema();
@@ -76579,6 +76621,9 @@ var init_gate_bridge = __esm(() => {
76579
76621
  import { existsSync as existsSync35, mkdirSync as mkdirSync21, readFileSync as readFileSync19, writeFileSync as writeFileSync13 } from "node:fs";
76580
76622
  import { homedir as homedir8 } from "node:os";
76581
76623
  import { join as join52 } from "node:path";
76624
+ function isStrictSemver(value) {
76625
+ return typeof value === "string" && STRICT_SEMVER.test(value);
76626
+ }
76582
76627
  function cacheDir() {
76583
76628
  const xdg = process.env.XDG_CACHE_HOME;
76584
76629
  const base = xdg && xdg.length > 0 ? xdg : join52(homedir8(), ".cache");
@@ -76633,14 +76678,32 @@ function compareVersions(a, b) {
76633
76678
  }
76634
76679
  async function fetchLatestVersion(signal) {
76635
76680
  try {
76636
- const res = await fetch(NPM_REGISTRY_URL, {
76681
+ const res = await _internals43.fetch(NPM_REGISTRY_URL, {
76637
76682
  signal,
76638
76683
  headers: { Accept: "application/json" }
76639
76684
  });
76640
76685
  if (!res.ok)
76641
76686
  return null;
76642
- const body = await res.json();
76643
- return typeof body.version === "string" ? body.version : null;
76687
+ const contentType = (res.headers.get("content-type") ?? "").toLowerCase();
76688
+ if (!contentType.includes("json"))
76689
+ return null;
76690
+ const lengthHeader = res.headers.get("content-length");
76691
+ if (lengthHeader) {
76692
+ const advertised = Number.parseInt(lengthHeader, 10);
76693
+ if (Number.isFinite(advertised) && advertised > MAX_RESPONSE_BYTES) {
76694
+ return null;
76695
+ }
76696
+ }
76697
+ const text = await res.text();
76698
+ if (text.length > MAX_RESPONSE_BYTES)
76699
+ return null;
76700
+ let body;
76701
+ try {
76702
+ body = JSON.parse(text);
76703
+ } catch {
76704
+ return null;
76705
+ }
76706
+ return isStrictSemver(body.version) ? body.version : null;
76644
76707
  } catch {
76645
76708
  return null;
76646
76709
  }
@@ -76682,9 +76745,14 @@ function maybeWarn(runningVersion, npmLatest, emitWarning) {
76682
76745
  emitWarning(`[opencode-swarm] Update available: ${runningVersion} → ${npmLatest}. ` + "OpenCode caches plugins indefinitely. Run `bunx opencode-swarm update` to refresh.");
76683
76746
  }
76684
76747
  }
76685
- var NPM_REGISTRY_URL = "https://registry.npmjs.org/opencode-swarm/latest", CHECK_INTERVAL_MS, FETCH_TIMEOUT_MS = 5000, _checkLatched = false;
76748
+ var NPM_REGISTRY_URL = "https://registry.npmjs.org/opencode-swarm/latest", CHECK_INTERVAL_MS, FETCH_TIMEOUT_MS = 5000, MAX_RESPONSE_BYTES, STRICT_SEMVER, _checkLatched = false, _internals43;
76686
76749
  var init_version_check = __esm(() => {
76687
76750
  CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
76751
+ MAX_RESPONSE_BYTES = 256 * 1024;
76752
+ STRICT_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
76753
+ _internals43 = {
76754
+ fetch: (input, init) => fetch(input, init)
76755
+ };
76688
76756
  });
76689
76757
 
76690
76758
  // src/services/knowledge-diagnostics.ts
@@ -77482,9 +77550,9 @@ async function checkCurator(directory) {
77482
77550
  }
77483
77551
  async function getSandboxStatus() {
77484
77552
  try {
77485
- const capability = await _internals43.detectSandboxCapability();
77553
+ const capability = await _internals44.detectSandboxCapability();
77486
77554
  const mechanism = capability.mechanism ?? "none";
77487
- const executor = await _internals43.getSandboxExecutor();
77555
+ const executor = await _internals44.getSandboxExecutor();
77488
77556
  const hasExecutor = executor !== null;
77489
77557
  if (hasExecutor) {
77490
77558
  return {
@@ -77733,7 +77801,7 @@ async function handleDiagnoseCommand(directory, _args) {
77733
77801
  const diagnoseData = await getDiagnoseData(directory);
77734
77802
  return formatDiagnoseMarkdown(diagnoseData);
77735
77803
  }
77736
- var version4, sandboxCapabilityProbe, _internals43;
77804
+ var version4, sandboxCapabilityProbe, _internals44;
77737
77805
  var init_diagnose_service = __esm(() => {
77738
77806
  init_package();
77739
77807
  init_cache_paths();
@@ -77750,7 +77818,7 @@ var init_diagnose_service = __esm(() => {
77750
77818
  init_warning_buffer();
77751
77819
  ({ version: version4 } = package_default);
77752
77820
  sandboxCapabilityProbe = new SandboxCapabilityProbe;
77753
- _internals43 = {
77821
+ _internals44 = {
77754
77822
  detectSandboxCapability: () => sandboxCapabilityProbe.detect(),
77755
77823
  getSandboxExecutor: getExecutor
77756
77824
  };
@@ -77812,6 +77880,21 @@ function emitObjectTypeMismatch(key, value, findings) {
77812
77880
  });
77813
77881
  }
77814
77882
  }
77883
+ function emitWorktreeIsolationLayeringAdvisory(config3, findings) {
77884
+ const parallelization = config3.parallelization;
77885
+ const worktreePolicy = config3.worktree?.policy ?? "auto";
77886
+ if (parallelization?.enabled === true && (parallelization.maxConcurrentTasks ?? 1) > 1 && worktreePolicy !== "disabled") {
77887
+ findings.push({
77888
+ id: "worktree-isolation-baseline-active",
77889
+ title: "Worktree isolation is already active for standard parallel coders",
77890
+ description: "Standard parallel coders already use baseline worktree isolation through the parallel execution profile plus top-level worktree.policy. Lean Turbo and Epic are additive strategies, not requirements for obtaining worktree isolation.",
77891
+ severity: "warn",
77892
+ path: "worktree.policy",
77893
+ currentValue: worktreePolicy,
77894
+ autoFixable: false
77895
+ });
77896
+ }
77897
+ }
77815
77898
  function getUserConfigDir3() {
77816
77899
  return process.env.XDG_CONFIG_HOME || path69.join(os15.homedir(), ".config");
77817
77900
  }
@@ -78372,6 +78455,14 @@ function validateConfigKey(path70, value) {
78372
78455
  emitObjectTypeMismatch("summaries", value, findings);
78373
78456
  break;
78374
78457
  }
78458
+ case "auto_review": {
78459
+ emitObjectTypeMismatch("auto_review", value, findings);
78460
+ break;
78461
+ }
78462
+ case "repo_graph": {
78463
+ emitObjectTypeMismatch("repo_graph", value, findings);
78464
+ break;
78465
+ }
78375
78466
  case "review_passes": {
78376
78467
  emitObjectTypeMismatch("review_passes", value, findings);
78377
78468
  break;
@@ -78448,6 +78539,10 @@ function validateConfigKey(path70, value) {
78448
78539
  emitObjectTypeMismatch("skill_improver", value, findings);
78449
78540
  break;
78450
78541
  }
78542
+ case "skills": {
78543
+ emitObjectTypeMismatch("skills", value, findings);
78544
+ break;
78545
+ }
78451
78546
  case "spec_writer": {
78452
78547
  emitObjectTypeMismatch("spec_writer", value, findings);
78453
78548
  break;
@@ -78633,6 +78728,7 @@ function walkConfigAndValidate(obj, path70, findings, visited = new WeakSet) {
78633
78728
  function runConfigDoctor(config3, directory) {
78634
78729
  const findings = [];
78635
78730
  walkConfigAndValidate(config3, "", findings);
78731
+ emitWorktreeIsolationLayeringAdvisory(config3, findings);
78636
78732
  const summary = {
78637
78733
  info: findings.filter((f) => f.severity === "info").length,
78638
78734
  warn: findings.filter((f) => f.severity === "warn").length,
@@ -80140,7 +80236,7 @@ function isCommandAvailable(command) {
80140
80236
  const isWindows = process.platform === "win32";
80141
80237
  const cmd = isWindows ? `${command}.exe` : command;
80142
80238
  try {
80143
- const result = _internals44.spawnSyncImpl(isWindows ? ["where", cmd] : ["which", cmd], {
80239
+ const result = _internals45.spawnSyncImpl(isWindows ? ["where", cmd] : ["which", cmd], {
80144
80240
  cwd: process.cwd(),
80145
80241
  stdin: "ignore",
80146
80242
  stdout: "ignore",
@@ -80290,7 +80386,7 @@ async function discoverBuildCommands(workingDir, options) {
80290
80386
  const scope = options?.scope ?? "all";
80291
80387
  const changedFiles = options?.changedFiles ?? [];
80292
80388
  const _filesToCheck = filterByScope(workingDir, scope, changedFiles);
80293
- const profileResult = await _internals44.discoverBuildCommandsFromProfiles(workingDir);
80389
+ const profileResult = await _internals45.discoverBuildCommandsFromProfiles(workingDir);
80294
80390
  const profileCommands = profileResult.commands;
80295
80391
  const profileSkipped = profileResult.skipped;
80296
80392
  const coveredEcosystems = new Set;
@@ -80353,7 +80449,7 @@ function clearToolchainCache() {
80353
80449
  function getEcosystems() {
80354
80450
  return ECOSYSTEMS.map((e) => e.ecosystem);
80355
80451
  }
80356
- var ECOSYSTEMS, PROFILE_TO_ECOSYSTEM_NAMES, toolchainCache, IS_COMMAND_AVAILABLE_TIMEOUT_MS = 3000, _internals44, build_discovery;
80452
+ var ECOSYSTEMS, PROFILE_TO_ECOSYSTEM_NAMES, toolchainCache, IS_COMMAND_AVAILABLE_TIMEOUT_MS = 3000, _internals45, build_discovery;
80357
80453
  var init_discovery = __esm(() => {
80358
80454
  init_dist();
80359
80455
  init_detector();
@@ -80471,7 +80567,7 @@ var init_discovery = __esm(() => {
80471
80567
  php: ["php-composer"]
80472
80568
  };
80473
80569
  toolchainCache = new Map;
80474
- _internals44 = {
80570
+ _internals45 = {
80475
80571
  isCommandAvailable,
80476
80572
  discoverBuildCommandsFromProfiles,
80477
80573
  discoverBuildCommands,
@@ -81128,7 +81224,7 @@ async function handleEpicCommand(directory, args2, sessionID) {
81128
81224
  if (!sessionID || sessionID.trim() === "") {
81129
81225
  return "Error: No active session context. Epic Mode requires an active session. Use /swarm epic from within an OpenCode session.";
81130
81226
  }
81131
- const session = _internals45.ensureAgentSession(sessionID, undefined, directory);
81227
+ const session = _internals46.ensureAgentSession(sessionID, undefined, directory);
81132
81228
  const arg0 = args2[0]?.toLowerCase();
81133
81229
  switch (arg0) {
81134
81230
  case "status":
@@ -81155,7 +81251,7 @@ Usage:
81155
81251
  }
81156
81252
  function enableAndAck(directory, sessionID, session) {
81157
81253
  try {
81158
- _internals45.enableEpicMode(directory, sessionID);
81254
+ _internals46.enableEpicMode(directory, sessionID);
81159
81255
  } catch (err) {
81160
81256
  return `Error enabling Epic Mode: ${err instanceof Error ? err.message : String(err)}`;
81161
81257
  }
@@ -81171,7 +81267,7 @@ function enableAndAck(directory, sessionID, session) {
81171
81267
  }
81172
81268
  function disableAndAck(directory, sessionID, session) {
81173
81269
  try {
81174
- _internals45.disableEpicMode(directory, sessionID);
81270
+ _internals46.disableEpicMode(directory, sessionID);
81175
81271
  } catch (err) {
81176
81272
  return `Error disabling Epic Mode: ${err instanceof Error ? err.message : String(err)}`;
81177
81273
  }
@@ -81180,12 +81276,12 @@ function disableAndAck(directory, sessionID, session) {
81180
81276
  }
81181
81277
  function renderStatus(directory, sessionID) {
81182
81278
  const lines = ["## Epic Mode — Status", ""];
81183
- if (_internals45.isStateUnreadable(directory)) {
81279
+ if (_internals46.isStateUnreadable(directory)) {
81184
81280
  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.");
81185
81281
  return lines.join(`
81186
81282
  `);
81187
81283
  }
81188
- const state = _internals45.loadEpicSessionState(directory, sessionID);
81284
+ const state = _internals46.loadEpicSessionState(directory, sessionID);
81189
81285
  if (!state) {
81190
81286
  lines.push("Epic Mode has not been toggled for this session.");
81191
81287
  return lines.join(`
@@ -81237,7 +81333,7 @@ function formatGreenfieldDetail(input) {
81237
81333
  function renderLast(directory) {
81238
81334
  let records;
81239
81335
  try {
81240
- records = _internals45.readPromotionEvidence(directory);
81336
+ records = _internals46.readPromotionEvidence(directory);
81241
81337
  } catch (err) {
81242
81338
  return `Error reading epic-promotions.jsonl: ${err instanceof Error ? err.message : String(err)}`;
81243
81339
  }
@@ -81292,7 +81388,7 @@ function renderLast(directory) {
81292
81388
  `);
81293
81389
  }
81294
81390
  function renderCalibration(directory) {
81295
- if (_internals45.isCalibrationStateUnreadable(directory)) {
81391
+ if (_internals46.isCalibrationStateUnreadable(directory)) {
81296
81392
  return [
81297
81393
  "## Epic Mode — Calibration",
81298
81394
  "",
@@ -81304,11 +81400,11 @@ function renderCalibration(directory) {
81304
81400
  }
81305
81401
  let state;
81306
81402
  try {
81307
- state = _internals45.loadCalibrationState(directory);
81403
+ state = _internals46.loadCalibrationState(directory);
81308
81404
  } catch (err) {
81309
81405
  return `Error reading calibration state: ${err instanceof Error ? err.message : String(err)}`;
81310
81406
  }
81311
- const { config: config3 } = _internals45.loadPluginConfigWithMeta(directory);
81407
+ const { config: config3 } = _internals46.loadPluginConfigWithMeta(directory);
81312
81408
  const staticThreshold = config3.turbo?.epic?.mode?.activation_threshold ?? 0.3;
81313
81409
  const calibrationCfg = config3.turbo?.epic?.calibration;
81314
81410
  const loosenWindow = calibrationCfg?.loosen_window ?? 10;
@@ -81356,7 +81452,7 @@ function renderCalibration(directory) {
81356
81452
  lines.push("");
81357
81453
  let recentDivergent = [];
81358
81454
  try {
81359
- const all = _internals45.readDivergenceHistory(directory, { limit: 50 });
81455
+ const all = _internals46.readDivergenceHistory(directory, { limit: 50 });
81360
81456
  recentDivergent = all.filter((r) => !r.isClean).slice(-5);
81361
81457
  } catch {}
81362
81458
  lines.push("### Recent divergent tasks (tightened the threshold)");
@@ -81373,11 +81469,11 @@ function renderCalibration(directory) {
81373
81469
  `);
81374
81470
  }
81375
81471
  async function renderDecide(directory) {
81376
- const plan = await _internals45.loadPlanJsonOnly(directory);
81472
+ const plan = await _internals46.loadPlanJsonOnly(directory);
81377
81473
  if (!plan) {
81378
81474
  return "No plan found at `.swarm/plan.json`. Run `/swarm plan` first.";
81379
81475
  }
81380
- const { config: config3 } = _internals45.loadPluginConfigWithMeta(directory);
81476
+ const { config: config3 } = _internals46.loadPluginConfigWithMeta(directory);
81381
81477
  const modeCfg = config3.turbo?.epic?.mode;
81382
81478
  const cochangeCfg = config3.turbo?.epic?.cochange;
81383
81479
  const activationThreshold = modeCfg?.activation_threshold ?? 0.3;
@@ -81387,20 +81483,20 @@ async function renderDecide(directory) {
81387
81483
  const tasks = [];
81388
81484
  for (const phase of plan.phases) {
81389
81485
  for (const task of phase.tasks) {
81390
- const scopeFiles = _internals45.readTaskScopes(directory, task.id);
81486
+ const scopeFiles = _internals46.readTaskScopes(directory, task.id);
81391
81487
  const scope = scopeFiles ?? task.files_touched ?? [];
81392
81488
  tasks.push({ id: task.id, scope });
81393
81489
  }
81394
81490
  }
81395
- const { pairs, commitsObserved } = await _internals45.getCoChangeData(directory);
81491
+ const { pairs, commitsObserved } = await _internals46.getCoChangeData(directory);
81396
81492
  const isGitProject = (() => {
81397
81493
  try {
81398
- return _internals45.isGitRepo(directory);
81494
+ return _internals46.isGitRepo(directory);
81399
81495
  } catch {
81400
81496
  return false;
81401
81497
  }
81402
81498
  })();
81403
- const verdict = _internals45.decideEpicActivation(tasks, pairs, commitsObserved, {
81499
+ const verdict = _internals46.decideEpicActivation(tasks, pairs, commitsObserved, {
81404
81500
  activationThreshold,
81405
81501
  minCommitsForSignal,
81406
81502
  cochangeNpmiThreshold,
@@ -81442,7 +81538,7 @@ function formatVerdict(verdict) {
81442
81538
  return lines.join(`
81443
81539
  `);
81444
81540
  }
81445
- var _internals45;
81541
+ var _internals46;
81446
81542
  var init_epic = __esm(() => {
81447
81543
  init_config();
81448
81544
  init_branch();
@@ -81455,7 +81551,7 @@ var init_epic = __esm(() => {
81455
81551
  init_promotion_evidence();
81456
81552
  init_state();
81457
81553
  init_conflicts();
81458
- _internals45 = {
81554
+ _internals46 = {
81459
81555
  loadPluginConfigWithMeta,
81460
81556
  loadPlanJsonOnly,
81461
81557
  getCoChangeData,
@@ -81480,7 +81576,7 @@ var exports_evidence_summary_service = {};
81480
81576
  __export(exports_evidence_summary_service, {
81481
81577
  isAutoSummaryEnabled: () => isAutoSummaryEnabled,
81482
81578
  buildEvidenceSummary: () => buildEvidenceSummary,
81483
- _internals: () => _internals46,
81579
+ _internals: () => _internals47,
81484
81580
  REQUIRED_EVIDENCE_TYPES: () => REQUIRED_EVIDENCE_TYPES,
81485
81581
  EVIDENCE_SUMMARY_VERSION: () => EVIDENCE_SUMMARY_VERSION
81486
81582
  });
@@ -81518,7 +81614,7 @@ function getTaskStatus(task, bundle) {
81518
81614
  if (task?.status) {
81519
81615
  return task.status;
81520
81616
  }
81521
- const entries = _internals46.normalizeBundleEntries(bundle);
81617
+ const entries = _internals47.normalizeBundleEntries(bundle);
81522
81618
  if (entries.length > 0) {
81523
81619
  return "completed";
81524
81620
  }
@@ -81544,7 +81640,7 @@ function evidenceCompleteFromEntries(entries) {
81544
81640
  };
81545
81641
  }
81546
81642
  function isEvidenceComplete(bundle) {
81547
- return evidenceCompleteFromEntries(_internals46.normalizeBundleEntries(bundle));
81643
+ return evidenceCompleteFromEntries(_internals47.normalizeBundleEntries(bundle));
81548
81644
  }
81549
81645
  function getTaskBlockers(task, summary, status) {
81550
81646
  const blockers = [];
@@ -81564,9 +81660,9 @@ async function buildTaskSummary(directory, task, taskId) {
81564
81660
  const bundle = result.status === "found" ? result.bundle : null;
81565
81661
  const gateEvidence = await readDurableGateEvidence(directory, taskId);
81566
81662
  const phase = task?.phase ?? 0;
81567
- const status = _internals46.getTaskStatus(task, bundle);
81568
- const entries = mergeDurableGateEntriesFromEvidence(taskId, _internals46.normalizeBundleEntries(bundle), gateEvidence);
81569
- let evidenceCheck = _internals46.evidenceCompleteFromEntries(entries);
81663
+ const status = _internals47.getTaskStatus(task, bundle);
81664
+ const entries = mergeDurableGateEntriesFromEvidence(taskId, _internals47.normalizeBundleEntries(bundle), gateEvidence);
81665
+ let evidenceCheck = _internals47.evidenceCompleteFromEntries(entries);
81570
81666
  if (gateEvidence) {
81571
81667
  const gateStatus = getDurableGateEvidenceStatus(gateEvidence);
81572
81668
  evidenceCheck = gateStatus.isComplete ? { isComplete: true, missingEvidence: [] } : {
@@ -81574,7 +81670,7 @@ async function buildTaskSummary(directory, task, taskId) {
81574
81670
  missingEvidence: gateStatus.missingGates.map((gate) => `gate:${gate}`)
81575
81671
  };
81576
81672
  }
81577
- const blockers = _internals46.getTaskBlockers(task, evidenceCheck, status);
81673
+ const blockers = _internals47.getTaskBlockers(task, evidenceCheck, status);
81578
81674
  const hasReview = entries.some((e) => e.type === "review");
81579
81675
  const hasTest = entries.some((e) => e.type === "test");
81580
81676
  const hasApproval = entries.some((e) => e.type === "approval");
@@ -81603,12 +81699,12 @@ async function buildPhaseSummary(directory, phase) {
81603
81699
  const taskSummaries = [];
81604
81700
  const _taskMap = new Map(phase.tasks.map((t) => [t.id, t]));
81605
81701
  for (const task of phase.tasks) {
81606
- const summary = await _internals46.buildTaskSummary(directory, task, task.id);
81702
+ const summary = await _internals47.buildTaskSummary(directory, task, task.id);
81607
81703
  taskSummaries.push(summary);
81608
81704
  }
81609
81705
  const extraTaskIds = taskIds.filter((id) => !phaseTaskIds.has(id));
81610
81706
  for (const taskId of extraTaskIds) {
81611
- const summary = await _internals46.buildTaskSummary(directory, undefined, taskId);
81707
+ const summary = await _internals47.buildTaskSummary(directory, undefined, taskId);
81612
81708
  if (summary.phase === phase.id) {
81613
81709
  taskSummaries.push(summary);
81614
81710
  }
@@ -81709,7 +81805,7 @@ async function buildEvidenceSummary(directory, currentPhase) {
81709
81805
  let totalTasks = 0;
81710
81806
  let completedTasks = 0;
81711
81807
  for (const phase of phasesToProcess) {
81712
- const summary = await _internals46.buildPhaseSummary(directory, phase);
81808
+ const summary = await _internals47.buildPhaseSummary(directory, phase);
81713
81809
  phaseSummaries.push(summary);
81714
81810
  totalTasks += summary.totalTasks;
81715
81811
  completedTasks += summary.completedTasks;
@@ -81731,7 +81827,7 @@ async function buildEvidenceSummary(directory, currentPhase) {
81731
81827
  overallBlockers,
81732
81828
  summaryText: ""
81733
81829
  };
81734
- artifact.summaryText = _internals46.generateSummaryText(artifact);
81830
+ artifact.summaryText = _internals47.generateSummaryText(artifact);
81735
81831
  log("[EvidenceSummary] Summary built", {
81736
81832
  phases: phaseSummaries.length,
81737
81833
  totalTasks,
@@ -81750,7 +81846,7 @@ function isAutoSummaryEnabled(automationConfig) {
81750
81846
  }
81751
81847
  return automationConfig.capabilities?.evidence_auto_summaries === true;
81752
81848
  }
81753
- var VALID_EVIDENCE_TYPES2, REQUIRED_EVIDENCE_TYPES, EVIDENCE_SUMMARY_VERSION = "1.0.0", _internals46;
81849
+ var VALID_EVIDENCE_TYPES2, REQUIRED_EVIDENCE_TYPES, EVIDENCE_SUMMARY_VERSION = "1.0.0", _internals47;
81754
81850
  var init_evidence_summary_service = __esm(() => {
81755
81851
  init_gate_bridge();
81756
81852
  init_manager2();
@@ -81765,7 +81861,7 @@ var init_evidence_summary_service = __esm(() => {
81765
81861
  "retrospective"
81766
81862
  ]);
81767
81863
  REQUIRED_EVIDENCE_TYPES = ["review", "test"];
81768
- _internals46 = {
81864
+ _internals47 = {
81769
81865
  buildEvidenceSummary,
81770
81866
  isAutoSummaryEnabled,
81771
81867
  normalizeBundleEntries,
@@ -81821,7 +81917,7 @@ function getVerdictEmoji(verdict) {
81821
81917
  return getVerdictIcon(verdict);
81822
81918
  }
81823
81919
  async function getTaskEvidenceData(directory, taskId) {
81824
- const result = await _internals47.loadEvidence(directory, taskId);
81920
+ const result = await _internals48.loadEvidence(directory, taskId);
81825
81921
  if (result.status !== "found") {
81826
81922
  return {
81827
81923
  hasEvidence: false,
@@ -81844,13 +81940,13 @@ async function getTaskEvidenceData(directory, taskId) {
81844
81940
  };
81845
81941
  }
81846
81942
  async function getEvidenceListData(directory) {
81847
- const taskIds = await _internals47.listEvidenceTaskIds(directory);
81943
+ const taskIds = await _internals48.listEvidenceTaskIds(directory);
81848
81944
  if (taskIds.length === 0) {
81849
81945
  return { hasEvidence: false, tasks: [] };
81850
81946
  }
81851
81947
  const tasks = [];
81852
81948
  for (const taskId of taskIds) {
81853
- const result = await _internals47.loadEvidence(directory, taskId);
81949
+ const result = await _internals48.loadEvidence(directory, taskId);
81854
81950
  if (result.status === "found") {
81855
81951
  tasks.push({
81856
81952
  taskId,
@@ -81964,10 +82060,10 @@ async function handleEvidenceSummaryCommand(directory) {
81964
82060
  return lines.join(`
81965
82061
  `);
81966
82062
  }
81967
- var _internals47;
82063
+ var _internals48;
81968
82064
  var init_evidence_service = __esm(() => {
81969
82065
  init_manager2();
81970
- _internals47 = {
82066
+ _internals48 = {
81971
82067
  loadEvidence,
81972
82068
  listEvidenceTaskIds
81973
82069
  };
@@ -82616,7 +82712,7 @@ function extractCurrentPhaseFromPlan2(plan) {
82616
82712
  if (!plan) {
82617
82713
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
82618
82714
  }
82619
- if (!_internals48.validatePlanPhases(plan)) {
82715
+ if (!_internals49.validatePlanPhases(plan)) {
82620
82716
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
82621
82717
  }
82622
82718
  let currentPhase = null;
@@ -82758,9 +82854,9 @@ function extractPhaseMetrics(content) {
82758
82854
  async function getHandoffData(directory) {
82759
82855
  const now = new Date().toISOString();
82760
82856
  const sessionContent = await readSwarmFileAsync(directory, "session/state.json");
82761
- const sessionState = _internals48.parseSessionState(sessionContent);
82857
+ const sessionState = _internals49.parseSessionState(sessionContent);
82762
82858
  const plan = await loadPlanJsonOnly(directory);
82763
- const planInfo = _internals48.extractCurrentPhaseFromPlan(plan);
82859
+ const planInfo = _internals49.extractCurrentPhaseFromPlan(plan);
82764
82860
  if (!plan) {
82765
82861
  const planMdContent = await readSwarmFileAsync(directory, "plan.md");
82766
82862
  if (planMdContent) {
@@ -82779,8 +82875,8 @@ async function getHandoffData(directory) {
82779
82875
  }
82780
82876
  }
82781
82877
  const contextContent = await readSwarmFileAsync(directory, "context.md");
82782
- const recentDecisions = _internals48.extractDecisions(contextContent);
82783
- const rawPhaseMetrics = _internals48.extractPhaseMetrics(contextContent);
82878
+ const recentDecisions = _internals49.extractDecisions(contextContent);
82879
+ const rawPhaseMetrics = _internals49.extractPhaseMetrics(contextContent);
82784
82880
  const phaseMetrics = sanitizeString(rawPhaseMetrics, 1000);
82785
82881
  let delegationState = null;
82786
82882
  if (sessionState?.delegationState) {
@@ -82944,13 +83040,13 @@ ${lines.join(`
82944
83040
  `)}
82945
83041
  \`\`\``;
82946
83042
  }
82947
- var RTL_OVERRIDE_PATTERN, MAX_TASK_ID_LENGTH = 100, MAX_DECISION_LENGTH = 500, MAX_INCOMPLETE_TASKS = 20, _internals48;
83043
+ var RTL_OVERRIDE_PATTERN, MAX_TASK_ID_LENGTH = 100, MAX_DECISION_LENGTH = 500, MAX_INCOMPLETE_TASKS = 20, _internals49;
82948
83044
  var init_handoff_service = __esm(() => {
82949
83045
  init_utils2();
82950
83046
  init_manager();
82951
83047
  init_utils();
82952
83048
  RTL_OVERRIDE_PATTERN = /[\u202e\u202d\u202c\u200f]/g;
82953
- _internals48 = {
83049
+ _internals49 = {
82954
83050
  getHandoffData,
82955
83051
  formatHandoffMarkdown,
82956
83052
  formatContinuationPrompt,
@@ -83093,22 +83189,22 @@ async function writeSnapshot(directory, state) {
83093
83189
  }
83094
83190
  function createSnapshotWriterHook(directory) {
83095
83191
  return (_input, _output) => {
83096
- _writeInFlight = _writeInFlight.then(() => _internals49.writeSnapshot(directory, swarmState), () => _internals49.writeSnapshot(directory, swarmState));
83192
+ _writeInFlight = _writeInFlight.then(() => _internals50.writeSnapshot(directory, swarmState), () => _internals50.writeSnapshot(directory, swarmState));
83097
83193
  return _writeInFlight;
83098
83194
  };
83099
83195
  }
83100
83196
  async function flushPendingSnapshot(directory) {
83101
- _writeInFlight = _writeInFlight.then(() => _internals49.writeSnapshot(directory, swarmState), () => _internals49.writeSnapshot(directory, swarmState));
83197
+ _writeInFlight = _writeInFlight.then(() => _internals50.writeSnapshot(directory, swarmState), () => _internals50.writeSnapshot(directory, swarmState));
83102
83198
  await _writeInFlight;
83103
83199
  }
83104
- var _writeInFlight, _internals49;
83200
+ var _writeInFlight, _internals50;
83105
83201
  var init_snapshot_writer = __esm(() => {
83106
83202
  init_utils2();
83107
83203
  init_state2();
83108
83204
  init_utils();
83109
83205
  init_bun_compat();
83110
83206
  _writeInFlight = Promise.resolve();
83111
- _internals49 = {
83207
+ _internals50 = {
83112
83208
  writeSnapshot,
83113
83209
  createSnapshotWriterHook,
83114
83210
  flushPendingSnapshot
@@ -83428,7 +83524,7 @@ function validateAndSanitizeGithubUrl(rawUrl, resource) {
83428
83524
  }
83429
83525
  function detectGitRemote(cwd) {
83430
83526
  try {
83431
- const result = _internals50.spawnSync("git", ["remote", "get-url", "origin"], {
83527
+ const result = _internals51.spawnSync("git", ["remote", "get-url", "origin"], {
83432
83528
  encoding: "utf-8",
83433
83529
  stdio: ["ignore", "pipe", "pipe"],
83434
83530
  timeout: 5000,
@@ -83473,7 +83569,7 @@ function parseGitRemoteUrl(remoteUrl) {
83473
83569
  }
83474
83570
  return null;
83475
83571
  }
83476
- var MAX_URL_LEN = 2048, IPV4_PRIVATE, IPV4_LOOPBACK, IPV4_LINK_LOCAL, IPV4_PRIVATE_172, IPV4_PRIVATE_192, IPV4_ZERO_NETWORK, IPV6_LINK_LOCAL, IPV6_UNIQUE_LOCAL, _internals50;
83572
+ var MAX_URL_LEN = 2048, IPV4_PRIVATE, IPV4_LOOPBACK, IPV4_LINK_LOCAL, IPV4_PRIVATE_172, IPV4_PRIVATE_192, IPV4_ZERO_NETWORK, IPV6_LINK_LOCAL, IPV6_UNIQUE_LOCAL, _internals51;
83477
83573
  var init_url_security = __esm(() => {
83478
83574
  IPV4_PRIVATE = /^10\./;
83479
83575
  IPV4_LOOPBACK = /^127\./;
@@ -83483,7 +83579,7 @@ var init_url_security = __esm(() => {
83483
83579
  IPV4_ZERO_NETWORK = /^0\./;
83484
83580
  IPV6_LINK_LOCAL = /^fe80:/i;
83485
83581
  IPV6_UNIQUE_LOCAL = /^f[cd][0-9a-f]{2}:/i;
83486
- _internals50 = { spawnSync: spawnSync10 };
83582
+ _internals51 = { spawnSync: spawnSync10 };
83487
83583
  });
83488
83584
 
83489
83585
  // src/commands/issue.ts
@@ -83619,7 +83715,7 @@ import * as path76 from "node:path";
83619
83715
  async function migrateKnowledgeToExternal(_directory, _config) {
83620
83716
  const externalSentinelPath = path76.join(_directory, ".swarm", ".knowledge-external-migrated");
83621
83717
  const contextPath = path76.join(_directory, ".swarm", "context.md");
83622
- if (_internals51.existsSync(externalSentinelPath)) {
83718
+ if (_internals52.existsSync(externalSentinelPath)) {
83623
83719
  return {
83624
83720
  migrated: false,
83625
83721
  entriesMigrated: 0,
@@ -83628,7 +83724,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
83628
83724
  skippedReason: "external-sentinel-exists"
83629
83725
  };
83630
83726
  }
83631
- if (!_internals51.existsSync(contextPath)) {
83727
+ if (!_internals52.existsSync(contextPath)) {
83632
83728
  return {
83633
83729
  migrated: false,
83634
83730
  entriesMigrated: 0,
@@ -83637,7 +83733,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
83637
83733
  skippedReason: "no-context-file"
83638
83734
  };
83639
83735
  }
83640
- const contextContent = await _internals51.readFile(contextPath, "utf-8");
83736
+ const contextContent = await _internals52.readFile(contextPath, "utf-8");
83641
83737
  if (contextContent.trim().length === 0) {
83642
83738
  return {
83643
83739
  migrated: false,
@@ -83655,7 +83751,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
83655
83751
  entriesCount++;
83656
83752
  }
83657
83753
  }
83658
- await _internals51.writeSentinel(externalSentinelPath, entriesCount, entriesCount);
83754
+ await _internals52.writeSentinel(externalSentinelPath, entriesCount, entriesCount);
83659
83755
  return {
83660
83756
  migrated: true,
83661
83757
  entriesMigrated: entriesCount,
@@ -83695,9 +83791,9 @@ async function migrateContextToKnowledge(directory, config3) {
83695
83791
  skippedReason: "empty-context"
83696
83792
  };
83697
83793
  }
83698
- const rawEntries = _internals51.parseContextMd(contextContent);
83794
+ const rawEntries = _internals52.parseContextMd(contextContent);
83699
83795
  if (rawEntries.length === 0) {
83700
- await _internals51.writeSentinel(sentinelPath, 0, 0);
83796
+ await _internals52.writeSentinel(sentinelPath, 0, 0);
83701
83797
  return {
83702
83798
  migrated: true,
83703
83799
  entriesMigrated: 0,
@@ -83708,10 +83804,10 @@ async function migrateContextToKnowledge(directory, config3) {
83708
83804
  const existing = await readKnowledge(knowledgePath);
83709
83805
  let migrated = 0;
83710
83806
  let dropped = 0;
83711
- const projectName = _internals51.inferProjectName(directory);
83807
+ const projectName = _internals52.inferProjectName(directory);
83712
83808
  for (const raw of rawEntries) {
83713
83809
  if (config3.validation_enabled !== false) {
83714
- const category = raw.categoryHint ?? _internals51.inferCategoryFromText(raw.text);
83810
+ const category = raw.categoryHint ?? _internals52.inferCategoryFromText(raw.text);
83715
83811
  const result = validateLesson(raw.text, existing.map((e) => e.lesson), {
83716
83812
  category,
83717
83813
  scope: "global",
@@ -83731,8 +83827,8 @@ async function migrateContextToKnowledge(directory, config3) {
83731
83827
  const entry = {
83732
83828
  id: randomUUID6(),
83733
83829
  tier: "swarm",
83734
- lesson: _internals51.truncateLesson(raw.text),
83735
- category: raw.categoryHint ?? _internals51.inferCategoryFromText(raw.text),
83830
+ lesson: _internals52.truncateLesson(raw.text),
83831
+ category: raw.categoryHint ?? _internals52.inferCategoryFromText(raw.text),
83736
83832
  tags: [...inferredTags, `migration:${raw.sourceSection}`],
83737
83833
  scope: "global",
83738
83834
  confidence: 0.3,
@@ -83755,7 +83851,7 @@ async function migrateContextToKnowledge(directory, config3) {
83755
83851
  if (migrated > 0) {
83756
83852
  await rewriteKnowledge(knowledgePath, existing);
83757
83853
  }
83758
- await _internals51.writeSentinel(sentinelPath, migrated, dropped);
83854
+ await _internals52.writeSentinel(sentinelPath, migrated, dropped);
83759
83855
  log(`[knowledge-migrator] Migrated ${migrated} entries, dropped ${dropped}`);
83760
83856
  return {
83761
83857
  migrated: true,
@@ -83765,7 +83861,7 @@ async function migrateContextToKnowledge(directory, config3) {
83765
83861
  };
83766
83862
  }
83767
83863
  async function migrateHiveKnowledgeLegacy(config3) {
83768
- const legacyHivePath = _internals51.resolveLegacyHiveKnowledgePath();
83864
+ const legacyHivePath = _internals52.resolveLegacyHiveKnowledgePath();
83769
83865
  const canonicalHivePath = resolveHiveKnowledgePath();
83770
83866
  const sentinelPath = path76.join(path76.dirname(canonicalHivePath), ".hive-knowledge-migrated");
83771
83867
  if (existsSync44(sentinelPath)) {
@@ -83788,7 +83884,7 @@ async function migrateHiveKnowledgeLegacy(config3) {
83788
83884
  }
83789
83885
  const legacyEntries = await readKnowledge(legacyHivePath);
83790
83886
  if (legacyEntries.length === 0) {
83791
- await _internals51.writeSentinel(sentinelPath, 0, 0);
83887
+ await _internals52.writeSentinel(sentinelPath, 0, 0);
83792
83888
  return {
83793
83889
  migrated: true,
83794
83890
  entriesMigrated: 0,
@@ -83836,7 +83932,7 @@ async function migrateHiveKnowledgeLegacy(config3) {
83836
83932
  const newHiveEntry = {
83837
83933
  id: resolvedId,
83838
83934
  tier: "hive",
83839
- lesson: _internals51.truncateLesson(lesson),
83935
+ lesson: _internals52.truncateLesson(lesson),
83840
83936
  category,
83841
83937
  tags: ["migration:legacy-hive"],
83842
83938
  scope: scopeTag,
@@ -83855,7 +83951,7 @@ async function migrateHiveKnowledgeLegacy(config3) {
83855
83951
  encounter_score: 1
83856
83952
  };
83857
83953
  try {
83858
- await _internals51.appendKnowledge(canonicalHivePath, newHiveEntry);
83954
+ await _internals52.appendKnowledge(canonicalHivePath, newHiveEntry);
83859
83955
  existingHiveEntries.push(newHiveEntry);
83860
83956
  migrated++;
83861
83957
  } catch (appendError) {
@@ -83871,7 +83967,7 @@ async function migrateHiveKnowledgeLegacy(config3) {
83871
83967
  dropped++;
83872
83968
  }
83873
83969
  }
83874
- await _internals51.writeSentinel(sentinelPath, migrated, dropped);
83970
+ await _internals52.writeSentinel(sentinelPath, migrated, dropped);
83875
83971
  log(`[knowledge-migrator] Migrated ${migrated} legacy hive entries, dropped ${dropped}`);
83876
83972
  return {
83877
83973
  migrated: true,
@@ -83882,7 +83978,7 @@ async function migrateHiveKnowledgeLegacy(config3) {
83882
83978
  };
83883
83979
  }
83884
83980
  function parseContextMd(content) {
83885
- const sections = _internals51.splitIntoSections(content);
83981
+ const sections = _internals52.splitIntoSections(content);
83886
83982
  const entries = [];
83887
83983
  const seen = new Set;
83888
83984
  const sectionPatterns = [
@@ -83898,7 +83994,7 @@ function parseContextMd(content) {
83898
83994
  const match = sectionPatterns.find((sp) => sp.pattern.test(section.heading));
83899
83995
  if (!match)
83900
83996
  continue;
83901
- const bullets = _internals51.extractBullets(section.body);
83997
+ const bullets = _internals52.extractBullets(section.body);
83902
83998
  for (const bullet of bullets) {
83903
83999
  if (bullet.length < 15)
83904
84000
  continue;
@@ -83907,9 +84003,9 @@ function parseContextMd(content) {
83907
84003
  continue;
83908
84004
  seen.add(normalized);
83909
84005
  entries.push({
83910
- text: _internals51.truncateLesson(bullet),
84006
+ text: _internals52.truncateLesson(bullet),
83911
84007
  sourceSection: match.sourceSection,
83912
- categoryHint: _internals51.inferCategoryFromText(bullet)
84008
+ categoryHint: _internals52.inferCategoryFromText(bullet)
83913
84009
  });
83914
84010
  }
83915
84011
  }
@@ -83999,8 +84095,8 @@ async function writeSentinel(sentinelPath, migrated, dropped) {
83999
84095
  schema_version: 1,
84000
84096
  migration_tool: "knowledge-migrator.ts"
84001
84097
  };
84002
- await _internals51.mkdir(path76.dirname(sentinelPath), { recursive: true });
84003
- await _internals51.writeFile(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
84098
+ await _internals52.mkdir(path76.dirname(sentinelPath), { recursive: true });
84099
+ await _internals52.writeFile(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
84004
84100
  }
84005
84101
  function resolveLegacyHiveKnowledgePath() {
84006
84102
  const platform = process.platform;
@@ -84015,12 +84111,12 @@ function resolveLegacyHiveKnowledgePath() {
84015
84111
  }
84016
84112
  return path76.join(dataDir, "hive-knowledge.jsonl");
84017
84113
  }
84018
- var _internals51;
84114
+ var _internals52;
84019
84115
  var init_knowledge_migrator = __esm(() => {
84020
84116
  init_logger();
84021
84117
  init_knowledge_store();
84022
84118
  init_knowledge_validator();
84023
- _internals51 = {
84119
+ _internals52 = {
84024
84120
  appendKnowledge,
84025
84121
  migrateContextToKnowledge,
84026
84122
  migrateKnowledgeToExternal,
@@ -84278,7 +84374,7 @@ function timeoutMessage(timeoutMs) {
84278
84374
  async function computeWithTimeout(directory, currentPhase, timeoutMs) {
84279
84375
  const controller = new AbortController;
84280
84376
  let timeout;
84281
- const metricsPromise = _internals52.computeLearningMetrics(directory, {
84377
+ const metricsPromise = _internals53.computeLearningMetrics(directory, {
84282
84378
  currentPhase,
84283
84379
  signal: controller.signal
84284
84380
  });
@@ -84335,7 +84431,7 @@ ${JSON.stringify({
84335
84431
  return `Error computing learning metrics: ${message}. Run /swarm diagnose to check .swarm/ health.`;
84336
84432
  }
84337
84433
  }
84338
- var DEFAULT_LEARNING_TIMEOUT_MS = 30000, MAX_LEARNING_TIMEOUT_MS = 300000, LearningMetricsTimeoutError, _internals52;
84434
+ var DEFAULT_LEARNING_TIMEOUT_MS = 30000, MAX_LEARNING_TIMEOUT_MS = 300000, LearningMetricsTimeoutError, _internals53;
84339
84435
  var init_learning = __esm(() => {
84340
84436
  init_learning_metrics();
84341
84437
  LearningMetricsTimeoutError = class LearningMetricsTimeoutError extends Error {
@@ -84346,7 +84442,7 @@ var init_learning = __esm(() => {
84346
84442
  this.name = "LearningMetricsTimeoutError";
84347
84443
  }
84348
84444
  };
84349
- _internals52 = {
84445
+ _internals53 = {
84350
84446
  computeLearningMetrics
84351
84447
  };
84352
84448
  });
@@ -84639,7 +84735,7 @@ ${USAGE7}`;
84639
84735
  }
84640
84736
  let autonomy = parsed.autonomy;
84641
84737
  if (parsed.resume && !parsed.autonomyExplicit) {
84642
- const state = await _internals53.readLatestLoopState(_directory);
84738
+ const state = await _internals54.readLatestLoopState(_directory);
84643
84739
  if (state?.autonomy && AUTONOMY_LEVELS.has(state.autonomy)) {
84644
84740
  autonomy = state.autonomy;
84645
84741
  }
@@ -84650,7 +84746,7 @@ ${USAGE7}`;
84650
84746
  }
84651
84747
  return `${header} ${objective}`;
84652
84748
  }
84653
- var MAX_OBJECTIVE_LEN = 2000, DEPTHS2, AUTONOMY_LEVELS, DEFAULT_DEPTH2 = "standard", DEFAULT_AUTONOMY = "auto", DEFAULT_MAX_CYCLES = 3, MIN_MAX_CYCLES = 1, MAX_MAX_CYCLES = 5, _internals53, USAGE7 = `Usage: /swarm loop <objective> [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]
84749
+ var MAX_OBJECTIVE_LEN = 2000, DEPTHS2, AUTONOMY_LEVELS, DEFAULT_DEPTH2 = "standard", DEFAULT_AUTONOMY = "auto", DEFAULT_MAX_CYCLES = 3, MIN_MAX_CYCLES = 1, MAX_MAX_CYCLES = 5, _internals54, USAGE7 = `Usage: /swarm loop <objective> [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]
84654
84750
 
84655
84751
  Run a compound-engineering loop: brainstorm → plan → build → review → improve,
84656
84752
  iterating until the objective is met or a budget stop condition fires.
@@ -84671,7 +84767,7 @@ Flags:
84671
84767
  var init_loop = __esm(() => {
84672
84768
  DEPTHS2 = new Set(["standard", "exhaustive"]);
84673
84769
  AUTONOMY_LEVELS = new Set(["checkpoint", "auto"]);
84674
- _internals53 = {
84770
+ _internals54 = {
84675
84771
  readLatestLoopState
84676
84772
  };
84677
84773
  });
@@ -89679,9 +89775,9 @@ var init_memory2 = __esm(() => {
89679
89775
 
89680
89776
  // src/services/plan-service.ts
89681
89777
  async function getPlanData(directory, phaseArg) {
89682
- const plan = await _internals54.loadPlanJsonOnly(directory);
89778
+ const plan = await _internals55.loadPlanJsonOnly(directory);
89683
89779
  if (plan) {
89684
- const fullMarkdown = _internals54.derivePlanMarkdown(plan);
89780
+ const fullMarkdown = _internals55.derivePlanMarkdown(plan);
89685
89781
  if (phaseArg === undefined || phaseArg === null || phaseArg === "") {
89686
89782
  return {
89687
89783
  hasPlan: true,
@@ -89724,7 +89820,7 @@ async function getPlanData(directory, phaseArg) {
89724
89820
  isLegacy: false
89725
89821
  };
89726
89822
  }
89727
- const planContent = await _internals54.readSwarmFileAsync(directory, "plan.md");
89823
+ const planContent = await _internals55.readSwarmFileAsync(directory, "plan.md");
89728
89824
  if (!planContent) {
89729
89825
  return {
89730
89826
  hasPlan: false,
@@ -89820,11 +89916,11 @@ async function handlePlanCommand(directory, args2) {
89820
89916
  const planData = await getPlanData(directory, phaseArg);
89821
89917
  return formatPlanMarkdown(planData);
89822
89918
  }
89823
- var _internals54;
89919
+ var _internals55;
89824
89920
  var init_plan_service = __esm(() => {
89825
89921
  init_utils2();
89826
89922
  init_manager();
89827
- _internals54 = {
89923
+ _internals55 = {
89828
89924
  loadPlanJsonOnly,
89829
89925
  derivePlanMarkdown,
89830
89926
  readSwarmFileAsync
@@ -89845,10 +89941,10 @@ async function handlePostMortemCommand(directory, args2, options) {
89845
89941
  };
89846
89942
  if (options?.sessionID) {
89847
89943
  try {
89848
- pmOptions.llmDelegate = _internals55.createCuratorLLMDelegate(directory, "postmortem", options.sessionID);
89944
+ pmOptions.llmDelegate = _internals56.createCuratorLLMDelegate(directory, "postmortem", options.sessionID);
89849
89945
  } catch {}
89850
89946
  }
89851
- const result = await _internals55.runCuratorPostMortem(directory, pmOptions);
89947
+ const result = await _internals56.runCuratorPostMortem(directory, pmOptions);
89852
89948
  const lines = [];
89853
89949
  if (result.success) {
89854
89950
  lines.push("## Post-Mortem Report Generated");
@@ -89879,11 +89975,11 @@ async function handlePostMortemCommand(directory, args2, options) {
89879
89975
  return `Error running post-mortem: ${message}. Run /swarm diagnose to check .swarm/ health.`;
89880
89976
  }
89881
89977
  }
89882
- var _internals55;
89978
+ var _internals56;
89883
89979
  var init_post_mortem = __esm(() => {
89884
89980
  init_curator_llm_factory();
89885
89981
  init_curator_postmortem();
89886
- _internals55 = {
89982
+ _internals56 = {
89887
89983
  createCuratorLLMDelegate,
89888
89984
  runCuratorPostMortem
89889
89985
  };
@@ -90019,7 +90115,7 @@ function formatRelativeTime(epochMs) {
90019
90115
  return `${diffDays} day${diffDays === 1 ? "" : "s"} ago`;
90020
90116
  }
90021
90117
  async function handlePrMonitorStatusCommand(directory, _args, sessionID, source) {
90022
- const allActive = await _internals56.listActive(directory);
90118
+ const allActive = await _internals57.listActive(directory);
90023
90119
  const allSessions = source === "cli";
90024
90120
  const subs = allSessions ? allActive : allActive.filter((record3) => record3.sessionID === sessionID);
90025
90121
  if (subs.length === 0) {
@@ -90052,10 +90148,10 @@ async function handlePrMonitorStatusCommand(directory, _args, sessionID, source)
90052
90148
  return lines.join(`
90053
90149
  `);
90054
90150
  }
90055
- var _internals56;
90151
+ var _internals57;
90056
90152
  var init_pr_monitor_status = __esm(() => {
90057
90153
  init_pr_subscriptions();
90058
- _internals56 = {
90154
+ _internals57 = {
90059
90155
  formatRelativeTime,
90060
90156
  listActive
90061
90157
  };
@@ -90169,7 +90265,7 @@ async function handlePrSubscribeCommand(directory, args2, sessionID) {
90169
90265
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
90170
90266
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
90171
90267
  try {
90172
- const config3 = _internals57.loadPluginConfig(directory);
90268
+ const config3 = _internals58.loadPluginConfig(directory);
90173
90269
  const prMonitorConfig = config3.pr_monitor;
90174
90270
  if (!prMonitorConfig?.enabled) {
90175
90271
  return [
@@ -90179,7 +90275,7 @@ async function handlePrSubscribeCommand(directory, args2, sessionID) {
90179
90275
  ].join(`
90180
90276
  `);
90181
90277
  }
90182
- await _internals57.subscribe(directory, {
90278
+ await _internals58.subscribe(directory, {
90183
90279
  sessionID,
90184
90280
  prNumber: prInfo.number,
90185
90281
  repoFullName,
@@ -90203,12 +90299,12 @@ async function handlePrSubscribeCommand(directory, args2, sessionID) {
90203
90299
  `);
90204
90300
  }
90205
90301
  }
90206
- var _internals57;
90302
+ var _internals58;
90207
90303
  var init_pr_subscribe = __esm(() => {
90208
90304
  init_pr_subscriptions();
90209
90305
  init_loader();
90210
90306
  init_pr_ref();
90211
- _internals57 = {
90307
+ _internals58 = {
90212
90308
  loadPluginConfig,
90213
90309
  subscribe
90214
90310
  };
@@ -90232,9 +90328,9 @@ async function handlePrUnsubscribeCommand(directory, args2, sessionID) {
90232
90328
  `);
90233
90329
  }
90234
90330
  const refToken = rest[0];
90235
- const prInfo = _internals58.parsePrRef(refToken, directory);
90331
+ const prInfo = _internals59.parsePrRef(refToken, directory);
90236
90332
  if (!prInfo) {
90237
- if (_internals58.looksLikePrRef(refToken)) {
90333
+ if (_internals59.looksLikePrRef(refToken)) {
90238
90334
  return [
90239
90335
  `Error: Could not resolve PR reference from "${refToken}".`,
90240
90336
  "",
@@ -90255,8 +90351,8 @@ async function handlePrUnsubscribeCommand(directory, args2, sessionID) {
90255
90351
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
90256
90352
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
90257
90353
  try {
90258
- const correlationId = _internals58.buildCorrelationId(sessionID, repoFullName, prInfo.number);
90259
- const result = await _internals58.unsubscribe(directory, correlationId);
90354
+ const correlationId = _internals59.buildCorrelationId(sessionID, repoFullName, prInfo.number);
90355
+ const result = await _internals59.unsubscribe(directory, correlationId);
90260
90356
  if (!result) {
90261
90357
  return [
90262
90358
  `Not subscribed to ${prUrl}`,
@@ -90283,11 +90379,11 @@ async function handlePrUnsubscribeCommand(directory, args2, sessionID) {
90283
90379
  `);
90284
90380
  }
90285
90381
  }
90286
- var _internals58;
90382
+ var _internals59;
90287
90383
  var init_pr_unsubscribe = __esm(() => {
90288
90384
  init_pr_subscriptions();
90289
90385
  init_pr_ref();
90290
- _internals58 = {
90386
+ _internals59 = {
90291
90387
  unsubscribe,
90292
90388
  buildCorrelationId,
90293
90389
  parsePrRef,
@@ -90743,7 +90839,7 @@ async function runAdditionalLint(linter, mode, cwd) {
90743
90839
  };
90744
90840
  }
90745
90841
  }
90746
- var MAX_OUTPUT_BYTES = 512000, MAX_COMMAND_LENGTH = 500, lint, _internals59;
90842
+ var MAX_OUTPUT_BYTES = 512000, MAX_COMMAND_LENGTH = 500, lint, _internals60;
90747
90843
  var init_lint = __esm(() => {
90748
90844
  init_zod();
90749
90845
  init_discovery();
@@ -90775,15 +90871,15 @@ var init_lint = __esm(() => {
90775
90871
  }
90776
90872
  const { mode } = args2;
90777
90873
  const cwd = directory;
90778
- const linter = await _internals59.detectAvailableLinter(directory);
90874
+ const linter = await _internals60.detectAvailableLinter(directory);
90779
90875
  if (linter) {
90780
- const result = await _internals59.runLint(linter, mode, directory);
90876
+ const result = await _internals60.runLint(linter, mode, directory);
90781
90877
  return JSON.stringify(result, null, 2);
90782
90878
  }
90783
- const additionalLinter = _internals59.detectAdditionalLinter(cwd);
90879
+ const additionalLinter = _internals60.detectAdditionalLinter(cwd);
90784
90880
  if (additionalLinter) {
90785
90881
  warn(`[lint] Using ${additionalLinter} linter for this project`);
90786
- const result = await _internals59.runAdditionalLint(additionalLinter, mode, cwd);
90882
+ const result = await _internals60.runAdditionalLint(additionalLinter, mode, cwd);
90787
90883
  return JSON.stringify(result, null, 2);
90788
90884
  }
90789
90885
  const errorResult = {
@@ -90797,7 +90893,7 @@ For Rust: rustup component add clippy`
90797
90893
  return JSON.stringify(errorResult, null, 2);
90798
90894
  }
90799
90895
  });
90800
- _internals59 = {
90896
+ _internals60 = {
90801
90897
  detectAvailableLinter,
90802
90898
  runLint,
90803
90899
  detectAdditionalLinter,
@@ -91111,7 +91207,7 @@ function findScannableFiles(dir, excludeExact, excludeGlobs, scanDir, visited, s
91111
91207
  }
91112
91208
  async function runSecretscan(directory) {
91113
91209
  try {
91114
- const result = await _internals60.secretscan.execute({ directory }, {});
91210
+ const result = await _internals61.secretscan.execute({ directory }, {});
91115
91211
  const jsonStr = typeof result === "string" ? result : result.output;
91116
91212
  return JSON.parse(jsonStr);
91117
91213
  } catch (e) {
@@ -91126,7 +91222,7 @@ async function runSecretscan(directory) {
91126
91222
  return errorResult;
91127
91223
  }
91128
91224
  }
91129
- var MAX_FILE_PATH_LENGTH = 500, MAX_FILE_SIZE_BYTES, MAX_FILES_SCANNED = 1000, MAX_FINDINGS = 100, MAX_OUTPUT_BYTES2 = 512000, MAX_LINE_LENGTH = 1e4, MAX_CONTENT_BYTES, BINARY_SIGNATURES, BINARY_PREFIX_BYTES = 4, BINARY_NULL_CHECK_BYTES = 8192, BINARY_NULL_THRESHOLD = 0.1, DEFAULT_EXCLUDE_DIRS, DEFAULT_EXCLUDE_EXTENSIONS, SECRET_PATTERNS2, O_NOFOLLOW, secretscan, _internals60;
91225
+ var MAX_FILE_PATH_LENGTH = 500, MAX_FILE_SIZE_BYTES, MAX_FILES_SCANNED = 1000, MAX_FINDINGS = 100, MAX_OUTPUT_BYTES2 = 512000, MAX_LINE_LENGTH = 1e4, MAX_CONTENT_BYTES, BINARY_SIGNATURES, BINARY_PREFIX_BYTES = 4, BINARY_NULL_CHECK_BYTES = 8192, BINARY_NULL_THRESHOLD = 0.1, DEFAULT_EXCLUDE_DIRS, DEFAULT_EXCLUDE_EXTENSIONS, SECRET_PATTERNS2, O_NOFOLLOW, secretscan, _internals61;
91130
91226
  var init_secretscan = __esm(() => {
91131
91227
  init_zod();
91132
91228
  init_path_security();
@@ -91498,7 +91594,7 @@ var init_secretscan = __esm(() => {
91498
91594
  }
91499
91595
  }
91500
91596
  });
91501
- _internals60 = {
91597
+ _internals61 = {
91502
91598
  secretscan,
91503
91599
  runSecretscan
91504
91600
  };
@@ -92090,14 +92186,14 @@ function buildGoBackend() {
92090
92186
  selectEntryPoints
92091
92187
  };
92092
92188
  }
92093
- var PROFILE_ID = "go", IMPORT_REGEX_SINGLE, IMPORT_REGEX_GROUP, IMPORT_REGEX_GROUP_LINE, _internals61;
92189
+ var PROFILE_ID = "go", IMPORT_REGEX_SINGLE, IMPORT_REGEX_GROUP, IMPORT_REGEX_GROUP_LINE, _internals62;
92094
92190
  var init_go = __esm(() => {
92095
92191
  init_default_backend();
92096
92192
  init_profiles();
92097
92193
  IMPORT_REGEX_SINGLE = /^\s*import\s+(?:[a-zA-Z_.][a-zA-Z0-9_]*\s+)?"([^"]+)"/gm;
92098
92194
  IMPORT_REGEX_GROUP = /^\s*import\s*\(([\s\S]*?)\)/gm;
92099
92195
  IMPORT_REGEX_GROUP_LINE = /(?:[a-zA-Z_.][a-zA-Z0-9_]*\s+)?"([^"]+)"/g;
92100
- _internals61 = { extractImports };
92196
+ _internals62 = { extractImports };
92101
92197
  });
92102
92198
 
92103
92199
  // src/lang/backends/python.ts
@@ -92209,13 +92305,13 @@ function buildPythonBackend() {
92209
92305
  selectEntryPoints: selectEntryPoints2
92210
92306
  };
92211
92307
  }
92212
- var PROFILE_ID2 = "python", IMPORT_REGEX_FROM_WITH_TARGETS, IMPORT_REGEX_IMPORT, _internals62;
92308
+ var PROFILE_ID2 = "python", IMPORT_REGEX_FROM_WITH_TARGETS, IMPORT_REGEX_IMPORT, _internals63;
92213
92309
  var init_python = __esm(() => {
92214
92310
  init_default_backend();
92215
92311
  init_profiles();
92216
92312
  IMPORT_REGEX_FROM_WITH_TARGETS = /^\s*from\s+(\.*[\w.]*)\s+import\s+(\([^)]*\)|[^\n#]+)/gm;
92217
92313
  IMPORT_REGEX_IMPORT = /^\s*import\s+([^\n#]+)/gm;
92218
- _internals62 = { extractImports: extractImports2 };
92314
+ _internals63 = { extractImports: extractImports2 };
92219
92315
  });
92220
92316
 
92221
92317
  // src/test-impact/analyzer.ts
@@ -92439,7 +92535,7 @@ function addImpactEdgesForTestFile(testFile, content, impactMap) {
92439
92535
  return;
92440
92536
  }
92441
92537
  if (PYTHON_EXTENSIONS.has(ext)) {
92442
- const modules = _internals62.extractImports(testFile, content);
92538
+ const modules = _internals63.extractImports(testFile, content);
92443
92539
  for (const mod of modules) {
92444
92540
  const resolved = resolvePythonImport(testDir, mod);
92445
92541
  if (resolved !== null)
@@ -92448,7 +92544,7 @@ function addImpactEdgesForTestFile(testFile, content, impactMap) {
92448
92544
  return;
92449
92545
  }
92450
92546
  if (GO_EXTENSIONS.has(ext)) {
92451
- const imports = _internals61.extractImports(testFile, content);
92547
+ const imports = _internals62.extractImports(testFile, content);
92452
92548
  for (const importPath of imports) {
92453
92549
  const sourceFiles = resolveGoImport(testDir, importPath);
92454
92550
  for (const source of sourceFiles)
@@ -92475,8 +92571,8 @@ async function buildImpactMapInternal(cwd) {
92475
92571
  return impactMap;
92476
92572
  }
92477
92573
  async function buildImpactMap(cwd) {
92478
- const impactMap = await _internals63.buildImpactMapInternal(cwd);
92479
- await _internals63.saveImpactMap(cwd, impactMap);
92574
+ const impactMap = await _internals64.buildImpactMapInternal(cwd);
92575
+ await _internals64.saveImpactMap(cwd, impactMap);
92480
92576
  return impactMap;
92481
92577
  }
92482
92578
  async function loadImpactMap(cwd, options) {
@@ -92490,7 +92586,7 @@ async function loadImpactMap(cwd, options) {
92490
92586
  const hasValidValues = Object.values(map3).every((v) => Array.isArray(v) && v.every((item) => typeof item === "string"));
92491
92587
  if (hasValidValues) {
92492
92588
  const generatedAt = new Date(data.generatedAt).getTime();
92493
- if (!_internals63.isCacheStale(map3, generatedAt)) {
92589
+ if (!_internals64.isCacheStale(map3, generatedAt)) {
92494
92590
  return map3;
92495
92591
  }
92496
92592
  if (options?.skipRebuild) {
@@ -92510,13 +92606,13 @@ async function loadImpactMap(cwd, options) {
92510
92606
  if (options?.skipRebuild) {
92511
92607
  return {};
92512
92608
  }
92513
- return _internals63.buildImpactMap(cwd);
92609
+ return _internals64.buildImpactMap(cwd);
92514
92610
  }
92515
92611
  async function saveImpactMap(cwd, impactMap) {
92516
92612
  if (!path94.isAbsolute(cwd)) {
92517
92613
  throw new Error(`saveImpactMap requires an absolute project root path, got: "${cwd}"`);
92518
92614
  }
92519
- _internals63.validateProjectRoot(cwd);
92615
+ _internals64.validateProjectRoot(cwd);
92520
92616
  const cacheDir2 = path94.join(cwd, ".swarm", "cache");
92521
92617
  const cachePath = path94.join(cacheDir2, "impact-map.json");
92522
92618
  if (!fs45.existsSync(cacheDir2)) {
@@ -92540,7 +92636,7 @@ async function analyzeImpact(changedFiles, cwd, budget) {
92540
92636
  };
92541
92637
  }
92542
92638
  const validFiles = changedFiles.filter((f) => typeof f === "string" && f.length > 0 && !f.includes("\x00"));
92543
- const impactMap = await _internals63.loadImpactMap(cwd);
92639
+ const impactMap = await _internals64.loadImpactMap(cwd);
92544
92640
  const impactedTestsSet = new Set;
92545
92641
  const untestedFiles = [];
92546
92642
  let visitedCount = 0;
@@ -92625,7 +92721,7 @@ async function analyzeImpact(changedFiles, cwd, budget) {
92625
92721
  budgetExceeded
92626
92722
  };
92627
92723
  }
92628
- var IMPORT_REGEX_ES, IMPORT_REGEX_REQUIRE, IMPORT_REGEX_REEXPORT, TS_EXTENSIONS, PYTHON_EXTENSIONS, GO_EXTENSIONS, EXTENSIONS_TO_TRY, goModuleCache, _internals63;
92724
+ var IMPORT_REGEX_ES, IMPORT_REGEX_REQUIRE, IMPORT_REGEX_REEXPORT, TS_EXTENSIONS, PYTHON_EXTENSIONS, GO_EXTENSIONS, EXTENSIONS_TO_TRY, goModuleCache, _internals64;
92629
92725
  var init_analyzer = __esm(() => {
92630
92726
  init_manager2();
92631
92727
  init_go();
@@ -92638,7 +92734,7 @@ var init_analyzer = __esm(() => {
92638
92734
  GO_EXTENSIONS = new Set([".go"]);
92639
92735
  EXTENSIONS_TO_TRY = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
92640
92736
  goModuleCache = new Map;
92641
- _internals63 = {
92737
+ _internals64 = {
92642
92738
  validateProjectRoot,
92643
92739
  normalizePath: normalizePath2,
92644
92740
  isCacheStale,
@@ -93021,7 +93117,7 @@ function batchAppendTestRuns(records, workingDir) {
93021
93117
  }
93022
93118
  const historyPath = getHistoryPath(workingDir);
93023
93119
  const historyDir = path95.dirname(historyPath);
93024
- _internals64.validateProjectRoot(workingDir);
93120
+ _internals65.validateProjectRoot(workingDir);
93025
93121
  if (!fs46.existsSync(historyDir)) {
93026
93122
  fs46.mkdirSync(historyDir, { recursive: true });
93027
93123
  }
@@ -93144,7 +93240,7 @@ function getAllHistory(workingDir) {
93144
93240
  records.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
93145
93241
  return records;
93146
93242
  }
93147
- var MAX_HISTORY_PER_TEST = 20, MAX_ERROR_LENGTH = 500, MAX_STACK_LENGTH = 200, MAX_CHANGED_FILES = 50, HISTORY_WRITE_LOCK_TIMEOUT_MS = 5000, HISTORY_WRITE_LOCK_STALE_MS = 60000, HISTORY_WRITE_LOCK_BACKOFF_MS = 10, DANGEROUS_PROPERTY_NAMES, _internals64;
93243
+ var MAX_HISTORY_PER_TEST = 20, MAX_ERROR_LENGTH = 500, MAX_STACK_LENGTH = 200, MAX_CHANGED_FILES = 50, HISTORY_WRITE_LOCK_TIMEOUT_MS = 5000, HISTORY_WRITE_LOCK_STALE_MS = 60000, HISTORY_WRITE_LOCK_BACKOFF_MS = 10, DANGEROUS_PROPERTY_NAMES, _internals65;
93148
93244
  var init_history_store = __esm(() => {
93149
93245
  init_manager2();
93150
93246
  DANGEROUS_PROPERTY_NAMES = new Set([
@@ -93152,7 +93248,7 @@ var init_history_store = __esm(() => {
93152
93248
  "constructor",
93153
93249
  "prototype"
93154
93250
  ]);
93155
- _internals64 = {
93251
+ _internals65 = {
93156
93252
  validateProjectRoot
93157
93253
  };
93158
93254
  });
@@ -93191,7 +93287,7 @@ function resolveWorkingDirectory(workingDirectory, fallbackDirectory) {
93191
93287
  };
93192
93288
  }
93193
93289
  }
93194
- const rawPathParts = workingDirectory.split(path96.sep);
93290
+ const rawPathParts = workingDirectory.split(/[\\/]/);
93195
93291
  if (rawPathParts.includes("..")) {
93196
93292
  return {
93197
93293
  success: false,
@@ -93402,7 +93498,7 @@ function readPackageJsonRaw(dir) {
93402
93498
  }
93403
93499
  }
93404
93500
  function readPackageJson(dir) {
93405
- return _internals65.readPackageJsonRaw(dir);
93501
+ return _internals66.readPackageJsonRaw(dir);
93406
93502
  }
93407
93503
  function readPackageJsonTestScript(dir) {
93408
93504
  return readPackageJson(dir)?.scripts?.test ?? null;
@@ -93572,7 +93668,7 @@ function buildTypescriptBackend() {
93572
93668
  selectEntryPoints: selectEntryPoints3
93573
93669
  };
93574
93670
  }
93575
- var PROFILE_ID4 = "typescript", IMPORT_REGEX_ES2, IMPORT_REGEX_BARE, IMPORT_REGEX_REQUIRE2, IMPORT_REGEX_DYNAMIC, IMPORT_REGEX_REEXPORT2, _internals65;
93671
+ var PROFILE_ID4 = "typescript", IMPORT_REGEX_ES2, IMPORT_REGEX_BARE, IMPORT_REGEX_REQUIRE2, IMPORT_REGEX_DYNAMIC, IMPORT_REGEX_REEXPORT2, _internals66;
93576
93672
  var init_typescript = __esm(() => {
93577
93673
  init_default_backend();
93578
93674
  init_profiles();
@@ -93581,7 +93677,7 @@ var init_typescript = __esm(() => {
93581
93677
  IMPORT_REGEX_REQUIRE2 = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
93582
93678
  IMPORT_REGEX_DYNAMIC = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
93583
93679
  IMPORT_REGEX_REEXPORT2 = /export\s+(?:\{[^}]*\}|\*)\s+from\s+['"]([^'"]+)['"]/g;
93584
- _internals65 = {
93680
+ _internals66 = {
93585
93681
  readPackageJsonRaw,
93586
93682
  readPackageJsonTestScript,
93587
93683
  frameworkFromScriptsTest
@@ -93614,7 +93710,7 @@ __export(exports_dispatch, {
93614
93710
  pickedProfiles: () => pickedProfiles,
93615
93711
  pickBackend: () => pickBackend,
93616
93712
  clearDispatchCache: () => clearDispatchCache,
93617
- _internals: () => _internals66
93713
+ _internals: () => _internals67
93618
93714
  });
93619
93715
  import * as fs50 from "node:fs";
93620
93716
  import * as path99 from "node:path";
@@ -93669,7 +93765,7 @@ function findManifestRoot(start) {
93669
93765
  return start;
93670
93766
  }
93671
93767
  function evictIfNeeded() {
93672
- if (cache2.size <= _internals66.cacheCapacity)
93768
+ if (cache2.size <= _internals67.cacheCapacity)
93673
93769
  return;
93674
93770
  let oldestKey;
93675
93771
  let oldestOrder = Infinity;
@@ -93700,7 +93796,7 @@ async function pickBackend(dir) {
93700
93796
  evictIfNeeded();
93701
93797
  return null;
93702
93798
  }
93703
- const profiles = await _internals66.detectProjectLanguages(root);
93799
+ const profiles = await _internals67.detectProjectLanguages(root);
93704
93800
  if (profiles.length === 0) {
93705
93801
  cache2.set(cacheKey, {
93706
93802
  hash: hash4,
@@ -93732,12 +93828,12 @@ function clearDispatchCache() {
93732
93828
  manifestRootCache.clear();
93733
93829
  insertCounter = 0;
93734
93830
  }
93735
- var _internals66, cache2, insertCounter = 0, MANIFEST_FILES, _MANIFEST_SET, manifestRootCache;
93831
+ var _internals67, cache2, insertCounter = 0, MANIFEST_FILES, _MANIFEST_SET, manifestRootCache;
93736
93832
  var init_dispatch = __esm(() => {
93737
93833
  init_backends();
93738
93834
  init_detector();
93739
93835
  init_registry_backend();
93740
- _internals66 = {
93836
+ _internals67 = {
93741
93837
  detectProjectLanguages,
93742
93838
  cacheCapacity: 64
93743
93839
  };
@@ -95593,9 +95689,9 @@ function getVersionFileVersion(dir) {
95593
95689
  async function runVersionCheck2(dir, _timeoutMs) {
95594
95690
  const startTime = Date.now();
95595
95691
  try {
95596
- const packageVersion = _internals67.getPackageVersion(dir);
95597
- const changelogVersion = _internals67.getChangelogVersion(dir);
95598
- const versionFileVersion = _internals67.getVersionFileVersion(dir);
95692
+ const packageVersion = _internals68.getPackageVersion(dir);
95693
+ const changelogVersion = _internals68.getChangelogVersion(dir);
95694
+ const versionFileVersion = _internals68.getVersionFileVersion(dir);
95599
95695
  const versions3 = [];
95600
95696
  if (packageVersion)
95601
95697
  versions3.push(`package.json: ${packageVersion}`);
@@ -95959,7 +96055,7 @@ async function runPreflight(dir, phase, config3) {
95959
96055
  const reportId = `preflight-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
95960
96056
  let validatedDir;
95961
96057
  try {
95962
- validatedDir = _internals67.validateDirectoryPath(dir);
96058
+ validatedDir = _internals68.validateDirectoryPath(dir);
95963
96059
  } catch (error93) {
95964
96060
  return {
95965
96061
  id: reportId,
@@ -95979,7 +96075,7 @@ async function runPreflight(dir, phase, config3) {
95979
96075
  }
95980
96076
  let validatedTimeout;
95981
96077
  try {
95982
- validatedTimeout = _internals67.validateTimeout(config3?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
96078
+ validatedTimeout = _internals68.validateTimeout(config3?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
95983
96079
  } catch (error93) {
95984
96080
  return {
95985
96081
  id: reportId,
@@ -96020,12 +96116,12 @@ async function runPreflight(dir, phase, config3) {
96020
96116
  });
96021
96117
  const checks5 = [];
96022
96118
  log("[Preflight] Running lint check...");
96023
- const lintResult = await _internals67.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
96119
+ const lintResult = await _internals68.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
96024
96120
  checks5.push(lintResult);
96025
96121
  log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`);
96026
96122
  if (!cfg.skipTests) {
96027
96123
  log("[Preflight] Running tests check...");
96028
- const testsResult = await _internals67.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
96124
+ const testsResult = await _internals68.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
96029
96125
  checks5.push(testsResult);
96030
96126
  log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`);
96031
96127
  } else {
@@ -96037,7 +96133,7 @@ async function runPreflight(dir, phase, config3) {
96037
96133
  }
96038
96134
  if (!cfg.skipSecrets) {
96039
96135
  log("[Preflight] Running secrets check...");
96040
- const secretsResult = await _internals67.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
96136
+ const secretsResult = await _internals68.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
96041
96137
  checks5.push(secretsResult);
96042
96138
  log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`);
96043
96139
  } else {
@@ -96049,7 +96145,7 @@ async function runPreflight(dir, phase, config3) {
96049
96145
  }
96050
96146
  if (!cfg.skipEvidence) {
96051
96147
  log("[Preflight] Running evidence check...");
96052
- const evidenceResult = await _internals67.runEvidenceCheck(validatedDir);
96148
+ const evidenceResult = await _internals68.runEvidenceCheck(validatedDir);
96053
96149
  checks5.push(evidenceResult);
96054
96150
  log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`);
96055
96151
  } else {
@@ -96060,12 +96156,12 @@ async function runPreflight(dir, phase, config3) {
96060
96156
  });
96061
96157
  }
96062
96158
  log("[Preflight] Running requirement coverage check...");
96063
- const reqCoverageResult = await _internals67.runRequirementCoverageCheck(validatedDir, phase);
96159
+ const reqCoverageResult = await _internals68.runRequirementCoverageCheck(validatedDir, phase);
96064
96160
  checks5.push(reqCoverageResult);
96065
96161
  log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`);
96066
96162
  if (!cfg.skipVersion) {
96067
96163
  log("[Preflight] Running version check...");
96068
- const versionResult = await _internals67.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
96164
+ const versionResult = await _internals68.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
96069
96165
  checks5.push(versionResult);
96070
96166
  log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`);
96071
96167
  } else {
@@ -96128,10 +96224,10 @@ function formatPreflightMarkdown(report) {
96128
96224
  async function handlePreflightCommand(directory, _args) {
96129
96225
  const plan = await loadPlan(directory);
96130
96226
  const phase = plan?.current_phase ?? 1;
96131
- const report = await _internals67.runPreflight(directory, phase);
96132
- return _internals67.formatPreflightMarkdown(report);
96227
+ const report = await _internals68.runPreflight(directory, phase);
96228
+ return _internals68.formatPreflightMarkdown(report);
96133
96229
  }
96134
- var MIN_CHECK_TIMEOUT_MS = 5000, MAX_CHECK_TIMEOUT_MS = 300000, DEFAULT_CONFIG, _internals67;
96230
+ var MIN_CHECK_TIMEOUT_MS = 5000, MAX_CHECK_TIMEOUT_MS = 300000, DEFAULT_CONFIG, _internals68;
96135
96231
  var init_preflight_service = __esm(() => {
96136
96232
  init_gate_bridge();
96137
96233
  init_manager2();
@@ -96150,7 +96246,7 @@ var init_preflight_service = __esm(() => {
96150
96246
  testScope: "convention",
96151
96247
  linter: "biome"
96152
96248
  };
96153
- _internals67 = {
96249
+ _internals68 = {
96154
96250
  runPreflight,
96155
96251
  formatPreflightMarkdown,
96156
96252
  handlePreflightCommand,
@@ -97977,7 +98073,7 @@ function resetPrmSessionState(session, sessionId) {
97977
98073
  session.prmTrajectoryStep = 0;
97978
98074
  session.replayArtifactPath = null;
97979
98075
  if (sessionId) {
97980
- _internals68.clearTrajectoryCache(sessionId);
98076
+ _internals69.clearTrajectoryCache(sessionId);
97981
98077
  }
97982
98078
  }
97983
98079
  function createPrmHook(config3, directory) {
@@ -97986,26 +98082,26 @@ function createPrmHook(config3, directory) {
97986
98082
  return;
97987
98083
  }
97988
98084
  const { sessionID } = context;
97989
- const session = _internals68.getAgentSession(sessionID);
98085
+ const session = _internals69.getAgentSession(sessionID);
97990
98086
  if (!session || !session.delegationActive) {
97991
98087
  return;
97992
98088
  }
97993
98089
  try {
97994
- const cachedTrajectory = _internals68.getInMemoryTrajectory(sessionID);
97995
- const trajectory = cachedTrajectory.length > 0 ? cachedTrajectory : await _internals68.readTrajectory(sessionID, directory);
97996
- const detectionResult = _internals68.detectPatterns(trajectory, config3, session.prmTrajectoryStep);
98090
+ const cachedTrajectory = _internals69.getInMemoryTrajectory(sessionID);
98091
+ const trajectory = cachedTrajectory.length > 0 ? cachedTrajectory : await _internals69.readTrajectory(sessionID, directory);
98092
+ const detectionResult = _internals69.detectPatterns(trajectory, config3, session.prmTrajectoryStep);
97997
98093
  if (detectionResult.matches.length === 0) {
97998
98094
  return;
97999
98095
  }
98000
98096
  const sessionPrmState = session;
98001
98097
  let escalationTracker = sessionPrmState.prmEscalationTracker;
98002
98098
  if (!sessionPrmState.replayArtifactPath) {
98003
- sessionPrmState.replayArtifactPath = await _internals68.startReplayRecording(sessionID, directory);
98099
+ sessionPrmState.replayArtifactPath = await _internals69.startReplayRecording(sessionID, directory);
98004
98100
  }
98005
98101
  const artifactPath = sessionPrmState.replayArtifactPath;
98006
98102
  if (!sessionPrmState.prmInitialized) {
98007
98103
  sessionPrmState.prmInitialized = true;
98008
- _internals68.cleanupOldTrajectoryFiles(directory).catch(() => {});
98104
+ _internals69.cleanupOldTrajectoryFiles(directory).catch(() => {});
98009
98105
  }
98010
98106
  if (!escalationTracker) {
98011
98107
  const initialState = session.prmLastPatternDetected ? {
@@ -98020,8 +98116,8 @@ function createPrmHook(config3, directory) {
98020
98116
  }
98021
98117
  const previousEscalationLevel = session.prmEscalationLevel;
98022
98118
  for (const match of detectionResult.matches) {
98023
- const correction = _internals68.generateCourseCorrection(match, trajectory);
98024
- const formattedCorrection = _internals68.formatCourseCorrectionForInjection(correction);
98119
+ const correction = _internals69.generateCourseCorrection(match, trajectory);
98120
+ const formattedCorrection = _internals69.formatCourseCorrectionForInjection(correction);
98025
98121
  if (!session.pendingAdvisoryMessages) {
98026
98122
  session.pendingAdvisoryMessages = [];
98027
98123
  }
@@ -98037,10 +98133,10 @@ function createPrmHook(config3, directory) {
98037
98133
  session.prmEscalationLevel = escalationLevel;
98038
98134
  session.prmLastPatternDetected = match;
98039
98135
  session.prmHardStopPending = hardStopPending;
98040
- _internals68.telemetry.prmPatternDetected(sessionID, match.pattern, match.severity, match.category, match.stepRange);
98041
- _internals68.telemetry.prmCourseCorrectionInjected(sessionID, match.pattern, escalationLevel);
98136
+ _internals69.telemetry.prmPatternDetected(sessionID, match.pattern, match.severity, match.category, match.stepRange);
98137
+ _internals69.telemetry.prmCourseCorrectionInjected(sessionID, match.pattern, escalationLevel);
98042
98138
  if (artifactPath) {
98043
- await _internals68.recordReplayEntry(artifactPath, sessionID, {
98139
+ await _internals69.recordReplayEntry(artifactPath, sessionID, {
98044
98140
  type: "pattern_detected",
98045
98141
  data: {
98046
98142
  pattern: match.pattern,
@@ -98055,7 +98151,7 @@ function createPrmHook(config3, directory) {
98055
98151
  });
98056
98152
  }
98057
98153
  if (artifactPath) {
98058
- await _internals68.recordReplayEntry(artifactPath, sessionID, {
98154
+ await _internals69.recordReplayEntry(artifactPath, sessionID, {
98059
98155
  type: "course_correction",
98060
98156
  data: {
98061
98157
  pattern: correction.pattern,
@@ -98071,7 +98167,7 @@ function createPrmHook(config3, directory) {
98071
98167
  }
98072
98168
  escalationTracker.clearPendingCorrections();
98073
98169
  if (artifactPath && session.prmEscalationLevel > previousEscalationLevel) {
98074
- await _internals68.recordReplayEntry(artifactPath, sessionID, {
98170
+ await _internals69.recordReplayEntry(artifactPath, sessionID, {
98075
98171
  type: "escalation",
98076
98172
  data: {
98077
98173
  previousLevel: previousEscalationLevel,
@@ -98081,7 +98177,7 @@ function createPrmHook(config3, directory) {
98081
98177
  });
98082
98178
  }
98083
98179
  if (artifactPath && session.prmHardStopPending && previousEscalationLevel < 3) {
98084
- await _internals68.recordReplayEntry(artifactPath, sessionID, {
98180
+ await _internals69.recordReplayEntry(artifactPath, sessionID, {
98085
98181
  type: "hard_stop",
98086
98182
  data: {
98087
98183
  escalationLevel: session.prmEscalationLevel,
@@ -98098,7 +98194,7 @@ function createPrmHook(config3, directory) {
98098
98194
  }
98099
98195
  return { toolAfter };
98100
98196
  }
98101
- var _internals68;
98197
+ var _internals69;
98102
98198
  var init_prm = __esm(() => {
98103
98199
  init_course_correction();
98104
98200
  init_escalation();
@@ -98110,7 +98206,7 @@ var init_prm = __esm(() => {
98110
98206
  init_pattern_detector();
98111
98207
  init_replay();
98112
98208
  init_trajectory_store();
98113
- _internals68 = {
98209
+ _internals69 = {
98114
98210
  getAgentSession,
98115
98211
  readTrajectory,
98116
98212
  getInMemoryTrajectory,
@@ -99273,7 +99369,7 @@ async function getStatusData(directory, agents) {
99273
99369
  }
99274
99370
  function enrichWithLeanTurbo(status, directory) {
99275
99371
  const turboMode = hasActiveTurboMode();
99276
- const leanActive = _internals69.hasActiveLeanTurbo();
99372
+ const leanActive = _internals70.hasActiveLeanTurbo();
99277
99373
  let turboStrategy = "off";
99278
99374
  if (leanActive) {
99279
99375
  turboStrategy = "lean";
@@ -99292,7 +99388,7 @@ function enrichWithLeanTurbo(status, directory) {
99292
99388
  }
99293
99389
  }
99294
99390
  if (leanSessionID) {
99295
- const runState = _internals69.loadLeanTurboRunState(directory, leanSessionID);
99391
+ const runState = _internals70.loadLeanTurboRunState(directory, leanSessionID);
99296
99392
  if (runState) {
99297
99393
  status.leanTurboPhase = runState.phase;
99298
99394
  status.leanMaxParallelCoders = runState.maxParallelCoders;
@@ -99324,7 +99420,7 @@ function enrichWithLeanTurbo(status, directory) {
99324
99420
  }
99325
99421
  }
99326
99422
  }
99327
- status.fullAutoActive = _internals69.hasActiveFullAuto();
99423
+ status.fullAutoActive = _internals70.hasActiveFullAuto();
99328
99424
  return status;
99329
99425
  }
99330
99426
  function formatStatusMarkdown(status) {
@@ -99452,7 +99548,7 @@ async function countProposals(directory) {
99452
99548
  return 0;
99453
99549
  }
99454
99550
  }
99455
- var _internals69;
99551
+ var _internals70;
99456
99552
  var init_status_service = __esm(() => {
99457
99553
  init_extractors();
99458
99554
  init_knowledge_escalator();
@@ -99463,7 +99559,7 @@ var init_status_service = __esm(() => {
99463
99559
  init_state4();
99464
99560
  init_compaction_service();
99465
99561
  init_context_budget_service();
99466
- _internals69 = {
99562
+ _internals70 = {
99467
99563
  loadLeanTurboRunState,
99468
99564
  hasActiveLeanTurbo,
99469
99565
  hasActiveFullAuto
@@ -99560,7 +99656,7 @@ async function handleTurboCommand(directory, args2, sessionID) {
99560
99656
  if (arg0 === "on") {
99561
99657
  let strategy = "standard";
99562
99658
  try {
99563
- const { config: config3 } = _internals70.loadPluginConfigWithMeta(directory);
99659
+ const { config: config3 } = _internals71.loadPluginConfigWithMeta(directory);
99564
99660
  if (config3.turbo?.strategy === "lean") {
99565
99661
  strategy = "lean";
99566
99662
  }
@@ -99657,7 +99753,7 @@ function enableLeanTurbo(session, directory, sessionID) {
99657
99753
  let maxParallelCoders = 4;
99658
99754
  let conflictPolicy = "serialize";
99659
99755
  try {
99660
- const { config: config3 } = _internals70.loadPluginConfigWithMeta(directory);
99756
+ const { config: config3 } = _internals71.loadPluginConfigWithMeta(directory);
99661
99757
  const leanConfig = config3.turbo?.lean;
99662
99758
  if (leanConfig) {
99663
99759
  maxParallelCoders = leanConfig.max_parallel_coders ?? 4;
@@ -99727,14 +99823,14 @@ function buildStatusMessage2(session, directory, sessionID) {
99727
99823
  ].join(`
99728
99824
  `);
99729
99825
  }
99730
- var _internals70;
99826
+ var _internals71;
99731
99827
  var init_turbo = __esm(() => {
99732
99828
  init_config();
99733
99829
  init_state2();
99734
99830
  init_state();
99735
99831
  init_state4();
99736
99832
  init_logger();
99737
- _internals70 = {
99833
+ _internals71 = {
99738
99834
  loadPluginConfigWithMeta
99739
99835
  };
99740
99836
  });
@@ -101625,7 +101721,7 @@ Subcommands:
101625
101721
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handlePrReviewCommand),
101626
101722
  description: "Launch deep PR review with multi-lane analysis [url] [--council]",
101627
101723
  args: "<pr-url|owner/repo#N|N> [--council]",
101628
- details: "Launches a structured PR review: reconstructs PR intent via obligation extraction cascade, runs 6 parallel explorer lanes through the deterministic dispatch_lanes join barrier (correctness, security, dependencies, docs-intent-vs-actual, tests, performance-architecture), validates findings through independent reviewer confirmation, applies critic challenge to HIGH/CRITICAL findings, synthesizes structured report. --council variant fires adversarial multi-model review. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolves against origin remote).",
101724
+ details: "Launches a structured PR review: reconstructs PR intent via obligation extraction cascade, launches all 6 fixed base explorer lanes through dispatch_lanes_async while the architect keeps doing non-dependent work, polls collect_lane_results incrementally, runs every triggered micro-lane, validates findings through independent reviewer confirmation, applies critic challenge to HIGH/CRITICAL findings, then synthesizes only after coverage is closed. If lane tools cannot close coverage, Task-tool dispatch is the final verified-equivalent fallback; if equivalence cannot be proven, the review is BLOCKED rather than degraded. --council variant fires adversarial multi-model review. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolves against origin remote).",
101629
101725
  category: "agent",
101630
101726
  toolPolicy: "none"
101631
101727
  },
@@ -102658,6 +102754,8 @@ If a tool modifies a file, it is a CODER tool. Delegate.
102658
102754
  2. ONE agent per message. Send, STOP, wait for response.
102659
102755
  Exception: Stage B reviewer/test_engineer gate agents for the SAME completed coder task may be dispatched together before waiting when both gates are required. This exception NEVER applies to coder delegations. Preserve ONE task per coder call.
102660
102756
  Separate parallel-mode exception (distinct from the Stage B exception above, and the ONLY case where more than one coder may be dispatched before waiting): when an active \`[PARALLEL EXECUTION PROFILE]\` directive is present in your context (parallelization_enabled=true), you MAY dispatch multiple {{AGENT_PREFIX}}coder agents in a single message — up to the stated max_concurrent_tasks — but ONLY for distinct, dependency-ready tasks whose declared file scopes do NOT overlap. Each coder still requires its own \`declare_scope\` call and carries exactly ONE task (Rule 3 still holds: never batch multiple objectives into one coder). Parallel coders each run in an isolated git worktree, so their writes never collide and are merged back automatically. If no \`[PARALLEL EXECUTION PROFILE]\` directive is present, dispatch coders one at a time.
102757
+
102758
+ > **WORKTREE ISOLATION IS BASELINE.** Standard parallel coders use isolated git worktrees by default; this is governed by the top-level \`worktree.policy\` setting (default \`auto\`) in \`PluginConfig\` — a sibling of \`parallelization:\`, not nested under it — and is active whenever the plan's \`parallelization_enabled=true\`. \`turbo.lean.worktree_isolation\` is a separate, Lean-Turbo-internal flag (default \`false\`); it is one possible SOURCE but NOT the recommended one. Do NOT recommend Lean Turbo (or Epic) SOLELY to obtain worktree isolation; recommend them only for what they add beyond baseline (Lean Turbo: lane planning, file locks, phase reviewer, integrated diff; Epic: co-change awareness + auto-decide). Lean Turbo users can also enable isolation via \`turbo.lean.worktree_isolation: true\`, but this is the secondary/legacy path — the recommended path is \`worktree.policy\`.
102661
102759
  Read-only advisory-lane exception (NON-BLOCKING; distinct from both exceptions above): the "Send, STOP, wait" rule governs MUTATION delegations (coder, and the test_engineer/reviewer Stage B completion gates). It does NOT govern read-only advisory exploration/review lanes. When you dispatch read-only advisory lanes — \`{{AGENT_PREFIX}}explorer\`, \`{{AGENT_PREFIX}}sme\`, \`{{AGENT_PREFIX}}researcher\`, the council members (\`council_generalist\`/\`council_skeptic\`/\`council_domain_expert\`), or an advisory \`{{AGENT_PREFIX}}critic\` lane — use the NON-BLOCKING path so you keep working while they run. Dispatch PROMPTLY: emit the \`dispatch_lanes_async\` call EARLY with compact lane prompts — do not accumulate long planning prose or build oversized inline prompts first, or the tool call can be truncated out of your message and the lanes never launch (a real failure mode on smaller models). The lane mechanism is a SINGLE \`dispatch_lanes_async\` call carrying all lane specs — NOT a per-agent Task/run-in-background pattern. Call \`dispatch_lanes_async\` with all lane specs in one call, record the returned \`batch_id\`, then IMMEDIATELY continue non-dependent architect work (refine the plan/obligation ledger, inspect metadata, prepare the synthesis/reviewer structure, run deterministic read-only tools). Poll incrementally with \`collect_lane_results\` without \`wait\` (or with \`wait: false\`) to harvest lanes as they settle; process completed lane output immediately while other lanes remain pending/running, then continue independent work between polls. Do NOT sit idle waiting on running lanes, and do NOT synthesize findings from still-running lanes. Join later by calling \`collect_lane_results\` with \`wait: true\` as the explicit barrier immediately before you synthesize. Use blocking \`dispatch_lanes\` only when \`dispatch_lanes_async\`/promptAsync is unavailable. Keep each lane prompt compact: send large shared context (PR diff, ledger, scope) ONCE via the \`common_prompt\` field, or have lanes read it from a file by absolute path, instead of inlining the same blob into every lane prompt — inlining large context into many lanes is what produces malformed or truncated tool-call JSON and forces clumsy file workarounds. This non-blocking exception applies ONLY to read-only advisory lanes; it NEVER applies to coder delegations, to the test_engineer/reviewer Stage B completion gates, or to the critic PLAN-review gate, which all still follow "Send, STOP, wait" (or the Stage B parallel-dispatch exception above).
102662
102760
  3. ONE task per {{AGENT_PREFIX}}coder call. Never batch.
102663
102761
  3a. PRE-DELEGATION SCOPE CALL (required): BEFORE every {{AGENT_PREFIX}}coder delegation, you MUST call \`declare_scope\` with { taskId, files } listing the exact file(s) this task will modify (including generated/lockfile paths). No \`declare_scope\` call → no coder delegation. See Rule 1a.
@@ -103263,6 +103361,7 @@ ACTION: Load skill file:.opencode/skills/pre-phase-briefing/SKILL.md immediately
103263
103361
 
103264
103362
  HARD CONSTRAINTS:
103265
103363
  - Complete the codebase reality report before spec finalization, plan generation, plan ingestion, declare_scope, or starting/resuming phase implementation. Dispatching the reality-check lanes asynchronously is allowed and preferred; settling all lanes before any of that downstream work is not optional.
103364
+ - When reality-check lanes are dispatched asynchronously, record the \`batch_id\`, keep doing non-dependent architect work, poll with \`collect_lane_results\` without \`wait\`, process settled lanes immediately, and use \`wait: true\` only when no independent work remains.
103266
103365
 
103267
103366
  ### MODE: COUNCIL
103268
103367
  Activates when the user invokes /swarm council or requests a council-style decision review.
@@ -103273,6 +103372,7 @@ ACTION: Load skill file:.opencode/skills/council/SKILL.md immediately. Follow th
103273
103372
 
103274
103373
  HARD CONSTRAINTS:
103275
103374
  - Provide research context up front and synthesize only from returned council member responses.
103375
+ - For async council lanes, record the \`batch_id\`, keep doing non-dependent architect work, poll with \`collect_lane_results\` without \`wait\`, process settled lanes immediately, and use \`wait: true\` only when no independent work remains.
103276
103376
 
103277
103377
  ### MODE: DEEP_DIVE
103278
103378
  Activates when: architect receives \`[MODE: DEEP_DIVE profile=X max_explorers=N output=X update_main=X allow_dirty=X] <scope>\` signal from the deep-dive command handler.
@@ -103289,6 +103389,7 @@ HARD CONSTRAINTS (apply regardless of skill load success):
103289
103389
  - No final finding may appear in the report without reviewer verification
103290
103390
  - Explorers generate candidate findings only — reviewers verify or reject
103291
103391
  - Critics challenge only HIGH/CRITICAL findings — do NOT waste cycles on lower severity
103392
+ - For async explorer waves, record the \`batch_id\`, keep doing non-dependent architect work, poll with \`collect_lane_results\` without \`wait\`, process settled lanes immediately, and use \`wait: true\` only when no independent work remains.
103292
103393
 
103293
103394
  ### MODE: LOOP
103294
103395
  Activates when: architect receives \`[MODE: LOOP max_cycles=N autonomy=checkpoint|auto depth=standard|exhaustive resume=true|false] <objective>\` signal from the loop command handler.
@@ -103322,6 +103423,8 @@ HARD CONSTRAINTS (apply regardless of skill load success):
103322
103423
  - Critics challenge only high-stakes / contested claims — do NOT waste cycles on well-supported ones
103323
103424
  - If council.general.enabled is false or no search API key is configured, surface that and STOP — do not produce ungrounded research
103324
103425
 
103426
+ - For async synthesis lanes, record the \`batch_id\`, keep doing non-dependent architect work, poll with \`collect_lane_results\` without \`wait\`, process settled lanes immediately, and use \`wait: true\` only when no independent work remains.
103427
+
103325
103428
  ### MODE: CODEBASE_REVIEW
103326
103429
  Activates when: architect receives \`[MODE: CODEBASE_REVIEW mode=X output=X update_main=X allow_dirty=X tracks="..." continue_run="..."] scope="..."\` signal from the codebase-review command handler.
103327
103430
 
@@ -103341,6 +103444,8 @@ HARD CONSTRAINTS (apply regardless of skill load success):
103341
103444
  - Every repo-derived factual claim needs quote-grounded evidence with file path and line/range
103342
103445
  - Final report is forbidden until selected-track coverage is closed and final critic passes
103343
103446
 
103447
+ - For async inventory or candidate-generation lanes, record the \`batch_id\`, keep doing non-dependent architect work, poll with \`collect_lane_results\` without \`wait\`, process settled lanes immediately, and use \`wait: true\` only when no independent work remains.
103448
+
103344
103449
  ### MODE: DESIGN_DOCS
103345
103450
  Activates when: architect receives \`[MODE: DESIGN_DOCS out=X lang=X update=X] <description>\` signal from the design-docs command handler (issue #1080).
103346
103451
 
@@ -103372,9 +103477,11 @@ HARD CONSTRAINTS (apply regardless of skill load success):
103372
103477
  - No finding may appear as CONFIRMED in the final report without reviewer validation provenance
103373
103478
  - Test execution, explorer lanes, reviewer dispatch, and critic challenge are all permitted within this mode
103374
103479
  - Quality is the only metric — time, tokens, and agent dispatches are irrelevant to correctness
103375
- - FOLLOW THE SKILL EXACTLY: execute every phase of the loaded SKILL.md in order with no shortcuts, no phase-skipping, and no premature synthesis. If a phase cannot complete, state the limitation explicitly and continue do not silently skip it.
103480
+ - FOLLOW THE SKILL EXACTLY: execute every phase of the loaded SKILL.md in order with no shortcuts, no phase-skipping, and no premature synthesis. If a required coverage phase cannot complete, apply the skill's coverage gate (retry or verified equivalent alternative). If the gap still cannot be closed, stop and surface the lane failure to the user as BLOCKED; do not produce a degraded review, partial verdict, or final synthesis.
103376
103481
  - CHECK OUT THE PR BRANCH LOCALLY before launching explorer lanes: fetch the PR head ref if it is not present, verify the working tree is clean (git status --porcelain) and stash/abort if not, then check out the head branch. Explorers read the working-tree filesystem (Read/Glob/Grep), so without a checkout they read the base branch and produce invalid candidates. Always pass the base..head commit range in explorer delegations.
103377
- - RUN THE TRIGGERED MICRO-LANES: after the base explorer lanes start, inspect the context pack risk triggers and launch every matching Swarm plugin micro-lane from the skill's risk-trigger map (launch only triggered lanes, never irrelevant ones). Do not skip micro-lanes that match the diff.
103482
+ - RUN ALL BASE LANES: the default PR_REVIEW path always launches the fixed six base check-type lanes from the skill (correctness, security, dependencies/deployment, docs/intent, tests, performance/architecture). Do not collapse, omit, or scale down the base lanes for a small, docs-only, or CI-only PR.
103483
+ - USE ASYNC DISPATCH WITHOUT IDLING: launch the base lanes with one \`dispatch_lanes_async\` call when available, record the \`batch_id\`, then keep doing non-dependent architect work while they run. Poll with \`collect_lane_results\` without \`wait\` (or \`wait: false\`) to process settled lanes and continue independent work between polls; use \`wait: true\` only as the final join when no independent work remains.
103484
+ - RUN THE TRIGGERED MICRO-LANES: after the base explorer lanes settle, inspect the context pack risk triggers and launch every matching Swarm plugin micro-lane from the skill's risk-trigger map (launch only triggered lanes, never irrelevant ones). Do not skip micro-lanes that match the diff; when multiple micro-lanes are needed, dispatch them with \`dispatch_lanes_async\` and the same non-idling incremental collection pattern.
103378
103485
  - Honor any free-text instructions that follow the closing bracket of the signal as additional reviewer focus, without weakening the validation ladder above.
103379
103486
 
103380
103487
  ### MODE: PR_FEEDBACK
@@ -103389,6 +103496,7 @@ HARD CONSTRAINTS (apply regardless of skill load success):
103389
103496
  - CHECK OUT THE PR BRANCH LOCALLY before verifying feedback or making fixes: fetch the PR head ref if absent, verify the working tree is clean (git status --porcelain) and stash/abort if not, then check out the head branch. Feedback verification and fix validation require the PR branch in the working tree.
103390
103497
  - Do NOT run a fresh broad PR review — inspect adjacent code only as needed to verify reachability, dependencies, shared root causes, regression risk, or sibling changes for a confirmed item.
103391
103498
  - Treat every review comment, CI failure, bot summary, and pasted note as a CLAIM until source evidence proves it; classify each ledger item (CONFIRMED, DISPROVED, PRE_EXISTING, or NEEDS_USER_DECISION) and never silently drop, defer, or mark items out of scope.
103499
+ - For async verification lanes, record the \`batch_id\`, keep doing ledger-safe non-dependent architect work, poll with \`collect_lane_results\` without \`wait\`, process settled lanes immediately, and use \`wait: true\` only when no independent work remains.
103392
103500
  - Patch only confirmed items plus the tests/docs they require; report closure status for every ledger item including disproved ones.
103393
103501
  - Do NOT resolve or mark GitHub review threads resolved unless the user explicitly instructs it.
103394
103502
  - Honor any free-text instructions that follow the closing bracket of the signal as additional scope, without dropping any ledger item.
@@ -106659,42 +106767,42 @@ var init_evidence_summary_integration = __esm(() => {
106659
106767
  var exports_pr_event_subscribers = {};
106660
106768
  __export(exports_pr_event_subscribers, {
106661
106769
  registerPrEventSubscribers: () => registerPrEventSubscribers,
106662
- _internals: () => _internals71
106770
+ _internals: () => _internals72
106663
106771
  });
106664
106772
  function registerPrEventSubscribers(options) {
106665
106773
  const { directory, config: config3 } = options;
106666
- const bus = _internals71.getGlobalEventBus();
106774
+ const bus = _internals72.getGlobalEventBus();
106667
106775
  const unsubscribers = [];
106668
106776
  for (const [eventType, configFlag] of Object.entries(EVENT_CONFIG_MAP)) {
106669
106777
  if (!config3[configFlag]) {
106670
- _internals71.log(`[pr-monitor] Skipping ${eventType} subscriber (disabled by config)`);
106778
+ _internals72.log(`[pr-monitor] Skipping ${eventType} subscriber (disabled by config)`);
106671
106779
  continue;
106672
106780
  }
106673
106781
  const listener = async (event) => {
106674
106782
  try {
106675
- await _internals71.handlePrEvent(event, directory, config3);
106783
+ await _internals72.handlePrEvent(event, directory, config3);
106676
106784
  } catch (err) {
106677
- _internals71.log(`[pr-monitor] Error handling ${eventType}`, {
106785
+ _internals72.log(`[pr-monitor] Error handling ${eventType}`, {
106678
106786
  error: err instanceof Error ? err.message : String(err)
106679
106787
  });
106680
106788
  }
106681
106789
  };
106682
106790
  const unsub = bus.subscribe(eventType, listener);
106683
106791
  unsubscribers.push(unsub);
106684
- _internals71.log(`[pr-monitor] Registered subscriber for ${eventType}`);
106792
+ _internals72.log(`[pr-monitor] Registered subscriber for ${eventType}`);
106685
106793
  }
106686
106794
  return () => {
106687
106795
  for (const unsub of unsubscribers) {
106688
106796
  unsub();
106689
106797
  }
106690
- _internals71.log("[pr-monitor] Unregistered all PR event subscribers");
106798
+ _internals72.log("[pr-monitor] Unregistered all PR event subscribers");
106691
106799
  };
106692
106800
  }
106693
106801
  async function handlePrEvent(event, directory, config3) {
106694
106802
  const payload = event.payload;
106695
106803
  if (!payload?.prNumber || !payload?.repoFullName)
106696
106804
  return;
106697
- const subscriptions = await _internals71.listActive(directory);
106805
+ const subscriptions = await _internals72.listActive(directory);
106698
106806
  const matching = subscriptions.filter((sub) => sub.prNumber === payload.prNumber && sub.repoFullName === payload.repoFullName);
106699
106807
  if (matching.length === 0)
106700
106808
  return;
@@ -106706,9 +106814,9 @@ async function handlePrEvent(event, directory, config3) {
106706
106814
  return `[MODE: PR_FEEDBACK pr="${safePrUrl}"]`;
106707
106815
  })() : null;
106708
106816
  for (const sub of matching) {
106709
- const session = _internals71.getAgentSession(sub.sessionID);
106817
+ const session = _internals72.getAgentSession(sub.sessionID);
106710
106818
  if (!session) {
106711
- _internals71.log(`[pr-monitor] Session ${sub.sessionID} not found — skipping advisory delivery`);
106819
+ _internals72.log(`[pr-monitor] Session ${sub.sessionID} not found — skipping advisory delivery`);
106712
106820
  continue;
106713
106821
  }
106714
106822
  session.pendingAdvisoryMessages ??= [];
@@ -106718,10 +106826,10 @@ async function handlePrEvent(event, directory, config3) {
106718
106826
  continue;
106719
106827
  }
106720
106828
  session.pendingAdvisoryMessages.push(message);
106721
- _internals71.log(`[pr-monitor] Delivered ${event.type} advisory to session ${sub.sessionID}`);
106829
+ _internals72.log(`[pr-monitor] Delivered ${event.type} advisory to session ${sub.sessionID}`);
106722
106830
  if (modeSignal) {
106723
106831
  session.pendingAdvisoryMessages.push(modeSignal);
106724
- _internals71.log(`[pr-monitor] Injected PR_FEEDBACK mode signal for session ${sub.sessionID} (${event.type})`);
106832
+ _internals72.log(`[pr-monitor] Injected PR_FEEDBACK mode signal for session ${sub.sessionID} (${event.type})`);
106725
106833
  }
106726
106834
  }
106727
106835
  }
@@ -106757,13 +106865,13 @@ function formatAdvisory(type, payload) {
106757
106865
  return null;
106758
106866
  }
106759
106867
  }
106760
- var _internals71, AUTO_PR_FEEDBACK_EVENTS, EVENT_CONFIG_MAP;
106868
+ var _internals72, AUTO_PR_FEEDBACK_EVENTS, EVENT_CONFIG_MAP;
106761
106869
  var init_pr_event_subscribers = __esm(() => {
106762
106870
  init_state2();
106763
106871
  init_utils();
106764
106872
  init_event_bus();
106765
106873
  init_pr_subscriptions();
106766
- _internals71 = {
106874
+ _internals72 = {
106767
106875
  handlePrEvent,
106768
106876
  getGlobalEventBus,
106769
106877
  listActive,
@@ -107750,7 +107858,7 @@ __export(exports_runtime, {
107750
107858
  getSupportedLanguages: () => getSupportedLanguages,
107751
107859
  getInitializedLanguages: () => getInitializedLanguages,
107752
107860
  clearParserCache: () => clearParserCache,
107753
- _internals: () => _internals80
107861
+ _internals: () => _internals81
107754
107862
  });
107755
107863
  import { existsSync as existsSync75, statSync as statSync24 } from "node:fs";
107756
107864
  import * as path130 from "node:path";
@@ -107762,10 +107870,10 @@ async function initTreeSitter() {
107762
107870
  const thisDir = path130.dirname(fileURLToPath4(import.meta.url));
107763
107871
  const isSource = thisDir.replace(/\\/g, "/").endsWith("/src/lang");
107764
107872
  if (isSource) {
107765
- await _internals80.parserInit();
107873
+ await _internals81.parserInit();
107766
107874
  } else {
107767
107875
  const grammarsDir = getGrammarsDirAbsolute();
107768
- await _internals80.parserInit({
107876
+ await _internals81.parserInit({
107769
107877
  locateFile(scriptName) {
107770
107878
  return path130.join(grammarsDir, scriptName);
107771
107879
  }
@@ -107880,12 +107988,12 @@ function getInitializedLanguages() {
107880
107988
  function getSupportedLanguages() {
107881
107989
  return Object.keys(LANGUAGE_WASM_MAP);
107882
107990
  }
107883
- var parserCache, inflightLoads, GRAMMAR_LOAD_TIMEOUT_MS = 1e4, initializedLanguages, treeSitterInitPromise = null, _internals80, LANGUAGE_WASM_MAP;
107991
+ var parserCache, inflightLoads, GRAMMAR_LOAD_TIMEOUT_MS = 1e4, initializedLanguages, treeSitterInitPromise = null, _internals81, LANGUAGE_WASM_MAP;
107884
107992
  var init_runtime = __esm(() => {
107885
107993
  parserCache = new Map;
107886
107994
  inflightLoads = new Map;
107887
107995
  initializedLanguages = new Set;
107888
- _internals80 = {
107996
+ _internals81 = {
107889
107997
  parserInit: TreeSitterParser.init
107890
107998
  };
107891
107999
  LANGUAGE_WASM_MAP = {
@@ -108608,7 +108716,7 @@ async function updateRetrievalOutcome(directory, phaseInfo, phaseSucceeded) {
108608
108716
  return data;
108609
108717
  });
108610
108718
  for (const id of shownIds) {
108611
- await _internals83.recordKnowledgeEvent(directory, {
108719
+ await _internals84.recordKnowledgeEvent(directory, {
108612
108720
  type: "outcome",
108613
108721
  knowledge_id: id,
108614
108722
  phase: phaseInfo,
@@ -108677,13 +108785,13 @@ function scoreDirectiveAgainstContext(entry, ctx) {
108677
108785
  score += 0.1;
108678
108786
  return { triggerHit, actionHit, agentHit, score: Math.min(1, score) };
108679
108787
  }
108680
- var JACCARD_THRESHOLD2 = 0.6, HIVE_TIER_BOOST = 0.05, DEFAULT_SAME_PROJECT_PENALTY = -0.05, QUARANTINED_STATUS = "quarantined", _internals83;
108788
+ var JACCARD_THRESHOLD2 = 0.6, HIVE_TIER_BOOST = 0.05, DEFAULT_SAME_PROJECT_PENALTY = -0.05, QUARANTINED_STATUS = "quarantined", _internals84;
108681
108789
  var init_knowledge_reader = __esm(() => {
108682
108790
  init_task_file();
108683
108791
  init_logger();
108684
108792
  init_knowledge_events();
108685
108793
  init_knowledge_store();
108686
- _internals83 = {
108794
+ _internals84 = {
108687
108795
  readMergedKnowledge,
108688
108796
  updateRetrievalOutcome,
108689
108797
  scoreDirectiveAgainstContext,
@@ -108983,9 +109091,9 @@ var init_search_knowledge = __esm(() => {
108983
109091
  var exports_knowledge_recall = {};
108984
109092
  __export(exports_knowledge_recall, {
108985
109093
  knowledge_recall: () => knowledge_recall,
108986
- _internals: () => _internals84
109094
+ _internals: () => _internals85
108987
109095
  });
108988
- var knowledge_recall, _internals84;
109096
+ var knowledge_recall, _internals85;
108989
109097
  var init_knowledge_recall = __esm(() => {
108990
109098
  init_zod();
108991
109099
  init_config();
@@ -109066,7 +109174,7 @@ var init_knowledge_recall = __esm(() => {
109066
109174
  return JSON.stringify(result);
109067
109175
  }
109068
109176
  });
109069
- _internals84 = {
109177
+ _internals85 = {
109070
109178
  knowledge_recall
109071
109179
  };
109072
109180
  });
@@ -109121,7 +109229,7 @@ __export(exports_curator_drift, {
109121
109229
  runDeterministicDriftCheck: () => runDeterministicDriftCheck,
109122
109230
  readPriorDriftReports: () => readPriorDriftReports,
109123
109231
  buildDriftInjectionText: () => buildDriftInjectionText,
109124
- _internals: () => _internals88
109232
+ _internals: () => _internals89
109125
109233
  });
109126
109234
  import * as fs87 from "node:fs";
109127
109235
  import * as path149 from "node:path";
@@ -109170,7 +109278,7 @@ async function runDeterministicDriftCheck(directory, phase, curatorResult, confi
109170
109278
  try {
109171
109279
  const planMd = await readSwarmFileAsync(directory, "plan.md");
109172
109280
  const specMd = readEffectiveSpecSync(directory)?.content ?? null;
109173
- const priorReports = await _internals88.readPriorDriftReports(directory);
109281
+ const priorReports = await _internals89.readPriorDriftReports(directory);
109174
109282
  const complianceCount = curatorResult.compliance.length;
109175
109283
  const warningCompliance = curatorResult.compliance.filter((obs) => obs.severity === "warning");
109176
109284
  let alignment = "ALIGNED";
@@ -109233,7 +109341,7 @@ async function runDeterministicDriftCheck(directory, phase, curatorResult, confi
109233
109341
  scope_additions: [],
109234
109342
  injection_summary: injectionSummary
109235
109343
  };
109236
- const reportPath = await _internals88.writeDriftReport(directory, report);
109344
+ const reportPath = await _internals89.writeDriftReport(directory, report);
109237
109345
  getGlobalEventBus().publish("curator.drift.completed", {
109238
109346
  phase,
109239
109347
  alignment,
@@ -109296,13 +109404,13 @@ function buildDriftInjectionText(report, maxChars) {
109296
109404
  }
109297
109405
  return text.slice(0, maxChars);
109298
109406
  }
109299
- var DRIFT_REPORT_PREFIX = "drift-report-phase-", _internals88;
109407
+ var DRIFT_REPORT_PREFIX = "drift-report-phase-", _internals89;
109300
109408
  var init_curator_drift = __esm(() => {
109301
109409
  init_event_bus();
109302
109410
  init_effective_spec();
109303
109411
  init_logger();
109304
109412
  init_utils2();
109305
- _internals88 = {
109413
+ _internals89 = {
109306
109414
  readPriorDriftReports,
109307
109415
  writeDriftReport,
109308
109416
  runDeterministicDriftCheck,
@@ -109314,7 +109422,7 @@ var init_curator_drift = __esm(() => {
109314
109422
  var exports_design_doc_drift = {};
109315
109423
  __export(exports_design_doc_drift, {
109316
109424
  runDesignDocDriftCheck: () => runDesignDocDriftCheck,
109317
- _internals: () => _internals118
109425
+ _internals: () => _internals119
109318
109426
  });
109319
109427
  import * as fs124 from "node:fs";
109320
109428
  import * as path195 from "node:path";
@@ -109447,7 +109555,7 @@ async function runDesignDocDriftCheck(directory, phase, outDir) {
109447
109555
  return null;
109448
109556
  }
109449
109557
  }
109450
- var DOC_DRIFT_REPORT_PREFIX = "doc-drift-phase-", MAX_TRACEABILITY_BYTES, DESIGN_DOC_FILES, TRACEABILITY_REL, _internals118;
109558
+ var DOC_DRIFT_REPORT_PREFIX = "doc-drift-phase-", MAX_TRACEABILITY_BYTES, DESIGN_DOC_FILES, TRACEABILITY_REL, _internals119;
109451
109559
  var init_design_doc_drift = __esm(() => {
109452
109560
  init_event_bus();
109453
109561
  init_effective_spec();
@@ -109462,7 +109570,7 @@ var init_design_doc_drift = __esm(() => {
109462
109570
  "idiom-notes": path195.join("reference", "idiom-notes.md")
109463
109571
  };
109464
109572
  TRACEABILITY_REL = path195.join("reference", "traceability.json");
109465
- _internals118 = {
109573
+ _internals119 = {
109466
109574
  mtimeMsOrNull,
109467
109575
  resolveAnchorWithin,
109468
109576
  DESIGN_DOC_FILES
@@ -109473,7 +109581,7 @@ var init_design_doc_drift = __esm(() => {
109473
109581
  var exports_project_context = {};
109474
109582
  __export(exports_project_context, {
109475
109583
  buildProjectContext: () => buildProjectContext,
109476
- _internals: () => _internals136,
109584
+ _internals: () => _internals137,
109477
109585
  LANG_BACKEND_DETECTION_TIMEOUT_MS: () => LANG_BACKEND_DETECTION_TIMEOUT_MS
109478
109586
  });
109479
109587
  import * as fs148 from "node:fs";
@@ -109557,7 +109665,7 @@ function selectLintCommand(backend, directory) {
109557
109665
  return null;
109558
109666
  }
109559
109667
  async function buildProjectContext(directory) {
109560
- const backend = await _internals136.pickBackend(directory);
109668
+ const backend = await _internals137.pickBackend(directory);
109561
109669
  if (!backend)
109562
109670
  return null;
109563
109671
  const ctx = emptyProjectContext();
@@ -109596,17 +109704,17 @@ async function buildProjectContext(directory) {
109596
109704
  if (backend.prompts.reviewerChecklist.length > 0) {
109597
109705
  ctx.REVIEWER_CHECKLIST = bulletList(backend.prompts.reviewerChecklist);
109598
109706
  }
109599
- const profiles = _internals136.pickedProfiles(directory);
109707
+ const profiles = _internals137.pickedProfiles(directory);
109600
109708
  if (profiles.length > 1) {
109601
109709
  ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES = profiles.slice(1).map((p) => p.id).join(", ");
109602
109710
  }
109603
109711
  return ctx;
109604
109712
  }
109605
- var LANG_BACKEND_DETECTION_TIMEOUT_MS = 300, _internals136;
109713
+ var LANG_BACKEND_DETECTION_TIMEOUT_MS = 300, _internals137;
109606
109714
  var init_project_context = __esm(() => {
109607
109715
  init_dispatch();
109608
109716
  init_framework_detector();
109609
- _internals136 = {
109717
+ _internals137 = {
109610
109718
  pickBackend,
109611
109719
  pickedProfiles
109612
109720
  };
@@ -110030,11 +110138,11 @@ async function ghExecAsync(args2, cwd) {
110030
110138
  });
110031
110139
  });
110032
110140
  }
110033
- var _internals72 = { ghExec, ghExecAsync, spawnSyncWithTransientRetry };
110141
+ var _internals73 = { ghExec, ghExecAsync, spawnSyncWithTransientRetry };
110034
110142
  async function getPRStatus(prNumber, repoFullName, cwd) {
110035
110143
  let stdout;
110036
110144
  try {
110037
- stdout = await _internals72.ghExecAsync([
110145
+ stdout = await _internals73.ghExecAsync([
110038
110146
  "pr",
110039
110147
  "view",
110040
110148
  String(prNumber),
@@ -110055,13 +110163,13 @@ async function getPRComments(prNumber, repoFullName, cwd, since) {
110055
110163
  let issueComments;
110056
110164
  let reviewComments;
110057
110165
  try {
110058
- const issueRaw = await _internals72.ghExecAsync(["api", issueCommentsPath], cwd);
110166
+ const issueRaw = await _internals73.ghExecAsync(["api", issueCommentsPath], cwd);
110059
110167
  issueComments = JSON.parse(issueRaw);
110060
110168
  } catch (err) {
110061
110169
  throw new Error(`Failed to fetch issue comments for ${repoFullName}#${prNumber}: ${err instanceof Error ? err.message : String(err)}`);
110062
110170
  }
110063
110171
  try {
110064
- const reviewRaw = await _internals72.ghExecAsync(["api", reviewCommentsPath], cwd);
110172
+ const reviewRaw = await _internals73.ghExecAsync(["api", reviewCommentsPath], cwd);
110065
110173
  reviewComments = JSON.parse(reviewRaw);
110066
110174
  } catch (err) {
110067
110175
  throw new Error(`Failed to fetch review comments for ${repoFullName}#${prNumber}: ${err instanceof Error ? err.message : String(err)}`);
@@ -110088,7 +110196,7 @@ async function getPRComments(prNumber, repoFullName, cwd, since) {
110088
110196
  async function getMergeState(prNumber, repoFullName, cwd) {
110089
110197
  let stdout;
110090
110198
  try {
110091
- stdout = await _internals72.ghExecAsync([
110199
+ stdout = await _internals73.ghExecAsync([
110092
110200
  "pr",
110093
110201
  "view",
110094
110202
  String(prNumber),
@@ -110110,7 +110218,7 @@ async function getMergeState(prNumber, repoFullName, cwd) {
110110
110218
  async function getPRReviewState(prNumber, repoFullName, cwd) {
110111
110219
  let stdout;
110112
110220
  try {
110113
- stdout = await _internals72.ghExecAsync([
110221
+ stdout = await _internals73.ghExecAsync([
110114
110222
  "pr",
110115
110223
  "view",
110116
110224
  String(prNumber),
@@ -110218,7 +110326,7 @@ class PrMonitorWorker {
110218
110326
  async executePollCycle() {
110219
110327
  log("[PrMonitorWorker] Poll cycle starting");
110220
110328
  try {
110221
- const activeSubs = await _internals73.listActive(this.directory);
110329
+ const activeSubs = await _internals74.listActive(this.directory);
110222
110330
  if (activeSubs.length === 0) {
110223
110331
  log("[PrMonitorWorker] No active subscriptions");
110224
110332
  await this.runSweep();
@@ -110290,10 +110398,10 @@ class PrMonitorWorker {
110290
110398
  }
110291
110399
  try {
110292
110400
  const [statusResult, commentsResult, mergeResult, reviewResult] = await Promise.all([
110293
- _internals73.getPRStatus(sub.prNumber, sub.repoFullName, this.directory),
110294
- _internals73.getPRComments(sub.prNumber, sub.repoFullName, this.directory),
110295
- _internals73.getMergeState(sub.prNumber, sub.repoFullName, this.directory),
110296
- _internals73.getPRReviewState(sub.prNumber, sub.repoFullName, this.directory)
110401
+ _internals74.getPRStatus(sub.prNumber, sub.repoFullName, this.directory),
110402
+ _internals74.getPRComments(sub.prNumber, sub.repoFullName, this.directory),
110403
+ _internals74.getMergeState(sub.prNumber, sub.repoFullName, this.directory),
110404
+ _internals74.getPRReviewState(sub.prNumber, sub.repoFullName, this.directory)
110297
110405
  ]);
110298
110406
  if (isTimedOut?.()) {
110299
110407
  log("[PrMonitorWorker] Skipping late result — poll already timed out", {
@@ -110310,7 +110418,7 @@ class PrMonitorWorker {
110310
110418
  await this.applyChanges(sub, changes, isTimedOut);
110311
110419
  if (!isTimedOut?.()) {
110312
110420
  this.circuitBreakerMap.delete(correlationId);
110313
- await _internals73.updateSnapshot(this.directory, correlationId, {
110421
+ await _internals74.updateSnapshot(this.directory, correlationId, {
110314
110422
  errorCount: 0,
110315
110423
  lastCheckedAt: Date.now()
110316
110424
  });
@@ -110511,7 +110619,7 @@ class PrMonitorWorker {
110511
110619
  this.mergedOrClosedKeys.add(`${sub.repoFullName}::${sub.prNumber}`);
110512
110620
  }
110513
110621
  if (changes.isMerged && this.config.auto_unsubscribe_on_merge) {
110514
- await _internals73.unsubscribe(this.directory, sub.correlationId);
110622
+ await _internals74.unsubscribe(this.directory, sub.correlationId);
110515
110623
  this.reviewStateMap.delete(sub.correlationId);
110516
110624
  this.circuitBreakerMap.delete(sub.correlationId);
110517
110625
  log("[PrMonitorWorker] Auto-unsubscribed merged PR", {
@@ -110520,7 +110628,7 @@ class PrMonitorWorker {
110520
110628
  return;
110521
110629
  }
110522
110630
  if (changes.isClosed && this.config.auto_unsubscribe_on_close) {
110523
- await _internals73.unsubscribe(this.directory, sub.correlationId);
110631
+ await _internals74.unsubscribe(this.directory, sub.correlationId);
110524
110632
  this.reviewStateMap.delete(sub.correlationId);
110525
110633
  this.circuitBreakerMap.delete(sub.correlationId);
110526
110634
  log("[PrMonitorWorker] Auto-unsubscribed closed PR", {
@@ -110532,7 +110640,7 @@ class PrMonitorWorker {
110532
110640
  log("[PrMonitorWorker] Skipping snapshot update — poll timed out before write", { correlationId: sub.correlationId });
110533
110641
  return;
110534
110642
  }
110535
- await _internals73.updateSnapshot(this.directory, sub.correlationId, changes.snapshotUpdates);
110643
+ await _internals74.updateSnapshot(this.directory, sub.correlationId, changes.snapshotUpdates);
110536
110644
  }
110537
110645
  async handlePollError(sub, error93) {
110538
110646
  const correlationId = sub.correlationId;
@@ -110542,7 +110650,7 @@ class PrMonitorWorker {
110542
110650
  cooldownLevel: 0
110543
110651
  };
110544
110652
  cb.errorCount++;
110545
- await _internals73.updateSnapshot(this.directory, correlationId, {
110653
+ await _internals74.updateSnapshot(this.directory, correlationId, {
110546
110654
  errorCount: cb.errorCount,
110547
110655
  lastCheckedAt: Date.now()
110548
110656
  });
@@ -110581,7 +110689,7 @@ class PrMonitorWorker {
110581
110689
  source: "pr-monitor-worker"
110582
110690
  };
110583
110691
  try {
110584
- const bus = _internals73.getGlobalEventBus();
110692
+ const bus = _internals74.getGlobalEventBus();
110585
110693
  await bus.publish(type, payload, "pr-monitor-worker");
110586
110694
  } catch (err) {
110587
110695
  log("[PrMonitorWorker] Event publish failed", {
@@ -110599,7 +110707,7 @@ class PrMonitorWorker {
110599
110707
  if (this.config.cleanup_ttl_days > 0) {
110600
110708
  try {
110601
110709
  const keysToPass = this.mergedOrClosedKeys.size > 0 ? this.mergedOrClosedKeys : undefined;
110602
- await _internals73.sweepStale(this.directory, this.config.cleanup_ttl_days, keysToPass);
110710
+ await _internals74.sweepStale(this.directory, this.config.cleanup_ttl_days, keysToPass);
110603
110711
  } catch (err) {
110604
110712
  log("[PrMonitorWorker] Sweep failed", {
110605
110713
  error: err instanceof Error ? err.message : String(err)
@@ -110623,7 +110731,7 @@ class PrMonitorWorker {
110623
110731
  }
110624
110732
  }
110625
110733
  }
110626
- var _internals73 = {
110734
+ var _internals74 = {
110627
110735
  getPRStatus,
110628
110736
  getPRComments,
110629
110737
  getMergeState,
@@ -111094,7 +111202,7 @@ import * as path121 from "node:path";
111094
111202
  import * as crypto9 from "node:crypto";
111095
111203
  import * as fs65 from "node:fs";
111096
111204
  import * as path120 from "node:path";
111097
- var _internals74 = {
111205
+ var _internals75 = {
111098
111206
  readFileSync: fs65.readFileSync,
111099
111207
  writeFileSync: fs65.writeFileSync,
111100
111208
  mkdirSync: fs65.mkdirSync,
@@ -111104,7 +111212,7 @@ var _internals74 = {
111104
111212
  createHash: crypto9.createHash.bind(crypto9)
111105
111213
  };
111106
111214
  function computeContentHash(content) {
111107
- return _internals74.createHash("sha256").update(content, "utf-8").digest("hex");
111215
+ return _internals75.createHash("sha256").update(content, "utf-8").digest("hex");
111108
111216
  }
111109
111217
  function createEmptyContextMap() {
111110
111218
  return {
@@ -111119,10 +111227,10 @@ function createEmptyContextMap() {
111119
111227
  function loadContextMap(directory) {
111120
111228
  const filePath = path120.join(directory, ".swarm", "context-map.json");
111121
111229
  try {
111122
- if (!_internals74.existsSync(filePath)) {
111230
+ if (!_internals75.existsSync(filePath)) {
111123
111231
  return null;
111124
111232
  }
111125
- const raw = _internals74.readFileSync(filePath, "utf-8");
111233
+ const raw = _internals75.readFileSync(filePath, "utf-8");
111126
111234
  const parsed = JSON.parse(raw);
111127
111235
  if (typeof parsed !== "object" || parsed === null || parsed.schema_version !== 1) {
111128
111236
  return null;
@@ -111136,14 +111244,14 @@ function saveContextMap(map3, directory) {
111136
111244
  const swarmDir = path120.join(directory, ".swarm");
111137
111245
  const tmpPath = path120.join(swarmDir, "context-map.tmp");
111138
111246
  const finalPath = path120.join(swarmDir, "context-map.json");
111139
- _internals74.mkdirSync(swarmDir, { recursive: true });
111247
+ _internals75.mkdirSync(swarmDir, { recursive: true });
111140
111248
  const updated = {
111141
111249
  ...map3,
111142
111250
  generated_at: new Date().toISOString()
111143
111251
  };
111144
111252
  const json3 = JSON.stringify(updated, null, 2);
111145
- _internals74.writeFileSync(tmpPath, json3, "utf-8");
111146
- _internals74.renameSync(tmpPath, finalPath);
111253
+ _internals75.writeFileSync(tmpPath, json3, "utf-8");
111254
+ _internals75.renameSync(tmpPath, finalPath);
111147
111255
  }
111148
111256
  function appendTaskHistory(map3, summary) {
111149
111257
  return {
@@ -111309,10 +111417,10 @@ function deriveFinalStatus(params) {
111309
111417
  }
111310
111418
  function readFileContent(absolutePath) {
111311
111419
  try {
111312
- if (!_internals75.existsSync(absolutePath)) {
111420
+ if (!_internals76.existsSync(absolutePath)) {
111313
111421
  return null;
111314
111422
  }
111315
- return _internals75.readFileSync(absolutePath, "utf-8");
111423
+ return _internals76.readFileSync(absolutePath, "utf-8");
111316
111424
  } catch {
111317
111425
  return null;
111318
111426
  }
@@ -111322,9 +111430,9 @@ function refreshFileEntry(relativePath, absolutePath, existingEntry) {
111322
111430
  if (content === null) {
111323
111431
  return null;
111324
111432
  }
111325
- return _internals75.extractFileSummary(relativePath, content, absolutePath, existingEntry);
111433
+ return _internals76.extractFileSummary(relativePath, content, absolutePath, existingEntry);
111326
111434
  }
111327
- var _internals75 = {
111435
+ var _internals76 = {
111328
111436
  loadContextMap,
111329
111437
  saveContextMap,
111330
111438
  createEmptyContextMap,
@@ -111343,10 +111451,10 @@ function extractEvidenceFindings(taskId, directory) {
111343
111451
  };
111344
111452
  try {
111345
111453
  const evidenceDir = path122.join(directory, ".swarm", "evidence", taskId);
111346
- if (!_internals75.existsSync(evidenceDir)) {
111454
+ if (!_internals76.existsSync(evidenceDir)) {
111347
111455
  return result;
111348
111456
  }
111349
- const evidenceFiles = _internals75.readdirSync(evidenceDir);
111457
+ const evidenceFiles = _internals76.readdirSync(evidenceDir);
111350
111458
  const targetFiles = [
111351
111459
  "evidence.json",
111352
111460
  "reviewer.json",
@@ -111438,20 +111546,20 @@ function extractEvidenceFindings(taskId, directory) {
111438
111546
  }
111439
111547
  function updateContextMapAfterAgent(params) {
111440
111548
  try {
111441
- let map3 = _internals75.loadContextMap(params.directory);
111549
+ let map3 = _internals76.loadContextMap(params.directory);
111442
111550
  if (map3 === null) {
111443
- map3 = _internals75.createEmptyContextMap();
111551
+ map3 = _internals76.createEmptyContextMap();
111444
111552
  }
111445
111553
  const root = path122.resolve(params.directory);
111446
111554
  const updatedFiles = {
111447
111555
  ...map3.files
111448
111556
  };
111449
111557
  const validFiles = [];
111450
- const realRoot = _internals75.realpathSync(root);
111558
+ const realRoot = _internals76.realpathSync(root);
111451
111559
  for (const filePath of params.files_touched) {
111452
111560
  try {
111453
111561
  const resolved = path122.resolve(root, filePath);
111454
- const realResolved = _internals75.realpathSync(resolved);
111562
+ const realResolved = _internals76.realpathSync(resolved);
111455
111563
  const relative20 = path122.relative(realRoot, realResolved);
111456
111564
  if (relative20.startsWith("..") || path122.isAbsolute(relative20)) {
111457
111565
  continue;
@@ -111489,7 +111597,7 @@ function updateContextMapAfterAgent(params) {
111489
111597
  reviewer_findings: reviewerFindings.length > 0 ? reviewerFindings : undefined,
111490
111598
  final_status: mergedRejectionReasons.length > 0 ? "rejected" : deriveFinalStatus(params)
111491
111599
  };
111492
- map3 = _internals75.appendTaskHistory(map3, taskSummary);
111600
+ map3 = _internals76.appendTaskHistory(map3, taskSummary);
111493
111601
  if (params.decisions) {
111494
111602
  for (const entry of params.decisions) {
111495
111603
  const decision = {
@@ -111499,17 +111607,17 @@ function updateContextMapAfterAgent(params) {
111499
111607
  timestamp: new Date().toISOString(),
111500
111608
  task_id: params.task_id
111501
111609
  };
111502
- map3 = _internals75.appendDecision(map3, decision);
111610
+ map3 = _internals76.appendDecision(map3, decision);
111503
111611
  }
111504
111612
  }
111505
- _internals75.saveContextMap(map3, params.directory);
111613
+ _internals76.saveContextMap(map3, params.directory);
111506
111614
  return map3;
111507
111615
  } catch {
111508
111616
  try {
111509
- const fallback = _internals75.loadContextMap(params.directory) ?? _internals75.createEmptyContextMap();
111617
+ const fallback = _internals76.loadContextMap(params.directory) ?? _internals76.createEmptyContextMap();
111510
111618
  return fallback;
111511
111619
  } catch {
111512
- return _internals75.createEmptyContextMap();
111620
+ return _internals76.createEmptyContextMap();
111513
111621
  }
111514
111622
  }
111515
111623
  }
@@ -112840,7 +112948,7 @@ import * as path124 from "node:path";
112840
112948
  function estimateTokens3(content) {
112841
112949
  return Math.max(1, estimateTokens2(content));
112842
112950
  }
112843
- var _internals76 = {
112951
+ var _internals77 = {
112844
112952
  loadContextMap,
112845
112953
  createEmptyContextMap,
112846
112954
  computeContentHash,
@@ -112908,14 +113016,14 @@ function buildReadPolicy(files, map3, directory, invalidateOnHashChange = true,
112908
113016
  const absolutePath = path124.join(directory, filePath);
112909
113017
  let currentContent;
112910
113018
  try {
112911
- if (_internals76.existsSync(absolutePath)) {
112912
- currentContent = _internals76.readFileSync(absolutePath, "utf-8");
113019
+ if (_internals77.existsSync(absolutePath)) {
113020
+ currentContent = _internals77.readFileSync(absolutePath, "utf-8");
112913
113021
  }
112914
113022
  } catch {}
112915
113023
  if (contentCache !== undefined) {
112916
113024
  contentCache.set(filePath, currentContent);
112917
113025
  }
112918
- if (currentContent === undefined || invalidateOnHashChange && _internals76.isFileStale(entry, currentContent)) {
113026
+ if (currentContent === undefined || invalidateOnHashChange && _internals77.isFileStale(entry, currentContent)) {
112919
113027
  policy.push({
112920
113028
  file_path: filePath,
112921
113029
  trust_summary: false,
@@ -112990,7 +113098,7 @@ function pruneCapsuleContent(sections, tokenEstimate, maxTokens, estimateFn) {
112990
113098
  function buildCapsule(params) {
112991
113099
  const { task_id, agent_role, delegation_reason, directory } = params;
112992
113100
  const generatedAt = new Date().toISOString();
112993
- const map3 = _internals76.loadContextMap(directory) ?? _internals76.createEmptyContextMap();
113101
+ const map3 = _internals77.loadContextMap(directory) ?? _internals77.createEmptyContextMap();
112994
113102
  let profile = DEFAULT_ROLE_PROFILES[agent_role];
112995
113103
  if (params.mode === "conservative") {
112996
113104
  profile = { ...profile, max_files: Math.ceil(profile.max_files * 1.5) };
@@ -113019,7 +113127,7 @@ function buildCapsule(params) {
113019
113127
  const shouldCheckStaleness = params.invalidate_on_hash_change !== false;
113020
113128
  if (shouldCheckStaleness) {
113021
113129
  const currentContent = contentCache.get(filePath);
113022
- if (currentContent === undefined || _internals76.isFileStale(entry, currentContent)) {
113130
+ if (currentContent === undefined || _internals77.isFileStale(entry, currentContent)) {
113023
113131
  staleEntries++;
113024
113132
  fileSummaries.push(`- ${filePath} — ${entry.purpose || "No summary available"} (stale)`);
113025
113133
  } else {
@@ -113061,11 +113169,11 @@ function buildCapsule(params) {
113061
113169
  }
113062
113170
  const content = sections.join(`
113063
113171
  `);
113064
- let tokenEstimate = _internals76.estimateTokens(content);
113172
+ let tokenEstimate = _internals77.estimateTokens(content);
113065
113173
  const maxCapsuleTokens = params.max_capsule_tokens ?? 2000;
113066
113174
  let prunedContent = content;
113067
113175
  if (tokenEstimate > maxCapsuleTokens) {
113068
- const { prunedSections, prunedTokenEstimate } = pruneCapsuleContent(sections, tokenEstimate, maxCapsuleTokens, _internals76.estimateTokens);
113176
+ const { prunedSections, prunedTokenEstimate } = pruneCapsuleContent(sections, tokenEstimate, maxCapsuleTokens, _internals77.estimateTokens);
113069
113177
  prunedContent = prunedSections.join(`
113070
113178
  `);
113071
113179
  tokenEstimate = prunedTokenEstimate;
@@ -113101,7 +113209,7 @@ function buildCapsule(params) {
113101
113209
  // src/context-map/capsule-persistence.ts
113102
113210
  import * as fs71 from "node:fs";
113103
113211
  import * as path125 from "node:path";
113104
- var _internals77 = {
113212
+ var _internals78 = {
113105
113213
  writeFileSync: fs71.writeFileSync,
113106
113214
  readFileSync: fs71.readFileSync,
113107
113215
  existsSync: fs71.existsSync,
@@ -113137,10 +113245,10 @@ function saveCapsule(capsule, directory) {
113137
113245
  const capsulesDir = path125.join(directory, ".swarm", "capsules");
113138
113246
  const finalPath = capsulePath(capsule.task_id, directory);
113139
113247
  const tmpPath = path125.join(capsulesDir, `capsule-${capsule.task_id}.tmp`);
113140
- _internals77.mkdirSync(capsulesDir, { recursive: true });
113248
+ _internals78.mkdirSync(capsulesDir, { recursive: true });
113141
113249
  const json3 = JSON.stringify(capsule, null, 2);
113142
- _internals77.writeFileSync(tmpPath, json3, "utf-8");
113143
- _internals77.renameSync(tmpPath, finalPath);
113250
+ _internals78.writeFileSync(tmpPath, json3, "utf-8");
113251
+ _internals78.renameSync(tmpPath, finalPath);
113144
113252
  return {
113145
113253
  success: true,
113146
113254
  capsule_path: finalPath,
@@ -113168,7 +113276,7 @@ function saveCapsule(capsule, directory) {
113168
113276
  // src/context-map/telemetry.ts
113169
113277
  import * as fs72 from "node:fs";
113170
113278
  import * as path126 from "node:path";
113171
- var _internals78 = {
113279
+ var _internals79 = {
113172
113280
  appendFileSync: fs72.appendFileSync,
113173
113281
  readFileSync: fs72.readFileSync,
113174
113282
  existsSync: fs72.existsSync,
@@ -113181,10 +113289,10 @@ function recordTelemetry(entry, directory) {
113181
113289
  const filePath = telemetryFilePath(directory);
113182
113290
  const swarmDir = path126.join(directory, ".swarm");
113183
113291
  try {
113184
- _internals78.mkdirSync(swarmDir, { recursive: true });
113292
+ _internals79.mkdirSync(swarmDir, { recursive: true });
113185
113293
  const line = `${JSON.stringify(entry)}
113186
113294
  `;
113187
- _internals78.appendFileSync(filePath, line, "utf-8");
113295
+ _internals79.appendFileSync(filePath, line, "utf-8");
113188
113296
  return true;
113189
113297
  } catch {
113190
113298
  return false;
@@ -113226,7 +113334,7 @@ function extractTaskGoal(taskId, directory) {
113226
113334
  return "";
113227
113335
  }
113228
113336
  }
113229
- var _internals79 = {
113337
+ var _internals80 = {
113230
113338
  buildCapsule,
113231
113339
  recordTelemetry,
113232
113340
  saveCapsule,
@@ -113294,21 +113402,21 @@ async function injectCapsule(input, output, config3, directory) {
113294
113402
  const sessionID = input.sessionID;
113295
113403
  if (!sessionID)
113296
113404
  return;
113297
- const agentName = _internals79.getActiveAgent(sessionID);
113405
+ const agentName = _internals80.getActiveAgent(sessionID);
113298
113406
  if (!agentName)
113299
113407
  return;
113300
113408
  const role = extractCapsuleRole(agentName);
113301
113409
  if (!role)
113302
113410
  return;
113303
- const taskId = _internals79.getCurrentTaskId(sessionID);
113411
+ const taskId = _internals80.getCurrentTaskId(sessionID);
113304
113412
  const effectiveTaskId = taskId ?? "unknown";
113305
- const files = _internals79.readScopeFile(effectiveTaskId, directory);
113413
+ const files = _internals80.readScopeFile(effectiveTaskId, directory);
113306
113414
  if (files.length === 0)
113307
113415
  return;
113308
113416
  const maxTokens = config3.context_map?.max_capsule_tokens;
113309
- const delegationReason = _internals79.resolveCapsuleDelegationReason(_internals79.getSession(sessionID), role, effectiveTaskId);
113310
- const taskGoal = _internals79.extractTaskGoal(effectiveTaskId, directory);
113311
- const { capsule, metadata } = _internals79.buildCapsule({
113417
+ const delegationReason = _internals80.resolveCapsuleDelegationReason(_internals80.getSession(sessionID), role, effectiveTaskId);
113418
+ const taskGoal = _internals80.extractTaskGoal(effectiveTaskId, directory);
113419
+ const { capsule, metadata } = _internals80.buildCapsule({
113312
113420
  task_id: effectiveTaskId,
113313
113421
  agent_role: role,
113314
113422
  delegation_reason: delegationReason,
@@ -113324,7 +113432,7 @@ async function injectCapsule(input, output, config3, directory) {
113324
113432
  return;
113325
113433
  output.system.push(capsule.content);
113326
113434
  try {
113327
- _internals79.saveCapsule(capsule, directory);
113435
+ _internals80.saveCapsule(capsule, directory);
113328
113436
  } catch {}
113329
113437
  const telemetryEntry = {
113330
113438
  timestamp: new Date().toISOString(),
@@ -113340,7 +113448,7 @@ async function injectCapsule(input, output, config3, directory) {
113340
113448
  success: metadata.success
113341
113449
  };
113342
113450
  try {
113343
- _internals79.recordTelemetry(telemetryEntry, directory);
113451
+ _internals80.recordTelemetry(telemetryEntry, directory);
113344
113452
  } catch {}
113345
113453
  }
113346
113454
 
@@ -116432,7 +116540,7 @@ function validateGraphEdge(edge) {
116432
116540
  }
116433
116541
 
116434
116542
  // src/tools/repo-graph/builder.ts
116435
- var _internals81 = {
116543
+ var _internals82 = {
116436
116544
  safeRealpathSync,
116437
116545
  extractTSSymbols,
116438
116546
  extractPythonSymbols,
@@ -116521,12 +116629,12 @@ function resolveModuleSpecifier(workspaceRoot, sourceFile, specifier) {
116521
116629
  if (specifier.startsWith(".")) {
116522
116630
  const sourceDir = path134.dirname(sourceFile);
116523
116631
  let resolved = path134.resolve(sourceDir, specifier);
116524
- const initialRealResolved = _internals81.safeRealpathSync(resolved, resolved);
116632
+ const initialRealResolved = _internals82.safeRealpathSync(resolved, resolved);
116525
116633
  if (initialRealResolved === null) {
116526
116634
  return null;
116527
116635
  }
116528
116636
  let realResolved = initialRealResolved;
116529
- const realRoot = _internals81.safeRealpathSync(workspaceRoot, path134.normalize(workspaceRoot));
116637
+ const realRoot = _internals82.safeRealpathSync(workspaceRoot, path134.normalize(workspaceRoot));
116530
116638
  if (realRoot === null) {
116531
116639
  return null;
116532
116640
  }
@@ -116550,7 +116658,7 @@ function resolveModuleSpecifier(workspaceRoot, sourceFile, specifier) {
116550
116658
  }
116551
116659
  }
116552
116660
  if (found) {
116553
- const foundRealPath = _internals81.safeRealpathSync(found, found);
116661
+ const foundRealPath = _internals82.safeRealpathSync(found, found);
116554
116662
  if (foundRealPath === null) {
116555
116663
  return null;
116556
116664
  }
@@ -116931,7 +117039,7 @@ async function scanFileAsync(filePath, absoluteRoot, maxFileSize) {
116931
117039
  return { node: null, edges: [], symbolEdges: [] };
116932
117040
  }
116933
117041
  const grammarId = getLanguage(filePath);
116934
- const facts = await _internals81.extractFileSymbols(grammarId, content);
117042
+ const facts = await _internals82.extractFileSymbols(grammarId, content);
116935
117043
  if (facts === null) {
116936
117044
  const moduleName2 = toModuleName(filePath, absoluteRoot);
116937
117045
  return {
@@ -116942,7 +117050,7 @@ async function scanFileAsync(filePath, absoluteRoot, maxFileSize) {
116942
117050
  imports: [],
116943
117051
  language: grammarId,
116944
117052
  mtime: fileStats.mtime.toISOString(),
116945
- ontology: _internals81.extractFileOntology({
117053
+ ontology: _internals82.extractFileOntology({
116946
117054
  moduleName: moduleName2,
116947
117055
  filePath,
116948
117056
  content,
@@ -116975,7 +117083,7 @@ async function scanFileAsync(filePath, absoluteRoot, maxFileSize) {
116975
117083
  imports,
116976
117084
  language,
116977
117085
  mtime: fileStats.mtime.toISOString(),
116978
- ontology: _internals81.extractFileOntology({
117086
+ ontology: _internals82.extractFileOntology({
116979
117087
  moduleName,
116980
117088
  filePath,
116981
117089
  content,
@@ -117848,7 +117956,7 @@ import * as fsPromises6 from "node:fs/promises";
117848
117956
  import * as path137 from "node:path";
117849
117957
  var WINDOWS_RENAME_MAX_RETRIES2 = 5;
117850
117958
  var WINDOWS_RENAME_RETRY_DELAY_MS2 = 100;
117851
- var _internals82 = {
117959
+ var _internals83 = {
117852
117960
  safeRealpathSync,
117853
117961
  fsRename: fsPromises6.rename.bind(fsPromises6),
117854
117962
  retryDelayMs: WINDOWS_RENAME_RETRY_DELAY_MS2
@@ -118003,12 +118111,12 @@ async function saveGraph(workspace, graph, options) {
118003
118111
  throw new Error("Graph must have edges array");
118004
118112
  }
118005
118113
  const normalizedWorkspace = path137.normalize(workspace);
118006
- const realWorkspace = _internals82.safeRealpathSync(workspace, normalizedWorkspace);
118114
+ const realWorkspace = _internals83.safeRealpathSync(workspace, normalizedWorkspace);
118007
118115
  if (realWorkspace === null) {
118008
118116
  throw new Error(`Workspace realpath security check failed (non-ENOENT): ${workspace}`);
118009
118117
  }
118010
118118
  const normalizedGraphRoot = path137.normalize(graph.workspaceRoot);
118011
- const realGraphRoot = _internals82.safeRealpathSync(graph.workspaceRoot, normalizedGraphRoot);
118119
+ const realGraphRoot = _internals83.safeRealpathSync(graph.workspaceRoot, normalizedGraphRoot);
118012
118120
  if (realGraphRoot === null) {
118013
118121
  throw new Error(`Graph workspaceRoot realpath security check failed (non-ENOENT): ${graph.workspaceRoot}`);
118014
118122
  }
@@ -118046,7 +118154,7 @@ async function saveGraph(workspace, graph, options) {
118046
118154
  } else {
118047
118155
  for (let attempt = 0;attempt < WINDOWS_RENAME_MAX_RETRIES2; attempt++) {
118048
118156
  try {
118049
- await _internals82.fsRename(tempPath, graphPath);
118157
+ await _internals83.fsRename(tempPath, graphPath);
118050
118158
  lastError = null;
118051
118159
  break;
118052
118160
  } catch (error93) {
@@ -118056,7 +118164,7 @@ async function saveGraph(workspace, graph, options) {
118056
118164
  break;
118057
118165
  }
118058
118166
  if (attempt < WINDOWS_RENAME_MAX_RETRIES2 - 1) {
118059
- await new Promise((resolve49) => setTimeout(resolve49, _internals82.retryDelayMs));
118167
+ await new Promise((resolve49) => setTimeout(resolve49, _internals83.retryDelayMs));
118060
118168
  }
118061
118169
  }
118062
118170
  }
@@ -121758,7 +121866,7 @@ function resolveDefaultReviewerAgent(generatedAgentNames) {
121758
121866
  }
121759
121867
  async function compileReviewPackage(directory, phase, sessionID, requireDiffSummary) {
121760
121868
  const lanes = await listLaneEvidence(directory, phase);
121761
- const persisted = _internals85.readPersisted?.(directory) ?? null;
121869
+ const persisted = _internals86.readPersisted?.(directory) ?? null;
121762
121870
  if (persisted) {
121763
121871
  let matchingRunState = null;
121764
121872
  for (const sessionState of Object.values(persisted.sessions)) {
@@ -121968,7 +122076,7 @@ Be specific and evidence-based. Do not approve a phase with unresolved degraded
121968
122076
  client.session.delete({ path: { id: sessionId } }).catch(() => {});
121969
122077
  }
121970
122078
  }
121971
- var _internals85 = {
122079
+ var _internals86 = {
121972
122080
  compileReviewPackage,
121973
122081
  parseReviewerVerdict,
121974
122082
  writeReviewerEvidence,
@@ -121985,28 +122093,28 @@ async function dispatchPhaseReviewer(directory, phase, sessionID, config3) {
121985
122093
  };
121986
122094
  const generatedAgentNames = swarmState.generatedAgentNames;
121987
122095
  const agentName = mergedConfig.reviewerAgent || resolveDefaultReviewerAgent(generatedAgentNames);
121988
- const pkg = await _internals85.compileReviewPackage(directory, phase, sessionID, mergedConfig.requireDiffSummary);
122096
+ const pkg = await _internals86.compileReviewPackage(directory, phase, sessionID, mergedConfig.requireDiffSummary);
121989
122097
  let responseText;
121990
122098
  try {
121991
- responseText = await _internals85.dispatchReviewerAgent(directory, pkg, agentName, mergedConfig.timeoutMs, sessionID);
122099
+ responseText = await _internals86.dispatchReviewerAgent(directory, pkg, agentName, mergedConfig.timeoutMs, sessionID);
121992
122100
  } catch (error93) {
121993
- const evidencePath2 = await _internals85.writeReviewerEvidence(directory, phase, "REJECTED", error93 instanceof Error ? error93.message : String(error93));
122101
+ const evidencePath2 = await _internals86.writeReviewerEvidence(directory, phase, "REJECTED", error93 instanceof Error ? error93.message : String(error93));
121994
122102
  return {
121995
122103
  verdict: "REJECTED",
121996
122104
  reason: `Reviewer dispatch failed: ${error93 instanceof Error ? error93.message : String(error93)}`,
121997
122105
  evidencePath: evidencePath2
121998
122106
  };
121999
122107
  }
122000
- const parsed = _internals85.parseReviewerVerdict(responseText);
122108
+ const parsed = _internals86.parseReviewerVerdict(responseText);
122001
122109
  if (!parsed) {
122002
- const evidencePath2 = await _internals85.writeReviewerEvidence(directory, phase, "REJECTED", "Reviewer response could not be parsed");
122110
+ const evidencePath2 = await _internals86.writeReviewerEvidence(directory, phase, "REJECTED", "Reviewer response could not be parsed");
122003
122111
  return {
122004
122112
  verdict: "REJECTED",
122005
122113
  reason: "Reviewer response could not be parsed",
122006
122114
  evidencePath: evidencePath2
122007
122115
  };
122008
122116
  }
122009
- const evidencePath = await _internals85.writeReviewerEvidence(directory, phase, parsed.verdict, parsed.reason);
122117
+ const evidencePath = await _internals86.writeReviewerEvidence(directory, phase, parsed.verdict, parsed.reason);
122010
122118
  return {
122011
122119
  verdict: parsed.verdict,
122012
122120
  reason: parsed.reason,
@@ -122190,7 +122298,7 @@ async function runAutoReview(input) {
122190
122298
  phase
122191
122299
  };
122192
122300
  try {
122193
- const diffResult = await _internals86.computeExecutionDiff(directory, config3.max_diff_kb * 1024);
122301
+ const diffResult = await _internals87.computeExecutionDiff(directory, config3.max_diff_kb * 1024);
122194
122302
  if (diffResult.status === "clean") {
122195
122303
  writeAutoReviewEvent(directory, {
122196
122304
  ...base,
@@ -122212,7 +122320,7 @@ async function runAutoReview(input) {
122212
122320
  const prompt = buildReviewPrompt(trigger, diff, taskId, phase);
122213
122321
  let transcript;
122214
122322
  try {
122215
- transcript = await _internals86.dispatchReviewer(directory, prompt, agentName, config3.timeout_ms, sessionID);
122323
+ transcript = await _internals87.dispatchReviewer(directory, prompt, agentName, config3.timeout_ms, sessionID);
122216
122324
  } catch (err) {
122217
122325
  writeAutoReviewEvent(directory, {
122218
122326
  ...base,
@@ -122316,13 +122424,13 @@ function createAutoReviewHook(options) {
122316
122424
  if (inFlightSessions.has(sessionID))
122317
122425
  return;
122318
122426
  const last = lastDispatchBySession.get(sessionID) ?? 0;
122319
- if (_internals86.now() - last < COOLDOWN_MS)
122427
+ if (_internals87.now() - last < COOLDOWN_MS)
122320
122428
  return;
122321
122429
  inFlightSessions.add(sessionID);
122322
122430
  lastDispatchBySession.delete(sessionID);
122323
- lastDispatchBySession.set(sessionID, _internals86.now());
122431
+ lastDispatchBySession.set(sessionID, _internals87.now());
122324
122432
  evictCooldownMap();
122325
- _internals86.runAutoReview({
122433
+ _internals87.runAutoReview({
122326
122434
  directory,
122327
122435
  sessionID,
122328
122436
  trigger,
@@ -122342,7 +122450,7 @@ function createAutoReviewHook(options) {
122342
122450
  }
122343
122451
  };
122344
122452
  }
122345
- var _internals86 = {
122453
+ var _internals87 = {
122346
122454
  computeExecutionDiff,
122347
122455
  dispatchReviewer,
122348
122456
  runAutoReview,
@@ -122783,10 +122891,10 @@ async function getRunMemorySummary(directory) {
122783
122891
  if (entries.length === 0) {
122784
122892
  return null;
122785
122893
  }
122786
- const groups = _internals87.groupByTaskId(entries);
122894
+ const groups = _internals88.groupByTaskId(entries);
122787
122895
  const summaries = [];
122788
122896
  for (const [taskId, taskEntries] of groups) {
122789
- const summary = _internals87.summarizeTask(taskId, taskEntries);
122897
+ const summary = _internals88.summarizeTask(taskId, taskEntries);
122790
122898
  if (summary) {
122791
122899
  summaries.push(summary);
122792
122900
  }
@@ -122819,7 +122927,7 @@ Use this data to avoid repeating known failure patterns.`;
122819
122927
  }
122820
122928
  return prefix + summaryText + suffix;
122821
122929
  }
122822
- var _internals87 = {
122930
+ var _internals88 = {
122823
122931
  generateTaskFingerprint,
122824
122932
  recordOutcome,
122825
122933
  getTaskHistory,
@@ -123008,7 +123116,7 @@ async function injectForDelegate(params) {
123008
123116
  currentTool: firstTool,
123009
123117
  mode: "delegation"
123010
123118
  };
123011
- const searchFn = params.searchFn ?? (_internals89.searchKnowledge === defaultSearchKnowledge ? searchKnowledge : _internals89.searchKnowledge);
123119
+ const searchFn = params.searchFn ?? (_internals90.searchKnowledge === defaultSearchKnowledge ? searchKnowledge : _internals90.searchKnowledge);
123012
123120
  try {
123013
123121
  const search = await searchFn({
123014
123122
  directory,
@@ -123032,7 +123140,7 @@ async function injectForDelegate(params) {
123032
123140
  ranks[e.id] = idx + 1;
123033
123141
  scores[e.id] = e.finalScore;
123034
123142
  });
123035
- await _internals89.recordKnowledgeEvent(directory, {
123143
+ await _internals90.recordKnowledgeEvent(directory, {
123036
123144
  type: "retrieved",
123037
123145
  trace_id: search.trace_id,
123038
123146
  session_id: sessionId ?? "unknown",
@@ -123239,7 +123347,7 @@ function createKnowledgeInjectorHook(directory, config3, modelLimitOverrides = {
123239
123347
  projectName,
123240
123348
  currentPhase: phaseDescription
123241
123349
  };
123242
- const searchFn = _internals89.searchKnowledge === defaultSearchKnowledge ? searchKnowledge : _internals89.searchKnowledge;
123350
+ const searchFn = _internals90.searchKnowledge === defaultSearchKnowledge ? searchKnowledge : _internals90.searchKnowledge;
123243
123351
  const search = await searchFn({
123244
123352
  directory,
123245
123353
  config: config3,
@@ -123355,7 +123463,7 @@ ${freshPreamble}` : `<curator_briefing>${truncatedBriefing}</curator_briefing>`;
123355
123463
  ranks[id] = idx + 1;
123356
123464
  scores[id] = scoreById.get(id) ?? 0;
123357
123465
  });
123358
- await _internals89.recordKnowledgeEvent(directory, {
123466
+ await _internals90.recordKnowledgeEvent(directory, {
123359
123467
  type: "retrieved",
123360
123468
  trace_id: search.trace_id,
123361
123469
  session_id: systemMsg?.info?.sessionID ?? "unknown",
@@ -123368,7 +123476,7 @@ ${freshPreamble}` : `<curator_briefing>${truncatedBriefing}</curator_briefing>`;
123368
123476
  ranks,
123369
123477
  scores
123370
123478
  });
123371
- _internals89.recordKnowledgeShown(directory, cachedShownIds, {
123479
+ _internals90.recordKnowledgeShown(directory, cachedShownIds, {
123372
123480
  phase: phaseLabel,
123373
123481
  tool: retrievalCtx.currentTool,
123374
123482
  action: retrievalCtx.currentAction,
@@ -123378,7 +123486,7 @@ ${freshPreamble}` : `<curator_briefing>${truncatedBriefing}</curator_briefing>`;
123378
123486
  }
123379
123487
  });
123380
123488
  }
123381
- var _internals89 = {
123489
+ var _internals90 = {
123382
123490
  searchKnowledge,
123383
123491
  recordKnowledgeEvent,
123384
123492
  recordKnowledgeShown
@@ -125377,7 +125485,7 @@ async function knowledgeApplicationGateBefore(directory, input, config3) {
125377
125485
  if (config3.mode === "enforce") {
125378
125486
  throw new Error("KNOWLEDGE_ENFORCE_GATE_DENY: missing sessionID on tool.execute.before; refusing to evaluate critical-directive ack state");
125379
125487
  }
125380
- _internals90.writeWarnEvent(directory, {
125488
+ _internals91.writeWarnEvent(directory, {
125381
125489
  timestamp: new Date().toISOString(),
125382
125490
  event: "knowledge_application_gate_warn",
125383
125491
  tool: toolName,
@@ -125460,7 +125568,7 @@ async function knowledgeApplicationTransformScan(directory, output, sessionID) {
125460
125568
  }
125461
125569
  }
125462
125570
  }
125463
- var _internals90 = {
125571
+ var _internals91 = {
125464
125572
  knowledgeApplicationGateBefore,
125465
125573
  knowledgeApplicationTransformScan,
125466
125574
  HIGH_RISK_TOOLS,
@@ -126694,7 +126802,7 @@ function timeoutKillSignal(platform) {
126694
126802
  }
126695
126803
  function killProcess(proc) {
126696
126804
  try {
126697
- proc?.kill(timeoutKillSignal(_internals91.platform()));
126805
+ proc?.kill(timeoutKillSignal(_internals92.platform()));
126698
126806
  } catch {}
126699
126807
  }
126700
126808
  async function runExternalTool(options) {
@@ -126714,7 +126822,7 @@ async function runExternalTool(options) {
126714
126822
  let exitSettled = false;
126715
126823
  let settledExitCode = null;
126716
126824
  try {
126717
- proc = _internals91.bunSpawn([options.executable, ...options.args], {
126825
+ proc = _internals92.bunSpawn([options.executable, ...options.args], {
126718
126826
  cwd: options.cwd,
126719
126827
  env: options.env,
126720
126828
  stdin: "ignore",
@@ -126782,7 +126890,7 @@ async function runExternalTool(options) {
126782
126890
  }
126783
126891
  }
126784
126892
  }
126785
- var _internals91 = {
126893
+ var _internals92 = {
126786
126894
  bunSpawn,
126787
126895
  platform: () => process.platform
126788
126896
  };
@@ -126799,7 +126907,7 @@ var MAX_WORKFLOW_FILES = 500;
126799
126907
  var MAX_WORKFLOW_DIRS = 200;
126800
126908
  var MAX_WORKFLOW_DEPTH = 20;
126801
126909
  function resolveActionlintBinary() {
126802
- return _internals92.resolveExecutableFromPath(["actionlint"]);
126910
+ return _internals93.resolveExecutableFromPath(["actionlint"]);
126803
126911
  }
126804
126912
  function normalizeRelativeWorkflowFile(file3, workspace) {
126805
126913
  if (!file3 || containsControlChars(file3) || containsPathTraversal(file3)) {
@@ -126913,7 +127021,7 @@ var actionlint_scan = createSwarmTool({
126913
127021
  const discovery = requestedFiles ? {
126914
127022
  files: requestedFiles.map((f) => normalizeRelativeWorkflowFile(f, directory)).filter((f) => Boolean(f)),
126915
127023
  truncated: false
126916
- } : _internals92.discoverWorkflowFiles(directory);
127024
+ } : _internals93.discoverWorkflowFiles(directory);
126917
127025
  let files = discovery.files;
126918
127026
  if (requestedFiles && files.length !== requestedFiles.length) {
126919
127027
  return JSON.stringify({
@@ -126937,7 +127045,7 @@ var actionlint_scan = createSwarmTool({
126937
127045
  note: discoveryTruncated ? `Workflow discovery was truncated at ${MAX_WORKFLOW_FILES} files, ${MAX_WORKFLOW_DIRS} directories, or depth ${MAX_WORKFLOW_DEPTH}; result is incomplete.` : "No GitHub Actions workflow YAML files found"
126938
127046
  }, null, 2);
126939
127047
  }
126940
- const executable = _internals92.resolveActionlintBinary();
127048
+ const executable = _internals93.resolveActionlintBinary();
126941
127049
  if (!executable) {
126942
127050
  return JSON.stringify({
126943
127051
  error: true,
@@ -126950,7 +127058,7 @@ var actionlint_scan = createSwarmTool({
126950
127058
  "{{json .}}",
126951
127059
  ...files.map((file3) => `./${file3}`)
126952
127060
  ];
126953
- const run = await _internals92.runExternalTool({
127061
+ const run = await _internals93.runExternalTool({
126954
127062
  executable,
126955
127063
  args: lintArgs,
126956
127064
  cwd: directory,
@@ -126994,7 +127102,7 @@ var actionlint_scan = createSwarmTool({
126994
127102
  }, null, 2);
126995
127103
  }
126996
127104
  });
126997
- var _internals92 = {
127105
+ var _internals93 = {
126998
127106
  resolveExecutableFromPath,
126999
127107
  resolveActionlintBinary,
127000
127108
  runExternalTool,
@@ -127841,7 +127949,7 @@ function splitGlobPatterns(value) {
127841
127949
  return value ? value.split(",").map((p) => p.trim()).filter(Boolean) : [];
127842
127950
  }
127843
127951
  function resolveAstGrepBinary() {
127844
- return _internals93.resolveExecutableFromPath(["ast-grep", "sg"]);
127952
+ return _internals94.resolveExecutableFromPath(["ast-grep", "sg"]);
127845
127953
  }
127846
127954
  function toWorkspaceRelativePath(filePath, workspace) {
127847
127955
  try {
@@ -127973,7 +128081,7 @@ var ast_grep = createSwarmTool({
127973
128081
  message: "Workspace directory does not exist"
127974
128082
  }, null, 2);
127975
128083
  }
127976
- const executable = _internals93.resolveAstGrepBinary();
128084
+ const executable = _internals94.resolveAstGrepBinary();
127977
128085
  if (!executable) {
127978
128086
  return JSON.stringify({
127979
128087
  error: true,
@@ -127999,7 +128107,7 @@ var ast_grep = createSwarmTool({
127999
128107
  sgArgs.push("--globs", `!${glob}`);
128000
128108
  }
128001
128109
  sgArgs.push(".");
128002
- const run = await _internals93.runExternalTool({
128110
+ const run = await _internals94.runExternalTool({
128003
128111
  executable,
128004
128112
  args: sgArgs,
128005
128113
  cwd: directory,
@@ -128041,7 +128149,7 @@ var ast_grep = createSwarmTool({
128041
128149
  }, null, 2);
128042
128150
  }
128043
128151
  });
128044
- var _internals93 = {
128152
+ var _internals94 = {
128045
128153
  resolveExecutableFromPath,
128046
128154
  resolveAstGrepBinary,
128047
128155
  runExternalTool,
@@ -129770,7 +129878,7 @@ init_model_limits();
129770
129878
  init_utils2();
129771
129879
  init_state2();
129772
129880
  init_create_tool();
129773
- var _internals94 = {
129881
+ var _internals95 = {
129774
129882
  loadPluginConfig,
129775
129883
  fetchSessionMessages: async (sessionID, directory, limit = 100) => {
129776
129884
  if (!swarmState.opencodeClient?.session)
@@ -129819,13 +129927,13 @@ var context_status = createSwarmTool({
129819
129927
  description: "Report current context-window headroom for the active session. Returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only — no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",
129820
129928
  args: {},
129821
129929
  async execute(_args, directory, ctx) {
129822
- const config3 = _internals94.loadPluginConfig(directory);
129930
+ const config3 = _internals95.loadPluginConfig(directory);
129823
129931
  const warnThreshold = config3.context_budget?.warn_threshold ?? 0.7;
129824
129932
  const criticalThreshold = config3.context_budget?.critical_threshold ?? 0.9;
129825
129933
  const modelLimitsConfig = config3.context_budget?.model_limits ?? {};
129826
129934
  let messages = [];
129827
129935
  if (ctx?.sessionID) {
129828
- const sessionMessages = await _internals94.fetchSessionMessages(ctx.sessionID, directory);
129936
+ const sessionMessages = await _internals95.fetchSessionMessages(ctx.sessionID, directory);
129829
129937
  if (sessionMessages) {
129830
129938
  messages = sessionMessages;
129831
129939
  }
@@ -129866,7 +129974,7 @@ var VALID_TASK_ID = /^\d+\.\d+(\.\d+)*$/;
129866
129974
  var COUNCIL_GATE_NAME = "council";
129867
129975
  var COUNCIL_AGENT_ID = "architect";
129868
129976
  var EvidenceFileSchema = exports_external.record(exports_external.string(), exports_external.unknown());
129869
- var _internals95 = {
129977
+ var _internals96 = {
129870
129978
  withTaskEvidenceLock
129871
129979
  };
129872
129980
  var FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
@@ -129901,7 +130009,7 @@ async function writeCouncilEvidence(workingDir, synthesis) {
129901
130009
  const dir = join131(workingDir, EVIDENCE_DIR2);
129902
130010
  mkdirSync42(dir, { recursive: true });
129903
130011
  const filePath = taskEvidencePath(workingDir, synthesis.taskId);
129904
- await _internals95.withTaskEvidenceLock(workingDir, synthesis.taskId, COUNCIL_AGENT_ID, async () => {
130012
+ await _internals96.withTaskEvidenceLock(workingDir, synthesis.taskId, COUNCIL_AGENT_ID, async () => {
129905
130013
  const existingRoot = Object.create(null);
129906
130014
  if (existsSync95(filePath)) {
129907
130015
  try {
@@ -132421,7 +132529,7 @@ var CollectLaneResultsArgsSchema = exports_external.object({
132421
132529
  include_pending: exports_external.boolean().optional().describe("Include pending/running lanes in lane_results. Defaults to true for non-blocking polls and false for wait=true joins."),
132422
132530
  cancel_pending: exports_external.boolean().optional().describe("Abort and mark pending/running lanes cancelled")
132423
132531
  });
132424
- var _internals96 = {
132532
+ var _internals97 = {
132425
132533
  getSessionOps: () => swarmState.opencodeClient?.session ?? null,
132426
132534
  getGeneratedAgentNames: () => swarmState.generatedAgentNames,
132427
132535
  createParallelDispatcher,
@@ -132445,7 +132553,7 @@ async function executeDispatchLanes(args2, directory, context = {}) {
132445
132553
  errors: duplicateLaneIds.map((id) => `Duplicate lane id: ${id}`)
132446
132554
  });
132447
132555
  }
132448
- const session = _internals96.getSessionOps();
132556
+ const session = _internals97.getSessionOps();
132449
132557
  if (!session) {
132450
132558
  return failureResult({
132451
132559
  failure_class: "no_client",
@@ -132463,7 +132571,7 @@ async function executeDispatchLanes(args2, directory, context = {}) {
132463
132571
  const lanes = applyExplorerFormatSuffix(common.lanes);
132464
132572
  const maxConcurrent = Math.min(parsed.data.max_concurrent ?? lanes.length, lanes.length, MAX_LANES);
132465
132573
  const timeoutMs = parsed.data.timeout_ms ?? DEFAULT_TIMEOUT_MS3;
132466
- const dispatcher = _internals96.createParallelDispatcher({
132574
+ const dispatcher = _internals97.createParallelDispatcher({
132467
132575
  enabled: true,
132468
132576
  maxConcurrentTasks: maxConcurrent,
132469
132577
  evidenceLockTimeoutMs: 0
@@ -132493,7 +132601,7 @@ async function executeDispatchLanesAsync(args2, directory, context = {}) {
132493
132601
  errors: duplicateLaneIds.map((id) => `Duplicate lane id: ${id}`)
132494
132602
  });
132495
132603
  }
132496
- const session = _internals96.getSessionOps();
132604
+ const session = _internals97.getSessionOps();
132497
132605
  if (!session || typeof session.promptAsync !== "function") {
132498
132606
  return asyncFailureResult({
132499
132607
  failure_class: "no_client",
@@ -132519,7 +132627,7 @@ async function executeDispatchLanesAsync(args2, directory, context = {}) {
132519
132627
  }
132520
132628
  const maxConcurrent = Math.min(parsed.data.max_concurrent ?? lanes.length, lanes.length, MAX_LANES);
132521
132629
  const launchTimeoutMs = parsed.data.launch_timeout_ms ?? parsed.data.timeout_ms ?? DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS;
132522
- const dispatcher = _internals96.createParallelDispatcher({
132630
+ const dispatcher = _internals97.createParallelDispatcher({
132523
132631
  enabled: true,
132524
132632
  maxConcurrentTasks: maxConcurrent,
132525
132633
  evidenceLockTimeoutMs: 0
@@ -132567,7 +132675,7 @@ async function executeCollectLaneResults(args2, directory, context = {}) {
132567
132675
  errors: parsed.error.issues.map((issue3) => `${issue3.path.join(".")}: ${issue3.message}`)
132568
132676
  });
132569
132677
  }
132570
- const session = _internals96.getSessionOps();
132678
+ const session = _internals97.getSessionOps();
132571
132679
  if (!session || typeof session.messages !== "function") {
132572
132680
  return collectFailureResult({
132573
132681
  failure_class: "no_client",
@@ -132576,7 +132684,7 @@ async function executeCollectLaneResults(args2, directory, context = {}) {
132576
132684
  });
132577
132685
  }
132578
132686
  const timeoutMs = parsed.data.timeout_ms ?? DEFAULT_COLLECT_TIMEOUT_MS;
132579
- const deadline = _internals96.now() + timeoutMs;
132687
+ const deadline = _internals97.now() + timeoutMs;
132580
132688
  const batchFilter = context.sessionID !== undefined ? { parentSessionId: context.sessionID } : undefined;
132581
132689
  let records = findByBatchId(directory, parsed.data.batch_id, batchFilter);
132582
132690
  if (records.length === 0) {
@@ -132596,11 +132704,11 @@ async function executeCollectLaneResults(args2, directory, context = {}) {
132596
132704
  keepPolling = false;
132597
132705
  continue;
132598
132706
  }
132599
- if (_internals96.now() >= deadline) {
132707
+ if (_internals97.now() >= deadline) {
132600
132708
  keepPolling = false;
132601
132709
  continue;
132602
132710
  }
132603
- await _internals96.sleep(Math.min(pollIntervalMs, Math.max(0, deadline - _internals96.now())));
132711
+ await _internals97.sleep(Math.min(pollIntervalMs, Math.max(0, deadline - _internals97.now())));
132604
132712
  pollIntervalMs = nextCollectPollInterval(pollIntervalMs);
132605
132713
  }
132606
132714
  return buildCollectResult(parsed.data.batch_id, records, parsed.data.include_pending ?? parsed.data.wait !== true);
@@ -132829,7 +132937,7 @@ async function isLaneReadyForCollection(session, directory, sessionId) {
132829
132937
  async function sweepStaleAsyncLaneRecords(session, directory, records, staleTimeoutMs) {
132830
132938
  if (staleTimeoutMs <= 0)
132831
132939
  return;
132832
- const now = _internals96.now();
132940
+ const now = _internals97.now();
132833
132941
  for (const record3 of records) {
132834
132942
  if (record3.status !== "pending" && record3.status !== "running" && record3.status !== "ingestion_error")
132835
132943
  continue;
@@ -133040,7 +133148,7 @@ function failedLane(lane, role, startedAt, error93, slotId, runId, sessionId) {
133040
133148
  };
133041
133149
  }
133042
133150
  function validateLaneAgent(agent, context) {
133043
- const generatedAgentNames = _internals96.getGeneratedAgentNames();
133151
+ const generatedAgentNames = _internals97.getGeneratedAgentNames();
133044
133152
  const role = resolveGeneratedAgentRole(agent, generatedAgentNames);
133045
133153
  if (!isKnownCanonicalRole(role)) {
133046
133154
  return {
@@ -133191,7 +133299,7 @@ function applyCommonPrompt(lanes, commonPrompt) {
133191
133299
  return { ok: true, lanes: merged };
133192
133300
  }
133193
133301
  function applyExplorerFormatSuffix(lanes) {
133194
- const generatedAgentNames = _internals96.getGeneratedAgentNames();
133302
+ const generatedAgentNames = _internals97.getGeneratedAgentNames();
133195
133303
  return lanes.map((lane) => {
133196
133304
  const role = resolveGeneratedAgentRole(lane.agent, generatedAgentNames);
133197
133305
  if (role !== "explorer")
@@ -133264,7 +133372,7 @@ function boundErrorString(text) {
133264
133372
  return `${text.slice(0, MAX_ERROR_CHARS)}${ERROR_TRUNCATION_SUFFIX}`;
133265
133373
  }
133266
133374
  function isoNow() {
133267
- return new Date(_internals96.now()).toISOString();
133375
+ return new Date(_internals97.now()).toISOString();
133268
133376
  }
133269
133377
  function buildLaneSessionCreateArgs(directory, lane, context) {
133270
133378
  const parentID = context.sessionID?.trim();
@@ -133278,7 +133386,7 @@ function buildLaneSessionCreateArgs(directory, lane, context) {
133278
133386
  };
133279
133387
  }
133280
133388
  function makeBatchId() {
133281
- return `lanes-${_internals96.now().toString(36)}`;
133389
+ return `lanes-${_internals97.now().toString(36)}`;
133282
133390
  }
133283
133391
  function promptHash(lane, directory, batchId) {
133284
133392
  return digestText2(JSON.stringify({
@@ -133571,7 +133679,7 @@ function buildIsUpstreamCommittedWithStatus(directory, options) {
133571
133679
  const max = options?.maxCommits ?? MAX_LOG_COMMITS;
133572
133680
  let subjects;
133573
133681
  try {
133574
- subjects = _internals97.readGitLogSubjects(directory, max);
133682
+ subjects = _internals98.readGitLogSubjects(directory, max);
133575
133683
  } catch (err) {
133576
133684
  const msg = err instanceof Error ? err.message : String(err);
133577
133685
  criticalWarn(`[epic:upstream-commits] git log scan failed (degrading to permissive predicate, the activation gate may flip fail-closed): ${msg}`);
@@ -133593,7 +133701,7 @@ function buildIsUpstreamCommittedWithStatus(directory, options) {
133593
133701
  gitFailed: false
133594
133702
  };
133595
133703
  }
133596
- var _internals97 = {
133704
+ var _internals98 = {
133597
133705
  readGitLogSubjects: (cwd, max) => {
133598
133706
  return _internals4.gitExec(["log", "--no-merges", `--max-count=${max}`, "--pretty=%s"], cwd);
133599
133707
  }
@@ -133998,7 +134106,7 @@ function readPlanJson(directory) {
133998
134106
  }
133999
134107
  async function executeEpicPlanWaves(args2) {
134000
134108
  const { directory, phase, scopes } = args2;
134001
- const plan = _internals98.readPlanJson(directory);
134109
+ const plan = _internals99.readPlanJson(directory);
134002
134110
  if (!plan) {
134003
134111
  return {
134004
134112
  success: false,
@@ -134051,7 +134159,7 @@ async function executeEpicPlanWaves(args2) {
134051
134159
  try {
134052
134160
  const tasksMissingScope = [];
134053
134161
  for (const task of pendingTasks) {
134054
- const declaredScope = _internals98.readTaskScopes(directory, task.id);
134162
+ const declaredScope = _internals99.readTaskScopes(directory, task.id);
134055
134163
  const filesTouched = task.files_touched ?? [];
134056
134164
  const providedScope = scopes && task.id in scopes ? scopes[task.id] : null;
134057
134165
  if ((declaredScope === null || declaredScope.length === 0) && filesTouched.length === 0 && (providedScope === null || providedScope.length === 0)) {
@@ -134074,8 +134182,8 @@ async function executeEpicPlanWaves(args2) {
134074
134182
  };
134075
134183
  }
134076
134184
  let isUpstreamCommitted;
134077
- if (_internals98.isGitRepo(directory)) {
134078
- const evidence = _internals98.buildIsUpstreamCommittedWithStatus(directory);
134185
+ if (_internals99.isGitRepo(directory)) {
134186
+ const evidence = _internals99.buildIsUpstreamCommittedWithStatus(directory);
134079
134187
  if (evidence.gitFailed) {
134080
134188
  criticalWarn(`[epic_plan_waves] wave-planning blocked for directory=${directory} phase=${phase}: git log scan failed. Any prior promote verdict in .swarm/evidence/epic-promotions.jsonl for this phase is not backed by actual parallel execution.`);
134081
134189
  return {
@@ -134090,7 +134198,7 @@ async function executeEpicPlanWaves(args2) {
134090
134198
  }
134091
134199
  let leanConfig = { ...DEFAULT_LEAN_TURBO_CONFIG };
134092
134200
  try {
134093
- const loaded = await _internals98.loadPluginConfigWithMeta(directory);
134201
+ const loaded = await _internals99.loadPluginConfigWithMeta(directory);
134094
134202
  const userLean = loaded?.config?.turbo?.lean;
134095
134203
  if (userLean) {
134096
134204
  leanConfig = { ...leanConfig, ...userLean };
@@ -134114,7 +134222,7 @@ async function executeEpicPlanWaves(args2) {
134114
134222
  };
134115
134223
  }
134116
134224
  }
134117
- var _internals98 = {
134225
+ var _internals99 = {
134118
134226
  readPlanJson,
134119
134227
  readTaskScopes,
134120
134228
  isGitRepo: (cwd) => isGitRepo(cwd),
@@ -134146,7 +134254,7 @@ init_state2();
134146
134254
  init_divergence_recorder();
134147
134255
  init_logger();
134148
134256
  init_create_tool();
134149
- var _internals99 = {
134257
+ var _internals100 = {
134150
134258
  hasActiveEpicMode,
134151
134259
  getAgentSession,
134152
134260
  readScopeFromDisk,
@@ -134155,7 +134263,7 @@ var _internals99 = {
134155
134263
  };
134156
134264
  async function findPhaseForTask(directory, taskId) {
134157
134265
  try {
134158
- const plan = await _internals99.loadPlanJsonOnly(directory);
134266
+ const plan = await _internals100.loadPlanJsonOnly(directory);
134159
134267
  if (!plan)
134160
134268
  return;
134161
134269
  for (const phase of plan.phases) {
@@ -134168,20 +134276,20 @@ async function findPhaseForTask(directory, taskId) {
134168
134276
  }
134169
134277
  async function executeEpicRecordDivergence(args2) {
134170
134278
  const { directory, taskId, sessionID } = args2;
134171
- if (!_internals99.hasActiveEpicMode(sessionID)) {
134279
+ if (!_internals100.hasActiveEpicMode(sessionID)) {
134172
134280
  return { success: true, reason: "epic-mode-not-active" };
134173
134281
  }
134174
- const session = _internals99.getAgentSession(sessionID);
134282
+ const session = _internals100.getAgentSession(sessionID);
134175
134283
  if (!session) {
134176
134284
  return { success: true, reason: "no-session" };
134177
134285
  }
134178
- const declaredScope = _internals99.readScopeFromDisk(directory, taskId);
134286
+ const declaredScope = _internals100.readScopeFromDisk(directory, taskId);
134179
134287
  if (declaredScope === null) {
134180
134288
  return { success: true, reason: "no-scope" };
134181
134289
  }
134182
134290
  const actualFiles = session.modifiedFilesThisCoderTask ?? [];
134183
134291
  const phaseNumber = await findPhaseForTask(directory, taskId);
134184
- const result = _internals99.recordTaskDivergence({
134292
+ const result = _internals100.recordTaskDivergence({
134185
134293
  directory,
134186
134294
  sessionID,
134187
134295
  taskId,
@@ -134563,7 +134671,7 @@ init_state4();
134563
134671
 
134564
134672
  // src/turbo/lean/state-lock.ts
134565
134673
  init_file_locks();
134566
- var _internals100 = { tryAcquireLock };
134674
+ var _internals101 = { tryAcquireLock };
134567
134675
 
134568
134676
  class TurboStateLockTimeoutError extends Error {
134569
134677
  directory;
@@ -134591,7 +134699,7 @@ async function withTurboStateLock(directory, sessionID, fn2, timeoutMs = 30000)
134591
134699
  while (true) {
134592
134700
  let result;
134593
134701
  try {
134594
- result = await _internals100.tryAcquireLock(directory, lockPath, agent, sessionID);
134702
+ result = await _internals101.tryAcquireLock(directory, lockPath, agent, sessionID);
134595
134703
  } catch (acquireErr) {
134596
134704
  console.warn(`[lean-turbo] state lock acquisition error for ${sessionID} (${lockPath}), will retry: ${acquireErr instanceof Error ? acquireErr.message : String(acquireErr)}`);
134597
134705
  }
@@ -135338,7 +135446,7 @@ ${fileList}
135338
135446
  // src/tools/epic-run-phase.ts
135339
135447
  init_logger();
135340
135448
  init_create_tool();
135341
- var _internals101 = {
135449
+ var _internals102 = {
135342
135450
  loadPluginConfigWithMeta,
135343
135451
  loadPlanJsonOnly,
135344
135452
  getCoChangeData,
@@ -135360,13 +135468,13 @@ var _internals101 = {
135360
135468
  };
135361
135469
  async function executeEpicDecidePhase(args2) {
135362
135470
  const { directory, phase, sessionID } = args2;
135363
- if (!_internals101.isEpicModeActive(directory, sessionID)) {
135471
+ if (!_internals102.isEpicModeActive(directory, sessionID)) {
135364
135472
  return {
135365
135473
  success: false,
135366
135474
  reason: "epic-mode-not-active"
135367
135475
  };
135368
135476
  }
135369
- const plan = await _internals101.loadPlanJsonOnly(directory);
135477
+ const plan = await _internals102.loadPlanJsonOnly(directory);
135370
135478
  if (plan === null) {
135371
135479
  return { success: false, reason: "no-plan" };
135372
135480
  }
@@ -135396,7 +135504,7 @@ async function executeEpicDecidePhase(args2) {
135396
135504
  }
135397
135505
  const tasksMissingScope = [];
135398
135506
  for (const task of pendingTasks) {
135399
- const declaredScope = _internals101.readTaskScopes(directory, task.id);
135507
+ const declaredScope = _internals102.readTaskScopes(directory, task.id);
135400
135508
  const filesTouched = task.files_touched ?? [];
135401
135509
  if ((declaredScope === null || declaredScope.length === 0) && filesTouched.length === 0) {
135402
135510
  tasksMissingScope.push(task.id);
@@ -135416,7 +135524,7 @@ async function executeEpicDecidePhase(args2) {
135416
135524
  };
135417
135525
  }
135418
135526
  }
135419
- const { config: config3 } = _internals101.loadPluginConfigWithMeta(directory);
135527
+ const { config: config3 } = _internals102.loadPluginConfigWithMeta(directory);
135420
135528
  const modeCfg = config3.turbo?.epic?.mode;
135421
135529
  const cochangeCfg = config3.turbo?.epic?.cochange;
135422
135530
  const calibrationCfg = config3.turbo?.epic?.calibration;
@@ -135429,14 +135537,14 @@ async function executeEpicDecidePhase(args2) {
135429
135537
  let extraHotModules = [];
135430
135538
  if (calibrationEnabled) {
135431
135539
  try {
135432
- const currentCalibration = _internals101.loadCalibrationState(directory);
135540
+ const currentCalibration = _internals102.loadCalibrationState(directory);
135433
135541
  if (currentCalibration !== null) {
135434
- const history = _internals101.readDivergenceHistory(directory, {
135542
+ const history = _internals102.readDivergenceHistory(directory, {
135435
135543
  maxBytes: Number.POSITIVE_INFINITY
135436
135544
  });
135437
135545
  const newRecords = history.slice(currentCalibration.processedRecords);
135438
135546
  if (newRecords.length > 0) {
135439
- const updated = _internals101.applyCalibration(currentCalibration, newRecords, {
135547
+ const updated = _internals102.applyCalibration(currentCalibration, newRecords, {
135440
135548
  staticThreshold: staticActivationThreshold,
135441
135549
  floorThreshold: calibrationCfg?.floor_threshold,
135442
135550
  tightenStep: calibrationCfg?.tighten_step,
@@ -135445,17 +135553,17 @@ async function executeEpicDecidePhase(args2) {
135445
135553
  });
135446
135554
  let savedSuccessfully = false;
135447
135555
  try {
135448
- _internals101.saveCalibrationState(directory, updated);
135556
+ _internals102.saveCalibrationState(directory, updated);
135449
135557
  savedSuccessfully = true;
135450
135558
  } catch (err) {
135451
135559
  criticalWarn(`[epic_run_phase] calibration persist failed; ignoring this run's calibration delta to avoid drift on next run: ${err instanceof Error ? err.message : String(err)}`);
135452
135560
  }
135453
135561
  const sourceForThisRun = savedSuccessfully ? updated : currentCalibration;
135454
- effectiveThreshold = _internals101.effectiveActivationThreshold(staticActivationThreshold, sourceForThisRun);
135455
- extraHotModules = _internals101.effectiveHotModules([], sourceForThisRun);
135562
+ effectiveThreshold = _internals102.effectiveActivationThreshold(staticActivationThreshold, sourceForThisRun);
135563
+ extraHotModules = _internals102.effectiveHotModules([], sourceForThisRun);
135456
135564
  } else {
135457
- effectiveThreshold = _internals101.effectiveActivationThreshold(staticActivationThreshold, currentCalibration);
135458
- extraHotModules = _internals101.effectiveHotModules([], currentCalibration);
135565
+ effectiveThreshold = _internals102.effectiveActivationThreshold(staticActivationThreshold, currentCalibration);
135566
+ extraHotModules = _internals102.effectiveHotModules([], currentCalibration);
135459
135567
  }
135460
135568
  }
135461
135569
  } catch (err) {
@@ -135471,14 +135579,14 @@ async function executeEpicDecidePhase(args2) {
135471
135579
  }
135472
135580
  }
135473
135581
  const tasks = rawTasks.map((task) => {
135474
- const scopeFiles = _internals101.readTaskScopes(directory, task.id);
135582
+ const scopeFiles = _internals102.readTaskScopes(directory, task.id);
135475
135583
  const scope = scopeFiles ?? task.files_touched ?? [];
135476
135584
  return { id: task.id, scope };
135477
135585
  });
135478
- const { pairs, commitsObserved } = await _internals101.getCoChangeData(directory);
135586
+ const { pairs, commitsObserved } = await _internals102.getCoChangeData(directory);
135479
135587
  const isGitProject = (() => {
135480
135588
  try {
135481
- return _internals101.isGitRepo(directory);
135589
+ return _internals102.isGitRepo(directory);
135482
135590
  } catch {
135483
135591
  return false;
135484
135592
  }
@@ -135511,10 +135619,10 @@ async function executeEpicDecidePhase(args2) {
135511
135619
  const phantomDeps = [...phantomDepsSet];
135512
135620
  let isUpstreamCommitted;
135513
135621
  if (isGitProject) {
135514
- const evidence = _internals101.buildIsUpstreamCommittedWithStatus(directory);
135622
+ const evidence = _internals102.buildIsUpstreamCommittedWithStatus(directory);
135515
135623
  isUpstreamCommitted = evidence.gitFailed ? () => false : evidence.predicate;
135516
135624
  }
135517
- const verdict = _internals101.decideEpicActivation(tasks, pairs, commitsObserved, {
135625
+ const verdict = _internals102.decideEpicActivation(tasks, pairs, commitsObserved, {
135518
135626
  activationThreshold: effectiveThreshold,
135519
135627
  minCommitsForSignal,
135520
135628
  cochangeNpmiThreshold,
@@ -135526,7 +135634,7 @@ async function executeEpicDecidePhase(args2) {
135526
135634
  isUpstreamCommitted
135527
135635
  });
135528
135636
  try {
135529
- _internals101.appendPromotionEvidence(directory, {
135637
+ _internals102.appendPromotionEvidence(directory, {
135530
135638
  timestamp: new Date().toISOString(),
135531
135639
  sessionID,
135532
135640
  phase,
@@ -135536,7 +135644,7 @@ async function executeEpicDecidePhase(args2) {
135536
135644
  warn(`[epic_run_phase] promotion-evidence append failed: ${err instanceof Error ? err.message : String(err)}`);
135537
135645
  }
135538
135646
  try {
135539
- _internals101.recordEpicDecision(directory, sessionID, {
135647
+ _internals102.recordEpicDecision(directory, sessionID, {
135540
135648
  decidedAt: new Date().toISOString(),
135541
135649
  phase,
135542
135650
  decision: verdict.decision,
@@ -135833,7 +135941,7 @@ function candidateFilePath(storePath3, id) {
135833
135941
  }
135834
135942
  return path173.join(storePath3, `${id}.json`);
135835
135943
  }
135836
- var _internals102 = {
135944
+ var _internals103 = {
135837
135945
  randomUUID: crypto12.randomUUID.bind(crypto12),
135838
135946
  fs: {
135839
135947
  mkdir: fs108.mkdir,
@@ -135846,11 +135954,11 @@ var _internals102 = {
135846
135954
  function createExternalSkillStore(directory, config3) {
135847
135955
  const storePath3 = path173.join(directory, ".swarm", "skills", "candidates");
135848
135956
  async function add2(candidate) {
135849
- const id = _internals102.randomUUID();
135957
+ const id = _internals103.randomUUID();
135850
135958
  const full = { ...candidate, id };
135851
135959
  const filePath = path173.join(storePath3, `${id}.json`);
135852
- await _internals102.fs.mkdir(storePath3, { recursive: true });
135853
- await _internals102.atomicWriteFile(filePath, JSON.stringify(full, null, "\t"));
135960
+ await _internals103.fs.mkdir(storePath3, { recursive: true });
135961
+ await _internals103.atomicWriteFile(filePath, JSON.stringify(full, null, "\t"));
135854
135962
  return full;
135855
135963
  }
135856
135964
  async function get2(id) {
@@ -135860,7 +135968,7 @@ function createExternalSkillStore(directory, config3) {
135860
135968
  }
135861
135969
  let raw;
135862
135970
  try {
135863
- raw = await _internals102.fs.readFile(filePath, "utf-8");
135971
+ raw = await _internals103.fs.readFile(filePath, "utf-8");
135864
135972
  } catch (err) {
135865
135973
  if (err.code === "ENOENT") {
135866
135974
  return null;
@@ -135876,7 +135984,7 @@ function createExternalSkillStore(directory, config3) {
135876
135984
  async function list(filter) {
135877
135985
  let entries;
135878
135986
  try {
135879
- entries = await _internals102.fs.readdir(storePath3);
135987
+ entries = await _internals103.fs.readdir(storePath3);
135880
135988
  } catch (err) {
135881
135989
  if (err.code === "ENOENT") {
135882
135990
  return [];
@@ -135891,7 +135999,7 @@ function createExternalSkillStore(directory, config3) {
135891
135999
  const filePath = path173.join(storePath3, entry);
135892
136000
  let raw;
135893
136001
  try {
135894
- raw = await _internals102.fs.readFile(filePath, "utf-8");
136002
+ raw = await _internals103.fs.readFile(filePath, "utf-8");
135895
136003
  } catch {
135896
136004
  continue;
135897
136005
  }
@@ -135958,7 +136066,7 @@ function createExternalSkillStore(directory, config3) {
135958
136066
  ...patch.evaluation_history
135959
136067
  ];
135960
136068
  }
135961
- await _internals102.atomicWriteFile(filePath, JSON.stringify(updated, null, "\t"));
136069
+ await _internals103.atomicWriteFile(filePath, JSON.stringify(updated, null, "\t"));
135962
136070
  return updated;
135963
136071
  }
135964
136072
  async function deleteCandidate(id) {
@@ -135967,7 +136075,7 @@ function createExternalSkillStore(directory, config3) {
135967
136075
  return false;
135968
136076
  }
135969
136077
  try {
135970
- await _internals102.fs.unlink(filePath);
136078
+ await _internals103.fs.unlink(filePath);
135971
136079
  return true;
135972
136080
  } catch (err) {
135973
136081
  if (err.code === "ENOENT") {
@@ -136005,7 +136113,7 @@ function createExternalSkillStore(directory, config3) {
136005
136113
 
136006
136114
  // src/tools/external-skill-delete.ts
136007
136115
  init_create_tool();
136008
- var _internals103 = {
136116
+ var _internals104 = {
136009
136117
  loadConfig: (directory) => {
136010
136118
  const pluginConfig = loadPluginConfig(directory);
136011
136119
  return pluginConfig.external_skills;
@@ -136027,7 +136135,7 @@ var external_skill_delete = createSwarmTool({
136027
136135
  } catch {}
136028
136136
  let config3;
136029
136137
  try {
136030
- config3 = _internals103.loadConfig(directory);
136138
+ config3 = _internals104.loadConfig(directory);
136031
136139
  } catch {
136032
136140
  return JSON.stringify({
136033
136141
  success: false,
@@ -136606,7 +136714,7 @@ function scanProvenanceIntegrity(candidate, trustLevel = "low", ttlDays) {
136606
136714
  });
136607
136715
  }
136608
136716
  fieldsScanned.push("fetched_at");
136609
- const now = new Date(_internals104.getTimestamp()).getTime();
136717
+ const now = new Date(_internals105.getTimestamp()).getTime();
136610
136718
  const fetchedAtMs = new Date(candidate.fetched_at).getTime();
136611
136719
  if (Number.isNaN(fetchedAtMs)) {
136612
136720
  findings.push({
@@ -136670,7 +136778,7 @@ function scanProvenanceIntegrity(candidate, trustLevel = "low", ttlDays) {
136670
136778
  });
136671
136779
  }
136672
136780
  fieldsScanned.push("skill_body");
136673
- const computedHash = _internals104.computeSha256(candidate.skill_body);
136781
+ const computedHash = _internals105.computeSha256(candidate.skill_body);
136674
136782
  if (computedHash !== candidate.sha256) {
136675
136783
  findings.push({
136676
136784
  pattern: "content_hash_mismatch",
@@ -136720,7 +136828,7 @@ function evaluateCandidate(candidate, options) {
136720
136828
  risk_flags: riskFlags
136721
136829
  };
136722
136830
  }
136723
- var _internals104 = {
136831
+ var _internals105 = {
136724
136832
  getTimestamp: () => new Date().toISOString(),
136725
136833
  computeSha256: (content) => createHash22("sha256").update(content).digest("hex"),
136726
136834
  splitMarkdownCodeSegments,
@@ -136730,7 +136838,7 @@ var _internals104 = {
136730
136838
 
136731
136839
  // src/tools/external-skill-discover.ts
136732
136840
  init_create_tool();
136733
- var _internals105 = {
136841
+ var _internals106 = {
136734
136842
  fetchContent: async (_url3, _timeoutMs) => {
136735
136843
  const parsed = new URL(_url3);
136736
136844
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
@@ -136891,7 +136999,7 @@ var external_skill_discover = createSwarmTool({
136891
136999
  resolvedContent = content;
136892
137000
  } else {
136893
137001
  try {
136894
- const fetched = await _internals105.fetchContent(resolvedUrl, config3.fetch_timeout_ms);
137002
+ const fetched = await _internals106.fetchContent(resolvedUrl, config3.fetch_timeout_ms);
136895
137003
  if (fetched.finalUrl !== resolvedUrl && matchedSource && !isSubpathUrl(fetched.finalUrl, matchedSource.location)) {
136896
137004
  return JSON.stringify({
136897
137005
  success: false,
@@ -136913,14 +137021,14 @@ var external_skill_discover = createSwarmTool({
136913
137021
  error: `Content too large: ${resolvedContent.length} bytes exceeds max_bytes_per_candidate (${config3.max_bytes_per_candidate})`
136914
137022
  });
136915
137023
  }
136916
- const sha256 = _internals105.computeSha256(resolvedContent);
137024
+ const sha256 = _internals106.computeSha256(resolvedContent);
136917
137025
  const candidate = {
136918
- id: _internals105.uuid(),
137026
+ id: _internals106.uuid(),
136919
137027
  source_url: resolvedUrl,
136920
137028
  source_type: sourceType,
136921
137029
  publisher,
136922
137030
  sha256,
136923
- fetched_at: _internals105.getTimestamp(),
137031
+ fetched_at: _internals106.getTimestamp(),
136924
137032
  skill_name: typeof skillName === "string" ? skillName : undefined,
136925
137033
  skill_description: typeof skillDescription === "string" ? skillDescription : undefined,
136926
137034
  skill_body: resolvedContent,
@@ -136938,7 +137046,7 @@ var external_skill_discover = createSwarmTool({
136938
137046
  candidate.evaluation_history = [
136939
137047
  {
136940
137048
  verdict: result.overall_verdict,
136941
- timestamp: _internals105.getTimestamp(),
137049
+ timestamp: _internals106.getTimestamp(),
136942
137050
  actor: "system",
136943
137051
  reason: `Validation: ${result.gate_results.length} gates, ${result.all_findings.length} findings`,
136944
137052
  gate_results: result.gate_results.map((gr) => ({
@@ -136983,7 +137091,7 @@ var external_skill_discover = createSwarmTool({
136983
137091
  init_zod();
136984
137092
  init_loader();
136985
137093
  init_create_tool();
136986
- var _internals106 = {
137094
+ var _internals107 = {
136987
137095
  loadConfig: (directory) => {
136988
137096
  const pluginConfig = loadPluginConfig(directory);
136989
137097
  return pluginConfig.external_skills;
@@ -137005,7 +137113,7 @@ var external_skill_inspect = createSwarmTool({
137005
137113
  } catch {}
137006
137114
  let config3;
137007
137115
  try {
137008
- config3 = _internals106.loadConfig(directory);
137116
+ config3 = _internals107.loadConfig(directory);
137009
137117
  } catch {
137010
137118
  return JSON.stringify({
137011
137119
  success: false,
@@ -137047,7 +137155,7 @@ var external_skill_inspect = createSwarmTool({
137047
137155
  init_zod();
137048
137156
  init_loader();
137049
137157
  init_create_tool();
137050
- var _internals107 = {
137158
+ var _internals108 = {
137051
137159
  loadConfig: (directory) => {
137052
137160
  const pluginConfig = loadPluginConfig(directory);
137053
137161
  return pluginConfig.external_skills;
@@ -137083,7 +137191,7 @@ var external_skill_list = createSwarmTool({
137083
137191
  } catch {}
137084
137192
  let config3;
137085
137193
  try {
137086
- config3 = _internals107.loadConfig(directory);
137194
+ config3 = _internals108.loadConfig(directory);
137087
137195
  } catch {
137088
137196
  return JSON.stringify({
137089
137197
  success: false,
@@ -137136,7 +137244,7 @@ import { createHash as createHash24 } from "node:crypto";
137136
137244
  import * as fs109 from "node:fs/promises";
137137
137245
  import * as path174 from "node:path";
137138
137246
  init_create_tool();
137139
- var _internals108 = {
137247
+ var _internals109 = {
137140
137248
  loadConfig: (directory) => {
137141
137249
  const pluginConfig = loadPluginConfig(directory);
137142
137250
  return pluginConfig.external_skills;
@@ -137206,7 +137314,7 @@ var external_skill_promote = createSwarmTool({
137206
137314
  } catch {}
137207
137315
  let config3;
137208
137316
  try {
137209
- config3 = _internals108.loadConfig(directory);
137317
+ config3 = _internals109.loadConfig(directory);
137210
137318
  } catch {
137211
137319
  return JSON.stringify({
137212
137320
  success: false,
@@ -137276,8 +137384,8 @@ var external_skill_promote = createSwarmTool({
137276
137384
  }
137277
137385
  const targetDir = path174.join(directory, ".opencode", "skills", "generated", sanitizedSlug);
137278
137386
  const targetPath = path174.join(targetDir, "SKILL.md");
137279
- const timestamp = _internals108.getTimestamp();
137280
- const alreadyExists = await _internals108.fileExists(targetPath);
137387
+ const timestamp = _internals109.getTimestamp();
137388
+ const alreadyExists = await _internals109.fileExists(targetPath);
137281
137389
  if (alreadyExists) {
137282
137390
  return JSON.stringify({
137283
137391
  success: false,
@@ -137286,7 +137394,7 @@ var external_skill_promote = createSwarmTool({
137286
137394
  }
137287
137395
  const skillMarkdown = buildSkillMarkdown(candidate, sanitizedSlug, timestamp);
137288
137396
  try {
137289
- await _internals108.writeSkillFile(targetPath, skillMarkdown);
137397
+ await _internals109.writeSkillFile(targetPath, skillMarkdown);
137290
137398
  } catch (writeErr) {
137291
137399
  const writeError = writeErr;
137292
137400
  if (writeError?.code === "EEXIST") {
@@ -137363,7 +137471,7 @@ var external_skill_promote = createSwarmTool({
137363
137471
  init_zod();
137364
137472
  init_loader();
137365
137473
  init_create_tool();
137366
- var _internals109 = {
137474
+ var _internals110 = {
137367
137475
  loadConfig: (directory) => {
137368
137476
  const pluginConfig = loadPluginConfig(directory);
137369
137477
  return pluginConfig.external_skills;
@@ -137388,7 +137496,7 @@ var external_skill_reject = createSwarmTool({
137388
137496
  } catch {}
137389
137497
  let config3;
137390
137498
  try {
137391
- config3 = _internals109.loadConfig(directory);
137499
+ config3 = _internals110.loadConfig(directory);
137392
137500
  } catch {
137393
137501
  return JSON.stringify({
137394
137502
  success: false,
@@ -137451,7 +137559,7 @@ init_zod();
137451
137559
  init_loader();
137452
137560
  import * as path175 from "node:path";
137453
137561
  init_create_tool();
137454
- var _internals110 = {
137562
+ var _internals111 = {
137455
137563
  loadConfig: (directory) => {
137456
137564
  const pluginConfig = loadPluginConfig(directory);
137457
137565
  return pluginConfig.external_skills;
@@ -137502,7 +137610,7 @@ var external_skill_revoke = createSwarmTool({
137502
137610
  } catch {}
137503
137611
  let config3;
137504
137612
  try {
137505
- config3 = _internals110.loadConfig(directory);
137613
+ config3 = _internals111.loadConfig(directory);
137506
137614
  } catch {
137507
137615
  return JSON.stringify({
137508
137616
  success: false,
@@ -137549,8 +137657,8 @@ var external_skill_revoke = createSwarmTool({
137549
137657
  });
137550
137658
  }
137551
137659
  const skillPath = path175.join(directory, ".opencode", "skills", "generated", slug, "SKILL.md");
137552
- const skillFileRemoved = await _internals110.retireSkillFile(skillPath);
137553
- const timestamp = _internals110.getTimestamp();
137660
+ const skillFileRemoved = await _internals111.retireSkillFile(skillPath);
137661
+ const timestamp = _internals111.getTimestamp();
137554
137662
  const historyEntry = {
137555
137663
  verdict: "revoked",
137556
137664
  timestamp,
@@ -138071,7 +138179,7 @@ var ISSUE_FIELD_ALLOWLIST = new Set([
138071
138179
  "updatedAt"
138072
138180
  ]);
138073
138181
  function resolveGhBinary() {
138074
- return _internals111.resolveExecutableFromPath(["gh"]);
138182
+ return _internals112.resolveExecutableFromPath(["gh"]);
138075
138183
  }
138076
138184
  function normalizeRepo(value) {
138077
138185
  if (value === undefined || value === null || value === "")
@@ -138159,7 +138267,7 @@ var gh_evidence = createSwarmTool({
138159
138267
  if (!Array.isArray(fields)) {
138160
138268
  return JSON.stringify(fields, null, 2);
138161
138269
  }
138162
- const executable = _internals111.resolveGhBinary();
138270
+ const executable = _internals112.resolveGhBinary();
138163
138271
  if (!executable) {
138164
138272
  return JSON.stringify({
138165
138273
  error: true,
@@ -138171,7 +138279,7 @@ var gh_evidence = createSwarmTool({
138171
138279
  if (repo) {
138172
138280
  ghArgs.push("--repo", repo);
138173
138281
  }
138174
- const run = await _internals111.runExternalTool({
138282
+ const run = await _internals112.runExternalTool({
138175
138283
  executable,
138176
138284
  args: ghArgs,
138177
138285
  cwd: directory,
@@ -138222,7 +138330,7 @@ var gh_evidence = createSwarmTool({
138222
138330
  }, null, 2);
138223
138331
  }
138224
138332
  });
138225
- var _internals111 = {
138333
+ var _internals112 = {
138226
138334
  resolveExecutableFromPath,
138227
138335
  resolveGhBinary,
138228
138336
  runExternalTool
@@ -140232,7 +140340,7 @@ init_zod();
140232
140340
  init_config();
140233
140341
  init_state2();
140234
140342
  init_create_tool();
140235
- var _internals112 = {
140343
+ var _internals113 = {
140236
140344
  LeanTurboRunner,
140237
140345
  loadPluginConfigWithMeta
140238
140346
  };
@@ -140242,9 +140350,9 @@ async function executeLeanTurboRunPhase(args2) {
140242
140350
  let runError = null;
140243
140351
  let runner = null;
140244
140352
  try {
140245
- const { config: config3 } = _internals112.loadPluginConfigWithMeta(directory);
140353
+ const { config: config3 } = _internals113.loadPluginConfigWithMeta(directory);
140246
140354
  const leanConfig = config3.turbo?.strategy === "lean" ? config3.turbo.lean : undefined;
140247
- runner = new _internals112.LeanTurboRunner({
140355
+ runner = new _internals113.LeanTurboRunner({
140248
140356
  directory,
140249
140357
  sessionID,
140250
140358
  opencodeClient: swarmState.opencodeClient ?? null,
@@ -140580,7 +140688,7 @@ function isStaticallyEquivalent(originalCode, mutatedCode) {
140580
140688
  const strippedMutated = stripCode(mutatedCode);
140581
140689
  return strippedOriginal === strippedMutated;
140582
140690
  }
140583
- var _internals113 = {
140691
+ var _internals114 = {
140584
140692
  isStaticallyEquivalent,
140585
140693
  checkEquivalence,
140586
140694
  batchCheckEquivalence
@@ -140620,7 +140728,7 @@ async function batchCheckEquivalence(patches, llmJudge) {
140620
140728
  const results = [];
140621
140729
  for (const { patch, originalCode, mutatedCode } of patches) {
140622
140730
  try {
140623
- const result = await _internals113.checkEquivalence(patch, originalCode, mutatedCode, llmJudge);
140731
+ const result = await _internals114.checkEquivalence(patch, originalCode, mutatedCode, llmJudge);
140624
140732
  results.push(result);
140625
140733
  } catch (err) {
140626
140734
  results.push({
@@ -140680,7 +140788,7 @@ function validateTestCommand(testCommand) {
140680
140788
  var MUTATION_TIMEOUT_MS = 30000;
140681
140789
  var TOTAL_BUDGET_MS = 300000;
140682
140790
  var GIT_APPLY_TIMEOUT_MS = 5000;
140683
- var _internals114 = {
140791
+ var _internals115 = {
140684
140792
  executeMutation,
140685
140793
  computeReport,
140686
140794
  executeMutationSuite,
@@ -140712,7 +140820,7 @@ async function executeMutation(patch, testCommand, testFiles, workingDir) {
140712
140820
  };
140713
140821
  }
140714
140822
  try {
140715
- const applyResult = _internals114.spawnSync("git", ["apply", "--", patchFile], {
140823
+ const applyResult = _internals115.spawnSync("git", ["apply", "--", patchFile], {
140716
140824
  cwd: workingDir,
140717
140825
  timeout: GIT_APPLY_TIMEOUT_MS,
140718
140826
  stdio: "pipe"
@@ -140743,7 +140851,7 @@ async function executeMutation(patch, testCommand, testFiles, workingDir) {
140743
140851
  try {
140744
140852
  const safeTestFiles = testFiles.filter((f) => !f.startsWith("-"));
140745
140853
  const testArgs = safeTestFiles.length > 0 ? [...testCommand.slice(1), ...safeTestFiles] : testCommand.slice(1);
140746
- const spawnResult = _internals114.spawnSync(testCommand[0], testArgs, {
140854
+ const spawnResult = _internals115.spawnSync(testCommand[0], testArgs, {
140747
140855
  cwd: workingDir,
140748
140856
  timeout: MUTATION_TIMEOUT_MS,
140749
140857
  stdio: "pipe"
@@ -140776,7 +140884,7 @@ async function executeMutation(patch, testCommand, testFiles, workingDir) {
140776
140884
  } finally {
140777
140885
  if (patchFile) {
140778
140886
  try {
140779
- const revertResult = _internals114.spawnSync("git", ["apply", "-R", "--", patchFile], {
140887
+ const revertResult = _internals115.spawnSync("git", ["apply", "-R", "--", patchFile], {
140780
140888
  cwd: workingDir,
140781
140889
  timeout: GIT_APPLY_TIMEOUT_MS,
140782
140890
  stdio: "pipe"
@@ -140973,7 +141081,7 @@ async function executeMutationSuite(patches, testCommand, testFiles, workingDir,
140973
141081
  }
140974
141082
 
140975
141083
  // src/mutation/gate.ts
140976
- var _internals115 = {
141084
+ var _internals116 = {
140977
141085
  evaluateMutationGate,
140978
141086
  buildTestImprovementPrompt,
140979
141087
  buildMessage
@@ -140994,8 +141102,8 @@ function evaluateMutationGate(report, passThreshold = PASS_THRESHOLD, warnThresh
140994
141102
  } else {
140995
141103
  verdict = "fail";
140996
141104
  }
140997
- const testImprovementPrompt = _internals115.buildTestImprovementPrompt(report, passThreshold, verdict);
140998
- const message = _internals115.buildMessage(verdict, adjustedKillRate, report.killed, report.totalMutants, report.equivalent, warnThreshold);
141105
+ const testImprovementPrompt = _internals116.buildTestImprovementPrompt(report, passThreshold, verdict);
141106
+ const message = _internals116.buildMessage(verdict, adjustedKillRate, report.killed, report.totalMutants, report.equivalent, warnThreshold);
140999
141107
  return {
141000
141108
  verdict,
141001
141109
  killRate: report.killRate,
@@ -141140,7 +141248,7 @@ var OSV_MAX_STDERR_BYTES = 256 * 1024;
141140
141248
  var DEFAULT_MAX_RESULTS3 = 200;
141141
141249
  var HARD_CAP_RESULTS3 = 2000;
141142
141250
  function resolveOsvScannerBinary() {
141143
- return _internals116.resolveExecutableFromPath(["osv-scanner"]);
141251
+ return _internals117.resolveExecutableFromPath(["osv-scanner"]);
141144
141252
  }
141145
141253
  function normalizeScanPath(value, workspace) {
141146
141254
  const raw = typeof value === "string" && value.trim() ? value.trim() : ".";
@@ -141228,7 +141336,7 @@ var osv_scan = createSwarmTool({
141228
141336
  }, null, 2);
141229
141337
  }
141230
141338
  const maxResults = sanitizeMaxResults2(obj.max_results);
141231
- const executable = _internals116.resolveOsvScannerBinary();
141339
+ const executable = _internals117.resolveOsvScannerBinary();
141232
141340
  if (!executable) {
141233
141341
  return JSON.stringify({
141234
141342
  error: true,
@@ -141238,7 +141346,7 @@ var osv_scan = createSwarmTool({
141238
141346
  }
141239
141347
  const target = scanPath === "." ? "." : `./${scanPath}`;
141240
141348
  const osvArgs = ["scan", "--format", "json", target];
141241
- const run = await _internals116.runExternalTool({
141349
+ const run = await _internals117.runExternalTool({
141242
141350
  executable,
141243
141351
  args: osvArgs,
141244
141352
  cwd: directory,
@@ -141288,7 +141396,7 @@ var osv_scan = createSwarmTool({
141288
141396
  }, null, 2);
141289
141397
  }
141290
141398
  });
141291
- var _internals116 = {
141399
+ var _internals117 = {
141292
141400
  resolveExecutableFromPath,
141293
141401
  resolveOsvScannerBinary,
141294
141402
  runExternalTool,
@@ -142092,6 +142200,7 @@ var parse_lane_candidates = createSwarmTool({
142092
142200
  // src/tools/phase-complete.ts
142093
142201
  init_zod();
142094
142202
  init_config();
142203
+ init_plan_schema();
142095
142204
  init_schema();
142096
142205
  init_manager2();
142097
142206
  init_task_file();
@@ -142986,7 +143095,7 @@ function listLaneEvidenceSync(directory, phase) {
142986
143095
  }
142987
143096
  return laneIds;
142988
143097
  }
142989
- var _internals117 = {
143098
+ var _internals118 = {
142990
143099
  listActiveLocks,
142991
143100
  readPersisted: readPersisted3,
142992
143101
  readPlanJson: defaultReadPlanJson,
@@ -143047,7 +143156,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
143047
143156
  reason: "Lean Turbo state unreadable or missing"
143048
143157
  };
143049
143158
  }
143050
- const persisted = _internals117.readPersisted(directory);
143159
+ const persisted = _internals118.readPersisted(directory);
143051
143160
  if (!persisted) {
143052
143161
  return {
143053
143162
  ok: false,
@@ -143111,7 +143220,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
143111
143220
  }
143112
143221
  }
143113
143222
  if (runState.lanes.length > 0) {
143114
- const evidenceLaneIds = new Set(_internals117.listLaneEvidenceSync(directory, phase));
143223
+ const evidenceLaneIds = new Set(_internals118.listLaneEvidenceSync(directory, phase));
143115
143224
  for (const lane of runState.lanes) {
143116
143225
  if ((lane.status === "completed" || lane.status === "failed") && !evidenceLaneIds.has(lane.laneId)) {
143117
143226
  return {
@@ -143121,7 +143230,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
143121
143230
  }
143122
143231
  }
143123
143232
  }
143124
- const activeLocks = _internals117.listActiveLocks(directory);
143233
+ const activeLocks = _internals118.listActiveLocks(directory);
143125
143234
  const phaseLaneIds = new Set(laneIds);
143126
143235
  for (const lock of activeLocks) {
143127
143236
  if (lock.laneId && phaseLaneIds.has(lock.laneId)) {
@@ -143141,7 +143250,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
143141
143250
  }
143142
143251
  const serialDegradedTasks = runState.degradedTasks.filter((dt) => !laneTaskIds.has(dt.taskId));
143143
143252
  if (serialDegradedTasks.length > 0) {
143144
- const plan = _internals117.readPlanJson(directory);
143253
+ const plan = _internals118.readPlanJson(directory);
143145
143254
  if (!plan) {
143146
143255
  return {
143147
143256
  ok: false,
@@ -143185,7 +143294,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
143185
143294
  }
143186
143295
  const serializedTasks = runState.serializedTasks;
143187
143296
  if (Array.isArray(serializedTasks) && serializedTasks.length > 0) {
143188
- const plan = _internals117.readPlanJson(directory);
143297
+ const plan = _internals118.readPlanJson(directory);
143189
143298
  if (!plan) {
143190
143299
  return {
143191
143300
  ok: false,
@@ -143244,7 +143353,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
143244
143353
  }
143245
143354
  let reviewerVerdict = runState.lastReviewerVerdict;
143246
143355
  if (!reviewerVerdict) {
143247
- const evidence = _internals117.readReviewerEvidence(directory, phase);
143356
+ const evidence = _internals118.readReviewerEvidence(directory, phase);
143248
143357
  reviewerVerdict = evidence?.verdict ?? undefined;
143249
143358
  }
143250
143359
  if (mergedConfig.phase_reviewer) {
@@ -143257,7 +143366,7 @@ function verifyLeanTurboPhaseReady(directory, phase, sessionIDOrConfig, config3)
143257
143366
  }
143258
143367
  let criticVerdict = runState.lastCriticVerdict;
143259
143368
  if (!criticVerdict) {
143260
- const evidence = _internals117.readCriticEvidence(directory, phase);
143369
+ const evidence = _internals118.readCriticEvidence(directory, phase);
143261
143370
  criticVerdict = evidence?.verdict ?? undefined;
143262
143371
  }
143263
143372
  if (mergedConfig.phase_critic) {
@@ -144243,6 +144352,29 @@ function collectCrossSessionDispatchedAgents(phaseReferenceTimestamp, callerSess
144243
144352
  }
144244
144353
  return { agents, contributorSessionIds };
144245
144354
  }
144355
+ async function fallbackWritePlanWithTrace(dir, planPath, candidate, phase, warnings) {
144356
+ const validation2 = PlanSchema.safeParse(candidate);
144357
+ if (!validation2.success) {
144358
+ const detail = validation2.error.issues.slice(0, 5).map((issue3) => `${issue3.path.join(".") || "<root>"}: ${issue3.message}`).join("; ");
144359
+ warn("[phase_complete] Last-resort plan.json write aborted — mutated plan failed PlanSchema validation:", detail);
144360
+ warnings.push(`Warning: last-resort plan.json write skipped — mutated plan failed schema validation (${detail})`);
144361
+ return false;
144362
+ }
144363
+ await atomicWriteFile(planPath, JSON.stringify(validation2.data, null, 2));
144364
+ try {
144365
+ const traceEvent = {
144366
+ event: "phase_complete_fallback_write",
144367
+ phase,
144368
+ timestamp: new Date().toISOString()
144369
+ };
144370
+ const eventsPath = validateSwarmPath(dir, "events.jsonl");
144371
+ fs125.appendFileSync(eventsPath, `${JSON.stringify(traceEvent)}
144372
+ `, "utf-8");
144373
+ } catch (eventError) {
144374
+ warnings.push(`Warning: failed to record phase_complete_fallback_write trace event: ${eventError instanceof Error ? eventError.message : String(eventError)}`);
144375
+ }
144376
+ return true;
144377
+ }
144246
144378
  function _getDelegationsSince(sessionID, sinceTimestamp) {
144247
144379
  const chain = swarmState.delegationChains.get(sessionID);
144248
144380
  if (!chain) {
@@ -144548,7 +144680,7 @@ async function executePhaseComplete(args2, workingDirectory, directory) {
144548
144680
  phase_critic: leanConfig.phase_critic,
144549
144681
  integrated_diff_required: leanConfig.integrated_diff_required
144550
144682
  } : undefined;
144551
- const leanCheck = _internals117.verifyLeanTurboPhaseReady(dir, phase, sessionID, leanPhaseReadyConfig);
144683
+ const leanCheck = _internals118.verifyLeanTurboPhaseReady(dir, phase, sessionID, leanPhaseReadyConfig);
144552
144684
  if (!leanCheck.ok) {
144553
144685
  return JSON.stringify({
144554
144686
  success: false,
@@ -144959,6 +145091,22 @@ async function executePhaseComplete(args2, workingDirectory, directory) {
144959
145091
  }
144960
145092
  try {
144961
145093
  const plan = await loadPlan(dir);
145094
+ const runtimePlan = plan;
145095
+ if (runtimePlan?._ledgerReplayStale === true) {
145096
+ const staleReason = runtimePlan._ledgerReplayStaleReason ?? "unknown reason";
145097
+ return JSON.stringify({
145098
+ success: false,
145099
+ phase: args2.phase,
145100
+ status: "incomplete",
145101
+ message: `Plan write refused: plan.json is stale from a failed ledger replay (${staleReason}). Refusing to complete phase ${args2.phase} against a known-stale plan.`,
145102
+ agentsDispatched,
145103
+ agentsMissing,
145104
+ warnings,
145105
+ errors: [`Stale plan from failed ledger replay: ${staleReason}`],
145106
+ recovery_guidance: "The ledger replay failed and no critic-approved snapshot was available, so loadPlan fell back to a stale plan.json. Do NOT retry blindly. Recover first: re-verify the plan (re-run completion verification), reset the session, or restore from the latest checkpoint under .swarm/plan-export/, then retry phase_complete.",
145107
+ _ledgerReplayStaleReason: staleReason
145108
+ });
145109
+ }
144962
145110
  if (plan === null) {
144963
145111
  if (await ledgerExists(dir)) {
144964
145112
  try {
@@ -144985,7 +145133,7 @@ async function executePhaseComplete(args2, workingDirectory, directory) {
144985
145133
  const phaseObj = plan2.phases.find((p) => p.id === phase);
144986
145134
  if (phaseObj) {
144987
145135
  phaseObj.status = "complete";
144988
- await atomicWriteFile(planPath, JSON.stringify(plan2, null, 2));
145136
+ await fallbackWritePlanWithTrace(dir, planPath, plan2, phase, warnings);
144989
145137
  }
144990
145138
  } catch {}
144991
145139
  } else if (plan) {
@@ -145027,7 +145175,7 @@ async function executePhaseComplete(args2, workingDirectory, directory) {
145027
145175
  const phaseObj = plan.phases.find((p) => p.id === phase);
145028
145176
  if (phaseObj) {
145029
145177
  phaseObj.status = "complete";
145030
- await atomicWriteFile(planPath, JSON.stringify(plan, null, 2));
145178
+ await fallbackWritePlanWithTrace(dir, planPath, plan, phase, warnings);
145031
145179
  }
145032
145180
  } catch {}
145033
145181
  } finally {
@@ -146945,11 +147093,11 @@ var quality_budget = createSwarmTool({
146945
147093
  }).optional().describe("Quality budget thresholds")
146946
147094
  },
146947
147095
  async execute(args2, directory) {
146948
- const result = await _internals119.qualityBudget(args2, directory);
147096
+ const result = await _internals120.qualityBudget(args2, directory);
146949
147097
  return JSON.stringify(result);
146950
147098
  }
146951
147099
  });
146952
- var _internals119 = {
147100
+ var _internals120 = {
146953
147101
  qualityBudget
146954
147102
  };
146955
147103
 
@@ -147674,7 +147822,7 @@ var DEFAULT_RULES_DIR = ".swarm/semgrep-rules";
147674
147822
  var DEFAULT_TIMEOUT_MS4 = 30000;
147675
147823
  var MAX_OUTPUT_BYTES8 = 10 * 1024 * 1024;
147676
147824
  var KILL_GRACE_MS = 2000;
147677
- var _internals120 = {
147825
+ var _internals121 = {
147678
147826
  isSemgrepAvailable,
147679
147827
  checkSemgrepAvailable,
147680
147828
  resetSemgrepCache,
@@ -147700,7 +147848,7 @@ function isSemgrepAvailable() {
147700
147848
  }
147701
147849
  }
147702
147850
  async function checkSemgrepAvailable() {
147703
- return _internals120.isSemgrepAvailable();
147851
+ return _internals121.isSemgrepAvailable();
147704
147852
  }
147705
147853
  function resetSemgrepCache() {
147706
147854
  semgrepAvailableCache = null;
@@ -147886,12 +148034,12 @@ async function runSemgrep(options) {
147886
148034
  const timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS4;
147887
148035
  if (files.length === 0) {
147888
148036
  return {
147889
- available: _internals120.isSemgrepAvailable(),
148037
+ available: _internals121.isSemgrepAvailable(),
147890
148038
  findings: [],
147891
148039
  engine: "tier_a"
147892
148040
  };
147893
148041
  }
147894
- if (!_internals120.isSemgrepAvailable()) {
148042
+ if (!_internals121.isSemgrepAvailable()) {
147895
148043
  return {
147896
148044
  available: false,
147897
148045
  findings: [],
@@ -148058,7 +148206,7 @@ function assignOccurrenceIndices(findings, directory) {
148058
148206
  }
148059
148207
  const occIdx = countMap.get(baseKey) ?? 0;
148060
148208
  countMap.set(baseKey, occIdx + 1);
148061
- const fp = _internals121.fingerprintFinding(finding, directory, occIdx);
148209
+ const fp = _internals122.fingerprintFinding(finding, directory, occIdx);
148062
148210
  return {
148063
148211
  finding,
148064
148212
  index: occIdx,
@@ -148127,7 +148275,7 @@ async function captureOrMergeBaseline(directory, phase, findings, engine, scanne
148127
148275
  }
148128
148276
  } catch {}
148129
148277
  const scannedRelFiles = new Set(scannedFiles.map((f) => normalizeFindingPath(directory, f)));
148130
- const indexed = _internals121.assignOccurrenceIndices(findings, directory);
148278
+ const indexed = _internals122.assignOccurrenceIndices(findings, directory);
148131
148279
  if (existing && !opts?.force) {
148132
148280
  const prunedFingerprints = existing.fingerprints.filter((fp) => {
148133
148281
  const relFile = fp.slice(0, fp.indexOf("|"));
@@ -148267,7 +148415,7 @@ function loadBaseline(directory, phase) {
148267
148415
  };
148268
148416
  }
148269
148417
  }
148270
- var _internals121 = {
148418
+ var _internals122 = {
148271
148419
  fingerprintFinding,
148272
148420
  assignOccurrenceIndices,
148273
148421
  captureOrMergeBaseline,
@@ -148677,11 +148825,11 @@ var sast_scan = createSwarmTool({
148677
148825
  capture_baseline: safeArgs.capture_baseline,
148678
148826
  phase: safeArgs.phase
148679
148827
  };
148680
- const result = await _internals122.sastScan(input, directory);
148828
+ const result = await _internals123.sastScan(input, directory);
148681
148829
  return JSON.stringify(result, null, 2);
148682
148830
  }
148683
148831
  });
148684
- var _internals122 = {
148832
+ var _internals123 = {
148685
148833
  sastScan,
148686
148834
  sast_scan
148687
148835
  };
@@ -152255,10 +152403,10 @@ function resolvePackagedRipgrep() {
152255
152403
  }
152256
152404
  }
152257
152405
  function resolveRipgrepBinary() {
152258
- return _internals123.resolvePackagedRipgrep() ?? _internals123.resolveExecutableFromPath(["rg"]);
152406
+ return _internals124.resolvePackagedRipgrep() ?? _internals124.resolveExecutableFromPath(["rg"]);
152259
152407
  }
152260
152408
  async function ripgrepSearch(opts) {
152261
- const rgPath = _internals123.resolveRipgrepBinary();
152409
+ const rgPath = _internals124.resolveRipgrepBinary();
152262
152410
  if (!rgPath) {
152263
152411
  return {
152264
152412
  error: true,
@@ -152281,7 +152429,7 @@ async function ripgrepSearch(opts) {
152281
152429
  args2.push("--fixed-strings");
152282
152430
  }
152283
152431
  args2.push("--", opts.query, ".");
152284
- const run = await _internals123.runExternalTool({
152432
+ const run = await _internals124.runExternalTool({
152285
152433
  executable: rgPath,
152286
152434
  args: args2,
152287
152435
  cwd: opts.workspace,
@@ -152585,7 +152733,7 @@ var search = createSwarmTool({
152585
152733
  }, null, 2);
152586
152734
  }
152587
152735
  let result;
152588
- if (_internals123.resolveRipgrepBinary()) {
152736
+ if (_internals124.resolveRipgrepBinary()) {
152589
152737
  result = await ripgrepSearch({
152590
152738
  query,
152591
152739
  mode,
@@ -152612,7 +152760,7 @@ var search = createSwarmTool({
152612
152760
  return JSON.stringify(result, null, 2);
152613
152761
  }
152614
152762
  });
152615
- var _internals123 = {
152763
+ var _internals124 = {
152616
152764
  resolvePackagedRipgrep,
152617
152765
  resolveExecutableFromPath,
152618
152766
  resolveRipgrepBinary,
@@ -152973,18 +153121,18 @@ var run_stale_reconciliation = createSwarmTool({
152973
153121
  if (typeof directory !== "string" || !directory) {
152974
153122
  return JSON.stringify({ found: 0, skills: [] }, null, 2);
152975
153123
  }
152976
- const archivedIds = await _internals124.getArchivedKnowledgeIds(directory);
153124
+ const archivedIds = await _internals125.getArchivedKnowledgeIds(directory);
152977
153125
  const archivedSet = new Set(archivedIds);
152978
153126
  const allKnownIds = new Set;
152979
- const swarmPath = _internals124.resolveSwarmKnowledgePath(directory);
152980
- const hivePath = _internals124.resolveHiveKnowledgePath();
153127
+ const swarmPath = _internals125.resolveSwarmKnowledgePath(directory);
153128
+ const hivePath = _internals125.resolveHiveKnowledgePath();
152981
153129
  try {
152982
- const swarmEntries = await _internals124.readKnowledge(swarmPath);
153130
+ const swarmEntries = await _internals125.readKnowledge(swarmPath);
152983
153131
  for (const e of swarmEntries)
152984
153132
  allKnownIds.add(e.id);
152985
153133
  } catch {}
152986
153134
  try {
152987
- const hiveEntries = await _internals124.readKnowledge(hivePath);
153135
+ const hiveEntries = await _internals125.readKnowledge(hivePath);
152988
153136
  for (const e of hiveEntries)
152989
153137
  allKnownIds.add(e.id);
152990
153138
  } catch {}
@@ -152993,9 +153141,9 @@ var run_stale_reconciliation = createSwarmTool({
152993
153141
  join166(directory, ".opencode", "skills", "generated"),
152994
153142
  join166(directory, ".swarm", "skills", "proposals")
152995
153143
  ]) {
152996
- if (!_internals124.existsSync(dir))
153144
+ if (!_internals125.existsSync(dir))
152997
153145
  continue;
152998
- const entries = await _internals124.readdir(dir, { withFileTypes: true });
153146
+ const entries = await _internals125.readdir(dir, { withFileTypes: true });
152999
153147
  for (const entry of entries) {
153000
153148
  if (entry.isDirectory()) {
153001
153149
  skillEntries.push({
@@ -153016,10 +153164,10 @@ var run_stale_reconciliation = createSwarmTool({
153016
153164
  const results = [];
153017
153165
  for (const { slug, path: path210, isProposal } of skillEntries) {
153018
153166
  const skillMdPath = isProposal ? path210 : join166(path210, "SKILL.md");
153019
- if (!_internals124.existsSync(skillMdPath))
153167
+ if (!_internals125.existsSync(skillMdPath))
153020
153168
  continue;
153021
- const content = await _internals124.readFile(skillMdPath, "utf-8");
153022
- const fm = _internals124.parseDraftFrontmatter(content);
153169
+ const content = await _internals125.readFile(skillMdPath, "utf-8");
153170
+ const fm = _internals125.parseDraftFrontmatter(content);
153023
153171
  const sourceIds = fm?.sourceKnowledgeIds ?? [];
153024
153172
  if (sourceIds.length === 0)
153025
153173
  continue;
@@ -153029,9 +153177,9 @@ var run_stale_reconciliation = createSwarmTool({
153029
153177
  if (args2.clear) {
153030
153178
  if (!isProposal) {
153031
153179
  const markerPath = join166(path210, "stale.marker");
153032
- if (_internals124.existsSync(markerPath)) {
153180
+ if (_internals125.existsSync(markerPath)) {
153033
153181
  try {
153034
- await _internals124.clearSkillStale(path210);
153182
+ await _internals125.clearSkillStale(path210);
153035
153183
  results.push({
153036
153184
  slug,
153037
153185
  reason: affected.join(", "),
@@ -153043,7 +153191,7 @@ var run_stale_reconciliation = createSwarmTool({
153043
153191
  } else {
153044
153192
  if (!isProposal) {
153045
153193
  try {
153046
- await _internals124.retireOrMarkStale(directory, path210, archivedSet);
153194
+ await _internals125.retireOrMarkStale(directory, path210, archivedSet);
153047
153195
  results.push({
153048
153196
  slug,
153049
153197
  reason: affected.join(", "),
@@ -153056,7 +153204,7 @@ var run_stale_reconciliation = createSwarmTool({
153056
153204
  return JSON.stringify({ found: results.length, skills: results }, null, 2);
153057
153205
  }
153058
153206
  });
153059
- var _internals124 = {
153207
+ var _internals125 = {
153060
153208
  run_stale_reconciliation,
153061
153209
  clearSkillStale,
153062
153210
  retireOrMarkStale,
@@ -154034,7 +154182,7 @@ var swarm_memory_propose = createSwarmTool({
154034
154182
  evidenceRefs: exports_external.array(exports_external.string().min(1).max(500)).max(20).optional().describe("Evidence refs such as files, commits, test outputs, or URLs")
154035
154183
  },
154036
154184
  execute: async (args2, directory, ctx) => {
154037
- const { config: config3 } = _internals125.loadPluginConfigWithMeta(directory);
154185
+ const { config: config3 } = _internals126.loadPluginConfigWithMeta(directory);
154038
154186
  if (config3.memory?.enabled !== true) {
154039
154187
  return JSON.stringify({
154040
154188
  success: false,
@@ -154050,7 +154198,7 @@ var swarm_memory_propose = createSwarmTool({
154050
154198
  });
154051
154199
  }
154052
154200
  const agent = getContextAgent3(ctx);
154053
- const gateway = _internals125.createMemoryGateway({
154201
+ const gateway = _internals126.createMemoryGateway({
154054
154202
  directory,
154055
154203
  sessionID: ctx?.sessionID,
154056
154204
  agentRole: agent,
@@ -154075,7 +154223,7 @@ var swarm_memory_propose = createSwarmTool({
154075
154223
  }
154076
154224
  }
154077
154225
  });
154078
- var _internals125 = {
154226
+ var _internals126 = {
154079
154227
  loadPluginConfigWithMeta,
154080
154228
  createMemoryGateway
154081
154229
  };
@@ -154113,7 +154261,7 @@ var swarm_memory_recall = createSwarmTool({
154113
154261
  maxItems: exports_external.number().int().min(1).max(20).optional().describe("Maximum memories to return")
154114
154262
  },
154115
154263
  execute: async (args2, directory, ctx) => {
154116
- const { config: config3 } = _internals126.loadPluginConfigWithMeta(directory);
154264
+ const { config: config3 } = _internals127.loadPluginConfigWithMeta(directory);
154117
154265
  if (config3.memory?.enabled !== true) {
154118
154266
  return JSON.stringify({
154119
154267
  success: false,
@@ -154129,7 +154277,7 @@ var swarm_memory_recall = createSwarmTool({
154129
154277
  });
154130
154278
  }
154131
154279
  const agent = getContextAgent4(ctx);
154132
- const gateway = _internals126.createMemoryGateway({
154280
+ const gateway = _internals127.createMemoryGateway({
154133
154281
  directory,
154134
154282
  sessionID: ctx?.sessionID,
154135
154283
  agentRole: agent,
@@ -154162,7 +154310,7 @@ var RecallArgsSchema = exports_external.object({
154162
154310
  kinds: exports_external.array(exports_external.enum(MEMORY_KINDS2)).optional(),
154163
154311
  maxItems: exports_external.number().int().min(1).max(20).optional()
154164
154312
  });
154165
- var _internals126 = {
154313
+ var _internals127 = {
154166
154314
  loadPluginConfigWithMeta,
154167
154315
  createMemoryGateway
154168
154316
  };
@@ -154688,7 +154836,7 @@ import * as path215 from "node:path";
154688
154836
  init_bun_compat();
154689
154837
  import * as fs140 from "node:fs";
154690
154838
  import * as path214 from "node:path";
154691
- var _internals127 = { bunSpawn };
154839
+ var _internals128 = { bunSpawn };
154692
154840
  var _swarmGitExcludedChecked = false;
154693
154841
  function fileCoversSwarm(content) {
154694
154842
  for (const rawLine of content.split(`
@@ -154721,7 +154869,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
154721
154869
  checkIgnoreExitCode
154722
154870
  ] = await Promise.all([
154723
154871
  (async () => {
154724
- const proc = _internals127.bunSpawn(["git", "-C", directory, "rev-parse", "--show-toplevel"], GIT_SPAWN_OPTIONS);
154872
+ const proc = _internals128.bunSpawn(["git", "-C", directory, "rev-parse", "--show-toplevel"], GIT_SPAWN_OPTIONS);
154725
154873
  try {
154726
154874
  return await Promise.all([proc.exited, proc.stdout.text()]);
154727
154875
  } finally {
@@ -154731,7 +154879,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
154731
154879
  }
154732
154880
  })(),
154733
154881
  (async () => {
154734
- const proc = _internals127.bunSpawn(["git", "-C", directory, "rev-parse", "--git-path", "info/exclude"], GIT_SPAWN_OPTIONS);
154882
+ const proc = _internals128.bunSpawn(["git", "-C", directory, "rev-parse", "--git-path", "info/exclude"], GIT_SPAWN_OPTIONS);
154735
154883
  try {
154736
154884
  return await Promise.all([proc.exited, proc.stdout.text()]);
154737
154885
  } finally {
@@ -154741,7 +154889,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
154741
154889
  }
154742
154890
  })(),
154743
154891
  (async () => {
154744
- const proc = _internals127.bunSpawn(["git", "-C", directory, "check-ignore", "-q", ".swarm/.gitkeep"], GIT_SPAWN_OPTIONS);
154892
+ const proc = _internals128.bunSpawn(["git", "-C", directory, "check-ignore", "-q", ".swarm/.gitkeep"], GIT_SPAWN_OPTIONS);
154745
154893
  try {
154746
154894
  return await proc.exited;
154747
154895
  } finally {
@@ -154780,7 +154928,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
154780
154928
  }
154781
154929
  } catch {}
154782
154930
  }
154783
- const trackedProc = _internals127.bunSpawn(["git", "-C", directory, "ls-files", "--", ".swarm"], GIT_SPAWN_OPTIONS);
154931
+ const trackedProc = _internals128.bunSpawn(["git", "-C", directory, "ls-files", "--", ".swarm"], GIT_SPAWN_OPTIONS);
154784
154932
  let trackedExitCode;
154785
154933
  let trackedOutput;
154786
154934
  try {
@@ -154805,7 +154953,7 @@ async function ensureSwarmGitExcluded(directory, options = {}) {
154805
154953
  }
154806
154954
 
154807
154955
  // src/hooks/diff-scope.ts
154808
- var _internals128 = { bunSpawn };
154956
+ var _internals129 = { bunSpawn };
154809
154957
  function getDeclaredScope(taskId, directory) {
154810
154958
  try {
154811
154959
  const planPath = path215.join(directory, ".swarm", "plan.json");
@@ -154840,7 +154988,7 @@ var GIT_DIFF_SPAWN_OPTIONS = {
154840
154988
  };
154841
154989
  async function getChangedFiles2(directory) {
154842
154990
  try {
154843
- const proc = _internals128.bunSpawn(["git", "diff", "--name-only", "HEAD~1"], {
154991
+ const proc = _internals129.bunSpawn(["git", "diff", "--name-only", "HEAD~1"], {
154844
154992
  cwd: directory,
154845
154993
  ...GIT_DIFF_SPAWN_OPTIONS
154846
154994
  });
@@ -154857,7 +155005,7 @@ async function getChangedFiles2(directory) {
154857
155005
  return stdout.trim().split(`
154858
155006
  `).map((f) => f.trim()).filter((f) => f.length > 0);
154859
155007
  }
154860
- const proc2 = _internals128.bunSpawn(["git", "diff", "--name-only", "HEAD"], {
155008
+ const proc2 = _internals129.bunSpawn(["git", "diff", "--name-only", "HEAD"], {
154861
155009
  cwd: directory,
154862
155010
  ...GIT_DIFF_SPAWN_OPTIONS
154863
155011
  });
@@ -154916,7 +155064,7 @@ init_telemetry();
154916
155064
  init_file_locks();
154917
155065
  import * as fs142 from "node:fs";
154918
155066
  import * as path216 from "node:path";
154919
- var _internals129 = {
155067
+ var _internals130 = {
154920
155068
  listActiveLocks,
154921
155069
  verifyLeanTurboTaskCompletion
154922
155070
  };
@@ -155058,7 +155206,7 @@ function verifyLeanTurboTaskCompletion(directory, taskId, sessionID) {
155058
155206
  }
155059
155207
  };
155060
155208
  }
155061
- const activeLocks = _internals129.listActiveLocks(directory);
155209
+ const activeLocks = _internals130.listActiveLocks(directory);
155062
155210
  const laneLocks = activeLocks.filter((lock) => lock.laneId === lane.laneId);
155063
155211
  if (laneLocks.length > 0) {
155064
155212
  return {
@@ -155125,10 +155273,11 @@ function verifyLeanTurboTaskCompletion(directory, taskId, sessionID) {
155125
155273
  init_task_id();
155126
155274
  init_create_tool();
155127
155275
  init_resolve_working_directory();
155128
- var _internals130 = {
155276
+ var _internals131 = {
155129
155277
  tryAcquireLock,
155130
155278
  updateTaskStatus,
155131
- resolveWorkingDirectory
155279
+ resolveWorkingDirectory,
155280
+ loadPlan
155132
155281
  };
155133
155282
  var VALID_STATUSES2 = [
155134
155283
  "pending",
@@ -155222,7 +155371,7 @@ function checkReviewerGate(taskId, workingDirectory, stageBParallelEnabled = fal
155222
155371
  }
155223
155372
  let resolvedDir;
155224
155373
  if (fallbackDir) {
155225
- const resolveResult = _internals130.resolveWorkingDirectory(workingDirectory, fallbackDir);
155374
+ const resolveResult = _internals131.resolveWorkingDirectory(workingDirectory, fallbackDir);
155226
155375
  if (resolveResult.success) {
155227
155376
  resolvedDir = resolveResult.directory;
155228
155377
  } else {
@@ -155569,7 +155718,7 @@ async function executeUpdateTaskStatus(args2, fallbackDir, ctx) {
155569
155718
  }
155570
155719
  }
155571
155720
  let directory;
155572
- const resolveResult = _internals130.resolveWorkingDirectory(args2.working_directory, fallbackDir);
155721
+ const resolveResult = _internals131.resolveWorkingDirectory(args2.working_directory, fallbackDir);
155573
155722
  if (!resolveResult.success) {
155574
155723
  return {
155575
155724
  success: false,
@@ -155599,6 +155748,21 @@ async function executeUpdateTaskStatus(args2, fallbackDir, ctx) {
155599
155748
  };
155600
155749
  }
155601
155750
  }
155751
+ let loadedPlan = null;
155752
+ try {
155753
+ loadedPlan = await _internals131.loadPlan(directory);
155754
+ } catch {
155755
+ loadedPlan = null;
155756
+ }
155757
+ if (loadedPlan?._ledgerReplayStale === true) {
155758
+ const staleReason = loadedPlan._ledgerReplayStaleReason ?? "plan.json is stale relative to the authoritative ledger (.swarm/plan-ledger.jsonl)";
155759
+ return {
155760
+ success: false,
155761
+ message: `Task status update refused: plan.json is stale relative to the ledger (ledger replay failed). ${staleReason}`,
155762
+ errors: [staleReason],
155763
+ recovery_guidance: "Plan state could not be reconciled with the authoritative ledger (.swarm/plan-ledger.jsonl). " + "Restore from a critic-approved snapshot or re-run plan recovery to rebuild plan.json from the ledger, then retry update_task_status."
155764
+ };
155765
+ }
155602
155766
  if (args2.status === "in_progress") {
155603
155767
  try {
155604
155768
  const evidencePath = path217.join(directory, ".swarm", "evidence", `${args2.task_id}.json`);
@@ -155662,7 +155826,7 @@ async function executeUpdateTaskStatus(args2, fallbackDir, ctx) {
155662
155826
  }
155663
155827
  let lockResult;
155664
155828
  try {
155665
- lockResult = await _internals130.tryAcquireLock(directory, planFilePath, agentName, lockTaskId);
155829
+ lockResult = await _internals131.tryAcquireLock(directory, planFilePath, agentName, lockTaskId);
155666
155830
  } catch (error93) {
155667
155831
  return {
155668
155832
  success: false,
@@ -155681,7 +155845,7 @@ async function executeUpdateTaskStatus(args2, fallbackDir, ctx) {
155681
155845
  };
155682
155846
  }
155683
155847
  try {
155684
- const updatedPlan = await _internals130.updateTaskStatus(directory, args2.task_id, args2.status);
155848
+ const updatedPlan = await _internals131.updateTaskStatus(directory, args2.task_id, args2.status);
155685
155849
  if (args2.status === "completed") {
155686
155850
  for (const [_sessionId, session] of swarmState.agentSessions) {
155687
155851
  if (!(session.taskWorkflowStates instanceof Map)) {
@@ -156336,7 +156500,7 @@ var web_fetch = createSwarmTool({
156336
156500
  };
156337
156501
  return JSON.stringify(fail, null, 2);
156338
156502
  }
156339
- const config3 = _internals131.loadPluginConfig(dirResult.directory);
156503
+ const config3 = _internals132.loadPluginConfig(dirResult.directory);
156340
156504
  const generalConfig = config3.council?.general;
156341
156505
  if (!generalConfig || generalConfig.enabled !== true) {
156342
156506
  const fail = {
@@ -156346,7 +156510,7 @@ var web_fetch = createSwarmTool({
156346
156510
  };
156347
156511
  return JSON.stringify(fail, null, 2);
156348
156512
  }
156349
- const validated = await validateFetchUrl(parsed.data.url, _internals131.dnsLookup);
156513
+ const validated = await validateFetchUrl(parsed.data.url, _internals132.dnsLookup);
156350
156514
  if (!validated.ok) {
156351
156515
  const fail = {
156352
156516
  success: false,
@@ -156357,7 +156521,7 @@ var web_fetch = createSwarmTool({
156357
156521
  }
156358
156522
  const maxBytes = parsed.data.max_bytes ?? DEFAULT_MAX_BYTES;
156359
156523
  const timeoutMs = parsed.data.timeout_ms ?? DEFAULT_TIMEOUT_MS5;
156360
- const result = await boundedFetch({ url: validated.url, address: validated.address }, maxBytes, timeoutMs, _internals131);
156524
+ const result = await boundedFetch({ url: validated.url, address: validated.address }, maxBytes, timeoutMs, _internals132);
156361
156525
  if (!result.ok) {
156362
156526
  const fail = {
156363
156527
  success: false,
@@ -156392,7 +156556,7 @@ var web_fetch = createSwarmTool({
156392
156556
  });
156393
156557
  async function captureFetchEvidence(directory, url3, title, text) {
156394
156558
  try {
156395
- const written = await _internals131.writeEvidenceDocuments(directory, [
156559
+ const written = await _internals132.writeEvidenceDocuments(directory, [
156396
156560
  {
156397
156561
  sourceType: "crawl",
156398
156562
  url: url3,
@@ -156413,7 +156577,7 @@ async function captureFetchEvidence(directory, url3, title, text) {
156413
156577
  };
156414
156578
  }
156415
156579
  }
156416
- var _internals131 = {
156580
+ var _internals132 = {
156417
156581
  httpRequest: performHttpRequest,
156418
156582
  dnsLookup: lookup,
156419
156583
  loadPluginConfig,
@@ -156727,7 +156891,7 @@ var web_search = createSwarmTool({
156727
156891
  });
156728
156892
  async function captureSearchEvidence(directory, query, results) {
156729
156893
  try {
156730
- const written = await _internals132.writeEvidenceDocuments(directory, results.map((result) => ({
156894
+ const written = await _internals133.writeEvidenceDocuments(directory, results.map((result) => ({
156731
156895
  sourceType: "web_search",
156732
156896
  query,
156733
156897
  title: result.title,
@@ -156755,7 +156919,7 @@ async function captureSearchEvidence(directory, query, results) {
156755
156919
  };
156756
156920
  }
156757
156921
  }
156758
- var _internals132 = {
156922
+ var _internals133 = {
156759
156923
  writeEvidenceDocuments
156760
156924
  };
156761
156925
 
@@ -156963,7 +157127,7 @@ async function executeWriteDriftEvidence(args2, directory) {
156963
157127
  message: "Invalid summary: must be a non-empty string"
156964
157128
  }, null, 2);
156965
157129
  }
156966
- const normalizedVerdict = _internals133.normalizeVerdict2(args2.verdict);
157130
+ const normalizedVerdict = _internals134.normalizeVerdict2(args2.verdict);
156967
157131
  const provenance = args2.provenanceAgentName || args2.provenanceSessionId ? {
156968
157132
  agent_name: args2.provenanceAgentName,
156969
157133
  session_id: args2.provenanceSessionId,
@@ -157060,7 +157224,7 @@ async function executeWriteDriftEvidence(args2, directory) {
157060
157224
  }, null, 2);
157061
157225
  }
157062
157226
  }
157063
- var _internals133 = {
157227
+ var _internals134 = {
157064
157228
  normalizeVerdict2,
157065
157229
  VERDICT_SET_2,
157066
157230
  isAcceptedVerdict2
@@ -157323,7 +157487,7 @@ async function executeWriteHallucinationEvidence(args2, directory) {
157323
157487
  message: "Invalid summary: must be a non-empty string"
157324
157488
  }, null, 2);
157325
157489
  }
157326
- const normalizedVerdict = _internals134.normalizeVerdict2(args2.verdict);
157490
+ const normalizedVerdict = _internals135.normalizeVerdict2(args2.verdict);
157327
157491
  const evidenceEntry = {
157328
157492
  type: "hallucination-verification",
157329
157493
  verdict: normalizedVerdict,
@@ -157366,7 +157530,7 @@ async function executeWriteHallucinationEvidence(args2, directory) {
157366
157530
  }, null, 2);
157367
157531
  }
157368
157532
  }
157369
- var _internals134 = {
157533
+ var _internals135 = {
157370
157534
  normalizeVerdict2,
157371
157535
  VERDICT_SET_2,
157372
157536
  isAcceptedVerdict2
@@ -157447,7 +157611,7 @@ async function executeWriteMutationEvidence(args2, directory) {
157447
157611
  message: "Invalid summary: must be a non-empty string"
157448
157612
  }, null, 2);
157449
157613
  }
157450
- const normalizedVerdict = _internals135.normalizeVerdict4(args2.verdict);
157614
+ const normalizedVerdict = _internals136.normalizeVerdict4(args2.verdict);
157451
157615
  const evidenceEntry = {
157452
157616
  type: "mutation-gate",
157453
157617
  verdict: normalizedVerdict,
@@ -157494,7 +157658,7 @@ async function executeWriteMutationEvidence(args2, directory) {
157494
157658
  }, null, 2);
157495
157659
  }
157496
157660
  }
157497
- var _internals135 = {
157661
+ var _internals136 = {
157498
157662
  normalizeVerdict4,
157499
157663
  VERDICT_SET_4,
157500
157664
  isAcceptedVerdict4