opencode-swarm 7.158.1 → 7.159.1

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.
Files changed (84) hide show
  1. package/README.md +4 -2
  2. package/dist/cli/{coder-settlement-nrtcjr0h.js → coder-settlement-d89tqam8.js} +9 -9
  3. package/dist/cli/{config-doctor-hs0x10ty.js → config-doctor-8zawz3qh.js} +2 -2
  4. package/dist/cli/{core-a42bexs1.js → core-pp64ys5v.js} +1 -1
  5. package/dist/cli/{curation-policy-vn3m5nq2.js → curation-policy-2gq8307w.js} +6 -6
  6. package/dist/cli/{curator-llm-factory-21vqqvn3.js → curator-llm-factory-m3yw6sn5.js} +30 -30
  7. package/dist/cli/{curator-yawrnk3t.js → curator-mpqpbr0r.js} +30 -30
  8. package/dist/cli/{evidence-summary-service-kmc92b95.js → evidence-summary-service-qaq1eba9.js} +12 -12
  9. package/dist/cli/{gate-evidence-6tzhdxb2.js → gate-evidence-r0c71n04.js} +6 -6
  10. package/dist/cli/{guardrail-explain-7xrdp18c.js → guardrail-explain-5z64w3ah.js} +31 -31
  11. package/dist/cli/{guardrail-log-f16sdc3p.js → guardrail-log-f9nf687y.js} +5 -5
  12. package/dist/cli/{guardrail-reset-0ks08s0t.js → guardrail-reset-yjwk20rb.js} +30 -30
  13. package/dist/cli/{hive-promoter-d661k3qq.js → hive-promoter-zjtgbh4w.js} +30 -30
  14. package/dist/cli/{index-nwkr6tvv.js → index-0zerbq1v.js} +1 -1
  15. package/dist/cli/{index-mc9qgkwd.js → index-1qpagg2t.js} +3 -3
  16. package/dist/cli/{index-tc14d2zy.js → index-29wav1x0.js} +4 -4
  17. package/dist/cli/{index-ygxb3jw4.js → index-2z00wqvb.js} +3 -3
  18. package/dist/cli/{index-4wy9kzjg.js → index-36sgq7n9.js} +32 -32
  19. package/dist/cli/{index-xzhk2hav.js → index-3rcqxbwt.js} +1 -1
  20. package/dist/cli/{index-6x9jq0cd.js → index-3scbg6n2.js} +2 -2
  21. package/dist/cli/{index-zy60xd05.js → index-4k9pqbxw.js} +2 -2
  22. package/dist/cli/{index-mfv7mfgg.js → index-4nc9npx5.js} +2 -2
  23. package/dist/cli/{index-pfnj5pvs.js → index-54pkyasv.js} +1 -1
  24. package/dist/cli/{index-86vvhe8m.js → index-60mzwj91.js} +15 -1
  25. package/dist/cli/{index-8fqb0ynp.js → index-6z53bew2.js} +1 -1
  26. package/dist/cli/{index-jz216dhj.js → index-7yg4ypyg.js} +26 -2
  27. package/dist/cli/{index-ac8rwjsg.js → index-86dvzyac.js} +785 -235
  28. package/dist/cli/{index-tppnfxkm.js → index-8819vcke.js} +4 -4
  29. package/dist/cli/{index-ff8xjr1c.js → index-9fphcxes.js} +2 -2
  30. package/dist/cli/{index-hrrzxz3q.js → index-9yxyc1gb.js} +6 -6
  31. package/dist/cli/{index-zcmwwp1x.js → index-a5w29k1t.js} +1 -1
  32. package/dist/cli/{index-xagq35tf.js → index-av3gnekk.js} +1 -1
  33. package/dist/cli/{index-xscjecyq.js → index-bea260ta.js} +6 -6
  34. package/dist/cli/{index-dr2tfawg.js → index-bz7ayg01.js} +5 -5
  35. package/dist/cli/{index-7qvfkgyk.js → index-f3yphmk6.js} +7 -7
  36. package/dist/cli/{index-5zgf140g.js → index-g6d8xam2.js} +1 -1
  37. package/dist/cli/{index-azx50qge.js → index-gkw7kq6z.js} +5 -5
  38. package/dist/cli/{index-203fqkqk.js → index-k6y6btb6.js} +3 -3
  39. package/dist/cli/{index-h1g8w4v0.js → index-prknc0xn.js} +129 -44
  40. package/dist/cli/{index-z54qw70y.js → index-tvz43tea.js} +1 -1
  41. package/dist/cli/{index-h52hs4e9.js → index-v3jy0tc6.js} +2 -2
  42. package/dist/cli/{index-t8g88esk.js → index-ve3v09kq.js} +1 -1
  43. package/dist/cli/{index-mt6qjp4c.js → index-wae55z9w.js} +81 -72
  44. package/dist/cli/{index-nphnjeh8.js → index-wttqayp1.js} +2 -2
  45. package/dist/cli/{index-5erwyk1b.js → index-yw26j0q7.js} +7 -7
  46. package/dist/cli/{index-2j07670d.js → index-zmc8mm7v.js} +4 -4
  47. package/dist/cli/{index-7s1hmrfh.js → index-zxkv8x5n.js} +2 -2
  48. package/dist/cli/index.js +38 -46
  49. package/dist/cli/{knowledge-escalator-9py5r6c9.js → knowledge-escalator-585m4927.js} +11 -11
  50. package/dist/cli/{knowledge-events-vcbece74.js → knowledge-events-ssegqfmy.js} +9 -9
  51. package/dist/cli/{knowledge-link-cj2abbae.js → knowledge-link-a9fafeb3.js} +5 -5
  52. package/dist/cli/{knowledge-store-0rdfjv20.js → knowledge-store-nznky6cv.js} +6 -6
  53. package/dist/cli/{knowledge-validator-nwjnjgf5.js → knowledge-validator-3byea8gp.js} +8 -8
  54. package/dist/cli/{pending-delegations-ht1vgaze.js → pending-delegations-qrjq3s29.js} +3 -3
  55. package/dist/cli/{pr-review-reentry-authorization-857b9rvv.js → pr-review-reentry-authorization-w8ja0m2p.js} +30 -30
  56. package/dist/cli/{pr-subscriptions-j9j70bmd.js → pr-subscriptions-fvmey1x6.js} +4 -4
  57. package/dist/cli/{runner-sj5sf36c.js → runner-atbehryj.js} +6 -6
  58. package/dist/cli/{scan-cursor-59yj7tp9.js → scan-cursor-kv9scb2v.js} +7 -7
  59. package/dist/cli/{schema-8a7fyp87.js → schema-a7f88yc3.js} +1 -1
  60. package/dist/cli/{scope-persistence-prdxtcr3.js → scope-persistence-x6de46s4.js} +8 -8
  61. package/dist/cli/{skill-generator-v2jkgp63.js → skill-generator-vwcrfrw3.js} +13 -13
  62. package/dist/cli/{telemetry-r8e8zey7.js → telemetry-3rh94wv3.js} +1 -1
  63. package/dist/cli/{worktree-collision-ownership-6x03w8h7.js → worktree-collision-ownership-7kf9mm5z.js} +5 -5
  64. package/dist/cli/{worktree-isolation-s0setq2a.js → worktree-isolation-6zh5bxrd.js} +30 -30
  65. package/dist/commands/close.d.ts +2 -0
  66. package/dist/config/loader.d.ts +3 -0
  67. package/dist/config/project-init.d.ts +11 -7
  68. package/dist/config/schema.d.ts +21 -0
  69. package/dist/evaluation/contracts.d.ts +5 -5
  70. package/dist/evaluation/ephemeral-agent-dispatcher.d.ts +2 -0
  71. package/dist/evaluation/model-dispatcher.d.ts +2 -2
  72. package/dist/index.js +478 -475
  73. package/dist/observability/catalog.d.ts +5 -3
  74. package/dist/review/contracts.d.ts +2 -1
  75. package/dist/review/evidence.d.ts +12 -0
  76. package/dist/services/cost-accounting.d.ts +100 -0
  77. package/dist/services/status-service.d.ts +12 -0
  78. package/dist/telemetry.d.ts +1 -1
  79. package/dist/tools/repo-graph/query.d.ts +1 -0
  80. package/dist/tools/repo-graph/symbol-query.d.ts +47 -0
  81. package/dist/tools/repo-graph/types.d.ts +267 -1
  82. package/dist/tools/repo-graph.d.ts +3 -1
  83. package/opencode-swarm.schema.json +5200 -0
  84. package/package.json +4 -2
@@ -6,7 +6,7 @@ import {
6
6
  resolveExecutableFromPath,
7
7
  runEvaluation,
8
8
  runExternalTool
9
- } from "./index-z54qw70y.js";
9
+ } from "./index-tvz43tea.js";
10
10
  import {
11
11
  finalizeShellAuditForClose,
12
12
  isPolicyProtectedPath,
@@ -15,13 +15,13 @@ import {
15
15
  protectedRoots,
16
16
  redactDecisionLineForArchive,
17
17
  stableCanonicalStringify
18
- } from "./index-ff8xjr1c.js";
18
+ } from "./index-9fphcxes.js";
19
19
  import {
20
20
  detectStraySwarmDirs,
21
21
  readDoctorArtifact,
22
22
  removeStraySwarmDir,
23
23
  runConfigDoctor
24
- } from "./index-86vvhe8m.js";
24
+ } from "./index-60mzwj91.js";
25
25
  import {
26
26
  MAX_TRANSIENT_RETRIES,
27
27
  archiveEvidence,
@@ -68,7 +68,7 @@ import {
68
68
  validateProjectRoot,
69
69
  validateSymlinkBoundary,
70
70
  validateTargetWithinRoot
71
- } from "./index-7qvfkgyk.js";
71
+ } from "./index-f3yphmk6.js";
72
72
  import {
73
73
  EvaluationTaskV1Schema,
74
74
  GateAuditManifestV1Schema,
@@ -85,7 +85,7 @@ import {
85
85
  saveGateAuditResult,
86
86
  savePromotionDecision,
87
87
  saveTaskSetSnapshot
88
- } from "./index-7s1hmrfh.js";
88
+ } from "./index-zxkv8x5n.js";
89
89
  import {
90
90
  canonicalHash,
91
91
  canonicalJson,
@@ -129,15 +129,15 @@ import {
129
129
  retireSkill,
130
130
  selectCandidateEntries,
131
131
  syncBundledProjectSkillsIfMissingAsync
132
- } from "./index-tc14d2zy.js";
132
+ } from "./index-29wav1x0.js";
133
133
  import {
134
134
  readRecentEscalations
135
- } from "./index-azx50qge.js";
135
+ } from "./index-gkw7kq6z.js";
136
136
  import {
137
137
  alreadyCuratedThisGeneration,
138
138
  claimNextScanBatch,
139
139
  resolveCohortId
140
- } from "./index-mfv7mfgg.js";
140
+ } from "./index-4nc9npx5.js";
141
141
  import {
142
142
  CURATOR_INIT_PROMPT,
143
143
  CURATOR_PHASE_PROMPT,
@@ -161,7 +161,7 @@ import {
161
161
  listActive,
162
162
  subscribe,
163
163
  unsubscribe
164
- } from "./index-mc9qgkwd.js";
164
+ } from "./index-1qpagg2t.js";
165
165
  import {
166
166
  clearWorktreeMergeStatus,
167
167
  getAllWorktreeMergeFailures,
@@ -173,7 +173,7 @@ import {
173
173
  listCoderSettlementWalStates,
174
174
  recoverCoderSettlement,
175
175
  recoverStaleCoderSettlements
176
- } from "./index-hrrzxz3q.js";
176
+ } from "./index-9yxyc1gb.js";
177
177
  import {
178
178
  parsePorcelainV2Snapshot,
179
179
  resolveCommitCountSince,
@@ -206,7 +206,7 @@ import {
206
206
  WORKTREE_LIFECYCLE_LOCK_FILE,
207
207
  recordWorktreeProvisioningOwner,
208
208
  removeWorktreeProvisioningOwner
209
- } from "./index-8fqb0ynp.js";
209
+ } from "./index-6z53bew2.js";
210
210
  import {
211
211
  appendUnactionable,
212
212
  quarantineEntry,
@@ -217,11 +217,11 @@ import {
217
217
  validateActionableFields,
218
218
  validateLesson,
219
219
  validateSkillPath
220
- } from "./index-tppnfxkm.js";
220
+ } from "./index-8819vcke.js";
221
221
  import {
222
222
  authorizeCuration,
223
223
  buildConfigFingerprintInput
224
- } from "./index-pfnj5pvs.js";
224
+ } from "./index-54pkyasv.js";
225
225
  import {
226
226
  cohortConfigFingerprint
227
227
  } from "./index-rtry5xyf.js";
@@ -252,12 +252,12 @@ import {
252
252
  transitionTaskWorkflowEvidence,
253
253
  withTaskEvidenceTransaction,
254
254
  writeWorkflowWalFile
255
- } from "./index-2j07670d.js";
255
+ } from "./index-zmc8mm7v.js";
256
256
  import {
257
257
  makeWorktreeBranchName,
258
258
  provisionWorktree,
259
259
  removeWorktree
260
- } from "./index-t8g88esk.js";
260
+ } from "./index-ve3v09kq.js";
261
261
  import {
262
262
  DEFAULT_STALE_DELEGATION_TIMEOUT_MS,
263
263
  DELEGATION_COMPACTION_HIGH_WATER_BYTES,
@@ -272,7 +272,7 @@ import {
272
272
  scanBackgroundCoderReservationsForAdmission,
273
273
  scanDelegationsForRecovery,
274
274
  sweepStaleDelegations
275
- } from "./index-zy60xd05.js";
275
+ } from "./index-4k9pqbxw.js";
276
276
  import {
277
277
  compositeSessionKey,
278
278
  sessionKeySuffix
@@ -283,7 +283,7 @@ import {
283
283
  clearAllScopes,
284
284
  clearScopeBindingFromDisk,
285
285
  clearScopeBindings
286
- } from "./index-dr2tfawg.js";
286
+ } from "./index-bz7ayg01.js";
287
287
  import {
288
288
  appendLedgerEvent,
289
289
  computePlanHash,
@@ -298,7 +298,7 @@ import {
298
298
  readPlanEpochIdentity,
299
299
  replayFromLedgerWithStatus,
300
300
  takeSnapshotEvent
301
- } from "./index-203fqkqk.js";
301
+ } from "./index-k6y6btb6.js";
302
302
  import {
303
303
  CORE_EVENT_LOCKED,
304
304
  appendCoreEventSync,
@@ -308,7 +308,7 @@ import {
308
308
  hasSpecDriftAuditEvent,
309
309
  hasTaskRepairAuditEvent,
310
310
  readCoreEvents
311
- } from "./index-nwkr6tvv.js";
311
+ } from "./index-0zerbq1v.js";
312
312
  import {
313
313
  sanitizeDiagnosticText
314
314
  } from "./index-556ja8an.js";
@@ -357,7 +357,7 @@ import {
357
357
  transactFile,
358
358
  transactKnowledge,
359
359
  wordBigrams
360
- } from "./index-xscjecyq.js";
360
+ } from "./index-bea260ta.js";
361
361
  import {
362
362
  MAX_EVENT_LOG_ENTRIES,
363
363
  _internals as _internals2,
@@ -373,10 +373,10 @@ import {
373
373
  recordKnowledgeEvent,
374
374
  recordPhaseCloseIntent,
375
375
  resolveKnowledgeEventsPath
376
- } from "./index-5erwyk1b.js";
376
+ } from "./index-yw26j0q7.js";
377
377
  import {
378
378
  resolveWorktreeIsolationConfig
379
- } from "./index-6x9jq0cd.js";
379
+ } from "./index-3scbg6n2.js";
380
380
  import {
381
381
  RetrospectiveEvidenceSchema
382
382
  } from "./index-gprxjmm7.js";
@@ -399,7 +399,7 @@ import {
399
399
  init_loader,
400
400
  loadPluginConfig,
401
401
  loadPluginConfigWithMeta
402
- } from "./index-jz216dhj.js";
402
+ } from "./index-7yg4ypyg.js";
403
403
  import {
404
404
  DEFAULT_HARNESS_EVOLUTION_CONFIG,
405
405
  DEFAULT_PR_REVIEW_RESILIENCE_CONFIG,
@@ -415,7 +415,7 @@ import {
415
415
  package_default,
416
416
  resolveAutoReviewConfig,
417
417
  stripKnownSwarmPrefix
418
- } from "./index-mt6qjp4c.js";
418
+ } from "./index-wae55z9w.js";
419
419
  import {
420
420
  init_git_executable,
421
421
  resolveGitExecutable,
@@ -455,10 +455,10 @@ import {
455
455
  resolveLinkDir,
456
456
  sanitizeLinkId,
457
457
  writeLinkPointer
458
- } from "./index-5zgf140g.js";
458
+ } from "./index-g6d8xam2.js";
459
459
  import {
460
460
  atomicWriteFile
461
- } from "./index-h52hs4e9.js";
461
+ } from "./index-v3jy0tc6.js";
462
462
  import {
463
463
  KNOWLEDGE_SCHEMA_VERSION,
464
464
  OUTCOME_BLOCK_THRESHOLD,
@@ -470,7 +470,7 @@ import {
470
470
  atomicWriteSwarmFileSync,
471
471
  matchTempGrammar,
472
472
  parseTargetBasename
473
- } from "./index-zcmwwp1x.js";
473
+ } from "./index-a5w29k1t.js";
474
474
  import {
475
475
  assertProjectRoot,
476
476
  hasExplicitProjectBoundary,
@@ -478,7 +478,7 @@ import {
478
478
  listActiveLocks,
479
479
  tryAcquireLock,
480
480
  withEvidenceLock
481
- } from "./index-xagq35tf.js";
481
+ } from "./index-av3gnekk.js";
482
482
  import {
483
483
  invalidateCachedArtifact,
484
484
  resetSwarmArtifactCache
@@ -487,7 +487,7 @@ import {
487
487
  emit,
488
488
  getLastHeartbeat,
489
489
  telemetry
490
- } from "./index-h1g8w4v0.js";
490
+ } from "./index-prknc0xn.js";
491
491
  import {
492
492
  require_proper_lockfile
493
493
  } from "./index-7g4c7s5r.js";
@@ -15777,38 +15777,339 @@ async function computeGateStatistics(directory, minSamples = 6, runId) {
15777
15777
  }
15778
15778
 
15779
15779
  // src/services/cost-accounting.ts
15780
- init_logger();
15781
15780
  import * as fs8 from "fs";
15781
+ init_logger();
15782
15782
  import * as os from "os";
15783
15783
  import * as path16 from "path";
15784
+ var ZERO_USAGE = {
15785
+ tokens_input: 0,
15786
+ tokens_output: 0,
15787
+ tokens_reasoning: 0,
15788
+ tokens_cache: 0
15789
+ };
15790
+ var MAX_EVIDENCE_ITEMS = 8;
15791
+ var MAX_COST_STRING_LENGTH = 128;
15792
+ var MAX_PROVIDER_REPORTED_COST_USD = 1e9;
15793
+ var MAX_TELEMETRY_FILE_BYTES = 4 * 1024 * 1024;
15794
+ function projectCostEvidence(evidence2) {
15795
+ const reports = evidence2.filter((item) => item.kind === "provider_reported" && item.reason !== "missing_cost");
15796
+ const compatibleReports = reports.filter((item) => item.amount_usd !== null && item.amount_usd <= MAX_PROVIDER_REPORTED_COST_USD && item.currency === "USD");
15797
+ const incompatibleReport = reports.some((item) => item.amount_usd !== null && item.amount_usd <= MAX_PROVIDER_REPORTED_COST_USD && (item.currency !== "USD" || item.reason !== "authoritative"));
15798
+ const reportConflict = hasReportConflict(reports);
15799
+ if (!reportConflict && !incompatibleReport && compatibleReports.length > 0) {
15800
+ return {
15801
+ cost_usd: roundUsd(compatibleReports[0].amount_usd ?? 0),
15802
+ cost_source: "reported",
15803
+ evidence_status: "complete",
15804
+ reason: "authoritative",
15805
+ currency: "USD"
15806
+ };
15807
+ }
15808
+ const estimate = evidence2.find((item) => item.kind === "normalized_estimate" && item.amount_usd !== null && item.currency === "USD" && item.reason === "authoritative");
15809
+ const hasHardIncompatibleReport = reports.some((item) => item.amount_usd !== null && item.amount_usd <= MAX_PROVIDER_REPORTED_COST_USD && (item.currency !== "USD" || item.reason === "unsupported_currency"));
15810
+ if (!reportConflict && !hasHardIncompatibleReport && estimate) {
15811
+ return {
15812
+ cost_usd: roundUsd(estimate.amount_usd ?? 0),
15813
+ cost_source: "estimated",
15814
+ evidence_status: "complete",
15815
+ reason: "authoritative",
15816
+ currency: "USD"
15817
+ };
15818
+ }
15819
+ return {
15820
+ cost_usd: null,
15821
+ cost_source: "unavailable",
15822
+ evidence_status: "inconclusive",
15823
+ reason: reportConflict ? "conflict" : incompatibleReport ? reports[0]?.reason ?? "unsupported_currency" : "missing_cost",
15824
+ currency: reports[0]?.currency ?? "unknown"
15825
+ };
15826
+ }
15784
15827
  function summarizeTelemetryCosts(directory) {
15785
15828
  const summary = createEmptySummary();
15786
- for (const event of readTelemetryEvents(directory)) {
15829
+ const folded = foldTelemetryEvents(readTelemetryEvents(directory));
15830
+ summary.conflict_count = folded.stats.conflict_count;
15831
+ summary.join_miss_count = folded.stats.join_miss_count;
15832
+ summary.telemetry_error_count = folded.stats.telemetry_error_count;
15833
+ if (folded.stats.join_miss_count > 0 || folded.stats.telemetry_error_count > 0) {
15834
+ summary.evidence_status = "inconclusive";
15835
+ }
15836
+ if (folded.stats.rejected_corrections > 0 || folded.stats.conflict_count > 0) {
15837
+ summary.evidence_status = "inconclusive";
15838
+ }
15839
+ summary.accepted_corrections = folded.stats.accepted_corrections;
15840
+ summary.rejected_corrections = folded.stats.rejected_corrections;
15841
+ summary.duplicate_corrections = folded.stats.duplicate_corrections;
15842
+ for (const event of folded.events) {
15787
15843
  if (event.event !== "delegation_end")
15788
15844
  continue;
15789
15845
  addDelegationEvent(summary, event);
15790
15846
  }
15791
15847
  return finalizeSummary(summary);
15792
15848
  }
15849
+ function foldTelemetryEvents(events) {
15850
+ const stats = {
15851
+ conflict_count: 0,
15852
+ join_miss_count: 0,
15853
+ telemetry_error_count: 0,
15854
+ accepted_corrections: 0,
15855
+ rejected_corrections: 0,
15856
+ duplicate_corrections: 0
15857
+ };
15858
+ const rows = new Map;
15859
+ const states = new Map;
15860
+ const legacy = [];
15861
+ const corrections = [];
15862
+ for (const event of events) {
15863
+ const eventKind = event.event;
15864
+ if (eventKind === "delegation_cost_join" && event.reason === "join_miss") {
15865
+ stats.join_miss_count++;
15866
+ continue;
15867
+ }
15868
+ if (eventKind === "delegation_cost_join" && (event.reason === "unreadable" || event.reason === "malformed")) {
15869
+ stats.telemetry_error_count++;
15870
+ continue;
15871
+ }
15872
+ if (eventKind !== "delegation_end" && eventKind !== "delegation_cost_correction")
15873
+ continue;
15874
+ if (eventKind === "delegation_end") {
15875
+ const recordId = boundedId(event.record_id ?? event.recordId);
15876
+ if (!recordId) {
15877
+ legacy.push(event);
15878
+ continue;
15879
+ }
15880
+ const fingerprint = boundedDigest(event.identity_fingerprint);
15881
+ const initialVersion = validVersion(event.version);
15882
+ if (!fingerprint || initialVersion !== 1) {
15883
+ legacy.push(event);
15884
+ stats.rejected_corrections++;
15885
+ continue;
15886
+ }
15887
+ const snapshot = { ...event, record_id: recordId };
15888
+ const digest2 = boundedDigest(event.digest) ?? costSnapshotDigest(snapshot);
15889
+ if (rows.has(recordId)) {
15890
+ stats.rejected_corrections++;
15891
+ continue;
15892
+ }
15893
+ rows.set(recordId, snapshot);
15894
+ states.set(recordId, {
15895
+ version: initialVersion,
15896
+ digest: digest2,
15897
+ fingerprint
15898
+ });
15899
+ if (parseCostSource(event.cost_source) === "unavailable") {
15900
+ const evidence2 = readEventEvidence(event);
15901
+ if (evidence2.some((item) => item.reason === "conflict"))
15902
+ stats.conflict_count++;
15903
+ }
15904
+ continue;
15905
+ }
15906
+ corrections.push(event);
15907
+ }
15908
+ corrections.sort((left, right) => {
15909
+ const leftRecord = boundedId(left.record_id ?? left.recordId) ?? "";
15910
+ const rightRecord = boundedId(right.record_id ?? right.recordId) ?? "";
15911
+ if (leftRecord !== rightRecord)
15912
+ return leftRecord.localeCompare(rightRecord);
15913
+ return (validVersion(left.version) ?? Number.MAX_SAFE_INTEGER) - (validVersion(right.version) ?? Number.MAX_SAFE_INTEGER);
15914
+ });
15915
+ for (const event of corrections) {
15916
+ const recordId = boundedId(event.record_id ?? event.recordId);
15917
+ const state = recordId ? states.get(recordId) : undefined;
15918
+ const current = recordId ? rows.get(recordId) : undefined;
15919
+ if (!recordId || !state || !current) {
15920
+ stats.rejected_corrections++;
15921
+ continue;
15922
+ }
15923
+ const fingerprint = boundedDigest(event.identity_fingerprint);
15924
+ if (!fingerprint || fingerprint !== state.fingerprint) {
15925
+ stats.rejected_corrections++;
15926
+ continue;
15927
+ }
15928
+ const nextVersion = validVersion(event.version);
15929
+ if (nextVersion === null || nextVersion !== state.version + 1) {
15930
+ stats.rejected_corrections++;
15931
+ continue;
15932
+ }
15933
+ const replacement = {
15934
+ ...current,
15935
+ event: "delegation_end",
15936
+ record_id: recordId,
15937
+ version: event.version,
15938
+ digest: event.digest,
15939
+ cost_evidence: event.cost_evidence,
15940
+ evidence_status: event.evidence_status,
15941
+ evidence_reason: event.evidence_reason,
15942
+ currency: event.currency,
15943
+ cost_usd: event.cost_usd,
15944
+ cost_source: event.cost_source,
15945
+ tokens_input: event.tokens_input,
15946
+ tokens_output: event.tokens_output,
15947
+ tokens_reasoning: event.tokens_reasoning,
15948
+ tokens_cache: event.tokens_cache
15949
+ };
15950
+ const digest2 = boundedDigest(event.digest) ?? costSnapshotDigest(replacement);
15951
+ if (digest2 === state.digest) {
15952
+ stats.duplicate_corrections++;
15953
+ states.set(recordId, {
15954
+ version: nextVersion,
15955
+ digest: state.digest,
15956
+ fingerprint: state.fingerprint
15957
+ });
15958
+ continue;
15959
+ }
15960
+ const currentEvidence = readEventEvidence(current);
15961
+ const nextEvidence = readEventEvidence(replacement);
15962
+ if (hasReportConflict(nextEvidence)) {
15963
+ stats.conflict_count++;
15964
+ stats.rejected_corrections++;
15965
+ continue;
15966
+ }
15967
+ if (!isCostUpgrade(currentEvidence, nextEvidence)) {
15968
+ stats.rejected_corrections++;
15969
+ continue;
15970
+ }
15971
+ rows.set(recordId, replacement);
15972
+ states.set(recordId, {
15973
+ version: nextVersion,
15974
+ digest: digest2,
15975
+ fingerprint: state.fingerprint
15976
+ });
15977
+ stats.accepted_corrections++;
15978
+ }
15979
+ return {
15980
+ events: [...legacy, ...rows.values()],
15981
+ stats,
15982
+ versions: Object.fromEntries([...states].map(([recordId, state]) => [recordId, state.version]))
15983
+ };
15984
+ }
15985
+ function boundedId(value) {
15986
+ return typeof value === "string" && /^[A-Za-z0-9_-]{1,32}$/.test(value) ? value : null;
15987
+ }
15988
+ function boundedDigest(value) {
15989
+ return typeof value === "string" && /^[a-f0-9]{32,64}$/.test(value) ? value : undefined;
15990
+ }
15991
+ function validVersion(value) {
15992
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 1e5 ? value : null;
15993
+ }
15994
+ function readEventEvidence(event) {
15995
+ const value = event.cost_evidence ?? event.evidence;
15996
+ if (!Array.isArray(value))
15997
+ return legacyEventEvidence(event);
15998
+ return value.slice(0, MAX_EVIDENCE_ITEMS).flatMap((item) => {
15999
+ if (!isRecord(item))
16000
+ return [];
16001
+ const kind = item.kind === "provider_reported" || item.kind === "normalized_estimate" ? item.kind : null;
16002
+ const sourcePath = isCostSourcePath(item.source_path) ? item.source_path : null;
16003
+ const amount = readBoundedReportedCost(item.amount_usd);
16004
+ const usage = isRecord(item.usage) ? readPinnedTokens(item.usage) : { ...ZERO_USAGE };
16005
+ if (!kind || !sourcePath)
16006
+ return [];
16007
+ return [
16008
+ {
16009
+ kind,
16010
+ amount_usd: amount,
16011
+ currency: normalizeCurrency(item.currency),
16012
+ source_path: sourcePath,
16013
+ reason: isCostEvidenceReason(item.reason) ? item.reason : amount === null ? "missing_cost" : "authoritative",
16014
+ usage,
16015
+ model: typeof item.model === "string" ? item.model.slice(0, MAX_COST_STRING_LENGTH) : undefined,
16016
+ digest: boundedDigest(item.digest)
16017
+ }
16018
+ ];
16019
+ });
16020
+ }
16021
+ function legacyEventEvidence(event) {
16022
+ const amount = readBoundedReportedCost(event.cost_usd);
16023
+ return [
16024
+ {
16025
+ kind: parseCostSource(event.cost_source) === "estimated" ? "normalized_estimate" : "provider_reported",
16026
+ amount_usd: amount,
16027
+ currency: "USD",
16028
+ source_path: "legacy.cost",
16029
+ reason: amount === null ? "legacy" : "authoritative",
16030
+ usage: {
16031
+ tokens_input: readFiniteNonNegative(event.tokens_input) ?? 0,
16032
+ tokens_output: readFiniteNonNegative(event.tokens_output) ?? 0,
16033
+ tokens_reasoning: readFiniteNonNegative(event.tokens_reasoning) ?? 0,
16034
+ tokens_cache: readFiniteNonNegative(event.tokens_cache) ?? 0
16035
+ }
16036
+ }
16037
+ ];
16038
+ }
16039
+ function isCostSourcePath(value) {
16040
+ return value === "assistant.cost" || value === "step-finish.cost" || value === "response.info.cost" || value === "response.cost" || value === "legacy.cost" || value === "pricing.model";
16041
+ }
16042
+ function isCostEvidenceReason(value) {
16043
+ return value === "authoritative" || value === "missing_cost" || value === "invalid_number" || value === "pricing_missing" || value === "unsupported_currency" || value === "conflict" || value === "unbilled" || value === "join_miss" || value === "legacy" || value === "unreadable" || value === "partial";
16044
+ }
16045
+ function costSnapshotDigest(event) {
16046
+ const canonical = JSON.stringify({
16047
+ cost_usd: event.cost_usd ?? null,
16048
+ cost_source: parseCostSource(event.cost_source),
16049
+ tokens_input: readFiniteNonNegative(event.tokens_input) ?? 0,
16050
+ tokens_output: readFiniteNonNegative(event.tokens_output) ?? 0,
16051
+ tokens_reasoning: readFiniteNonNegative(event.tokens_reasoning) ?? 0,
16052
+ tokens_cache: readFiniteNonNegative(event.tokens_cache) ?? 0,
16053
+ cost_evidence: Array.isArray(event.cost_evidence) ? event.cost_evidence.slice(0, MAX_EVIDENCE_ITEMS) : undefined
16054
+ });
16055
+ let hash = 2166136261;
16056
+ for (let i = 0;i < canonical.length; i++)
16057
+ hash = Math.imul(hash ^ canonical.charCodeAt(i), 16777619);
16058
+ return `${(hash >>> 0).toString(16).padStart(8, "0")}${canonical.length.toString(16).padStart(8, "0")}`.slice(0, 32);
16059
+ }
16060
+ function evidenceAuthority(evidence2) {
16061
+ const projection = projectCostEvidence(evidence2);
16062
+ return projection.cost_source === "reported" ? 2 : projection.cost_source === "estimated" ? 1 : 0;
16063
+ }
16064
+ function isCostUpgrade(current, next) {
16065
+ const currentProjection = projectCostEvidence(current);
16066
+ const nextProjection = projectCostEvidence(next);
16067
+ const currentAuthority = evidenceAuthority(current);
16068
+ const nextAuthority = evidenceAuthority(next);
16069
+ if (nextAuthority > currentAuthority)
16070
+ return true;
16071
+ if (nextAuthority < currentAuthority)
16072
+ return false;
16073
+ if (currentProjection.cost_usd !== nextProjection.cost_usd)
16074
+ return true;
16075
+ const currentUsage = current.reduce(mergeUsage, { ...ZERO_USAGE });
16076
+ const nextUsage = next.reduce(mergeUsage, { ...ZERO_USAGE });
16077
+ return Object.keys(currentUsage).some((key) => nextUsage[key] > currentUsage[key]);
16078
+ }
15793
16079
  function readTelemetryEvents(directory) {
15794
16080
  const swarmDir = path16.join(directory, ".swarm");
15795
16081
  const files = [
15796
16082
  path16.join(swarmDir, "telemetry.jsonl.1"),
15797
16083
  path16.join(swarmDir, "telemetry.jsonl")
15798
16084
  ];
15799
- const tmpDir = fs8.mkdtempSync(path16.join(os.tmpdir(), "telemetry-snapshot-"));
16085
+ let tmpDir;
16086
+ try {
16087
+ tmpDir = fs8.mkdtempSync(path16.join(os.tmpdir(), "telemetry-snapshot-"));
16088
+ } catch {
16089
+ return [{ event: "delegation_cost_join", reason: "unreadable" }];
16090
+ }
15800
16091
  const snapshotFiles = [];
16092
+ let telemetryErrors = 0;
15801
16093
  try {
15802
16094
  for (const file of files) {
15803
16095
  if (!fs8.existsSync(file))
15804
16096
  continue;
15805
16097
  const snap = path16.join(tmpDir, path16.basename(file));
15806
16098
  try {
16099
+ const stat3 = fs8.statSync(file);
16100
+ if (!stat3.isFile() || stat3.size > MAX_TELEMETRY_FILE_BYTES) {
16101
+ telemetryErrors++;
16102
+ continue;
16103
+ }
15807
16104
  fs8.copyFileSync(file, snap);
15808
16105
  snapshotFiles.push(snap);
15809
- } catch {}
16106
+ } catch {
16107
+ telemetryErrors++;
16108
+ }
15810
16109
  }
15811
- } catch {}
16110
+ } catch {
16111
+ telemetryErrors++;
16112
+ }
15812
16113
  const events = [];
15813
16114
  let unreadableSnapshots = 0;
15814
16115
  let firstUnreadableReason = "";
@@ -15831,10 +16132,13 @@ function readTelemetryEvents(directory) {
15831
16132
  const parsed = JSON.parse(trimmed);
15832
16133
  if (isRecord(parsed))
15833
16134
  events.push(parsed);
15834
- } catch {}
16135
+ } catch {
16136
+ telemetryErrors++;
16137
+ }
15835
16138
  }
15836
16139
  }
15837
16140
  if (unreadableSnapshots > 0) {
16141
+ telemetryErrors += unreadableSnapshots;
15838
16142
  warn(`[cost-accounting] ${unreadableSnapshots} of ${snapshotFiles.length} snapshot file(s) were unreadable; cost totals undercount. First reason: ${firstUnreadableReason}`);
15839
16143
  }
15840
16144
  try {
@@ -15845,8 +16149,59 @@ function readTelemetryEvents(directory) {
15845
16149
  }
15846
16150
  fs8.rmdirSync(tmpDir);
15847
16151
  } catch {}
16152
+ if (telemetryErrors > 0) {
16153
+ events.push({ event: "delegation_cost_join", reason: "unreadable" });
16154
+ }
15848
16155
  return events;
15849
16156
  }
16157
+ function readPinnedTokens(record) {
16158
+ const tokens = isRecord(record.tokens) ? record.tokens : isRecord(record.usage) ? record.usage : record;
16159
+ return {
16160
+ tokens_input: readFiniteNonNegative(tokens.tokens_input ?? tokens.input ?? tokens.input_tokens ?? tokens.prompt_tokens) ?? 0,
16161
+ tokens_output: readFiniteNonNegative(tokens.tokens_output ?? tokens.output ?? tokens.output_tokens ?? tokens.completion_tokens) ?? 0,
16162
+ tokens_reasoning: readFiniteNonNegative(tokens.tokens_reasoning ?? tokens.reasoning ?? tokens.reasoning_tokens) ?? 0,
16163
+ tokens_cache: readFiniteNonNegative(tokens.tokens_cache) ?? readCacheTokens(tokens) ?? 0
16164
+ };
16165
+ }
16166
+ function mergeUsage(total, next) {
16167
+ const usage = "usage" in next && next.usage ? next.usage : next;
16168
+ return {
16169
+ tokens_input: Math.max(total.tokens_input, usage.tokens_input),
16170
+ tokens_output: Math.max(total.tokens_output, usage.tokens_output),
16171
+ tokens_reasoning: Math.max(total.tokens_reasoning, usage.tokens_reasoning),
16172
+ tokens_cache: Math.max(total.tokens_cache, usage.tokens_cache)
16173
+ };
16174
+ }
16175
+ function readFiniteNonNegative(value) {
16176
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
16177
+ }
16178
+ function readBoundedReportedCost(value) {
16179
+ const amount = readFiniteNonNegative(value);
16180
+ return amount !== null && amount <= MAX_PROVIDER_REPORTED_COST_USD ? amount : null;
16181
+ }
16182
+ function normalizeCurrency(value) {
16183
+ if (typeof value !== "string" || value.trim() === "")
16184
+ return "unknown";
16185
+ const currency = value.trim().slice(0, MAX_COST_STRING_LENGTH).toUpperCase();
16186
+ return currency || "unknown";
16187
+ }
16188
+ function hasReportConflict(reports) {
16189
+ const monetary = reports.filter((item) => item.kind === "provider_reported" && item.amount_usd !== null);
16190
+ for (let i = 0;i < monetary.length; i++) {
16191
+ for (let j = i + 1;j < monetary.length; j++) {
16192
+ const left = monetary[i];
16193
+ const right = monetary[j];
16194
+ if (left.currency !== right.currency)
16195
+ return true;
16196
+ if (left.currency === "USD" && !withinCostTolerance(left.amount_usd ?? 0, right.amount_usd ?? 0))
16197
+ return true;
16198
+ }
16199
+ }
16200
+ return false;
16201
+ }
16202
+ function withinCostTolerance(left, right) {
16203
+ return Math.abs(left - right) <= Math.max(0.000000001, Math.max(Math.abs(left), Math.abs(right)) * 0.000001);
16204
+ }
15850
16205
  function readNumber(record, keys) {
15851
16206
  for (const key of keys) {
15852
16207
  const value = record[key];
@@ -15860,6 +16215,22 @@ function readNumber(record, keys) {
15860
16215
  }
15861
16216
  return null;
15862
16217
  }
16218
+ function readCacheTokens(record) {
16219
+ const cacheRecord = isRecord(record.cache) ? record.cache : record;
16220
+ const read = readNumber(cacheRecord, [
16221
+ "read",
16222
+ "cache_read_input_tokens",
16223
+ "cached_input_tokens"
16224
+ ]);
16225
+ const write = readNumber(cacheRecord, [
16226
+ "write",
16227
+ "cache_write_input_tokens",
16228
+ "write_input_tokens"
16229
+ ]);
16230
+ if (read === null && write === null)
16231
+ return null;
16232
+ return (read ?? 0) + (write ?? 0);
16233
+ }
15863
16234
  function isRecord(value) {
15864
16235
  return typeof value === "object" && value !== null && !Array.isArray(value);
15865
16236
  }
@@ -15882,18 +16253,51 @@ function createEmptySummary() {
15882
16253
  reported: { delegations: 0, cost_usd: 0 },
15883
16254
  estimated: { delegations: 0, cost_usd: 0 },
15884
16255
  unavailable: { delegations: 0, cost_usd: 0 }
15885
- }
16256
+ },
16257
+ total_legacy_usd: 0,
16258
+ conflict_count: 0,
16259
+ legacy_count: 0,
16260
+ join_miss_count: 0,
16261
+ telemetry_error_count: 0,
16262
+ accepted_corrections: 0,
16263
+ rejected_corrections: 0,
16264
+ duplicate_corrections: 0,
16265
+ evidence_status: "complete",
16266
+ currencies: []
15886
16267
  };
15887
16268
  }
15888
16269
  function addDelegationEvent(summary, event) {
15889
- const costSource = parseCostSource(event.cost_source);
15890
- const cost = readNumber(event, ["cost_usd"]) ?? 0;
15891
- const usage = {
16270
+ const legacyCostSource = parseCostSource(event.cost_source);
16271
+ const legacyCost = readNumber(event, ["cost_usd"]) ?? 0;
16272
+ const hasRecord = boundedId(event.record_id ?? event.recordId) !== null;
16273
+ const evidence2 = readEventEvidence(event);
16274
+ const projection = projectCostEvidence(evidence2);
16275
+ const costSource = hasRecord ? projection.cost_source : legacyCostSource;
16276
+ const cost = hasRecord ? projection.cost_usd ?? 0 : legacyCost;
16277
+ if (!hasRecord) {
16278
+ summary.legacy_count++;
16279
+ summary.total_legacy_usd += legacyCost;
16280
+ summary.evidence_status = "inconclusive";
16281
+ }
16282
+ if (projection.evidence_status === "inconclusive")
16283
+ summary.evidence_status = "inconclusive";
16284
+ for (const item of evidence2) {
16285
+ if (item.currency !== "unknown" && !summary.currencies.includes(item.currency))
16286
+ summary.currencies.push(item.currency);
16287
+ }
16288
+ const legacyUsage = {
15892
16289
  tokens_input: readNumber(event, ["tokens_input"]) ?? 0,
15893
16290
  tokens_output: readNumber(event, ["tokens_output"]) ?? 0,
15894
16291
  tokens_reasoning: readNumber(event, ["tokens_reasoning"]) ?? 0,
15895
16292
  tokens_cache: readNumber(event, ["tokens_cache"]) ?? 0
15896
16293
  };
16294
+ const evidenceUsage = evidence2.reduce((acc, item) => ({
16295
+ tokens_input: Math.max(acc.tokens_input, item.usage.tokens_input),
16296
+ tokens_output: Math.max(acc.tokens_output, item.usage.tokens_output),
16297
+ tokens_reasoning: Math.max(acc.tokens_reasoning, item.usage.tokens_reasoning),
16298
+ tokens_cache: Math.max(acc.tokens_cache, item.usage.tokens_cache)
16299
+ }), { ...ZERO_USAGE });
16300
+ const usage = hasRecord ? evidenceUsage : legacyUsage;
15897
16301
  summary.delegations++;
15898
16302
  summary.total_cost_usd += cost;
15899
16303
  summary.total_input_tokens += usage.tokens_input;
@@ -15957,6 +16361,7 @@ function finalizeSummary(summary) {
15957
16361
  summary.total_cost_usd = roundUsd(summary.total_cost_usd);
15958
16362
  summary.total_reported_usd = roundUsd(summary.total_reported_usd);
15959
16363
  summary.total_estimated_usd = roundUsd(summary.total_estimated_usd);
16364
+ summary.total_legacy_usd = roundUsd(summary.total_legacy_usd);
15960
16365
  for (const source of Object.values(summary.by_source)) {
15961
16366
  source.cost_usd = roundUsd(source.cost_usd);
15962
16367
  }
@@ -16217,12 +16622,15 @@ async function handleBenchmarkCommand(directory, args) {
16217
16622
  }
16218
16623
  ];
16219
16624
  if (maxCostUsd !== null) {
16625
+ const costEvidenceComplete = costSummary !== undefined && costSummary.delegations > 0 && costSummary.evidence_status === "complete";
16220
16626
  checks.push({
16221
16627
  name: "Total cost",
16222
16628
  value: costSummary?.total_cost_usd ?? 0,
16223
16629
  threshold: maxCostUsd,
16224
16630
  operator: "<=",
16225
- passed: (costSummary?.total_cost_usd ?? 0) <= maxCostUsd
16631
+ passed: costEvidenceComplete && (costSummary?.total_cost_usd ?? 0) <= maxCostUsd,
16632
+ evidence_status: costEvidenceComplete ? "complete" : "inconclusive",
16633
+ reason: costEvidenceComplete ? (costSummary?.total_cost_usd ?? 0) <= maxCostUsd ? undefined : "thresholdExceeded" : "budgetInconclusive"
16226
16634
  });
16227
16635
  }
16228
16636
  if (gateAudit && gateAuditSummary) {
@@ -16315,6 +16723,10 @@ async function handleBenchmarkCommand(directory, args) {
16315
16723
  if (ciGate) {
16316
16724
  lines.push("### CI Gate", ciGate.passed ? "\u2705 PASSED" : "\u274C FAILED");
16317
16725
  for (const c of ciGate.checks) {
16726
+ if (c.name === "Total cost" && c.evidence_status === "inconclusive") {
16727
+ lines.push(`- Total cost: inconclusive (budget evidence unavailable) <= $${c.threshold.toFixed(6)} \u274C`);
16728
+ continue;
16729
+ }
16318
16730
  let valueStr;
16319
16731
  if (c.name === "Complexity Delta" || c.name === "Public API Delta") {
16320
16732
  valueStr = `${c.value}`;
@@ -16403,7 +16815,9 @@ async function handleBenchmarkCommand(directory, args) {
16403
16815
  value: c.value,
16404
16816
  threshold: c.threshold,
16405
16817
  operator: c.operator,
16406
- passed: c.passed
16818
+ passed: c.passed,
16819
+ ...c.evidence_status ? { evidence_status: c.evidence_status } : {},
16820
+ ...c.reason ? { reason: c.reason } : {}
16407
16821
  }))
16408
16822
  };
16409
16823
  lines.push("[BENCHMARK_JSON]", JSON.stringify(json, null, 2), "[/BENCHMARK_JSON]");
@@ -21040,7 +21454,7 @@ function planMerges(active, threshold, maxComparisons, maxMerges) {
21040
21454
  };
21041
21455
  }
21042
21456
  async function sweepActiveNearDuplicates(directory, options = {}) {
21043
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-ygxb3jw4.js");
21457
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-2z00wqvb.js");
21044
21458
  const { config } = loadPluginConfigWithMeta2(directory);
21045
21459
  const sweepConfig = config.learning?.dedup_sweep;
21046
21460
  if (sweepConfig?.enabled === false)
@@ -22170,7 +22584,7 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
22170
22584
  }
22171
22585
  if (config.skill_generation_enabled === true && skillCandidates.length > 0) {
22172
22586
  try {
22173
- const skillModule = await import("./skill-generator-v2jkgp63.js");
22587
+ const skillModule = await import("./skill-generator-vwcrfrw3.js");
22174
22588
  for (const cand of skillCandidates) {
22175
22589
  if (cand.confidence < (config.min_skill_confidence ?? DEFAULT_SKILL_MIN_CONFIDENCE)) {
22176
22590
  continue;
@@ -22642,7 +23056,7 @@ async function applyCuratorKnowledgeUpdates(directory, recommendations, knowledg
22642
23056
  } catch {}
22643
23057
  }
22644
23058
  if (contradictedEntries.length > 0 && knowledgeConfig.contradiction_threshold_action === "quarantine") {
22645
- const { maybeQuarantineOnContradiction } = await import("./knowledge-escalator-9py5r6c9.js");
23059
+ const { maybeQuarantineOnContradiction } = await import("./knowledge-escalator-585m4927.js");
22646
23060
  for (const { id } of contradictedEntries) {
22647
23061
  try {
22648
23062
  await maybeQuarantineOnContradiction(directory, id, knowledgeConfig.contradiction_quarantine_threshold, knowledgeConfig.contradiction_quarantine_window_days);
@@ -23461,7 +23875,7 @@ async function runCuratorPostMortem(directory, options = {}) {
23461
23875
  warnings.push("Failed to collect knowledge summary.");
23462
23876
  }
23463
23877
  try {
23464
- const { getScanStatus } = await import("./scan-cursor-59yj7tp9.js");
23878
+ const { getScanStatus } = await import("./scan-cursor-kv9scb2v.js");
23465
23879
  const scanStatus = await getScanStatus(directory);
23466
23880
  if (scanStatus.remaining_estimate > 0) {
23467
23881
  warnings.push(`Fair scan: reviewed ${knowledgeSummary.length} entries this sweep (generation ${scanStatus.generation}); ${scanStatus.remaining_estimate} more eligible entries will be visited in future curation sweeps.`);
@@ -23633,9 +24047,9 @@ var _internals27 = {
23633
24047
  verifyPostMortemKnowledgeActions,
23634
24048
  repairPostMortemActions,
23635
24049
  loadDefaultKnowledgeConfig: async (directory) => {
23636
- const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-8a7fyp87.js");
24050
+ const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-a7f88yc3.js");
23637
24051
  try {
23638
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-ygxb3jw4.js");
24052
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-2z00wqvb.js");
23639
24053
  const loaded = loadPluginConfigWithMeta2(directory);
23640
24054
  return KnowledgeConfigSchema2.parse(loaded.config.knowledge ?? {});
23641
24055
  } catch {
@@ -23643,11 +24057,11 @@ var _internals27 = {
23643
24057
  }
23644
24058
  },
23645
24059
  applyCuratorKnowledgeUpdates: async (directory, recommendations, knowledgeConfig, generation) => {
23646
- const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-yawrnk3t.js");
24060
+ const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-mpqpbr0r.js");
23647
24061
  return applyCuratorKnowledgeUpdates2(directory, recommendations, knowledgeConfig, generation);
23648
24062
  },
23649
24063
  checkHivePromotions: async (entries, knowledgeConfig, directory) => {
23650
- const { checkHivePromotions } = await import("./hive-promoter-d661k3qq.js");
24064
+ const { checkHivePromotions } = await import("./hive-promoter-zjtgbh4w.js");
23651
24065
  return checkHivePromotions(entries, knowledgeConfig, directory);
23652
24066
  },
23653
24067
  applyProposalTriage: async (directory, triage) => {
@@ -23656,7 +24070,7 @@ var _internals27 = {
23656
24070
  activateProposal,
23657
24071
  listSkills: listSkills2,
23658
24072
  sanitizeSlug
23659
- } = await import("./skill-generator-v2jkgp63.js");
24073
+ } = await import("./skill-generator-vwcrfrw3.js");
23660
24074
  const result = {
23661
24075
  approved: [],
23662
24076
  rejected: [],
@@ -24986,9 +25400,9 @@ function hashContent(content) {
24986
25400
  return createHash13("sha1").update(content).digest("hex");
24987
25401
  }
24988
25402
  async function loadConfigForPolicyCurator(directory) {
24989
- const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-8a7fyp87.js");
25403
+ const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-a7f88yc3.js");
24990
25404
  try {
24991
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-ygxb3jw4.js");
25405
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-2z00wqvb.js");
24992
25406
  const { config: loadedConfig } = loadPluginConfigWithMeta2(directory);
24993
25407
  return KnowledgeConfigSchema2.parse(loadedConfig.knowledge ?? {});
24994
25408
  } catch {
@@ -25466,12 +25880,15 @@ RETRY: your last output was missing ${result.missing.join("; ")}; produce valid
25466
25880
  }
25467
25881
  async function appendCuratorSkippedEvent(directory, record) {
25468
25882
  try {
25883
+ const redactedLesson = redactSecrets(record.lesson);
25469
25884
  appendCoreEventSync(directory, {
25470
25885
  timestamp: new Date().toISOString(),
25471
25886
  event: "curator_skipped",
25472
25887
  entry_id: record.entry_id,
25473
- lesson: record.lesson.slice(0, 200),
25474
- reason: record.reason
25888
+ content_hash: hashContent(redactedLesson),
25889
+ lesson: redactedLesson.slice(0, 200),
25890
+ reason: record.reason,
25891
+ ...record.duplicate_target_id ? { duplicate_target_id: record.duplicate_target_id } : {}
25475
25892
  });
25476
25893
  } catch {}
25477
25894
  }
@@ -25624,12 +26041,6 @@ async function curateAndStoreSwarm(lessons, projectName, phaseInfo, directory, c
25624
26041
  continue;
25625
26042
  }
25626
26043
  }
25627
- const duplicate = findActiveSwarmNearDuplicate(lesson, snapshotPlusNew, config.dedup_threshold);
25628
- if (duplicate) {
25629
- pendingReinforcementIds.add(duplicate.id);
25630
- skipped++;
25631
- continue;
25632
- }
25633
26044
  const entry = {
25634
26045
  id: crypto.randomUUID(),
25635
26046
  tier: "swarm",
@@ -25657,6 +26068,18 @@ async function curateAndStoreSwarm(lessons, projectName, phaseInfo, directory, c
25657
26068
  project_name: projectName,
25658
26069
  auto_generated: true
25659
26070
  };
26071
+ const duplicate = findActiveSwarmNearDuplicate(lesson, snapshotPlusNew, config.dedup_threshold);
26072
+ if (duplicate) {
26073
+ pendingReinforcementIds.add(duplicate.id);
26074
+ skipped++;
26075
+ await appendCuratorSkippedEvent(directory, {
26076
+ entry_id: entry.id,
26077
+ lesson,
26078
+ reason: "near_duplicate",
26079
+ duplicate_target_id: duplicate.id
26080
+ });
26081
+ continue;
26082
+ }
25660
26083
  const actionability = validateActionability(entry);
25661
26084
  if (!actionability.actionable && options?.llmDelegate) {
25662
26085
  pendingBatchEnrichment.push({ entry, lesson, category, tags });
@@ -25730,17 +26153,35 @@ async function curateAndStoreSwarm(lessons, projectName, phaseInfo, directory, c
25730
26153
  try {
25731
26154
  await appendUnactionable(directory, entry, "insight_unactionable");
25732
26155
  } catch {}
26156
+ await appendCuratorSkippedEvent(directory, {
26157
+ entry_id: entry.id,
26158
+ lesson: entry.lesson,
26159
+ reason: "insight_unactionable"
26160
+ });
25733
26161
  continue;
25734
26162
  }
25735
26163
  const marker = insightAdmissionMarker(resolveInsightCandidateId(cand));
25736
- if (findActiveEntryWithInsightMarker(snapshotPlusNew, marker)) {
26164
+ const admitted = findActiveEntryWithInsightMarker(snapshotPlusNew, marker);
26165
+ if (admitted) {
25737
26166
  skipped++;
26167
+ await appendCuratorSkippedEvent(directory, {
26168
+ entry_id: entry.id,
26169
+ lesson: entry.lesson,
26170
+ reason: "already_admitted",
26171
+ duplicate_target_id: admitted.id
26172
+ });
25738
26173
  continue;
25739
26174
  }
25740
26175
  const duplicate = findActiveSwarmNearDuplicate(entry.lesson, snapshotPlusNew, config.dedup_threshold);
25741
26176
  if (duplicate) {
25742
26177
  insightReinforcements.push({ entryId: duplicate.id, marker });
25743
26178
  skipped++;
26179
+ await appendCuratorSkippedEvent(directory, {
26180
+ entry_id: entry.id,
26181
+ lesson: entry.lesson,
26182
+ reason: "near_duplicate",
26183
+ duplicate_target_id: duplicate.id
26184
+ });
25744
26185
  continue;
25745
26186
  }
25746
26187
  toAdd.push(entry);
@@ -25749,6 +26190,7 @@ async function curateAndStoreSwarm(lessons, projectName, phaseInfo, directory, c
25749
26190
  } catch {}
25750
26191
  let stored = 0;
25751
26192
  let reinforced = 0;
26193
+ const transactionSkipEvents = [];
25752
26194
  if (toAdd.length > 0 || pendingReinforcementIds.size > 0 || insightReinforcements.length > 0) {
25753
26195
  await transactKnowledge(knowledgePath, (current) => {
25754
26196
  let changed = false;
@@ -25787,13 +26229,26 @@ async function curateAndStoreSwarm(lessons, projectName, phaseInfo, directory, c
25787
26229
  const trulyNew = [];
25788
26230
  for (const entry of toAdd) {
25789
26231
  const marker = findInsightAdmissionMarker(entry.source_knowledge_ids);
25790
- if (marker && findActiveEntryWithInsightMarker(current, marker)) {
26232
+ const admitted = marker ? findActiveEntryWithInsightMarker(current, marker) : undefined;
26233
+ if (admitted) {
25791
26234
  skipped++;
26235
+ transactionSkipEvents.push({
26236
+ entry_id: entry.id,
26237
+ lesson: entry.lesson,
26238
+ reason: "already_admitted",
26239
+ duplicate_target_id: admitted.id
26240
+ });
25792
26241
  continue;
25793
26242
  }
25794
26243
  const duplicate = findActiveSwarmNearDuplicate(entry.lesson, current, config.dedup_threshold);
25795
26244
  if (duplicate) {
25796
26245
  skipped++;
26246
+ transactionSkipEvents.push({
26247
+ entry_id: entry.id,
26248
+ lesson: entry.lesson,
26249
+ reason: "near_duplicate",
26250
+ duplicate_target_id: duplicate.id
26251
+ });
25797
26252
  const result = reinforceSwarmKnowledgeEntry(duplicate, {
25798
26253
  phase_number: phaseInfo.phase_number,
25799
26254
  confirmed_at: new Date().toISOString(),
@@ -25816,6 +26271,9 @@ async function curateAndStoreSwarm(lessons, projectName, phaseInfo, directory, c
25816
26271
  }
25817
26272
  return changed ? current : null;
25818
26273
  });
26274
+ for (const event of transactionSkipEvents) {
26275
+ await appendCuratorSkippedEvent(directory, event);
26276
+ }
25819
26277
  }
25820
26278
  await enforceKnowledgeCap(knowledgePath, config.swarm_max_entries);
25821
26279
  if (stored > 0) {
@@ -26022,7 +26480,7 @@ function safeRealpathSync(targetPath, fallback, realpathResolver = realpathSync3
26022
26480
  }
26023
26481
 
26024
26482
  // src/tools/repo-graph/types.ts
26025
- var GRAPH_SCHEMA_VERSION = "1.5.0";
26483
+ var GRAPH_SCHEMA_VERSION = "1.6.0";
26026
26484
  var DEFAULT_MAX_SOURCE_BYTES = 1024 * 1024;
26027
26485
  var FILE_ROLE_VALUES = [
26028
26486
  "api_route",
@@ -26111,6 +26569,15 @@ var SYMBOL_EDGE_RESOLUTION_VALUES = [
26111
26569
  "heuristic",
26112
26570
  "unresolved"
26113
26571
  ];
26572
+ var GRAPH_SYMBOL_KIND_VALUES = [
26573
+ "function",
26574
+ "class",
26575
+ "const",
26576
+ "type",
26577
+ "interface",
26578
+ "enum",
26579
+ "method"
26580
+ ];
26114
26581
  var PACKAGE_BOUNDARY_ROOTS = new Set([
26115
26582
  "packages",
26116
26583
  "crates",
@@ -26154,6 +26621,7 @@ var SECURITY_KIND_SET = new Set(SECURITY_KIND_VALUES);
26154
26621
  var SECURITY_CONFIDENCE_SET = new Set(SECURITY_CONFIDENCE_VALUES);
26155
26622
  var ONTOLOGY_FINDING_SEVERITY_SET = new Set(ONTOLOGY_FINDING_SEVERITY_VALUES);
26156
26623
  var IMPORT_TYPE_SET = new Set(IMPORT_TYPE_VALUES);
26624
+ var GRAPH_SYMBOL_KIND_SET = new Set(GRAPH_SYMBOL_KIND_VALUES);
26157
26625
  function validateWorkspace(workspace) {
26158
26626
  if (!workspace || typeof workspace !== "string" || workspace.trim() === "") {
26159
26627
  throw new Error("Invalid workspace: must be a non-empty string");
@@ -28988,7 +29456,7 @@ import {
28988
29456
  existsSync as existsSync19,
28989
29457
  mkdirSync as mkdirSync11,
28990
29458
  readFileSync as readFileSync16,
28991
- statSync as statSync10,
29459
+ statSync as statSync11,
28992
29460
  writeFileSync as writeFileSync9
28993
29461
  } from "fs";
28994
29462
  import { createRequire as createRequire3 } from "module";
@@ -30672,13 +31140,13 @@ class SQLiteMemoryProvider {
30672
31140
  }
30673
31141
  try {
30674
31142
  const wal = `${dbPath}-wal`;
30675
- const st = statSync10(wal);
31143
+ const st = statSync11(wal);
30676
31144
  if (st.size > 0)
30677
31145
  walPath = wal;
30678
31146
  } catch {}
30679
31147
  try {
30680
31148
  const shm = `${dbPath}-shm`;
30681
- const st = statSync10(shm);
31149
+ const st = statSync11(shm);
30682
31150
  if (st.size > 0)
30683
31151
  shmPath = shm;
30684
31152
  } catch {}
@@ -32149,7 +32617,7 @@ init_logger();
32149
32617
  import * as path39 from "path";
32150
32618
 
32151
32619
  // src/memory/memory-link.ts
32152
- import { existsSync as existsSync20, mkdirSync as mkdirSync12, readFileSync as readFileSync17, rmSync as rmSync2, statSync as statSync11 } from "fs";
32620
+ import { existsSync as existsSync20, mkdirSync as mkdirSync12, readFileSync as readFileSync17, rmSync as rmSync2, statSync as statSync12 } from "fs";
32153
32621
  import * as path38 from "path";
32154
32622
  init_logger();
32155
32623
  var MEMORY_LINK_POINTER_FILENAME = "memory-link.json";
@@ -32209,7 +32677,7 @@ var _resolutionCache = new Map;
32209
32677
  function pointerStatFingerprint(directory) {
32210
32678
  const pointerPath = resolveMemoryLinkPointerPath(directory);
32211
32679
  try {
32212
- const st = statSync11(pointerPath);
32680
+ const st = statSync12(pointerPath);
32213
32681
  return `${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
32214
32682
  } catch {
32215
32683
  return null;
@@ -33127,7 +33595,7 @@ function buildReflectionDataSummary(data) {
33127
33595
  lines.push("KNOWLEDGE DELTA:");
33128
33596
  lines.push(` - ${kd.sessionKnowledgeCreated} knowledge entries created this session.`);
33129
33597
  if (kd.curation) {
33130
- lines.push(` - Curation (finalize batch): ${kd.curation.stored} stored, ${kd.curation.reinforced} reinforced, ${kd.curation.skipped} skipped, ${kd.curation.rejected} rejected, ${kd.curation.quarantined} quarantined.`);
33598
+ lines.push(` - Curation (finalize batch): ${kd.curation.stored} stored, ${kd.curation.reinforced} reinforced, ${kd.curation.skipped} skipped (dedup/already-admitted; audit: .swarm/events.jsonl curator_skipped), ${kd.curation.rejected} rejected (validator-refused; ledger: .swarm/knowledge-rejected.jsonl), ${kd.curation.quarantined} quarantined (actionability-gated; queue: .swarm/knowledge-unactionable.jsonl; audit: .swarm/events.jsonl curator_skipped).`);
33131
33599
  }
33132
33600
  if (kd.admitted !== undefined || kd.reinforcedRealtime !== undefined || kd.rejectedCurator !== undefined) {
33133
33601
  lines.push(` - Realtime admission: ${kd.admitted ?? 0} admitted, ${kd.reinforcedRealtime ?? 0} reinforced, ${kd.rejectedCurator ?? 0} curator-rejected (from durable markers).`);
@@ -33163,7 +33631,7 @@ function buildSignalsBlock(data) {
33163
33631
  lines.push("**Knowledge Delta**");
33164
33632
  lines.push(`- ${kd.sessionKnowledgeCreated} knowledge entries created this session.`);
33165
33633
  if (kd.curation) {
33166
- lines.push(`- Curation (finalize batch): ${kd.curation.stored} stored, ${kd.curation.reinforced} reinforced, ${kd.curation.skipped} skipped, ${kd.curation.rejected} rejected, ${kd.curation.quarantined} quarantined.`);
33634
+ lines.push(`- Curation (finalize batch): ${kd.curation.stored} stored, ${kd.curation.reinforced} reinforced, ${kd.curation.skipped} skipped (dedup/already-admitted; audit: .swarm/events.jsonl curator_skipped), ${kd.curation.rejected} rejected (validator-refused; ledger: .swarm/knowledge-rejected.jsonl), ${kd.curation.quarantined} quarantined (actionability-gated; queue: .swarm/knowledge-unactionable.jsonl; audit: .swarm/events.jsonl curator_skipped).`);
33167
33635
  }
33168
33636
  if (kd.admitted !== undefined || kd.reinforcedRealtime !== undefined || kd.rejectedCurator !== undefined) {
33169
33637
  lines.push(`- Realtime admission: ${kd.admitted ?? 0} admitted, ${kd.reinforcedRealtime ?? 0} reinforced, ${kd.rejectedCurator ?? 0} curator-rejected (from durable markers).`);
@@ -36682,6 +37150,17 @@ async function runAbortableSkillReview(req, timeoutMs) {
36682
37150
  clearTimeout(timeout);
36683
37151
  }
36684
37152
  }
37153
+ async function archiveCloseSummary(ctx, closeSummaryPath, summaryWritten) {
37154
+ if (!summaryWritten || ctx.archiveStageFailed || !ctx.archiveDir)
37155
+ return;
37156
+ try {
37157
+ await fs17.copyFile(closeSummaryPath, path47.join(ctx.archiveDir, "close-summary.md"));
37158
+ } catch (error2) {
37159
+ const msg = error2 instanceof Error ? error2.message : String(error2);
37160
+ ctx.warnings.push(`Failed to archive close-summary.md: ${msg}`);
37161
+ log("[close-command] Failed to archive close-summary.md:", error2);
37162
+ }
37163
+ }
36685
37164
  function normalizeLessonText(text) {
36686
37165
  return (text ?? "").trim().toLowerCase();
36687
37166
  }
@@ -37176,7 +37655,7 @@ async function runFinalizeStage(ctx) {
37176
37655
  }
37177
37656
  }
37178
37657
  try {
37179
- const { CuratorConfigSchema: CCS } = await import("./schema-8a7fyp87.js");
37658
+ const { CuratorConfigSchema: CCS } = await import("./schema-a7f88yc3.js");
37180
37659
  const { config: pmLoadedConfig } = _internals41.loadPluginConfigWithMeta(ctx.directory);
37181
37660
  const curatorCfg = CCS.parse(pmLoadedConfig.curator ?? {});
37182
37661
  if (curatorCfg.enabled && curatorCfg.postmortem_enabled) {
@@ -37919,13 +38398,16 @@ No active state was archived or removed. Fix the reported durable-state problem,
37919
38398
  ...ctx.warnings.length > 0 ? ["## Warnings", ...ctx.warnings.map((w) => `- ${w}`), ""] : []
37920
38399
  ].join(`
37921
38400
  `);
38401
+ let closeSummaryWritten = false;
37922
38402
  try {
37923
38403
  await atomicWriteSwarmFile(closeSummaryPath, summaryContent);
38404
+ closeSummaryWritten = true;
37924
38405
  } catch (error2) {
37925
38406
  const msg = error2 instanceof Error ? error2.message : String(error2);
37926
38407
  ctx.warnings.push(`Failed to write close-summary.md: ${msg}`);
37927
38408
  log("[close-command] Failed to write close-summary.md:", error2);
37928
38409
  }
38410
+ await archiveCloseSummary(ctx, closeSummaryPath, closeSummaryWritten);
37929
38411
  try {
37930
38412
  const sessionIdsToEnd = [...swarmState.agentSessions.keys()];
37931
38413
  for (const sessionId of sessionIdsToEnd) {
@@ -38050,6 +38532,7 @@ var _internals41 = {
38050
38532
  runFinalizeRewardSweep,
38051
38533
  acquireFinalizeLock,
38052
38534
  runArchiveStage,
38535
+ archiveCloseSummary,
38053
38536
  runArchiveEvidenceRetention,
38054
38537
  runCleanStage,
38055
38538
  runAlignStage,
@@ -38058,7 +38541,7 @@ var _internals41 = {
38058
38541
  closePlanTerminalState: reconcileCloseTerminalStateForPlan,
38059
38542
  endAgentSession,
38060
38543
  flushAndDrainTelemetry: async () => {
38061
- const { flushAndDrainTelemetry } = await import("./telemetry-r8e8zey7.js");
38544
+ const { flushAndDrainTelemetry } = await import("./telemetry-3rh94wv3.js");
38062
38545
  return flushAndDrainTelemetry();
38063
38546
  },
38064
38547
  finalizeContextTelemetry: (directory) => {
@@ -38578,6 +39061,7 @@ function renderCostSummary(summary) {
38578
39061
  `Delegations: ${summary.delegations}`,
38579
39062
  `Tokens: input ${summary.total_input_tokens.toLocaleString()}, output ${summary.total_output_tokens.toLocaleString()}, reasoning ${summary.total_reasoning_tokens.toLocaleString()}, cache ${summary.total_cache_tokens.toLocaleString()}`,
38580
39063
  `Cost source: reported ${formatUsd(summary.total_reported_usd)}, estimated ${formatUsd(summary.total_estimated_usd)}, unavailable ${summary.unavailable_delegations}`,
39064
+ `Evidence: ${summary.evidence_status}; joins missed ${summary.join_miss_count}; telemetry errors ${summary.telemetry_error_count}; corrections accepted ${summary.accepted_corrections}, rejected ${summary.rejected_corrections}, duplicate ${summary.duplicate_corrections}`,
38581
39065
  "",
38582
39066
  "### By Agent"
38583
39067
  ];
@@ -39395,9 +39879,9 @@ var _internals45 = {
39395
39879
  loadPluginConfigWithMeta,
39396
39880
  loadCuratorDeps: async () => {
39397
39881
  const [{ CuratorConfigSchema }, curator, { createCuratorLLMDelegate: createCuratorLLMDelegate2 }] = await Promise.all([
39398
- import("./schema-8a7fyp87.js"),
39399
- import("./curator-yawrnk3t.js"),
39400
- import("./curator-llm-factory-21vqqvn3.js")
39882
+ import("./schema-a7f88yc3.js"),
39883
+ import("./curator-mpqpbr0r.js"),
39884
+ import("./curator-llm-factory-m3yw6sn5.js")
39401
39885
  ]);
39402
39886
  return { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 };
39403
39887
  }
@@ -39897,7 +40381,7 @@ ${USAGE9}`;
39897
40381
  // src/services/diagnose-service.ts
39898
40382
  init_package();
39899
40383
  import * as child_process5 from "child_process";
39900
- import { existsSync as existsSync32, readdirSync as readdirSync6, readFileSync as readFileSync23, statSync as statSync13 } from "fs";
40384
+ import { existsSync as existsSync32, readdirSync as readdirSync6, readFileSync as readFileSync23, statSync as statSync14 } from "fs";
39901
40385
  import * as path54 from "path";
39902
40386
  import { fileURLToPath } from "url";
39903
40387
 
@@ -40406,7 +40890,7 @@ async function computeCurationDiagnostics(directory, entries) {
40406
40890
  let scanCompleted = false;
40407
40891
  let scanRemaining = 0;
40408
40892
  try {
40409
- const { getScanStatus } = await import("./scan-cursor-59yj7tp9.js");
40893
+ const { getScanStatus } = await import("./scan-cursor-kv9scb2v.js");
40410
40894
  const status = await getScanStatus(directory);
40411
40895
  scanGeneration = status.generation;
40412
40896
  scanCompleted = status.completed;
@@ -40414,19 +40898,19 @@ async function computeCurationDiagnostics(directory, entries) {
40414
40898
  } catch {}
40415
40899
  let configMatch = null;
40416
40900
  try {
40417
- const { isLinked: isLinked2 } = await import("./knowledge-link-cj2abbae.js");
40901
+ const { isLinked: isLinked2 } = await import("./knowledge-link-a9fafeb3.js");
40418
40902
  if (isLinked2(directory)) {
40419
- const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-8a7fyp87.js");
40903
+ const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-a7f88yc3.js");
40420
40904
  let config;
40421
40905
  try {
40422
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-ygxb3jw4.js");
40906
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-2z00wqvb.js");
40423
40907
  const loaded = loadPluginConfigWithMeta2(directory);
40424
40908
  config = KnowledgeConfigSchema2.parse(loaded.config.knowledge ?? {});
40425
40909
  } catch {
40426
40910
  config = KnowledgeConfigSchema2.parse({});
40427
40911
  }
40428
40912
  const { cohortConfigFingerprint: cohortConfigFingerprint2 } = await import("./config-fingerprint-v22xh5a2.js");
40429
- const { buildConfigFingerprintInput: buildConfigFingerprintInput2, readCohortConfigFingerprint } = await import("./curation-policy-vn3m5nq2.js");
40913
+ const { buildConfigFingerprintInput: buildConfigFingerprintInput2, readCohortConfigFingerprint } = await import("./curation-policy-2gq8307w.js");
40430
40914
  const currentFp = cohortConfigFingerprint2(buildConfigFingerprintInput2(config));
40431
40915
  const cohortFp = await readCohortConfigFingerprint(directory);
40432
40916
  configMatch = cohortFp === null ? null : currentFp === cohortFp;
@@ -40833,7 +41317,7 @@ async function checkConfigBackups(directory) {
40833
41317
  }
40834
41318
  async function checkGitRepository(directory) {
40835
41319
  try {
40836
- if (!existsSync32(directory) || !statSync13(directory).isDirectory()) {
41320
+ if (!existsSync32(directory) || !statSync14(directory).isDirectory()) {
40837
41321
  return {
40838
41322
  name: "Git Repository",
40839
41323
  status: "\u274C",
@@ -41739,7 +42223,7 @@ async function handleDoctorCommand(directory, args) {
41739
42223
  const result = runConfigDoctor(config, directory);
41740
42224
  let output;
41741
42225
  if (enableAutoFix && result.hasAutoFixableIssues) {
41742
- const { runConfigDoctorWithFixes } = await import("./config-doctor-hs0x10ty.js");
42226
+ const { runConfigDoctorWithFixes } = await import("./config-doctor-8zawz3qh.js");
41743
42227
  const fixResult = await runConfigDoctorWithFixes(directory, config, true, {
41744
42228
  applyLossy: true
41745
42229
  });
@@ -42679,7 +43163,7 @@ async function handleEvidenceCommand(directory, args) {
42679
43163
  return formatTaskEvidenceMarkdown(evidenceData);
42680
43164
  }
42681
43165
  async function handleEvidenceSummaryCommand(directory) {
42682
- const { buildEvidenceSummary } = await import("./evidence-summary-service-kmc92b95.js");
43166
+ const { buildEvidenceSummary } = await import("./evidence-summary-service-qaq1eba9.js");
42683
43167
  const artifact = await buildEvidenceSummary(directory);
42684
43168
  if (!artifact) {
42685
43169
  return "No plan found. Run `/swarm plan` to check plan status.";
@@ -50419,7 +50903,7 @@ import {
50419
50903
  readFileSync as readFileSync32,
50420
50904
  renameSync as renameSync12,
50421
50905
  rmSync as rmSync7,
50422
- statSync as statSync17,
50906
+ statSync as statSync18,
50423
50907
  unlinkSync as unlinkSync12,
50424
50908
  writeSync
50425
50909
  } from "fs";
@@ -56025,7 +56509,7 @@ var MIN_MAX_CYCLES = 1;
56025
56509
  var MAX_MAX_CYCLES = 5;
56026
56510
  async function readLatestLoopState(directory) {
56027
56511
  try {
56028
- const { readdirSync: readdirSync9, statSync: statSync19, readFileSync: readFileSync38 } = await import("fs");
56512
+ const { readdirSync: readdirSync9, statSync: statSync20, readFileSync: readFileSync38 } = await import("fs");
56029
56513
  const loopDir = `${directory}/.swarm/loop`;
56030
56514
  let latestMtime = 0;
56031
56515
  let latestPath = null;
@@ -56036,7 +56520,7 @@ async function readLatestLoopState(directory) {
56036
56520
  continue;
56037
56521
  const statePath = `${loopDir}/${entry.name}/state.json`;
56038
56522
  try {
56039
- const mtime = statSync19(statePath).mtimeMs;
56523
+ const mtime = statSync20(statePath).mtimeMs;
56040
56524
  if (mtime > latestMtime) {
56041
56525
  latestMtime = mtime;
56042
56526
  latestPath = statePath;
@@ -56674,7 +57158,7 @@ import {
56674
57158
  openSync as openSync13,
56675
57159
  readSync as readSync7,
56676
57160
  realpathSync as realpathSync8,
56677
- statSync as statSync20
57161
+ statSync as statSync21
56678
57162
  } from "fs";
56679
57163
  var import_proper_lockfile9 = __toESM(require_proper_lockfile(), 1);
56680
57164
 
@@ -74113,12 +74597,16 @@ function autoReviewEvidenceRelativePath(trigger, scopeHash, phase) {
74113
74597
  }
74114
74598
  return path99.join("evidence", "auto-review", `${trigger}-${scopeHash.slice(0, 64)}.json`);
74115
74599
  }
74600
+ var _internals89 = {
74601
+ bunWrite,
74602
+ renameSync: fs46.renameSync
74603
+ };
74116
74604
  async function persistAutoReviewEvidence(directory, evidence2, options = {}) {
74117
74605
  const target = validateSwarmPath(directory, autoReviewEvidenceRelativePath(evidence2.trigger, evidence2.scope.hash, evidence2.phase));
74118
74606
  fs46.mkdirSync(path99.dirname(target), { recursive: true });
74119
74607
  const tempPath = `${target}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`;
74120
74608
  try {
74121
- await bunWrite(tempPath, `${JSON.stringify(evidence2, null, 2)}
74609
+ await _internals89.bunWrite(tempPath, `${JSON.stringify(evidence2, null, 2)}
74122
74610
  `);
74123
74611
  const safeTemp = validateSwarmPath(directory, path99.relative(path99.join(directory, ".swarm"), tempPath));
74124
74612
  const tempStat = fs46.lstatSync(safeTemp);
@@ -74134,7 +74622,7 @@ async function persistAutoReviewEvidence(directory, evidence2, options = {}) {
74134
74622
  if (!revalidatedStat.isFile() || revalidatedStat.isSymbolicLink()) {
74135
74623
  throw new Error("auto-review evidence temp path changed before commit");
74136
74624
  }
74137
- fs46.renameSync(revalidatedTemp, safeTarget);
74625
+ _internals89.renameSync(revalidatedTemp, safeTarget);
74138
74626
  invalidateCachedArtifact(safeTarget);
74139
74627
  return safeTarget;
74140
74628
  } finally {
@@ -74381,7 +74869,7 @@ function scopeFreshnessMismatches(reviewed, current) {
74381
74869
  }
74382
74870
  function createScopeVerifier(input, reviewed, maxBytes) {
74383
74871
  return async () => {
74384
- const current = await _internals89.collectReviewDiff({
74872
+ const current = await _internals90.collectReviewDiff({
74385
74873
  directory: input.directory,
74386
74874
  selector: input.selector,
74387
74875
  maxBytes
@@ -74390,7 +74878,7 @@ function createScopeVerifier(input, reviewed, maxBytes) {
74390
74878
  };
74391
74879
  }
74392
74880
  async function stalePersistenceResult(input, maxBytes, message, modelCalls) {
74393
- const current = await _internals89.collectReviewDiff({
74881
+ const current = await _internals90.collectReviewDiff({
74394
74882
  directory: input.directory,
74395
74883
  selector: input.selector,
74396
74884
  maxBytes
@@ -74677,10 +75165,20 @@ async function dispatchReviewerWithFallback(input, prompt, timeoutMs, promptByte
74677
75165
  return { result: attempts[0], attempts };
74678
75166
  }
74679
75167
  function addCost(evidence2, dispatches) {
75168
+ const MAX_REVIEW_COST_EVIDENCE = 32;
74680
75169
  evidence2.cost.model_calls = dispatches.length;
74681
75170
  evidence2.cost.prompt_bytes = dispatches.reduce((sum, dispatch) => sum + dispatch.promptBytes, 0);
74682
75171
  for (const dispatch of dispatches) {
74683
75172
  const fields = dispatch.costFields;
75173
+ for (const item of fields?.cost_evidence ?? []) {
75174
+ if (evidence2.cost.cost_evidence.length >= MAX_REVIEW_COST_EVIDENCE)
75175
+ break;
75176
+ evidence2.cost.cost_evidence.push(item);
75177
+ }
75178
+ if (fields?.evidence_status !== "complete") {
75179
+ evidence2.cost.evidence_status = "inconclusive";
75180
+ evidence2.cost.evidence_reason = fields?.evidence_reason ?? "missing_cost";
75181
+ }
74684
75182
  evidence2.cost.tokens_input += fields?.tokens_input ?? 0;
74685
75183
  evidence2.cost.tokens_output += fields?.tokens_output ?? 0;
74686
75184
  evidence2.cost.tokens_reasoning += fields?.tokens_reasoning ?? 0;
@@ -74729,7 +75227,9 @@ function baseEvidence(input, diff, status) {
74729
75227
  tokens_reasoning: 0,
74730
75228
  tokens_cache: 0,
74731
75229
  cost_usd: null,
74732
- cost_source: "unavailable"
75230
+ cost_source: "unavailable",
75231
+ cost_evidence: [],
75232
+ evidence_status: "complete"
74733
75233
  }
74734
75234
  };
74735
75235
  }
@@ -74778,7 +75278,7 @@ async function persistErrorResult(input, diff, result, error2, dispatches, promp
74778
75278
  evidence2.review.error = error2;
74779
75279
  addCost(evidence2, dispatches);
74780
75280
  try {
74781
- result.evidencePath = await _internals89.persistEvidence(input.directory, evidence2);
75281
+ result.evidencePath = await _internals90.persistEvidence(input.directory, evidence2);
74782
75282
  } catch {
74783
75283
  if (input.config.final_review.mode === "gate") {
74784
75284
  result.blocked = true;
@@ -74795,7 +75295,7 @@ async function runReviewEngine(input) {
74795
75295
  const gateMode = input.config.final_review.mode === "gate";
74796
75296
  const maxBytes = input.trigger === "task_completion" ? input.config.max_diff_kb * 1024 : input.config.final_review.max_diff_bytes;
74797
75297
  const timeoutMs = input.trigger === "task_completion" ? input.config.timeout_ms : input.config.final_review.timeout_ms;
74798
- const diff = await _internals89.collectReviewDiff({
75298
+ const diff = await _internals90.collectReviewDiff({
74799
75299
  directory: input.directory,
74800
75300
  selector: input.selector,
74801
75301
  maxBytes
@@ -74811,7 +75311,7 @@ async function runReviewEngine(input) {
74811
75311
  evidence3.policy.digest = evidence3.scope.manifest.review_policy_digest;
74812
75312
  let evidencePath2;
74813
75313
  try {
74814
- evidencePath2 = await _internals89.persistEvidence(input.directory, evidence3, { verifyCurrent: createScopeVerifier(input, diff, maxBytes) });
75314
+ evidencePath2 = await _internals90.persistEvidence(input.directory, evidence3, { verifyCurrent: createScopeVerifier(input, diff, maxBytes) });
74815
75315
  } catch (error2) {
74816
75316
  if (error2 instanceof ReviewScopeStaleError) {
74817
75317
  return stalePersistenceResult(input, maxBytes, "Review scope changed before clean evidence could be committed.", 0);
@@ -74835,7 +75335,7 @@ async function runReviewEngine(input) {
74835
75335
  });
74836
75336
  const reviewManifest = await materializeAutoReviewManifest(input.directory, diff.manifest, input.config);
74837
75337
  if (input.phase !== undefined && (input.trigger === "phase_completion" || input.trigger === "plan_completion")) {
74838
- const existing = _internals89.readPhaseEvidence(input.directory, input.phase);
75338
+ const existing = _internals90.readPhaseEvidence(input.directory, input.phase);
74839
75339
  const integrity = existing ? validateAutoReviewEvidenceIntegrity(input.directory, existing, {
74840
75340
  scopeHash: diff.scopeHash,
74841
75341
  phase: input.phase,
@@ -74963,7 +75463,7 @@ async function runReviewEngine(input) {
74963
75463
  validation: byId.get(finding.finding_id)
74964
75464
  }));
74965
75465
  }
74966
- const currentScope = await _internals89.collectReviewDiff({
75466
+ const currentScope = await _internals90.collectReviewDiff({
74967
75467
  directory: input.directory,
74968
75468
  selector: input.selector,
74969
75469
  maxBytes
@@ -75044,7 +75544,7 @@ async function runReviewEngine(input) {
75044
75544
  findingValidations: findings.map((finding) => finding.validation).filter((item) => Boolean(item))
75045
75545
  });
75046
75546
  receiptId = receipt.id;
75047
- receiptPath = await _internals89.persistReceipt(input.directory, receipt, {
75547
+ receiptPath = await _internals90.persistReceipt(input.directory, receipt, {
75048
75548
  verifyCurrent: createScopeVerifier(input, diff, maxBytes)
75049
75549
  });
75050
75550
  evidence2.receipt_path = receiptPath;
@@ -75074,7 +75574,7 @@ async function runReviewEngine(input) {
75074
75574
  }
75075
75575
  let evidencePath;
75076
75576
  try {
75077
- evidencePath = await _internals89.persistEvidence(input.directory, evidence2, {
75577
+ evidencePath = await _internals90.persistEvidence(input.directory, evidence2, {
75078
75578
  verifyCurrent: createScopeVerifier(input, diff, maxBytes)
75079
75579
  });
75080
75580
  } catch (error2) {
@@ -75112,7 +75612,7 @@ async function runReviewEngine(input) {
75112
75612
  input.injectAdvisory?.(input.sessionID, advisoryMessage(input, result));
75113
75613
  return result;
75114
75614
  }
75115
- var _internals89 = {
75615
+ var _internals90 = {
75116
75616
  collectReviewDiff,
75117
75617
  persistEvidence: persistAutoReviewEvidence,
75118
75618
  persistReceipt: persistReviewReceipt,
@@ -75383,7 +75883,7 @@ async function handleReviewCommand(ctx) {
75383
75883
  } catch (error2) {
75384
75884
  return `Review configuration error: ${error2 instanceof Error ? error2.message : String(error2)}`;
75385
75885
  }
75386
- const result = await _internals90.runReviewEngine({
75886
+ const result = await _internals91.runReviewEngine({
75387
75887
  directory: ctx.directory,
75388
75888
  sessionID: ctx.sessionID,
75389
75889
  trigger: "manual",
@@ -75397,10 +75897,10 @@ async function handleReviewCommand(ctx) {
75397
75897
  validatorModel,
75398
75898
  validatorFallbackModels
75399
75899
  });
75400
- const evidence2 = _internals90.readEvidence(result.evidencePath, ctx.directory);
75900
+ const evidence2 = _internals91.readEvidence(result.evidencePath, ctx.directory);
75401
75901
  return parsed.json ? renderJson(result, evidence2, parsed.selector) : renderHuman(result, evidence2, parsed.selector);
75402
75902
  }
75403
- var _internals90 = {
75903
+ var _internals91 = {
75404
75904
  runReviewEngine,
75405
75905
  readEvidence
75406
75906
  };
@@ -75642,7 +76142,7 @@ async function handleRollbackCommand(directory, args) {
75642
76142
  // src/commands/sdd.ts
75643
76143
  import * as fs50 from "fs";
75644
76144
  import * as path103 from "path";
75645
- var _internals91 = {
76145
+ var _internals92 = {
75646
76146
  writeProjectedSpecSync
75647
76147
  };
75648
76148
  var SWARM_SPEC_REL = path103.join(".swarm", "spec.md");
@@ -76042,7 +76542,7 @@ ${USAGE14}`;
76042
76542
 
76043
76543
  ${USAGE14}`;
76044
76544
  }
76045
- const result2 = _internals91.writeProjectedSpecSync(directory, {
76545
+ const result2 = _internals92.writeProjectedSpecSync(directory, {
76046
76546
  source: "speckit",
76047
76547
  feature: resolution.feature,
76048
76548
  dryRun: parsed.dryRun,
@@ -76100,7 +76600,7 @@ ${formatList(result2.projection.warnings)}` : ""
76100
76600
  ].join(`
76101
76601
  `);
76102
76602
  }
76103
- const result = _internals91.writeProjectedSpecSync(directory, {
76603
+ const result = _internals92.writeProjectedSpecSync(directory, {
76104
76604
  changeId: parsed.changeId,
76105
76605
  dryRun: parsed.dryRun,
76106
76606
  overwrite: parsed.overwrite
@@ -76245,7 +76745,7 @@ import {
76245
76745
  openSync as openSync20,
76246
76746
  readFileSync as readFileSync46,
76247
76747
  renameSync as renameSync16,
76248
- statSync as statSync24,
76748
+ statSync as statSync25,
76249
76749
  unlinkSync as unlinkSync22,
76250
76750
  writeFileSync as writeFileSync18,
76251
76751
  writeFileSync as writeFileSyncAsync
@@ -76327,7 +76827,7 @@ function writeFileFsyncedThenRename(tempPath, targetPath, data) {
76327
76827
  throw err;
76328
76828
  }
76329
76829
  }
76330
- var _internals92 = {
76830
+ var _internals93 = {
76331
76831
  withEvidenceLock,
76332
76832
  writeFileFsyncedThenRename,
76333
76833
  writeFileSync: writeFileSyncAsync,
@@ -76335,7 +76835,7 @@ var _internals92 = {
76335
76835
  renameSync: renameSync16,
76336
76836
  unlinkSync: unlinkSync22,
76337
76837
  existsSync: existsSync57,
76338
- statSync: statSync24
76838
+ statSync: statSync25
76339
76839
  };
76340
76840
  async function appendEvent2(directory, eventInput) {
76341
76841
  assertProjectRoot(directory);
@@ -76346,7 +76846,7 @@ async function appendEvent2(directory, eventInput) {
76346
76846
  throw new Error(`invalid candidate id: ${eventInput.candidateId}`);
76347
76847
  }
76348
76848
  const filePath = ledgerPath2(directory, eventInput.skillSlug, eventInput.candidateId);
76349
- return _internals92.withEvidenceLock(directory, path104.join(".swarm", "evolution", "skills", eventInput.skillSlug, eventInput.candidateId, "lifecycle.jsonl"), "skill-opt-ledger", "append-skill-opt-event", async () => {
76849
+ return _internals93.withEvidenceLock(directory, path104.join(".swarm", "evolution", "skills", eventInput.skillSlug, eventInput.candidateId, "lifecycle.jsonl"), "skill-opt-ledger", "append-skill-opt-event", async () => {
76350
76850
  ensureCandidateDir(directory, eventInput.skillSlug, eventInput.candidateId);
76351
76851
  const existing = existsSync57(filePath) ? readFileSync46(filePath, "utf8") : "";
76352
76852
  const events = parseEventsFromText(existing);
@@ -76378,8 +76878,8 @@ async function appendEvent2(directory, eventInput) {
76378
76878
  const validContent = events.map((e) => JSON.stringify(e)).join(`
76379
76879
  `) + (events.length > 0 ? `
76380
76880
  ` : "");
76381
- _internals92.writeFileFsyncedThenRename(tempPath, filePath, validContent + line);
76382
- const verify = parseEventsFromText(_internals92.readFileSync(filePath, "utf8"));
76881
+ _internals93.writeFileFsyncedThenRename(tempPath, filePath, validContent + line);
76882
+ const verify = parseEventsFromText(_internals93.readFileSync(filePath, "utf8"));
76383
76883
  const last = verify.length > 0 ? verify[verify.length - 1] : null;
76384
76884
  if (!last || last.seq !== event.seq || last.hashAfter !== event.hashAfter) {
76385
76885
  throw new Error(`skill-opt ledger append verification failed for candidate ${event.candidateId} seq ${event.seq}`);
@@ -76483,7 +76983,7 @@ function writeStateProjection(directory, skillSlug, candidateId2, replay) {
76483
76983
  updatedAt: new Date().toISOString()
76484
76984
  };
76485
76985
  const tempPath = `${target}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`;
76486
- _internals92.writeFileFsyncedThenRename(tempPath, target, `${JSON.stringify(projection, null, 2)}
76986
+ _internals93.writeFileFsyncedThenRename(tempPath, target, `${JSON.stringify(projection, null, 2)}
76487
76987
  `);
76488
76988
  }
76489
76989
  function writeArtifact(directory, skillSlug, candidateId2, fileName, content) {
@@ -76491,7 +76991,7 @@ function writeArtifact(directory, skillSlug, candidateId2, fileName, content) {
76491
76991
  const dir = ensureCandidateDir(directory, skillSlug, candidateId2);
76492
76992
  const target = path104.join(dir, fileName);
76493
76993
  const tempPath = `${target}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`;
76494
- _internals92.writeFileFsyncedThenRename(tempPath, target, content);
76994
+ _internals93.writeFileFsyncedThenRename(tempPath, target, content);
76495
76995
  return target;
76496
76996
  }
76497
76997
  function readArtifact(directory, skillSlug, candidateId2, fileName) {
@@ -76584,16 +77084,16 @@ function currentCandidateState(directory, skillSlug, candidateId2) {
76584
77084
  function writeSkillFileAtomic(targetPath, content) {
76585
77085
  const tempPath = `${targetPath}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`;
76586
77086
  try {
76587
- _internals93.writeFileSync(tempPath, content, "utf8");
76588
- _internals93.renameSync(tempPath, targetPath);
77087
+ _internals94.writeFileSync(tempPath, content, "utf8");
77088
+ _internals94.renameSync(tempPath, targetPath);
76589
77089
  } finally {
76590
77090
  try {
76591
77091
  if (existsSync58(tempPath))
76592
- _internals93.unlinkSync(tempPath);
77092
+ _internals94.unlinkSync(tempPath);
76593
77093
  } catch {}
76594
77094
  }
76595
77095
  }
76596
- var _internals93 = {
77096
+ var _internals94 = {
76597
77097
  writeFileSync: writeFileSync19,
76598
77098
  renameSync: renameSync17,
76599
77099
  unlinkSync: unlinkSync23
@@ -77175,7 +77675,7 @@ function buildGeneratorInputs(args) {
77175
77675
  }
77176
77676
  };
77177
77677
  }
77178
- var _internals94 = {
77678
+ var _internals95 = {
77179
77679
  draftDeterministic: defaultDeterministicDraft
77180
77680
  };
77181
77681
  function defaultDeterministicDraft(inputs) {
@@ -77245,7 +77745,7 @@ function countChangedLines(a, b) {
77245
77745
  return changed;
77246
77746
  }
77247
77747
  function draftCandidate(inputs) {
77248
- const candidate2 = _internals94.draftDeterministic(inputs);
77748
+ const candidate2 = _internals95.draftDeterministic(inputs);
77249
77749
  enforceTrustRegion(candidate2, inputs.budget);
77250
77750
  return candidate2;
77251
77751
  }
@@ -77288,7 +77788,7 @@ import * as path108 from "path";
77288
77788
  // src/hooks/spawn-helper.ts
77289
77789
  import * as child_process7 from "child_process";
77290
77790
  var WIN32_CMD_BINARIES = new Set(["npm", "npx", "pnpm", "yarn"]);
77291
- var _internals95 = {
77791
+ var _internals96 = {
77292
77792
  spawn: child_process7.spawn
77293
77793
  };
77294
77794
  function spawnAsync(command, cwd, timeoutMs) {
@@ -77296,7 +77796,7 @@ function spawnAsync(command, cwd, timeoutMs) {
77296
77796
  try {
77297
77797
  const [rawCmd, ...args] = command;
77298
77798
  const cmd = process.platform === "win32" && WIN32_CMD_BINARIES.has(rawCmd) && !rawCmd.includes(".") ? `${rawCmd}.cmd` : rawCmd;
77299
- const proc = _internals95.spawn(cmd, args, {
77799
+ const proc = _internals96.spawn(cmd, args, {
77300
77800
  cwd,
77301
77801
  stdio: ["ignore", "pipe", "pipe"]
77302
77802
  });
@@ -77362,7 +77862,7 @@ function spawnAsync(command, cwd, timeoutMs) {
77362
77862
  }
77363
77863
 
77364
77864
  // src/services/skill-optimizer/smoke.ts
77365
- var _internals96 = {
77865
+ var _internals97 = {
77366
77866
  validateSkillPath,
77367
77867
  isSymbolicLink: (p) => {
77368
77868
  try {
@@ -77383,7 +77883,7 @@ var _internals96 = {
77383
77883
  async function validateSkillSmoke(input) {
77384
77884
  const notes = [];
77385
77885
  const repoRel = path108.join(".opencode", "skills", "generated", input.skillSlug, "SKILL.md");
77386
- if (!_internals96.validateSkillPath(repoRel)) {
77886
+ if (!_internals97.validateSkillPath(repoRel)) {
77387
77887
  return {
77388
77888
  ok: false,
77389
77889
  verdict: "VIOLATED",
@@ -77392,16 +77892,16 @@ async function validateSkillSmoke(input) {
77392
77892
  }
77393
77893
  const skillRoot = path108.join(input.directory, ".opencode", "skills", "generated", input.skillSlug);
77394
77894
  if (existsSync59(skillRoot)) {
77395
- if (_internals96.isSymbolicLink(skillRoot)) {
77895
+ if (_internals97.isSymbolicLink(skillRoot)) {
77396
77896
  return {
77397
77897
  ok: false,
77398
77898
  verdict: "VIOLATED",
77399
77899
  notes: ["skill root is a symlink (reparse denied)"]
77400
77900
  };
77401
77901
  }
77402
- const realRoot = _internals96.realpath(skillRoot);
77403
- const realProjectDir = _internals96.realpath(input.directory);
77404
- if (_internals96.escapedRoot(realProjectDir, realRoot)) {
77902
+ const realRoot = _internals97.realpath(skillRoot);
77903
+ const realProjectDir = _internals97.realpath(input.directory);
77904
+ if (_internals97.escapedRoot(realProjectDir, realRoot)) {
77405
77905
  return {
77406
77906
  ok: false,
77407
77907
  verdict: "VIOLATED",
@@ -77419,7 +77919,7 @@ async function validateSkillSmoke(input) {
77419
77919
  notes: [`frontmatter: ${fmError}`]
77420
77920
  };
77421
77921
  }
77422
- const rejected = await _internals96.isRejectedSkillContent(input.directory, input.skillSlug, input.candidateContent);
77922
+ const rejected = await _internals97.isRejectedSkillContent(input.directory, input.skillSlug, input.candidateContent);
77423
77923
  if (rejected) {
77424
77924
  return {
77425
77925
  ok: false,
@@ -77429,7 +77929,7 @@ async function validateSkillSmoke(input) {
77429
77929
  ]
77430
77930
  };
77431
77931
  }
77432
- const evalResult = await _internals96.evaluateSkillChange({
77932
+ const evalResult = await _internals97.evaluateSkillChange({
77433
77933
  directory: input.directory,
77434
77934
  slug: input.skillSlug,
77435
77935
  candidateContent: input.candidateContent,
@@ -77448,7 +77948,7 @@ async function validateSkillSmoke(input) {
77448
77948
  notes.push(`phrase-eval passed (score ${evalResult.candidateScore.toFixed(2)})`);
77449
77949
  }
77450
77950
  if (input.checkCommand && input.checkCommand.length > 0) {
77451
- const cmdResult = await _internals96.spawnAsync(input.checkCommand, input.directory, input.checkTimeoutMs ?? 60000);
77951
+ const cmdResult = await _internals97.spawnAsync(input.checkCommand, input.directory, input.checkTimeoutMs ?? 60000);
77452
77952
  if (!cmdResult || cmdResult.exitCode !== 0) {
77453
77953
  return {
77454
77954
  ok: false,
@@ -77518,7 +78018,7 @@ async function prepareCandidatePayloads(inputRoot, candidateId2, skillSlug, base
77518
78018
  candidate2.contentHash = await computeCandidateInputContentHash2(inputRoot, candidate2);
77519
78019
  return { baseline, candidate: candidate2 };
77520
78020
  }
77521
- var _internals97 = {
78021
+ var _internals98 = {
77522
78022
  tryAcquireLock,
77523
78023
  emitTelemetry: emit,
77524
78024
  evaluateCandidateV1,
@@ -77526,7 +78026,7 @@ var _internals97 = {
77526
78026
  };
77527
78027
  async function acquireProjectLock(directory) {
77528
78028
  assertProjectRoot(directory);
77529
- const result = await _internals97.tryAcquireLock(directory, PROJECT_LOCK_PATH, "skill-opt-controller", "project-run");
78029
+ const result = await _internals98.tryAcquireLock(directory, PROJECT_LOCK_PATH, "skill-opt-controller", "project-run");
77530
78030
  if (!result.acquired)
77531
78031
  return null;
77532
78032
  return async () => {
@@ -77540,7 +78040,7 @@ async function acquireProjectLock(directory) {
77540
78040
  async function acquireSkillLock(directory, skillSlug) {
77541
78041
  assertProjectRoot(directory);
77542
78042
  const lockPath = path109.join(".swarm", "evolution", "skills", skillSlug, ".skill.lock");
77543
- const result = await _internals97.tryAcquireLock(directory, lockPath, "skill-opt-controller", `skill-${skillSlug}`);
78043
+ const result = await _internals98.tryAcquireLock(directory, lockPath, "skill-opt-controller", `skill-${skillSlug}`);
77544
78044
  if (!result.acquired)
77545
78045
  return null;
77546
78046
  return async () => {
@@ -77737,13 +78237,13 @@ async function runValidationWithTransientRetry(input, candidateContent, baseline
77737
78237
  while (true) {
77738
78238
  try {
77739
78239
  const evalInputRoot = input.inputRoot ?? input.directory;
77740
- const { baseline, candidate: candidate2 } = await _internals97.prepareCandidatePayloads(evalInputRoot, candidateId2, input.skillSlug, input.baselineModel, input.candidateModel, baselineContent, candidateContent);
78240
+ const { baseline, candidate: candidate2 } = await _internals98.prepareCandidatePayloads(evalInputRoot, candidateId2, input.skillSlug, input.baselineModel, input.candidateModel, baselineContent, candidateContent);
77741
78241
  if (!input.dispatcher) {
77742
78242
  throw new Error("no evaluation dispatcher available (cannot run validation)");
77743
78243
  }
77744
- const { createModelEvaluationExecutor: createModelEvaluationExecutor2 } = await import("./runner-sj5sf36c.js");
78244
+ const { createModelEvaluationExecutor: createModelEvaluationExecutor2 } = await import("./runner-atbehryj.js");
77745
78245
  const executor = createModelEvaluationExecutor2(input.dispatcher, input.sessionId);
77746
- const result = await withProtectedSetIntegrity([evalInputRoot, ...protectedRoots(input.directory)], () => _internals97.evaluateCandidateV1({
78246
+ const result = await withProtectedSetIntegrity([evalInputRoot, ...protectedRoots(input.directory)], () => _internals98.evaluateCandidateV1({
77747
78247
  projectRoot: input.directory,
77748
78248
  inputRoot: input.inputRoot ?? input.directory,
77749
78249
  tasks: input.validationTasks,
@@ -77801,7 +78301,7 @@ async function runValidationWithTransientRetry(input, candidateContent, baseline
77801
78301
  deadband: input.config.deadband
77802
78302
  };
77803
78303
  }
77804
- _internals97.emitTelemetry?.("loop_detected", {
78304
+ _internals98.emitTelemetry?.("loop_detected", {
77805
78305
  skillSlug: input.skillSlug,
77806
78306
  reason: message.slice(0, 160),
77807
78307
  source: "skill-opt-controller"
@@ -78656,13 +79156,46 @@ function getCompactionMetrics(sessionId) {
78656
79156
  }
78657
79157
 
78658
79158
  // src/services/status-service.ts
78659
- var _internals98 = {
79159
+ var _internals99 = {
78660
79160
  loadLeanTurboRunState,
78661
79161
  hasActiveLeanTurbo,
78662
79162
  hasActiveFullAuto,
78663
79163
  getActiveFullAutoSessionID,
78664
- loadFullAutoRunState
79164
+ loadFullAutoRunState,
79165
+ summarizeTelemetryCosts
78665
79166
  };
79167
+ var MAX_TRACKED_TELEMETRY_COST_SUMMARIES = 32;
79168
+ var telemetryCostSummaryCache = new Map;
79169
+ function getTelemetryCostSummary(directory) {
79170
+ const stamp = readTelemetryCostStamp(directory);
79171
+ const cached = telemetryCostSummaryCache.get(directory);
79172
+ if (cached && cached.stamp === stamp)
79173
+ return cached.summary;
79174
+ const summary = _internals99.summarizeTelemetryCosts(directory);
79175
+ telemetryCostSummaryCache.set(directory, { stamp, summary });
79176
+ while (telemetryCostSummaryCache.size > MAX_TRACKED_TELEMETRY_COST_SUMMARIES) {
79177
+ const oldest = telemetryCostSummaryCache.keys().next().value;
79178
+ if (oldest === undefined)
79179
+ break;
79180
+ telemetryCostSummaryCache.delete(oldest);
79181
+ }
79182
+ return summary;
79183
+ }
79184
+ function readTelemetryCostStamp(directory) {
79185
+ const swarmDir = path114.join(directory, ".swarm");
79186
+ const files = [
79187
+ path114.join(swarmDir, "telemetry.jsonl.1"),
79188
+ path114.join(swarmDir, "telemetry.jsonl")
79189
+ ];
79190
+ return files.map((file) => {
79191
+ try {
79192
+ const stat9 = fsSync4.statSync(file);
79193
+ return stat9.isFile() ? `${stat9.mtimeMs}:${stat9.ctimeMs}:${stat9.size}` : "missing";
79194
+ } catch {
79195
+ return "missing";
79196
+ }
79197
+ }).join("|");
79198
+ }
78666
79199
  async function collectBackgroundWorkStatus(directory) {
78667
79200
  try {
78668
79201
  await maintainBackgroundDelegations(directory, {
@@ -78930,11 +79463,11 @@ async function getStatusData(directory, agents, sessionId, options) {
78930
79463
  } catch {
78931
79464
  status.memoryCohort = { linked: false };
78932
79465
  }
78933
- status.fullAutoActive = _internals98.hasActiveFullAuto();
79466
+ status.fullAutoActive = _internals99.hasActiveFullAuto();
78934
79467
  if (status.fullAutoActive) {
78935
- const sid = _internals98.getActiveFullAutoSessionID();
79468
+ const sid = _internals99.getActiveFullAutoSessionID();
78936
79469
  if (sid) {
78937
- const runState = _internals98.loadFullAutoRunState(directory, sid);
79470
+ const runState = _internals99.loadFullAutoRunState(directory, sid);
78938
79471
  if (runState?.lastEscalation) {
78939
79472
  status.fullAutoEscalation = {
78940
79473
  reason: runState.lastEscalation.reason,
@@ -78964,11 +79497,24 @@ async function getStatusData(directory, agents, sessionId, options) {
78964
79497
  };
78965
79498
  }
78966
79499
  }
78967
- return enrichWithLeanTurbo(status, directory);
79500
+ status = enrichWithLeanTurbo(status, directory);
79501
+ try {
79502
+ const costs = getTelemetryCostSummary(directory);
79503
+ status.costs = {
79504
+ totalCostUsd: costs.total_cost_usd,
79505
+ delegations: costs.delegations,
79506
+ unavailableDelegations: costs.unavailable_delegations,
79507
+ evidenceStatus: costs.evidence_status,
79508
+ conflictCount: costs.conflict_count,
79509
+ joinMissCount: costs.join_miss_count,
79510
+ telemetryErrorCount: costs.telemetry_error_count
79511
+ };
79512
+ } catch {}
79513
+ return status;
78968
79514
  }
78969
79515
  function enrichWithLeanTurbo(status, directory) {
78970
79516
  const turboMode = hasActiveTurboMode();
78971
- const leanActive = _internals98.hasActiveLeanTurbo();
79517
+ const leanActive = _internals99.hasActiveLeanTurbo();
78972
79518
  let turboStrategy = "off";
78973
79519
  if (leanActive) {
78974
79520
  turboStrategy = "lean";
@@ -78999,7 +79545,7 @@ function enrichWithLeanTurbo(status, directory) {
78999
79545
  }
79000
79546
  }
79001
79547
  if (leanSessionID) {
79002
- const runState = _internals98.loadLeanTurboRunState(directory, leanSessionID);
79548
+ const runState = _internals99.loadLeanTurboRunState(directory, leanSessionID);
79003
79549
  if (runState) {
79004
79550
  status.leanTurboPhase = runState.phase;
79005
79551
  status.leanMaxParallelCoders = runState.maxParallelCoders;
@@ -79041,6 +79587,10 @@ function formatStatusMarkdown(status) {
79041
79587
  `**Tasks**: ${status.completedTasks}/${status.totalTasks} complete`,
79042
79588
  `**Agents**: ${status.agentCount} registered`
79043
79589
  ];
79590
+ if (status.costs && status.costs.delegations > 0) {
79591
+ const evidence2 = status.costs.evidenceStatus === "complete" ? "complete evidence" : `inconclusive evidence (${status.costs.unavailableDelegations} unavailable, ${status.costs.conflictCount} conflicts, ${status.costs.joinMissCount} join misses, ${status.costs.telemetryErrorCount} telemetry errors)`;
79592
+ lines.push("", `**Cost**: $${status.costs.totalCostUsd.toFixed(6)} across ${status.costs.delegations} delegations \u2014 ${evidence2}`);
79593
+ }
79044
79594
  if (status.lastActivity) {
79045
79595
  const label = status.lastActivity.agoLabel;
79046
79596
  const annotation = status.lastActivity.agoLabel !== "never" && status.lastActivity.agoMs !== null && status.lastActivity.agoMs > 120 * 1000 ? " \u26A0\uFE0F possibly stalled" : "";
@@ -79363,7 +79913,7 @@ init_logger();
79363
79913
  var TURBO_BYPASS_DISCLOSURE = "Bypassed: Stage B (reviewer + test_engineer) for Tier 0-2 tasks; phase_complete Gates 1-5 " + "(completion-verify, drift-verifier, hallucination-guard, mutation-gate, phase-council). " + "Still enforced: Stage A (lint, imports, pre_check_batch); Tier 3 Stage B; Gate 5b " + "(architecture-supervisor); Gate 6 (final-council); Gate 7 (full-auto).";
79364
79914
 
79365
79915
  // src/commands/turbo.ts
79366
- var _internals99 = {
79916
+ var _internals100 = {
79367
79917
  loadPluginConfigWithMeta
79368
79918
  };
79369
79919
  async function handleTurboCommand(directory, args, sessionID) {
@@ -79423,7 +79973,7 @@ async function handleTurboCommand(directory, args, sessionID) {
79423
79973
  if (arg0 === "on") {
79424
79974
  let strategy = "standard";
79425
79975
  try {
79426
- const { config } = _internals99.loadPluginConfigWithMeta(directory);
79976
+ const { config } = _internals100.loadPluginConfigWithMeta(directory);
79427
79977
  if (config.turbo?.strategy === "lean") {
79428
79978
  strategy = "lean";
79429
79979
  }
@@ -79520,7 +80070,7 @@ function enableLeanTurbo(session, directory, sessionID) {
79520
80070
  let maxParallelCoders = 4;
79521
80071
  let conflictPolicy = "serialize";
79522
80072
  try {
79523
- const { config } = _internals99.loadPluginConfigWithMeta(directory);
80073
+ const { config } = _internals100.loadPluginConfigWithMeta(directory);
79524
80074
  const leanConfig = config.turbo?.lean;
79525
80075
  if (leanConfig) {
79526
80076
  maxParallelCoders = leanConfig.max_parallel_coders ?? 4;
@@ -79728,7 +80278,7 @@ function findSimilarCommands(query) {
79728
80278
  }
79729
80279
  const scored = VALID_COMMANDS.map((cmd) => {
79730
80280
  const cmdLower = cmd.toLowerCase();
79731
- const fullScore = _internals100.levenshteinDistance(q, cmdLower);
80281
+ const fullScore = _internals101.levenshteinDistance(q, cmdLower);
79732
80282
  let tokenScore = Infinity;
79733
80283
  if (cmd.includes(" ") || cmd.includes("-")) {
79734
80284
  const qTokens = q.split(/[\s-]+/);
@@ -79741,7 +80291,7 @@ function findSimilarCommands(query) {
79741
80291
  for (const ct of cmdTokens) {
79742
80292
  if (ct.length === 0)
79743
80293
  continue;
79744
- const dist = _internals100.levenshteinDistance(qt, ct);
80294
+ const dist = _internals101.levenshteinDistance(qt, ct);
79745
80295
  if (dist < minDist)
79746
80296
  minDist = dist;
79747
80297
  }
@@ -79751,7 +80301,7 @@ function findSimilarCommands(query) {
79751
80301
  }
79752
80302
  const dashStrippedQ = q.replace(/-/g, "");
79753
80303
  const dashStrippedCmd = cmdLower.replace(/-/g, "");
79754
- const dashScore = _internals100.levenshteinDistance(dashStrippedQ, dashStrippedCmd);
80304
+ const dashScore = _internals101.levenshteinDistance(dashStrippedQ, dashStrippedCmd);
79755
80305
  const score = Math.min(fullScore, tokenScore, dashScore);
79756
80306
  return { cmd, score };
79757
80307
  });
@@ -79786,16 +80336,16 @@ function buildDetailedHelp(commandName, entry) {
79786
80336
  async function handleHelpCommand(ctx) {
79787
80337
  const targetCommand = ctx.args.join(" ");
79788
80338
  if (!targetCommand) {
79789
- const { buildHelpText } = await import("./index-4wy9kzjg.js");
80339
+ const { buildHelpText } = await import("./index-36sgq7n9.js");
79790
80340
  return buildHelpText();
79791
80341
  }
79792
80342
  const tokens = targetCommand.split(/\s+/);
79793
- const resolved = _internals100.resolveCommand(tokens);
80343
+ const resolved = _internals101.resolveCommand(tokens);
79794
80344
  if (resolved) {
79795
- return _internals100.buildDetailedHelp(resolved.key, resolved.entry);
80345
+ return _internals101.buildDetailedHelp(resolved.key, resolved.entry);
79796
80346
  }
79797
- const similar = _internals100.findSimilarCommands(targetCommand);
79798
- const { buildHelpText: fullHelp } = await import("./index-4wy9kzjg.js");
80347
+ const similar = _internals101.findSimilarCommands(targetCommand);
80348
+ const { buildHelpText: fullHelp } = await import("./index-36sgq7n9.js");
79799
80349
  if (similar.length > 0) {
79800
80350
  return `Command '/swarm ${targetCommand}' not found.
79801
80351
 
@@ -80057,7 +80607,7 @@ var COMMAND_REGISTRY = {
80057
80607
  toolNoArgs: true
80058
80608
  },
80059
80609
  help: {
80060
- handler: (ctx) => _internals100.handleHelpCommand(ctx),
80610
+ handler: (ctx) => _internals101.handleHelpCommand(ctx),
80061
80611
  description: "Show help for swarm commands",
80062
80612
  category: "core",
80063
80613
  args: "[command]",
@@ -80126,7 +80676,7 @@ var COMMAND_REGISTRY = {
80126
80676
  },
80127
80677
  "guardrail explain": {
80128
80678
  handler: async (ctx) => {
80129
- const { handleGuardrailExplain } = await import("./guardrail-explain-7xrdp18c.js");
80679
+ const { handleGuardrailExplain } = await import("./guardrail-explain-5z64w3ah.js");
80130
80680
  return handleGuardrailExplain(ctx.directory, ctx.args);
80131
80681
  },
80132
80682
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -80136,7 +80686,7 @@ var COMMAND_REGISTRY = {
80136
80686
  },
80137
80687
  "guardrail reset": {
80138
80688
  handler: async (ctx) => {
80139
- const { handleGuardrailReset } = await import("./guardrail-reset-0ks08s0t.js");
80689
+ const { handleGuardrailReset } = await import("./guardrail-reset-yjwk20rb.js");
80140
80690
  return handleGuardrailReset(ctx.args, ctx.sessionID);
80141
80691
  },
80142
80692
  description: "Reset one exact active invocation/action circuit after repair",
@@ -80145,7 +80695,7 @@ var COMMAND_REGISTRY = {
80145
80695
  },
80146
80696
  "guardrail-explain": {
80147
80697
  handler: async (ctx) => {
80148
- const { handleGuardrailExplain } = await import("./guardrail-explain-7xrdp18c.js");
80698
+ const { handleGuardrailExplain } = await import("./guardrail-explain-5z64w3ah.js");
80149
80699
  return handleGuardrailExplain(ctx.directory, ctx.args);
80150
80700
  },
80151
80701
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -80155,7 +80705,7 @@ var COMMAND_REGISTRY = {
80155
80705
  },
80156
80706
  "guardrail-reset": {
80157
80707
  handler: async (ctx) => {
80158
- const { handleGuardrailReset } = await import("./guardrail-reset-0ks08s0t.js");
80708
+ const { handleGuardrailReset } = await import("./guardrail-reset-yjwk20rb.js");
80159
80709
  return handleGuardrailReset(ctx.args, ctx.sessionID);
80160
80710
  },
80161
80711
  description: "Reset one exact active invocation/action circuit after repair",
@@ -80165,7 +80715,7 @@ var COMMAND_REGISTRY = {
80165
80715
  },
80166
80716
  "guardrail-log": {
80167
80717
  handler: async (ctx) => {
80168
- const { handleGuardrailLog } = await import("./guardrail-log-f16sdc3p.js");
80718
+ const { handleGuardrailLog } = await import("./guardrail-log-f9nf687y.js");
80169
80719
  return handleGuardrailLog(ctx.directory, ctx.args);
80170
80720
  },
80171
80721
  description: "Read the guardrail decision log (use --blocks-only for blocks)",
@@ -81171,7 +81721,7 @@ function validateToolPolicy() {
81171
81721
  }
81172
81722
  return { valid: warnings.length === 0, warnings };
81173
81723
  }
81174
- var _internals100 = {
81724
+ var _internals101 = {
81175
81725
  handleHelpCommand,
81176
81726
  validateAliases,
81177
81727
  validateToolPolicy,
@@ -81181,16 +81731,16 @@ var _internals100 = {
81181
81731
  findSimilarCommands,
81182
81732
  buildDetailedHelp
81183
81733
  };
81184
- var validation = _internals100.validateAliases();
81734
+ var validation = _internals101.validateAliases();
81185
81735
  if (!validation.valid) {
81186
81736
  throw new Error(`COMMAND_REGISTRY alias validation failed:
81187
81737
  ${validation.errors.join(`
81188
81738
  `)}`);
81189
81739
  }
81190
- _internals100.emitValidationWarnings("COMMAND_REGISTRY alias warnings", validation.warnings);
81740
+ _internals101.emitValidationWarnings("COMMAND_REGISTRY alias warnings", validation.warnings);
81191
81741
  try {
81192
- const toolPolicyValidation = _internals100.validateToolPolicy();
81193
- _internals100.emitValidationWarnings("COMMAND_REGISTRY toolPolicy warnings", toolPolicyValidation.warnings);
81742
+ const toolPolicyValidation = _internals101.validateToolPolicy();
81743
+ _internals101.emitValidationWarnings("COMMAND_REGISTRY toolPolicy warnings", toolPolicyValidation.warnings);
81194
81744
  } catch (e) {
81195
81745
  warn(`COMMAND_REGISTRY toolPolicy validation failed (non-fatal): ${e.message}`);
81196
81746
  }
@@ -83122,7 +83672,7 @@ function formatCommandNotFound(tokens) {
83122
83672
  const attemptedCommand = tokens[0] || "";
83123
83673
  const MAX_DISPLAY = 100;
83124
83674
  const displayCommand = attemptedCommand.length > MAX_DISPLAY ? `${attemptedCommand.slice(0, MAX_DISPLAY)}...` : attemptedCommand;
83125
- const similar = _internals100.findSimilarCommands(attemptedCommand);
83675
+ const similar = _internals101.findSimilarCommands(attemptedCommand);
83126
83676
  const header = `Command \`/swarm ${displayCommand}\` not found.`;
83127
83677
  const suggestions = similar.length > 0 ? `Did you mean:
83128
83678
  ${similar.map((cmd) => ` - /swarm ${cmd}`).join(`
@@ -86158,7 +86708,7 @@ function getDisplayFinalPromptPressure() {
86158
86708
  async function rehydratePrSubscriptions(sessionID, directory) {
86159
86709
  const map = new Map;
86160
86710
  try {
86161
- const { listActive: listActive2 } = await import("./pr-subscriptions-j9j70bmd.js");
86711
+ const { listActive: listActive2 } = await import("./pr-subscriptions-fvmey1x6.js");
86162
86712
  const records = await listActive2(directory);
86163
86713
  for (const record of records) {
86164
86714
  if (record.sessionID !== sessionID)
@@ -86363,7 +86913,7 @@ async function createSessionWithinBudget(promise, label, onLateResolve) {
86363
86913
  }
86364
86914
  }, () => {});
86365
86915
  try {
86366
- return await withTimeout(promise, _internals102.worktreeSessionCreateTimeoutMs, new Error(`${label} deadline expired after ${_internals102.worktreeSessionCreateTimeoutMs}ms`));
86916
+ return await withTimeout(promise, _internals103.worktreeSessionCreateTimeoutMs, new Error(`${label} deadline expired after ${_internals103.worktreeSessionCreateTimeoutMs}ms`));
86367
86917
  } catch (error2) {
86368
86918
  timedOut = true;
86369
86919
  throw error2;
@@ -86501,8 +87051,8 @@ var WORKTREE_LIST_TIMEOUT_MS = 15000;
86501
87051
  async function preProvisionCollisionCheck(taskId, directory, _sessionId) {
86502
87052
  let proc;
86503
87053
  try {
86504
- proc = _internals102.bunSpawn([
86505
- _internals102.resolveGitExecutable(),
87054
+ proc = _internals103.bunSpawn([
87055
+ _internals103.resolveGitExecutable(),
86506
87056
  "-C",
86507
87057
  directory,
86508
87058
  "worktree",
@@ -86604,13 +87154,13 @@ function isLaneOwnedByCurrentSession(branchName, expectedSessionId) {
86604
87154
  return extracted === expectedSessionId;
86605
87155
  }
86606
87156
  async function inspectStandardWorktreeCollisionOwnership(identity) {
86607
- const collisionOwnership = await import("./worktree-collision-ownership-6x03w8h7.js");
87157
+ const collisionOwnership = await import("./worktree-collision-ownership-7kf9mm5z.js");
86608
87158
  return collisionOwnership.inspectStandardWorktreeCollisionOwnership(identity);
86609
87159
  }
86610
87160
  async function runRecoveryGit(directory, args, timeoutMs = 15000) {
86611
87161
  let proc;
86612
87162
  try {
86613
- proc = _internals102.bunSpawn([_internals102.resolveGitExecutable(), "-C", directory, ...args], {
87163
+ proc = _internals103.bunSpawn([_internals103.resolveGitExecutable(), "-C", directory, ...args], {
86614
87164
  stdin: "ignore",
86615
87165
  stdout: "pipe",
86616
87166
  stderr: "pipe",
@@ -86673,7 +87223,7 @@ async function publishRecoveryAuthorityForSettlement(input) {
86673
87223
  if (input.dispatch.recoveryClaim || !input.provenance) {
86674
87224
  return { ok: true };
86675
87225
  }
86676
- const identity = await _internals102.buildWorktreeRecoveryPublishIdentity({
87226
+ const identity = await _internals103.buildWorktreeRecoveryPublishIdentity({
86677
87227
  directory: input.directory,
86678
87228
  dispatch: input.dispatch,
86679
87229
  taskId: input.taskId,
@@ -86687,7 +87237,7 @@ async function publishRecoveryAuthorityForSettlement(input) {
86687
87237
  reason: "worktree recovery publish identity could not be derived from the merge provenance"
86688
87238
  };
86689
87239
  }
86690
- const published = _internals102.publishWorktreeRecoveryAuthority(input.directory, identity);
87240
+ const published = _internals103.publishWorktreeRecoveryAuthority(input.directory, identity);
86691
87241
  return published.ok ? { ok: true } : { ok: false, code: published.code, reason: published.reason };
86692
87242
  }
86693
87243
  function isExactRecoveryClaimantStillActive(authority) {
@@ -86749,12 +87299,12 @@ async function precreateStandardWorktreeSession(args) {
86749
87299
  })
86750
87300
  };
86751
87301
  let recoveryLaunch;
86752
- const lifecycleLock = await _internals102.tryAcquireWorktreeLifecycleLock(args.directory, WORKTREE_LIFECYCLE_LOCK_FILE, "worktree-provisioning", args.taskId);
87302
+ const lifecycleLock = await _internals103.tryAcquireWorktreeLifecycleLock(args.directory, WORKTREE_LIFECYCLE_LOCK_FILE, "worktree-provisioning", args.taskId);
86753
87303
  if (!lifecycleLock.acquired) {
86754
87304
  hardStopStandardWorktreeLifecycle(args.parentSessionID, "STANDARD_WORKTREE_LIFECYCLE_BUSY: init orphan recovery is active; retry this coder dispatch after recovery completes.");
86755
87305
  }
86756
87306
  try {
86757
- const collision = await _internals102.preProvisionCollisionCheck(args.taskId, args.directory, args.parentSessionID);
87307
+ const collision = await _internals103.preProvisionCollisionCheck(args.taskId, args.directory, args.parentSessionID);
86758
87308
  if (collision.uncertainty) {
86759
87309
  hardStopStandardWorktreeLifecycle(args.parentSessionID, `STANDARD_WORKTREE_COLLISION_SCAN_UNCERTAIN: ${collision.uncertainty}. Destructive cleanup and provisioning were blocked.`);
86760
87310
  }
@@ -86763,17 +87313,17 @@ async function precreateStandardWorktreeSession(args) {
86763
87313
  const ownerInfo = collision.ownerSessionId ? ` owned by session ${collision.ownerSessionId}` : " with uncertain ownership";
86764
87314
  hardStopStandardWorktreeLifecycle(args.parentSessionID, `PREPROVISION_COLLISION: task ${args.taskId} already has a lane on branch ${collision.existingBranch ?? "unknown"}${ownerInfo}; cleanup and provisioning were blocked.`);
86765
87315
  }
86766
- for (const dispatch of _internals102.standardWorktreeByCallID.values()) {
87316
+ for (const dispatch of _internals103.standardWorktreeByCallID.values()) {
86767
87317
  if (dispatch.handle.branchName === collision.existingBranch) {
86768
87318
  hardStopStandardWorktreeLifecycle(args.parentSessionID, `PREPROVISION_COLLISION_ACTIVE: branch ${collision.existingBranch} is still tracked by an active standard-worktree dispatch.`);
86769
87319
  }
86770
87320
  }
86771
- for (const record of _internals102.awaitingMergeByCallID.values()) {
87321
+ for (const record of _internals103.awaitingMergeByCallID.values()) {
86772
87322
  if (record.branch === collision.existingBranch) {
86773
87323
  hardStopStandardWorktreeLifecycle(args.parentSessionID, `PREPROVISION_COLLISION_AWAITING_MERGE: branch ${collision.existingBranch} is still awaiting merge-back.`);
86774
87324
  }
86775
87325
  }
86776
- const recoveryCandidate = maybeSelectRecoverableAuthority(_internals102.lookupWorktreeRecoveryAuthoritiesByTask(args.directory, {
87326
+ const recoveryCandidate = maybeSelectRecoverableAuthority(_internals103.lookupWorktreeRecoveryAuthoritiesByTask(args.directory, {
86777
87327
  parentSessionId: args.parentSessionID,
86778
87328
  taskId: resolveRecoveryTaskId(args)
86779
87329
  }), collision);
@@ -86784,7 +87334,7 @@ async function precreateStandardWorktreeSession(args) {
86784
87334
  let recoveredChildSessionId = "";
86785
87335
  let claimed;
86786
87336
  try {
86787
- claimed = await _internals102.claimWorktreeRecoveryAuthority(args.directory, {
87337
+ claimed = await _internals103.claimWorktreeRecoveryAuthority(args.directory, {
86788
87338
  authorityDigest: recoveryCandidate.authority.authorityDigest,
86789
87339
  claimantCallID: args.callID,
86790
87340
  claimantSessionId: args.parentSessionID,
@@ -86844,7 +87394,7 @@ async function precreateStandardWorktreeSession(args) {
86844
87394
  }
86845
87395
  });
86846
87396
  } catch (error2) {
86847
- _internals102.replayWorktreeRecoveryClaimJournal(args.directory);
87397
+ _internals103.replayWorktreeRecoveryClaimJournal(args.directory);
86848
87398
  if (recoveredChildSessionId) {
86849
87399
  await teardownEphemeralSession(client.session, recoveredChildSessionId);
86850
87400
  }
@@ -86881,7 +87431,7 @@ async function precreateStandardWorktreeSession(args) {
86881
87431
  };
86882
87432
  }
86883
87433
  if (!recoveryLaunch) {
86884
- const ownership = await _internals102.inspectStandardWorktreeCollisionOwnership({
87434
+ const ownership = await _internals103.inspectStandardWorktreeCollisionOwnership({
86885
87435
  directory: args.directory,
86886
87436
  parentSessionId: args.parentSessionID,
86887
87437
  taskId: args.taskId,
@@ -86906,31 +87456,31 @@ async function precreateStandardWorktreeSession(args) {
86906
87456
  }
86907
87457
  }
86908
87458
  if (collisionPathExists) {
86909
- const preserveResult = await _internals102.preserveDirtyWorktreeAtPath(collision.worktreePath, collision.existingBranch, "denied", args.directory, worktreeConfig.worktree_dir);
87459
+ const preserveResult = await _internals103.preserveDirtyWorktreeAtPath(collision.worktreePath, collision.existingBranch, "denied", args.directory, worktreeConfig.worktree_dir);
86910
87460
  if (preserveResult.outcome === "preserve-failed") {
86911
87461
  hardStopStandardWorktreeLifecycle(args.parentSessionID, `STANDARD_WORKTREE_PRESERVATION_FAILED_ABORT_CLEANUP: pre-provision collision for task ${args.taskId} could not be preserved (${preserveResult.error}). Cleanup and provisioning were blocked.`);
86912
87462
  }
86913
- const removeResult = await _internals102.removeWorktree(collision.worktreePath, args.directory, { force: true, worktreeDir: worktreeConfig.worktree_dir });
87463
+ const removeResult = await _internals103.removeWorktree(collision.worktreePath, args.directory, { force: true, worktreeDir: worktreeConfig.worktree_dir });
86914
87464
  if ("error" in removeResult) {
86915
87465
  hardStopStandardWorktreeLifecycle(args.parentSessionID, `STANDARD_WORKTREE_COLLISION_REMOVE_FAILED: ${removeResult.error}. Provisioning was blocked.`);
86916
87466
  }
86917
- const cleanupResult = await _internals102.postMergeCleanup(args.directory, collision.existingBranch);
87467
+ const cleanupResult = await _internals103.postMergeCleanup(args.directory, collision.existingBranch);
86918
87468
  if ("error" in cleanupResult) {
86919
87469
  hardStopStandardWorktreeLifecycle(args.parentSessionID, `STANDARD_WORKTREE_COLLISION_BRANCH_CLEANUP_FAILED: ${cleanupResult.error}. Provisioning was blocked.`);
86920
87470
  }
86921
87471
  } else {
86922
- const pruneResult = await _internals102.pruneStaleWorktreeMetadata(args.directory);
87472
+ const pruneResult = await _internals103.pruneStaleWorktreeMetadata(args.directory);
86923
87473
  if ("error" in pruneResult) {
86924
87474
  hardStopStandardWorktreeLifecycle(args.parentSessionID, `STANDARD_WORKTREE_COLLISION_PRUNE_FAILED: ${pruneResult.error}. Provisioning was blocked without deleting the lane branch.`);
86925
87475
  }
86926
87476
  }
86927
- const verification = await _internals102.preProvisionCollisionCheck(args.taskId, args.directory, args.parentSessionID);
87477
+ const verification = await _internals103.preProvisionCollisionCheck(args.taskId, args.directory, args.parentSessionID);
86928
87478
  if (verification.uncertainty || verification.collision) {
86929
87479
  hardStopStandardWorktreeLifecycle(args.parentSessionID, `STANDARD_WORKTREE_COLLISION_CLEANUP_UNVERIFIED: ${verification.uncertainty ?? "git still reports the colliding lane after cleanup"}. Provisioning was blocked.`);
86930
87480
  }
86931
87481
  }
86932
87482
  }
86933
- _internals102.recordWorktreeProvisioningOwner(args.directory, {
87483
+ _internals103.recordWorktreeProvisioningOwner(args.directory, {
86934
87484
  callID: args.callID,
86935
87485
  parentSessionId: args.parentSessionID,
86936
87486
  worktreeSessionId: args.parentSessionID,
@@ -86977,7 +87527,7 @@ async function precreateStandardWorktreeSession(args) {
86977
87527
  canonicalPath2 = args.directory;
86978
87528
  let provisionResult;
86979
87529
  try {
86980
- provisionResult = await _internals102.provisionWorktree(args.directory, args.taskId, args.parentSessionID, {
87530
+ provisionResult = await _internals103.provisionWorktree(args.directory, args.taskId, args.parentSessionID, {
86981
87531
  purpose: "lane",
86982
87532
  worktreeDir: worktreeConfig.worktree_dir,
86983
87533
  mergeStrategy: worktreeConfig.merge_strategy,
@@ -86985,11 +87535,11 @@ async function precreateStandardWorktreeSession(args) {
86985
87535
  scope: args.scope
86986
87536
  });
86987
87537
  } catch (error2) {
86988
- _internals102.removeWorktreeProvisioningOwner(args.directory, args.callID, provisioningOwnerIdentity);
87538
+ _internals103.removeWorktreeProvisioningOwner(args.directory, args.callID, provisioningOwnerIdentity);
86989
87539
  throw error2;
86990
87540
  }
86991
87541
  if ("error" in provisionResult) {
86992
- _internals102.removeWorktreeProvisioningOwner(args.directory, args.callID, provisioningOwnerIdentity);
87542
+ _internals103.removeWorktreeProvisioningOwner(args.directory, args.callID, provisioningOwnerIdentity);
86993
87543
  const message = `STANDARD_WORKTREE_PROVISION_FAILED: ${provisionResult.error}.`;
86994
87544
  handleStandardWorktreeFailure(args.parentSessionID, worktreeConfig.policy, message);
86995
87545
  return;
@@ -87013,7 +87563,7 @@ async function precreateStandardWorktreeSession(args) {
87013
87563
  const laneProfile = computeLaneRuntimeProfile(worktreeConfig.runtime_isolation, laneIndex, handle.worktreePath);
87014
87564
  if (laneProfile) {
87015
87565
  try {
87016
- const { writeLaneProfileToDiskReal } = await import("./core-a42bexs1.js");
87566
+ const { writeLaneProfileToDiskReal } = await import("./core-pp64ys5v.js");
87017
87567
  await writeLaneProfileToDiskReal(handle.worktreePath, laneProfile.laneIndex, laneProfile.envOverrides);
87018
87568
  } catch {}
87019
87569
  }
@@ -87042,26 +87592,26 @@ async function precreateStandardWorktreeSession(args) {
87042
87592
  }
87043
87593
  });
87044
87594
  } catch (error2) {
87045
- await _internals102.removeWorktree(handle.worktreePath, args.directory, {
87595
+ await _internals103.removeWorktree(handle.worktreePath, args.directory, {
87046
87596
  force: true,
87047
87597
  worktreeDir: worktreeConfig.worktree_dir
87048
87598
  }).catch((cleanupError) => {
87049
87599
  log(`[worktree-isolation] session-create failure cleanup could not remove lane ${handle.worktreePath}: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
87050
87600
  });
87051
- _internals102.removeWorktreeProvisioningOwner(args.directory, args.callID, provisioningOwnerIdentity);
87601
+ _internals103.removeWorktreeProvisioningOwner(args.directory, args.callID, provisioningOwnerIdentity);
87052
87602
  const detail = error2 instanceof Error ? error2.message : String(error2);
87053
87603
  const message = `STANDARD_WORKTREE_SESSION_CREATE_FAILED: ${detail}.`;
87054
87604
  handleStandardWorktreeFailure(args.parentSessionID, worktreeConfig.policy, message);
87055
87605
  return;
87056
87606
  }
87057
87607
  if (!createResult?.data?.id) {
87058
- await _internals102.removeWorktree(handle.worktreePath, args.directory, {
87608
+ await _internals103.removeWorktree(handle.worktreePath, args.directory, {
87059
87609
  force: true,
87060
87610
  worktreeDir: worktreeConfig.worktree_dir
87061
87611
  }).catch((cleanupError) => {
87062
87612
  log(`[worktree-isolation] session-create failure cleanup could not remove lane ${handle.worktreePath}: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
87063
87613
  });
87064
- _internals102.removeWorktreeProvisioningOwner(args.directory, args.callID, provisioningOwnerIdentity);
87614
+ _internals103.removeWorktreeProvisioningOwner(args.directory, args.callID, provisioningOwnerIdentity);
87065
87615
  const createError = createResult.error;
87066
87616
  const detail = typeof createError === "string" ? createError : JSON.stringify(createError ?? "missing session id");
87067
87617
  const message = `STANDARD_WORKTREE_SESSION_CREATE_FAILED: ${detail}.`;
@@ -87100,8 +87650,8 @@ async function preserveBackgroundWorktreeOwnershipForCallId(callID) {
87100
87650
  return { outcome: "not-found" };
87101
87651
  let refProc;
87102
87652
  try {
87103
- refProc = _internals102.bunSpawn([
87104
- _internals102.resolveGitExecutable(),
87653
+ refProc = _internals103.bunSpawn([
87654
+ _internals103.resolveGitExecutable(),
87105
87655
  "-C",
87106
87656
  dispatch.handle.worktreePath,
87107
87657
  "rev-parse",
@@ -87145,8 +87695,8 @@ async function preserveBackgroundWorktreeOwnershipForCallId(callID) {
87145
87695
  const tag = `swarm-preserved-owner/${session}/${lane}/${callDigest}`;
87146
87696
  let tagProc;
87147
87697
  try {
87148
- tagProc = _internals102.bunSpawn([
87149
- _internals102.resolveGitExecutable(),
87698
+ tagProc = _internals103.bunSpawn([
87699
+ _internals103.resolveGitExecutable(),
87150
87700
  "-C",
87151
87701
  dispatch.handle.worktreePath,
87152
87702
  "tag",
@@ -87196,8 +87746,8 @@ async function preserveDirtyWorktreeForCallId(callID, reason, _directory, _workt
87196
87746
  }
87197
87747
  let statusProc;
87198
87748
  try {
87199
- statusProc = _internals102.bunSpawn([
87200
- _internals102.resolveGitExecutable(),
87749
+ statusProc = _internals103.bunSpawn([
87750
+ _internals103.resolveGitExecutable(),
87201
87751
  "-C",
87202
87752
  worktreePath,
87203
87753
  "status",
@@ -87239,7 +87789,7 @@ async function preserveDirtyWorktreeForCallId(callID, reason, _directory, _workt
87239
87789
  }
87240
87790
  let addProc;
87241
87791
  try {
87242
- addProc = _internals102.bunSpawn([_internals102.resolveGitExecutable(), "-C", worktreePath, "add", "-A"], {
87792
+ addProc = _internals103.bunSpawn([_internals103.resolveGitExecutable(), "-C", worktreePath, "add", "-A"], {
87243
87793
  stdin: "ignore",
87244
87794
  stdout: "pipe",
87245
87795
  stderr: "pipe",
@@ -87273,8 +87823,8 @@ async function preserveDirtyWorktreeForCallId(callID, reason, _directory, _workt
87273
87823
  const commitMessage = `swarm-preserved: ${reason} for callID ${sanitizedCallID} at ${isoDate}`;
87274
87824
  let commitProc;
87275
87825
  try {
87276
- commitProc = _internals102.bunSpawn([
87277
- _internals102.resolveGitExecutable(),
87826
+ commitProc = _internals103.bunSpawn([
87827
+ _internals103.resolveGitExecutable(),
87278
87828
  "-C",
87279
87829
  worktreePath,
87280
87830
  "commit",
@@ -87312,8 +87862,8 @@ async function preserveDirtyWorktreeForCallId(callID, reason, _directory, _workt
87312
87862
  }
87313
87863
  let hashProc;
87314
87864
  try {
87315
- hashProc = _internals102.bunSpawn([
87316
- _internals102.resolveGitExecutable(),
87865
+ hashProc = _internals103.bunSpawn([
87866
+ _internals103.resolveGitExecutable(),
87317
87867
  "-C",
87318
87868
  worktreePath,
87319
87869
  "rev-parse",
@@ -87359,7 +87909,7 @@ async function preserveDirtyWorktreeForCallId(callID, reason, _directory, _workt
87359
87909
  const tagName = `swarm-preserved-${sanitizedCallID}-${shortHash}`;
87360
87910
  let tagProc;
87361
87911
  try {
87362
- tagProc = _internals102.bunSpawn([_internals102.resolveGitExecutable(), "-C", worktreePath, "tag", tagName], {
87912
+ tagProc = _internals103.bunSpawn([_internals103.resolveGitExecutable(), "-C", worktreePath, "tag", tagName], {
87363
87913
  stdin: "ignore",
87364
87914
  stdout: "pipe",
87365
87915
  stderr: "pipe",
@@ -87395,8 +87945,8 @@ async function preserveDirtyWorktreeForCallId(callID, reason, _directory, _workt
87395
87945
  async function preserveDirtyWorktreeAtPath(worktreePath, branchName, reason, _directory, _worktree_dir) {
87396
87946
  let statusProc;
87397
87947
  try {
87398
- statusProc = _internals102.bunSpawn([
87399
- _internals102.resolveGitExecutable(),
87948
+ statusProc = _internals103.bunSpawn([
87949
+ _internals103.resolveGitExecutable(),
87400
87950
  "-C",
87401
87951
  worktreePath,
87402
87952
  "status",
@@ -87438,7 +87988,7 @@ async function preserveDirtyWorktreeAtPath(worktreePath, branchName, reason, _di
87438
87988
  }
87439
87989
  let addProc;
87440
87990
  try {
87441
- addProc = _internals102.bunSpawn([_internals102.resolveGitExecutable(), "-C", worktreePath, "add", "-A"], {
87991
+ addProc = _internals103.bunSpawn([_internals103.resolveGitExecutable(), "-C", worktreePath, "add", "-A"], {
87442
87992
  stdin: "ignore",
87443
87993
  stdout: "pipe",
87444
87994
  stderr: "pipe",
@@ -87473,8 +88023,8 @@ async function preserveDirtyWorktreeAtPath(worktreePath, branchName, reason, _di
87473
88023
  const commitMessage = `swarm-preserved: ${reason} for worktree ${sanitizedPath} at ${isoDate}`;
87474
88024
  let commitProc;
87475
88025
  try {
87476
- commitProc = _internals102.bunSpawn([
87477
- _internals102.resolveGitExecutable(),
88026
+ commitProc = _internals103.bunSpawn([
88027
+ _internals103.resolveGitExecutable(),
87478
88028
  "-C",
87479
88029
  worktreePath,
87480
88030
  "commit",
@@ -87512,8 +88062,8 @@ async function preserveDirtyWorktreeAtPath(worktreePath, branchName, reason, _di
87512
88062
  }
87513
88063
  let hashProc;
87514
88064
  try {
87515
- hashProc = _internals102.bunSpawn([
87516
- _internals102.resolveGitExecutable(),
88065
+ hashProc = _internals103.bunSpawn([
88066
+ _internals103.resolveGitExecutable(),
87517
88067
  "-C",
87518
88068
  worktreePath,
87519
88069
  "rev-parse",
@@ -87559,7 +88109,7 @@ async function preserveDirtyWorktreeAtPath(worktreePath, branchName, reason, _di
87559
88109
  const tagName = `swarm-preserved-worktree-${sanitizedBranch}-${shortHash}`;
87560
88110
  let tagProc;
87561
88111
  try {
87562
- tagProc = _internals102.bunSpawn([_internals102.resolveGitExecutable(), "-C", worktreePath, "tag", tagName], {
88112
+ tagProc = _internals103.bunSpawn([_internals103.resolveGitExecutable(), "-C", worktreePath, "tag", tagName], {
87563
88113
  stdin: "ignore",
87564
88114
  stdout: "pipe",
87565
88115
  stderr: "pipe",
@@ -87613,7 +88163,7 @@ async function cleanupStandardWorktreeForCallId(callID, reason, directory, workt
87613
88163
  parentSessionID = awaiting.parentSessionID;
87614
88164
  }
87615
88165
  if (dispatch?.recoveryClaim && (reason === "denied" || reason === "cancelled")) {
87616
- const renewResult = _internals102.renewWorktreeRecoveryClaim(directory, {
88166
+ const renewResult = _internals103.renewWorktreeRecoveryClaim(directory, {
87617
88167
  authorityDigest: dispatch.recoveryClaim.authorityDigest,
87618
88168
  claimantCallID: callID,
87619
88169
  claimRevision: dispatch.recoveryClaim.claimRevision,
@@ -87630,7 +88180,7 @@ async function cleanupStandardWorktreeForCallId(callID, reason, directory, workt
87630
88180
  pushAdvisory(session3, message);
87631
88181
  throw new Error(message);
87632
88182
  }
87633
- const releaseResult = _internals102.releaseWorktreeRecoveryClaim(directory, {
88183
+ const releaseResult = _internals103.releaseWorktreeRecoveryClaim(directory, {
87634
88184
  authorityDigest: dispatch.recoveryClaim.authorityDigest,
87635
88185
  claimantCallID: callID,
87636
88186
  claimRevision: dispatch.recoveryClaim.claimRevision,
@@ -87659,7 +88209,7 @@ async function cleanupStandardWorktreeForCallId(callID, reason, directory, workt
87659
88209
  let preserveResult;
87660
88210
  if (reason === "denied" || reason === "cancelled") {
87661
88211
  try {
87662
- preserveResult = await _internals102.preserveDirtyWorktreeForCallId(callID, reason, directory, worktree_dir);
88212
+ preserveResult = await _internals103.preserveDirtyWorktreeForCallId(callID, reason, directory, worktree_dir);
87663
88213
  } catch (err) {
87664
88214
  log(`[swarm] cleanupStandardWorktreeForCallId: preserveDirtyWorktreeForCallId threw for ${callID}: ${err}`);
87665
88215
  preserveResult = {
@@ -87670,7 +88220,7 @@ async function cleanupStandardWorktreeForCallId(callID, reason, directory, workt
87670
88220
  }
87671
88221
  if (preserveResult.outcome === "clean") {
87672
88222
  try {
87673
- preserveResult = await _internals102.preserveDirtyWorktreeForCallId(callID, reason, directory, worktree_dir);
88223
+ preserveResult = await _internals103.preserveDirtyWorktreeForCallId(callID, reason, directory, worktree_dir);
87674
88224
  } catch (err) {
87675
88225
  log(`[swarm] cleanupStandardWorktreeForCallId: final preservation check threw for ${callID}: ${err}`);
87676
88226
  preserveResult = {
@@ -87694,7 +88244,7 @@ async function cleanupStandardWorktreeForCallId(callID, reason, directory, workt
87694
88244
  }
87695
88245
  let removedWorktree = false;
87696
88246
  try {
87697
- const result = await _internals102.removeWorktree(worktreePath, directory, {
88247
+ const result = await _internals103.removeWorktree(worktreePath, directory, {
87698
88248
  force: true,
87699
88249
  worktreeDir: worktree_dir
87700
88250
  });
@@ -87704,7 +88254,7 @@ async function cleanupStandardWorktreeForCallId(callID, reason, directory, workt
87704
88254
  }
87705
88255
  let cleanedBranch = false;
87706
88256
  try {
87707
- const result = await _internals102.postMergeCleanup(directory, branchName);
88257
+ const result = await _internals103.postMergeCleanup(directory, branchName);
87708
88258
  cleanedBranch = !("error" in result);
87709
88259
  } catch (err) {
87710
88260
  log(`[swarm] cleanupStandardWorktreeForCallId: postMergeCleanup failed for ${callID}: ${err}`);
@@ -87754,7 +88304,7 @@ async function finishStandardWorktreeDispatch(directory, dispatch, config, callI
87754
88304
  const renewRecoveryClaimLease = (phase, provenance) => {
87755
88305
  if (!dispatch.recoveryClaim)
87756
88306
  return;
87757
- const renewed = _internals102.renewWorktreeRecoveryClaim(directory, {
88307
+ const renewed = _internals103.renewWorktreeRecoveryClaim(directory, {
87758
88308
  authorityDigest: dispatch.recoveryClaim.authorityDigest,
87759
88309
  claimantCallID: resolvedCallID,
87760
88310
  claimRevision: dispatch.recoveryClaim.claimRevision,
@@ -87772,7 +88322,7 @@ async function finishStandardWorktreeDispatch(directory, dispatch, config, callI
87772
88322
  const releaseRecoveryClaim = (provenance) => {
87773
88323
  if (!dispatch.recoveryClaim)
87774
88324
  return;
87775
- const released = _internals102.releaseWorktreeRecoveryClaim(directory, {
88325
+ const released = _internals103.releaseWorktreeRecoveryClaim(directory, {
87776
88326
  authorityDigest: dispatch.recoveryClaim.authorityDigest,
87777
88327
  claimantCallID: resolvedCallID,
87778
88328
  claimRevision: dispatch.recoveryClaim.claimRevision,
@@ -87808,7 +88358,7 @@ async function finishStandardWorktreeDispatch(directory, dispatch, config, callI
87808
88358
  }
87809
88359
  const mergeResult = await (async () => {
87810
88360
  if (!dispatch.recoveryClaim) {
87811
- return _internals102.attemptMergeBackFromDirty(dispatch.handle.worktreePath, dispatch.handle.branchName, directory, getMergeStrategy({ merge_strategy: dispatch.mergeStrategy }), {
88361
+ return _internals103.attemptMergeBackFromDirty(dispatch.handle.worktreePath, dispatch.handle.branchName, directory, getMergeStrategy({ merge_strategy: dispatch.mergeStrategy }), {
87812
88362
  operationId: settlement.operationId,
87813
88363
  resume: settlement.resume,
87814
88364
  onBeforeMerge: settlement.onBeforeMerge
@@ -87832,7 +88382,7 @@ async function finishStandardWorktreeDispatch(directory, dispatch, config, callI
87832
88382
  if (settlement.onBeforeMerge) {
87833
88383
  await settlement.onBeforeMerge(provenance);
87834
88384
  }
87835
- const recovered = await _internals102.recoverMergeBackFromImmutableCoordinates(directory, coordinates);
88385
+ const recovered = await _internals103.recoverMergeBackFromImmutableCoordinates(directory, coordinates);
87836
88386
  if ("merged" in recovered && recovered.merged) {
87837
88387
  if (recovered.sourceCommitOrder && recovered.rewrittenCommitOrder) {
87838
88388
  dispatch.recoveryClaim.settlement = {
@@ -87921,7 +88471,7 @@ async function finishStandardWorktreeDispatch(directory, dispatch, config, callI
87921
88471
  settlement: dispatch.recoveryClaim.settlement
87922
88472
  };
87923
88473
  if (cleanupResult.removedWorktree && cleanupResult.cleanedBranch) {
87924
- const finalized = _internals102.finalizeWorktreeRecoveryAuthority(directory, request);
88474
+ const finalized = _internals103.finalizeWorktreeRecoveryAuthority(directory, request);
87925
88475
  if (!finalized.ok) {
87926
88476
  return failRecoverySettlement("recovery-claim-finalize", `The merged recovery lane was cleaned up but could not finalize its exact claim; ${describeRecoveryMutationFailure({
87927
88477
  action: "finalize",
@@ -87938,7 +88488,7 @@ async function finishStandardWorktreeDispatch(directory, dispatch, config, callI
87938
88488
  }
87939
88489
  clearWorktreeMergeStatus(statusKey);
87940
88490
  try {
87941
- const { removeLaneProfileFromDiskReal } = await import("./core-a42bexs1.js");
88491
+ const { removeLaneProfileFromDiskReal } = await import("./core-pp64ys5v.js");
87942
88492
  await removeLaneProfileFromDiskReal(dispatch.handle.worktreePath, dispatch.laneIndex);
87943
88493
  } catch {}
87944
88494
  const state = serializationStateBySessionID.get(dispatch.parentSessionID);
@@ -88042,7 +88592,7 @@ async function finishStandardWorktreeDispatch(directory, dispatch, config, callI
88042
88592
  awaitingMergeByCallID.delete(resolvedCallID);
88043
88593
  if (dispatch.recoveryClaim) {
88044
88594
  try {
88045
- _internals102.releaseWorktreeRecoveryClaim(directory, {
88595
+ _internals103.releaseWorktreeRecoveryClaim(directory, {
88046
88596
  authorityDigest: dispatch.recoveryClaim.authorityDigest,
88047
88597
  claimantCallID: resolvedCallID,
88048
88598
  claimRevision: dispatch.recoveryClaim.claimRevision,
@@ -88103,7 +88653,7 @@ async function readLaneEnvFileFromDisk(worktreePath, laneIndex) {
88103
88653
  }
88104
88654
  return result;
88105
88655
  }
88106
- var _internals102 = {
88656
+ var _internals103 = {
88107
88657
  provisionWorktree,
88108
88658
  removeWorktree,
88109
88659
  attemptMergeBackFromDirty,
@@ -88141,4 +88691,4 @@ var _internals102 = {
88141
88691
  resolveGitExecutable
88142
88692
  };
88143
88693
 
88144
- export { PrReviewRunIdSchema, resetActionCircuitExternally, getBlockingActionCircuit, dcNormalizeCommand, dcUnwrapWrappers, dcSplitSegments, dcExtractRecursiveRmTargets, dcEvaluateRecursiveDeleteTargets, dcCheckJunctionCreation, dcExtractWindowsCmdTargets, dcExtractPowerShellTargets, getSharedClassifierGuardrailBlock, classifyCommand, normalizeSwarmCommandInput, canonicalCommandKey, formatCommandNotFound, executeSwarmCommand, SWARM_COMMAND_TOOL_COMMANDS, SWARM_COMMAND_TOOL_ALLOWLIST, HUMAN_ONLY_SWARM_COMMANDS, classifySwarmCommandToolUse, classifySwarmCommandChatFallbackUse, detectPosixWrites, detectWindowsWrites, resolveWriteTargets, getAgentSession, parseLeanLaneIndex, computeLaneRuntimeProfile, MAX_TRACKED_STANDARD_WORKTREE_CALLS, awaitingMergeByCallID, standardWorktreeByCallID, standardWorktreeSerializationSessions, getStandardWorktreeDegradationReason, resetStandardWorktreeIsolationState, checkStandardWorktreeSerializationRelease, sanitizeWorktreeTaskId, preProvisionCollisionCheck, isLaneOwnedByCurrentSession, precreateStandardWorktreeSession, preserveBackgroundWorktreeOwnershipForCallId, preserveDirtyWorktreeForCallId, preserveDirtyWorktreeAtPath, cleanupStandardWorktreeForCallId, abortStandardWorktreeDispatch, finishStandardWorktreeDispatch, readLaneEnvFileFromDisk, _internals102 as _internals, readPrReviewReentryBindingContext, prWorkflowSessionFileStem, handleAcknowledgeSpecDriftCommand, handleAgentsCommand, handleAnalyzeCommand, handleApproveWriteCommand, handleArchiveCommand, handleAutoProceedCommand, handleBenchmarkCommand, handleBrainstormCommand, handleCheckpointCommand, handleCiSimulateCommand, handleClarifyCommand, createCuratorLLMDelegate, _internals26 as _internals1, normalizeRecommendationEntryIdToken, parseKnowledgeRecommendations, parseKnowledgeRecommendationsWithDiagnostics, parseStructuredCuratorBlocks, readCuratorSummary, writeCuratorSummary, appendCuratorRecommendation, mergeCuratorPhaseSummary, filterPhaseEvents, checkPhaseCompliance, runCuratorInit, runCuratorPhase, applyCuratorKnowledgeUpdates, isHiveEligible, countDistinctProjects, checkHivePromotions, _internals30 as _internals2, createHivePromoterHook, promoteToHive, promoteFromSwarm, safeRealpathSync, handleCloseCommand, handleCodebaseReviewCommand, handleConcurrencyCommand, handleConfigCommand, handleConsolidateCommand, handleCostsCommand, handleCouncilCommand, handleCurateCommand, handleDarkMatterCommand, handleDeepDiveCommand, handleDeepResearchCommand, getPluginConfigDir, getPluginCachePaths, getPluginLockFilePaths, VERSION_PINNED_LEAF, discoverVersionPinnedCachePaths, readCachePackageVersion, handleDiagnoseCommand, handleDoctorCommand, handleEvidenceCommand, handleEvidenceSummaryCommand, handleExportCommand, handleFullAutoCommand, handleGateAuditCommand, handleGateStatsCommand, handleHandoffCommand, handleBlueprintValidateCommand, handleBlueprintCurrentCommand, handleBlueprintHistoryCommand, handleBlueprintDiffCommand, handleBlueprintExportCommand, handleHarnessCandidateValidateCommand, handleHarnessCandidateShowCommand, handleHarnessCandidateDiffCommand, handleHistoryCommand, handleKnowledgeQuarantineCommand, handleKnowledgeRestoreCommand, handleKnowledgeMigrateCommand, handleKnowledgeListCommand, handleKnowledgeUnactionableCommand, handleKnowledgeRetryHardeningCommand, handleLearningCommand, handleLinkCommand, handleMemoryCommand, handleMemoryStatusCommand, handleMemoryValueLogCommand, handleMemoryMigrateCommand, handleMemoryImportCommand, handleMemoryExportCommand, handlePlanCommand, handlePreflightCommand, handlePromoteCommand, handleQaGatesCommand, handleRecoverCommand, handleResetCommand, handleResetSessionCommand, handleRetrieveCommand, handleReviewCommand, handleRollbackCommand, handleSddStatusCommand, handleSddValidateCommand, handleSddProjectCommand, handleSddCommand, handleSimulateCommand, handleSpecifyCommand, handleStatusCommand, handleSyncPlanCommand, handleTurboCommand, handleUnlinkCommand, handleWriteRetroCommand, handleHelpCommand, COMMAND_REGISTRY, VALID_COMMANDS, _internals100 as _internals3, resolveCommand };
88694
+ export { PrReviewRunIdSchema, resetActionCircuitExternally, getBlockingActionCircuit, dcNormalizeCommand, dcUnwrapWrappers, dcSplitSegments, dcExtractRecursiveRmTargets, dcEvaluateRecursiveDeleteTargets, dcCheckJunctionCreation, dcExtractWindowsCmdTargets, dcExtractPowerShellTargets, getSharedClassifierGuardrailBlock, classifyCommand, normalizeSwarmCommandInput, canonicalCommandKey, formatCommandNotFound, executeSwarmCommand, SWARM_COMMAND_TOOL_COMMANDS, SWARM_COMMAND_TOOL_ALLOWLIST, HUMAN_ONLY_SWARM_COMMANDS, classifySwarmCommandToolUse, classifySwarmCommandChatFallbackUse, detectPosixWrites, detectWindowsWrites, resolveWriteTargets, getAgentSession, parseLeanLaneIndex, computeLaneRuntimeProfile, MAX_TRACKED_STANDARD_WORKTREE_CALLS, awaitingMergeByCallID, standardWorktreeByCallID, standardWorktreeSerializationSessions, getStandardWorktreeDegradationReason, resetStandardWorktreeIsolationState, checkStandardWorktreeSerializationRelease, sanitizeWorktreeTaskId, preProvisionCollisionCheck, isLaneOwnedByCurrentSession, precreateStandardWorktreeSession, preserveBackgroundWorktreeOwnershipForCallId, preserveDirtyWorktreeForCallId, preserveDirtyWorktreeAtPath, cleanupStandardWorktreeForCallId, abortStandardWorktreeDispatch, finishStandardWorktreeDispatch, readLaneEnvFileFromDisk, _internals103 as _internals, readPrReviewReentryBindingContext, prWorkflowSessionFileStem, handleAcknowledgeSpecDriftCommand, handleAgentsCommand, handleAnalyzeCommand, handleApproveWriteCommand, handleArchiveCommand, handleAutoProceedCommand, handleBenchmarkCommand, handleBrainstormCommand, handleCheckpointCommand, handleCiSimulateCommand, handleClarifyCommand, createCuratorLLMDelegate, _internals26 as _internals1, normalizeRecommendationEntryIdToken, parseKnowledgeRecommendations, parseKnowledgeRecommendationsWithDiagnostics, parseStructuredCuratorBlocks, readCuratorSummary, writeCuratorSummary, appendCuratorRecommendation, mergeCuratorPhaseSummary, filterPhaseEvents, checkPhaseCompliance, runCuratorInit, runCuratorPhase, applyCuratorKnowledgeUpdates, isHiveEligible, countDistinctProjects, checkHivePromotions, _internals30 as _internals2, createHivePromoterHook, promoteToHive, promoteFromSwarm, safeRealpathSync, handleCloseCommand, handleCodebaseReviewCommand, handleConcurrencyCommand, handleConfigCommand, handleConsolidateCommand, handleCostsCommand, handleCouncilCommand, handleCurateCommand, handleDarkMatterCommand, handleDeepDiveCommand, handleDeepResearchCommand, getPluginConfigDir, getPluginCachePaths, getPluginLockFilePaths, VERSION_PINNED_LEAF, discoverVersionPinnedCachePaths, readCachePackageVersion, handleDiagnoseCommand, handleDoctorCommand, handleEvidenceCommand, handleEvidenceSummaryCommand, handleExportCommand, handleFullAutoCommand, handleGateAuditCommand, handleGateStatsCommand, handleHandoffCommand, handleBlueprintValidateCommand, handleBlueprintCurrentCommand, handleBlueprintHistoryCommand, handleBlueprintDiffCommand, handleBlueprintExportCommand, handleHarnessCandidateValidateCommand, handleHarnessCandidateShowCommand, handleHarnessCandidateDiffCommand, handleHistoryCommand, handleKnowledgeQuarantineCommand, handleKnowledgeRestoreCommand, handleKnowledgeMigrateCommand, handleKnowledgeListCommand, handleKnowledgeUnactionableCommand, handleKnowledgeRetryHardeningCommand, handleLearningCommand, handleLinkCommand, handleMemoryCommand, handleMemoryStatusCommand, handleMemoryValueLogCommand, handleMemoryMigrateCommand, handleMemoryImportCommand, handleMemoryExportCommand, handlePlanCommand, handlePreflightCommand, handlePromoteCommand, handleQaGatesCommand, handleRecoverCommand, handleResetCommand, handleResetSessionCommand, handleRetrieveCommand, handleReviewCommand, handleRollbackCommand, handleSddStatusCommand, handleSddValidateCommand, handleSddProjectCommand, handleSddCommand, handleSimulateCommand, handleSpecifyCommand, handleStatusCommand, handleSyncPlanCommand, handleTurboCommand, handleUnlinkCommand, handleWriteRetroCommand, handleHelpCommand, COMMAND_REGISTRY, VALID_COMMANDS, _internals101 as _internals3, resolveCommand };