opencode-swarm 7.146.1 → 7.146.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/agents/council-prompts.d.ts +3 -3
  2. package/dist/cli/{config-doctor-sd7x5bts.js → config-doctor-yd866pd5.js} +2 -2
  3. package/dist/cli/{core-17febkvw.js → core-nc9a9g5m.js} +1 -1
  4. package/dist/cli/{curation-policy-x19e8bqc.js → curation-policy-9vv7v5rf.js} +6 -6
  5. package/dist/cli/{curator-vghf320v.js → curator-acp80hpc.js} +27 -27
  6. package/dist/cli/{curator-llm-factory-zxbgkjm5.js → curator-llm-factory-ewffa8r1.js} +27 -27
  7. package/dist/cli/{evidence-summary-service-xma4aagr.js → evidence-summary-service-8gw74j8g.js} +11 -11
  8. package/dist/cli/{gate-evidence-2bznvee8.js → gate-evidence-jj3zt2x1.js} +6 -6
  9. package/dist/cli/{guardrail-explain-ppzg0xz9.js → guardrail-explain-50cp8k3r.js} +28 -28
  10. package/dist/cli/{guardrail-log-xexwz93q.js → guardrail-log-jazq10gt.js} +3 -3
  11. package/dist/cli/{hive-promoter-j3vw2hj4.js → hive-promoter-qhrngsvb.js} +27 -27
  12. package/dist/cli/{index-4qvsh3m5.js → index-0a4s2803.js} +6 -6
  13. package/dist/cli/{index-qbpxrw95.js → index-1kq3x5q6.js} +2 -2
  14. package/dist/cli/{index-t7sfrv3v.js → index-262kyrk3.js} +4 -4
  15. package/dist/cli/{index-xz0ccakc.js → index-3377n9qp.js} +1 -1
  16. package/dist/cli/{index-g8qbjqqz.js → index-3gagma8p.js} +4 -4
  17. package/dist/cli/{index-5e5a1y2r.js → index-3p4wgm0d.js} +1 -1
  18. package/dist/cli/{index-e1hjd15c.js → index-463msy1e.js} +1 -1
  19. package/dist/cli/{index-twwb61bh.js → index-4zevsvaa.js} +3 -3
  20. package/dist/cli/{index-bghwrr59.js → index-6q35swn2.js} +1 -1
  21. package/dist/cli/{index-h8qed3pr.js → index-7ph5pz77.js} +17 -4
  22. package/dist/cli/{index-vacrzesw.js → index-923phxsp.js} +6 -6
  23. package/dist/cli/{index-k46kg4t6.js → index-a7cnyp5e.js} +7 -7
  24. package/dist/cli/{index-tzyvmkd1.js → index-bxk21f2w.js} +1 -1
  25. package/dist/cli/{index-97psh79d.js → index-bxs4wkjf.js} +1 -1
  26. package/dist/cli/{index-19f0zycs.js → index-bydybrke.js} +2 -2
  27. package/dist/cli/{index-cw96tpy6.js → index-cgcs823z.js} +4 -4
  28. package/dist/cli/{index-9qbr27bw.js → index-eybamsqg.js} +2 -2
  29. package/dist/cli/{index-1c9mfnj0.js → index-fypq68yn.js} +2 -2
  30. package/dist/cli/{index-n7trn9wz.js → index-gayh8tmh.js} +55 -1
  31. package/dist/cli/{index-va8a2zrq.js → index-gwt7ceh7.js} +2 -2
  32. package/dist/cli/{index-w0cj7zyd.js → index-j2ckvbx7.js} +1 -1
  33. package/dist/cli/{index-7x00nx8m.js → index-n96nt4gb.js} +1235 -589
  34. package/dist/cli/{index-zkaz3fhw.js → index-pc4423w8.js} +2 -2
  35. package/dist/cli/{index-fksfxhmx.js → index-pgsvn005.js} +5 -5
  36. package/dist/cli/{index-qyvjp0bq.js → index-q81s0m8k.js} +66 -37
  37. package/dist/cli/{index-w5r84rd1.js → index-qjgg9qzs.js} +1 -1
  38. package/dist/cli/{index-e3caa7ng.js → index-qqawmxe7.js} +29 -29
  39. package/dist/cli/{index-txh3h83v.js → index-v2eevdbj.js} +4 -4
  40. package/dist/cli/{index-ycgm9pzg.js → index-xz9w7sa9.js} +3 -2
  41. package/dist/cli/{index-bd4g9fvb.js → index-ypwwchs0.js} +1 -1
  42. package/dist/cli/{index-zwn2e2pe.js → index-yr1aabxa.js} +4 -4
  43. package/dist/cli/index.js +27 -27
  44. package/dist/cli/{knowledge-escalator-wj85ppdt.js → knowledge-escalator-7zpg79dx.js} +11 -11
  45. package/dist/cli/{knowledge-events-4y9kk2xe.js → knowledge-events-8abttcnt.js} +9 -9
  46. package/dist/cli/{knowledge-link-8pr02pza.js → knowledge-link-mgg482z6.js} +5 -5
  47. package/dist/cli/{knowledge-store-kc8dwc14.js → knowledge-store-a5mzf986.js} +6 -6
  48. package/dist/cli/{knowledge-validator-584ga9fb.js → knowledge-validator-fn2myc73.js} +8 -8
  49. package/dist/cli/{pending-delegations-kkrczqv7.js → pending-delegations-591vme3d.js} +3 -3
  50. package/dist/cli/{pr-subscriptions-2xn238xt.js → pr-subscriptions-js5v2xr6.js} +3 -3
  51. package/dist/cli/{runner-e7z9cf5y.js → runner-rcnpm510.js} +6 -6
  52. package/dist/cli/{scan-cursor-rhjym1pn.js → scan-cursor-4jv70zwb.js} +7 -7
  53. package/dist/cli/{schema-yb3pvhcs.js → schema-jhz9hme9.js} +1 -1
  54. package/dist/cli/{scope-persistence-bxwjk9rc.js → scope-persistence-ykswenxj.js} +7 -7
  55. package/dist/cli/{skill-generator-3w8w7htr.js → skill-generator-k5pxb3w2.js} +13 -13
  56. package/dist/cli/{telemetry-t109dhv7.js → telemetry-xzy0qeap.js} +1 -1
  57. package/dist/cli/{worktree-collision-ownership-2jtg2my1.js → worktree-collision-ownership-vt0jzmdt.js} +3 -3
  58. package/dist/cli/{worktree-isolation-av1rshr3.js → worktree-isolation-443q0pah.js} +27 -27
  59. package/dist/commands/close.d.ts +1 -0
  60. package/dist/commands/context-map-stats.d.ts +5 -0
  61. package/dist/config/schema.d.ts +16 -0
  62. package/dist/context-map/telemetry.d.ts +168 -26
  63. package/dist/council/council-evidence-writer.d.ts +2 -1
  64. package/dist/council/council-freshness.d.ts +49 -0
  65. package/dist/council/council-review-identity.d.ts +133 -0
  66. package/dist/council/council-round-state.d.ts +27 -3
  67. package/dist/council/disagreement-detector.d.ts +12 -2
  68. package/dist/council/general-council-types.d.ts +32 -0
  69. package/dist/council/types.d.ts +43 -7
  70. package/dist/hooks/knowledge-application-gate.d.ts +23 -0
  71. package/dist/index.js +166 -143
  72. package/dist/observability/catalog.d.ts +7 -5
  73. package/dist/telemetry.d.ts +22 -1
  74. package/dist/tools/phase-complete/gates/types.d.ts +7 -0
  75. package/dist/tools/write-final-council-evidence.d.ts +1 -7
  76. package/package.json +1 -1
@@ -6,16 +6,16 @@ import {
6
6
  resolveExecutableFromPath,
7
7
  runEvaluation,
8
8
  runExternalTool
9
- } from "./index-w5r84rd1.js";
9
+ } from "./index-qjgg9qzs.js";
10
10
  import {
11
11
  stableCanonicalStringify
12
- } from "./index-xz0ccakc.js";
12
+ } from "./index-3377n9qp.js";
13
13
  import {
14
14
  detectStraySwarmDirs,
15
15
  readDoctorArtifact,
16
16
  removeStraySwarmDir,
17
17
  runConfigDoctor
18
- } from "./index-n7trn9wz.js";
18
+ } from "./index-gayh8tmh.js";
19
19
  import {
20
20
  MAX_TRANSIENT_RETRIES,
21
21
  archiveEvidence,
@@ -61,7 +61,7 @@ import {
61
61
  updateTaskStatus,
62
62
  validateProjectRoot,
63
63
  validateSymlinkBoundary
64
- } from "./index-4qvsh3m5.js";
64
+ } from "./index-0a4s2803.js";
65
65
  import {
66
66
  EvaluationTaskV1Schema,
67
67
  GateAuditManifestV1Schema,
@@ -78,7 +78,7 @@ import {
78
78
  saveGateAuditResult,
79
79
  savePromotionDecision,
80
80
  saveTaskSetSnapshot
81
- } from "./index-zkaz3fhw.js";
81
+ } from "./index-pc4423w8.js";
82
82
  import {
83
83
  loadDatabaseCtor
84
84
  } from "./index-134d35c1.js";
@@ -104,12 +104,12 @@ import {
104
104
  } from "./index-y8552snf.js";
105
105
  import {
106
106
  readRecentEscalations
107
- } from "./index-fksfxhmx.js";
107
+ } from "./index-pgsvn005.js";
108
108
  import {
109
109
  alreadyCuratedThisGeneration,
110
110
  claimNextScanBatch,
111
111
  resolveCohortId
112
- } from "./index-9qbr27bw.js";
112
+ } from "./index-eybamsqg.js";
113
113
  import {
114
114
  CURATOR_INIT_PROMPT,
115
115
  CURATOR_PHASE_PROMPT,
@@ -158,7 +158,7 @@ import {
158
158
  listActive,
159
159
  subscribe,
160
160
  unsubscribe
161
- } from "./index-5e5a1y2r.js";
161
+ } from "./index-3p4wgm0d.js";
162
162
  import {
163
163
  BUNDLED_PROJECT_SKILL_ROOT,
164
164
  DEFAULT_SKILL_MIN_CONFIDENCE,
@@ -179,7 +179,7 @@ import {
179
179
  retireSkill,
180
180
  selectCandidateEntries,
181
181
  syncBundledProjectSkillsIfMissingAsync
182
- } from "./index-txh3h83v.js";
182
+ } from "./index-v2eevdbj.js";
183
183
  import {
184
184
  appendUnactionable,
185
185
  quarantineEntry,
@@ -190,11 +190,11 @@ import {
190
190
  validateActionableFields,
191
191
  validateLesson,
192
192
  validateSkillPath
193
- } from "./index-cw96tpy6.js";
193
+ } from "./index-cgcs823z.js";
194
194
  import {
195
195
  authorizeCuration,
196
196
  buildConfigFingerprintInput
197
- } from "./index-e1hjd15c.js";
197
+ } from "./index-463msy1e.js";
198
198
  import {
199
199
  cohortConfigFingerprint
200
200
  } from "./index-rtry5xyf.js";
@@ -213,7 +213,7 @@ import {
213
213
  findByBatchId,
214
214
  readDelegations,
215
215
  sweepStaleDelegations
216
- } from "./index-97psh79d.js";
216
+ } from "./index-bxs4wkjf.js";
217
217
  import {
218
218
  WORKTREE_LIFECYCLE_LOCK_FILE,
219
219
  recordWorktreeProvisioningOwner,
@@ -246,18 +246,18 @@ import {
246
246
  transitionTaskWorkflowEvidence,
247
247
  withTaskEvidenceTransaction,
248
248
  writeWorkflowWalFile
249
- } from "./index-t7sfrv3v.js";
249
+ } from "./index-262kyrk3.js";
250
250
  import {
251
251
  provisionWorktree,
252
252
  removeWorktree
253
- } from "./index-tzyvmkd1.js";
253
+ } from "./index-bxk21f2w.js";
254
254
  import {
255
255
  MAX_PENDING_SCOPE_BINDINGS,
256
256
  canonicalWorkspaceIdentity,
257
257
  clearAllScopes,
258
258
  clearScopeBindingFromDisk,
259
259
  clearScopeBindings
260
- } from "./index-zwn2e2pe.js";
260
+ } from "./index-yr1aabxa.js";
261
261
  import {
262
262
  appendLedgerEvent,
263
263
  computePlanHash,
@@ -267,11 +267,12 @@ import {
267
267
  getOrAdoptPlanEpochUnderLock,
268
268
  initLedger,
269
269
  ledgerExists,
270
+ normalizeExecutionProfileForHash,
270
271
  readLedgerEvents,
271
272
  readPlanEpochIdentity,
272
273
  replayFromLedgerWithStatus,
273
274
  takeSnapshotEvent
274
- } from "./index-g8qbjqqz.js";
275
+ } from "./index-3gagma8p.js";
275
276
  import {
276
277
  isPathWithinDeclaredScope,
277
278
  sanitizeDiagnosticText
@@ -322,7 +323,7 @@ import {
322
323
  transactFile,
323
324
  transactKnowledge,
324
325
  wordBigrams
325
- } from "./index-vacrzesw.js";
326
+ } from "./index-923phxsp.js";
326
327
  import {
327
328
  MAX_EVENT_LOG_ENTRIES,
328
329
  _internals as _internals2,
@@ -336,10 +337,10 @@ import {
336
337
  recordKnowledgeEvent,
337
338
  recordPhaseCloseIntent,
338
339
  resolveKnowledgeEventsPath
339
- } from "./index-k46kg4t6.js";
340
+ } from "./index-a7cnyp5e.js";
340
341
  import {
341
342
  resolveWorktreeIsolationConfig
342
- } from "./index-19f0zycs.js";
343
+ } from "./index-bydybrke.js";
343
344
  import {
344
345
  RetrospectiveEvidenceSchema
345
346
  } from "./index-gprxjmm7.js";
@@ -349,7 +350,7 @@ import {
349
350
  init_loader,
350
351
  loadPluginConfig,
351
352
  loadPluginConfigWithMeta
352
- } from "./index-1c9mfnj0.js";
353
+ } from "./index-fypq68yn.js";
353
354
  import {
354
355
  DEFAULT_SKILL_OPT_CONFIG,
355
356
  FALLBACK_MODELS_MAX,
@@ -363,7 +364,7 @@ import {
363
364
  package_default,
364
365
  resolveAutoReviewConfig,
365
366
  stripKnownSwarmPrefix
366
- } from "./index-h8qed3pr.js";
367
+ } from "./index-7ph5pz77.js";
367
368
  import {
368
369
  AGENT_TOOL_MAP,
369
370
  ALL_AGENT_NAMES,
@@ -414,10 +415,10 @@ import {
414
415
  resolveLinkDir,
415
416
  sanitizeLinkId,
416
417
  writeLinkPointer
417
- } from "./index-w0cj7zyd.js";
418
+ } from "./index-j2ckvbx7.js";
418
419
  import {
419
420
  atomicWriteFile
420
- } from "./index-qbpxrw95.js";
421
+ } from "./index-1kq3x5q6.js";
421
422
  import {
422
423
  KNOWLEDGE_SCHEMA_VERSION,
423
424
  OUTCOME_BLOCK_THRESHOLD,
@@ -429,7 +430,7 @@ import {
429
430
  atomicWriteSwarmFileSync,
430
431
  matchTempGrammar,
431
432
  parseTargetBasename
432
- } from "./index-ycgm9pzg.js";
433
+ } from "./index-xz9w7sa9.js";
433
434
  import {
434
435
  assertProjectRoot,
435
436
  hasExplicitProjectBoundary,
@@ -437,12 +438,12 @@ import {
437
438
  listActiveLocks,
438
439
  tryAcquireLock,
439
440
  withEvidenceLock
440
- } from "./index-bghwrr59.js";
441
+ } from "./index-6q35swn2.js";
441
442
  import {
442
443
  emit,
443
444
  getLastHeartbeat,
444
445
  telemetry
445
- } from "./index-qyvjp0bq.js";
446
+ } from "./index-q81s0m8k.js";
446
447
  import {
447
448
  require_proper_lockfile
448
449
  } from "./index-7g4c7s5r.js";
@@ -469,20 +470,107 @@ import {
469
470
 
470
471
  // src/hooks/delegation-gate/worktree-isolation.ts
471
472
  init_constants();
472
- import { createHash as createHash24 } from "crypto";
473
+ import { createHash as createHash25 } from "crypto";
473
474
  import * as fs53 from "fs/promises";
474
475
  import * as path114 from "path";
475
476
  init_executor();
476
477
 
477
478
  // src/state.ts
478
479
  init_constants();
480
+ init_loader();
479
481
  import { randomUUID as randomUUID14 } from "crypto";
480
482
  import * as fs52 from "fs/promises";
481
483
  import * as path113 from "path";
482
484
  init_schema();
483
485
 
484
- // src/db/qa-gate-profile.ts
486
+ // src/council/council-review-identity.ts
487
+ init_schema();
485
488
  import { createHash } from "crypto";
489
+ var COUNCIL_REVIEW_IDENTITY_VERSION = 2;
490
+ function computeCouncilReviewHash(plan) {
491
+ const normalized = {
492
+ schema_version: plan.schema_version,
493
+ title: plan.title,
494
+ swarm: plan.swarm,
495
+ migration_status: plan.migration_status,
496
+ execution_profile: normalizeExecutionProfileForHash(plan.execution_profile),
497
+ phases: plan.phases.map((phase) => ({
498
+ id: phase.id,
499
+ name: phase.name,
500
+ type: phase.type,
501
+ required_agents: phase.required_agents ? [...phase.required_agents].sort() : undefined,
502
+ tasks: phase.tasks.map((task) => ({
503
+ id: task.id,
504
+ phase: task.phase,
505
+ size: task.size,
506
+ description: task.description,
507
+ depends: [...task.depends].sort(),
508
+ acceptance: task.acceptance,
509
+ files_touched: [...task.files_touched].sort(),
510
+ evidence_path: task.evidence_path,
511
+ fr_refs: task.fr_refs ? [...task.fr_refs].sort() : undefined
512
+ }))
513
+ }))
514
+ };
515
+ return createHash("sha256").update(JSON.stringify(normalized), "utf8").digest("hex");
516
+ }
517
+ function computeCouncilPolicyDigest(level, config) {
518
+ const base = {
519
+ maxRounds: config?.maxRounds ?? 3,
520
+ vetoPriority: config?.vetoPriority ?? true,
521
+ freshnessMaxAgeHours: config?.freshnessMaxAgeHours ?? 24
522
+ };
523
+ let normalized;
524
+ if (level === "final") {
525
+ normalized = {
526
+ ...base,
527
+ finalCompletionPolicy: resolveFinalCompletionPolicy(config)
528
+ };
529
+ } else if (level === "phase") {
530
+ normalized = {
531
+ ...base,
532
+ requireAllMembers: config?.requireAllMembers ?? false,
533
+ minimumMembers: config?.minimumMembers ?? 3,
534
+ phaseConcernsAllowComplete: config?.phaseConcernsAllowComplete ?? true
535
+ };
536
+ } else {
537
+ normalized = {
538
+ ...base,
539
+ requireAllMembers: config?.requireAllMembers ?? false,
540
+ minimumMembers: config?.minimumMembers ?? 3
541
+ };
542
+ }
543
+ return createHash("sha256").update(JSON.stringify(normalized), "utf8").digest("hex");
544
+ }
545
+ function resolveFinalCompletionPolicy(config) {
546
+ const policy = config?.finalCompletionPolicy;
547
+ if (!policy || policy.mode !== "quorum") {
548
+ return { mode: "all_required" };
549
+ }
550
+ const minimum = policy.minimumMembers;
551
+ if (typeof minimum === "number" && Number.isInteger(minimum) && minimum >= 3 && minimum <= 5) {
552
+ return { mode: "quorum", minimumMembers: minimum };
553
+ }
554
+ return { mode: "all_required" };
555
+ }
556
+ function computeCouncilReviewIdentity(input) {
557
+ const identity = {
558
+ version: COUNCIL_REVIEW_IDENTITY_VERSION,
559
+ level: input.level,
560
+ scope: input.scope,
561
+ planId: input.plan ? derivePlanId(input.plan) : null,
562
+ planIdentityHash: input.plan ? derivePlanIdentityHash(input.plan) : null,
563
+ reviewHash: input.plan ? computeCouncilReviewHash(input.plan) : null,
564
+ policyDigest: computeCouncilPolicyDigest(input.level, input.config)
565
+ };
566
+ return {
567
+ ...identity,
568
+ identityDigest: createHash("sha256").update(JSON.stringify(identity), "utf8").digest("hex")
569
+ };
570
+ }
571
+
572
+ // src/db/qa-gate-profile.ts
573
+ import { createHash as createHash2 } from "crypto";
486
574
 
487
575
  // src/qa-gate/recovery.ts
488
576
  function formatLegacyQaBindingOnlyCall(identity) {
@@ -928,7 +1016,7 @@ function computeProfileHash(profile) {
928
1016
  identity_hash: profile.identity_hash,
929
1017
  gates: profile.gates
930
1018
  });
931
- return createHash("sha256").update(payload).digest("hex");
1019
+ return createHash2("sha256").update(payload).digest("hex");
932
1020
  }
933
1021
  function getEffectiveGates(profile, sessionOverrides) {
934
1022
  const merged = { ...profile.gates };
@@ -4197,7 +4285,7 @@ async function cleanupRecoveredWorktree(directory, descriptor) {
4197
4285
  awaitingMergeByCallID,
4198
4286
  cleanupStandardWorktreeForCallId,
4199
4287
  standardWorktreeByCallID
4200
- } = await import("./worktree-isolation-av1rshr3.js");
4288
+ } = await import("./worktree-isolation-443q0pah.js");
4201
4289
  standardWorktreeByCallID.delete(descriptor.callID);
4202
4290
  if (hasResidue)
4203
4291
  awaitingMergeByCallID.set(descriptor.callID, {
@@ -4299,7 +4387,7 @@ async function recoverCoderSettlement(directory, taskId) {
4299
4387
  awaitingMergeByCallID,
4300
4388
  finishStandardWorktreeDispatch,
4301
4389
  standardWorktreeByCallID
4302
- } = await import("./worktree-isolation-av1rshr3.js");
4390
+ } = await import("./worktree-isolation-443q0pah.js");
4303
4391
  const descriptor = wal.worktree;
4304
4392
  const reconstructedDispatch = {
4305
4393
  callID: descriptor.callID,
@@ -4962,7 +5050,7 @@ async function commitTaskTerminalUnderPlanLock(options) {
4962
5050
 
4963
5051
  // src/hooks/pr-workflow-gate.ts
4964
5052
  init_zod();
4965
- import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto";
5053
+ import { createHash as createHash5, randomUUID as randomUUID3 } from "crypto";
4966
5054
  import { readFileSync as readFileSync4 } from "fs";
4967
5055
  import * as fsp2 from "fs/promises";
4968
5056
  import * as path11 from "path";
@@ -6142,7 +6230,7 @@ ${trimmed}`;
6142
6230
 
6143
6231
  // src/background/lane-output-store.ts
6144
6232
  init_zod();
6145
- import { createHash as createHash3 } from "crypto";
6233
+ import { createHash as createHash4 } from "crypto";
6146
6234
  import {
6147
6235
  existsSync as existsSync6,
6148
6236
  mkdirSync as mkdirSync3,
@@ -6217,7 +6305,7 @@ function hasValidArtifactIntegrity(artifact, expectedRef) {
6217
6305
  return artifact.ref === expectedRef && artifact.ref === expectedArtifactRef;
6218
6306
  }
6219
6307
  function digestText(text) {
6220
- return createHash3("sha256").update(text).digest("hex");
6308
+ return createHash4("sha256").update(text).digest("hex");
6221
6309
  }
6222
6310
 
6223
6311
  // src/background/pr-review-trigger-contract.ts
@@ -7778,7 +7866,7 @@ async function readPrReviewFeedbackHandoffArtifact(directory, relativePath) {
7778
7866
  }
7779
7867
  return {
7780
7868
  artifact: parsed.data,
7781
- digest: createHash4("sha256").update(raw, "utf8").digest("hex")
7869
+ digest: createHash5("sha256").update(raw, "utf8").digest("hex")
7782
7870
  };
7783
7871
  }
7784
7872
  var PrReviewFindingProjectionSchema = exports_external.object({
@@ -7834,7 +7922,7 @@ function canonicalGitHubPrUrl(value) {
7834
7922
  }
7835
7923
  }
7836
7924
  function workflowIdentity(state) {
7837
- return state.workflowInstanceId ?? `legacy-${createHash4("sha256").update(`${state.sessionID}\x00${state.mode}\x00${state.activatedAt}`).digest("hex").slice(0, 32)}`;
7925
+ return state.workflowInstanceId ?? `legacy-${createHash5("sha256").update(`${state.sessionID}\x00${state.mode}\x00${state.activatedAt}`).digest("hex").slice(0, 32)}`;
7838
7926
  }
7839
7927
  function sameHandoffIds(left, right) {
7840
7928
  const normalizedLeft = [...new Set(left)].sort();
@@ -9325,7 +9413,7 @@ function parseReviewerVerdictFields(text, itemId) {
9325
9413
  return fields;
9326
9414
  }
9327
9415
  function reviewerVerdictRowDigest(fields) {
9328
- return createHash4("sha256").update(fields.join("\x00")).digest("hex");
9416
+ return createHash5("sha256").update(fields.join("\x00")).digest("hex");
9329
9417
  }
9330
9418
  function parseLaneItemVerdicts(text, itemIds, phase, reviewerClaims) {
9331
9419
  const parsed = new Map;
@@ -9931,7 +10019,7 @@ function workflowGateStateRelativePath(sessionID) {
9931
10019
  function prWorkflowSessionFileStem(sessionID) {
9932
10020
  const normalized = normalizeSessionID(sessionID);
9933
10021
  const slug = normalized.replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 80) || "session";
9934
- const digest = createHash4("sha256").update(normalized).digest("hex").slice(0, 12);
10022
+ const digest = createHash5("sha256").update(normalized).digest("hex").slice(0, 12);
9935
10023
  return `${slug}-${digest}`;
9936
10024
  }
9937
10025
  function normalizeSessionID(sessionID) {
@@ -10153,7 +10241,7 @@ ${USAGE}`;
10153
10241
  }
10154
10242
 
10155
10243
  // src/services/spec-drift-recovery.ts
10156
- import { createHash as createHash5 } from "crypto";
10244
+ import { createHash as createHash6 } from "crypto";
10157
10245
  import { appendFile as appendFile5, mkdir as mkdir5, readFile as readFile6, unlink as unlink2 } from "fs/promises";
10158
10246
  import { dirname as dirname9 } from "path";
10159
10247
  var SPEC_DRIFT_RECOVERY_AGENT = "spec-drift-recovery";
@@ -10182,7 +10270,7 @@ function now() {
10182
10270
  return new Date().toISOString();
10183
10271
  }
10184
10272
  function sha2562(text) {
10185
- return createHash5("sha256").update(text, "utf-8").digest("hex");
10273
+ return createHash6("sha256").update(text, "utf-8").digest("hex");
10186
10274
  }
10187
10275
  function parseMarker(raw) {
10188
10276
  try {
@@ -13490,8 +13578,8 @@ async function handleClarifyCommand(_directory, args) {
13490
13578
 
13491
13579
  // src/commands/close.ts
13492
13580
  import * as fsSync2 from "fs";
13493
- import { promises as fs15 } from "fs";
13494
- import path44 from "path";
13581
+ import { promises as fs16 } from "fs";
13582
+ import path45 from "path";
13495
13583
  init_schema();
13496
13584
 
13497
13585
  // src/full-auto/state.ts
@@ -15598,7 +15686,7 @@ function planMerges(active, threshold, maxComparisons, maxMerges) {
15598
15686
  };
15599
15687
  }
15600
15688
  async function sweepActiveNearDuplicates(directory, options = {}) {
15601
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-twwb61bh.js");
15689
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-4zevsvaa.js");
15602
15690
  const { config } = loadPluginConfigWithMeta2(directory);
15603
15691
  const sweepConfig = config.learning?.dedup_sweep;
15604
15692
  if (sweepConfig?.enabled === false)
@@ -16682,7 +16770,7 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
16682
16770
  }
16683
16771
  if (config.skill_generation_enabled === true && skillCandidates.length > 0) {
16684
16772
  try {
16685
- const skillModule = await import("./skill-generator-3w8w7htr.js");
16773
+ const skillModule = await import("./skill-generator-k5pxb3w2.js");
16686
16774
  for (const cand of skillCandidates) {
16687
16775
  if (cand.confidence < (config.min_skill_confidence ?? DEFAULT_SKILL_MIN_CONFIDENCE)) {
16688
16776
  continue;
@@ -17142,7 +17230,7 @@ async function applyCuratorKnowledgeUpdates(directory, recommendations, knowledg
17142
17230
  } catch {}
17143
17231
  }
17144
17232
  if (contradictedEntries.length > 0 && knowledgeConfig.contradiction_threshold_action === "quarantine") {
17145
- const { maybeQuarantineOnContradiction } = await import("./knowledge-escalator-wj85ppdt.js");
17233
+ const { maybeQuarantineOnContradiction } = await import("./knowledge-escalator-7zpg79dx.js");
17146
17234
  for (const { id } of contradictedEntries) {
17147
17235
  try {
17148
17236
  await maybeQuarantineOnContradiction(directory, id, knowledgeConfig.contradiction_quarantine_threshold, knowledgeConfig.contradiction_quarantine_window_days);
@@ -17961,7 +18049,7 @@ async function runCuratorPostMortem(directory, options = {}) {
17961
18049
  warnings.push("Failed to collect knowledge summary.");
17962
18050
  }
17963
18051
  try {
17964
- const { getScanStatus } = await import("./scan-cursor-rhjym1pn.js");
18052
+ const { getScanStatus } = await import("./scan-cursor-4jv70zwb.js");
17965
18053
  const scanStatus = await getScanStatus(directory);
17966
18054
  if (scanStatus.remaining_estimate > 0) {
17967
18055
  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.`);
@@ -18133,9 +18221,9 @@ var _internals24 = {
18133
18221
  verifyPostMortemKnowledgeActions,
18134
18222
  repairPostMortemActions,
18135
18223
  loadDefaultKnowledgeConfig: async (directory) => {
18136
- const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-yb3pvhcs.js");
18224
+ const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-jhz9hme9.js");
18137
18225
  try {
18138
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-twwb61bh.js");
18226
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-4zevsvaa.js");
18139
18227
  const loaded = loadPluginConfigWithMeta2(directory);
18140
18228
  return KnowledgeConfigSchema2.parse(loaded.config.knowledge ?? {});
18141
18229
  } catch {
@@ -18143,11 +18231,11 @@ var _internals24 = {
18143
18231
  }
18144
18232
  },
18145
18233
  applyCuratorKnowledgeUpdates: async (directory, recommendations, knowledgeConfig, generation) => {
18146
- const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-vghf320v.js");
18234
+ const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-acp80hpc.js");
18147
18235
  return applyCuratorKnowledgeUpdates2(directory, recommendations, knowledgeConfig, generation);
18148
18236
  },
18149
18237
  checkHivePromotions: async (entries, knowledgeConfig, directory) => {
18150
- const { checkHivePromotions } = await import("./hive-promoter-j3vw2hj4.js");
18238
+ const { checkHivePromotions } = await import("./hive-promoter-qhrngsvb.js");
18151
18239
  return checkHivePromotions(entries, knowledgeConfig, directory);
18152
18240
  },
18153
18241
  applyProposalTriage: async (directory, triage) => {
@@ -18156,7 +18244,7 @@ var _internals24 = {
18156
18244
  activateProposal,
18157
18245
  listSkills: listSkills2,
18158
18246
  sanitizeSlug
18159
- } = await import("./skill-generator-3w8w7htr.js");
18247
+ } = await import("./skill-generator-k5pxb3w2.js");
18160
18248
  const result = {
18161
18249
  approved: [],
18162
18250
  rejected: [],
@@ -18246,7 +18334,7 @@ function extractCurrentPhaseFromPlan(plan) {
18246
18334
 
18247
18335
  // src/hooks/hive-promoter.ts
18248
18336
  init_schema();
18249
- import { createHash as createHash6 } from "crypto";
18337
+ import { createHash as createHash7 } from "crypto";
18250
18338
  import path25 from "path";
18251
18339
 
18252
18340
  // src/hooks/hive-policy.ts
@@ -18662,7 +18750,7 @@ function buildLineage(args) {
18662
18750
  return lineage;
18663
18751
  }
18664
18752
  function lessonRevision(lesson) {
18665
- return createHash6("sha256").update(lesson).digest("hex").slice(0, 12);
18753
+ return createHash7("sha256").update(lesson).digest("hex").slice(0, 12);
18666
18754
  }
18667
18755
  async function checkHivePromotions(swarmEntries, config, directory) {
18668
18756
  const empty = {
@@ -19251,7 +19339,7 @@ async function promoteFromSwarm(directory, lessonId, options, config) {
19251
19339
  }
19252
19340
 
19253
19341
  // src/hooks/knowledge-curator.ts
19254
- import { createHash as createHash7 } from "crypto";
19342
+ import { createHash as createHash8 } from "crypto";
19255
19343
  import { existsSync as existsSync14 } from "fs";
19256
19344
  import {
19257
19345
  appendFile as appendFile7,
@@ -19489,12 +19577,12 @@ function recordSeenRetroSection(key, value, timestamp) {
19489
19577
  capSeenRetroSections();
19490
19578
  }
19491
19579
  function hashContent(content) {
19492
- return createHash7("sha1").update(content).digest("hex");
19580
+ return createHash8("sha1").update(content).digest("hex");
19493
19581
  }
19494
19582
  async function loadConfigForPolicyCurator(directory) {
19495
- const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-yb3pvhcs.js");
19583
+ const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-jhz9hme9.js");
19496
19584
  try {
19497
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-twwb61bh.js");
19585
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-4zevsvaa.js");
19498
19586
  const { config: loadedConfig } = loadPluginConfigWithMeta2(directory);
19499
19587
  return KnowledgeConfigSchema2.parse(loadedConfig.knowledge ?? {});
19500
19588
  } catch {
@@ -20512,6 +20600,599 @@ var _internals28 = {
20512
20600
  realpath: realpath3
20513
20601
  };
20514
20602
 
20603
+ // src/context-map/telemetry.ts
20604
+ import * as fs13 from "fs";
20605
+ import * as path28 from "path";
20606
+ init_logger();
20607
+ var CONTEXT_TELEMETRY_LIMITS = {
20608
+ activeMaxBytes: 256 * 1024,
20609
+ activeMaxEntries: 1e4,
20610
+ ageMaxMs: 30 * 24 * 60 * 60 * 1000,
20611
+ compactMaxBytes: 64 * 1024,
20612
+ readMaxBytes: 280 * 1024,
20613
+ checkInterval: 50,
20614
+ warnCooldownMs: 60000,
20615
+ headerMaxBytes: 8 * 1024
20616
+ };
20617
+ function isValidTelemetryEntry(value) {
20618
+ if (typeof value !== "object" || value === null) {
20619
+ return false;
20620
+ }
20621
+ const obj = value;
20622
+ const nonNegFinite = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
20623
+ return typeof obj.timestamp === "string" && typeof obj.task_id === "string" && typeof obj.agent_role === "string" && typeof obj.delegation_reason === "string" && nonNegFinite(obj.token_estimate) && nonNegFinite(obj.cache_hits) && nonNegFinite(obj.cache_misses) && nonNegFinite(obj.stale_entries) && nonNegFinite(obj.recommended_reads) && nonNegFinite(obj.skipped_reads) && typeof obj.success === "boolean";
20624
+ }
20625
+ var _internals29 = {
20626
+ appendFileSync: fs13.appendFileSync,
20627
+ readFileSync: fs13.readFileSync,
20628
+ existsSync: fs13.existsSync,
20629
+ mkdirSync: fs13.mkdirSync,
20630
+ statSync: fs13.statSync,
20631
+ renameSync: fs13.renameSync,
20632
+ writeFileSync: fs13.writeFileSync,
20633
+ unlinkSync: fs13.unlinkSync,
20634
+ openSync: fs13.openSync,
20635
+ closeSync: fs13.closeSync,
20636
+ readSync: fs13.readSync,
20637
+ limits: CONTEXT_TELEMETRY_LIMITS,
20638
+ emitHealth: emitContextTelemetryHealth,
20639
+ withStoreLock
20640
+ };
20641
+ function telemetryFilePath(directory) {
20642
+ return path28.join(directory, ".swarm", "context-telemetry.jsonl");
20643
+ }
20644
+ function lockFilePath(directory) {
20645
+ return path28.join(directory, ".swarm", "context-telemetry.lock");
20646
+ }
20647
+ function tmpFilePath(directory) {
20648
+ return path28.join(directory, ".swarm", `.context-telemetry.jsonl.${process.pid}.tmp`);
20649
+ }
20650
+ var MANIFEST_TYPE = "ctx-telemetry-manifest";
20651
+ var MANIFEST_SCHEMA = 2;
20652
+ function emptyFolded() {
20653
+ return {
20654
+ delegations: 0,
20655
+ successCount: 0,
20656
+ cacheHits: 0,
20657
+ cacheMisses: 0,
20658
+ staleEntries: 0,
20659
+ tokenSum: 0,
20660
+ recommendedReads: 0,
20661
+ skippedReads: 0,
20662
+ corrupt: 0,
20663
+ dropped: 0,
20664
+ oldestTimestamp: null,
20665
+ newestTimestamp: null
20666
+ };
20667
+ }
20668
+ function emptyManifest() {
20669
+ return {
20670
+ v: 2,
20671
+ type: MANIFEST_TYPE,
20672
+ schemaVersion: MANIFEST_SCHEMA,
20673
+ folded: emptyFolded(),
20674
+ updatedAt: new Date().toISOString()
20675
+ };
20676
+ }
20677
+ function parseManifestLine(line) {
20678
+ const trimmed = line.trim();
20679
+ if (!trimmed)
20680
+ return null;
20681
+ try {
20682
+ const obj = JSON.parse(trimmed);
20683
+ if (typeof obj !== "object" || obj === null)
20684
+ return null;
20685
+ const rec = obj;
20686
+ if (rec.type !== MANIFEST_TYPE || rec.v !== 2 || rec.schemaVersion !== MANIFEST_SCHEMA || typeof rec.folded !== "object" || rec.folded === null) {
20687
+ return null;
20688
+ }
20689
+ const f = rec.folded;
20690
+ const manifest = emptyManifest();
20691
+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : 0;
20692
+ manifest.folded.delegations = num(f.delegations);
20693
+ manifest.folded.successCount = num(f.successCount);
20694
+ manifest.folded.cacheHits = num(f.cacheHits);
20695
+ manifest.folded.cacheMisses = num(f.cacheMisses);
20696
+ manifest.folded.staleEntries = num(f.staleEntries);
20697
+ manifest.folded.tokenSum = num(f.tokenSum);
20698
+ manifest.folded.recommendedReads = num(f.recommendedReads);
20699
+ manifest.folded.skippedReads = num(f.skippedReads);
20700
+ manifest.folded.corrupt = num(f.corrupt);
20701
+ manifest.folded.dropped = num(f.dropped);
20702
+ if (typeof f.oldestTimestamp === "string") {
20703
+ manifest.folded.oldestTimestamp = f.oldestTimestamp;
20704
+ }
20705
+ if (typeof f.newestTimestamp === "string") {
20706
+ manifest.folded.newestTimestamp = f.newestTimestamp;
20707
+ }
20708
+ manifest.updatedAt = typeof rec.updatedAt === "string" ? rec.updatedAt : new Date().toISOString();
20709
+ return manifest;
20710
+ } catch {
20711
+ return null;
20712
+ }
20713
+ }
20714
+ function readBoundedChunk(filePath, maxBytes) {
20715
+ try {
20716
+ if (!_internals29.existsSync(filePath)) {
20717
+ return { text: "", truncated: false };
20718
+ }
20719
+ const fd = _internals29.openSync(filePath, "r");
20720
+ try {
20721
+ const size = _internals29.statSync(filePath).size;
20722
+ const truncated = size > maxBytes;
20723
+ const len = Math.min(size, maxBytes);
20724
+ const buf = Buffer.alloc(len);
20725
+ let read = 0;
20726
+ while (read < len) {
20727
+ const n = _internals29.readSync(fd, buf, read, len - read, read);
20728
+ if (n <= 0)
20729
+ break;
20730
+ read += n;
20731
+ }
20732
+ return { text: buf.toString("utf-8", 0, read), truncated };
20733
+ } finally {
20734
+ _internals29.closeSync(fd);
20735
+ }
20736
+ } catch {
20737
+ warnThrottled("bounded read failed (transient I/O)");
20738
+ return { text: "", truncated: false };
20739
+ }
20740
+ }
20741
+ function fileSizeOrZero(filePath) {
20742
+ try {
20743
+ if (!_internals29.existsSync(filePath))
20744
+ return 0;
20745
+ return _internals29.statSync(filePath).size;
20746
+ } catch {
20747
+ return 0;
20748
+ }
20749
+ }
20750
+ function foldEntryInto(agg, entry) {
20751
+ agg.delegations += 1;
20752
+ if (entry.success)
20753
+ agg.successCount += 1;
20754
+ agg.cacheHits += entry.cache_hits;
20755
+ agg.cacheMisses += entry.cache_misses;
20756
+ agg.staleEntries += entry.stale_entries;
20757
+ agg.tokenSum += entry.token_estimate;
20758
+ agg.recommendedReads += entry.recommended_reads;
20759
+ agg.skippedReads += entry.skipped_reads;
20760
+ if (agg.oldestTimestamp === null || entry.timestamp < agg.oldestTimestamp) {
20761
+ agg.oldestTimestamp = entry.timestamp;
20762
+ }
20763
+ if (agg.newestTimestamp === null || entry.timestamp > agg.newestTimestamp) {
20764
+ agg.newestTimestamp = entry.timestamp;
20765
+ }
20766
+ }
20767
+ function cloneFolded(agg) {
20768
+ return {
20769
+ delegations: agg.delegations,
20770
+ successCount: agg.successCount,
20771
+ cacheHits: agg.cacheHits,
20772
+ cacheMisses: agg.cacheMisses,
20773
+ staleEntries: agg.staleEntries,
20774
+ tokenSum: agg.tokenSum,
20775
+ recommendedReads: agg.recommendedReads,
20776
+ skippedReads: agg.skippedReads,
20777
+ corrupt: agg.corrupt,
20778
+ dropped: agg.dropped,
20779
+ oldestTimestamp: agg.oldestTimestamp,
20780
+ newestTimestamp: agg.newestTimestamp
20781
+ };
20782
+ }
20783
+ function atomicReplace(directory, content) {
20784
+ const finalPath = telemetryFilePath(directory);
20785
+ const tmpPath = tmpFilePath(directory);
20786
+ try {
20787
+ if (_internals29.existsSync(tmpPath)) {
20788
+ try {
20789
+ _internals29.unlinkSync(tmpPath);
20790
+ } catch {}
20791
+ }
20792
+ _internals29.writeFileSync(tmpPath, content, "utf-8");
20793
+ _internals29.renameSync(tmpPath, finalPath);
20794
+ } catch {
20795
+ try {
20796
+ if (_internals29.existsSync(tmpPath)) {
20797
+ _internals29.unlinkSync(tmpPath);
20798
+ }
20799
+ } catch {}
20800
+ throw new Error("context-telemetry atomic replace failed");
20801
+ }
20802
+ }
20803
+ function withStoreLock(directory, fn) {
20804
+ const lockPath = lockFilePath(directory);
20805
+ let acquired = false;
20806
+ try {
20807
+ _internals29.mkdirSync(path28.dirname(lockPath), { recursive: true });
20808
+ const fd = _internals29.openSync(lockPath, "wx");
20809
+ _internals29.closeSync(fd);
20810
+ acquired = true;
20811
+ } catch {
20812
+ try {
20813
+ const age = Date.now() - _internals29.statSync(lockPath).mtimeMs;
20814
+ if (age > 5 * 60000) {
20815
+ try {
20816
+ _internals29.unlinkSync(lockPath);
20817
+ } catch {}
20818
+ try {
20819
+ const fd = _internals29.openSync(lockPath, "wx");
20820
+ _internals29.closeSync(fd);
20821
+ acquired = true;
20822
+ } catch {
20823
+ acquired = false;
20824
+ }
20825
+ }
20826
+ } catch {
20827
+ acquired = false;
20828
+ }
20829
+ }
20830
+ if (!acquired)
20831
+ return null;
20832
+ try {
20833
+ return fn();
20834
+ } finally {
20835
+ try {
20836
+ _internals29.unlinkSync(lockPath);
20837
+ } catch {}
20838
+ }
20839
+ }
20840
+ var _lastWarnAt = 0;
20841
+ function warnThrottled(message) {
20842
+ const now2 = Date.now();
20843
+ if (now2 - _lastWarnAt < _internals29.limits.warnCooldownMs)
20844
+ return;
20845
+ _lastWarnAt = now2;
20846
+ warn(`context-telemetry: ${message}`);
20847
+ }
20848
+ function readStore(directory, bounded) {
20849
+ const filePath = telemetryFilePath(directory);
20850
+ if (!_internals29.existsSync(filePath)) {
20851
+ return { manifest: null, records: [], corruptLines: 0, truncated: false };
20852
+ }
20853
+ let text;
20854
+ let truncated = false;
20855
+ if (bounded) {
20856
+ const chunk = readBoundedChunk(filePath, _internals29.limits.readMaxBytes);
20857
+ text = chunk.text;
20858
+ truncated = chunk.truncated;
20859
+ } else {
20860
+ try {
20861
+ text = _internals29.readFileSync(filePath, "utf-8");
20862
+ } catch {
20863
+ return { manifest: null, records: [], corruptLines: 0, truncated: false };
20864
+ }
20865
+ }
20866
+ const lines = text.split(`
20867
+ `);
20868
+ const records = [];
20869
+ let corruptLines = 0;
20870
+ let manifest = null;
20871
+ for (let i = 0;i < lines.length; i += 1) {
20872
+ const line = lines[i];
20873
+ if (line.trim() === "")
20874
+ continue;
20875
+ if (i === 0) {
20876
+ manifest = parseManifestLine(line);
20877
+ if (manifest)
20878
+ continue;
20879
+ }
20880
+ try {
20881
+ const parsed = JSON.parse(line);
20882
+ if (isValidTelemetryEntry(parsed)) {
20883
+ records.push(parsed);
20884
+ } else {
20885
+ corruptLines += 1;
20886
+ }
20887
+ } catch {
20888
+ corruptLines += 1;
20889
+ }
20890
+ }
20891
+ return { manifest, records, corruptLines, truncated };
20892
+ }
20893
+ function getTelemetrySummary(directory) {
20894
+ const filePath = telemetryFilePath(directory);
20895
+ const zero = () => ({
20896
+ total_delegations: 0,
20897
+ total_cache_hits: 0,
20898
+ total_cache_misses: 0,
20899
+ total_stale_entries: 0,
20900
+ avg_token_estimate: 0,
20901
+ total_recommended_reads: 0,
20902
+ total_skipped_reads: 0,
20903
+ success_rate: 0,
20904
+ coverage: "empty",
20905
+ tracked_period_ms: null,
20906
+ retained_entries: 0,
20907
+ folded_entries: 0,
20908
+ corrupt_entries: 0,
20909
+ dropped_entries: 0,
20910
+ on_disk_bytes: 0
20911
+ });
20912
+ const view = readStore(directory, true);
20913
+ const onDiskBytes = fileSizeOrZero(filePath);
20914
+ const corrupt = view.corruptLines;
20915
+ if (view.manifest === null) {
20916
+ const folded = emptyFolded();
20917
+ for (const rec of view.records)
20918
+ foldEntryInto(folded, rec);
20919
+ const total2 = folded.delegations;
20920
+ if (total2 === 0 && corrupt === 0 && view.records.length === 0) {
20921
+ return zero();
20922
+ }
20923
+ const coverage2 = view.truncated ? "partial-unmigrated" : "complete";
20924
+ return {
20925
+ total_delegations: total2,
20926
+ total_cache_hits: folded.cacheHits,
20927
+ total_cache_misses: folded.cacheMisses,
20928
+ total_stale_entries: folded.staleEntries,
20929
+ avg_token_estimate: total2 > 0 ? Math.round(folded.tokenSum / total2) : 0,
20930
+ total_recommended_reads: folded.recommendedReads,
20931
+ total_skipped_reads: folded.skippedReads,
20932
+ success_rate: total2 > 0 ? Math.round(folded.successCount / total2 * 100) : 0,
20933
+ coverage: coverage2,
20934
+ tracked_period_ms: periodMs(folded.oldestTimestamp, folded.newestTimestamp),
20935
+ retained_entries: view.records.length,
20936
+ folded_entries: 0,
20937
+ corrupt_entries: corrupt,
20938
+ dropped_entries: 0,
20939
+ on_disk_bytes: onDiskBytes
20940
+ };
20941
+ }
20942
+ const agg = cloneFolded(view.manifest.folded);
20943
+ for (const rec of view.records)
20944
+ foldEntryInto(agg, rec);
20945
+ const total = agg.delegations;
20946
+ if (total === 0 && view.records.length === 0 && corrupt === 0) {
20947
+ return zero();
20948
+ }
20949
+ const coverage = view.truncated ? "partial-unmigrated" : "complete";
20950
+ return {
20951
+ total_delegations: total,
20952
+ total_cache_hits: agg.cacheHits,
20953
+ total_cache_misses: agg.cacheMisses,
20954
+ total_stale_entries: agg.staleEntries,
20955
+ avg_token_estimate: total > 0 ? Math.round(agg.tokenSum / total) : 0,
20956
+ total_recommended_reads: agg.recommendedReads,
20957
+ total_skipped_reads: agg.skippedReads,
20958
+ success_rate: total > 0 ? Math.round(agg.successCount / total * 100) : 0,
20959
+ coverage,
20960
+ tracked_period_ms: periodMs(agg.oldestTimestamp, agg.newestTimestamp),
20961
+ retained_entries: view.records.length,
20962
+ folded_entries: view.manifest.folded.delegations,
20963
+ corrupt_entries: corrupt + view.manifest.folded.corrupt,
20964
+ dropped_entries: view.manifest.folded.dropped,
20965
+ on_disk_bytes: onDiskBytes
20966
+ };
20967
+ }
20968
+ function periodMs(oldest, newest) {
20969
+ if (oldest === null || newest === null)
20970
+ return null;
20971
+ const o = Date.parse(oldest);
20972
+ const n = Date.parse(newest);
20973
+ if (Number.isNaN(o) || Number.isNaN(n))
20974
+ return null;
20975
+ return Math.max(0, n - o);
20976
+ }
20977
+ function compactStore(directory, trigger = "compaction", alreadyLocked = false) {
20978
+ const filePath = telemetryFilePath(directory);
20979
+ if (!_internals29.existsSync(filePath))
20980
+ return;
20981
+ const run = () => {
20982
+ const view = readStore(directory, false);
20983
+ if (view.manifest === null)
20984
+ return;
20985
+ const folded = cloneFolded(view.manifest.folded);
20986
+ const now2 = Date.now();
20987
+ const agePruned = [];
20988
+ const kept = [];
20989
+ for (const rec of view.records) {
20990
+ const ts = Date.parse(rec.timestamp);
20991
+ if (!Number.isNaN(ts) && now2 - ts > _internals29.limits.ageMaxMs) {
20992
+ agePruned.push(rec);
20993
+ } else {
20994
+ kept.push(rec);
20995
+ }
20996
+ }
20997
+ const retained = [];
20998
+ let bytes = 0;
20999
+ for (let i = kept.length - 1;i >= 0; i -= 1) {
21000
+ const rec = kept[i];
21001
+ const lineBytes = Buffer.byteLength(JSON.stringify(rec)) + 1;
21002
+ if (retained.length >= _internals29.limits.activeMaxEntries || bytes + lineBytes > _internals29.limits.activeMaxBytes) {
21003
+ break;
21004
+ }
21005
+ retained.push(rec);
21006
+ bytes += lineBytes;
21007
+ }
21008
+ retained.reverse();
21009
+ for (const rec of agePruned)
21010
+ foldEntryInto(folded, rec);
21011
+ folded.dropped += agePruned.length;
21012
+ const retainedSet = new Set(retained);
21013
+ const compacted = [];
21014
+ const keptSet = new Set(kept);
21015
+ for (const rec of view.records) {
21016
+ if (keptSet.has(rec) && !retainedSet.has(rec)) {
21017
+ compacted.push(rec);
21018
+ }
21019
+ }
21020
+ for (const rec of compacted)
21021
+ foldEntryInto(folded, rec);
21022
+ folded.corrupt += view.corruptLines;
21023
+ const manifest = {
21024
+ ...emptyManifest(),
21025
+ folded,
21026
+ updatedAt: new Date().toISOString()
21027
+ };
21028
+ const lines = [`${JSON.stringify(manifest)}`];
21029
+ for (const rec of retained)
21030
+ lines.push(JSON.stringify(rec));
21031
+ atomicReplace(directory, lines.length > 1 ? `${lines.join(`
21032
+ `)}
21033
+ ` : `${lines[0]}
21034
+ `);
21035
+ emitHealth(directory, {
21036
+ trigger,
21037
+ accepted: folded.delegations + retained.length,
21038
+ compacted: compacted.length,
21039
+ retained: retained.length,
21040
+ dropped: agePruned.length,
21041
+ corrupt: folded.corrupt,
21042
+ oldest: folded.oldestTimestamp,
21043
+ newest: folded.newestTimestamp,
21044
+ bytes: fileSizeOrZero(filePath),
21045
+ limitBytes: _internals29.limits.activeMaxBytes
21046
+ });
21047
+ };
21048
+ if (alreadyLocked) {
21049
+ run();
21050
+ return;
21051
+ }
21052
+ withStoreLock(directory, run);
21053
+ }
21054
+ function migrateCutover(directory, trigger = "compaction", alreadyLocked = false) {
21055
+ const filePath = telemetryFilePath(directory);
21056
+ if (!_internals29.existsSync(filePath))
21057
+ return;
21058
+ const run = () => {
21059
+ if (!_internals29.existsSync(filePath))
21060
+ return;
21061
+ const view = readStore(directory, false);
21062
+ if (view.manifest === null && view.records.length === 0)
21063
+ return;
21064
+ const folded = view.manifest ? cloneFolded(view.manifest.folded) : emptyFolded();
21065
+ const now2 = Date.now();
21066
+ const agePruned = [];
21067
+ const kept = [];
21068
+ for (const rec of view.records) {
21069
+ const ts = Date.parse(rec.timestamp);
21070
+ if (!Number.isNaN(ts) && now2 - ts > _internals29.limits.ageMaxMs) {
21071
+ agePruned.push(rec);
21072
+ } else {
21073
+ kept.push(rec);
21074
+ }
21075
+ }
21076
+ const retained = [];
21077
+ let bytes = 0;
21078
+ for (let i = kept.length - 1;i >= 0; i -= 1) {
21079
+ const rec = kept[i];
21080
+ const lb = Buffer.byteLength(JSON.stringify(rec)) + 1;
21081
+ if (retained.length >= _internals29.limits.activeMaxEntries || bytes + lb > _internals29.limits.activeMaxBytes) {
21082
+ break;
21083
+ }
21084
+ retained.push(rec);
21085
+ bytes += lb;
21086
+ }
21087
+ retained.reverse();
21088
+ const retainedSet = new Set(retained);
21089
+ const keptSet = new Set(kept);
21090
+ const budgetPruned = [];
21091
+ for (const rec of view.records) {
21092
+ if (keptSet.has(rec) && !retainedSet.has(rec))
21093
+ budgetPruned.push(rec);
21094
+ }
21095
+ const candidates = [...agePruned, ...budgetPruned];
21096
+ const toFold = new Set;
21097
+ let foldedBytes = 0;
21098
+ for (const cand of candidates) {
21099
+ const cb = Buffer.byteLength(JSON.stringify(cand)) + 1;
21100
+ if (foldedBytes + cb > _internals29.limits.compactMaxBytes && toFold.size > 0) {
21101
+ break;
21102
+ }
21103
+ toFold.add(cand);
21104
+ foldedBytes += cb;
21105
+ }
21106
+ const finalRetained = [];
21107
+ const agePrunedSet = new Set(agePruned);
21108
+ let dropped = 0;
21109
+ for (const rec of view.records) {
21110
+ if (toFold.has(rec)) {
21111
+ foldEntryInto(folded, rec);
21112
+ if (agePrunedSet.has(rec))
21113
+ dropped += 1;
21114
+ } else {
21115
+ finalRetained.push(rec);
21116
+ }
21117
+ }
21118
+ if (dropped > 0)
21119
+ folded.dropped += dropped;
21120
+ folded.corrupt += view.corruptLines;
21121
+ const manifest = {
21122
+ ...emptyManifest(),
21123
+ folded,
21124
+ updatedAt: new Date().toISOString()
21125
+ };
21126
+ const lines = [`${JSON.stringify(manifest)}`];
21127
+ for (const rec of finalRetained)
21128
+ lines.push(JSON.stringify(rec));
21129
+ atomicReplace(directory, lines.length > 1 ? `${lines.join(`
21130
+ `)}
21131
+ ` : `${lines[0]}
21132
+ `);
21133
+ emitHealth(directory, {
21134
+ trigger,
21135
+ accepted: folded.delegations + finalRetained.length,
21136
+ compacted: toFold.size - dropped,
21137
+ retained: finalRetained.length,
21138
+ dropped,
21139
+ corrupt: folded.corrupt,
21140
+ oldest: folded.oldestTimestamp,
21141
+ newest: folded.newestTimestamp,
21142
+ bytes: fileSizeOrZero(filePath),
21143
+ limitBytes: _internals29.limits.activeMaxBytes
21144
+ });
21145
+ };
21146
+ if (alreadyLocked) {
21147
+ run();
21148
+ return;
21149
+ }
21150
+ withStoreLock(directory, run);
21151
+ }
21152
+ function finalizeContextTelemetry(directory) {
21153
+ try {
21154
+ const filePath = telemetryFilePath(directory);
21155
+ if (!_internals29.existsSync(filePath))
21156
+ return;
21157
+ withStoreLock(directory, () => {
21158
+ let prev = Number.POSITIVE_INFINITY;
21159
+ for (let pass = 0;pass < 1e4; pass += 1) {
21160
+ const view = readStore(directory, false);
21161
+ if (view.manifest !== null)
21162
+ break;
21163
+ if (view.records.length === 0)
21164
+ break;
21165
+ if (view.records.length >= prev)
21166
+ break;
21167
+ prev = view.records.length;
21168
+ migrateCutover(directory, "close", true);
21169
+ }
21170
+ compactStore(directory, "close", true);
21171
+ });
21172
+ } catch {
21173
+ warnThrottled("finalize failed");
21174
+ }
21175
+ }
21176
+ function emitContextTelemetryHealth(_directory, payload) {
21177
+ try {
21178
+ telemetry.contextTelemetryHealth({
21179
+ trigger: payload.trigger,
21180
+ accepted_count: payload.accepted,
21181
+ compacted_count: payload.compacted,
21182
+ retained_count: payload.retained,
21183
+ dropped_count: payload.dropped,
21184
+ corrupt_count: payload.corrupt,
21185
+ oldest_timestamp: payload.oldest,
21186
+ newest_timestamp: payload.newest,
21187
+ bytes: payload.bytes,
21188
+ limit_bytes: payload.limitBytes
21189
+ });
21190
+ } catch {}
21191
+ }
21192
+ function emitHealth(directory, payload) {
21193
+ _internals29.emitHealth(directory, payload);
21194
+ }
21195
+
20515
21196
  // src/memory/finalize-reward-sweep.ts
20516
21197
  init_logger();
20517
21198
 
@@ -20745,11 +21426,11 @@ class MemoryValidationError extends Error {
20745
21426
 
20746
21427
  // src/memory/schema.ts
20747
21428
  init_zod();
20748
- import { createHash as createHash9 } from "crypto";
21429
+ import { createHash as createHash10 } from "crypto";
20749
21430
 
20750
21431
  // src/memory/pii.ts
20751
21432
  import * as os3 from "os";
20752
- import * as path28 from "path";
21433
+ import * as path29 from "path";
20753
21434
  function computePiiScore(findings) {
20754
21435
  return findings.reduce((max, f) => Math.max(max, f.confidence), 0);
20755
21436
  }
@@ -20760,10 +21441,10 @@ function summarizePiiFindings(findings) {
20760
21441
  }
20761
21442
  return { score: computePiiScore(findings), countsByType };
20762
21443
  }
20763
- var NER_MODEL_CACHE_DIR = path28.join(os3.homedir(), ".cache", "opencode-swarm", "models");
21444
+ var NER_MODEL_CACHE_DIR = path29.join(os3.homedir(), ".cache", "opencode-swarm", "models");
20764
21445
 
20765
21446
  // src/memory/redaction.ts
20766
- import { createHash as createHash8 } from "crypto";
21447
+ import { createHash as createHash9 } from "crypto";
20767
21448
  var SECRET_PATTERNS = [
20768
21449
  { type: "openai_api_key", pattern: /\bsk-[A-Za-z0-9_-]{20,}\b/g },
20769
21450
  {
@@ -20813,10 +21494,10 @@ function computeRedactionPolicyVersion(policy) {
20813
21494
  }
20814
21495
  var FINGERPRINT_ALGORITHM_VERSION = 2;
20815
21496
  var LEGACY_FINGERPRINT_ALGORITHM_VERSION = 1;
20816
- var _internals29 = {
21497
+ var _internals30 = {
20817
21498
  currentAlgorithmVersion: FINGERPRINT_ALGORITHM_VERSION
20818
21499
  };
20819
- function classifyStoredFingerprintAlgorithmVersion(rawStoredVersion, currentVersion = _internals29.currentAlgorithmVersion) {
21500
+ function classifyStoredFingerprintAlgorithmVersion(rawStoredVersion, currentVersion = _internals30.currentAlgorithmVersion) {
20820
21501
  const storedVersion = rawStoredVersion === undefined ? LEGACY_FINGERPRINT_ALGORITHM_VERSION : rawStoredVersion;
20821
21502
  if (typeof storedVersion !== "number" || !Number.isFinite(storedVersion)) {
20822
21503
  return { status: "unknown" };
@@ -20825,7 +21506,7 @@ function classifyStoredFingerprintAlgorithmVersion(rawStoredVersion, currentVers
20825
21506
  }
20826
21507
  function computeMemoryCohortFingerprint(input) {
20827
21508
  const canonical = stableCanonicalStringify(input);
20828
- return createHash8("sha256").update(canonical).digest("hex").slice(0, 12);
21509
+ return createHash9("sha256").update(canonical).digest("hex").slice(0, 12);
20829
21510
  }
20830
21511
  function buildMemoryCohortFingerprintInput(config) {
20831
21512
  return {
@@ -21123,7 +21804,7 @@ function stableScopeKey(scope) {
21123
21804
  }
21124
21805
  function computeMemoryContentHash(recordLike) {
21125
21806
  const normalized = normalizeMemoryText(recordLike.text).toLowerCase();
21126
- return createHash9("sha256").update(`${stableScopeKey(recordLike.scope)}
21807
+ return createHash10("sha256").update(`${stableScopeKey(recordLike.scope)}
21127
21808
  ${recordLike.kind}
21128
21809
  ${normalized}`).digest("hex");
21129
21810
  }
@@ -21278,7 +21959,7 @@ function normalizeTags(tags) {
21278
21959
  // src/memory/local-jsonl-provider.ts
21279
21960
  var import_proper_lockfile6 = __toESM(require_proper_lockfile(), 1);
21280
21961
  import { randomUUID as randomUUID6 } from "crypto";
21281
- import { existsSync as existsSync15, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "fs";
21962
+ import { existsSync as existsSync16, readFileSync as readFileSync13, writeFileSync as writeFileSync7 } from "fs";
21282
21963
  import {
21283
21964
  appendFile as appendFile8,
21284
21965
  mkdir as mkdir11,
@@ -21287,7 +21968,7 @@ import {
21287
21968
  truncate,
21288
21969
  writeFile as writeFile7
21289
21970
  } from "fs/promises";
21290
- import * as path29 from "path";
21971
+ import * as path30 from "path";
21291
21972
 
21292
21973
  // src/memory/q-learning.ts
21293
21974
  function clamp01(value) {
@@ -21865,7 +22546,7 @@ function proposalSort(a, b) {
21865
22546
  }
21866
22547
 
21867
22548
  // src/memory/outcome-events.ts
21868
- import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
22549
+ import { createHash as createHash11, randomUUID as randomUUID5 } from "crypto";
21869
22550
  function newOutcomeGeneration() {
21870
22551
  return randomUUID5();
21871
22552
  }
@@ -21998,7 +22679,7 @@ function dedupeAnchors(anchors) {
21998
22679
  return [...byKey.values()].sort((a, b) => compareText(a.file, b.file) || compareText(a.symbol ?? "", b.symbol ?? ""));
21999
22680
  }
22000
22681
  function hash(value) {
22001
- return createHash10("sha256").update(value).digest("hex").slice(0, 32);
22682
+ return createHash11("sha256").update(value).digest("hex").slice(0, 32);
22002
22683
  }
22003
22684
  function compareText(a, b) {
22004
22685
  return a < b ? -1 : a > b ? 1 : 0;
@@ -22023,10 +22704,10 @@ class LocalJsonlMemoryProvider {
22023
22704
  pathFor(file) {
22024
22705
  const filename = file === "memories" ? "memories.jsonl" : file === "proposals" ? "proposals.jsonl" : file === "audit" ? "audit.jsonl" : file === "reward-events" ? "reward-events.jsonl" : "outcome-events.jsonl";
22025
22706
  if (this.cohortRoot) {
22026
- return path29.join(this.cohortRoot, filename);
22707
+ return path30.join(this.cohortRoot, filename);
22027
22708
  }
22028
22709
  const storageDir = this.config.storageDir.replace(/^\.swarm[/\\]?/, "");
22029
- return validateSwarmPath(this.rootDirectory, path29.join(storageDir, filename));
22710
+ return validateSwarmPath(this.rootDirectory, path30.join(storageDir, filename));
22030
22711
  }
22031
22712
  async initialize() {
22032
22713
  if (this.initialized)
@@ -22448,7 +23129,7 @@ class LocalJsonlMemoryProvider {
22448
23129
  await appendJsonl(this.pathFor("audit"), event);
22449
23130
  }
22450
23131
  async withOutcomeStoreLock(fn) {
22451
- const storageDirectory = path29.dirname(this.pathFor("memories"));
23132
+ const storageDirectory = path30.dirname(this.pathFor("memories"));
22452
23133
  await mkdir11(storageDirectory, { recursive: true });
22453
23134
  const release = await lockfile6.lock(storageDirectory, {
22454
23135
  realpath: false,
@@ -22478,9 +23159,9 @@ class LocalJsonlMemoryProvider {
22478
23159
  }
22479
23160
  readOutcomeEventsSync() {
22480
23161
  const filePath = this.pathFor("outcome-events");
22481
- if (!existsSync15(filePath))
23162
+ if (!existsSync16(filePath))
22482
23163
  return [];
22483
- const content = readFileSync12(filePath, "utf-8");
23164
+ const content = readFileSync13(filePath, "utf-8");
22484
23165
  const completeContent = content.endsWith(`
22485
23166
  `) ? content : content.slice(0, Math.max(0, content.lastIndexOf(`
22486
23167
  `) + 1));
@@ -22526,18 +23207,18 @@ class LocalJsonlMemoryProvider {
22526
23207
  if (!this.cohortRoot)
22527
23208
  return;
22528
23209
  try {
22529
- const markerPath = path29.join(this.cohortRoot, "memory.gen");
22530
- writeFileSync6(markerPath, String(Date.now()), "utf-8");
23210
+ const markerPath = path30.join(this.cohortRoot, "memory.gen");
23211
+ writeFileSync7(markerPath, String(Date.now()), "utf-8");
22531
23212
  } catch {}
22532
23213
  }
22533
23214
  assertCohortConfigFingerprint() {
22534
23215
  if (!this.cohortRoot)
22535
23216
  return;
22536
- const configPath = path29.join(this.cohortRoot, "memory-cohort-config.json");
22537
- if (!existsSync15(configPath))
23217
+ const configPath = path30.join(this.cohortRoot, "memory-cohort-config.json");
23218
+ if (!existsSync16(configPath))
22538
23219
  return;
22539
23220
  try {
22540
- const stored = JSON.parse(readFileSync12(configPath, "utf-8"));
23221
+ const stored = JSON.parse(readFileSync13(configPath, "utf-8"));
22541
23222
  const versionCheck = classifyStoredFingerprintAlgorithmVersion(stored.algorithm_version);
22542
23223
  if (versionCheck.status === "unknown") {
22543
23224
  warn("[memory-cohort] cohort config has a present but non-numeric `algorithm_version`, so its fingerprint cannot be attributed to a known algorithm and the config-coherence check was skipped. Run `/swarm memory link` to rewrite the cohort fingerprint.", {
@@ -22650,7 +23331,7 @@ function validateLoadedProposals(values, config) {
22650
23331
  return { records, invalidCount };
22651
23332
  }
22652
23333
  async function readJsonl(filePath) {
22653
- if (!existsSync15(filePath))
23334
+ if (!existsSync16(filePath))
22654
23335
  return [];
22655
23336
  const content = await readFile12(filePath, "utf-8");
22656
23337
  const records = [];
@@ -22727,12 +23408,12 @@ function parseRewardEvent(value) {
22727
23408
  };
22728
23409
  }
22729
23410
  async function appendJsonl(filePath, value) {
22730
- await mkdir11(path29.dirname(filePath), { recursive: true });
23411
+ await mkdir11(path30.dirname(filePath), { recursive: true });
22731
23412
  await appendFile8(filePath, `${JSON.stringify(value)}
22732
23413
  `, "utf-8");
22733
23414
  }
22734
23415
  async function writeJsonlAtomic(filePath, values) {
22735
- await mkdir11(path29.dirname(filePath), { recursive: true });
23416
+ await mkdir11(path30.dirname(filePath), { recursive: true });
22736
23417
  const tmp = `${filePath}.tmp.${randomUUID6()}`;
22737
23418
  const content = values.map((value) => JSON.stringify(value)).join(`
22738
23419
  `) + (values.length > 0 ? `
@@ -22741,7 +23422,7 @@ async function writeJsonlAtomic(filePath, values) {
22741
23422
  await rename5(tmp, filePath);
22742
23423
  }
22743
23424
  async function repairIncompleteJsonlTail(filePath) {
22744
- if (!existsSync15(filePath))
23425
+ if (!existsSync16(filePath))
22745
23426
  return;
22746
23427
  const content = await readFile12(filePath, "utf-8");
22747
23428
  if (content.length === 0 || content.endsWith(`
@@ -22754,19 +23435,19 @@ async function repairIncompleteJsonlTail(filePath) {
22754
23435
 
22755
23436
  // src/memory/provider-pool.ts
22756
23437
  import { realpathSync as realpathSync3 } from "fs";
22757
- import * as path34 from "path";
23438
+ import * as path35 from "path";
22758
23439
 
22759
23440
  // src/memory/sqlite-provider.ts
22760
- import { createHash as createHash11, randomUUID as randomUUID7 } from "crypto";
23441
+ import { createHash as createHash12, randomUUID as randomUUID7 } from "crypto";
22761
23442
  import {
22762
- existsSync as existsSync17,
22763
- mkdirSync as mkdirSync9,
22764
- readFileSync as readFileSync13,
22765
- statSync as statSync7,
22766
- writeFileSync as writeFileSync7
23443
+ existsSync as existsSync18,
23444
+ mkdirSync as mkdirSync10,
23445
+ readFileSync as readFileSync14,
23446
+ statSync as statSync8,
23447
+ writeFileSync as writeFileSync8
22767
23448
  } from "fs";
22768
23449
  import { createRequire as createRequire3 } from "module";
22769
- import * as path33 from "path";
23450
+ import * as path34 from "path";
22770
23451
 
22771
23452
  // src/memory/embeddings/cache.ts
22772
23453
  var DEFAULT_CACHE_SIZE = 256;
@@ -22882,10 +23563,10 @@ function minMaxNormalise(candidates) {
22882
23563
  }
22883
23564
 
22884
23565
  // src/memory/embeddings/local-provider.ts
22885
- import { mkdirSync as mkdirSync7 } from "fs";
23566
+ import { mkdirSync as mkdirSync8 } from "fs";
22886
23567
  import { createRequire } from "module";
22887
23568
  import * as os4 from "os";
22888
- import * as path30 from "path";
23569
+ import * as path31 from "path";
22889
23570
 
22890
23571
  // src/memory/embeddings/types.ts
22891
23572
  class EmbeddingUnavailableError extends Error {
@@ -22907,20 +23588,20 @@ class EmbeddingVersionMismatchError extends Error {
22907
23588
  }
22908
23589
 
22909
23590
  // src/memory/embeddings/local-provider.ts
22910
- var _internals30 = {
23591
+ var _internals31 = {
22911
23592
  resolveEmbeddingCacheDir() {
22912
23593
  let base;
22913
23594
  if (process.platform === "win32") {
22914
- base = process.env.LOCALAPPDATA || path30.join(os4.homedir(), "AppData", "Local");
23595
+ base = process.env.LOCALAPPDATA || path31.join(os4.homedir(), "AppData", "Local");
22915
23596
  } else if (process.platform === "darwin") {
22916
- base = path30.join(os4.homedir(), "Library", "Caches");
23597
+ base = path31.join(os4.homedir(), "Library", "Caches");
22917
23598
  } else {
22918
- base = process.env.XDG_CACHE_HOME || path30.join(os4.homedir(), ".cache");
23599
+ base = process.env.XDG_CACHE_HOME || path31.join(os4.homedir(), ".cache");
22919
23600
  }
22920
- const resolved = path30.join(base, "opencode", "embeddings");
22921
- const segments = resolved.split(path30.sep);
23601
+ const resolved = path31.join(base, "opencode", "embeddings");
23602
+ const segments = resolved.split(path31.sep);
22922
23603
  if (segments.includes(".swarm")) {
22923
- const safeDefault = process.platform === "win32" ? path30.join(os4.homedir(), "AppData", "Local", "opencode", "embeddings") : process.platform === "darwin" ? path30.join(os4.homedir(), "Library", "Caches", "opencode", "embeddings") : path30.join(os4.homedir(), ".cache", "opencode", "embeddings");
23604
+ const safeDefault = process.platform === "win32" ? path31.join(os4.homedir(), "AppData", "Local", "opencode", "embeddings") : process.platform === "darwin" ? path31.join(os4.homedir(), "Library", "Caches", "opencode", "embeddings") : path31.join(os4.homedir(), ".cache", "opencode", "embeddings");
22924
23605
  warn("Embedding cache dir resolved under .swarm/ \u2014 falling back to safe default");
22925
23606
  return safeDefault;
22926
23607
  }
@@ -22928,7 +23609,7 @@ var _internals30 = {
22928
23609
  }
22929
23610
  };
22930
23611
  function resolveEmbeddingCacheDir() {
22931
- return _internals30.resolveEmbeddingCacheDir();
23612
+ return _internals31.resolveEmbeddingCacheDir();
22932
23613
  }
22933
23614
 
22934
23615
  class LocalEmbeddingProvider {
@@ -22961,7 +23642,7 @@ class LocalEmbeddingProvider {
22961
23642
  console.log(`[opencode-swarm] Downloading embedding model "${this.modelName}" (~25 MB) \u2014 this happens once per process.`);
22962
23643
  }
22963
23644
  const cacheDir = resolveEmbeddingCacheDir();
22964
- mkdirSync7(cacheDir, { recursive: true });
23645
+ mkdirSync8(cacheDir, { recursive: true });
22965
23646
  this.pipeline = await transformers.pipeline("feature-extraction", this.modelName, { cache_dir: cacheDir });
22966
23647
  this._available = true;
22967
23648
  return this.pipeline;
@@ -23035,10 +23716,10 @@ class LocalEmbeddingProvider {
23035
23716
  }
23036
23717
 
23037
23718
  // src/memory/embeddings/reranker.ts
23038
- import { mkdirSync as mkdirSync8 } from "fs";
23719
+ import { mkdirSync as mkdirSync9 } from "fs";
23039
23720
  import { createRequire as createRequire2 } from "module";
23040
23721
  import * as os5 from "os";
23041
- import * as path31 from "path";
23722
+ import * as path32 from "path";
23042
23723
  function shouldRerank(previousRecallElapsedMs, latencyBudgetMs) {
23043
23724
  return previousRecallElapsedMs <= latencyBudgetMs;
23044
23725
  }
@@ -23064,7 +23745,7 @@ class CrossEncoderReranker {
23064
23745
  const transformers = req("@xenova/transformers");
23065
23746
  const modelName = this.options.model ?? "Xenova/ms-marco-MiniLM-L-6-v2";
23066
23747
  const cacheDir = resolveRerankerCacheDir();
23067
- mkdirSync8(cacheDir, { recursive: true });
23748
+ mkdirSync9(cacheDir, { recursive: true });
23068
23749
  this.pipeline = await transformers.pipeline("text-classification", modelName, { cache_dir: cacheDir });
23069
23750
  this._available = true;
23070
23751
  return this.pipeline;
@@ -23106,16 +23787,16 @@ class CrossEncoderReranker {
23106
23787
  function resolveRerankerCacheDir() {
23107
23788
  let base;
23108
23789
  if (process.platform === "win32") {
23109
- base = process.env.LOCALAPPDATA || path31.join(os5.homedir(), "AppData", "Local");
23790
+ base = process.env.LOCALAPPDATA || path32.join(os5.homedir(), "AppData", "Local");
23110
23791
  } else if (process.platform === "darwin") {
23111
- base = path31.join(os5.homedir(), "Library", "Caches");
23792
+ base = path32.join(os5.homedir(), "Library", "Caches");
23112
23793
  } else {
23113
- base = process.env.XDG_CACHE_HOME || path31.join(os5.homedir(), ".cache");
23794
+ base = process.env.XDG_CACHE_HOME || path32.join(os5.homedir(), ".cache");
23114
23795
  }
23115
- const resolved = path31.join(base, "opencode", "embeddings");
23116
- const segments = resolved.split(path31.sep);
23796
+ const resolved = path32.join(base, "opencode", "embeddings");
23797
+ const segments = resolved.split(path32.sep);
23117
23798
  if (segments.includes(".swarm")) {
23118
- const safeDefault = process.platform === "win32" ? path31.join(os5.homedir(), "AppData", "Local", "opencode", "embeddings") : process.platform === "darwin" ? path31.join(os5.homedir(), "Library", "Caches", "opencode", "embeddings") : path31.join(os5.homedir(), ".cache", "opencode", "embeddings");
23799
+ const safeDefault = process.platform === "win32" ? path32.join(os5.homedir(), "AppData", "Local", "opencode", "embeddings") : process.platform === "darwin" ? path32.join(os5.homedir(), "Library", "Caches", "opencode", "embeddings") : path32.join(os5.homedir(), ".cache", "opencode", "embeddings");
23119
23800
  warn("Reranker cache dir resolved under .swarm/ \u2014 falling back to safe default");
23120
23801
  return safeDefault;
23121
23802
  }
@@ -23123,9 +23804,9 @@ function resolveRerankerCacheDir() {
23123
23804
  }
23124
23805
 
23125
23806
  // src/memory/jsonl-migration.ts
23126
- import { existsSync as existsSync16, renameSync as renameSync5, unlinkSync as unlinkSync3 } from "fs";
23807
+ import { existsSync as existsSync17, renameSync as renameSync6, unlinkSync as unlinkSync4 } from "fs";
23127
23808
  import { copyFile, mkdir as mkdir12, readFile as readFile13, stat as stat4, writeFile as writeFile8 } from "fs/promises";
23128
- import * as path32 from "path";
23809
+ import * as path33 from "path";
23129
23810
  var LEGACY_JSONL_MIGRATION_VERSION = 2;
23130
23811
  var LEGACY_JSONL_MIGRATION_NAME = "legacy_jsonl_import_complete";
23131
23812
  var LEGACY_JSONL_OUTCOME_META_KEY = "legacy_jsonl_outcomes_import_complete";
@@ -23142,9 +23823,9 @@ function resolveSqliteDatabasePath(rootDirectory, config = {}) {
23142
23823
  async function readLegacyJsonl(rootDirectory, config = {}) {
23143
23824
  const resolved = resolveConfig(config);
23144
23825
  const storageDir = resolveMemoryStorageDir(rootDirectory, resolved);
23145
- const memoryLoad = await readMemoryJsonl(path32.join(storageDir, "memories.jsonl"), resolved);
23146
- const proposalLoad = await readProposalJsonl(path32.join(storageDir, "proposals.jsonl"), resolved);
23147
- const outcomeLoad = await readOutcomeJsonl(path32.join(storageDir, "outcome-events.jsonl"));
23826
+ const memoryLoad = await readMemoryJsonl(path33.join(storageDir, "memories.jsonl"), resolved);
23827
+ const proposalLoad = await readProposalJsonl(path33.join(storageDir, "proposals.jsonl"), resolved);
23828
+ const outcomeLoad = await readOutcomeJsonl(path33.join(storageDir, "outcome-events.jsonl"));
23148
23829
  return {
23149
23830
  memories: memoryLoad.records,
23150
23831
  memoryRows: memoryLoad.rows,
@@ -23161,7 +23842,7 @@ async function readLegacyJsonl(rootDirectory, config = {}) {
23161
23842
  }
23162
23843
  async function backupLegacyJsonl(rootDirectory, config = {}) {
23163
23844
  const storageDir = resolveMemoryStorageDir(rootDirectory, config);
23164
- const backupDir = path32.join(storageDir, "backups");
23845
+ const backupDir = path33.join(storageDir, "backups");
23165
23846
  await mkdir12(backupDir, { recursive: true });
23166
23847
  const results = [];
23167
23848
  for (const filename of [
@@ -23169,11 +23850,11 @@ async function backupLegacyJsonl(rootDirectory, config = {}) {
23169
23850
  "proposals.jsonl",
23170
23851
  "outcome-events.jsonl"
23171
23852
  ]) {
23172
- const source = path32.join(storageDir, filename);
23173
- if (!existsSync16(source))
23853
+ const source = path33.join(storageDir, filename);
23854
+ if (!existsSync17(source))
23174
23855
  continue;
23175
- const backup = path32.join(backupDir, `${filename}.pre-sqlite-migration`);
23176
- if (existsSync16(backup)) {
23856
+ const backup = path33.join(backupDir, `${filename}.pre-sqlite-migration`);
23857
+ if (existsSync17(backup)) {
23177
23858
  results.push({ source, backup, created: false });
23178
23859
  continue;
23179
23860
  }
@@ -23183,62 +23864,62 @@ async function backupLegacyJsonl(rootDirectory, config = {}) {
23183
23864
  return results;
23184
23865
  }
23185
23866
  async function writeJsonlExport(rootDirectory, config, memories, proposals, outcomeEvents = []) {
23186
- const exportDir = path32.join(resolveMemoryStorageDir(rootDirectory, config), "export");
23867
+ const exportDir = path33.join(resolveMemoryStorageDir(rootDirectory, config), "export");
23187
23868
  await mkdir12(exportDir, { recursive: true });
23188
- const memoriesPath = path32.join(exportDir, "memories.jsonl");
23189
- const proposalsPath = path32.join(exportDir, "proposals.jsonl");
23190
- const outcomesPath = path32.join(exportDir, "outcome-events.jsonl");
23191
- const memoriesTempPath = path32.join(path32.dirname(memoriesPath), `${path32.basename(memoriesPath)}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`);
23869
+ const memoriesPath = path33.join(exportDir, "memories.jsonl");
23870
+ const proposalsPath = path33.join(exportDir, "proposals.jsonl");
23871
+ const outcomesPath = path33.join(exportDir, "outcome-events.jsonl");
23872
+ const memoriesTempPath = path33.join(path33.dirname(memoriesPath), `${path33.basename(memoriesPath)}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`);
23192
23873
  try {
23193
23874
  await writeFile8(memoriesTempPath, toJsonl(memories), "utf-8");
23194
- renameSync5(memoriesTempPath, memoriesPath);
23875
+ renameSync6(memoriesTempPath, memoriesPath);
23195
23876
  } catch (err) {
23196
23877
  try {
23197
- unlinkSync3(memoriesTempPath);
23878
+ unlinkSync4(memoriesTempPath);
23198
23879
  } catch {}
23199
23880
  throw err;
23200
23881
  }
23201
- const proposalsTempPath = path32.join(path32.dirname(proposalsPath), `${path32.basename(proposalsPath)}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`);
23882
+ const proposalsTempPath = path33.join(path33.dirname(proposalsPath), `${path33.basename(proposalsPath)}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`);
23202
23883
  try {
23203
23884
  await writeFile8(proposalsTempPath, toJsonl(proposals), "utf-8");
23204
- renameSync5(proposalsTempPath, proposalsPath);
23885
+ renameSync6(proposalsTempPath, proposalsPath);
23205
23886
  } catch (err) {
23206
23887
  try {
23207
- unlinkSync3(proposalsTempPath);
23888
+ unlinkSync4(proposalsTempPath);
23208
23889
  } catch {}
23209
23890
  throw err;
23210
23891
  }
23211
- const outcomesTempPath = path32.join(path32.dirname(outcomesPath), `${path32.basename(outcomesPath)}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`);
23892
+ const outcomesTempPath = path33.join(path33.dirname(outcomesPath), `${path33.basename(outcomesPath)}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`);
23212
23893
  try {
23213
23894
  await writeFile8(outcomesTempPath, toJsonl(outcomeEvents), "utf-8");
23214
- renameSync5(outcomesTempPath, outcomesPath);
23895
+ renameSync6(outcomesTempPath, outcomesPath);
23215
23896
  } catch (err) {
23216
23897
  try {
23217
- unlinkSync3(outcomesTempPath);
23898
+ unlinkSync4(outcomesTempPath);
23218
23899
  } catch {}
23219
23900
  throw err;
23220
23901
  }
23221
23902
  return { directory: exportDir, memoriesPath, proposalsPath, outcomesPath };
23222
23903
  }
23223
23904
  async function writeMigrationReport(rootDirectory, report, config = {}) {
23224
- const reportPath = path32.join(resolveMemoryStorageDir(rootDirectory, config), "migration-report.json");
23225
- await mkdir12(path32.dirname(reportPath), { recursive: true });
23226
- const reportTempPath = path32.join(path32.dirname(reportPath), `${path32.basename(reportPath)}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`);
23905
+ const reportPath = path33.join(resolveMemoryStorageDir(rootDirectory, config), "migration-report.json");
23906
+ await mkdir12(path33.dirname(reportPath), { recursive: true });
23907
+ const reportTempPath = path33.join(path33.dirname(reportPath), `${path33.basename(reportPath)}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`);
23227
23908
  try {
23228
23909
  await writeFile8(reportTempPath, `${JSON.stringify(report, null, 2)}
23229
23910
  `, "utf-8");
23230
- renameSync5(reportTempPath, reportPath);
23911
+ renameSync6(reportTempPath, reportPath);
23231
23912
  } catch (err) {
23232
23913
  try {
23233
- unlinkSync3(reportTempPath);
23914
+ unlinkSync4(reportTempPath);
23234
23915
  } catch {}
23235
23916
  throw err;
23236
23917
  }
23237
23918
  return reportPath;
23238
23919
  }
23239
23920
  async function readMigrationReport(rootDirectory, config = {}) {
23240
- const reportPath = path32.join(resolveMemoryStorageDir(rootDirectory, config), "migration-report.json");
23241
- if (!existsSync16(reportPath))
23921
+ const reportPath = path33.join(resolveMemoryStorageDir(rootDirectory, config), "migration-report.json");
23922
+ if (!existsSync17(reportPath))
23242
23923
  return null;
23243
23924
  try {
23244
23925
  return JSON.parse(await readFile13(reportPath, "utf-8"));
@@ -23254,23 +23935,23 @@ async function getLegacyJsonlFileStatus(rootDirectory, config = {}) {
23254
23935
  "proposals.jsonl",
23255
23936
  "outcome-events.jsonl"
23256
23937
  ]) {
23257
- const filePath = path32.join(storageDir, file);
23938
+ const filePath = path33.join(storageDir, file);
23258
23939
  let sizeBytes = 0;
23259
- if (existsSync16(filePath)) {
23940
+ if (existsSync17(filePath)) {
23260
23941
  sizeBytes = (await stat4(filePath)).size;
23261
23942
  }
23262
23943
  statuses.push({
23263
23944
  file,
23264
23945
  path: filePath,
23265
- exists: existsSync16(filePath),
23946
+ exists: existsSync17(filePath),
23266
23947
  sizeBytes
23267
23948
  });
23268
23949
  }
23269
23950
  return statuses;
23270
23951
  }
23271
23952
  async function getLegacyOutcomeJsonlSignature(rootDirectory, config = {}) {
23272
- const filePath = path32.join(resolveMemoryStorageDir(rootDirectory, config), "outcome-events.jsonl");
23273
- if (!existsSync16(filePath))
23953
+ const filePath = path33.join(resolveMemoryStorageDir(rootDirectory, config), "outcome-events.jsonl");
23954
+ if (!existsSync17(filePath))
23274
23955
  return "missing";
23275
23956
  const details = await stat4(filePath);
23276
23957
  return `${details.size}:${details.mtimeMs}`;
@@ -23392,7 +24073,7 @@ async function readOutcomeJsonl(filePath) {
23392
24073
  return { records, rows: validRows, invalidRows, totalRows: rows.totalRows };
23393
24074
  }
23394
24075
  async function readJsonlRows(filePath) {
23395
- if (!existsSync16(filePath)) {
24076
+ if (!existsSync17(filePath)) {
23396
24077
  return { rows: [], invalidRows: [], totalRows: 0 };
23397
24078
  }
23398
24079
  const content = await readFile13(filePath, "utf-8");
@@ -23426,7 +24107,7 @@ function toJsonl(values) {
23426
24107
  var EVENT_CHAIN_GENESIS = "GENESIS";
23427
24108
  var MEMORY_EVENTS_CHAIN_HEAD_KEY = "memory_events_chain_head";
23428
24109
  function memoryEventRowHash(row) {
23429
- return createHash11("sha256").update(stableCanonicalStringify({
24110
+ return createHash12("sha256").update(stableCanonicalStringify({
23430
24111
  id: row.id,
23431
24112
  operation: row.operation,
23432
24113
  target_id: row.target_id,
@@ -23771,7 +24452,7 @@ class SQLiteMemoryProvider {
23771
24452
  }
23772
24453
  databasePath() {
23773
24454
  if (this.cohortRoot) {
23774
- return path33.join(this.cohortRoot, "memory.db");
24455
+ return path34.join(this.cohortRoot, "memory.db");
23775
24456
  }
23776
24457
  const relativePath2 = this.config.sqlite.path.replace(/^\.swarm[/\\]?/, "");
23777
24458
  return validateSwarmPath(this.rootDirectory, relativePath2);
@@ -23792,7 +24473,7 @@ class SQLiteMemoryProvider {
23792
24473
  if (this.cohortRoot) {
23793
24474
  this.assertCohortConfigFingerprint();
23794
24475
  }
23795
- mkdirSync9(path33.dirname(dbPath), { recursive: true });
24476
+ mkdirSync10(path34.dirname(dbPath), { recursive: true });
23796
24477
  const Db = loadDatabaseCtor();
23797
24478
  this.db = new Db(dbPath);
23798
24479
  try {
@@ -24446,13 +25127,13 @@ class SQLiteMemoryProvider {
24446
25127
  }
24447
25128
  try {
24448
25129
  const wal = `${dbPath}-wal`;
24449
- const st = statSync7(wal);
25130
+ const st = statSync8(wal);
24450
25131
  if (st.size > 0)
24451
25132
  walPath2 = wal;
24452
25133
  } catch {}
24453
25134
  try {
24454
25135
  const shm = `${dbPath}-shm`;
24455
- const st = statSync7(shm);
25136
+ const st = statSync8(shm);
24456
25137
  if (st.size > 0)
24457
25138
  shmPath = shm;
24458
25139
  } catch {}
@@ -24864,9 +25545,9 @@ class SQLiteMemoryProvider {
24864
25545
  try {
24865
25546
  const dimension = Math.max(1, Math.trunc(this.config.embeddings.dimension ?? 384));
24866
25547
  const req = createRequire3(import.meta.url);
24867
- const pkgDir = path33.dirname(req.resolve("@sqlite/sqlite-vec/package.json"));
25548
+ const pkgDir = path34.dirname(req.resolve("@sqlite/sqlite-vec/package.json"));
24868
25549
  const ext = process.platform === "win32" ? ".dll" : process.platform === "darwin" ? ".dylib" : ".so";
24869
- const vec0Path = path33.join(pkgDir, `vec0${ext}`);
25550
+ const vec0Path = path34.join(pkgDir, `vec0${ext}`);
24870
25551
  db.loadExtension(vec0Path);
24871
25552
  db.run(`CREATE VIRTUAL TABLE IF NOT EXISTS memory_items_vec USING vec0(
24872
25553
  id TEXT PRIMARY KEY, embedding FLOAT[${dimension}]
@@ -25075,20 +25756,20 @@ class SQLiteMemoryProvider {
25075
25756
  if (!this.cohortRoot)
25076
25757
  return;
25077
25758
  try {
25078
- const markerPath = path33.join(this.cohortRoot, "memory.gen");
25079
- writeFileSync7(markerPath, String(Date.now()), "utf-8");
25759
+ const markerPath = path34.join(this.cohortRoot, "memory.gen");
25760
+ writeFileSync8(markerPath, String(Date.now()), "utf-8");
25080
25761
  } catch {}
25081
25762
  }
25082
25763
  assertCohortConfigFingerprint() {
25083
25764
  if (!this.cohortRoot)
25084
25765
  return;
25085
- const configPath = path33.join(this.cohortRoot, "memory-cohort-config.json");
25086
- if (!existsSync17(configPath)) {
25766
+ const configPath = path34.join(this.cohortRoot, "memory-cohort-config.json");
25767
+ if (!existsSync18(configPath)) {
25087
25768
  warn("[memory-cohort] cohort config fingerprint file is absent; config-coherence check skipped. Run `/swarm memory link` to re-establish the fingerprint.", { cohortRoot: this.cohortRoot });
25088
25769
  return;
25089
25770
  }
25090
25771
  try {
25091
- const stored = JSON.parse(readFileSync13(configPath, "utf-8"));
25772
+ const stored = JSON.parse(readFileSync14(configPath, "utf-8"));
25092
25773
  const versionCheck = classifyStoredFingerprintAlgorithmVersion(stored.algorithm_version);
25093
25774
  if (versionCheck.status === "unknown") {
25094
25775
  warn("[memory-cohort] cohort config has a present but non-numeric `algorithm_version`, so its fingerprint cannot be attributed to a known algorithm and the config-coherence check was skipped. Run `/swarm memory link` to rewrite the cohort fingerprint.", {
@@ -25808,7 +26489,7 @@ function resolvePoolKeyForRoot(root) {
25808
26489
  try {
25809
26490
  return `cohort:${realpathSync3(root.cohortRoot)}`;
25810
26491
  } catch {
25811
- return `cohort:${path34.resolve(root.cohortRoot)}`;
26492
+ return `cohort:${path35.resolve(root.cohortRoot)}`;
25812
26493
  }
25813
26494
  }
25814
26495
  return resolvePoolKey(root.directory);
@@ -25887,7 +26568,7 @@ function unlinkEntry(entry) {
25887
26568
  tail = entry.prev;
25888
26569
  }
25889
26570
  function resolvePoolKey(directory) {
25890
- const rawKey = path34.resolve(directory);
26571
+ const rawKey = path35.resolve(directory);
25891
26572
  try {
25892
26573
  const canonical = realpathSync3(directory);
25893
26574
  resolvedKeyCache.delete(rawKey);
@@ -25920,24 +26601,24 @@ function evictAndClose(directory) {
25920
26601
 
25921
26602
  // src/memory/storage-root.ts
25922
26603
  init_logger();
25923
- import * as path36 from "path";
26604
+ import * as path37 from "path";
25924
26605
 
25925
26606
  // src/memory/memory-link.ts
25926
- import { existsSync as existsSync18, mkdirSync as mkdirSync10, readFileSync as readFileSync14, rmSync as rmSync2, statSync as statSync8 } from "fs";
25927
- import * as path35 from "path";
26607
+ import { existsSync as existsSync19, mkdirSync as mkdirSync11, readFileSync as readFileSync15, rmSync as rmSync2, statSync as statSync9 } from "fs";
26608
+ import * as path36 from "path";
25928
26609
  init_logger();
25929
26610
  var MEMORY_LINK_POINTER_FILENAME = "memory-link.json";
25930
26611
  var CACHE_TTL_MS = 2000;
25931
26612
  var MAX_CACHE_ENTRIES = 500;
25932
26613
  function resolveMemoryLinkPointerPath(directory) {
25933
- return path35.join(directory, ".swarm", MEMORY_LINK_POINTER_FILENAME);
26614
+ return path36.join(directory, ".swarm", MEMORY_LINK_POINTER_FILENAME);
25934
26615
  }
25935
26616
  function readMemoryLinkPointer(directory) {
25936
26617
  const pointerPath = resolveMemoryLinkPointerPath(directory);
25937
- if (!existsSync18(pointerPath))
26618
+ if (!existsSync19(pointerPath))
25938
26619
  return null;
25939
26620
  try {
25940
- const raw = JSON.parse(readFileSync14(pointerPath, "utf-8"));
26621
+ const raw = JSON.parse(readFileSync15(pointerPath, "utf-8"));
25941
26622
  if (!raw || typeof raw !== "object")
25942
26623
  return null;
25943
26624
  const obj = raw;
@@ -25965,8 +26646,8 @@ function readMemoryLinkPointer(directory) {
25965
26646
  }
25966
26647
  }
25967
26648
  async function writeMemoryLinkPointer(directory, pointer) {
25968
- const swarmDir = path35.join(directory, ".swarm");
25969
- mkdirSync10(swarmDir, { recursive: true });
26649
+ const swarmDir = path36.join(directory, ".swarm");
26650
+ mkdirSync11(swarmDir, { recursive: true });
25970
26651
  const pointerPath = resolveMemoryLinkPointerPath(directory);
25971
26652
  await atomicWriteFile(pointerPath, JSON.stringify(pointer, null, 2));
25972
26653
  invalidateMemoryStoreDirCache(directory);
@@ -25983,14 +26664,14 @@ var _resolutionCache = new Map;
25983
26664
  function pointerStatFingerprint(directory) {
25984
26665
  const pointerPath = resolveMemoryLinkPointerPath(directory);
25985
26666
  try {
25986
- const st = statSync8(pointerPath);
26667
+ const st = statSync9(pointerPath);
25987
26668
  return `${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
25988
26669
  } catch {
25989
26670
  return null;
25990
26671
  }
25991
26672
  }
25992
26673
  function resolveMemoryStoreDir(directory) {
25993
- const localSwarm = path35.join(directory, ".swarm");
26674
+ const localSwarm = path36.join(directory, ".swarm");
25994
26675
  const now2 = Date.now();
25995
26676
  const cached = _resolutionCache.get(directory);
25996
26677
  const currentStat = pointerStatFingerprint(directory);
@@ -26001,7 +26682,7 @@ function resolveMemoryStoreDir(directory) {
26001
26682
  try {
26002
26683
  const pointer = readMemoryLinkPointer(directory);
26003
26684
  if (pointer) {
26004
- linkDir = path35.resolve(resolveLinkDir(pointer.linkId));
26685
+ linkDir = path36.resolve(resolveLinkDir(pointer.linkId));
26005
26686
  }
26006
26687
  } catch {
26007
26688
  linkDir = null;
@@ -26041,13 +26722,13 @@ function resolveVettedMemoryRoot(directory, config) {
26041
26722
  return wrapLocalRoot(directory);
26042
26723
  }
26043
26724
  const sharedDir = resolveMemoryStoreDir(directory);
26044
- const localSwarm = path36.join(directory, ".swarm");
26725
+ const localSwarm = path37.join(directory, ".swarm");
26045
26726
  if (sharedDir === localSwarm) {
26046
26727
  return wrapLocalRoot(directory);
26047
26728
  }
26048
26729
  return {
26049
26730
  kind: "cohort",
26050
- cohortRoot: path36.join(sharedDir, "memory"),
26731
+ cohortRoot: path37.join(sharedDir, "memory"),
26051
26732
  cohortId: pointer.cohortId ?? pointer.linkId,
26052
26733
  generation: pointer.generation ?? 0,
26053
26734
  linkId: pointer.linkId,
@@ -26058,7 +26739,7 @@ function wrapLocalRoot(directory) {
26058
26739
  log("[memory] wrapping raw directory as local vetted root \u2014 cohort sharing inactive for this caller", { directory });
26059
26740
  return {
26060
26741
  kind: "local",
26061
- root: path36.join(directory, ".swarm"),
26742
+ root: path37.join(directory, ".swarm"),
26062
26743
  directory
26063
26744
  };
26064
26745
  }
@@ -26066,7 +26747,7 @@ function isCohortRoot(root) {
26066
26747
  return root.kind === "cohort";
26067
26748
  }
26068
26749
  function rootStoragePath(root) {
26069
- return root.kind === "cohort" ? root.cohortRoot : path36.join(root.root, "memory");
26750
+ return root.kind === "cohort" ? root.cohortRoot : path37.join(root.root, "memory");
26070
26751
  }
26071
26752
 
26072
26753
  // src/memory/gateway.ts
@@ -26338,7 +27019,7 @@ async function runFinalizeRewardSweep(args) {
26338
27019
  }
26339
27020
  const timestamp = args.timestamp ?? new Date().toISOString();
26340
27021
  const vettedRoot = resolveVettedMemoryRoot(directory, memoryConfig);
26341
- const provider = _internals31.createConfiguredMemoryProviderForRoot(vettedRoot, memoryConfig);
27022
+ const provider = _internals32.createConfiguredMemoryProviderForRoot(vettedRoot, memoryConfig);
26342
27023
  try {
26343
27024
  result.swept = true;
26344
27025
  for (const taskId of taskIds) {
@@ -26358,7 +27039,7 @@ async function runFinalizeRewardSweep(args) {
26358
27039
  }
26359
27040
  let taskRewarded = 0;
26360
27041
  for (const runId of runIds) {
26361
- const { memoriesRewarded } = await _internals31.applyCouncilReward(provider, {
27042
+ const { memoriesRewarded } = await _internals32.applyCouncilReward(provider, {
26362
27043
  runId,
26363
27044
  unitId: taskId,
26364
27045
  reward: FINALIZE_NEGATIVE_TERMINAL_REWARD,
@@ -26384,15 +27065,15 @@ async function runFinalizeRewardSweep(args) {
26384
27065
  }
26385
27066
  return result;
26386
27067
  }
26387
- var _internals31 = {
27068
+ var _internals32 = {
26388
27069
  createConfiguredMemoryProvider,
26389
27070
  createConfiguredMemoryProviderForRoot,
26390
27071
  applyCouncilReward
26391
27072
  };
26392
27073
 
26393
27074
  // src/services/session-reflection.ts
26394
- import { promises as fs13 } from "fs";
26395
- import * as path37 from "path";
27075
+ import { promises as fs14 } from "fs";
27076
+ import * as path38 from "path";
26396
27077
 
26397
27078
  // src/hooks/skill-improver-llm-factory.ts
26398
27079
  init_schema();
@@ -26569,13 +27250,13 @@ async function gatherRetroLessonsAndTaxonomy(directory) {
26569
27250
  const lessons = [];
26570
27251
  const taxonomy = {};
26571
27252
  try {
26572
- const evidenceDir = path37.join(directory, ".swarm", "evidence");
26573
- const entries = await fs13.readdir(evidenceDir);
27253
+ const evidenceDir = path38.join(directory, ".swarm", "evidence");
27254
+ const entries = await fs14.readdir(evidenceDir);
26574
27255
  const retroDirs = entries.filter((e) => e.startsWith("retro-")).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
26575
27256
  for (const retroDir of retroDirs) {
26576
- const evidencePath = path37.join(evidenceDir, retroDir, "evidence.json");
27257
+ const evidencePath = path38.join(evidenceDir, retroDir, "evidence.json");
26577
27258
  try {
26578
- const content = await fs13.readFile(evidencePath, "utf-8");
27259
+ const content = await fs14.readFile(evidencePath, "utf-8");
26579
27260
  const parsed = JSON.parse(content);
26580
27261
  const bundleEntries = parsed.entries ?? [parsed];
26581
27262
  for (const entry of bundleEntries) {
@@ -26602,14 +27283,14 @@ async function gatherRetroLessonsAndTaxonomy(directory) {
26602
27283
  async function gatherGateFailures(directory) {
26603
27284
  const failures = new Map;
26604
27285
  try {
26605
- const evidenceDir = path37.join(directory, ".swarm", "evidence");
26606
- const entries = await fs13.readdir(evidenceDir);
27286
+ const evidenceDir = path38.join(directory, ".swarm", "evidence");
27287
+ const entries = await fs14.readdir(evidenceDir);
26607
27288
  for (const entry of entries) {
26608
27289
  if (entry.startsWith("retro-"))
26609
27290
  continue;
26610
- const evidencePath = path37.join(evidenceDir, entry, "evidence.json");
27291
+ const evidencePath = path38.join(evidenceDir, entry, "evidence.json");
26611
27292
  try {
26612
- const content = await fs13.readFile(evidencePath, "utf-8");
27293
+ const content = await fs14.readFile(evidencePath, "utf-8");
26613
27294
  const parsed = JSON.parse(content);
26614
27295
  const bundleEntries = parsed.entries ?? [parsed];
26615
27296
  for (const e of bundleEntries) {
@@ -26642,7 +27323,7 @@ async function gatherLedgerRejections(directory, sessionId) {
26642
27323
  const counts = {};
26643
27324
  const readLedger = async (filePath) => {
26644
27325
  try {
26645
- const handle = await fs13.open(filePath, "r");
27326
+ const handle = await fs14.open(filePath, "r");
26646
27327
  try {
26647
27328
  const stat5 = await handle.stat();
26648
27329
  if (!stat5.isFile())
@@ -26659,23 +27340,23 @@ async function gatherLedgerRejections(directory, sessionId) {
26659
27340
  }
26660
27341
  };
26661
27342
  const readContained = async (root, ...segments) => {
26662
- const target = path37.join(root, ...segments);
27343
+ const target = path38.join(root, ...segments);
26663
27344
  try {
26664
- const realRoot = await fs13.realpath(path37.join(root));
26665
- const realTarget = await fs13.realpath(target);
26666
- const rel = path37.relative(realRoot, realTarget);
26667
- if (rel.startsWith("..") || path37.isAbsolute(rel))
27345
+ const realRoot = await fs14.realpath(path38.join(root));
27346
+ const realTarget = await fs14.realpath(target);
27347
+ const rel = path38.relative(realRoot, realTarget);
27348
+ if (rel.startsWith("..") || path38.isAbsolute(rel))
26668
27349
  return null;
26669
27350
  } catch {
26670
27351
  return null;
26671
27352
  }
26672
27353
  return readLedger(target);
26673
27354
  };
26674
- let content = await readLedger(path37.join(directory, ".swarm", "events.jsonl"));
27355
+ let content = await readLedger(path38.join(directory, ".swarm", "events.jsonl"));
26675
27356
  if (content === null) {
26676
27357
  try {
26677
- const archiveRoot = path37.join(directory, ".swarm", "archive");
26678
- const archiveEntries = await fs13.readdir(archiveRoot);
27358
+ const archiveRoot = path38.join(directory, ".swarm", "archive");
27359
+ const archiveEntries = await fs14.readdir(archiveRoot);
26679
27360
  const archives = archiveEntries.filter((entry) => entry.startsWith("swarm-")).sort();
26680
27361
  for (let index = archives.length - 1;index >= 0 && content === null; index--) {
26681
27362
  content = await readContained(archiveRoot, archives[index], "events.jsonl");
@@ -26718,7 +27399,7 @@ function gatherSkillViolations(directory, sessionId) {
26718
27399
  if (!sessionId)
26719
27400
  return [];
26720
27401
  try {
26721
- const entries = _internals32.readSkillUsageEntriesTail(directory, {
27402
+ const entries = _internals33.readSkillUsageEntriesTail(directory, {
26722
27403
  sessionID: sessionId
26723
27404
  });
26724
27405
  const bySkill = new Map;
@@ -26751,7 +27432,7 @@ async function gatherContradictionCandidates(directory, sessionStart, dedupThres
26751
27432
  if (!Number.isFinite(sessionStartMs))
26752
27433
  return [];
26753
27434
  try {
26754
- const all = await _internals32.readKnowledge(resolveSwarmKnowledgePath(directory));
27435
+ const all = await _internals33.readKnowledge(resolveSwarmKnowledgePath(directory));
26755
27436
  const sessionCreated = all.filter((e) => {
26756
27437
  if (typeof e.created_at !== "string")
26757
27438
  return false;
@@ -26799,7 +27480,7 @@ async function gatherRealtimeAdmissionCounts(directory, sessionStart) {
26799
27480
  if (!Number.isFinite(sessionStartMs))
26800
27481
  return;
26801
27482
  try {
26802
- const entries = await _internals32.readKnowledge(resolveSwarmKnowledgePath(directory));
27483
+ const entries = await _internals33.readKnowledge(resolveSwarmKnowledgePath(directory));
26803
27484
  let admitted = 0;
26804
27485
  let reinforced = 0;
26805
27486
  for (const e of entries) {
@@ -26818,7 +27499,7 @@ async function gatherRealtimeAdmissionCounts(directory, sessionStart) {
26818
27499
  }
26819
27500
  let rejected = 0;
26820
27501
  try {
26821
- const rejectedLessons = await _internals32.readRejectedLessons(directory);
27502
+ const rejectedLessons = await _internals33.readRejectedLessons(directory);
26822
27503
  rejected = rejectedLessons.filter((r) => {
26823
27504
  const ms = Date.parse(r.rejected_at ?? "");
26824
27505
  return Number.isFinite(ms) && ms >= sessionStartMs;
@@ -27132,10 +27813,10 @@ async function runSessionReflection(input) {
27132
27813
  const agentDispatches = gatherAgentDispatches(input.agentSessions);
27133
27814
  const { lessons, taxonomy } = await gatherRetroLessonsAndTaxonomy(input.directory);
27134
27815
  const gateFailures = await gatherGateFailures(input.directory);
27135
- const ledgerRejections = await _internals32.gatherLedgerRejections(input.directory, input.sessionId);
27136
- const skillViolations = _internals32.gatherSkillViolations(input.directory, input.sessionId);
27137
- const contradictionCandidates = await _internals32.gatherContradictionCandidates(input.directory, input.sessionStart, input.dedupThreshold ?? DEFAULT_DEDUP_THRESHOLD2);
27138
- const realtimeCounts = await _internals32.gatherRealtimeAdmissionCounts(input.directory, input.sessionStart);
27816
+ const ledgerRejections = await _internals33.gatherLedgerRejections(input.directory, input.sessionId);
27817
+ const skillViolations = _internals33.gatherSkillViolations(input.directory, input.sessionId);
27818
+ const contradictionCandidates = await _internals33.gatherContradictionCandidates(input.directory, input.sessionStart, input.dedupThreshold ?? DEFAULT_DEDUP_THRESHOLD2);
27819
+ const realtimeCounts = await _internals33.gatherRealtimeAdmissionCounts(input.directory, input.sessionStart);
27139
27820
  const knowledgeDelta = input.knowledgeDelta ? {
27140
27821
  ...input.knowledgeDelta,
27141
27822
  admitted: realtimeCounts?.admitted ?? input.knowledgeDelta.admitted,
@@ -27193,10 +27874,10 @@ async function writeSessionReflection(directory, result) {
27193
27874
  lines.push(result.architectReport);
27194
27875
  const content = lines.join(`
27195
27876
  `);
27196
- await fs13.writeFile(reflectionPath, content, "utf-8");
27877
+ await fs14.writeFile(reflectionPath, content, "utf-8");
27197
27878
  return reflectionPath;
27198
27879
  }
27199
- var _internals32 = {
27880
+ var _internals33 = {
27200
27881
  gatherToolProblems,
27201
27882
  gatherAgentDispatches,
27202
27883
  gatherRetroLessonsAndTaxonomy,
@@ -27216,14 +27897,14 @@ var _internals32 = {
27216
27897
  };
27217
27898
 
27218
27899
  // src/services/skill-improver.ts
27219
- import { existsSync as existsSync20 } from "fs";
27900
+ import { existsSync as existsSync21 } from "fs";
27220
27901
  import { mkdir as mkdir14, readFile as readFile14 } from "fs/promises";
27221
- import * as path39 from "path";
27902
+ import * as path40 from "path";
27222
27903
  init_logger();
27223
27904
 
27224
27905
  // src/services/trajectory-cluster.ts
27225
27906
  import { mkdir as mkdir13, writeFile as writeFile9 } from "fs/promises";
27226
- import * as path38 from "path";
27907
+ import * as path39 from "path";
27227
27908
  init_logger();
27228
27909
  var MACRO_TRAJECTORY_WINDOW = 200;
27229
27910
  var MOTIF_MIN_TASKS = 2;
@@ -27383,14 +28064,14 @@ async function writeMotifProposals(directory, opts = {}) {
27383
28064
  return result;
27384
28065
  const max = opts.maxProposals ?? 10;
27385
28066
  const selected = motifs.slice(0, max);
27386
- const producedAt = _internals33.now().toISOString();
28067
+ const producedAt = _internals34.now().toISOString();
27387
28068
  const candidates = selected.map((motif) => buildMotifCandidate(motif, opts.sessionId));
27388
- const dedupCheck = await _internals33.checkRecommendations(directory, candidates);
28069
+ const dedupCheck = await _internals34.checkRecommendations(directory, candidates);
27389
28070
  const emitted = dedupCheck.decisions.filter((decision) => decision.emit);
27390
28071
  result.duplicatesSuppressed = dedupCheck.decisions.length - emitted.length;
27391
28072
  if (emitted.length === 0)
27392
28073
  return result;
27393
- const proposalsDir = validateSwarmPath(directory, path38.join("skills", "proposals"));
28074
+ const proposalsDir = validateSwarmPath(directory, path39.join("skills", "proposals"));
27394
28075
  await mkdir13(proposalsDir, { recursive: true });
27395
28076
  const written = [];
27396
28077
  for (const decision of emitted) {
@@ -27399,7 +28080,7 @@ async function writeMotifProposals(directory, opts = {}) {
27399
28080
  if (motif === undefined || candidate === undefined)
27400
28081
  continue;
27401
28082
  const slug = `motif-${slugify(motif.signature)}`;
27402
- const filePath = path38.join(proposalsDir, `${slug}.md`);
28083
+ const filePath = path39.join(proposalsDir, `${slug}.md`);
27403
28084
  await writeFile9(filePath, buildMotifProposal(motif, {
27404
28085
  fingerprint: decision.fingerprint,
27405
28086
  producedAt
@@ -27407,7 +28088,7 @@ async function writeMotifProposals(directory, opts = {}) {
27407
28088
  result.proposalsWritten.push(filePath);
27408
28089
  written.push(candidate);
27409
28090
  }
27410
- await _internals33.recordEmittedRecommendations(directory, written, {
28091
+ await _internals34.recordEmittedRecommendations(directory, written, {
27411
28092
  producedAt
27412
28093
  });
27413
28094
  return result;
@@ -27573,14 +28254,14 @@ async function writeSuccessMotifProposals(directory, opts = {}) {
27573
28254
  return result;
27574
28255
  const max = opts.maxProposals ?? 10;
27575
28256
  const selected = motifs.slice(0, max);
27576
- const producedAt = _internals33.now().toISOString();
28257
+ const producedAt = _internals34.now().toISOString();
27577
28258
  const candidates = selected.map((motif) => buildWorkflowCandidate(motif, opts.sessionId));
27578
- const dedupCheck = await _internals33.checkRecommendations(directory, candidates);
28259
+ const dedupCheck = await _internals34.checkRecommendations(directory, candidates);
27579
28260
  const emitted = dedupCheck.decisions.filter((decision) => decision.emit);
27580
28261
  result.duplicatesSuppressed = dedupCheck.decisions.length - emitted.length;
27581
28262
  if (emitted.length === 0)
27582
28263
  return result;
27583
- const proposalsDir = validateSwarmPath(directory, path38.join("skills", "proposals"));
28264
+ const proposalsDir = validateSwarmPath(directory, path39.join("skills", "proposals"));
27584
28265
  await mkdir13(proposalsDir, { recursive: true });
27585
28266
  const written = [];
27586
28267
  for (const decision of emitted) {
@@ -27589,7 +28270,7 @@ async function writeSuccessMotifProposals(directory, opts = {}) {
27589
28270
  if (motif === undefined || candidate === undefined)
27590
28271
  continue;
27591
28272
  const slug = workflowSlug(motif.signature);
27592
- const filePath = path38.join(proposalsDir, `${slug}.md`);
28273
+ const filePath = path39.join(proposalsDir, `${slug}.md`);
27593
28274
  await writeFile9(filePath, buildWorkflowProposal(motif, {
27594
28275
  fingerprint: decision.fingerprint,
27595
28276
  producedAt
@@ -27597,7 +28278,7 @@ async function writeSuccessMotifProposals(directory, opts = {}) {
27597
28278
  result.proposalsWritten.push(filePath);
27598
28279
  written.push(candidate);
27599
28280
  }
27600
- await _internals33.recordEmittedRecommendations(directory, written, {
28281
+ await _internals34.recordEmittedRecommendations(directory, written, {
27601
28282
  producedAt
27602
28283
  });
27603
28284
  return result;
@@ -27606,21 +28287,21 @@ async function writeSuccessMotifProposals(directory, opts = {}) {
27606
28287
  return result;
27607
28288
  }
27608
28289
  }
27609
- var _internals33 = {
28290
+ var _internals34 = {
27610
28291
  now: () => new Date,
27611
28292
  checkRecommendations,
27612
28293
  recordEmittedRecommendations
27613
28294
  };
27614
28295
 
27615
28296
  // src/services/unactionable-hardening.ts
27616
- import { existsSync as existsSync19 } from "fs";
28297
+ import { existsSync as existsSync20 } from "fs";
27617
28298
  init_logger();
27618
28299
  var HARDENING_BATCH_LIMIT = 5;
27619
28300
  async function hardenUnactionableEntries(params) {
27620
28301
  const result = { hardened: 0, retired: 0, remaining: 0 };
27621
28302
  try {
27622
28303
  const queuePath = resolveUnactionablePath(params.directory);
27623
- if (!existsSync19(queuePath))
28304
+ if (!existsSync20(queuePath))
27624
28305
  return result;
27625
28306
  const limit = params.batchLimit ?? HARDENING_BATCH_LIMIT;
27626
28307
  const dedupThreshold = params.dedupThreshold ?? 0.6;
@@ -27724,13 +28405,13 @@ function timestampSlug(d) {
27724
28405
  return d.toISOString().replace(/[:.]/g, "-");
27725
28406
  }
27726
28407
  async function atomicWrite(p, content) {
27727
- await mkdir14(path39.dirname(p), { recursive: true });
28408
+ await mkdir14(path40.dirname(p), { recursive: true });
27728
28409
  await atomicWriteSwarmFile(p, content);
27729
28410
  }
27730
28411
  async function gatherInventory(directory) {
27731
28412
  const swarm = await readKnowledge(resolveSwarmKnowledgePath(directory));
27732
28413
  const hivePath = resolveHiveKnowledgePath2();
27733
- const hive = existsSync20(hivePath) ? await readKnowledge(hivePath) : [];
28414
+ const hive = existsSync21(hivePath) ? await readKnowledge(hivePath) : [];
27734
28415
  const archived = [...swarm, ...hive].filter((e) => e.status === "archived").length;
27735
28416
  const skills = await listSkills(directory);
27736
28417
  const knowledgeById = new Map([...swarm, ...hive].map((entry) => [entry.id, entry]));
@@ -27933,7 +28614,7 @@ async function reconcileStaleActiveSkills(directory, options = {}) {
27933
28614
  continue;
27934
28615
  }
27935
28616
  try {
27936
- const regen = await _internals34.regenerateSkill(directory, skill.slug, {
28617
+ const regen = await _internals35.regenerateSkill(directory, skill.slug, {
27937
28618
  evaluate: false
27938
28619
  });
27939
28620
  if (regen.regenerated) {
@@ -28125,8 +28806,8 @@ async function runSkillImprover(req) {
28125
28806
  }
28126
28807
  throw err;
28127
28808
  }
28128
- const proposalDir = path39.join(req.directory, ".swarm", "skill-improver", "proposals");
28129
- const proposalFile = path39.join(proposalDir, `${timestampSlug(now2)}.md`);
28809
+ const proposalDir = path40.join(req.directory, ".swarm", "skill-improver", "proposals");
28810
+ const proposalFile = path40.join(proposalDir, `${timestampSlug(now2)}.md`);
28130
28811
  const finalBody = source === "llm" ? buildLLMProposalFrame({
28131
28812
  body,
28132
28813
  targets,
@@ -28189,7 +28870,7 @@ async function runSkillImprover(req) {
28189
28870
  autoApply
28190
28871
  };
28191
28872
  }
28192
- var _internals34 = {
28873
+ var _internals35 = {
28193
28874
  runSkillImprover,
28194
28875
  buildDeterministicProposal,
28195
28876
  buildLLMProposalFrame,
@@ -28201,9 +28882,9 @@ var _internals34 = {
28201
28882
  };
28202
28883
 
28203
28884
  // src/services/swarm-residue.ts
28204
- import { createHash as createHash12 } from "crypto";
28205
- import * as fs14 from "fs";
28206
- import * as path40 from "path";
28885
+ import { createHash as createHash13 } from "crypto";
28886
+ import * as fs15 from "fs";
28887
+ import * as path41 from "path";
28207
28888
  var RESIDUE_STALE_AGE_MS = 30 * 60000;
28208
28889
  var MAX_RESIDUE_SCAN_ENTRIES = 20000;
28209
28890
  var RESIDUE_SCAN_DEPTH = 8;
@@ -28213,10 +28894,10 @@ var RESIDUE_SKIP_DIRS = Object.freeze([
28213
28894
  "quarantine",
28214
28895
  "locks"
28215
28896
  ]);
28216
- var _internals35 = {
28897
+ var _internals36 = {
28217
28898
  now: () => Date.now(),
28218
28899
  renameResidueEntry: (from, to) => {
28219
- fs14.renameSync(from, to);
28900
+ fs15.renameSync(from, to);
28220
28901
  },
28221
28902
  queryTracked: (projectRoot, swarmRoot) => {
28222
28903
  const result = bunSpawnSync([
@@ -28225,7 +28906,7 @@ var _internals35 = {
28225
28906
  "core.quotepath=false",
28226
28907
  "ls-files",
28227
28908
  "--",
28228
- swarmRoot.split(path40.sep).join("/")
28909
+ swarmRoot.split(path41.sep).join("/")
28229
28910
  ], {
28230
28911
  cwd: projectRoot,
28231
28912
  stdin: "ignore",
@@ -28243,30 +28924,30 @@ var _internals35 = {
28243
28924
  for (const line of out.split(/\r?\n/)) {
28244
28925
  const t = line.trim();
28245
28926
  if (t)
28246
- tracked.add(path40.normalize(path40.resolve(projectRoot, t)));
28927
+ tracked.add(path41.normalize(path41.resolve(projectRoot, t)));
28247
28928
  }
28248
28929
  return { tracked };
28249
28930
  },
28250
28931
  activeLockTargets: (directory) => {
28251
28932
  const targets = new Set;
28252
28933
  for (const lock of listActiveLocks(directory)) {
28253
- targets.add(path40.normalize(path40.resolve(directory, lock.filePath)));
28934
+ targets.add(path41.normalize(path41.resolve(directory, lock.filePath)));
28254
28935
  }
28255
28936
  return targets;
28256
28937
  },
28257
28938
  sha256File: (absPath) => {
28258
- const hash2 = createHash12("sha256");
28259
- const fd = fs14.openSync(absPath, "r");
28939
+ const hash2 = createHash13("sha256");
28940
+ const fd = fs15.openSync(absPath, "r");
28260
28941
  try {
28261
28942
  const chunk = Buffer.alloc(1024 * 1024);
28262
28943
  for (;; ) {
28263
- const read = fs14.readSync(fd, chunk, 0, chunk.byteLength, null);
28944
+ const read = fs15.readSync(fd, chunk, 0, chunk.byteLength, null);
28264
28945
  if (read === 0)
28265
28946
  break;
28266
28947
  hash2.update(chunk.subarray(0, read));
28267
28948
  }
28268
28949
  } finally {
28269
- fs14.closeSync(fd);
28950
+ fs15.closeSync(fd);
28270
28951
  }
28271
28952
  return hash2.digest("hex");
28272
28953
  }
@@ -28278,10 +28959,10 @@ function collectCandidates(swarmRoot) {
28278
28959
  const walk = (relDir, depth) => {
28279
28960
  if (truncated)
28280
28961
  return;
28281
- const absDir = relDir === "" ? swarmRoot : path40.join(swarmRoot, ...relDir.split("/"));
28962
+ const absDir = relDir === "" ? swarmRoot : path41.join(swarmRoot, ...relDir.split("/"));
28282
28963
  let dirents;
28283
28964
  try {
28284
- dirents = fs14.readdirSync(absDir, { withFileTypes: true });
28965
+ dirents = fs15.readdirSync(absDir, { withFileTypes: true });
28285
28966
  } catch {
28286
28967
  return;
28287
28968
  }
@@ -28305,7 +28986,7 @@ function collectCandidates(swarmRoot) {
28305
28986
  let mtimeMs = 0;
28306
28987
  if (!dirent.isSymbolicLink()) {
28307
28988
  try {
28308
- const st = fs14.lstatSync(path40.join(swarmRoot, ...rel.split("/")));
28989
+ const st = fs15.lstatSync(path41.join(swarmRoot, ...rel.split("/")));
28309
28990
  if (!st.isFile())
28310
28991
  continue;
28311
28992
  bytes = st.size;
@@ -28327,8 +29008,8 @@ function collectCandidates(swarmRoot) {
28327
29008
  return { items, scannedEntries, truncated };
28328
29009
  }
28329
29010
  async function inventorySwarmResidue(directory) {
28330
- const swarmRoot = path40.normalize(path40.resolve(directory, ".swarm"));
28331
- if (!fs14.existsSync(swarmRoot)) {
29011
+ const swarmRoot = path41.normalize(path41.resolve(directory, ".swarm"));
29012
+ if (!fs15.existsSync(swarmRoot)) {
28332
29013
  return {
28333
29014
  swarmRoot,
28334
29015
  scannedEntries: 0,
@@ -28344,15 +29025,15 @@ async function inventorySwarmResidue(directory) {
28344
29025
  gitState: "unknown"
28345
29026
  };
28346
29027
  }
28347
- const rootStat = fs14.lstatSync(swarmRoot);
29028
+ const rootStat = fs15.lstatSync(swarmRoot);
28348
29029
  if (rootStat.isSymbolicLink()) {
28349
29030
  throw new Error(`Refusing to scan a symlinked .swarm root: ${swarmRoot}`);
28350
29031
  }
28351
- const projectRoot = path40.dirname(swarmRoot);
28352
- const { tracked } = _internals35.queryTracked(projectRoot, swarmRoot);
28353
- const lockTargets = _internals35.activeLockTargets(directory);
29032
+ const projectRoot = path41.dirname(swarmRoot);
29033
+ const { tracked } = _internals36.queryTracked(projectRoot, swarmRoot);
29034
+ const lockTargets = _internals36.activeLockTargets(directory);
28354
29035
  const { items, scannedEntries, truncated } = collectCandidates(swarmRoot);
28355
- const now2 = _internals35.now();
29036
+ const now2 = _internals36.now();
28356
29037
  const entries = [];
28357
29038
  for (const item of items) {
28358
29039
  const ageMs = Math.max(0, now2 - item.mtimeMs);
@@ -28360,7 +29041,7 @@ async function inventorySwarmResidue(directory) {
28360
29041
  if (ageMs < RESIDUE_STALE_AGE_MS)
28361
29042
  continue;
28362
29043
  }
28363
- const abs = path40.normalize(path40.join(swarmRoot, ...item.relPath.split("/")));
29044
+ const abs = path41.normalize(path41.join(swarmRoot, ...item.relPath.split("/")));
28364
29045
  const reasons = [];
28365
29046
  if (!item.grammar.quarantineEligible)
28366
29047
  reasons.push("constant-name-grammar");
@@ -28378,7 +29059,7 @@ async function inventorySwarmResidue(directory) {
28378
29059
  }
28379
29060
  if (item.isSymlink)
28380
29061
  reasons.push("symlink");
28381
- const lockHeld = lockTargets.has(abs) || (item.grammar.parsesTarget ? lockTargets.has(path40.normalize(path40.join(path40.dirname(abs), parseTargetBasename(item.relPath.split("/").pop() ?? "") ?? ""))) : false);
29062
+ const lockHeld = lockTargets.has(abs) || (item.grammar.parsesTarget ? lockTargets.has(path41.normalize(path41.join(path41.dirname(abs), parseTargetBasename(item.relPath.split("/").pop() ?? "") ?? ""))) : false);
28382
29063
  if (lockHeld)
28383
29064
  reasons.push("active-lock");
28384
29065
  if (item.bytes > RESIDUE_HASH_MAX_BYTES)
@@ -28386,10 +29067,10 @@ async function inventorySwarmResidue(directory) {
28386
29067
  if (item.grammar.quarantineEligible && item.grammar.parsesTarget) {
28387
29068
  const targetBasename = parseTargetBasename(item.relPath.split("/").pop() ?? "");
28388
29069
  if (targetBasename) {
28389
- const targetAbs = path40.join(path40.dirname(abs), targetBasename);
29070
+ const targetAbs = path41.join(path41.dirname(abs), targetBasename);
28390
29071
  let targetOk = false;
28391
29072
  try {
28392
- targetOk = fs14.lstatSync(targetAbs).isFile();
29073
+ targetOk = fs15.lstatSync(targetAbs).isFile();
28393
29074
  } catch {
28394
29075
  targetOk = false;
28395
29076
  }
@@ -28429,14 +29110,14 @@ async function inventorySwarmResidue(directory) {
28429
29110
  };
28430
29111
  }
28431
29112
  function validateRelPath(rel, what) {
28432
- if (!rel || path40.isAbsolute(rel) || rel.split("/").some((s) => s === ".." || s === "" || /[\0-\x1f]/.test(s))) {
29113
+ if (!rel || path41.isAbsolute(rel) || rel.split("/").some((s) => s === ".." || s === "" || /[\0-\x1f]/.test(s))) {
28433
29114
  throw new Error(`unsafe ${what} in quarantine manifest: ${JSON.stringify(rel)}`);
28434
29115
  }
28435
29116
  return rel;
28436
29117
  }
28437
29118
  function sha256Bounded(absPath) {
28438
29119
  try {
28439
- return _internals35.sha256File(absPath);
29120
+ return _internals36.sha256File(absPath);
28440
29121
  } catch {
28441
29122
  return;
28442
29123
  }
@@ -28454,8 +29135,8 @@ async function quarantineSwarmResidue(directory, options) {
28454
29135
  }
28455
29136
  const swarmRoot = inventory.swarmRoot;
28456
29137
  const batchId = `${new Date().toISOString().replace(/[:.]/g, "-")}-${Math.random().toString(36).slice(2, 10)}`;
28457
- const batchAbs = path40.join(swarmRoot, "quarantine", batchId);
28458
- fs14.mkdirSync(batchAbs, { recursive: true });
29138
+ const batchAbs = path41.join(swarmRoot, "quarantine", batchId);
29139
+ fs15.mkdirSync(batchAbs, { recursive: true });
28459
29140
  const manifest = {
28460
29141
  schema_version: 1,
28461
29142
  batch_id: batchId,
@@ -28465,9 +29146,9 @@ async function quarantineSwarmResidue(directory, options) {
28465
29146
  };
28466
29147
  const moved = [];
28467
29148
  for (const entry of eligible) {
28468
- const abs = path40.join(swarmRoot, ...entry.relPath.split("/"));
29149
+ const abs = path41.join(swarmRoot, ...entry.relPath.split("/"));
28469
29150
  try {
28470
- const st = fs14.lstatSync(abs);
29151
+ const st = fs15.lstatSync(abs);
28471
29152
  if (!st.isFile() || st.size !== entry.bytes || st.mtimeMs !== entry.mtimeMs) {
28472
29153
  preserved.push({
28473
29154
  relPath: entry.relPath,
@@ -28493,10 +29174,10 @@ async function quarantineSwarmResidue(directory, options) {
28493
29174
  });
28494
29175
  continue;
28495
29176
  }
28496
- const storedAbs = path40.join(batchAbs, ...entry.relPath.split("/"));
29177
+ const storedAbs = path41.join(batchAbs, ...entry.relPath.split("/"));
28497
29178
  try {
28498
- fs14.mkdirSync(path40.dirname(storedAbs), { recursive: true });
28499
- _internals35.renameResidueEntry(abs, storedAbs);
29179
+ fs15.mkdirSync(path41.dirname(storedAbs), { recursive: true });
29180
+ _internals36.renameResidueEntry(abs, storedAbs);
28500
29181
  } catch (moveErr) {
28501
29182
  const code = moveErr?.code ?? "unknown";
28502
29183
  preserved.push({
@@ -28508,7 +29189,7 @@ async function quarantineSwarmResidue(directory, options) {
28508
29189
  }
28509
29190
  manifest.entries.push({
28510
29191
  original_rel_path: entry.relPath,
28511
- stored_rel_path: path40.posix.join("quarantine", batchId, entry.relPath),
29192
+ stored_rel_path: path41.posix.join("quarantine", batchId, entry.relPath),
28512
29193
  sha256: sha,
28513
29194
  bytes: entry.bytes,
28514
29195
  mtime_ms: entry.mtimeMs,
@@ -28519,12 +29200,12 @@ async function quarantineSwarmResidue(directory, options) {
28519
29200
  }
28520
29201
  let batchRelDir;
28521
29202
  if (manifest.entries.length > 0) {
28522
- atomicWriteSwarmFileSync(path40.join(batchAbs, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
29203
+ atomicWriteSwarmFileSync(path41.join(batchAbs, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
28523
29204
  `);
28524
- batchRelDir = path40.posix.join("quarantine", batchId);
29205
+ batchRelDir = path41.posix.join("quarantine", batchId);
28525
29206
  } else {
28526
29207
  try {
28527
- fs14.rmSync(batchAbs, { recursive: true, force: true });
29208
+ fs15.rmSync(batchAbs, { recursive: true, force: true });
28528
29209
  } catch {}
28529
29210
  }
28530
29211
  try {
@@ -28552,15 +29233,15 @@ async function quarantineSwarmResidue(directory, options) {
28552
29233
  };
28553
29234
  }
28554
29235
  function listQuarantineBatches(swarmRoot) {
28555
- const quarantineRoot = path40.join(swarmRoot, "quarantine");
29236
+ const quarantineRoot = path41.join(swarmRoot, "quarantine");
28556
29237
  try {
28557
- return fs14.readdirSync(quarantineRoot, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.isSymbolicLink()).map((d) => d.name).sort();
29238
+ return fs15.readdirSync(quarantineRoot, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.isSymbolicLink()).map((d) => d.name).sort();
28558
29239
  } catch {
28559
29240
  return [];
28560
29241
  }
28561
29242
  }
28562
29243
  async function rollbackResidueQuarantine(directory, batchId) {
28563
- const swarmRoot = path40.normalize(path40.resolve(directory, ".swarm"));
29244
+ const swarmRoot = path41.normalize(path41.resolve(directory, ".swarm"));
28564
29245
  const batches = listQuarantineBatches(swarmRoot);
28565
29246
  if (batches.length === 0) {
28566
29247
  throw new Error("No quarantine batches found under .swarm/quarantine/");
@@ -28568,11 +29249,11 @@ async function rollbackResidueQuarantine(directory, batchId) {
28568
29249
  const selected = batchId ? batches.find((b) => b === batchId || b.endsWith(`-${batchId}`)) ?? (() => {
28569
29250
  throw new Error(`Quarantine batch not found: ${batchId}`);
28570
29251
  })() : batches[batches.length - 1];
28571
- const batchAbs = path40.join(swarmRoot, "quarantine", selected);
28572
- const manifestPath = path40.join(batchAbs, "manifest.json");
29252
+ const batchAbs = path41.join(swarmRoot, "quarantine", selected);
29253
+ const manifestPath = path41.join(batchAbs, "manifest.json");
28573
29254
  let manifest;
28574
29255
  try {
28575
- manifest = JSON.parse(fs14.readFileSync(manifestPath, "utf-8"));
29256
+ manifest = JSON.parse(fs15.readFileSync(manifestPath, "utf-8"));
28576
29257
  } catch {
28577
29258
  throw new Error(`Quarantine batch has no readable manifest.json: ${selected}`);
28578
29259
  }
@@ -28584,20 +29265,20 @@ async function rollbackResidueQuarantine(directory, batchId) {
28584
29265
  for (const entry of manifest.entries) {
28585
29266
  const originalRel = validateRelPath(entry.original_rel_path, "original_rel_path");
28586
29267
  const storedRel = validateRelPath(entry.stored_rel_path, "stored_rel_path");
28587
- const originalAbs = path40.join(swarmRoot, ...originalRel.split("/"));
28588
- const storedAbs = path40.join(swarmRoot, ...storedRel.split("/"));
28589
- if (!originalAbs.startsWith(swarmRoot + path40.sep) || !storedAbs.startsWith(batchAbs + path40.sep)) {
29268
+ const originalAbs = path41.join(swarmRoot, ...originalRel.split("/"));
29269
+ const storedAbs = path41.join(swarmRoot, ...storedRel.split("/"));
29270
+ if (!originalAbs.startsWith(swarmRoot + path41.sep) || !storedAbs.startsWith(batchAbs + path41.sep)) {
28590
29271
  throw new Error(`Quarantine manifest path escapes its root: ${selected}`);
28591
29272
  }
28592
- if (!fs14.existsSync(storedAbs)) {
29273
+ if (!fs15.existsSync(storedAbs)) {
28593
29274
  items.push({ relPath: originalRel, status: "missing-copy" });
28594
29275
  allResolved = false;
28595
29276
  continue;
28596
29277
  }
28597
- if (fs14.existsSync(originalAbs)) {
29278
+ if (fs15.existsSync(originalAbs)) {
28598
29279
  const currentSha = sha256Bounded(originalAbs);
28599
29280
  if (currentSha === entry.sha256) {
28600
- fs14.unlinkSync(storedAbs);
29281
+ fs15.unlinkSync(storedAbs);
28601
29282
  items.push({ relPath: originalRel, status: "already-restored" });
28602
29283
  } else {
28603
29284
  items.push({ relPath: originalRel, status: "collision" });
@@ -28605,17 +29286,17 @@ async function rollbackResidueQuarantine(directory, batchId) {
28605
29286
  }
28606
29287
  continue;
28607
29288
  }
28608
- fs14.mkdirSync(path40.dirname(originalAbs), { recursive: true });
28609
- fs14.renameSync(storedAbs, originalAbs);
29289
+ fs15.mkdirSync(path41.dirname(originalAbs), { recursive: true });
29290
+ fs15.renameSync(storedAbs, originalAbs);
28610
29291
  items.push({ relPath: originalRel, status: "restored" });
28611
29292
  }
28612
29293
  if (allResolved) {
28613
29294
  try {
28614
- fs14.rmSync(batchAbs, { recursive: true, force: true });
29295
+ fs15.rmSync(batchAbs, { recursive: true, force: true });
28615
29296
  } catch {}
28616
29297
  }
28617
29298
  return {
28618
- batchRelDir: path40.posix.join("quarantine", selected),
29299
+ batchRelDir: path41.posix.join("quarantine", selected),
28619
29300
  items,
28620
29301
  drained: allResolved
28621
29302
  };
@@ -28668,26 +29349,26 @@ function formatResidueInventoryLines(inv, options) {
28668
29349
  }
28669
29350
 
28670
29351
  // src/session/session-start-store.ts
28671
- import { existsSync as existsSync22, mkdirSync as mkdirSync12, readFileSync as readFileSync16, writeFileSync as writeFileSync8 } from "fs";
28672
- import * as path41 from "path";
29352
+ import { existsSync as existsSync23, mkdirSync as mkdirSync13, readFileSync as readFileSync17, writeFileSync as writeFileSync9 } from "fs";
29353
+ import * as path42 from "path";
28673
29354
  var SESSION_START_FILE = "session-start.jsonl";
28674
29355
  function recordSessionStart(directory, startMs) {
28675
29356
  try {
28676
- const swarmDir = path41.join(directory, ".swarm");
28677
- const sessionDir = path41.join(swarmDir, "session");
28678
- const filePath = path41.join(sessionDir, SESSION_START_FILE);
29357
+ const swarmDir = path42.join(directory, ".swarm");
29358
+ const sessionDir = path42.join(swarmDir, "session");
29359
+ const filePath = path42.join(sessionDir, SESSION_START_FILE);
28679
29360
  const line = JSON.stringify({ startMs, ts: Date.now() });
28680
- mkdirSync12(sessionDir, { recursive: true });
28681
- writeFileSync8(filePath, `${line}
29361
+ mkdirSync13(sessionDir, { recursive: true });
29362
+ writeFileSync9(filePath, `${line}
28682
29363
  `, { flag: "a" });
28683
29364
  } catch {}
28684
29365
  }
28685
29366
  function readEarliestSessionStart(directory) {
28686
29367
  try {
28687
- const filePath = path41.join(directory, ".swarm", "session", SESSION_START_FILE);
28688
- if (!existsSync22(filePath))
29368
+ const filePath = path42.join(directory, ".swarm", "session", SESSION_START_FILE);
29369
+ if (!existsSync23(filePath))
28689
29370
  return null;
28690
- const content = readFileSync16(filePath, "utf-8");
29371
+ const content = readFileSync17(filePath, "utf-8");
28691
29372
  const lines = content.split(`
28692
29373
  `);
28693
29374
  const validStartMs = [];
@@ -28711,8 +29392,8 @@ function readEarliestSessionStart(directory) {
28711
29392
 
28712
29393
  // src/tools/write-retro.ts
28713
29394
  init_zod();
28714
- import { existsSync as existsSync23 } from "fs";
28715
- import path42 from "path";
29395
+ import { existsSync as existsSync24 } from "fs";
29396
+ import path43 from "path";
28716
29397
  async function executeWriteRetro(args, directory) {
28717
29398
  if (/^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(:|$)/i.test(directory)) {
28718
29399
  return JSON.stringify({
@@ -28720,7 +29401,7 @@ async function executeWriteRetro(args, directory) {
28720
29401
  message: "Invalid directory: reserved device name"
28721
29402
  }, null, 2);
28722
29403
  }
28723
- if (!existsSync23(path42.join(directory, ".swarm"))) {
29404
+ if (!existsSync24(path43.join(directory, ".swarm"))) {
28724
29405
  return JSON.stringify({
28725
29406
  success: false,
28726
29407
  message: `Cannot write evidence in "${directory}" \u2014 no .swarm/ folder was found. Run write_retro from an initialized project root.`
@@ -29071,13 +29752,13 @@ var write_retro = createSwarmTool({
29071
29752
  task_id: args.task_id !== undefined ? String(args.task_id) : undefined,
29072
29753
  metadata: args.metadata
29073
29754
  };
29074
- return await _internals36.executeWriteRetro(writeRetroArgs, directory);
29755
+ return await _internals37.executeWriteRetro(writeRetroArgs, directory);
29075
29756
  } catch {
29076
29757
  return JSON.stringify({ success: false, phase: rawPhase, message: "Invalid arguments" }, null, 2);
29077
29758
  }
29078
29759
  }
29079
29760
  });
29080
- var _internals36 = {
29761
+ var _internals37 = {
29081
29762
  executeWriteRetro,
29082
29763
  write_retro
29083
29764
  };
@@ -29086,9 +29767,9 @@ var _internals36 = {
29086
29767
  init_logger();
29087
29768
 
29088
29769
  // src/workflow/close-terminal.ts
29089
- import { createHash as createHash13 } from "crypto";
29770
+ import { createHash as createHash14 } from "crypto";
29090
29771
  function createCloseTransitionId(planEpoch, taskId, target) {
29091
- const digest = createHash13("sha256").update(JSON.stringify([planEpoch, taskId, target]), "utf8").digest("hex");
29772
+ const digest = createHash14("sha256").update(JSON.stringify([planEpoch, taskId, target]), "utf8").digest("hex");
29092
29773
  return `close-terminal:${digest}`;
29093
29774
  }
29094
29775
  function findTask(plan, taskId) {
@@ -29303,10 +29984,10 @@ async function reconcileCloseTerminalState(directory, targetPlan, options) {
29303
29984
 
29304
29985
  // src/commands/archive-sqlite.ts
29305
29986
  import * as fsSync from "fs";
29306
- import path43 from "path";
29987
+ import path44 from "path";
29307
29988
  var DEFAULT_MAX_SOURCE_BYTES = 2 * 1024 * 1024 * 1024;
29308
29989
  var DEFAULT_BUSY_TIMEOUT_MS = 5000;
29309
- var _internals37 = {
29990
+ var _internals38 = {
29310
29991
  existsSync: fsSync.existsSync,
29311
29992
  statSync: fsSync.statSync,
29312
29993
  renameSync: fsSync.renameSync,
@@ -29316,11 +29997,11 @@ var _internals37 = {
29316
29997
  DatabaseCtor: null
29317
29998
  };
29318
29999
  function resolveDatabaseCtor() {
29319
- return _internals37.DatabaseCtor ?? loadDatabaseCtor();
30000
+ return _internals38.DatabaseCtor ?? loadDatabaseCtor();
29320
30001
  }
29321
30002
  function safeRemoveTemp(tempPath) {
29322
30003
  try {
29323
- _internals37.rmSync(tempPath, {
30004
+ _internals38.rmSync(tempPath, {
29324
30005
  force: true,
29325
30006
  recursive: true,
29326
30007
  maxRetries: 3,
@@ -29376,7 +30057,7 @@ function captureRowCounts(db) {
29376
30057
  async function archiveSqliteSnapshot(opts) {
29377
30058
  const maxSourceBytes = opts.maxSourceBytes ?? DEFAULT_MAX_SOURCE_BYTES;
29378
30059
  const busyTimeoutMs = opts.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS;
29379
- if (!_internals37.existsSync(opts.sourcePath)) {
30060
+ if (!_internals38.existsSync(opts.sourcePath)) {
29380
30061
  return {
29381
30062
  requiredness: "required",
29382
30063
  attempt: "not_attempted",
@@ -29389,10 +30070,10 @@ async function archiveSqliteSnapshot(opts) {
29389
30070
  let sourceBytes = 0;
29390
30071
  for (const suffix of ["", "-wal", "-shm"]) {
29391
30072
  const sidecar = opts.sourcePath + suffix;
29392
- if (!_internals37.existsSync(sidecar))
30073
+ if (!_internals38.existsSync(sidecar))
29393
30074
  continue;
29394
30075
  try {
29395
- sourceBytes += _internals37.statSync(sidecar).size;
30076
+ sourceBytes += _internals38.statSync(sidecar).size;
29396
30077
  } catch (err) {
29397
30078
  if (suffix === "") {
29398
30079
  return {
@@ -29418,8 +30099,8 @@ async function archiveSqliteSnapshot(opts) {
29418
30099
  detail: `source bytes ${sourceBytes} > budget ${maxSourceBytes}`
29419
30100
  };
29420
30101
  }
29421
- const destFinal = path43.join(opts.destDir, opts.destName);
29422
- const destTemp = path43.join(opts.destDir, `.${opts.destName}.tmp.${_internals37.now()}.${_internals37.randomSuffix()}`);
30102
+ const destFinal = path44.join(opts.destDir, opts.destName);
30103
+ const destTemp = path44.join(opts.destDir, `.${opts.destName}.tmp.${_internals38.now()}.${_internals38.randomSuffix()}`);
29423
30104
  let Db;
29424
30105
  try {
29425
30106
  Db = resolveDatabaseCtor();
@@ -29518,7 +30199,7 @@ async function archiveSqliteSnapshot(opts) {
29518
30199
  };
29519
30200
  }
29520
30201
  try {
29521
- _internals37.renameSync(destTemp, destFinal);
30202
+ _internals38.renameSync(destTemp, destFinal);
29522
30203
  } catch (err) {
29523
30204
  safeRemoveTemp(destTemp);
29524
30205
  return {
@@ -29618,20 +30299,20 @@ function countSessionKnowledgeEntries(entries, sessionStart, fallbackCount) {
29618
30299
  async function copyDirRecursiveWithFailures(src, dest) {
29619
30300
  let count = 0;
29620
30301
  const failures = [];
29621
- const entries = await fs15.readdir(src);
29622
- await fs15.mkdir(dest, { recursive: true });
30302
+ const entries = await fs16.readdir(src);
30303
+ await fs16.mkdir(dest, { recursive: true });
29623
30304
  for (const entry of entries) {
29624
- const srcEntry = path44.join(src, entry);
29625
- const destEntry = path44.join(dest, entry);
30305
+ const srcEntry = path45.join(src, entry);
30306
+ const destEntry = path45.join(dest, entry);
29626
30307
  try {
29627
- const stat5 = await fs15.stat(srcEntry);
30308
+ const stat5 = await fs16.stat(srcEntry);
29628
30309
  if (stat5.isDirectory()) {
29629
30310
  const subResult = await copyDirRecursiveWithFailures(srcEntry, destEntry);
29630
30311
  count += subResult.copied;
29631
30312
  failures.push(...subResult.failures);
29632
30313
  } else {
29633
30314
  try {
29634
- await fs15.copyFile(srcEntry, destEntry);
30315
+ await fs16.copyFile(srcEntry, destEntry);
29635
30316
  count++;
29636
30317
  } catch (err) {
29637
30318
  const errno = err?.code;
@@ -29684,7 +30365,8 @@ var ARCHIVE_ARTIFACTS = [
29684
30365
  "background-delegations.jsonl",
29685
30366
  "background-delegations.checkpoint.json",
29686
30367
  "background-delegations.manifest.json",
29687
- "background-delegations-health.json"
30368
+ "background-delegations-health.json",
30369
+ "context-telemetry.jsonl"
29688
30370
  ];
29689
30371
  var ACTIVE_STATE_TO_CLEAN = [
29690
30372
  "plan.json",
@@ -29861,20 +30543,20 @@ async function runFinalizeStage(ctx) {
29861
30543
  ctx.warnings.push(`Session retrospective write threw: ${retroError instanceof Error ? retroError.message : String(retroError)}`);
29862
30544
  }
29863
30545
  }
29864
- const lessonsFilePath = path44.join(ctx.swarmDir, "close-lessons.md");
30546
+ const lessonsFilePath = path45.join(ctx.swarmDir, "close-lessons.md");
29865
30547
  try {
29866
- const lessonsText = await fs15.readFile(lessonsFilePath, "utf-8");
30548
+ const lessonsText = await fs16.readFile(lessonsFilePath, "utf-8");
29867
30549
  ctx.explicitLessons = lessonsText.split(`
29868
30550
  `).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
29869
30551
  } catch {}
29870
30552
  try {
29871
- const evidenceDir = path44.join(ctx.swarmDir, "evidence");
29872
- const evidenceEntries = await fs15.readdir(evidenceDir);
30553
+ const evidenceDir = path45.join(ctx.swarmDir, "evidence");
30554
+ const evidenceEntries = await fs16.readdir(evidenceDir);
29873
30555
  const retroDirs = evidenceEntries.filter((e) => e.startsWith("retro-")).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
29874
30556
  for (const retroDir of retroDirs) {
29875
- const evidencePath = path44.join(evidenceDir, retroDir, "evidence.json");
30557
+ const evidencePath = path45.join(evidenceDir, retroDir, "evidence.json");
29876
30558
  try {
29877
- const content = await fs15.readFile(evidencePath, "utf-8");
30559
+ const content = await fs16.readFile(evidencePath, "utf-8");
29878
30560
  const parsed = JSON.parse(content);
29879
30561
  const entries = parsed.entries ?? [parsed];
29880
30562
  for (const entry of entries) {
@@ -29908,8 +30590,8 @@ async function runFinalizeStage(ctx) {
29908
30590
  ];
29909
30591
  ctx.curationSucceeded = false;
29910
30592
  try {
29911
- ctx.curationResult = await _internals38.curateAndStoreSwarm(ctx.allLessons, ctx.projectName, { phase_number: 0 }, ctx.directory, ctx.config, {
29912
- llmDelegate: _internals38.createCuratorLLMDelegate(ctx.directory, "phase", ctx.options.sessionID),
30593
+ ctx.curationResult = await _internals39.curateAndStoreSwarm(ctx.allLessons, ctx.projectName, { phase_number: 0 }, ctx.directory, ctx.config, {
30594
+ llmDelegate: _internals39.createCuratorLLMDelegate(ctx.directory, "phase", ctx.options.sessionID),
29913
30595
  enrichmentQuota: {
29914
30596
  maxCalls: ctx.config.enrichment.max_calls_per_day,
29915
30597
  window: ctx.config.enrichment.quota_window
@@ -29922,13 +30604,13 @@ async function runFinalizeStage(ctx) {
29922
30604
  log("[close-command] curateAndStoreSwarm error:", error2);
29923
30605
  }
29924
30606
  if (ctx.curationSucceeded && ctx.allLessons.length > 0) {
29925
- await fs15.unlink(lessonsFilePath).catch(() => {});
30607
+ await fs16.unlink(lessonsFilePath).catch(() => {});
29926
30608
  }
29927
30609
  if (ctx.curationSucceeded) {
29928
30610
  if (ctx.config.hive_enabled === false) {} else {
29929
30611
  try {
29930
30612
  const entries = await readKnowledge(resolveSwarmKnowledgePath(ctx.directory));
29931
- const result = await _internals38.checkHivePromotions(entries, ctx.config, ctx.directory);
30613
+ const result = await _internals39.checkHivePromotions(entries, ctx.config, ctx.directory);
29932
30614
  ctx.hivePromoted = result.new_promotions;
29933
30615
  } catch (hiveErr) {
29934
30616
  const msg = hiveErr instanceof Error ? hiveErr.message : String(hiveErr);
@@ -29949,7 +30631,7 @@ async function runFinalizeStage(ctx) {
29949
30631
  ctx.knowledgeSkillHint = ctx.sessionKnowledgeCreated > 0 ? `${ctx.sessionKnowledgeCreated} knowledge entries created this session. Consider running skill_improve or skill_generate to compile mature entries into skills.` : "";
29950
30632
  if (ctx.runSkillReview) {
29951
30633
  try {
29952
- const { config: loadedConfig } = _internals38.loadPluginConfigWithMeta(ctx.directory);
30634
+ const { config: loadedConfig } = _internals39.loadPluginConfigWithMeta(ctx.directory);
29953
30635
  const skillImproverConfig = SkillImproverConfigSchema.parse(loadedConfig.skill_improver ?? {});
29954
30636
  const skillReviewResult = await runAbortableSkillReview({
29955
30637
  directory: ctx.directory,
@@ -30046,7 +30728,7 @@ async function runFinalizeStage(ctx) {
30046
30728
  let terminalPlanPersisted = !ctx.planExists;
30047
30729
  if (ctx.planExists) {
30048
30730
  try {
30049
- const reconciled = await _internals38.closePlanTerminalState(ctx.directory, ctx.planData, {
30731
+ const reconciled = await _internals39.closePlanTerminalState(ctx.directory, ctx.planData, {
30050
30732
  actor: ctx.options.sessionID ?? "close-command",
30051
30733
  closedPhaseIds: ctx.guaranteeResult.closedPhaseIds,
30052
30734
  requestedClosedTaskIds: ctx.guaranteeResult.closedTaskIds,
@@ -30088,12 +30770,12 @@ async function runFinalizeStage(ctx) {
30088
30770
  }
30089
30771
  }
30090
30772
  try {
30091
- const { CuratorConfigSchema: CCS } = await import("./schema-yb3pvhcs.js");
30092
- const { config: pmLoadedConfig } = _internals38.loadPluginConfigWithMeta(ctx.directory);
30773
+ const { CuratorConfigSchema: CCS } = await import("./schema-jhz9hme9.js");
30774
+ const { config: pmLoadedConfig } = _internals39.loadPluginConfigWithMeta(ctx.directory);
30093
30775
  const curatorCfg = CCS.parse(pmLoadedConfig.curator ?? {});
30094
30776
  if (curatorCfg.enabled && curatorCfg.postmortem_enabled) {
30095
- const pmResult = await _internals38.runCuratorPostMortem(ctx.directory, {
30096
- llmDelegate: _internals38.createCuratorLLMDelegate(ctx.directory, "postmortem", ctx.options.sessionID),
30777
+ const pmResult = await _internals39.runCuratorPostMortem(ctx.directory, {
30778
+ llmDelegate: _internals39.createCuratorLLMDelegate(ctx.directory, "postmortem", ctx.options.sessionID),
30097
30779
  scope: "project",
30098
30780
  sessionID: ctx.options.sessionID
30099
30781
  });
@@ -30112,15 +30794,21 @@ async function runFinalizeStage(ctx) {
30112
30794
  async function runArchiveStage(ctx) {
30113
30795
  ctx.timestamp = new Date().toISOString().replace(/[:.]/g, "-");
30114
30796
  ctx.archiveSuffix = Math.random().toString(36).slice(2, 8);
30115
- ctx.archiveDir = path44.join(ctx.swarmDir, "archive", `swarm-${ctx.timestamp}-${ctx.archiveSuffix}`);
30797
+ ctx.archiveDir = path45.join(ctx.swarmDir, "archive", `swarm-${ctx.timestamp}-${ctx.archiveSuffix}`);
30116
30798
  try {
30117
- await fs15.mkdir(ctx.archiveDir, { recursive: true });
30799
+ await fs16.mkdir(ctx.archiveDir, { recursive: true });
30118
30800
  try {
30119
- await _internals38.flushAndDrainTelemetry();
30801
+ await _internals39.flushAndDrainTelemetry();
30120
30802
  } catch (flushErr) {
30121
30803
  const msg = flushErr instanceof Error ? flushErr.message : String(flushErr);
30122
30804
  ctx.warnings.push(`Telemetry flush before archive failed: ${msg}`);
30123
30805
  }
30806
+ try {
30807
+ _internals39.finalizeContextTelemetry(ctx.directory);
30808
+ } catch (finalizeErr) {
30809
+ const msg = finalizeErr instanceof Error ? finalizeErr.message : String(finalizeErr);
30810
+ ctx.warnings.push(`Context-map telemetry finalize before archive failed: ${msg}`);
30811
+ }
30124
30812
  const linkedKnowledgeShared = isLinked(ctx.directory);
30125
30813
  if (linkedKnowledgeShared) {
30126
30814
  ctx.warnings.push("Worktree is linked: shared knowledge (knowledge.jsonl, knowledge-rejected.jsonl) lives in the link store and is not archived or cleaned by /swarm close. Manage it via the link.");
@@ -30129,8 +30817,8 @@ async function runArchiveStage(ctx) {
30129
30817
  if (linkedKnowledgeShared && KNOWLEDGE_FAMILY_ARTIFACTS.has(artifact)) {
30130
30818
  continue;
30131
30819
  }
30132
- const srcPath = path44.join(ctx.swarmDir, artifact);
30133
- const destPath = path44.join(ctx.archiveDir, artifact);
30820
+ const srcPath = path45.join(ctx.swarmDir, artifact);
30821
+ const destPath = path45.join(ctx.archiveDir, artifact);
30134
30822
  const requiredness = REQUIRED_ARTIFACTS.has(artifact) ? "required" : "optional";
30135
30823
  if (artifact === "swarm.db") {
30136
30824
  const r = await archiveSqliteSnapshot({
@@ -30161,7 +30849,7 @@ async function runArchiveStage(ctx) {
30161
30849
  }
30162
30850
  } else {
30163
30851
  try {
30164
- await fs15.copyFile(srcPath, destPath);
30852
+ await fs16.copyFile(srcPath, destPath);
30165
30853
  ctx.archivedFileCount++;
30166
30854
  if (ACTIVE_STATE_TO_CLEAN.includes(artifact)) {
30167
30855
  ctx.archivedActiveStateFiles.add(artifact);
@@ -30205,12 +30893,12 @@ async function runArchiveStage(ctx) {
30205
30893
  }
30206
30894
  }
30207
30895
  }
30208
- const dynamicArchiveArtifacts = (await fs15.readdir(ctx.swarmDir).catch(() => [])).filter((name) => /^post-mortem-[^/\\]+\.md$/.test(name) || /^drift-report-phase-\d+\.json$/.test(name));
30896
+ const dynamicArchiveArtifacts = (await fs16.readdir(ctx.swarmDir).catch(() => [])).filter((name) => /^post-mortem-[^/\\]+\.md$/.test(name) || /^drift-report-phase-\d+\.json$/.test(name));
30209
30897
  for (const artifact of dynamicArchiveArtifacts) {
30210
- const srcPath = path44.join(ctx.swarmDir, artifact);
30211
- const destPath = path44.join(ctx.archiveDir, artifact);
30898
+ const srcPath = path45.join(ctx.swarmDir, artifact);
30899
+ const destPath = path45.join(ctx.archiveDir, artifact);
30212
30900
  try {
30213
- await fs15.copyFile(srcPath, destPath);
30901
+ await fs16.copyFile(srcPath, destPath);
30214
30902
  ctx.archivedFileCount++;
30215
30903
  ctx.archivedActiveStateFiles.add(artifact);
30216
30904
  ctx.archiveResults.push({
@@ -30252,8 +30940,8 @@ async function runArchiveStage(ctx) {
30252
30940
  }
30253
30941
  }
30254
30942
  for (const dirName of ACTIVE_STATE_DIRS_TO_CLEAN) {
30255
- const srcDir = path44.join(ctx.swarmDir, dirName);
30256
- const destDir = path44.join(ctx.archiveDir, dirName);
30943
+ const srcDir = path45.join(ctx.swarmDir, dirName);
30944
+ const destDir = path45.join(ctx.archiveDir, dirName);
30257
30945
  try {
30258
30946
  const result = await copyDirRecursiveWithFailures(srcDir, destDir);
30259
30947
  ctx.archivedFileCount += result.copied;
@@ -30295,7 +30983,7 @@ async function runArchiveEvidenceRetention(ctx) {
30295
30983
  let cacheMaxBytes;
30296
30984
  let cacheMaxRecords;
30297
30985
  try {
30298
- const { config: evidenceLoadedConfig } = _internals38.loadPluginConfigWithMeta(ctx.directory);
30986
+ const { config: evidenceLoadedConfig } = _internals39.loadPluginConfigWithMeta(ctx.directory);
30299
30987
  const evidenceCfg = evidenceLoadedConfig.evidence ?? {};
30300
30988
  if (typeof evidenceCfg.max_age_days === "number") {
30301
30989
  maxAgeDays = evidenceCfg.max_age_days;
@@ -30311,7 +30999,7 @@ async function runArchiveEvidenceRetention(ctx) {
30311
30999
  }
30312
31000
  } catch {}
30313
31001
  try {
30314
- await _internals38.archiveEvidence(ctx.directory, maxAgeDays, maxBundles, {
31002
+ await _internals39.archiveEvidence(ctx.directory, maxAgeDays, maxBundles, {
30315
31003
  report: true,
30316
31004
  cacheMaxBytes,
30317
31005
  cacheMaxRecords
@@ -30349,14 +31037,14 @@ async function runCleanStage(ctx) {
30349
31037
  }
30350
31038
  continue;
30351
31039
  }
30352
- const filePath = path44.join(ctx.swarmDir, artifact);
31040
+ const filePath = path45.join(ctx.swarmDir, artifact);
30353
31041
  if (artifact === "swarm.db") {
30354
31042
  try {
30355
31043
  closeProjectDb(ctx.directory);
30356
31044
  } catch {}
30357
31045
  }
30358
31046
  try {
30359
- await fs15.unlink(filePath);
31047
+ await fs16.unlink(filePath);
30360
31048
  cleanedFiles.push(artifact);
30361
31049
  } catch (err) {
30362
31050
  const errno = err?.code;
@@ -30374,7 +31062,7 @@ async function runCleanStage(ctx) {
30374
31062
  continue;
30375
31063
  }
30376
31064
  try {
30377
- await fs15.unlink(path44.join(ctx.swarmDir, artifact));
31065
+ await fs16.unlink(path45.join(ctx.swarmDir, artifact));
30378
31066
  cleanedFiles.push(artifact);
30379
31067
  } catch (err) {
30380
31068
  const errno = err?.code;
@@ -30388,18 +31076,18 @@ async function runCleanStage(ctx) {
30388
31076
  if (!ctx.archivedActiveStateDirs.has(dirName)) {
30389
31077
  continue;
30390
31078
  }
30391
- const dirPath = path44.join(ctx.swarmDir, dirName);
31079
+ const dirPath = path45.join(ctx.swarmDir, dirName);
30392
31080
  try {
30393
- await fs15.rm(dirPath, { recursive: true, force: true });
31081
+ await fs16.rm(dirPath, { recursive: true, force: true });
30394
31082
  cleanedFiles.push(`${dirName}/`);
30395
31083
  } catch {}
30396
31084
  }
30397
31085
  try {
30398
- const swarmFiles = await fs15.readdir(ctx.swarmDir);
31086
+ const swarmFiles = await fs16.readdir(ctx.swarmDir);
30399
31087
  const configBackups = swarmFiles.filter((f) => f.startsWith("config-backup-") && f.endsWith(".json"));
30400
31088
  for (const backup of configBackups) {
30401
31089
  try {
30402
- await fs15.unlink(path44.join(ctx.swarmDir, backup));
31090
+ await fs16.unlink(path45.join(ctx.swarmDir, backup));
30403
31091
  configBackupsRemoved++;
30404
31092
  } catch (err) {
30405
31093
  const errno = err?.code;
@@ -30412,7 +31100,7 @@ async function runCleanStage(ctx) {
30412
31100
  const ledgerSiblings = swarmFiles.filter((f) => (f.startsWith("plan-ledger.archived-") || f.startsWith("plan-ledger.backup-")) && f.endsWith(".jsonl"));
30413
31101
  for (const sibling of ledgerSiblings) {
30414
31102
  try {
30415
- await fs15.unlink(path44.join(ctx.swarmDir, sibling));
31103
+ await fs16.unlink(path45.join(ctx.swarmDir, sibling));
30416
31104
  } catch (err) {
30417
31105
  const errno = err?.code;
30418
31106
  if (errno === "ENOENT") {} else {
@@ -30430,16 +31118,16 @@ async function runCleanStage(ctx) {
30430
31118
  }
30431
31119
  let swarmPlanFilesRemoved = 0;
30432
31120
  const candidates = [
30433
- path44.join(ctx.directory, ".swarm", "plan-export", "SWARM_PLAN.json"),
30434
- path44.join(ctx.directory, ".swarm", "plan-export", "SWARM_PLAN.md"),
30435
- path44.join(ctx.directory, ".swarm", "SWARM_PLAN.json"),
30436
- path44.join(ctx.directory, ".swarm", "SWARM_PLAN.md"),
30437
- path44.join(ctx.directory, "SWARM_PLAN.json"),
30438
- path44.join(ctx.directory, "SWARM_PLAN.md")
31121
+ path45.join(ctx.directory, ".swarm", "plan-export", "SWARM_PLAN.json"),
31122
+ path45.join(ctx.directory, ".swarm", "plan-export", "SWARM_PLAN.md"),
31123
+ path45.join(ctx.directory, ".swarm", "SWARM_PLAN.json"),
31124
+ path45.join(ctx.directory, ".swarm", "SWARM_PLAN.md"),
31125
+ path45.join(ctx.directory, "SWARM_PLAN.json"),
31126
+ path45.join(ctx.directory, "SWARM_PLAN.md")
30439
31127
  ];
30440
31128
  for (const candidate of candidates) {
30441
31129
  try {
30442
- await fs15.unlink(candidate);
31130
+ await fs16.unlink(candidate);
30443
31131
  swarmPlanFilesRemoved++;
30444
31132
  } catch (err) {
30445
31133
  if (err?.code !== "ENOENT") {
@@ -30469,7 +31157,7 @@ async function runCleanStage(ctx) {
30469
31157
  }
30470
31158
  for (const terminalFile of TERMINAL_STATE_FILES) {
30471
31159
  try {
30472
- await fs15.unlink(path44.join(ctx.swarmDir, terminalFile));
31160
+ await fs16.unlink(path45.join(ctx.swarmDir, terminalFile));
30473
31161
  if (!cleanedFiles.includes(terminalFile)) {
30474
31162
  cleanedFiles.push(terminalFile);
30475
31163
  }
@@ -30482,7 +31170,7 @@ async function runCleanStage(ctx) {
30482
31170
  }
30483
31171
  }
30484
31172
  clearAllScopes(ctx.directory);
30485
- const contextPath = path44.join(ctx.swarmDir, "context.md");
31173
+ const contextPath = path45.join(ctx.swarmDir, "context.md");
30486
31174
  const contextContent = [
30487
31175
  "# Context",
30488
31176
  "",
@@ -30513,9 +31201,9 @@ async function runAlignStage(ctx) {
30513
31201
  const pruneBranches = ctx.args.includes("--prune-branches");
30514
31202
  let gitAlignResult = "";
30515
31203
  const prunedBranches = [];
30516
- const gitStatus = _internals38.getGitRepositoryStatus(ctx.directory);
31204
+ const gitStatus = _internals39.getGitRepositoryStatus(ctx.directory);
30517
31205
  if (gitStatus.isRepo) {
30518
- const aggressiveResult = await _internals38.resetToMainAfterMerge(ctx.directory, {
31206
+ const aggressiveResult = await _internals39.resetToMainAfterMerge(ctx.directory, {
30519
31207
  pruneBranches
30520
31208
  });
30521
31209
  if (aggressiveResult.success) {
@@ -30527,7 +31215,7 @@ async function runAlignStage(ctx) {
30527
31215
  ctx.warnings.push("Uncommitted changes were discarded during git alignment");
30528
31216
  }
30529
31217
  } else {
30530
- const alignResult = await _internals38.resetToRemoteBranch(ctx.directory, {
31218
+ const alignResult = await _internals39.resetToRemoteBranch(ctx.directory, {
30531
31219
  pruneBranches
30532
31220
  });
30533
31221
  gitAlignResult = alignResult.message;
@@ -30554,16 +31242,16 @@ async function runAlignStage(ctx) {
30554
31242
  return { gitAlignResult, prunedBranches };
30555
31243
  }
30556
31244
  async function runFinalizeDryRun(directory, swarmDir, planData, planExists) {
30557
- const existsInSwarm = (name) => fsSync2.existsSync(path44.join(swarmDir, name));
31245
+ const existsInSwarm = (name) => fsSync2.existsSync(path45.join(swarmDir, name));
30558
31246
  const phases = planData.phases ?? [];
30559
31247
  const nonTerminalPhases = phases.filter((p) => p.status !== "complete" && p.status !== "completed" && p.status !== "blocked" && p.status !== "closed");
30560
31248
  const planAlreadyDone = planExists && phases.length > 0 && nonTerminalPhases.length === 0;
30561
31249
  const wouldArchive = ARCHIVE_ARTIFACTS.filter(existsInSwarm);
30562
- const dynamicArchive = (await fs15.readdir(swarmDir).catch(() => [])).filter((name) => /^post-mortem-[^/\\]+\.md$/.test(name) || /^drift-report-phase-\d+\.json$/.test(name));
31250
+ const dynamicArchive = (await fs16.readdir(swarmDir).catch(() => [])).filter((name) => /^post-mortem-[^/\\]+\.md$/.test(name) || /^drift-report-phase-\d+\.json$/.test(name));
30563
31251
  const wouldArchiveDirs = ACTIVE_STATE_DIRS_TO_CLEAN.filter(existsInSwarm);
30564
31252
  const wouldRemoveTerminal = TERMINAL_STATE_FILES.filter(existsInSwarm);
30565
31253
  const wouldCleanFiles = ACTIVE_STATE_TO_CLEAN.filter((f) => existsInSwarm(f) && !TERMINAL_STATE_FILES.includes(f));
30566
- const gitStatus = _internals38.getGitRepositoryStatus(directory);
31254
+ const gitStatus = _internals39.getGitRepositoryStatus(directory);
30567
31255
  const gitNote = gitStatus.isRepo ? "would align the working tree to main/remote (git reset), pruning merged branches only with --prune-branches" : "would skip git alignment (not a git repository / git unavailable)";
30568
31256
  let residueSection = [];
30569
31257
  try {
@@ -30617,7 +31305,7 @@ async function runFinalizeDryRun(directory, swarmDir, planData, planExists) {
30617
31305
  `);
30618
31306
  }
30619
31307
  async function handleCloseCommand(directory, args, options = {}) {
30620
- const swarmDir = path44.join(directory, ".swarm");
31308
+ const swarmDir = path45.join(directory, ".swarm");
30621
31309
  try {
30622
31310
  const stat5 = fsSync2.lstatSync(swarmDir);
30623
31311
  if (stat5.isSymbolicLink()) {
@@ -30631,43 +31319,43 @@ async function handleCloseCommand(directory, args, options = {}) {
30631
31319
  const planPath = validateSwarmPath(directory, "plan.json");
30632
31320
  let planExists = false;
30633
31321
  let planData = {
30634
- title: path44.basename(directory) || "Ad-hoc session",
31322
+ title: path45.basename(directory) || "Ad-hoc session",
30635
31323
  phases: []
30636
31324
  };
30637
31325
  try {
30638
- const content = await fs15.readFile(planPath, "utf-8");
31326
+ const content = await fs16.readFile(planPath, "utf-8");
30639
31327
  planData = JSON.parse(content);
30640
31328
  planExists = true;
30641
31329
  } catch (error2) {
30642
31330
  if (error2?.code !== "ENOENT") {
30643
31331
  return `\u274C Failed to read plan.json: ${error2 instanceof Error ? error2.message : String(error2)}`;
30644
31332
  }
30645
- const swarmDirExists = await fs15.access(swarmDir).then(() => true).catch(() => false);
31333
+ const swarmDirExists = await fs16.access(swarmDir).then(() => true).catch(() => false);
30646
31334
  if (!swarmDirExists) {
30647
31335
  return `\u274C No .swarm/ directory found in ${directory}. Run /swarm close from the project root, or run /swarm plan first.`;
30648
31336
  }
30649
31337
  }
30650
31338
  if (args.includes("--dry-run")) {
30651
- return _internals38.runFinalizeDryRun(directory, swarmDir, planData, planExists);
31339
+ return _internals39.runFinalizeDryRun(directory, swarmDir, planData, planExists);
30652
31340
  }
30653
31341
  let finalizeLock = {
30654
31342
  acquired: false
30655
31343
  };
30656
- finalizeLock = await _internals38.acquireFinalizeLock(directory);
31344
+ finalizeLock = await _internals39.acquireFinalizeLock(directory);
30657
31345
  if (!finalizeLock.acquired) {
30658
31346
  return `\u274C Another /swarm finalize is already running for this project. If you are certain no other run is active, wait for the lock to expire or remove the stale lock and retry.`;
30659
31347
  }
30660
31348
  try {
30661
31349
  if (!planExists) {
30662
- const archiveDir = path44.join(swarmDir, "archive");
31350
+ const archiveDir = path45.join(swarmDir, "archive");
30663
31351
  try {
30664
- const archiveEntries = await fs15.readdir(archiveDir);
31352
+ const archiveEntries = await fs16.readdir(archiveDir);
30665
31353
  const hasArchiveBundle = archiveEntries.some((entry) => entry.startsWith("swarm-"));
30666
31354
  if (hasArchiveBundle) {
30667
31355
  const hasActiveState = [
30668
31356
  ...ACTIVE_STATE_TO_CLEAN,
30669
31357
  ...ACTIVE_STATE_DIRS_TO_CLEAN
30670
- ].some((entry) => fsSync2.existsSync(path44.join(swarmDir, entry)));
31358
+ ].some((entry) => fsSync2.existsSync(path45.join(swarmDir, entry)));
30671
31359
  if (!hasActiveState) {
30672
31360
  return `\u2705 Already finalized \u2014 nothing to do.
30673
31361
 
@@ -30684,7 +31372,7 @@ This project was already finalized in a previous /swarm close run. The plan has
30684
31372
  if (planExists) {
30685
31373
  planAlreadyDone = phases.length > 0 && phases.every((p) => p.status === "complete" || p.status === "completed" || p.status === "blocked" || p.status === "closed");
30686
31374
  }
30687
- const { config: loadedConfig } = _internals38.loadPluginConfigWithMeta(directory);
31375
+ const { config: loadedConfig } = _internals39.loadPluginConfigWithMeta(directory);
30688
31376
  const config = KnowledgeConfigSchema.parse(loadedConfig.knowledge ?? {});
30689
31377
  const ctx = {
30690
31378
  directory,
@@ -30733,14 +31421,14 @@ This project was already finalized in a previous /swarm close run. The plan has
30733
31421
  archiveSuffix: "",
30734
31422
  args
30735
31423
  };
30736
- ctx.fullAuto = options.sessionID ? _internals38.detectFullAuto(directory, options.sessionID) : false;
31424
+ ctx.fullAuto = options.sessionID ? _internals39.detectFullAuto(directory, options.sessionID) : false;
30737
31425
  await runFinalizeStage(ctx);
30738
31426
  if (ctx.terminalizationError) {
30739
31427
  return `\u274C Close paused before reward, archive, cleanup, teardown, and Git alignment because terminal plan/evidence reconciliation failed: ${ctx.terminalizationError}
30740
31428
 
30741
31429
  No active state was archived or removed. Fix the reported durable-state problem, then retry /swarm close.`;
30742
31430
  }
30743
- await _internals38.runFinalizeRewardSweep({
31431
+ await _internals39.runFinalizeRewardSweep({
30744
31432
  directory,
30745
31433
  closedTaskIds: ctx.guaranteeResult.closedTaskIds,
30746
31434
  memoryConfig: loadedConfig.memory
@@ -30818,9 +31506,9 @@ No active state was archived or removed. Fix the reported durable-state problem,
30818
31506
  try {
30819
31507
  const sessionIdsToEnd = [...swarmState.agentSessions.keys()];
30820
31508
  for (const sessionId of sessionIdsToEnd) {
30821
- _internals38.endAgentSession(sessionId);
31509
+ _internals39.endAgentSession(sessionId);
30822
31510
  }
30823
- _internals38.resetSwarmStatePreservingSingletons();
31511
+ _internals39.resetSwarmStatePreservingSingletons();
30824
31512
  } catch (teardownError) {
30825
31513
  const msg = teardownError instanceof Error ? teardownError.message : String(teardownError);
30826
31514
  ctx.warnings.push(`Session teardown encountered an error after finalization completed (state may not be fully reset): ${msg}`);
@@ -30917,7 +31605,7 @@ function detectFullAuto(directory, sessionID) {
30917
31605
  return false;
30918
31606
  }
30919
31607
  }
30920
- var _internals38 = {
31608
+ var _internals39 = {
30921
31609
  ACTIVE_STATE_DIRS_TO_CLEAN,
30922
31610
  countSessionKnowledgeEntries,
30923
31611
  CLOSE_SKILL_REVIEW_TIMEOUT_MS,
@@ -30946,8 +31634,11 @@ var _internals38 = {
30946
31634
  closePlanTerminalState: reconcileCloseTerminalStateForPlan,
30947
31635
  endAgentSession,
30948
31636
  flushAndDrainTelemetry: async () => {
30949
- const { flushAndDrainTelemetry } = await import("./telemetry-t109dhv7.js");
31637
+ const { flushAndDrainTelemetry } = await import("./telemetry-xzy0qeap.js");
30950
31638
  return flushAndDrainTelemetry();
31639
+ },
31640
+ finalizeContextTelemetry: (directory) => {
31641
+ finalizeContextTelemetry(directory);
30951
31642
  }
30952
31643
  };
30953
31644
 
@@ -31183,14 +31874,14 @@ function buildStatusMessage(session, plan) {
31183
31874
  // src/commands/config.ts
31184
31875
  init_loader();
31185
31876
  import * as os6 from "os";
31186
- import * as path45 from "path";
31877
+ import * as path46 from "path";
31187
31878
  function getUserConfigDir() {
31188
- return process.env.XDG_CONFIG_HOME || path45.join(os6.homedir(), ".config");
31879
+ return process.env.XDG_CONFIG_HOME || path46.join(os6.homedir(), ".config");
31189
31880
  }
31190
31881
  async function handleConfigCommand(directory, _args) {
31191
31882
  const config = loadPluginConfig(directory);
31192
- const userConfigPath = path45.join(getUserConfigDir(), "opencode", "opencode-swarm.json");
31193
- const projectConfigPath = path45.join(directory, ".opencode", "opencode-swarm.json");
31883
+ const userConfigPath = path46.join(getUserConfigDir(), "opencode", "opencode-swarm.json");
31884
+ const projectConfigPath = path46.join(directory, ".opencode", "opencode-swarm.json");
31194
31885
  const lines = [
31195
31886
  "## Swarm Configuration",
31196
31887
  "",
@@ -31211,19 +31902,19 @@ async function handleConfigCommand(directory, _args) {
31211
31902
  init_schema();
31212
31903
 
31213
31904
  // src/services/skill-consolidation.ts
31214
- import { existsSync as existsSync26 } from "fs";
31905
+ import { existsSync as existsSync27 } from "fs";
31215
31906
  import { mkdir as mkdir15, readFile as readFile15 } from "fs/promises";
31216
- import * as path46 from "path";
31907
+ import * as path47 from "path";
31217
31908
  var DEFAULT_CONSOLIDATION_INTERVAL_HOURS = 24;
31218
31909
  var DEFAULT_CONSOLIDATION_MAX_CALLS_PER_RUN = 1;
31219
31910
  var CONSOLIDATION_RUN_TIMEOUT_MS = 5 * 60 * 1000;
31220
31911
  var runningByDirectory = new Map;
31221
31912
  function consolidationStatePath(directory) {
31222
- return path46.join(directory, ".swarm", "skill-improver", "consolidation-state.json");
31913
+ return path47.join(directory, ".swarm", "skill-improver", "consolidation-state.json");
31223
31914
  }
31224
31915
  async function readState2(directory) {
31225
31916
  const filePath = consolidationStatePath(directory);
31226
- if (!existsSync26(filePath))
31917
+ if (!existsSync27(filePath))
31227
31918
  return {};
31228
31919
  try {
31229
31920
  const parsed = JSON.parse(await readFile15(filePath, "utf-8"));
@@ -31235,7 +31926,7 @@ async function readState2(directory) {
31235
31926
  }
31236
31927
  }
31237
31928
  async function atomicWrite2(filePath, content) {
31238
- await mkdir15(path46.dirname(filePath), { recursive: true });
31929
+ await mkdir15(path47.dirname(filePath), { recursive: true });
31239
31930
  await atomicWriteSwarmFile(filePath, content);
31240
31931
  }
31241
31932
  async function writeState2(directory, state) {
@@ -31313,7 +32004,7 @@ async function runSkillConsolidationInner(req) {
31313
32004
  };
31314
32005
  }
31315
32006
  async function runSkillConsolidation(req) {
31316
- const key = path46.resolve(req.directory);
32007
+ const key = path47.resolve(req.directory);
31317
32008
  const existing = runningByDirectory.get(key);
31318
32009
  if (existing) {
31319
32010
  return {
@@ -31401,99 +32092,10 @@ async function handleConsolidateCommand(directory, args, options = {}) {
31401
32092
  }
31402
32093
  }
31403
32094
 
31404
- // src/context-map/telemetry.ts
31405
- import * as fs16 from "fs";
31406
- import * as path47 from "path";
31407
- function isValidTelemetryEntry(value) {
31408
- if (typeof value !== "object" || value === null) {
31409
- return false;
31410
- }
31411
- const obj = value;
31412
- return typeof obj.timestamp === "string" && typeof obj.task_id === "string" && typeof obj.agent_role === "string" && typeof obj.delegation_reason === "string" && typeof obj.token_estimate === "number" && typeof obj.cache_hits === "number" && typeof obj.cache_misses === "number" && typeof obj.stale_entries === "number" && typeof obj.recommended_reads === "number" && typeof obj.skipped_reads === "number" && typeof obj.success === "boolean";
31413
- }
31414
- var _internals39 = {
31415
- appendFileSync: fs16.appendFileSync,
31416
- readFileSync: fs16.readFileSync,
31417
- existsSync: fs16.existsSync,
31418
- mkdirSync: fs16.mkdirSync
31419
- };
31420
- function telemetryFilePath(directory) {
31421
- return path47.join(directory, ".swarm", "context-telemetry.jsonl");
31422
- }
31423
- function readTelemetry(directory) {
31424
- const filePath = telemetryFilePath(directory);
31425
- const entries = [];
31426
- try {
31427
- if (!_internals39.existsSync(filePath)) {
31428
- return entries;
31429
- }
31430
- const raw = _internals39.readFileSync(filePath, "utf-8");
31431
- const lines = raw.split(`
31432
- `);
31433
- for (const line of lines) {
31434
- if (line.trim() === "") {
31435
- continue;
31436
- }
31437
- try {
31438
- const parsed = JSON.parse(line);
31439
- if (isValidTelemetryEntry(parsed)) {
31440
- entries.push(parsed);
31441
- }
31442
- } catch {}
31443
- }
31444
- return entries;
31445
- } catch {
31446
- return entries;
31447
- }
31448
- }
31449
- function getTelemetrySummary(directory) {
31450
- const entries = readTelemetry(directory);
31451
- if (entries.length === 0) {
31452
- return {
31453
- total_delegations: 0,
31454
- total_cache_hits: 0,
31455
- total_cache_misses: 0,
31456
- total_stale_entries: 0,
31457
- avg_token_estimate: 0,
31458
- total_recommended_reads: 0,
31459
- total_skipped_reads: 0,
31460
- success_rate: 0
31461
- };
31462
- }
31463
- let totalCacheHits = 0;
31464
- let totalCacheMisses = 0;
31465
- let totalStaleEntries = 0;
31466
- let totalTokenEstimate = 0;
31467
- let totalRecommendedReads = 0;
31468
- let totalSkippedReads = 0;
31469
- let totalSuccess = 0;
31470
- for (const entry of entries) {
31471
- totalCacheHits += entry.cache_hits;
31472
- totalCacheMisses += entry.cache_misses;
31473
- totalStaleEntries += entry.stale_entries;
31474
- totalTokenEstimate += entry.token_estimate;
31475
- totalRecommendedReads += entry.recommended_reads;
31476
- totalSkippedReads += entry.skipped_reads;
31477
- if (entry.success) {
31478
- totalSuccess++;
31479
- }
31480
- }
31481
- return {
31482
- total_delegations: entries.length,
31483
- total_cache_hits: totalCacheHits,
31484
- total_cache_misses: totalCacheMisses,
31485
- total_stale_entries: totalStaleEntries,
31486
- avg_token_estimate: Math.round(totalTokenEstimate / entries.length),
31487
- total_recommended_reads: totalRecommendedReads,
31488
- total_skipped_reads: totalSkippedReads,
31489
- success_rate: Math.round(totalSuccess / entries.length * 100)
31490
- };
31491
- }
31492
-
31493
32095
  // src/commands/context-map-stats.ts
31494
32096
  async function handleContextMapStatsCommand(directory) {
31495
32097
  const summary = getTelemetrySummary(directory);
31496
- if (summary.total_delegations === 0) {
32098
+ if (summary.total_delegations === 0 && summary.corrupt_entries === 0) {
31497
32099
  return "No capsule telemetry recorded.";
31498
32100
  }
31499
32101
  const pct = (n, d) => d === 0 ? "N/A" : `${(n / d * 100).toFixed(1)}%`;
@@ -31509,6 +32111,15 @@ async function handleContextMapStatsCommand(directory) {
31509
32111
  `**Recommended reads:** ${summary.total_recommended_reads}`,
31510
32112
  `**Skipped reads:** ${summary.total_skipped_reads}`
31511
32113
  ];
32114
+ if (summary.coverage === "partial-unmigrated") {
32115
+ lines.push("", "> Historical context telemetry spans more than the documented read bound and is being migrated in bounded passes; totals above cover only the part already accounted. Run `/swarm context-map stats` again after the store settles for the full lifetime figure.");
32116
+ }
32117
+ if (summary.dropped_entries > 0) {
32118
+ lines.push(`**Dropped (age-pruned raw records, totals unaffected):** ${summary.dropped_entries}`);
32119
+ }
32120
+ if (summary.corrupt_entries > 0) {
32121
+ lines.push(`**Corrupt/partial lines skipped (diagnostics only):** ${summary.corrupt_entries}`);
32122
+ }
31512
32123
  return lines.join(`
31513
32124
  `);
31514
32125
  }
@@ -32352,9 +32963,9 @@ var _internals43 = {
32352
32963
  loadPluginConfigWithMeta,
32353
32964
  loadCuratorDeps: async () => {
32354
32965
  const [{ CuratorConfigSchema }, curator, { createCuratorLLMDelegate: createCuratorLLMDelegate2 }] = await Promise.all([
32355
- import("./schema-yb3pvhcs.js"),
32356
- import("./curator-vghf320v.js"),
32357
- import("./curator-llm-factory-zxbgkjm5.js")
32966
+ import("./schema-jhz9hme9.js"),
32967
+ import("./curator-acp80hpc.js"),
32968
+ import("./curator-llm-factory-ewffa8r1.js")
32358
32969
  ]);
32359
32970
  return { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 };
32360
32971
  }
@@ -32854,7 +33465,7 @@ ${USAGE8}`;
32854
33465
  // src/services/diagnose-service.ts
32855
33466
  init_package();
32856
33467
  import * as child_process5 from "child_process";
32857
- import { existsSync as existsSync31, readdirSync as readdirSync6, readFileSync as readFileSync21, statSync as statSync10 } from "fs";
33468
+ import { existsSync as existsSync31, readdirSync as readdirSync6, readFileSync as readFileSync21, statSync as statSync11 } from "fs";
32858
33469
  import * as path52 from "path";
32859
33470
  import { fileURLToPath } from "url";
32860
33471
 
@@ -32963,7 +33574,7 @@ import { readFile as readFile17 } from "fs/promises";
32963
33574
  import { join as join40 } from "path";
32964
33575
 
32965
33576
  // src/services/version-check.ts
32966
- import { existsSync as existsSync29, mkdirSync as mkdirSync15, readFileSync as readFileSync19, writeFileSync as writeFileSync9 } from "fs";
33577
+ import { existsSync as existsSync29, mkdirSync as mkdirSync15, readFileSync as readFileSync19, writeFileSync as writeFileSync10 } from "fs";
32967
33578
  import { homedir as homedir6 } from "os";
32968
33579
  import { join as join39 } from "path";
32969
33580
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
@@ -33308,7 +33919,7 @@ async function computeCurationDiagnostics(directory, entries) {
33308
33919
  let scanCompleted = false;
33309
33920
  let scanRemaining = 0;
33310
33921
  try {
33311
- const { getScanStatus } = await import("./scan-cursor-rhjym1pn.js");
33922
+ const { getScanStatus } = await import("./scan-cursor-4jv70zwb.js");
33312
33923
  const status = await getScanStatus(directory);
33313
33924
  scanGeneration = status.generation;
33314
33925
  scanCompleted = status.completed;
@@ -33316,19 +33927,19 @@ async function computeCurationDiagnostics(directory, entries) {
33316
33927
  } catch {}
33317
33928
  let configMatch = null;
33318
33929
  try {
33319
- const { isLinked: isLinked2 } = await import("./knowledge-link-8pr02pza.js");
33930
+ const { isLinked: isLinked2 } = await import("./knowledge-link-mgg482z6.js");
33320
33931
  if (isLinked2(directory)) {
33321
- const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-yb3pvhcs.js");
33932
+ const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-jhz9hme9.js");
33322
33933
  let config;
33323
33934
  try {
33324
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-twwb61bh.js");
33935
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-4zevsvaa.js");
33325
33936
  const loaded = loadPluginConfigWithMeta2(directory);
33326
33937
  config = KnowledgeConfigSchema2.parse(loaded.config.knowledge ?? {});
33327
33938
  } catch {
33328
33939
  config = KnowledgeConfigSchema2.parse({});
33329
33940
  }
33330
33941
  const { cohortConfigFingerprint: cohortConfigFingerprint2 } = await import("./config-fingerprint-v22xh5a2.js");
33331
- const { buildConfigFingerprintInput: buildConfigFingerprintInput2, readCohortConfigFingerprint } = await import("./curation-policy-x19e8bqc.js");
33942
+ const { buildConfigFingerprintInput: buildConfigFingerprintInput2, readCohortConfigFingerprint } = await import("./curation-policy-9vv7v5rf.js");
33332
33943
  const currentFp = cohortConfigFingerprint2(buildConfigFingerprintInput2(config));
33333
33944
  const cohortFp = await readCohortConfigFingerprint(directory);
33334
33945
  configMatch = cohortFp === null ? null : currentFp === cohortFp;
@@ -33735,7 +34346,7 @@ async function checkConfigBackups(directory) {
33735
34346
  }
33736
34347
  async function checkGitRepository(directory) {
33737
34348
  try {
33738
- if (!existsSync31(directory) || !statSync10(directory).isDirectory()) {
34349
+ if (!existsSync31(directory) || !statSync11(directory).isDirectory()) {
33739
34350
  return {
33740
34351
  name: "Git Repository",
33741
34352
  status: "\u274C",
@@ -34604,7 +35215,7 @@ async function handleDoctorCommand(directory, args) {
34604
35215
  const result = runConfigDoctor(config, directory);
34605
35216
  let output;
34606
35217
  if (enableAutoFix && result.hasAutoFixableIssues) {
34607
- const { runConfigDoctorWithFixes } = await import("./config-doctor-sd7x5bts.js");
35218
+ const { runConfigDoctorWithFixes } = await import("./config-doctor-yd866pd5.js");
34608
35219
  const fixResult = await runConfigDoctorWithFixes(directory, config, true, {
34609
35220
  applyLossy: true
34610
35221
  });
@@ -35544,7 +36155,7 @@ async function handleEvidenceCommand(directory, args) {
35544
36155
  return formatTaskEvidenceMarkdown(evidenceData);
35545
36156
  }
35546
36157
  async function handleEvidenceSummaryCommand(directory) {
35547
- const { buildEvidenceSummary } = await import("./evidence-summary-service-xma4aagr.js");
36158
+ const { buildEvidenceSummary } = await import("./evidence-summary-service-8gw74j8g.js");
35548
36159
  const artifact = await buildEvidenceSummary(directory);
35549
36160
  if (!artifact) {
35550
36161
  return "No plan found. Run `/swarm plan` to check plan status.";
@@ -35828,7 +36439,7 @@ init_zod();
35828
36439
 
35829
36440
  // src/mutation/engine.ts
35830
36441
  import { spawnSync as spawnSync4 } from "child_process";
35831
- import { unlinkSync as unlinkSync6, writeFileSync as writeFileSync11 } from "fs";
36442
+ import { unlinkSync as unlinkSync7, writeFileSync as writeFileSync12 } from "fs";
35832
36443
  import * as path57 from "path";
35833
36444
  init_git_executable();
35834
36445
 
@@ -36098,7 +36709,7 @@ async function executeMutation(patch, testCommand, testFiles, workingDir, option
36098
36709
  const safeId = patch.id.replace(/[^a-zA-Z0-9_-]/g, "_");
36099
36710
  patchFile = path57.join(workingDir, `.mutation_patch_${safeId}.diff`);
36100
36711
  try {
36101
- writeFileSync11(patchFile, patch.patch);
36712
+ writeFileSync12(patchFile, patch.patch);
36102
36713
  } catch (writeErr) {
36103
36714
  error2 = `Failed to write patch file: ${writeErr}`;
36104
36715
  outcome = "error";
@@ -36200,7 +36811,7 @@ async function executeMutation(patch, testCommand, testFiles, workingDir, option
36200
36811
  revertError = new Error(`Failed to revert mutation ${patch.id}: ${revertErr}. Working tree may be dirty.`);
36201
36812
  }
36202
36813
  try {
36203
- unlinkSync6(patchFile);
36814
+ unlinkSync7(patchFile);
36204
36815
  } catch (_unlinkErr) {}
36205
36816
  }
36206
36817
  }
@@ -40479,12 +41090,12 @@ var _internals54 = {
40479
41090
 
40480
41091
  // src/session/snapshot-writer.ts
40481
41092
  import {
40482
- closeSync as closeSync8,
41093
+ closeSync as closeSync9,
40483
41094
  existsSync as existsSync38,
40484
41095
  fsyncSync as fsyncSync2,
40485
41096
  mkdirSync as mkdirSync20,
40486
- openSync as openSync8,
40487
- unlinkSync as unlinkSync8
41097
+ openSync as openSync9,
41098
+ unlinkSync as unlinkSync9
40488
41099
  } from "fs";
40489
41100
  import { rename as fsRename } from "fs/promises";
40490
41101
  import * as path64 from "path";
@@ -40648,18 +41259,18 @@ async function writeSnapshot(directory, state) {
40648
41259
  const tempPath = `${resolvedPath}.tmp.${Date.now()}.${Math.random().toString(36).slice(2)}`;
40649
41260
  await bunWrite(tempPath, content);
40650
41261
  try {
40651
- const fd = openSync8(tempPath, "r+");
41262
+ const fd = openSync9(tempPath, "r+");
40652
41263
  try {
40653
41264
  fsyncSync2(fd);
40654
41265
  } finally {
40655
- closeSync8(fd);
41266
+ closeSync9(fd);
40656
41267
  }
40657
41268
  } catch {}
40658
41269
  try {
40659
41270
  await renameWithTransientRetry(tempPath, resolvedPath);
40660
41271
  } finally {
40661
41272
  try {
40662
- unlinkSync8(tempPath);
41273
+ unlinkSync9(tempPath);
40663
41274
  } catch {}
40664
41275
  }
40665
41276
  invalidateCachedArtifact(resolvedPath);
@@ -40861,7 +41472,7 @@ async function handleHistoryCommand(directory, _args) {
40861
41472
  }
40862
41473
  // src/knowledge/hive-quarantine.ts
40863
41474
  init_package();
40864
- import { createHash as createHash16, createHmac, randomBytes, randomUUID as randomUUID9 } from "crypto";
41475
+ import { createHash as createHash17, createHmac, randomBytes, randomUUID as randomUUID9 } from "crypto";
40865
41476
  import {
40866
41477
  chmod,
40867
41478
  copyFile as copyFile2,
@@ -40894,7 +41505,7 @@ function serializeCanonical(value) {
40894
41505
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${serializeCanonical(v)}`).join(",")}}`;
40895
41506
  }
40896
41507
  function sha256Hex(content) {
40897
- return createHash16("sha256").update(content, "utf-8").digest("hex");
41508
+ return createHash17("sha256").update(content, "utf-8").digest("hex");
40898
41509
  }
40899
41510
  var QUARANTINE_SECRET_FILE = "hive-quarantine.key";
40900
41511
  async function readQuarantineSecret() {
@@ -43354,7 +43965,7 @@ var MIN_MAX_CYCLES = 1;
43354
43965
  var MAX_MAX_CYCLES = 5;
43355
43966
  async function readLatestLoopState(directory) {
43356
43967
  try {
43357
- const { readdirSync: readdirSync9, statSync: statSync14, readFileSync: readFileSync33 } = await import("fs");
43968
+ const { readdirSync: readdirSync9, statSync: statSync15, readFileSync: readFileSync33 } = await import("fs");
43358
43969
  const loopDir = `${directory}/.swarm/loop`;
43359
43970
  let latestMtime = 0;
43360
43971
  let latestPath = null;
@@ -43365,7 +43976,7 @@ async function readLatestLoopState(directory) {
43365
43976
  continue;
43366
43977
  const statePath = `${loopDir}/${entry.name}/state.json`;
43367
43978
  try {
43368
- const mtime = statSync14(statePath).mtimeMs;
43979
+ const mtime = statSync15(statePath).mtimeMs;
43369
43980
  if (mtime > latestMtime) {
43370
43981
  latestMtime = mtime;
43371
43982
  latestPath = statePath;
@@ -43988,13 +44599,13 @@ function parseJsonObject(candidate) {
43988
44599
  init_schema();
43989
44600
  // src/memory/reflection-service.ts
43990
44601
  import {
43991
- closeSync as closeSync9,
44602
+ closeSync as closeSync10,
43992
44603
  existsSync as existsSync42,
43993
44604
  fstatSync,
43994
- openSync as openSync9,
43995
- readSync as readSync6,
44605
+ openSync as openSync10,
44606
+ readSync as readSync7,
43996
44607
  realpathSync as realpathSync8,
43997
- statSync as statSync15
44608
+ statSync as statSync16
43998
44609
  } from "fs";
43999
44610
  var import_proper_lockfile8 = __toESM(require_proper_lockfile(), 1);
44000
44611
 
@@ -47215,12 +47826,12 @@ var workspaceCache = new Map;
47215
47826
 
47216
47827
  // src/tools/repo-graph/freshness.ts
47217
47828
  init_package();
47218
- import { createHash as createHash17 } from "crypto";
47829
+ import { createHash as createHash18 } from "crypto";
47219
47830
  import * as fsPromises3 from "fs/promises";
47220
47831
  import * as path74 from "path";
47221
47832
  var REPO_GRAPH_FINGERPRINT_FILENAME = "repo-graph.fingerprint.json";
47222
47833
  var FINGERPRINT_SCHEMA_VERSION = 1;
47223
- var EXTRACTOR_STAMP = createHash17("sha256").update(`${package_default.version}\x00${GRAPH_SCHEMA_VERSION}`).digest("hex");
47834
+ var EXTRACTOR_STAMP = createHash18("sha256").update(`${package_default.version}\x00${GRAPH_SCHEMA_VERSION}`).digest("hex");
47224
47835
  var MAX_FINGERPRINT_BYTES = 24 * 1024 * 1024;
47225
47836
  var MAX_FINGERPRINT_ENTRIES = 100256;
47226
47837
  var MAX_RELATIVE_PATH_LENGTH = 4096;
@@ -47244,7 +47855,7 @@ function normalizedExcludes(options) {
47244
47855
  return [...new Set((options?.excludeDirs ?? []).filter(Boolean))].sort((a, b) => a.localeCompare(b));
47245
47856
  }
47246
47857
  function exclusionStamp(options) {
47247
- return createHash17("sha256").update(JSON.stringify({
47858
+ return createHash18("sha256").update(JSON.stringify({
47248
47859
  excludeDirs: normalizedExcludes(options),
47249
47860
  followSymlinks: options?.followSymlinks ?? false
47250
47861
  })).digest("hex");
@@ -47461,12 +48072,12 @@ function readReflectionDigest(directory) {
47461
48072
  return null;
47462
48073
  let fd;
47463
48074
  try {
47464
- fd = openSync9(filePath, "r");
48075
+ fd = openSync10(filePath, "r");
47465
48076
  const size = fstatSync(fd).size;
47466
48077
  if (size <= 0 || size > MAX_INJECTION_READ_BYTES)
47467
48078
  return null;
47468
48079
  const bytes = Buffer.alloc(size);
47469
- const read = readSync6(fd, bytes, 0, size, 0);
48080
+ const read = readSync7(fd, bytes, 0, size, 0);
47470
48081
  if (read !== size)
47471
48082
  return null;
47472
48083
  return JSON.parse(bytes.toString("utf-8"));
@@ -47474,7 +48085,7 @@ function readReflectionDigest(directory) {
47474
48085
  return null;
47475
48086
  } finally {
47476
48087
  if (fd !== undefined)
47477
- closeSync9(fd);
48088
+ closeSync10(fd);
47478
48089
  }
47479
48090
  }
47480
48091
  function readDeadAnchorMemoryIds(directory) {
@@ -48152,7 +48763,7 @@ init_schema();
48152
48763
 
48153
48764
  // src/memory/memory-family-migration.ts
48154
48765
  var import_proper_lockfile9 = __toESM(require_proper_lockfile(), 1);
48155
- import { copyFileSync as copyFileSync4, existsSync as existsSync44, readFileSync as readFileSync34, unlinkSync as unlinkSync10 } from "fs";
48766
+ import { copyFileSync as copyFileSync4, existsSync as existsSync44, readFileSync as readFileSync34, unlinkSync as unlinkSync11 } from "fs";
48156
48767
  import { mkdir as mkdir22, rename as rename8 } from "fs/promises";
48157
48768
  import * as path77 from "path";
48158
48769
  init_logger();
@@ -48415,10 +49026,10 @@ async function mergeStagedSqlite(destStoragePath, stagedPath) {
48415
49026
  }
48416
49027
  db.close();
48417
49028
  try {
48418
- unlinkSync10(stagedPath);
49029
+ unlinkSync11(stagedPath);
48419
49030
  for (const suffix of ["-wal", "-shm"]) {
48420
49031
  try {
48421
- unlinkSync10(`${stagedPath}${suffix}`);
49032
+ unlinkSync11(`${stagedPath}${suffix}`);
48422
49033
  } catch {}
48423
49034
  }
48424
49035
  } catch {}
@@ -53169,7 +53780,7 @@ function getTestFilesFromConvention(sourceFiles, workingDir = process.cwd()) {
53169
53780
  const absoluteFile = resolveWorkspacePath(file, workingDir);
53170
53781
  const relativeFile = path84.relative(workingDir, absoluteFile);
53171
53782
  const basename20 = path84.basename(absoluteFile);
53172
- const dirname36 = path84.dirname(absoluteFile);
53783
+ const dirname37 = path84.dirname(absoluteFile);
53173
53784
  const preferRelativeOutput = !path84.isAbsolute(file);
53174
53785
  if (isConventionTestFilePath(relativeFile) || isConventionTestFilePath(file)) {
53175
53786
  dedupePush(testFiles, toWorkspaceOutputPath(absoluteFile, workingDir, preferRelativeOutput));
@@ -53185,7 +53796,7 @@ function getTestFilesFromConvention(sourceFiles, workingDir = process.cwd()) {
53185
53796
  const colocatedCandidates = [
53186
53797
  ...genericTestNames,
53187
53798
  ...languageSpecificTestNames
53188
- ].map((candidateName) => path84.join(dirname36, candidateName));
53799
+ ].map((candidateName) => path84.join(dirname37, candidateName));
53189
53800
  const testDirectoryNames = [
53190
53801
  basename20,
53191
53802
  ...genericTestNames,
@@ -53194,7 +53805,7 @@ function getTestFilesFromConvention(sourceFiles, workingDir = process.cwd()) {
53194
53805
  const repoLevelDirectories = getRepoLevelCandidateDirectories(workingDir, relativeFile, ext);
53195
53806
  const possibleTestFiles = [
53196
53807
  ...colocatedCandidates,
53197
- ...TEST_DIRECTORY_NAMES.flatMap((dirName) => testDirectoryNames.map((candidateName) => path84.join(dirname36, dirName, candidateName))),
53808
+ ...TEST_DIRECTORY_NAMES.flatMap((dirName) => testDirectoryNames.map((candidateName) => path84.join(dirname37, dirName, candidateName))),
53198
53809
  ...repoLevelDirectories.flatMap((candidateDir) => testDirectoryNames.map((candidateName) => path84.join(candidateDir, candidateName)))
53199
53810
  ];
53200
53811
  for (const testFile of possibleTestFiles) {
@@ -55772,7 +56383,7 @@ async function handleQaGatesCommand(directory, args, sessionID) {
55772
56383
 
55773
56384
  // src/workflow/stage-a-repair.ts
55774
56385
  import { appendFile as appendFile10, mkdir as mkdir24, readdir as readdir7 } from "fs/promises";
55775
- import { dirname as dirname36 } from "path";
56386
+ import { dirname as dirname37 } from "path";
55776
56387
  init_logger();
55777
56388
  var MAX_STAGE_A_REPAIR_SCAN = 200;
55778
56389
  var RETRYABLE_EVENT_CODES = new Set(["EBUSY", "EPERM"]);
@@ -55785,7 +56396,7 @@ async function appendStageARepairEvent(directory, payload) {
55785
56396
  `;
55786
56397
  try {
55787
56398
  const eventsPath = validateSwarmPath(directory, "events.jsonl");
55788
- await mkdir24(dirname36(eventsPath), { recursive: true });
56399
+ await mkdir24(dirname37(eventsPath), { recursive: true });
55789
56400
  await appendFile10(eventsPath, line, "utf-8");
55790
56401
  } catch (error2) {
55791
56402
  const code = error2.code;
@@ -57197,7 +57808,7 @@ import * as fs46 from "fs";
57197
57808
  import * as path96 from "path";
57198
57809
 
57199
57810
  // src/review/diff-source.ts
57200
- import { createHash as createHash18 } from "crypto";
57811
+ import { createHash as createHash19 } from "crypto";
57201
57812
  import * as fs40 from "fs";
57202
57813
  import * as path90 from "path";
57203
57814
  init_git_executable();
@@ -57609,7 +58220,7 @@ function uniqueSkipCodes(skipReasons) {
57609
58220
  return [...new Set(skipReasons.map((item) => item.code))].sort();
57610
58221
  }
57611
58222
  function hashManifestPayload(payload) {
57612
- return createHash18("sha256").update(JSON.stringify(payload), "utf8").digest("hex");
58223
+ return createHash19("sha256").update(JSON.stringify(payload), "utf8").digest("hex");
57613
58224
  }
57614
58225
  function parseObjectFormat(stdout) {
57615
58226
  const objectFormat = stdout.trim();
@@ -57697,7 +58308,7 @@ function hashWorkingTreeIdentity(root, rawPath, budget) {
57697
58308
  if (fileBytes > budget.remainingBytes) {
57698
58309
  return deadlineExceeded(`working-tree content identity exceeded the ${WORKTREE_IDENTITY_TOTAL_BYTES}-byte aggregate cap`);
57699
58310
  }
57700
- const hash2 = createHash18("sha256");
58311
+ const hash2 = createHash19("sha256");
57701
58312
  const buffer = Buffer.alloc(64 * 1024);
57702
58313
  let offset = 0;
57703
58314
  while (offset < fileBytes) {
@@ -58277,8 +58888,8 @@ async function collectReviewDiff(options) {
58277
58888
  canonicalText,
58278
58889
  fileListFallback: fileListFallback ?? null
58279
58890
  });
58280
- const scopeHash = createHash18("sha256").update(hashPayload, "utf8").digest("hex");
58281
- const reviewContentHash = createHash18("sha256").update(JSON.stringify({
58891
+ const scopeHash = createHash19("sha256").update(hashPayload, "utf8").digest("hex");
58892
+ const reviewContentHash = createHash19("sha256").update(JSON.stringify({
58282
58893
  selector,
58283
58894
  canonicalText,
58284
58895
  fileListFallback: fileListFallback ?? null
@@ -58791,7 +59402,7 @@ function buildApprovedReceipt(opts) {
58791
59402
  init_schema();
58792
59403
 
58793
59404
  // src/review/finding-validator.ts
58794
- import { createHash as createHash20 } from "crypto";
59405
+ import { createHash as createHash21 } from "crypto";
58795
59406
  init_schema();
58796
59407
  var MAX_VALIDATOR_FALLBACK_MODELS = FALLBACK_MODELS_MAX;
58797
59408
  function canonicalFindingPayload(finding) {
@@ -58817,7 +59428,7 @@ function canonicalizeValidationCandidates(findings) {
58817
59428
  line_start: finding.line_start,
58818
59429
  line_end: finding.line_end
58819
59430
  };
58820
- const findingId = createHash20("sha256").update(canonicalFindingPayload(normalized), "utf8").digest("hex");
59431
+ const findingId = createHash21("sha256").update(canonicalFindingPayload(normalized), "utf8").digest("hex");
58821
59432
  const existing = candidates.get(findingId);
58822
59433
  if (existing) {
58823
59434
  existing.duplicate_count += "duplicate_count" in finding && finding.duplicate_count > 1 ? finding.duplicate_count : 1;
@@ -59098,7 +59709,7 @@ import * as path93 from "path";
59098
59709
  init_git_executable();
59099
59710
 
59100
59711
  // src/hooks/reviewer-scope-file-fingerprint.ts
59101
- import { createHash as createHash21 } from "crypto";
59712
+ import { createHash as createHash22 } from "crypto";
59102
59713
  import * as fs42 from "fs";
59103
59714
  import * as path92 from "path";
59104
59715
  var RETRYABLE_CAPTURE_FAILURE_CODES = new Set([
@@ -59384,7 +59995,7 @@ function captureReviewerScopeFileFingerprint(directory, file, options = {}) {
59384
59995
  retryable: true
59385
59996
  };
59386
59997
  }
59387
- const hash2 = createHash21("sha256");
59998
+ const hash2 = createHash22("sha256");
59388
59999
  const chunk = Buffer.alloc(REVIEWER_SCOPE_CAPTURE_CHUNK_BYTES);
59389
60000
  let totalBytes = 0;
59390
60001
  for (;; ) {
@@ -59904,11 +60515,11 @@ var _internals82 = {
59904
60515
  };
59905
60516
 
59906
60517
  // src/review/evidence.ts
59907
- import { createHash as createHash22 } from "crypto";
60518
+ import { createHash as createHash23 } from "crypto";
59908
60519
  import * as fs44 from "fs";
59909
60520
  import * as path94 from "path";
59910
60521
  function computeAutoReviewManifestHash(manifest) {
59911
- return createHash22("sha256").update(JSON.stringify({
60522
+ return createHash23("sha256").update(JSON.stringify({
59912
60523
  schema_version: manifest.schema_version,
59913
60524
  content_hash: manifest.content_hash,
59914
60525
  plan_requirements_hash: manifest.plan_requirements_hash,
@@ -59995,7 +60606,7 @@ async function computePlanRequirementsHash(directory) {
59995
60606
  return plan ? computeReviewPlanRequirementsHash(plan) : "plan:none";
59996
60607
  }
59997
60608
  function computeAutoReviewPolicyDigest(config) {
59998
- return createHash22("sha256").update(JSON.stringify({
60609
+ return createHash23("sha256").update(JSON.stringify({
59999
60610
  mode: config.final_review.mode,
60000
60611
  min_confidence: config.min_confidence,
60001
60612
  structured_findings: config.structured_findings,
@@ -60041,7 +60652,7 @@ async function loadReviewRequirementsPlan(directory) {
60041
60652
  return replayed.plan;
60042
60653
  }
60043
60654
  function computeReviewPlanRequirementsHash(plan) {
60044
- return createHash22("sha256").update(JSON.stringify({
60655
+ return createHash23("sha256").update(JSON.stringify({
60045
60656
  schema_version: plan.schema_version,
60046
60657
  title: plan.title,
60047
60658
  swarm: plan.swarm,
@@ -62042,25 +62653,25 @@ import {
62042
62653
  existsSync as existsSync56,
62043
62654
  mkdirSync as mkdirSync27,
62044
62655
  readFileSync as readFileSync42,
62045
- renameSync as renameSync14,
62046
- unlinkSync as unlinkSync18,
62047
- writeFileSync as writeFileSync16
62656
+ renameSync as renameSync15,
62657
+ unlinkSync as unlinkSync19,
62658
+ writeFileSync as writeFileSync17
62048
62659
  } from "fs";
62049
62660
  import * as path100 from "path";
62050
62661
 
62051
62662
  // src/services/skill-optimizer/store.ts
62052
- import { createHash as createHash23, randomUUID as randomUUID12 } from "crypto";
62663
+ import { createHash as createHash24, randomUUID as randomUUID12 } from "crypto";
62053
62664
  import {
62054
- closeSync as closeSync16,
62665
+ closeSync as closeSync17,
62055
62666
  existsSync as existsSync55,
62056
62667
  fsyncSync as fsyncSync3,
62057
62668
  mkdirSync as mkdirSync26,
62058
- openSync as openSync16,
62669
+ openSync as openSync17,
62059
62670
  readFileSync as readFileSync41,
62060
- renameSync as renameSync13,
62061
- statSync as statSync19,
62062
- unlinkSync as unlinkSync17,
62063
- writeFileSync as writeFileSync15,
62671
+ renameSync as renameSync14,
62672
+ statSync as statSync20,
62673
+ unlinkSync as unlinkSync18,
62674
+ writeFileSync as writeFileSync16,
62064
62675
  writeFileSync as writeFileSyncAsync
62065
62676
  } from "fs";
62066
62677
  import * as path99 from "path";
@@ -62074,10 +62685,10 @@ function canonicalJson3(value) {
62074
62685
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson3(v)}`).join(",")}}`;
62075
62686
  }
62076
62687
  function computeStateHash(value) {
62077
- return createHash23("sha256").update(canonicalJson3(value), "utf8").digest("hex");
62688
+ return createHash24("sha256").update(canonicalJson3(value), "utf8").digest("hex");
62078
62689
  }
62079
62690
  function computeContentHash2(content) {
62080
- return createHash23("sha256").update(content, "utf8").digest("hex");
62691
+ return createHash24("sha256").update(content, "utf8").digest("hex");
62081
62692
  }
62082
62693
  function computeEventHash(event) {
62083
62694
  return computeStateHash({
@@ -62124,18 +62735,18 @@ function ensureCandidateDir(directory, skillSlug, candidateId2) {
62124
62735
  return dir;
62125
62736
  }
62126
62737
  function writeFileFsyncedThenRename(tempPath, targetPath, data) {
62127
- const fd = openSync16(tempPath, "w");
62738
+ const fd = openSync17(tempPath, "w");
62128
62739
  try {
62129
- writeFileSync15(fd, data, "utf8");
62740
+ writeFileSync16(fd, data, "utf8");
62130
62741
  fsyncSync3(fd);
62131
62742
  } finally {
62132
- closeSync16(fd);
62743
+ closeSync17(fd);
62133
62744
  }
62134
62745
  try {
62135
- renameSync13(tempPath, targetPath);
62746
+ renameSync14(tempPath, targetPath);
62136
62747
  } catch (err) {
62137
62748
  try {
62138
- unlinkSync17(tempPath);
62749
+ unlinkSync18(tempPath);
62139
62750
  } catch {}
62140
62751
  throw err;
62141
62752
  }
@@ -62145,10 +62756,10 @@ var _internals86 = {
62145
62756
  writeFileFsyncedThenRename,
62146
62757
  writeFileSync: writeFileSyncAsync,
62147
62758
  readFileSync: readFileSync41,
62148
- renameSync: renameSync13,
62149
- unlinkSync: unlinkSync17,
62759
+ renameSync: renameSync14,
62760
+ unlinkSync: unlinkSync18,
62150
62761
  existsSync: existsSync55,
62151
- statSync: statSync19
62762
+ statSync: statSync20
62152
62763
  };
62153
62764
  async function appendEvent2(directory, eventInput) {
62154
62765
  assertProjectRoot(directory);
@@ -62407,9 +63018,9 @@ function writeSkillFileAtomic(targetPath, content) {
62407
63018
  }
62408
63019
  }
62409
63020
  var _internals87 = {
62410
- writeFileSync: writeFileSync16,
62411
- renameSync: renameSync14,
62412
- unlinkSync: unlinkSync18
63021
+ writeFileSync: writeFileSync17,
63022
+ renameSync: renameSync15,
63023
+ unlinkSync: unlinkSync19
62413
63024
  };
62414
63025
  async function activateCandidate(input) {
62415
63026
  const skillPath = path100.join(input.directory, ".opencode", "skills", "generated", input.skillSlug, "SKILL.md");
@@ -62498,7 +63109,7 @@ async function rollbackCandidate(input) {
62498
63109
 
62499
63110
  // src/services/skill-optimizer/controller.ts
62500
63111
  import { randomUUID as randomUUID13 } from "crypto";
62501
- import { existsSync as existsSync58, mkdirSync as mkdirSync28, readFileSync as readFileSync44, writeFileSync as writeFileSync17 } from "fs";
63112
+ import { existsSync as existsSync58, mkdirSync as mkdirSync28, readFileSync as readFileSync44, writeFileSync as writeFileSync18 } from "fs";
62502
63113
  import * as path103 from "path";
62503
63114
 
62504
63115
  // src/evaluation/pr-review-recovery.ts
@@ -63183,8 +63794,8 @@ async function prepareCandidatePayloads(inputRoot, candidateId2, skillSlug, base
63183
63794
  mkdirSync28(payloadSubdir, { recursive: true });
63184
63795
  const baselinePayloadRel = path103.join("candidates", candidateId2, "baseline.md");
63185
63796
  const candidatePayloadRel = path103.join("candidates", candidateId2, "candidate.md");
63186
- writeFileSync17(path103.join(payloadSubdir, "baseline.md"), baselineContent, "utf8");
63187
- writeFileSync17(path103.join(payloadSubdir, "candidate.md"), candidateContent, "utf8");
63797
+ writeFileSync18(path103.join(payloadSubdir, "baseline.md"), baselineContent, "utf8");
63798
+ writeFileSync18(path103.join(payloadSubdir, "candidate.md"), candidateContent, "utf8");
63188
63799
  const { computeCandidateInputContentHash: computeCandidateInputContentHash2 } = await import("./hashing-mjwn6j4y.js");
63189
63800
  const baseline = {
63190
63801
  v: 1,
@@ -63429,7 +64040,7 @@ async function runValidationWithTransientRetry(input, candidateContent, baseline
63429
64040
  if (!input.dispatcher) {
63430
64041
  throw new Error("no evaluation dispatcher available (cannot run validation)");
63431
64042
  }
63432
- const { createModelEvaluationExecutor: createModelEvaluationExecutor2 } = await import("./runner-e7z9cf5y.js");
64043
+ const { createModelEvaluationExecutor: createModelEvaluationExecutor2 } = await import("./runner-rcnpm510.js");
63433
64044
  const executor = createModelEvaluationExecutor2(input.dispatcher, input.sessionId);
63434
64045
  const result = await _internals91.evaluateCandidateV1({
63435
64046
  projectRoot: input.directory,
@@ -63518,7 +64129,7 @@ function writeConvergenceState(directory, nonImprovements) {
63518
64129
  const dir = path103.dirname(path103.join(directory, CONVERGENCE_FILE));
63519
64130
  if (!existsSync58(dir))
63520
64131
  mkdirSync28(dir, { recursive: true });
63521
- writeFileSync17(path103.join(directory, CONVERGENCE_FILE), JSON.stringify({ nonImprovements }), "utf8");
64132
+ writeFileSync18(path103.join(directory, CONVERGENCE_FILE), JSON.stringify({ nonImprovements }), "utf8");
63522
64133
  }
63523
64134
  async function runOptimizationLoop(input) {
63524
64135
  const rounds = [];
@@ -63573,7 +64184,7 @@ async function runOptimizationLoop(input) {
63573
64184
  }
63574
64185
 
63575
64186
  // src/services/skill-optimizer/skill-eval-tasks.ts
63576
- import { existsSync as existsSync59, mkdirSync as mkdirSync29, writeFileSync as writeFileSync18 } from "fs";
64187
+ import { existsSync as existsSync59, mkdirSync as mkdirSync29, writeFileSync as writeFileSync19 } from "fs";
63577
64188
  import * as path104 from "path";
63578
64189
  var DEFAULT_SKILL_EVAL_TASKS = [
63579
64190
  {
@@ -63618,12 +64229,12 @@ function buildSkillEvalTasks(args) {
63618
64229
  if (!existsSync59(taskDir))
63619
64230
  mkdirSync29(taskDir, { recursive: true });
63620
64231
  const instructionPath = path104.join("skill-eval", spec.id, "instruction.md");
63621
- writeFileSync18(path104.join(args.inputRoot, instructionPath), `${spec.instruction}
64232
+ writeFileSync19(path104.join(args.inputRoot, instructionPath), `${spec.instruction}
63622
64233
  `, "utf8");
63623
64234
  const envRelPath = path104.join("skill-eval", spec.id, "environment.md");
63624
- writeFileSync18(path104.join(args.inputRoot, envRelPath), spec.environmentBody, "utf8");
64235
+ writeFileSync19(path104.join(args.inputRoot, envRelPath), spec.environmentBody, "utf8");
63625
64236
  const phraseSpecPath = path104.join("skill-eval", spec.id, "phrase-spec.json");
63626
- writeFileSync18(path104.join(args.inputRoot, phraseSpecPath), JSON.stringify({
64237
+ writeFileSync19(path104.join(args.inputRoot, phraseSpecPath), JSON.stringify({
63627
64238
  required_phrases: spec.requiredPhrases,
63628
64239
  forbidden_phrases: spec.forbiddenPhrases
63629
64240
  }), "utf8");
@@ -65335,7 +65946,7 @@ function buildDetailedHelp(commandName, entry) {
65335
65946
  async function handleHelpCommand(ctx) {
65336
65947
  const targetCommand = ctx.args.join(" ");
65337
65948
  if (!targetCommand) {
65338
- const { buildHelpText } = await import("./index-e3caa7ng.js");
65949
+ const { buildHelpText } = await import("./index-qqawmxe7.js");
65339
65950
  return buildHelpText();
65340
65951
  }
65341
65952
  const tokens = targetCommand.split(/\s+/);
@@ -65344,7 +65955,7 @@ async function handleHelpCommand(ctx) {
65344
65955
  return _internals94.buildDetailedHelp(resolved.key, resolved.entry);
65345
65956
  }
65346
65957
  const similar = _internals94.findSimilarCommands(targetCommand);
65347
- const { buildHelpText: fullHelp } = await import("./index-e3caa7ng.js");
65958
+ const { buildHelpText: fullHelp } = await import("./index-qqawmxe7.js");
65348
65959
  if (similar.length > 0) {
65349
65960
  return `Command '/swarm ${targetCommand}' not found.
65350
65961
 
@@ -65521,7 +66132,7 @@ var COMMAND_REGISTRY = {
65521
66132
  },
65522
66133
  "guardrail explain": {
65523
66134
  handler: async (ctx) => {
65524
- const { handleGuardrailExplain } = await import("./guardrail-explain-ppzg0xz9.js");
66135
+ const { handleGuardrailExplain } = await import("./guardrail-explain-50cp8k3r.js");
65525
66136
  return handleGuardrailExplain(ctx.directory, ctx.args);
65526
66137
  },
65527
66138
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -65531,7 +66142,7 @@ var COMMAND_REGISTRY = {
65531
66142
  },
65532
66143
  "guardrail-explain": {
65533
66144
  handler: async (ctx) => {
65534
- const { handleGuardrailExplain } = await import("./guardrail-explain-ppzg0xz9.js");
66145
+ const { handleGuardrailExplain } = await import("./guardrail-explain-50cp8k3r.js");
65535
66146
  return handleGuardrailExplain(ctx.directory, ctx.args);
65536
66147
  },
65537
66148
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -65541,7 +66152,7 @@ var COMMAND_REGISTRY = {
65541
66152
  },
65542
66153
  "guardrail-log": {
65543
66154
  handler: async (ctx) => {
65544
- const { handleGuardrailLog } = await import("./guardrail-log-xexwz93q.js");
66155
+ const { handleGuardrailLog } = await import("./guardrail-log-jazq10gt.js");
65545
66156
  return handleGuardrailLog(ctx.directory, ctx.args);
65546
66157
  },
65547
66158
  description: "Read the guardrail decision log (use --blocks-only for blocks)",
@@ -67740,6 +68351,15 @@ Reply with a single fenced JSON block. No prose outside the block.
67740
68351
  "areasOfUncertainty": [
67741
68352
  "What I'm not sure about, in plain language."
67742
68353
  ],
68354
+ "claims": [
68355
+ {
68356
+ "subject": "The specific question or decision this claim is about",
68357
+ "statement": "Your position on that subject, in one or two sentences",
68358
+ "stance": "support",
68359
+ "confidence": 0.8,
68360
+ "evidence": ["URL or source reference, if any"]
68361
+ }
68362
+ ],
67743
68363
  "disagreementTopics": []
67744
68364
  }
67745
68365
  \`\`\`
@@ -67747,6 +68367,7 @@ Reply with a single fenced JSON block. No prose outside the block.
67747
68367
  Notes:
67748
68368
  - \`searchQueries\` is optional \u2014 list queries you would have run if you had web access (the architect uses these for audit), or omit / leave empty if none.
67749
68369
  - \`sources\` MUST come from the RESEARCH CONTEXT only. Copy title/url/snippet/query verbatim. Never invent sources.
68370
+ - \`claims\` is optional but strongly encouraged (max 8): list your key positions as bounded structured claims. Use one of these \`stance\` values exactly: "support" (the position holds), "oppose" (the position is wrong \u2014 a contrary position), "alternative" (a different option is better \u2014 a contrary position), "concern" (risk flagged without taking a side), "neutral" (no position). Claims make contrary positions detectable even without explicit disagreement phrasing.
67750
68371
  - For Round 1: leave \`disagreementTopics\` as []. For Round 2: list the specific disagreement topics this response addresses.`;
67751
68372
  var HARD_RULES = `================================================================
67752
68373
  HARD RULES
@@ -72390,7 +73011,17 @@ async function buildRehydrationCache(directory) {
72390
73011
  }
72391
73012
  }
72392
73013
  const evidenceMap = await readGateEvidenceFromDisk(directory);
72393
- _rehydrationCache = { planTaskStates, evidenceMap };
73014
+ let councilConfig;
73015
+ try {
73016
+ councilConfig = loadPluginConfig(directory).council;
73017
+ } catch {
73018
+ councilConfig = undefined;
73019
+ }
73020
+ _rehydrationCache = {
73021
+ planTaskStates,
73022
+ evidenceMap,
73023
+ taskIdentityContext: { plan, councilConfig }
73024
+ };
72394
73025
  }
72395
73026
  function applyRehydrationCache(session) {
72396
73027
  if (!_rehydrationCache) {
@@ -72405,7 +73036,7 @@ function applyRehydrationCache(session) {
72405
73036
  if (!session.taskCouncilApproved) {
72406
73037
  session.taskCouncilApproved = new Map;
72407
73038
  }
72408
- const { planTaskStates, evidenceMap } = _rehydrationCache;
73039
+ const { planTaskStates, evidenceMap, taskIdentityContext } = _rehydrationCache;
72409
73040
  for (const [taskId, planState] of planTaskStates) {
72410
73041
  const existingState = session.taskWorkflowStates.get(taskId);
72411
73042
  const existingCache = ensureTaskWorkflowCache(session).get(taskId);
@@ -72444,6 +73075,21 @@ function applyRehydrationCache(session) {
72444
73075
  session.taskCouncilApproved.delete(taskId);
72445
73076
  continue;
72446
73077
  }
73078
+ const rawIdentityDigest = council.identity_digest;
73079
+ if (typeof rawIdentityDigest !== "string" || !/^[a-f0-9]{64}$/.test(rawIdentityDigest)) {
73080
+ session.taskCouncilApproved.delete(taskId);
73081
+ continue;
73082
+ }
73083
+ const expectedIdentity = computeCouncilReviewIdentity({
73084
+ level: "task",
73085
+ scope: { kind: "task", taskId },
73086
+ plan: taskIdentityContext.plan,
73087
+ config: taskIdentityContext.councilConfig
73088
+ });
73089
+ if (rawIdentityDigest !== expectedIdentity.identityDigest) {
73090
+ session.taskCouncilApproved.delete(taskId);
73091
+ continue;
73092
+ }
72447
73093
  const councilWorkflow = getTaskWorkflowSnapshot(evidence2);
72448
73094
  if (!councilWorkflow.authoritative || council.workflowGeneration !== councilWorkflow.generation || councilWorkflow.state !== "pre_check_passed") {
72449
73095
  session.taskCouncilApproved.delete(taskId);
@@ -72548,7 +73194,7 @@ function getDisplayBudget() {
72548
73194
  async function rehydratePrSubscriptions(sessionID, directory) {
72549
73195
  const map = new Map;
72550
73196
  try {
72551
- const { listActive: listActive2 } = await import("./pr-subscriptions-2xn238xt.js");
73197
+ const { listActive: listActive2 } = await import("./pr-subscriptions-js5v2xr6.js");
72552
73198
  const records = await listActive2(directory);
72553
73199
  for (const record of records) {
72554
73200
  if (record.sessionID !== sessionID)
@@ -72964,7 +73610,7 @@ function isLaneOwnedByCurrentSession(branchName, expectedSessionId) {
72964
73610
  return extracted === expectedSessionId;
72965
73611
  }
72966
73612
  async function inspectStandardWorktreeCollisionOwnership(identity) {
72967
- const collisionOwnership = await import("./worktree-collision-ownership-2jtg2my1.js");
73613
+ const collisionOwnership = await import("./worktree-collision-ownership-vt0jzmdt.js");
72968
73614
  return collisionOwnership.inspectStandardWorktreeCollisionOwnership(identity);
72969
73615
  }
72970
73616
  async function precreateStandardWorktreeSession(args) {
@@ -73112,7 +73758,7 @@ async function precreateStandardWorktreeSession(args) {
73112
73758
  const laneProfile = computeLaneRuntimeProfile(worktreeConfig.runtime_isolation, laneIndex, provisionResult.worktreePath);
73113
73759
  if (laneProfile) {
73114
73760
  try {
73115
- const { writeLaneProfileToDiskReal } = await import("./core-17febkvw.js");
73761
+ const { writeLaneProfileToDiskReal } = await import("./core-nc9a9g5m.js");
73116
73762
  await writeLaneProfileToDiskReal(provisionResult.worktreePath, laneProfile.laneIndex, laneProfile.envOverrides);
73117
73763
  } catch {}
73118
73764
  }
@@ -73208,7 +73854,7 @@ async function preserveBackgroundWorktreeOwnershipForCallId(callID) {
73208
73854
  }
73209
73855
  const session = Buffer.from(dispatch.handle.sessionId, "utf8").toString("base64url");
73210
73856
  const lane = Buffer.from(dispatch.handle.id, "utf8").toString("base64url");
73211
- const callDigest = createHash24("sha256").update(callID).digest("hex").slice(0, 12);
73857
+ const callDigest = createHash25("sha256").update(callID).digest("hex").slice(0, 12);
73212
73858
  const tag = `swarm-preserved-owner/${session}/${lane}/${callDigest}`;
73213
73859
  let tagProc;
73214
73860
  try {
@@ -73770,7 +74416,7 @@ async function finishStandardWorktreeDispatch(directory, dispatch, config, callI
73770
74416
  }
73771
74417
  clearWorktreeMergeStatus(statusKey);
73772
74418
  try {
73773
- const { removeLaneProfileFromDiskReal } = await import("./core-17febkvw.js");
74419
+ const { removeLaneProfileFromDiskReal } = await import("./core-nc9a9g5m.js");
73774
74420
  await removeLaneProfileFromDiskReal(dispatch.handle.worktreePath, dispatch.laneIndex);
73775
74421
  } catch {}
73776
74422
  const state = serializationStateBySessionID.get(dispatch.parentSessionID);