opencode-swarm 7.121.3 → 7.122.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/cli/{curation-policy-10wnhpwn.js → curation-policy-cj1tpzr5.js} +2 -2
  2. package/dist/cli/{curator-ed91r7rw.js → curator-3rze3pd4.js} +8 -8
  3. package/dist/cli/{curator-llm-factory-q9veqj3h.js → curator-llm-factory-8rg0f77t.js} +8 -8
  4. package/dist/cli/{guardrail-explain-0vcaa7hj.js → guardrail-explain-hdsxa2c5.js} +9 -9
  5. package/dist/cli/{hive-promoter-dg6fk563.js → hive-promoter-dh38qd9m.js} +8 -8
  6. package/dist/cli/{index-5a3xsnzg.js → index-3r1w7xky.js} +1 -1
  7. package/dist/cli/{index-35xyj7gn.js → index-3sx27bxt.js} +26 -3
  8. package/dist/cli/{index-qad0m9bz.js → index-68aggz0v.js} +1 -1
  9. package/dist/cli/{index-fs2q8jyf.js → index-ahxrne50.js} +709 -550
  10. package/dist/cli/{index-x4fwtd59.js → index-gr7ssnj9.js} +3 -3
  11. package/dist/cli/{index-db82jxt7.js → index-j33zb3cx.js} +2 -2
  12. package/dist/cli/{index-g9eg7z93.js → index-jzpv74mq.js} +9 -9
  13. package/dist/cli/{index-0f800qg7.js → index-ny13nr0x.js} +2 -2
  14. package/dist/cli/{index-j8349ac0.js → index-rkd6qwjh.js} +1 -1
  15. package/dist/cli/{index-ft6jw816.js → index-xdsj4qtd.js} +3 -3
  16. package/dist/cli/index.js +8 -8
  17. package/dist/cli/{knowledge-escalator-8ajq1fhb.js → knowledge-escalator-sya06p12.js} +3 -3
  18. package/dist/cli/{knowledge-events-2sjy3aa7.js → knowledge-events-xzps61a9.js} +3 -1
  19. package/dist/cli/{knowledge-store-27cesthc.js → knowledge-store-qg66a93n.js} +1 -1
  20. package/dist/cli/{knowledge-validator-9keh3p8j.js → knowledge-validator-gar6wv4f.js} +4 -4
  21. package/dist/cli/{scan-cursor-qmsmmg1b.js → scan-cursor-nx5y5k7r.js} +2 -2
  22. package/dist/cli/{skill-generator-hkyxdc3j.js → skill-generator-nt5qxafq.js} +5 -5
  23. package/dist/db/index.d.ts +4 -0
  24. package/dist/db/sqlite-loader.d.ts +78 -0
  25. package/dist/hooks/cohort-cache.d.ts +44 -0
  26. package/dist/hooks/hive-promoter.d.ts +4 -3
  27. package/dist/hooks/host-boundary.d.ts +147 -0
  28. package/dist/hooks/incremental-verify.d.ts +3 -0
  29. package/dist/hooks/knowledge-events.d.ts +25 -2
  30. package/dist/hooks/knowledge-injector.d.ts +9 -1
  31. package/dist/hooks/knowledge-receipt-validator.d.ts +98 -0
  32. package/dist/hooks/micro-reflector.d.ts +3 -0
  33. package/dist/hooks/pr-auto-subscribe.d.ts +3 -0
  34. package/dist/hooks/promotion-evidence-store.d.ts +33 -0
  35. package/dist/index.js +362 -355
  36. package/dist/services/knowledge-diagnostics.d.ts +12 -0
  37. package/dist/session/snapshot-writer.d.ts +5 -0
  38. package/dist/state.d.ts +11 -0
  39. package/package.json +3 -2
@@ -95,15 +95,15 @@ import {
95
95
  retireSkill,
96
96
  selectCandidateEntries,
97
97
  syncBundledProjectSkillsIfMissingAsync
98
- } from "./index-x4fwtd59.js";
98
+ } from "./index-gr7ssnj9.js";
99
99
  import {
100
100
  readRecentEscalations
101
- } from "./index-ft6jw816.js";
101
+ } from "./index-xdsj4qtd.js";
102
102
  import {
103
103
  alreadyCuratedThisGeneration,
104
104
  claimNextScanBatch,
105
105
  resolveCohortId
106
- } from "./index-j8349ac0.js";
106
+ } from "./index-rkd6qwjh.js";
107
107
  import {
108
108
  CURATOR_INIT_PROMPT,
109
109
  CURATOR_PHASE_PROMPT,
@@ -136,11 +136,11 @@ import {
136
136
  validateActionability,
137
137
  validateActionableFields,
138
138
  validateLesson
139
- } from "./index-db82jxt7.js";
139
+ } from "./index-j33zb3cx.js";
140
140
  import {
141
141
  authorizeCuration,
142
142
  buildConfigFingerprintInput
143
- } from "./index-5a3xsnzg.js";
143
+ } from "./index-3r1w7xky.js";
144
144
  import {
145
145
  cohortConfigFingerprint
146
146
  } from "./index-rtry5xyf.js";
@@ -170,7 +170,7 @@ import {
170
170
  transactFile,
171
171
  transactKnowledge,
172
172
  wordBigrams
173
- } from "./index-0f800qg7.js";
173
+ } from "./index-ny13nr0x.js";
174
174
  import {
175
175
  MAX_EVENT_LOG_ENTRIES,
176
176
  _internals,
@@ -180,7 +180,7 @@ import {
180
180
  recordHiveKnowledgeEvent,
181
181
  recordKnowledgeEvent,
182
182
  resolveKnowledgeEventsPath
183
- } from "./index-35xyj7gn.js";
183
+ } from "./index-3sx27bxt.js";
184
184
  import {
185
185
  resolveHiveDataDir,
186
186
  resolveHiveEventsPath,
@@ -279,16 +279,123 @@ import { createHash } from "crypto";
279
279
 
280
280
  // src/db/project-db.ts
281
281
  import { existsSync, mkdirSync } from "fs";
282
- import { createRequire } from "module";
283
282
  import { join, resolve } from "path";
283
+
284
+ // src/db/sqlite-loader.ts
285
+ import { createRequire } from "module";
286
+ function createNodeDatabaseCtor(DatabaseSyncCtor) {
287
+
288
+ class NodeSqliteDatabase {
289
+ raw;
290
+ stmts = new Map;
291
+ savepointCounter = 0;
292
+ constructor(filename) {
293
+ this.raw = new DatabaseSyncCtor(filename, { allowExtension: true });
294
+ }
295
+ statement(sql) {
296
+ let stmt = this.stmts.get(sql);
297
+ if (!stmt) {
298
+ stmt = this.raw.prepare(sql);
299
+ this.stmts.set(sql, stmt);
300
+ }
301
+ return stmt;
302
+ }
303
+ run(sql, ...rest) {
304
+ if (rest.length === 0) {
305
+ this.raw.exec(sql);
306
+ return;
307
+ }
308
+ const params = rest.length === 1 && Array.isArray(rest[0]) ? rest[0] : rest;
309
+ return this.statement(sql).run(...params);
310
+ }
311
+ query(sql) {
312
+ const stmt = this.statement(sql);
313
+ return {
314
+ get: (...params) => stmt.get(...params),
315
+ all: (...params) => stmt.all(...params),
316
+ iterate: (...params) => stmt.iterate(...params)
317
+ };
318
+ }
319
+ get inTransaction() {
320
+ return this.raw.isTransaction;
321
+ }
322
+ transaction(fn) {
323
+ return (...args) => {
324
+ if (this.raw.isTransaction) {
325
+ const sp = `swarm_sp_${this.savepointCounter++}`;
326
+ this.raw.exec(`SAVEPOINT ${sp}`);
327
+ try {
328
+ const result = fn(...args);
329
+ this.raw.exec(`RELEASE ${sp}`);
330
+ return result;
331
+ } catch (err) {
332
+ try {
333
+ this.raw.exec(`ROLLBACK TO ${sp}`);
334
+ this.raw.exec(`RELEASE ${sp}`);
335
+ } catch {}
336
+ throw err;
337
+ }
338
+ }
339
+ this.raw.exec("BEGIN");
340
+ try {
341
+ const result = fn(...args);
342
+ this.raw.exec("COMMIT");
343
+ return result;
344
+ } catch (err) {
345
+ try {
346
+ this.raw.exec("ROLLBACK");
347
+ } catch {}
348
+ throw err;
349
+ }
350
+ };
351
+ }
352
+ loadExtension(path) {
353
+ this.raw.enableLoadExtension(true);
354
+ try {
355
+ this.raw.loadExtension(path);
356
+ } finally {
357
+ this.raw.enableLoadExtension(false);
358
+ }
359
+ }
360
+ close() {
361
+ this.stmts.clear();
362
+ this.raw.close();
363
+ }
364
+ }
365
+ return NodeSqliteDatabase;
366
+ }
284
367
  var _DatabaseCtor = null;
368
+ var _internals4 = {
369
+ requireModule(id) {
370
+ return createRequire(import.meta.url)(id);
371
+ },
372
+ reset() {
373
+ _DatabaseCtor = null;
374
+ }
375
+ };
285
376
  function loadDatabaseCtor() {
286
377
  if (_DatabaseCtor)
287
378
  return _DatabaseCtor;
288
- const req = createRequire(import.meta.url);
289
- _DatabaseCtor = req("bun:sqlite").Database;
290
- return _DatabaseCtor;
379
+ let bunError;
380
+ try {
381
+ const mod = _internals4.requireModule("bun:sqlite");
382
+ _DatabaseCtor = mod.Database;
383
+ return _DatabaseCtor;
384
+ } catch (err) {
385
+ bunError = err;
386
+ }
387
+ try {
388
+ const mod = _internals4.requireModule("node:sqlite");
389
+ _DatabaseCtor = createNodeDatabaseCtor(mod.DatabaseSync);
390
+ return _DatabaseCtor;
391
+ } catch (nodeError) {
392
+ const bunMsg = bunError instanceof Error ? bunError.message : String(bunError);
393
+ const nodeMsg = nodeError instanceof Error ? nodeError.message : String(nodeError);
394
+ throw new Error("opencode-swarm: no SQLite driver available. This build needs Bun " + "(bun:sqlite) or Node.js 22.13+ (node:sqlite). " + `bun:sqlite: ${bunMsg}; node:sqlite: ${nodeMsg}`);
395
+ }
291
396
  }
397
+
398
+ // src/db/project-db.ts
292
399
  var MIGRATIONS = [
293
400
  {
294
401
  version: 1,
@@ -371,7 +478,7 @@ function getProjectDb(directory) {
371
478
  }
372
479
 
373
480
  // src/db/qa-gate-profile.ts
374
- var _internals4 = {
481
+ var _internals5 = {
375
482
  getProfile,
376
483
  getOrCreateProfile,
377
484
  setGates,
@@ -447,7 +554,7 @@ function hasAnyProfileWithEnabledGate(directory, gate) {
447
554
  return false;
448
555
  }
449
556
  function getOrCreateProfile(directory, planId, projectType) {
450
- const existing = _internals4.getProfile(directory, planId);
557
+ const existing = _internals5.getProfile(directory, planId);
451
558
  if (existing)
452
559
  return existing;
453
560
  const db = getProjectDb(directory);
@@ -463,14 +570,14 @@ function getOrCreateProfile(directory, planId, projectType) {
463
570
  throw err;
464
571
  }
465
572
  }
466
- const after = _internals4.getProfile(directory, planId);
573
+ const after = _internals5.getProfile(directory, planId);
467
574
  if (!after) {
468
575
  throw new Error(`Failed to create or load QA gate profile for plan_id=${planId}`);
469
576
  }
470
577
  return after;
471
578
  }
472
579
  function setGates(directory, planId, gates) {
473
- const current = _internals4.getProfile(directory, planId);
580
+ const current = _internals5.getProfile(directory, planId);
474
581
  if (!current) {
475
582
  throw new Error(`No QA gate profile found for plan_id=${planId} \u2014 call getOrCreateProfile first`);
476
583
  }
@@ -494,7 +601,7 @@ function setGates(directory, planId, gates) {
494
601
  JSON.stringify(merged),
495
602
  planId
496
603
  ]);
497
- const updated = _internals4.getProfile(directory, planId);
604
+ const updated = _internals5.getProfile(directory, planId);
498
605
  if (!updated) {
499
606
  throw new Error(`Failed to re-read QA gate profile after update for plan_id=${planId}`);
500
607
  }
@@ -524,7 +631,7 @@ init_logger();
524
631
  init_executor();
525
632
  init_logger();
526
633
  // src/worktree/merge.ts
527
- var _internals5 = {
634
+ var _internals6 = {
528
635
  bunSpawn,
529
636
  platform: process.platform,
530
637
  sleep: (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)),
@@ -534,7 +641,7 @@ var _internals5 = {
534
641
  };
535
642
  var MERGE_TIMEOUT_MS = 30000;
536
643
  async function runGit(args, cwd, timeoutMs = MERGE_TIMEOUT_MS) {
537
- const proc = _internals5.bunSpawn(["git", ...args], {
644
+ const proc = _internals6.bunSpawn(["git", ...args], {
538
645
  cwd,
539
646
  timeout: timeoutMs,
540
647
  stdin: "ignore",
@@ -2419,7 +2526,7 @@ class EmbeddingVersionMismatchError extends Error {
2419
2526
  }
2420
2527
 
2421
2528
  // src/memory/embeddings/local-provider.ts
2422
- var _internals7 = {
2529
+ var _internals8 = {
2423
2530
  resolveEmbeddingCacheDir() {
2424
2531
  let base;
2425
2532
  if (process.platform === "win32") {
@@ -2440,7 +2547,7 @@ var _internals7 = {
2440
2547
  }
2441
2548
  };
2442
2549
  function resolveEmbeddingCacheDir() {
2443
- return _internals7.resolveEmbeddingCacheDir();
2550
+ return _internals8.resolveEmbeddingCacheDir();
2444
2551
  }
2445
2552
 
2446
2553
  class LocalEmbeddingProvider {
@@ -2858,14 +2965,6 @@ function toJsonl(values) {
2858
2965
  }
2859
2966
 
2860
2967
  // src/memory/sqlite-provider.ts
2861
- var _DatabaseCtor2 = null;
2862
- function loadDatabaseCtor2() {
2863
- if (_DatabaseCtor2)
2864
- return _DatabaseCtor2;
2865
- const req = createRequire4(import.meta.url);
2866
- _DatabaseCtor2 = req("bun:sqlite").Database;
2867
- return _DatabaseCtor2;
2868
- }
2869
2968
  var RECALL_CANDIDATE_LIMIT = 1000;
2870
2969
  var FTS_SCHEMA_MIGRATION_NAME = "create_memory_fts5_shadow_index";
2871
2970
  var FTS_TABLE_NAME = "memory_items_fts";
@@ -3110,7 +3209,7 @@ class SQLiteMemoryProvider {
3110
3209
  async doInitialize() {
3111
3210
  const dbPath = this.databasePath();
3112
3211
  mkdirSync4(path5.dirname(dbPath), { recursive: true });
3113
- const Db = loadDatabaseCtor2();
3212
+ const Db = loadDatabaseCtor();
3114
3213
  this.db = new Db(dbPath);
3115
3214
  try {
3116
3215
  this.db.run("PRAGMA journal_mode = WAL;");
@@ -3778,7 +3877,7 @@ class SQLiteMemoryProvider {
3778
3877
  }
3779
3878
  }
3780
3879
  getStoredModelVersion() {
3781
- const row = this.requireDb().query(`SELECT value FROM embedding_config WHERE key = 'model_version' LIMIT 1`).get("model_version");
3880
+ const row = this.requireDb().query(`SELECT value FROM embedding_config WHERE key = ? LIMIT 1`).get("model_version");
3782
3881
  return row?.value ?? null;
3783
3882
  }
3784
3883
  async selectDenseCandidates(request, queryEmbedding) {
@@ -3850,7 +3949,7 @@ class SQLiteMemoryProvider {
3850
3949
  }
3851
3950
  backfillScopeKeys() {
3852
3951
  const db = this.requireDb();
3853
- const metaRow = db.query("SELECT value FROM _meta WHERE key = 'scope_key_backfilled'").get("scope_key_backfilled");
3952
+ const metaRow = db.query("SELECT value FROM _meta WHERE key = ?").get("scope_key_backfilled");
3854
3953
  if (metaRow?.value === "1")
3855
3954
  return;
3856
3955
  const rows = db.query("SELECT id, record_json, scope_key FROM memory_items").all();
@@ -3875,7 +3974,7 @@ class SQLiteMemoryProvider {
3875
3974
  }
3876
3975
  backfillRecallRunIds() {
3877
3976
  const db = this.requireDb();
3878
- const metaRow = db.query("SELECT value FROM _meta WHERE key = 'recall_run_id_backfilled'").get("recall_run_id_backfilled");
3977
+ const metaRow = db.query("SELECT value FROM _meta WHERE key = ?").get("recall_run_id_backfilled");
3879
3978
  if (metaRow?.value === "1")
3880
3979
  return;
3881
3980
  const rows = db.query("SELECT id, usage_json FROM memory_recall_usage WHERE run_id IS NULL").all();
@@ -5033,7 +5132,7 @@ async function handleAnalyzeCommand(_directory, args) {
5033
5132
  }
5034
5133
 
5035
5134
  // src/commands/archive.ts
5036
- var _internals8 = {
5135
+ var _internals9 = {
5037
5136
  now: () => new Date
5038
5137
  };
5039
5138
  function artifactLabel(artifact) {
@@ -5047,7 +5146,7 @@ async function handleArchiveCommand(directory, args) {
5047
5146
  const report = await archiveEvidence(directory, maxAgeDays, maxBundles, {
5048
5147
  report: true,
5049
5148
  dryRun,
5050
- now: _internals8.now()
5149
+ now: _internals9.now()
5051
5150
  });
5052
5151
  const evaluationSelected = report.evaluation.selected.map(artifactLabel);
5053
5152
  const evaluationArchived = report.evaluation.archived.map(artifactLabel);
@@ -6618,7 +6717,7 @@ var IPV4_PRIVATE_192 = /^192\.168\./;
6618
6717
  var IPV4_ZERO_NETWORK = /^0\./;
6619
6718
  var IPV6_LINK_LOCAL = /^fe80:/i;
6620
6719
  var IPV6_UNIQUE_LOCAL = /^f[cd][0-9a-f]{2}:/i;
6621
- var _internals9 = {
6720
+ var _internals10 = {
6622
6721
  spawnSync: (cmd, args, options) => {
6623
6722
  const mergedEnv = mergeEnvForChild(options?.env, options?.envOverrides);
6624
6723
  return child_process2.spawnSync(cmd, args, {
@@ -6736,7 +6835,7 @@ function validateAndSanitizeGithubUrl(rawUrl, resource) {
6736
6835
  }
6737
6836
  function detectGitRemote(cwd, laneEnv) {
6738
6837
  try {
6739
- const result = _internals9.spawnSync("git", ["remote", "get-url", "origin"], {
6838
+ const result = _internals10.spawnSync("git", ["remote", "get-url", "origin"], {
6740
6839
  encoding: "utf-8",
6741
6840
  stdio: ["ignore", "pipe", "pipe"],
6742
6841
  timeout: 5000,
@@ -6998,7 +7097,7 @@ function timeoutKillSignal(platform) {
6998
7097
  }
6999
7098
  function killProcess(proc) {
7000
7099
  try {
7001
- proc?.kill(timeoutKillSignal(_internals10.platform()));
7100
+ proc?.kill(timeoutKillSignal(_internals11.platform()));
7002
7101
  } catch {}
7003
7102
  }
7004
7103
  async function runExternalTool(options) {
@@ -7030,7 +7129,7 @@ async function runExternalTool(options) {
7030
7129
  let exitSettled = false;
7031
7130
  let settledExitCode = null;
7032
7131
  try {
7033
- proc = _internals10.bunSpawn([options.executable, ...options.args], {
7132
+ proc = _internals11.bunSpawn([options.executable, ...options.args], {
7034
7133
  cwd: options.cwd,
7035
7134
  env: options.env,
7036
7135
  stdin: "ignore",
@@ -7129,7 +7228,7 @@ async function runExternalTool(options) {
7129
7228
  }
7130
7229
  }
7131
7230
  }
7132
- var _internals10 = {
7231
+ var _internals11 = {
7133
7232
  bunSpawn,
7134
7233
  platform: () => process.platform
7135
7234
  };
@@ -7139,7 +7238,7 @@ init_logger();
7139
7238
  var GIT_TIMEOUT_MS2 = 30000;
7140
7239
  var VALIDATION_TIMEOUT_MS = 5 * 60 * 1000;
7141
7240
  var OUTPUT_LIMIT_BYTES = 12000;
7142
- var _internals11 = {
7241
+ var _internals12 = {
7143
7242
  runExternalTool,
7144
7243
  getDefaultBaseBranch,
7145
7244
  platform: process.platform,
@@ -7150,7 +7249,7 @@ var _internals11 = {
7150
7249
  }
7151
7250
  };
7152
7251
  async function runGit2(args, cwd, timeoutMs = GIT_TIMEOUT_MS2) {
7153
- const result = await _internals11.runExternalTool({
7252
+ const result = await _internals12.runExternalTool({
7154
7253
  executable: "git",
7155
7254
  args,
7156
7255
  cwd,
@@ -7168,7 +7267,7 @@ async function runGit2(args, cwd, timeoutMs = GIT_TIMEOUT_MS2) {
7168
7267
  }
7169
7268
  async function runValidationCommand(cmd, cwd, timeoutMs = VALIDATION_TIMEOUT_MS) {
7170
7269
  const [executable, ...args] = cmd;
7171
- const result = await _internals11.runExternalTool({
7270
+ const result = await _internals12.runExternalTool({
7172
7271
  executable,
7173
7272
  args,
7174
7273
  cwd,
@@ -7196,7 +7295,7 @@ async function getCurrentBranchOrRef(directory) {
7196
7295
  return hashResult.stdout.trim();
7197
7296
  }
7198
7297
  async function setupWorktree(projectRoot, prRef, baseBranch, onWorktreeCreated) {
7199
- const worktreeBase = path13.join(_internals11.osTmpdir(), "swarm-ci-simulate");
7298
+ const worktreeBase = path13.join(_internals12.osTmpdir(), "swarm-ci-simulate");
7200
7299
  const worktreeName = `pr-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
7201
7300
  const worktreePath = path13.join(worktreeBase, worktreeName);
7202
7301
  await fsPromises2.mkdir(worktreeBase, { recursive: true });
@@ -7214,8 +7313,8 @@ async function setupWorktree(projectRoot, prRef, baseBranch, onWorktreeCreated)
7214
7313
  async function cleanupWorktree(worktreePath, projectRoot) {
7215
7314
  const removeResult = await runGit2(["worktree", "remove", "--force", worktreePath], projectRoot);
7216
7315
  try {
7217
- if (_internals11.fs.existsSync(worktreePath)) {
7218
- _internals11.fs.rmSync(worktreePath, { recursive: true, force: true });
7316
+ if (_internals12.fs.existsSync(worktreePath)) {
7317
+ _internals12.fs.rmSync(worktreePath, { recursive: true, force: true });
7219
7318
  }
7220
7319
  } catch {}
7221
7320
  if (removeResult.exitCode !== 0) {
@@ -7297,7 +7396,7 @@ async function handleCiSimulateCommand(directory, args) {
7297
7396
  steps: []
7298
7397
  };
7299
7398
  try {
7300
- const baseBranch = _internals11.getDefaultBaseBranch(directory);
7399
+ const baseBranch = _internals12.getDefaultBaseBranch(directory);
7301
7400
  if (!isSafeGitRef(baseBranch)) {
7302
7401
  throw new Error("Detected default branch is not a safe git reference.");
7303
7402
  }
@@ -8085,7 +8184,7 @@ async function reviseSkill(params) {
8085
8184
  }
8086
8185
  if (!params.delegate) {
8087
8186
  try {
8088
- const revised = _internals12.buildDeterministicRevision(params.currentContent, params.currentVersion, params.violationContexts);
8187
+ const revised = _internals13.buildDeterministicRevision(params.currentContent, params.currentVersion, params.violationContexts);
8089
8188
  const validation = await validateRevisionCandidate(params, revised, "skill_reviser:deterministic");
8090
8189
  if (!validation.passed) {
8091
8190
  return {
@@ -8212,7 +8311,7 @@ async function reviseSkill(params) {
8212
8311
  };
8213
8312
  }
8214
8313
  }
8215
- var _internals12 = {
8314
+ var _internals13 = {
8216
8315
  reviseSkill,
8217
8316
  getSkillVersion,
8218
8317
  buildDeterministicRevision,
@@ -8296,7 +8395,7 @@ function resolveLogPath(directory) {
8296
8395
  function normalizeComplianceVerdict(verdict) {
8297
8396
  return verdict === "violation" ? "violated" : verdict;
8298
8397
  }
8299
- var _internals13 = {
8398
+ var _internals14 = {
8300
8399
  generateId: () => crypto2.randomUUID(),
8301
8400
  appendFileSync: fs6.appendFileSync.bind(fs6),
8302
8401
  readFileSync: fs6.readFileSync.bind(fs6),
@@ -8366,9 +8465,9 @@ function parseFeedbackMarker(raw) {
8366
8465
  function readFeedbackAppliedEntryIds(directory) {
8367
8466
  const resolved = resolveLogPath(directory);
8368
8467
  const processed = new Set;
8369
- if (!_internals13.existsSync(resolved))
8468
+ if (!_internals14.existsSync(resolved))
8370
8469
  return processed;
8371
- const raw = _internals13.readFileSync(resolved, "utf-8");
8470
+ const raw = _internals14.readFileSync(resolved, "utf-8");
8372
8471
  for (const line of raw.split(`
8373
8472
  `)) {
8374
8473
  const trimmed = line.trim();
@@ -8389,15 +8488,15 @@ function appendFeedbackAppliedMarker(directory, processedEntryIds) {
8389
8488
  return;
8390
8489
  const resolved = resolveLogPath(directory);
8391
8490
  const dir = path16.dirname(resolved);
8392
- if (!_internals13.existsSync(dir)) {
8393
- _internals13.mkdirSync(dir, { recursive: true });
8491
+ if (!_internals14.existsSync(dir)) {
8492
+ _internals14.mkdirSync(dir, { recursive: true });
8394
8493
  }
8395
8494
  const marker = {
8396
8495
  type: "feedback_applied",
8397
8496
  timestamp: new Date().toISOString(),
8398
8497
  processedEntryIds: [...new Set(processedEntryIds)]
8399
8498
  };
8400
- _internals13.appendFileSync(resolved, `${JSON.stringify(marker)}
8499
+ _internals14.appendFileSync(resolved, `${JSON.stringify(marker)}
8401
8500
  `, "utf-8");
8402
8501
  }
8403
8502
  function appendSkillUsageEntry(directory, entry) {
@@ -8434,11 +8533,11 @@ function appendSkillUsageEntry(directory, entry) {
8434
8533
  }
8435
8534
  const resolved = validateSwarmPath(directory, "skill-usage.jsonl");
8436
8535
  const dir = path16.dirname(resolved);
8437
- if (!_internals13.existsSync(dir)) {
8438
- _internals13.mkdirSync(dir, { recursive: true });
8536
+ if (!_internals14.existsSync(dir)) {
8537
+ _internals14.mkdirSync(dir, { recursive: true });
8439
8538
  }
8440
8539
  const fullEntry = {
8441
- id: _internals13.generateId(),
8540
+ id: _internals14.generateId(),
8442
8541
  skillPath,
8443
8542
  agentName,
8444
8543
  taskID,
@@ -8448,21 +8547,21 @@ function appendSkillUsageEntry(directory, entry) {
8448
8547
  ...reviewerNotes !== undefined && { reviewerNotes },
8449
8548
  ...skillVersion !== undefined && { skillVersion }
8450
8549
  };
8451
- _internals13.appendFileSync(resolved, `${JSON.stringify(fullEntry)}
8550
+ _internals14.appendFileSync(resolved, `${JSON.stringify(fullEntry)}
8452
8551
  `, "utf-8");
8453
8552
  try {
8454
- const stat2 = _internals13.statSync(resolved);
8553
+ const stat2 = _internals14.statSync(resolved);
8455
8554
  if (stat2.size > SKILL_USAGE_LOG_ROTATE_BYTES) {
8456
- _internals13.pruneSkillUsageLog(directory, SKILL_USAGE_LOG_MAX_ENTRIES_PER_SKILL);
8555
+ _internals14.pruneSkillUsageLog(directory, SKILL_USAGE_LOG_MAX_ENTRIES_PER_SKILL);
8457
8556
  }
8458
8557
  } catch {}
8459
8558
  }
8460
8559
  function readSkillUsageEntries(directory, options) {
8461
8560
  const resolved = resolveLogPath(directory);
8462
- if (!_internals13.existsSync(resolved)) {
8561
+ if (!_internals14.existsSync(resolved)) {
8463
8562
  return [];
8464
8563
  }
8465
- const raw = _internals13.readFileSync(resolved, "utf-8");
8564
+ const raw = _internals14.readFileSync(resolved, "utf-8");
8466
8565
  const entries = [];
8467
8566
  for (const line of raw.split(`
8468
8567
  `)) {
@@ -8505,20 +8604,20 @@ var SKILL_USAGE_LOG_ROTATE_BYTES = 1024 * 1024;
8505
8604
  var SKILL_USAGE_LOG_MAX_ENTRIES_PER_SKILL = 500;
8506
8605
  function readSkillUsageEntriesTail(directory, filters, maxBytes = TAIL_BYTES_DEFAULT) {
8507
8606
  const logPath = resolveLogPath(directory);
8508
- if (!_internals13.existsSync(logPath))
8607
+ if (!_internals14.existsSync(logPath))
8509
8608
  return [];
8510
8609
  try {
8511
8610
  const normalizedMaxBytes = Number.isFinite(maxBytes) ? maxBytes : TAIL_BYTES_DEFAULT;
8512
8611
  const boundedMaxBytes = Math.min(Math.max(1, normalizedMaxBytes), MAX_TAIL_BYTES);
8513
- const stat2 = _internals13.statSync(logPath);
8612
+ const stat2 = _internals14.statSync(logPath);
8514
8613
  const start = Math.max(0, stat2.size - boundedMaxBytes);
8515
- const fd = _internals13.openSync(logPath, "r");
8614
+ const fd = _internals14.openSync(logPath, "r");
8516
8615
  try {
8517
8616
  const readLen = stat2.size - start;
8518
8617
  if (readLen === 0)
8519
8618
  return [];
8520
8619
  const buf = Buffer.alloc(readLen);
8521
- _internals13.readSync(fd, buf, 0, buf.length, start);
8620
+ _internals14.readSync(fd, buf, 0, buf.length, start);
8522
8621
  const content = buf.toString("utf-8");
8523
8622
  let usable;
8524
8623
  if (start > 0) {
@@ -8545,7 +8644,7 @@ function readSkillUsageEntriesTail(directory, filters, maxBytes = TAIL_BYTES_DEF
8545
8644
  }
8546
8645
  return entries;
8547
8646
  } finally {
8548
- _internals13.closeSync(fd);
8647
+ _internals14.closeSync(fd);
8549
8648
  }
8550
8649
  } catch {
8551
8650
  return [];
@@ -8582,10 +8681,10 @@ function computeComplianceByVersion(entries, skillPath) {
8582
8681
  }
8583
8682
  function pruneSkillUsageLog(directory, maxEntriesPerSkill = 500) {
8584
8683
  const resolved = resolveLogPath(directory);
8585
- if (!_internals13.existsSync(resolved)) {
8684
+ if (!_internals14.existsSync(resolved)) {
8586
8685
  return { pruned: 0, remaining: 0 };
8587
8686
  }
8588
- const raw = _internals13.readFileSync(resolved, "utf-8");
8687
+ const raw = _internals14.readFileSync(resolved, "utf-8");
8589
8688
  const lines = raw.split(`
8590
8689
  `);
8591
8690
  const entries = [];
@@ -8615,13 +8714,13 @@ function pruneSkillUsageLog(directory, maxEntriesPerSkill = 500) {
8615
8714
  `).concat(preservedMarkers.length > 0 ? `
8616
8715
  ` : "");
8617
8716
  try {
8618
- _internals13.writeFileSync(tmpPath2, content2, "utf-8");
8619
- _internals13.renameSync(tmpPath2, resolved);
8717
+ _internals14.writeFileSync(tmpPath2, content2, "utf-8");
8718
+ _internals14.renameSync(tmpPath2, resolved);
8620
8719
  } catch (writeErr) {
8621
8720
  const msg = writeErr instanceof Error ? writeErr.message : String(writeErr);
8622
8721
  try {
8623
- if (_internals13.existsSync(tmpPath2)) {
8624
- _internals13.writeFileSync(tmpPath2, "", "utf-8");
8722
+ if (_internals14.existsSync(tmpPath2)) {
8723
+ _internals14.writeFileSync(tmpPath2, "", "utf-8");
8625
8724
  }
8626
8725
  } catch {}
8627
8726
  return { pruned: 0, remaining: 0, error: msg };
@@ -8660,13 +8759,13 @@ function pruneSkillUsageLog(directory, maxEntriesPerSkill = 500) {
8660
8759
  `).concat(`
8661
8760
  `);
8662
8761
  try {
8663
- _internals13.writeFileSync(tmpPath, content, "utf-8");
8664
- _internals13.renameSync(tmpPath, resolved);
8762
+ _internals14.writeFileSync(tmpPath, content, "utf-8");
8763
+ _internals14.renameSync(tmpPath, resolved);
8665
8764
  } catch (writeErr) {
8666
8765
  const msg = writeErr instanceof Error ? writeErr.message : String(writeErr);
8667
8766
  try {
8668
- if (_internals13.existsSync(tmpPath)) {
8669
- _internals13.writeFileSync(tmpPath, "", "utf-8");
8767
+ if (_internals14.existsSync(tmpPath)) {
8768
+ _internals14.writeFileSync(tmpPath, "", "utf-8");
8670
8769
  }
8671
8770
  } catch {}
8672
8771
  return { pruned: 0, remaining: entries.length, error: msg };
@@ -8688,10 +8787,10 @@ async function resolveSourceKnowledgeIds(directory, skillPath) {
8688
8787
  if (!isContained) {
8689
8788
  return [];
8690
8789
  }
8691
- if (!_internals13.existsSync(absolute)) {
8790
+ if (!_internals14.existsSync(absolute)) {
8692
8791
  return [];
8693
8792
  }
8694
- const content = _internals13.readFileSync(absolute, "utf-8");
8793
+ const content = _internals14.readFileSync(absolute, "utf-8");
8695
8794
  return parseGeneratedFromKnowledge(content);
8696
8795
  } catch (err) {
8697
8796
  log("[skill-usage-log] resolveSourceKnowledgeIds failed (fail-open):", err instanceof Error ? err.message : String(err));
@@ -8799,7 +8898,7 @@ var DEFAULT_CURATOR_LLM_TIMEOUT_MS = 300000;
8799
8898
  var MAX_CURATOR_PHASE_DIGESTS = 50;
8800
8899
  var MAX_CURATOR_COMPLIANCE_OBSERVATIONS = 200;
8801
8900
  var MAX_CURATOR_RECOMMENDATIONS = 200;
8802
- var _internals14 = {
8901
+ var _internals15 = {
8803
8902
  parseKnowledgeRecommendations,
8804
8903
  parseKnowledgeRecommendationsWithDiagnostics,
8805
8904
  readCuratorSummary,
@@ -8905,9 +9004,9 @@ ${digest.summary}`).join(`
8905
9004
  async function autoRetireSkills(directory, _curatorKnowledgePath, excludeSlugs) {
8906
9005
  const observations = [];
8907
9006
  try {
8908
- const skillListResult = await _internals14.listSkills(directory);
8909
- const usageEntries = _internals14.readSkillUsageEntries(directory);
8910
- const allArchivedIds = await _internals14.getArchivedKnowledgeIds(directory);
9007
+ const skillListResult = await _internals15.listSkills(directory);
9008
+ const usageEntries = _internals15.readSkillUsageEntries(directory);
9009
+ const allArchivedIds = await _internals15.getArchivedKnowledgeIds(directory);
8911
9010
  for (const active of skillListResult.active) {
8912
9011
  if (excludeSlugs?.has(active.slug))
8913
9012
  continue;
@@ -8929,7 +9028,7 @@ async function autoRetireSkills(directory, _curatorKnowledgePath, excludeSlugs)
8929
9028
  const violationRate = skillUsage.length > 0 ? violations / skillUsage.length : 0;
8930
9029
  if (violationRate > 0.3) {
8931
9030
  const reason = `auto-retire: violation rate ${(violationRate * 100).toFixed(0)}% exceeds 30% threshold`;
8932
- await _internals14.retireSkill(directory, active.slug, reason);
9031
+ await _internals15.retireSkill(directory, active.slug, reason);
8933
9032
  observations.push(`Skill '${active.slug}' auto-retired: ${reason}`);
8934
9033
  warn(`[curator] ${observations[observations.length - 1]}`);
8935
9034
  continue;
@@ -8937,15 +9036,15 @@ async function autoRetireSkills(directory, _curatorKnowledgePath, excludeSlugs)
8937
9036
  let archivedSourceMatched = false;
8938
9037
  if (allArchivedIds.size > 0) {
8939
9038
  try {
8940
- const content = await _internals14.readFileAsync(active.path, "utf-8");
8941
- const sourceIds = _internals14.parseDraftFrontmatter(content)?.sourceKnowledgeIds ?? [];
9039
+ const content = await _internals15.readFileAsync(active.path, "utf-8");
9040
+ const sourceIds = _internals15.parseDraftFrontmatter(content)?.sourceKnowledgeIds ?? [];
8942
9041
  archivedSourceMatched = sourceIds.some((id) => allArchivedIds.has(id));
8943
9042
  } catch {
8944
9043
  archivedSourceMatched = false;
8945
9044
  }
8946
9045
  }
8947
9046
  if (archivedSourceMatched) {
8948
- const result = await _internals14.retireOrMarkStale(directory, path17.dirname(active.path), allArchivedIds);
9047
+ const result = await _internals15.retireOrMarkStale(directory, path17.dirname(active.path), allArchivedIds);
8949
9048
  if (result.action === "retire") {
8950
9049
  observations.push(`Skill '${active.slug}' auto-retired: all source knowledge entries archived`);
8951
9050
  warn(`[curator] ${observations[observations.length - 1]}`);
@@ -9213,7 +9312,7 @@ async function transactCuratorSummary(directory, mutate) {
9213
9312
  const resolvedPath = validateSwarmPath(directory, "curator-summary.json");
9214
9313
  let invoked = false;
9215
9314
  let mutationResult;
9216
- await _internals14.transactFile(resolvedPath, _internals14.readCuratorSummaryState, _internals14.writeCuratorSummaryState, (state) => {
9315
+ await _internals15.transactFile(resolvedPath, _internals15.readCuratorSummaryState, _internals15.writeCuratorSummaryState, (state) => {
9217
9316
  invoked = true;
9218
9317
  const mutation = mutate(state.summary);
9219
9318
  mutationResult = mutation.result;
@@ -9362,8 +9461,8 @@ function checkPhaseCompliance(phaseEvents, agentsDispatched, requiredAgents, pha
9362
9461
  const observations = [];
9363
9462
  const timestamp = new Date().toISOString();
9364
9463
  for (const agent of requiredAgents) {
9365
- const normalizedAgent = _internals14.normalizeAgentName(agent);
9366
- const isDispatched = agentsDispatched.some((a) => _internals14.normalizeAgentName(a) === normalizedAgent);
9464
+ const normalizedAgent = _internals15.normalizeAgentName(agent);
9465
+ const isDispatched = agentsDispatched.some((a) => _internals15.normalizeAgentName(a) === normalizedAgent);
9367
9466
  if (!isDispatched) {
9368
9467
  observations.push({
9369
9468
  phase,
@@ -9382,7 +9481,7 @@ function checkPhaseCompliance(phaseEvents, agentsDispatched, requiredAgents, pha
9382
9481
  if (e.type === "agent.delegation") {
9383
9482
  const agent = e.agent;
9384
9483
  if (agent && typeof agent === "string") {
9385
- const normalized = _internals14.normalizeAgentName(agent);
9484
+ const normalized = _internals15.normalizeAgentName(agent);
9386
9485
  if (normalized === "coder") {
9387
9486
  coderDelegations.push({ event: e, index: i });
9388
9487
  } else if (normalized === "reviewer") {
@@ -9439,7 +9538,7 @@ function checkPhaseCompliance(phaseEvents, agentsDispatched, requiredAgents, pha
9439
9538
  if (e.type === "agent.delegation" && e.agent) {
9440
9539
  const agent = e.agent;
9441
9540
  if (agent && typeof agent === "string") {
9442
- const normalized = _internals14.normalizeAgentName(agent);
9541
+ const normalized = _internals15.normalizeAgentName(agent);
9443
9542
  if (normalized === "sme") {
9444
9543
  smeDelegations.push({ event: e, index: i });
9445
9544
  }
@@ -9463,7 +9562,7 @@ function checkPhaseCompliance(phaseEvents, agentsDispatched, requiredAgents, pha
9463
9562
  }
9464
9563
  async function runCuratorInit(directory, config, llmDelegate) {
9465
9564
  try {
9466
- const priorSummary = await _internals14.readCuratorSummary(directory);
9565
+ const priorSummary = await _internals15.readCuratorSummary(directory);
9467
9566
  const knowledgePath = resolveSwarmKnowledgePath(directory);
9468
9567
  const allEntries = await readKnowledge(knowledgePath);
9469
9568
  const highConfidenceEntries = allEntries.filter((e) => typeof e.confidence === "number" && e.confidence >= config.min_knowledge_confidence);
@@ -9504,7 +9603,7 @@ async function runCuratorInit(directory, config, llmDelegate) {
9504
9603
  const maxContextChars = config.max_summary_tokens * 2;
9505
9604
  briefingParts.push(contextMd.slice(0, maxContextChars));
9506
9605
  }
9507
- const latestPostMortemDigest = _internals14.readLatestPostMortemDigest(directory);
9606
+ const latestPostMortemDigest = _internals15.readLatestPostMortemDigest(directory);
9508
9607
  if (latestPostMortemDigest) {
9509
9608
  briefingParts.push(`
9510
9609
  ## Latest Post-Mortem`);
@@ -9591,7 +9690,7 @@ Could not load prior session context.`,
9591
9690
  }
9592
9691
  async function runCuratorPhase(directory, phase, agentsDispatched, config, knowledgeConfig, llmDelegate) {
9593
9692
  try {
9594
- const priorSummary = await _internals14.readCuratorSummary(directory);
9693
+ const priorSummary = await _internals15.readCuratorSummary(directory);
9595
9694
  if (priorSummary?.phase_digests.some((d) => d.phase === phase)) {
9596
9695
  const existingDigest = priorSummary.phase_digests.find((d) => d.phase === phase);
9597
9696
  return {
@@ -9604,10 +9703,10 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
9604
9703
  };
9605
9704
  }
9606
9705
  const eventsJsonlContent = await readSwarmFileAsync(directory, "events.jsonl");
9607
- const phaseEvents = eventsJsonlContent ? _internals14.filterPhaseEvents(eventsJsonlContent, phase) : [];
9706
+ const phaseEvents = eventsJsonlContent ? _internals15.filterPhaseEvents(eventsJsonlContent, phase) : [];
9608
9707
  const contextMd = await readSwarmFileAsync(directory, "context.md");
9609
9708
  const requiredAgents = ["reviewer", "test_engineer"];
9610
- const complianceObservations = _internals14.checkPhaseCompliance(phaseEvents, agentsDispatched, requiredAgents, phase);
9709
+ const complianceObservations = _internals15.checkPhaseCompliance(phaseEvents, agentsDispatched, requiredAgents, phase);
9611
9710
  const plan = await loadPlanJsonOnly(directory);
9612
9711
  const phaseData = plan?.phases.find((p) => p.id === phase);
9613
9712
  const tasksCompleted = phaseData ? phaseData.tasks.filter((t) => t.status === "completed").length : 0;
@@ -9631,7 +9730,7 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
9631
9730
  timestamp: new Date().toISOString(),
9632
9731
  summary: `Phase ${phase} completed. ${tasksCompleted}/${tasksTotal} tasks completed. ${complianceObservations.length} compliance observations.`,
9633
9732
  agents_used: [
9634
- ...new Set(agentsDispatched.map((a) => _internals14.normalizeAgentName(a)))
9733
+ ...new Set(agentsDispatched.map((a) => _internals15.normalizeAgentName(a)))
9635
9734
  ],
9636
9735
  tasks_completed: tasksCompleted,
9637
9736
  tasks_total: tasksTotal,
@@ -9683,7 +9782,7 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
9683
9782
  clearTimeout(timer);
9684
9783
  }
9685
9784
  if (llmOutput?.trim()) {
9686
- const parsed = _internals14.parseKnowledgeRecommendationsWithDiagnostics(llmOutput);
9785
+ const parsed = _internals15.parseKnowledgeRecommendationsWithDiagnostics(llmOutput);
9687
9786
  for (const diagnostic of parsed.diagnostics) {
9688
9787
  warn("[curator] skipped malformed recommendation line", {
9689
9788
  phase,
@@ -9728,7 +9827,7 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
9728
9827
  }
9729
9828
  const sessionId = `session-${Date.now()}`;
9730
9829
  const now = new Date().toISOString();
9731
- const summaryUpdated = await _internals14.mergeCuratorPhaseSummary(directory, {
9830
+ const summaryUpdated = await _internals15.mergeCuratorPhaseSummary(directory, {
9732
9831
  phase,
9733
9832
  phaseDigest,
9734
9833
  complianceObservations,
@@ -9759,7 +9858,7 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
9759
9858
  }
9760
9859
  if (config.skill_generation_enabled === true && skillCandidates.length > 0) {
9761
9860
  try {
9762
- const skillModule = await import("./skill-generator-hkyxdc3j.js");
9861
+ const skillModule = await import("./skill-generator-nt5qxafq.js");
9763
9862
  for (const cand of skillCandidates) {
9764
9863
  if (cand.confidence < (config.min_skill_confidence ?? DEFAULT_SKILL_MIN_CONFIDENCE)) {
9765
9864
  continue;
@@ -9777,8 +9876,8 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
9777
9876
  }
9778
9877
  const revisedSlugs = new Set;
9779
9878
  try {
9780
- const skillListResult = await _internals14.listSkills(directory);
9781
- const usageEntries = _internals14.readSkillUsageEntries(directory);
9879
+ const skillListResult = await _internals15.listSkills(directory);
9880
+ const usageEntries = _internals15.readSkillUsageEntries(directory);
9782
9881
  let revisionCallsThisPhase = 0;
9783
9882
  for (const active of skillListResult.active) {
9784
9883
  if (revisionCallsThisPhase >= MAX_REVISION_CALLS_PER_PHASE)
@@ -9802,8 +9901,8 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
9802
9901
  const violations = skillUsage.filter((e) => e.complianceVerdict === "violated").length;
9803
9902
  const violationRate = violations / skillUsage.length;
9804
9903
  if (violationRate > REVISION_VIOLATION_THRESHOLD && violationRate <= 0.3) {
9805
- const content = await _internals14.readFileAsync(active.path, "utf-8");
9806
- const fm = _internals14.parseDraftFrontmatter(content);
9904
+ const content = await _internals15.readFileAsync(active.path, "utf-8");
9905
+ const fm = _internals15.parseDraftFrontmatter(content);
9807
9906
  if (fm && fm.skillOrigin === "promoted_external")
9808
9907
  continue;
9809
9908
  const currentVersion = fm?.version ?? 1;
@@ -9814,7 +9913,7 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
9814
9913
  reviewerNotes: e.reviewerNotes,
9815
9914
  timestamp: e.timestamp
9816
9915
  }));
9817
- const result2 = await _internals14.reviseSkill({
9916
+ const result2 = await _internals15.reviseSkill({
9818
9917
  directory,
9819
9918
  slug: active.slug,
9820
9919
  skillPath: active.path,
@@ -9833,7 +9932,7 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
9833
9932
  } catch (revisionErr) {
9834
9933
  warn(`[curator] skill revision check failed: ${revisionErr instanceof Error ? revisionErr.message : String(revisionErr)}`);
9835
9934
  }
9836
- const autoRetireObservations = await _internals14.autoRetireSkills(directory, curatorKnowledgePath, revisedSlugs);
9935
+ const autoRetireObservations = await _internals15.autoRetireSkills(directory, curatorKnowledgePath, revisedSlugs);
9837
9936
  if (autoRetireObservations.length > 0) {
9838
9937
  const retireNote = ` [${autoRetireObservations.length} skill(s) auto-retired]`;
9839
9938
  phaseDigest.summary += retireNote;
@@ -9928,7 +10027,7 @@ async function applyCuratorKnowledgeUpdates(directory, recommendations, knowledg
9928
10027
  const knowledgePath = resolveSwarmKnowledgePath(directory);
9929
10028
  const authorizedRevisions = new Map;
9930
10029
  if (validRecommendations.length > 0) {
9931
- const preSnapshot = await _internals14.readKnowledge(knowledgePath);
10030
+ const preSnapshot = await _internals15.readKnowledge(knowledgePath);
9932
10031
  const authorizedRecs = [];
9933
10032
  for (const rec of validRecommendations) {
9934
10033
  if (rec.action !== "archive" && rec.action !== "rewrite") {
@@ -10096,7 +10195,7 @@ async function applyCuratorKnowledgeUpdates(directory, recommendations, knowledg
10096
10195
  } catch {}
10097
10196
  }
10098
10197
  if (contradictedEntries.length > 0 && knowledgeConfig.contradiction_threshold_action === "quarantine") {
10099
- const { maybeQuarantineOnContradiction } = await import("./knowledge-escalator-8ajq1fhb.js");
10198
+ const { maybeQuarantineOnContradiction } = await import("./knowledge-escalator-sya06p12.js");
10100
10199
  for (const { id } of contradictedEntries) {
10101
10200
  try {
10102
10201
  await maybeQuarantineOnContradiction(directory, id, knowledgeConfig.contradiction_quarantine_threshold, knowledgeConfig.contradiction_quarantine_window_days);
@@ -10461,18 +10560,18 @@ async function executePostMortemActions(directory, parsed, options, generation)
10461
10560
  proposals_rejected: 0,
10462
10561
  proposals_skipped: 0
10463
10562
  };
10464
- const knowledgeConfig = options.knowledgeConfig ?? await _internals15.loadDefaultKnowledgeConfig(directory);
10563
+ const knowledgeConfig = options.knowledgeConfig ?? await _internals16.loadDefaultKnowledgeConfig(directory);
10465
10564
  if (parsed.recommendations.length > 0) {
10466
10565
  try {
10467
- const knowledgeResult = await _internals15.applyCuratorKnowledgeUpdates(directory, parsed.recommendations, knowledgeConfig, generation);
10566
+ const knowledgeResult = await _internals16.applyCuratorKnowledgeUpdates(directory, parsed.recommendations, knowledgeConfig, generation);
10468
10567
  result.knowledge_applied = knowledgeResult.applied;
10469
10568
  result.knowledge_skipped = knowledgeResult.skipped;
10470
10569
  } catch (err) {
10471
10570
  warnings.push(`Post-mortem knowledge actions failed: ${err instanceof Error ? err.message : String(err)}`);
10472
10571
  }
10473
10572
  try {
10474
- const entries = await _internals15.readSwarmKnowledge(directory);
10475
- const hiveResult = await _internals15.checkHivePromotions(entries, knowledgeConfig, directory);
10573
+ const entries = await _internals16.readSwarmKnowledge(directory);
10574
+ const hiveResult = await _internals16.checkHivePromotions(entries, knowledgeConfig, directory);
10476
10575
  result.hive_promotions = hiveResult.new_promotions;
10477
10576
  result.hive_encounters_incremented = hiveResult.encounters_incremented;
10478
10577
  result.hive_advancements = hiveResult.advancements;
@@ -10482,7 +10581,7 @@ async function executePostMortemActions(directory, parsed, options, generation)
10482
10581
  }
10483
10582
  if (parsed.queueTriage.length > 0) {
10484
10583
  try {
10485
- const proposalResult = await _internals15.applyProposalTriage(directory, parsed.queueTriage);
10584
+ const proposalResult = await _internals16.applyProposalTriage(directory, parsed.queueTriage);
10486
10585
  result.proposals_approved = proposalResult.approved.length;
10487
10586
  result.proposals_rejected = proposalResult.rejected.length;
10488
10587
  result.proposals_skipped = proposalResult.skipped.length;
@@ -10495,7 +10594,7 @@ async function executePostMortemActions(directory, parsed, options, generation)
10495
10594
  async function verifyPostMortemKnowledgeActions(directory, recommendations) {
10496
10595
  if (recommendations.length === 0)
10497
10596
  return [];
10498
- const entries = await _internals15.readSwarmKnowledge(directory);
10597
+ const entries = await _internals16.readSwarmKnowledge(directory);
10499
10598
  const activeEntries = entries.filter((entry) => isActiveStatus(entry.status));
10500
10599
  const exactIds = new Set(activeEntries.map((entry) => entry.id));
10501
10600
  const prefixMatches = new Map;
@@ -10596,7 +10695,7 @@ async function repairPostMortemActions(llmOutput, diagnostics, options) {
10596
10695
  ].join(`
10597
10696
  `);
10598
10697
  const repaired = await options.llmDelegate("", repairPrompt, ac.signal);
10599
- const parsed = _internals15.parsePostMortemActions(repaired);
10698
+ const parsed = _internals16.parsePostMortemActions(repaired);
10600
10699
  if (parsed.diagnostics.length === 0) {
10601
10700
  return parsed;
10602
10701
  }
@@ -10649,7 +10748,7 @@ function collectRetrospectives(directory) {
10649
10748
  }
10650
10749
  async function collectDriftReports(directory) {
10651
10750
  try {
10652
- const reports = await _internals15.readPriorDriftReports(directory);
10751
+ const reports = await _internals16.readPriorDriftReports(directory);
10653
10752
  return reports.slice(-MAX_DRIFT_REPORTS).map((report) => JSON.stringify(report, null, 2));
10654
10753
  } catch {
10655
10754
  return [];
@@ -10872,7 +10971,7 @@ async function runCuratorPostMortem(directory, options = {}) {
10872
10971
  warnings
10873
10972
  };
10874
10973
  }
10875
- const lock = await _internals15.acquirePostMortemLock(directory, effectivePlanId);
10974
+ const lock = await _internals16.acquirePostMortemLock(directory, effectivePlanId);
10876
10975
  if (!lock.acquired) {
10877
10976
  return {
10878
10977
  success: false,
@@ -10894,7 +10993,7 @@ async function runCuratorPostMortem(directory, options = {}) {
10894
10993
  warnings.push("Failed to collect knowledge summary.");
10895
10994
  }
10896
10995
  try {
10897
- const { getScanStatus } = await import("./scan-cursor-qmsmmg1b.js");
10996
+ const { getScanStatus } = await import("./scan-cursor-nx5y5k7r.js");
10898
10997
  const scanStatus = await getScanStatus(directory);
10899
10998
  if (scanStatus.remaining_estimate > 0) {
10900
10999
  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.`);
@@ -10953,20 +11052,20 @@ async function runCuratorPostMortem(directory, options = {}) {
10953
11052
  } finally {
10954
11053
  clearTimeout(timer);
10955
11054
  }
10956
- let parsedActions = _internals15.parsePostMortemActions(llmOutput);
11055
+ let parsedActions = _internals16.parsePostMortemActions(llmOutput);
10957
11056
  if (parsedActions.diagnostics.length > 0) {
10958
11057
  warnings.push(`Post-mortem structured action parse diagnostics: ${parsedActions.diagnostics.join("; ")}`);
10959
- const repaired = await _internals15.repairPostMortemActions(llmOutput, parsedActions.diagnostics, options);
11058
+ const repaired = await _internals16.repairPostMortemActions(llmOutput, parsedActions.diagnostics, options);
10960
11059
  if (repaired) {
10961
11060
  parsedActions = repaired;
10962
11061
  warnings.push("Post-mortem structured actions repaired by LLM.");
10963
11062
  }
10964
11063
  }
10965
11064
  llmSummary = parsedActions.summary;
10966
- const executed = await _internals15.executePostMortemActions(directory, parsedActions, options, scanCursor.generation);
11065
+ const executed = await _internals16.executePostMortemActions(directory, parsedActions, options, scanCursor.generation);
10967
11066
  actionResult = executed.result;
10968
11067
  warnings.push(...executed.warnings);
10969
- const knowledgeVerification = await _internals15.verifyPostMortemKnowledgeActions(directory, parsedActions.recommendations);
11068
+ const knowledgeVerification = await _internals16.verifyPostMortemKnowledgeActions(directory, parsedActions.recommendations);
10970
11069
  for (const item of knowledgeVerification) {
10971
11070
  if (item.status === "not_found" || item.status === "ambiguous_prefix" || item.status === "missing_entry_id") {
10972
11071
  warnings.push(`Post-mortem knowledge action ${item.action} for '${item.input_entry_id ?? "new"}' ${item.status}: ${item.reason}`);
@@ -11005,10 +11104,10 @@ ${actionSummary}`;
11005
11104
  } catch (err) {
11006
11105
  const msg = err instanceof Error ? err.message : String(err);
11007
11106
  warnings.push(`LLM delegate failed, falling back to data-only report: ${msg}`);
11008
- reportContent = _internals15.buildDataOnlyReport(effectivePlanId, planSummary, knowledgeSummary, curatorDigest, proposals, unactionable, retrospectives, driftReports, { scope, sessionID: options.sessionID, planLoaded });
11107
+ reportContent = _internals16.buildDataOnlyReport(effectivePlanId, planSummary, knowledgeSummary, curatorDigest, proposals, unactionable, retrospectives, driftReports, { scope, sessionID: options.sessionID, planLoaded });
11009
11108
  }
11010
11109
  } else {
11011
- reportContent = _internals15.buildDataOnlyReport(effectivePlanId, planSummary, knowledgeSummary, curatorDigest, proposals, unactionable, retrospectives, driftReports, { scope, sessionID: options.sessionID, planLoaded });
11110
+ reportContent = _internals16.buildDataOnlyReport(effectivePlanId, planSummary, knowledgeSummary, curatorDigest, proposals, unactionable, retrospectives, driftReports, { scope, sessionID: options.sessionID, planLoaded });
11012
11111
  }
11013
11112
  try {
11014
11113
  const { mkdirSync: mkdirSync8 } = await import("fs");
@@ -11049,7 +11148,7 @@ ${actionSummary}`;
11049
11148
  }
11050
11149
  }
11051
11150
  }
11052
- var _internals15 = {
11151
+ var _internals16 = {
11053
11152
  acquirePostMortemLock,
11054
11153
  collectKnowledgeSummary,
11055
11154
  collectRetrospectives,
@@ -11076,11 +11175,11 @@ var _internals15 = {
11076
11175
  }
11077
11176
  },
11078
11177
  applyCuratorKnowledgeUpdates: async (directory, recommendations, knowledgeConfig, generation) => {
11079
- const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-ed91r7rw.js");
11178
+ const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-3rze3pd4.js");
11080
11179
  return applyCuratorKnowledgeUpdates2(directory, recommendations, knowledgeConfig, generation);
11081
11180
  },
11082
11181
  checkHivePromotions: async (entries, knowledgeConfig, directory) => {
11083
- const { checkHivePromotions } = await import("./hive-promoter-dg6fk563.js");
11182
+ const { checkHivePromotions } = await import("./hive-promoter-dh38qd9m.js");
11084
11183
  return checkHivePromotions(entries, knowledgeConfig, directory);
11085
11184
  },
11086
11185
  applyProposalTriage: async (directory, triage) => {
@@ -11089,7 +11188,7 @@ var _internals15 = {
11089
11188
  activateProposal,
11090
11189
  listSkills: listSkills2,
11091
11190
  sanitizeSlug
11092
- } = await import("./skill-generator-hkyxdc3j.js");
11191
+ } = await import("./skill-generator-nt5qxafq.js");
11093
11192
  const result = {
11094
11193
  approved: [],
11095
11194
  rejected: [],
@@ -11228,10 +11327,10 @@ var HIVE_LOCK_RETRIES = {
11228
11327
  retries: { retries: 5, minTimeout: 100, maxTimeout: 500 }
11229
11328
  };
11230
11329
  async function transactHiveStore(mutate) {
11231
- const dataDir = _internals16.resolveHiveDataDir();
11232
- const hivePath = _internals16.resolveHiveKnowledgePath();
11233
- const rejectedPath = _internals16.resolveHiveRejectedPath();
11234
- const eventsPath = _internals16.resolveHiveEventsPath();
11330
+ const dataDir = _internals17.resolveHiveDataDir();
11331
+ const hivePath = _internals17.resolveHiveKnowledgePath();
11332
+ const rejectedPath = _internals17.resolveHiveRejectedPath();
11333
+ const eventsPath = _internals17.resolveHiveEventsPath();
11235
11334
  const diagnostics = [];
11236
11335
  try {
11237
11336
  await mkdir6(dataDir, { recursive: true });
@@ -11242,7 +11341,7 @@ async function transactHiveStore(mutate) {
11242
11341
  let release = null;
11243
11342
  try {
11244
11343
  try {
11245
- release = await _internals16.lockfile.lock(dataDir, {
11344
+ release = await _internals17.lockfile.lock(dataDir, {
11246
11345
  ...HIVE_LOCK_RETRIES,
11247
11346
  stale: HIVE_LOCK_STALE_MS
11248
11347
  });
@@ -11250,7 +11349,7 @@ async function transactHiveStore(mutate) {
11250
11349
  diagnostics.push(`hive lock acquire failed: ${err instanceof Error ? err.message : String(err)}`);
11251
11350
  return { committed: false, return: undefined, diagnostics };
11252
11351
  }
11253
- const entries = await _internals16.readKnowledge(hivePath);
11352
+ const entries = await _internals17.readKnowledge(hivePath);
11254
11353
  const outcome = await mutate({ entries });
11255
11354
  if (outcome.kind === "noop") {
11256
11355
  return { committed: false, return: outcome.return, diagnostics };
@@ -11271,12 +11370,12 @@ async function transactHiveStore(mutate) {
11271
11370
  return { committed: false, return: undefined, diagnostics };
11272
11371
  }
11273
11372
  if (typeof outcome.maxEntries === "number" && committedEntries.length > outcome.maxEntries) {
11274
- committedEntries = _internals16.selectKnowledgeCapSurvivors(committedEntries, outcome.maxEntries);
11373
+ committedEntries = _internals17.selectKnowledgeCapSurvivors(committedEntries, outcome.maxEntries);
11275
11374
  }
11276
11375
  const content = committedEntries.map((e) => JSON.stringify(e)).join(`
11277
11376
  `) + (committedEntries.length > 0 ? `
11278
11377
  ` : "");
11279
- await _internals16.atomicWriteFile(hivePath, content);
11378
+ await _internals17.atomicWriteFile(hivePath, content);
11280
11379
  if (outcome.rejects && outcome.rejects.length > 0) {
11281
11380
  const rejectBlock = `${outcome.rejects.map((r) => JSON.stringify(r)).join(`
11282
11381
  `)}
@@ -11318,7 +11417,7 @@ async function trimHiveEventsUnderLock(eventsPath) {
11318
11417
  `)}
11319
11418
  `);
11320
11419
  }
11321
- var _internals16 = {
11420
+ var _internals17 = {
11322
11421
  lockfile: import_proper_lockfile2.default,
11323
11422
  readKnowledge,
11324
11423
  atomicWriteFile,
@@ -11330,6 +11429,54 @@ var _internals16 = {
11330
11429
  path: path19
11331
11430
  };
11332
11431
 
11432
+ // src/hooks/promotion-evidence-store.ts
11433
+ import {
11434
+ appendFile as appendFile3,
11435
+ mkdir as mkdir7,
11436
+ readFile as readFile6,
11437
+ rename as rename4,
11438
+ writeFile as writeFile5
11439
+ } from "fs/promises";
11440
+ init_logger();
11441
+ function resolvePromotionEvidencePath(directory) {
11442
+ return validateSwarmPath(directory, "knowledge-promotion-evidence.jsonl");
11443
+ }
11444
+ function parseRecord(line) {
11445
+ try {
11446
+ const o = JSON.parse(line);
11447
+ if (typeof o.cohort_id === "string" && typeof o.entry_id === "string" && typeof o.retrieval_trace_id === "string" && (o.receipt_outcome === "applied" || o.receipt_outcome === "violated" || o.receipt_outcome === "contradicted") && typeof o.receipt_event_id === "string" && typeof o.timestamp === "string") {
11448
+ return o;
11449
+ }
11450
+ } catch {}
11451
+ return null;
11452
+ }
11453
+ async function loadPromotionEvidenceByEntry(directory) {
11454
+ const filePath = resolvePromotionEvidencePath(directory);
11455
+ let content;
11456
+ try {
11457
+ content = await readFile6(filePath, "utf-8");
11458
+ } catch {
11459
+ return {};
11460
+ }
11461
+ const out = {};
11462
+ for (const line of content.split(`
11463
+ `)) {
11464
+ const trimmed = line.trim();
11465
+ if (!trimmed)
11466
+ continue;
11467
+ const rec = parseRecord(trimmed);
11468
+ if (!rec)
11469
+ continue;
11470
+ const bucket = out[rec.entry_id];
11471
+ if (bucket) {
11472
+ bucket.push(rec);
11473
+ } else {
11474
+ out[rec.entry_id] = [rec];
11475
+ }
11476
+ }
11477
+ return out;
11478
+ }
11479
+
11333
11480
  // src/hooks/hive-promoter.ts
11334
11481
  function carryActionableFields(source) {
11335
11482
  const out = {};
@@ -11437,8 +11584,8 @@ async function checkHivePromotions(swarmEntries, config, directory) {
11437
11584
  if (config.hive_enabled === false) {
11438
11585
  return empty;
11439
11586
  }
11440
- const sourceCohort = await _internals17.resolveCohortId(directory);
11441
- const evidence = await _internals17.loadPromotionEvidence(swarmEntries);
11587
+ const sourceCohort = await _internals18.resolveCohortId(directory);
11588
+ const evidence = await _internals18.loadPromotionEvidence(directory);
11442
11589
  const diagnostics = [];
11443
11590
  const activeSwarm = swarmEntries.filter((e) => isActiveStatus(e.status));
11444
11591
  const activeSwarmBigrams = activeSwarm.map((e) => typeof e.lesson === "string" ? wordBigrams(e.lesson) : new Set);
@@ -11458,7 +11605,7 @@ async function checkHivePromotions(swarmEntries, config, directory) {
11458
11605
  diagnostics.push(`skip promote '${swarmEntry.lesson.slice(0, 40)}\u2026': ${decision.reason}`);
11459
11606
  continue;
11460
11607
  }
11461
- const validationResult = _internals17.validateLesson(swarmEntry.lesson, [], {
11608
+ const validationResult = _internals18.validateLesson(swarmEntry.lesson, [], {
11462
11609
  category: swarmEntry.category,
11463
11610
  scope: swarmEntry.scope,
11464
11611
  confidence: swarmEntry.confidence
@@ -11480,7 +11627,7 @@ async function checkHivePromotions(swarmEntries, config, directory) {
11480
11627
  });
11481
11628
  }
11482
11629
  const hiveDir = resolveHiveDataDir();
11483
- const result = await _internals17.transactHiveStore(async (ctx) => {
11630
+ const result = await _internals18.transactHiveStore(async (ctx) => {
11484
11631
  let newPromotions = 0;
11485
11632
  let encounters = 0;
11486
11633
  let advancements = 0;
@@ -11706,7 +11853,7 @@ async function authorizeAndRecordHiveMerge(args) {
11706
11853
  let authorized = true;
11707
11854
  let basis = "config-skipped-unlinked";
11708
11855
  try {
11709
- const decision = await _internals17.authorizeCuration({
11856
+ const decision = await _internals18.authorizeCuration({
11710
11857
  directory: hiveDir,
11711
11858
  action: "merge",
11712
11859
  entryId: survivingEntry.id,
@@ -11736,7 +11883,7 @@ async function authorizeAndRecordHiveMerge(args) {
11736
11883
  authorizationBasis: basis
11737
11884
  });
11738
11885
  }
11739
- var _internals17 = {
11886
+ var _internals18 = {
11740
11887
  readSwarmEntries: (directory) => readKnowledge(resolveSwarmKnowledgePath(directory)),
11741
11888
  checkHivePromotions,
11742
11889
  readCuratorSummary,
@@ -11745,20 +11892,20 @@ var _internals17 = {
11745
11892
  transactHiveStore,
11746
11893
  validateLesson,
11747
11894
  authorizeCuration,
11748
- loadPromotionEvidence: async (_swarmEntries) => ({}),
11895
+ loadPromotionEvidence: async (directory) => loadPromotionEvidenceByEntry(directory),
11749
11896
  loadDefaultKnowledgeConfig: () => KnowledgeConfigSchema.parse({})
11750
11897
  };
11751
11898
  function createHivePromoterHook(directory, config) {
11752
11899
  const hook = async (_input, _output) => {
11753
- const swarmEntries = await _internals17.readSwarmEntries(directory);
11754
- const promotionSummary = await _internals17.checkHivePromotions(swarmEntries, config, directory);
11755
- const curatorSummary = await _internals17.readCuratorSummary(directory);
11900
+ const swarmEntries = await _internals18.readSwarmEntries(directory);
11901
+ const promotionSummary = await _internals18.checkHivePromotions(swarmEntries, config, directory);
11902
+ const curatorSummary = await _internals18.readCuratorSummary(directory);
11756
11903
  if (!curatorSummary)
11757
11904
  return;
11758
11905
  const hasActivity = promotionSummary.new_promotions > 0 || promotionSummary.encounters_incremented > 0 || promotionSummary.advancements > 0;
11759
11906
  if (!hasActivity)
11760
11907
  return;
11761
- await _internals17.appendCuratorRecommendation(directory, {
11908
+ await _internals18.appendCuratorRecommendation(directory, {
11762
11909
  action: "promote",
11763
11910
  lesson: `Hive promotion: ${promotionSummary.new_promotions} new, ${promotionSummary.encounters_incremented} encounters, ${promotionSummary.advancements} advancements, ${promotionSummary.total_hive_entries} total entries`,
11764
11911
  reason: JSON.stringify({
@@ -11774,16 +11921,16 @@ function createHivePromoterHook(directory, config) {
11774
11921
  }
11775
11922
  async function promoteToHive(directory, lesson, category, options, config) {
11776
11923
  const trimmedLesson = lesson.trim();
11777
- const sourceCohort = await _internals17.resolveCohortId(directory);
11778
- const policyConfig = config ?? _internals17.loadDefaultKnowledgeConfig();
11779
- const result = await _internals17.transactHiveStore(async (ctx) => {
11924
+ const sourceCohort = await _internals18.resolveCohortId(directory);
11925
+ const policyConfig = config ?? _internals18.loadDefaultKnowledgeConfig();
11926
+ const result = await _internals18.transactHiveStore(async (ctx) => {
11780
11927
  if (findNearDuplicate(trimmedLesson, ctx.entries, policyConfig.dedup_threshold)) {
11781
11928
  return {
11782
11929
  kind: "noop",
11783
11930
  return: `Lesson already exists in hive (near-duplicate).`
11784
11931
  };
11785
11932
  }
11786
- const validationResult = _internals17.validateLesson(trimmedLesson, ctx.entries.map((e) => e.lesson), {
11933
+ const validationResult = _internals18.validateLesson(trimmedLesson, ctx.entries.map((e) => e.lesson), {
11787
11934
  category: category || "process",
11788
11935
  scope: "global",
11789
11936
  confidence: 1
@@ -11892,16 +12039,16 @@ async function promoteFromSwarm(directory, lessonId, options, config) {
11892
12039
  if (!swarmEntry) {
11893
12040
  throw new Error(`Lesson ${lessonId} not found in .swarm/knowledge.jsonl`);
11894
12041
  }
11895
- const sourceCohort = await _internals17.resolveCohortId(directory);
11896
- const policyConfig = config ?? _internals17.loadDefaultKnowledgeConfig();
11897
- const result = await _internals17.transactHiveStore(async (ctx) => {
12042
+ const sourceCohort = await _internals18.resolveCohortId(directory);
12043
+ const policyConfig = config ?? _internals18.loadDefaultKnowledgeConfig();
12044
+ const result = await _internals18.transactHiveStore(async (ctx) => {
11898
12045
  if (findNearDuplicate(swarmEntry.lesson, ctx.entries, policyConfig.dedup_threshold)) {
11899
12046
  return {
11900
12047
  kind: "noop",
11901
12048
  return: `Lesson already exists in hive (near-duplicate).`
11902
12049
  };
11903
12050
  }
11904
- const validationResult = _internals17.validateLesson(swarmEntry.lesson, ctx.entries.map((e) => e.lesson), {
12051
+ const validationResult = _internals18.validateLesson(swarmEntry.lesson, ctx.entries.map((e) => e.lesson), {
11905
12052
  category: swarmEntry.category,
11906
12053
  scope: swarmEntry.scope,
11907
12054
  confidence: swarmEntry.confidence
@@ -11992,23 +12139,23 @@ async function promoteFromSwarm(directory, lessonId, options, config) {
11992
12139
  import { createHash as createHash5 } from "crypto";
11993
12140
  import { existsSync as existsSync13 } from "fs";
11994
12141
  import {
11995
- appendFile as appendFile3,
11996
- mkdir as mkdir8,
11997
- readFile as readFile8,
12142
+ appendFile as appendFile4,
12143
+ mkdir as mkdir9,
12144
+ readFile as readFile9,
11998
12145
  realpath,
11999
- writeFile as writeFile7
12146
+ writeFile as writeFile8
12000
12147
  } from "fs/promises";
12001
12148
  import * as path25 from "path";
12002
12149
 
12003
12150
  // src/services/synonym-map.ts
12004
12151
  var import_proper_lockfile3 = __toESM(require_proper_lockfile(), 1);
12005
12152
  import {
12006
- mkdir as mkdir7,
12007
- readFile as readFile6,
12008
- rename as rename4,
12153
+ mkdir as mkdir8,
12154
+ readFile as readFile7,
12155
+ rename as rename5,
12009
12156
  stat as stat2,
12010
12157
  unlink,
12011
- writeFile as writeFile5
12158
+ writeFile as writeFile6
12012
12159
  } from "fs/promises";
12013
12160
  import * as path21 from "path";
12014
12161
  var SYNONYM_MAP_FILENAME = "synonym-map.json";
@@ -12158,18 +12305,18 @@ async function readSynonymMap(directory, maxPairs = DEFAULT_MAX_PAIRS) {
12158
12305
  const st = await stat2(filePath);
12159
12306
  if (st.size > ceiling)
12160
12307
  return emptySynonymMap();
12161
- const raw = await readFile6(filePath, "utf-8");
12308
+ const raw = await readFile7(filePath, "utf-8");
12162
12309
  return coerceSynonymMap(JSON.parse(raw), maxPairs);
12163
12310
  } catch {
12164
12311
  return emptySynonymMap();
12165
12312
  }
12166
12313
  }
12167
12314
  async function writeSynonymMapAtomic(filePath, map) {
12168
- await mkdir7(path21.dirname(filePath), { recursive: true });
12315
+ await mkdir8(path21.dirname(filePath), { recursive: true });
12169
12316
  const tmp = `${filePath}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`;
12170
12317
  try {
12171
- await writeFile5(tmp, JSON.stringify(map, null, 2), "utf-8");
12172
- await rename4(tmp, filePath);
12318
+ await writeFile6(tmp, JSON.stringify(map, null, 2), "utf-8");
12319
+ await rename5(tmp, filePath);
12173
12320
  } finally {
12174
12321
  try {
12175
12322
  await unlink(tmp);
@@ -12179,7 +12326,7 @@ async function writeSynonymMapAtomic(filePath, map) {
12179
12326
  async function rebuildSynonymMap(directory, entries, maxPairs = DEFAULT_MAX_PAIRS) {
12180
12327
  const filePath = resolveSynonymMapPath(directory);
12181
12328
  const dir = path21.dirname(filePath);
12182
- await mkdir7(dir, { recursive: true });
12329
+ await mkdir8(dir, { recursive: true });
12183
12330
  let release = null;
12184
12331
  try {
12185
12332
  release = await import_proper_lockfile3.default.lock(dir, {
@@ -12203,10 +12350,13 @@ init_logger();
12203
12350
 
12204
12351
  // src/hooks/micro-reflector.ts
12205
12352
  import { existsSync as existsSync12 } from "fs";
12206
- import { readFile as readFile7, writeFile as writeFile6 } from "fs/promises";
12353
+ import { readFile as readFile8, writeFile as writeFile7 } from "fs/promises";
12207
12354
  import * as path24 from "path";
12208
12355
  init_logger();
12209
12356
 
12357
+ // src/hooks/guardrails/stored-input-args.ts
12358
+ var storedInputArgs = new Map;
12359
+
12210
12360
  // src/hooks/skill-propagation-gate.ts
12211
12361
  import * as fs9 from "fs";
12212
12362
  import * as path23 from "path";
@@ -12233,7 +12383,7 @@ var SKILL_AUDIENCE_RUNNER_PATTERN = /^runner:(opencode|claude|codex)$/;
12233
12383
  var WORKFLOW_BOOST_MIN_CONTEXT = 0.05;
12234
12384
  var RECENCY_DECAY_MS = 30 * 24 * 60 * 60 * 1000;
12235
12385
  var SKILL_FRONTMATTER_READ_BYTES = 16 * 1024;
12236
- var _internals18 = {
12386
+ var _internals19 = {
12237
12387
  computeSkillRelevanceScore: null,
12238
12388
  rankSkillsForContext: null,
12239
12389
  getSkillStats: null,
@@ -12600,7 +12750,7 @@ function rankSkillsForContext(skills, taskContext, directory) {
12600
12750
  const results = [];
12601
12751
  for (const skillPath of skills) {
12602
12752
  const skillEntries = allEntries.filter((e) => e.skillPath === skillPath);
12603
- const metadata = _internals18.readSkillMetadata(skillPath, directory);
12753
+ const metadata = _internals19.readSkillMetadata(skillPath, directory);
12604
12754
  const score = computeSkillRelevanceScore(skillPath, taskContext, skillEntries, metadata);
12605
12755
  const entriesWithVerdict = skillEntries.filter((e) => e.complianceVerdict !== undefined && e.complianceVerdict !== "not_checked");
12606
12756
  const compliantCount = entriesWithVerdict.filter((e) => e.complianceVerdict === "compliant").length;
@@ -12659,7 +12809,7 @@ function formatSkillIndexWithContext(skills, directory, metadataBySkillPath) {
12659
12809
  } catch {}
12660
12810
  if (!hasHistory) {
12661
12811
  return skills.map((sp) => {
12662
- const meta = metadataBySkillPath?.get(sp) ?? _internals18.readSkillMetadata(sp, directory);
12812
+ const meta = metadataBySkillPath?.get(sp) ?? _internals19.readSkillMetadata(sp, directory);
12663
12813
  return ` - file:${meta.path} - ${meta.name}: ${meta.description}`;
12664
12814
  }).join(`
12665
12815
  `);
@@ -12667,7 +12817,7 @@ function formatSkillIndexWithContext(skills, directory, metadataBySkillPath) {
12667
12817
  const lines = [];
12668
12818
  for (const skillPath of skills) {
12669
12819
  const stats = getSkillStats(skillPath, directory);
12670
- const meta = metadataBySkillPath?.get(skillPath) ?? _internals18.readSkillMetadata(skillPath, directory);
12820
+ const meta = metadataBySkillPath?.get(skillPath) ?? _internals19.readSkillMetadata(skillPath, directory);
12671
12821
  const compliancePct = Math.round(stats.complianceRate * 100);
12672
12822
  const topAgentNames = stats.topAgents.slice(0, 3).map((a) => a.agent).join(", ");
12673
12823
  lines.push(` - file:${meta.path} - ${meta.name}: ${meta.description} (used: ${stats.totalUsage}, compliance: ${compliancePct}%)` + (stats.topAgents.length > 0 ? ` \u2192 ${topAgentNames}` : ""));
@@ -12675,16 +12825,16 @@ function formatSkillIndexWithContext(skills, directory, metadataBySkillPath) {
12675
12825
  return lines.join(`
12676
12826
  `);
12677
12827
  }
12678
- _internals18.computeSkillRelevanceScore = computeSkillRelevanceScore;
12679
- _internals18.rankSkillsForContext = rankSkillsForContext;
12680
- _internals18.getSkillStats = getSkillStats;
12681
- _internals18.formatSkillIndexWithContext = formatSkillIndexWithContext;
12682
- _internals18.parseSkillFrontmatter = parseSkillFrontmatter;
12683
- _internals18.readSkillMetadata = readSkillMetadata;
12684
- _internals18.extractSkillName = extractSkillName;
12685
- _internals18.computeRecencyScore = computeRecencyScore;
12686
- _internals18.computeContextMatchScore = computeContextMatchScore;
12687
- _internals18.computeTriggerMatchBoost = computeTriggerMatchBoost;
12828
+ _internals19.computeSkillRelevanceScore = computeSkillRelevanceScore;
12829
+ _internals19.rankSkillsForContext = rankSkillsForContext;
12830
+ _internals19.getSkillStats = getSkillStats;
12831
+ _internals19.formatSkillIndexWithContext = formatSkillIndexWithContext;
12832
+ _internals19.parseSkillFrontmatter = parseSkillFrontmatter;
12833
+ _internals19.readSkillMetadata = readSkillMetadata;
12834
+ _internals19.extractSkillName = extractSkillName;
12835
+ _internals19.computeRecencyScore = computeRecencyScore;
12836
+ _internals19.computeContextMatchScore = computeContextMatchScore;
12837
+ _internals19.computeTriggerMatchBoost = computeTriggerMatchBoost;
12688
12838
 
12689
12839
  // src/hooks/skill-propagation-gate.ts
12690
12840
  function parseSimpleYaml(content) {
@@ -12786,10 +12936,10 @@ function parseYamlValue(value) {
12786
12936
  }
12787
12937
  function loadRoutingSkills(directory, targetAgent) {
12788
12938
  const routingPath = path23.join(directory, ".opencode", "skill-routing.yaml");
12789
- if (!_internals19.existsSync(routingPath))
12939
+ if (!_internals20.existsSync(routingPath))
12790
12940
  return [];
12791
12941
  try {
12792
- const content = _internals19.readFileSync(routingPath, "utf-8");
12942
+ const content = _internals20.readFileSync(routingPath, "utf-8");
12793
12943
  const config = parseSimpleYaml(content);
12794
12944
  if (!config?.routing)
12795
12945
  return [];
@@ -12816,7 +12966,7 @@ var SKILL_SEARCH_ROOTS = [
12816
12966
  ".claude/skills"
12817
12967
  ];
12818
12968
  var MAX_SCORING_SESSION_ENTRIES = 500;
12819
- var _internals19 = {
12969
+ var _internals20 = {
12820
12970
  readdirSync: fs9.readdirSync.bind(fs9),
12821
12971
  existsSync: fs9.existsSync.bind(fs9),
12822
12972
  statSync: fs9.statSync.bind(fs9),
@@ -12849,11 +12999,11 @@ function discoverAvailableSkills(directory) {
12849
12999
  const results = [];
12850
13000
  for (const root of SKILL_SEARCH_ROOTS) {
12851
13001
  const rootPath = path23.join(directory, root);
12852
- if (!_internals19.existsSync(rootPath))
13002
+ if (!_internals20.existsSync(rootPath))
12853
13003
  continue;
12854
13004
  let entries;
12855
13005
  try {
12856
- entries = _internals19.readdirSync(rootPath);
13006
+ entries = _internals20.readdirSync(rootPath);
12857
13007
  } catch {
12858
13008
  continue;
12859
13009
  }
@@ -12861,11 +13011,11 @@ function discoverAvailableSkills(directory) {
12861
13011
  if (entry.startsWith("."))
12862
13012
  continue;
12863
13013
  const skillDir = path23.join(rootPath, entry);
12864
- if (_internals19.existsSync(path23.join(skillDir, "retired.marker")) || _internals19.existsSync(path23.join(skillDir, "stale.marker")))
13014
+ if (_internals20.existsSync(path23.join(skillDir, "retired.marker")) || _internals20.existsSync(path23.join(skillDir, "stale.marker")))
12865
13015
  continue;
12866
13016
  const skillFile = path23.join(skillDir, "SKILL.md");
12867
13017
  try {
12868
- if (_internals19.statSync(skillDir).isDirectory() && _internals19.existsSync(skillFile)) {
13018
+ if (_internals20.statSync(skillDir).isDirectory() && _internals20.existsSync(skillFile)) {
12869
13019
  results.push(path23.join(root, entry, "SKILL.md").replace(/\\/g, "/"));
12870
13020
  }
12871
13021
  } catch (err) {
@@ -12897,7 +13047,7 @@ function parseDelegationArgs(args) {
12897
13047
  }
12898
13048
  if (!targetAgent)
12899
13049
  return null;
12900
- const skillsField = prompt ? _internals19.extractSkillsFieldFromPrompt(prompt) : "";
13050
+ const skillsField = prompt ? _internals20.extractSkillsFieldFromPrompt(prompt) : "";
12901
13051
  return { targetAgent, skillsField };
12902
13052
  }
12903
13053
  function extractSkillsFieldFromPrompt(prompt) {
@@ -12938,10 +13088,10 @@ function writeWarnEvent(directory, record) {
12938
13088
  const filePath = path23.join(directory, ".swarm", "events.jsonl");
12939
13089
  try {
12940
13090
  const dir = path23.dirname(filePath);
12941
- if (!_internals19.existsSync(dir)) {
12942
- _internals19.mkdirSync(dir, { recursive: true });
13091
+ if (!_internals20.existsSync(dir)) {
13092
+ _internals20.mkdirSync(dir, { recursive: true });
12943
13093
  }
12944
- _internals19.appendFileSync(filePath, `${JSON.stringify(record)}
13094
+ _internals20.appendFileSync(filePath, `${JSON.stringify(record)}
12945
13095
  `, "utf-8");
12946
13096
  } catch (err) {
12947
13097
  warn(`[skill-propagation-gate] failed to write warning event: ${err instanceof Error ? err.message : String(err)}`);
@@ -12996,7 +13146,7 @@ function validateSkillReference(directory, reference, context, options) {
12996
13146
  };
12997
13147
  }
12998
13148
  try {
12999
- const root = _internals19.realpathSync(directory);
13149
+ const root = _internals20.realpathSync(directory);
13000
13150
  const lexicalPath = path23.resolve(root, withoutPrefix);
13001
13151
  if (!isWithinRoot(root, lexicalPath)) {
13002
13152
  return {
@@ -13004,10 +13154,10 @@ function validateSkillReference(directory, reference, context, options) {
13004
13154
  reason: "skill path resolves outside the project"
13005
13155
  };
13006
13156
  }
13007
- if (!_internals19.existsSync(lexicalPath) || !_internals19.statSync(lexicalPath).isFile()) {
13157
+ if (!_internals20.existsSync(lexicalPath) || !_internals20.statSync(lexicalPath).isFile()) {
13008
13158
  return { valid: false, reason: "skill file does not exist" };
13009
13159
  }
13010
- const realPath = _internals19.realpathSync(lexicalPath);
13160
+ const realPath = _internals20.realpathSync(lexicalPath);
13011
13161
  if (!isWithinRoot(root, realPath)) {
13012
13162
  return {
13013
13163
  valid: false,
@@ -13016,7 +13166,7 @@ function validateSkillReference(directory, reference, context, options) {
13016
13166
  }
13017
13167
  const normalizedPath = withoutPrefix.replace(/^\.\//, "");
13018
13168
  const validatedMetadataPath = path23.relative(root, realPath).replace(/\\/g, "/");
13019
- const metadata = _internals19.readSkillMetadata(validatedMetadataPath, root);
13169
+ const metadata = _internals20.readSkillMetadata(validatedMetadataPath, root);
13020
13170
  if (metadata.frontmatterStatus !== "valid" && metadata.frontmatterStatus !== "absent") {
13021
13171
  return {
13022
13172
  valid: false,
@@ -13048,18 +13198,18 @@ async function validateExplicitSkillReferencesBefore(directory, input, config) {
13048
13198
  if (!agentRaw || stripKnownSwarmPrefix(agentRaw) !== "architect") {
13049
13199
  return { blocked: false, reason: null };
13050
13200
  }
13051
- const parsed = _internals19.parseDelegationArgs(input.args);
13201
+ const parsed = _internals20.parseDelegationArgs(input.args);
13052
13202
  if (!parsed)
13053
13203
  return { blocked: false, reason: null };
13054
13204
  const targetBase = stripKnownSwarmPrefix(parsed.targetAgent);
13055
- if (!_internals19.SKILL_CAPABLE_AGENTS.has(targetBase)) {
13205
+ if (!_internals20.SKILL_CAPABLE_AGENTS.has(targetBase)) {
13056
13206
  return { blocked: false, reason: null };
13057
13207
  }
13058
13208
  const skillsValue = parsed.skillsField.trim();
13059
13209
  if (!skillsValue || skillsValue.toLowerCase() === "none") {
13060
13210
  return { blocked: false, reason: null };
13061
13211
  }
13062
- const fileReferences = _internals19.extractFileSkillReferences(skillsValue);
13212
+ const fileReferences = _internals20.extractFileSkillReferences(skillsValue);
13063
13213
  if (fileReferences.length === 0) {
13064
13214
  return { blocked: false, reason: null, validatedSkillPaths: [] };
13065
13215
  }
@@ -13072,7 +13222,7 @@ async function validateExplicitSkillReferencesBefore(directory, input, config) {
13072
13222
  const context = resolveSkillAudienceContext(config);
13073
13223
  const validatedSkillPaths = [];
13074
13224
  for (const reference of fileReferences) {
13075
- const result = _internals19.validateSkillReference(directory, reference, context, {
13225
+ const result = _internals20.validateSkillReference(directory, reference, context, {
13076
13226
  enforceAudience: true
13077
13227
  });
13078
13228
  if (!result.valid) {
@@ -13117,18 +13267,18 @@ async function skillPropagationGateBefore(directory, input, config) {
13117
13267
  const baseAgent = stripKnownSwarmPrefix(agentRaw);
13118
13268
  if (baseAgent !== "architect")
13119
13269
  return { blocked: false, reason: null, recommendedSkills: undefined };
13120
- const parsed = _internals19.parseDelegationArgs(input.args);
13270
+ const parsed = _internals20.parseDelegationArgs(input.args);
13121
13271
  if (!parsed)
13122
13272
  return { blocked: false, reason: null, recommendedSkills: undefined };
13123
13273
  const targetBase = stripKnownSwarmPrefix(parsed.targetAgent);
13124
- if (!_internals19.SKILL_CAPABLE_AGENTS.has(targetBase))
13274
+ if (!_internals20.SKILL_CAPABLE_AGENTS.has(targetBase))
13125
13275
  return { blocked: false, reason: null, recommendedSkills: undefined };
13126
13276
  const sessionID = typeof input.sessionID === "string" ? input.sessionID : "unknown";
13127
13277
  const audienceContext = resolveSkillAudienceContext(config);
13128
13278
  const availableSkills = [];
13129
13279
  const metadataBySkillPath = new Map;
13130
- for (const skillPath of _internals19.discoverAvailableSkills(directory)) {
13131
- const validation = _internals19.validateSkillReference(directory, skillPath, audienceContext, { enforceAudience: true, requireFilePrefix: false });
13280
+ for (const skillPath of _internals20.discoverAvailableSkills(directory)) {
13281
+ const validation = _internals20.validateSkillReference(directory, skillPath, audienceContext, { enforceAudience: true, requireFilePrefix: false });
13132
13282
  if (!validation.valid || !validation.skillPath)
13133
13283
  continue;
13134
13284
  availableSkills.push(validation.skillPath);
@@ -13139,7 +13289,7 @@ async function skillPropagationGateBefore(directory, input, config) {
13139
13289
  const skillsValue = parsed.skillsField.trim();
13140
13290
  if (skillsValue && skillsValue.toLowerCase() !== "none") {
13141
13291
  const prompt = typeof input.args?.prompt === "string" ? String(input.args.prompt) : "";
13142
- const taskId = _internals19.extractTaskIdFromPrompt(prompt);
13292
+ const taskId = _internals20.extractTaskIdFromPrompt(prompt);
13143
13293
  const skillPaths = explicitIntegrity.validatedSkillPaths ?? [];
13144
13294
  let coderSkillPaths = [];
13145
13295
  if (prompt) {
@@ -13148,19 +13298,19 @@ async function skillPropagationGateBefore(directory, input, config) {
13148
13298
  const trimmed = line.trim();
13149
13299
  if (trimmed.startsWith("SKILLS_USED_BY_CODER:")) {
13150
13300
  const fieldVal = trimmed.slice("SKILLS_USED_BY_CODER:".length).trim();
13151
- coderSkillPaths = _internals19.parseSkillPaths(fieldVal);
13301
+ coderSkillPaths = _internals20.parseSkillPaths(fieldVal);
13152
13302
  break;
13153
13303
  }
13154
13304
  }
13155
13305
  }
13156
13306
  const safeCoderSkillPaths = coderSkillPaths.flatMap((skillPath) => {
13157
- const validation = _internals19.validateSkillReference(directory, skillPath, audienceContext, { enforceAudience: false });
13307
+ const validation = _internals20.validateSkillReference(directory, skillPath, audienceContext, { enforceAudience: false });
13158
13308
  return validation.valid && validation.skillPath ? [validation.skillPath] : [];
13159
13309
  });
13160
13310
  const allPaths = [...new Set([...skillPaths, ...safeCoderSkillPaths])];
13161
13311
  for (const skillPath of allPaths) {
13162
13312
  try {
13163
- _internals19.appendSkillUsageEntry(directory, {
13313
+ _internals20.appendSkillUsageEntry(directory, {
13164
13314
  skillPath,
13165
13315
  agentName: targetBase,
13166
13316
  taskID: taskId,
@@ -13177,18 +13327,18 @@ async function skillPropagationGateBefore(directory, input, config) {
13177
13327
  let scored = [];
13178
13328
  if (skillsValue.toLowerCase() !== "none" && availableSkills.length > 0) {
13179
13329
  try {
13180
- const sessionEntries = _internals19.readSkillUsageEntriesTail(directory, {
13330
+ const sessionEntries = _internals20.readSkillUsageEntriesTail(directory, {
13181
13331
  sessionID
13182
13332
  });
13183
- if (sessionEntries.length > _internals19.MAX_SCORING_SESSION_ENTRIES) {
13333
+ if (sessionEntries.length > _internals20.MAX_SCORING_SESSION_ENTRIES) {
13184
13334
  scoringSkipped = true;
13185
- warn(`[skill-propagation-gate] skipping scoring \u2014 tail window has ${sessionEntries.length} session entries (limit: ${_internals19.MAX_SCORING_SESSION_ENTRIES})`);
13335
+ warn(`[skill-propagation-gate] skipping scoring \u2014 tail window has ${sessionEntries.length} session entries (limit: ${_internals20.MAX_SCORING_SESSION_ENTRIES})`);
13186
13336
  } else {
13187
13337
  const prompt = typeof input.args?.prompt === "string" ? String(input.args.prompt) : "";
13188
13338
  scored = availableSkills.map((skillPath) => {
13189
13339
  const skillEntries = sessionEntries.filter((e) => e.skillPath === skillPath);
13190
- const metadata = metadataBySkillPath.get(skillPath) ?? _internals19.readSkillMetadata(skillPath, directory);
13191
- const score = _internals19.computeSkillRelevanceScore(skillPath, prompt, skillEntries, metadata);
13340
+ const metadata = metadataBySkillPath.get(skillPath) ?? _internals20.readSkillMetadata(skillPath, directory);
13341
+ const score = _internals20.computeSkillRelevanceScore(skillPath, prompt, skillEntries, metadata);
13192
13342
  return { skillPath, score, usageCount: skillEntries.length };
13193
13343
  }).sort((a, b) => b.score - a.score || b.usageCount - a.usageCount);
13194
13344
  if (scored.length > 0) {
@@ -13202,11 +13352,11 @@ async function skillPropagationGateBefore(directory, input, config) {
13202
13352
  }
13203
13353
  }
13204
13354
  try {
13205
- const routingPaths = _internals19.loadRoutingSkills(directory, targetBase);
13355
+ const routingPaths = _internals20.loadRoutingSkills(directory, targetBase);
13206
13356
  if (routingPaths.length > 0) {
13207
13357
  const existingPaths = new Set(scored.map((s) => s.skillPath));
13208
13358
  for (const routingPath of routingPaths) {
13209
- const validation = _internals19.validateSkillReference(directory, routingPath, audienceContext, { enforceAudience: true, requireFilePrefix: false });
13359
+ const validation = _internals20.validateSkillReference(directory, routingPath, audienceContext, { enforceAudience: true, requireFilePrefix: false });
13210
13360
  if (!validation.valid || !validation.skillPath)
13211
13361
  continue;
13212
13362
  const eligibleRoutingPath = validation.skillPath;
@@ -13214,7 +13364,7 @@ async function skillPropagationGateBefore(directory, input, config) {
13214
13364
  metadataBySkillPath.set(eligibleRoutingPath, validation.metadata);
13215
13365
  }
13216
13366
  const routedSkillDir = path23.dirname(path23.join(directory, eligibleRoutingPath));
13217
- if (_internals19.existsSync(path23.join(routedSkillDir, "retired.marker")) || _internals19.existsSync(path23.join(routedSkillDir, "stale.marker")))
13367
+ if (_internals20.existsSync(path23.join(routedSkillDir, "retired.marker")) || _internals20.existsSync(path23.join(routedSkillDir, "stale.marker")))
13218
13368
  continue;
13219
13369
  if (!existingPaths.has(eligibleRoutingPath)) {
13220
13370
  scored.push({
@@ -13240,12 +13390,12 @@ async function skillPropagationGateBefore(directory, input, config) {
13240
13390
  } else if (typeof scored !== "undefined" && scored.length > 0) {
13241
13391
  skillsForIndex = scored.map((r) => r.skillPath);
13242
13392
  }
13243
- const formattedIndex = _internals19.formatSkillIndexWithContext(skillsForIndex, directory, metadataBySkillPath);
13393
+ const formattedIndex = _internals20.formatSkillIndexWithContext(skillsForIndex, directory, metadataBySkillPath);
13244
13394
  if (formattedIndex.length > 0) {
13245
13395
  const contextPath = path23.join(directory, ".swarm", "context.md");
13246
13396
  let existingContent = "";
13247
- if (_internals19.existsSync(contextPath)) {
13248
- existingContent = _internals19.readFileSync(contextPath, "utf-8");
13397
+ if (_internals20.existsSync(contextPath)) {
13398
+ existingContent = _internals20.readFileSync(contextPath, "utf-8");
13249
13399
  }
13250
13400
  const sectionHeader = "## Available Skills";
13251
13401
  const newSection = `${sectionHeader}
@@ -13265,10 +13415,10 @@ ${newSection}`;
13265
13415
  }
13266
13416
  }
13267
13417
  const swarmDir = path23.dirname(contextPath);
13268
- if (!_internals19.existsSync(swarmDir)) {
13269
- _internals19.mkdirSync(swarmDir, { recursive: true });
13418
+ if (!_internals20.existsSync(swarmDir)) {
13419
+ _internals20.mkdirSync(swarmDir, { recursive: true });
13270
13420
  }
13271
- _internals19.writeFileSync(contextPath, updatedContent, "utf-8");
13421
+ _internals20.writeFileSync(contextPath, updatedContent, "utf-8");
13272
13422
  }
13273
13423
  } catch (err) {
13274
13424
  warn(`[skill-propagation-gate] failed to write skill index to context.md: ${err instanceof Error ? err.message : String(err)}`);
@@ -13294,7 +13444,7 @@ ${newSection}`;
13294
13444
  });
13295
13445
  const warningMsg = `Skill propagation warning: Delegating to ${targetBase} without SKILLS field. ` + `Available skills: ${skillNames.join(", ")}`;
13296
13446
  try {
13297
- _internals19.writeWarnEvent(directory, {
13447
+ _internals20.writeWarnEvent(directory, {
13298
13448
  type: "skill_propagation_warn",
13299
13449
  timestamp: new Date().toISOString(),
13300
13450
  tool: toolName,
@@ -13326,17 +13476,17 @@ async function skillPropagationTransformScan(directory, output, sessionID, confi
13326
13476
  const validatedProvenancePaths = (fieldValue) => {
13327
13477
  if (remainingProvenanceValidationBudget <= 0)
13328
13478
  return [];
13329
- const references = _internals19.parseSkillPaths(fieldValue).slice(0, remainingProvenanceValidationBudget);
13479
+ const references = _internals20.parseSkillPaths(fieldValue).slice(0, remainingProvenanceValidationBudget);
13330
13480
  remainingProvenanceValidationBudget -= references.length;
13331
13481
  return references.flatMap((reference) => {
13332
- const validation = _internals19.validateSkillReference(directory, reference, audienceContext, { enforceAudience: true });
13482
+ const validation = _internals20.validateSkillReference(directory, reference, audienceContext, { enforceAudience: true });
13333
13483
  return validation.valid && validation.skillPath ? [validation.skillPath] : [];
13334
13484
  });
13335
13485
  };
13336
13486
  let dedupKeys = new Set;
13337
13487
  let existingEntries = [];
13338
13488
  try {
13339
- existingEntries = _internals19.readSkillUsageEntriesTail(directory, {
13489
+ existingEntries = _internals20.readSkillUsageEntriesTail(directory, {
13340
13490
  sessionID
13341
13491
  });
13342
13492
  dedupKeys = new Set(existingEntries.map((e, i) => {
@@ -13407,7 +13557,7 @@ async function skillPropagationTransformScan(directory, output, sessionID, confi
13407
13557
  if (isDuplicate(skillPath, "reviewer", resolvedTaskID))
13408
13558
  continue;
13409
13559
  try {
13410
- _internals19.appendSkillUsageEntry(directory, {
13560
+ _internals20.appendSkillUsageEntry(directory, {
13411
13561
  skillPath,
13412
13562
  agentName: "reviewer",
13413
13563
  taskID: resolvedTaskID,
@@ -13452,14 +13602,14 @@ async function skillPropagationTransformScan(directory, output, sessionID, confi
13452
13602
  }
13453
13603
  if (currentTargetAgent && skillsField && skillsField.toLowerCase() !== "none") {
13454
13604
  const skillPaths = validatedProvenancePaths(skillsField);
13455
- const taskId = _internals19.extractTaskIdFromPrompt(text);
13605
+ const taskId = _internals20.extractTaskIdFromPrompt(text);
13456
13606
  for (const skillPath of skillPaths) {
13457
13607
  if (hadRecordingError)
13458
13608
  break;
13459
13609
  if (isDuplicate(skillPath, currentTargetAgent, taskId))
13460
13610
  continue;
13461
13611
  try {
13462
- _internals19.appendSkillUsageEntry(directory, {
13612
+ _internals20.appendSkillUsageEntry(directory, {
13463
13613
  skillPath,
13464
13614
  agentName: currentTargetAgent,
13465
13615
  taskID: taskId,
@@ -13479,18 +13629,18 @@ async function skillPropagationTransformScan(directory, output, sessionID, confi
13479
13629
  break;
13480
13630
  }
13481
13631
  }
13482
- _internals19.skillPropagationGateBefore = skillPropagationGateBefore;
13483
- _internals19.skillPropagationTransformScan = skillPropagationTransformScan;
13484
- _internals19.writeWarnEvent = writeWarnEvent;
13485
- _internals19.discoverAvailableSkills = discoverAvailableSkills;
13486
- _internals19.parseDelegationArgs = parseDelegationArgs;
13487
- _internals19.parseSkillPaths = parseSkillPaths;
13488
- _internals19.extractFileSkillReferences = extractFileSkillReferences;
13489
- _internals19.validateSkillReference = validateSkillReference;
13490
- _internals19.extractTaskIdFromPrompt = extractTaskIdFromPrompt;
13491
- _internals19.extractSkillsFieldFromPrompt = extractSkillsFieldFromPrompt;
13492
- _internals19.formatSkillIndexWithContext = formatSkillIndexWithContext;
13493
- _internals19.loadRoutingSkills = loadRoutingSkills;
13632
+ _internals20.skillPropagationGateBefore = skillPropagationGateBefore;
13633
+ _internals20.skillPropagationTransformScan = skillPropagationTransformScan;
13634
+ _internals20.writeWarnEvent = writeWarnEvent;
13635
+ _internals20.discoverAvailableSkills = discoverAvailableSkills;
13636
+ _internals20.parseDelegationArgs = parseDelegationArgs;
13637
+ _internals20.parseSkillPaths = parseSkillPaths;
13638
+ _internals20.extractFileSkillReferences = extractFileSkillReferences;
13639
+ _internals20.validateSkillReference = validateSkillReference;
13640
+ _internals20.extractTaskIdFromPrompt = extractTaskIdFromPrompt;
13641
+ _internals20.extractSkillsFieldFromPrompt = extractSkillsFieldFromPrompt;
13642
+ _internals20.formatSkillIndexWithContext = formatSkillIndexWithContext;
13643
+ _internals20.loadRoutingSkills = loadRoutingSkills;
13494
13644
 
13495
13645
  // src/hooks/micro-reflector.ts
13496
13646
  var REFLECT_OUTCOMES = new Set([
@@ -13508,7 +13658,7 @@ async function readTaskTrajectory(directory, taskId) {
13508
13658
  const filePath = validateSwarmPath(directory, rel);
13509
13659
  if (!existsSync12(filePath))
13510
13660
  return [];
13511
- const content = await readFile7(filePath, "utf-8");
13661
+ const content = await readFile8(filePath, "utf-8");
13512
13662
  const out = [];
13513
13663
  for (const line of content.split(`
13514
13664
  `)) {
@@ -13567,7 +13717,7 @@ async function loadConfigForPolicyCurator(directory) {
13567
13717
  async function canonicalExistingPath(candidate) {
13568
13718
  let resolved = path25.resolve(candidate);
13569
13719
  try {
13570
- resolved = await _internals20.realpath(resolved);
13720
+ resolved = await _internals21.realpath(resolved);
13571
13721
  } catch {}
13572
13722
  return resolved;
13573
13723
  }
@@ -14036,8 +14186,8 @@ RETRY: your last output was missing ${result.missing.join("; ")}; produce valid
14036
14186
  async function appendCuratorSkippedEvent(directory, record) {
14037
14187
  try {
14038
14188
  const filePath = path25.join(directory, ".swarm", "events.jsonl");
14039
- await mkdir8(path25.dirname(filePath), { recursive: true });
14040
- await appendFile3(filePath, `${JSON.stringify({
14189
+ await mkdir9(path25.dirname(filePath), { recursive: true });
14190
+ await appendFile4(filePath, `${JSON.stringify({
14041
14191
  timestamp: new Date().toISOString(),
14042
14192
  event: "curator_skipped",
14043
14193
  entry_id: record.entry_id,
@@ -14079,11 +14229,11 @@ async function consumeInsightCandidates(directory, batchLimit = MESO_INSIGHT_BAT
14079
14229
  if (!existsSync13(filePath))
14080
14230
  return [];
14081
14231
  const consumed = [];
14082
- await transactFile(filePath, async (p) => readInsightJsonl(await readFile8(p, "utf-8").catch(() => "")), async (p, data) => {
14232
+ await transactFile(filePath, async (p) => readInsightJsonl(await readFile9(p, "utf-8").catch(() => "")), async (p, data) => {
14083
14233
  const body = data.length === 0 ? "" : `${data.map((c) => JSON.stringify(c)).join(`
14084
14234
  `)}
14085
14235
  `;
14086
- await writeFile7(p, body, "utf-8");
14236
+ await writeFile8(p, body, "utf-8");
14087
14237
  }, (all) => {
14088
14238
  if (all.length === 0)
14089
14239
  return null;
@@ -14362,9 +14512,9 @@ async function curateAndStoreSwarm(lessons, projectName, phaseInfo, directory, c
14362
14512
  } catch {}
14363
14513
  }
14364
14514
  if (!options?.skipAutoPromotion) {
14365
- await _internals20.runAutoPromotion(directory, config);
14515
+ await _internals21.runAutoPromotion(directory, config);
14366
14516
  if (phaseInfo.phase_number > 0) {
14367
- await _internals20.runAutoDemotion(directory, config, phaseInfo.phase_number);
14517
+ await _internals21.runAutoDemotion(directory, config, phaseInfo.phase_number);
14368
14518
  }
14369
14519
  }
14370
14520
  return { stored, reinforced, skipped, rejected, quarantined };
@@ -14479,7 +14629,7 @@ function createKnowledgeCuratorHook(directory, config, options = {}) {
14479
14629
  }
14480
14630
  inFlightEvidenceEntries.add(evidenceKey);
14481
14631
  try {
14482
- await _internals20.curateAndStoreSwarm(batch.lessons, batch.projectName, { phase_number: batch.phaseNumber }, directory, config, {
14632
+ await _internals21.curateAndStoreSwarm(batch.lessons, batch.projectName, { phase_number: batch.phaseNumber }, directory, config, {
14483
14633
  llmDelegate: options.llmDelegateFactory?.(trigger.sessionID),
14484
14634
  enrichmentQuota: options.enrichmentQuota
14485
14635
  });
@@ -14511,14 +14661,14 @@ function createKnowledgeCuratorHook(directory, config, options = {}) {
14511
14661
  const projectName = projectNameMatch ? projectNameMatch[1].trim() : "unknown";
14512
14662
  const phaseMatch = /^Phase:\s*(\d+)/m.exec(planContent);
14513
14663
  const phaseNumber = phaseMatch ? parseInt(phaseMatch[1], 10) : 1;
14514
- await _internals20.curateAndStoreSwarm(normalLessons, projectName, { phase_number: phaseNumber }, directory, config, {
14664
+ await _internals21.curateAndStoreSwarm(normalLessons, projectName, { phase_number: phaseNumber }, directory, config, {
14515
14665
  llmDelegate: options.llmDelegateFactory?.(trigger.sessionID),
14516
14666
  enrichmentQuota: options.enrichmentQuota
14517
14667
  });
14518
14668
  };
14519
14669
  return safeHook(handler);
14520
14670
  }
14521
- var _internals20 = {
14671
+ var _internals21 = {
14522
14672
  isWriteToEvidenceFile,
14523
14673
  curateAndStoreSwarm,
14524
14674
  runAutoPromotion,
@@ -14557,7 +14707,7 @@ async function runFinalizeRewardSweep(args) {
14557
14707
  return result;
14558
14708
  }
14559
14709
  const timestamp = args.timestamp ?? new Date().toISOString();
14560
- const provider = _internals21.createConfiguredMemoryProvider(directory, memoryConfig);
14710
+ const provider = _internals22.createConfiguredMemoryProvider(directory, memoryConfig);
14561
14711
  try {
14562
14712
  result.swept = true;
14563
14713
  for (const taskId of taskIds) {
@@ -14577,7 +14727,7 @@ async function runFinalizeRewardSweep(args) {
14577
14727
  }
14578
14728
  let taskRewarded = 0;
14579
14729
  for (const runId of runIds) {
14580
- const { memoriesRewarded } = await _internals21.applyCouncilReward(provider, {
14730
+ const { memoriesRewarded } = await _internals22.applyCouncilReward(provider, {
14581
14731
  runId,
14582
14732
  unitId: taskId,
14583
14733
  reward: FINALIZE_NEGATIVE_TERMINAL_REWARD,
@@ -14603,7 +14753,7 @@ async function runFinalizeRewardSweep(args) {
14603
14753
  }
14604
14754
  return result;
14605
14755
  }
14606
- var _internals21 = {
14756
+ var _internals22 = {
14607
14757
  createConfiguredMemoryProvider,
14608
14758
  applyCouncilReward
14609
14759
  };
@@ -15009,12 +15159,12 @@ async function writeSessionReflection(directory, result) {
15009
15159
 
15010
15160
  // src/services/skill-improver.ts
15011
15161
  import { existsSync as existsSync15 } from "fs";
15012
- import { mkdir as mkdir10, readFile as readFile9, rename as rename5, writeFile as writeFile9 } from "fs/promises";
15162
+ import { mkdir as mkdir11, readFile as readFile10, rename as rename6, writeFile as writeFile10 } from "fs/promises";
15013
15163
  import * as path28 from "path";
15014
15164
  init_logger();
15015
15165
 
15016
15166
  // src/services/trajectory-cluster.ts
15017
- import { mkdir as mkdir9, writeFile as writeFile8 } from "fs/promises";
15167
+ import { mkdir as mkdir10, writeFile as writeFile9 } from "fs/promises";
15018
15168
  import * as path27 from "path";
15019
15169
  init_logger();
15020
15170
  var MACRO_TRAJECTORY_WINDOW = 200;
@@ -15148,11 +15298,11 @@ async function writeMotifProposals(directory, opts = {}) {
15148
15298
  return result;
15149
15299
  const max = opts.maxProposals ?? 10;
15150
15300
  const proposalsDir = validateSwarmPath(directory, path27.join("skills", "proposals"));
15151
- await mkdir9(proposalsDir, { recursive: true });
15301
+ await mkdir10(proposalsDir, { recursive: true });
15152
15302
  for (const motif of motifs.slice(0, max)) {
15153
15303
  const slug = `motif-${slugify(motif.signature)}`;
15154
15304
  const filePath = path27.join(proposalsDir, `${slug}.md`);
15155
- await writeFile8(filePath, buildMotifProposal(motif), "utf-8");
15305
+ await writeFile9(filePath, buildMotifProposal(motif), "utf-8");
15156
15306
  result.proposalsWritten.push(filePath);
15157
15307
  }
15158
15308
  return result;
@@ -15293,11 +15443,11 @@ async function writeSuccessMotifProposals(directory, opts = {}) {
15293
15443
  return result;
15294
15444
  const max = opts.maxProposals ?? 10;
15295
15445
  const proposalsDir = validateSwarmPath(directory, path27.join("skills", "proposals"));
15296
- await mkdir9(proposalsDir, { recursive: true });
15446
+ await mkdir10(proposalsDir, { recursive: true });
15297
15447
  for (const motif of motifs.slice(0, max)) {
15298
15448
  const slug = workflowSlug(motif.signature);
15299
15449
  const filePath = path27.join(proposalsDir, `${slug}.md`);
15300
- await writeFile8(filePath, buildWorkflowProposal(motif), "utf-8");
15450
+ await writeFile9(filePath, buildWorkflowProposal(motif), "utf-8");
15301
15451
  result.proposalsWritten.push(filePath);
15302
15452
  }
15303
15453
  return result;
@@ -15419,10 +15569,10 @@ function timestampSlug(d) {
15419
15569
  return d.toISOString().replace(/[:.]/g, "-");
15420
15570
  }
15421
15571
  async function atomicWrite(p, content) {
15422
- await mkdir10(path28.dirname(p), { recursive: true });
15572
+ await mkdir11(path28.dirname(p), { recursive: true });
15423
15573
  const tmp = `${p}.tmp-${process.pid}-${Date.now()}`;
15424
- await writeFile9(tmp, content, "utf-8");
15425
- await rename5(tmp, p);
15574
+ await writeFile10(tmp, content, "utf-8");
15575
+ await rename6(tmp, p);
15426
15576
  }
15427
15577
  async function gatherInventory(directory) {
15428
15578
  const swarm = await readKnowledge(resolveSwarmKnowledgePath(directory));
@@ -15436,7 +15586,7 @@ async function gatherInventory(directory) {
15436
15586
  for (const skill of skills.active) {
15437
15587
  let content;
15438
15588
  try {
15439
- content = await readFile9(skill.path, "utf-8");
15589
+ content = await readFile10(skill.path, "utf-8");
15440
15590
  } catch {
15441
15591
  continue;
15442
15592
  }
@@ -15612,7 +15762,7 @@ async function reconcileStaleActiveSkills(directory, options = {}) {
15612
15762
  for (const skill of skills.active) {
15613
15763
  let content;
15614
15764
  try {
15615
- content = await readFile9(skill.path, "utf-8");
15765
+ content = await readFile10(skill.path, "utf-8");
15616
15766
  } catch {
15617
15767
  continue;
15618
15768
  }
@@ -15630,7 +15780,7 @@ async function reconcileStaleActiveSkills(directory, options = {}) {
15630
15780
  continue;
15631
15781
  }
15632
15782
  try {
15633
- const regen = await _internals22.regenerateSkill(directory, skill.slug, {
15783
+ const regen = await _internals23.regenerateSkill(directory, skill.slug, {
15634
15784
  evaluate: false
15635
15785
  });
15636
15786
  if (regen.regenerated) {
@@ -15880,7 +16030,7 @@ async function runSkillImprover(req) {
15880
16030
  autoApply
15881
16031
  };
15882
16032
  }
15883
- var _internals22 = {
16033
+ var _internals23 = {
15884
16034
  runSkillImprover,
15885
16035
  buildDeterministicProposal,
15886
16036
  buildLLMProposalFrame,
@@ -16283,13 +16433,13 @@ var write_retro = createSwarmTool({
16283
16433
  task_id: args.task_id !== undefined ? String(args.task_id) : undefined,
16284
16434
  metadata: args.metadata
16285
16435
  };
16286
- return await _internals23.executeWriteRetro(writeRetroArgs, directory);
16436
+ return await _internals24.executeWriteRetro(writeRetroArgs, directory);
16287
16437
  } catch {
16288
16438
  return JSON.stringify({ success: false, phase: rawPhase, message: "Invalid arguments" }, null, 2);
16289
16439
  }
16290
16440
  }
16291
16441
  });
16292
- var _internals23 = {
16442
+ var _internals24 = {
16293
16443
  executeWriteRetro,
16294
16444
  write_retro
16295
16445
  };
@@ -16595,8 +16745,8 @@ async function runFinalizeStage(ctx) {
16595
16745
  ];
16596
16746
  ctx.curationSucceeded = false;
16597
16747
  try {
16598
- ctx.curationResult = await _internals24.curateAndStoreSwarm(ctx.allLessons, ctx.projectName, { phase_number: 0 }, ctx.directory, ctx.config, {
16599
- llmDelegate: _internals24.createCuratorLLMDelegate(ctx.directory, "phase", ctx.options.sessionID),
16748
+ ctx.curationResult = await _internals25.curateAndStoreSwarm(ctx.allLessons, ctx.projectName, { phase_number: 0 }, ctx.directory, ctx.config, {
16749
+ llmDelegate: _internals25.createCuratorLLMDelegate(ctx.directory, "phase", ctx.options.sessionID),
16600
16750
  enrichmentQuota: {
16601
16751
  maxCalls: ctx.config.enrichment.max_calls_per_day,
16602
16752
  window: ctx.config.enrichment.quota_window
@@ -16615,7 +16765,7 @@ async function runFinalizeStage(ctx) {
16615
16765
  if (ctx.config.hive_enabled === false) {} else {
16616
16766
  try {
16617
16767
  const entries = await readKnowledge(resolveSwarmKnowledgePath(ctx.directory));
16618
- const result = await _internals24.checkHivePromotions(entries, ctx.config, ctx.directory);
16768
+ const result = await _internals25.checkHivePromotions(entries, ctx.config, ctx.directory);
16619
16769
  ctx.hivePromoted = result.new_promotions;
16620
16770
  } catch (hiveErr) {
16621
16771
  const msg = hiveErr instanceof Error ? hiveErr.message : String(hiveErr);
@@ -16636,7 +16786,7 @@ async function runFinalizeStage(ctx) {
16636
16786
  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.` : "";
16637
16787
  if (ctx.runSkillReview) {
16638
16788
  try {
16639
- const { config: loadedConfig } = _internals24.loadPluginConfigWithMeta(ctx.directory);
16789
+ const { config: loadedConfig } = _internals25.loadPluginConfigWithMeta(ctx.directory);
16640
16790
  const skillImproverConfig = SkillImproverConfigSchema.parse(loadedConfig.skill_improver ?? {});
16641
16791
  const skillReviewResult = await runAbortableSkillReview({
16642
16792
  directory: ctx.directory,
@@ -16699,7 +16849,7 @@ async function runFinalizeStage(ctx) {
16699
16849
  }
16700
16850
  if (!ctx.planAlreadyDone || ctx.guaranteeResult.closedPhaseIds.length > 0 || ctx.guaranteeResult.closedTaskIds.length > 0) {
16701
16851
  try {
16702
- await _internals24.closePlanTerminalState(ctx.directory, ctx.planData, {
16852
+ await _internals25.closePlanTerminalState(ctx.directory, ctx.planData, {
16703
16853
  closedPhaseIds: ctx.guaranteeResult.closedPhaseIds,
16704
16854
  closedTaskIds: ctx.guaranteeResult.closedTaskIds,
16705
16855
  originalStatuses: ctx.originalStatuses
@@ -16716,11 +16866,11 @@ async function runFinalizeStage(ctx) {
16716
16866
  }
16717
16867
  try {
16718
16868
  const { CuratorConfigSchema: CCS } = await import("./schema-vwxpsk6j.js");
16719
- const { config: pmLoadedConfig } = _internals24.loadPluginConfigWithMeta(ctx.directory);
16869
+ const { config: pmLoadedConfig } = _internals25.loadPluginConfigWithMeta(ctx.directory);
16720
16870
  const curatorCfg = CCS.parse(pmLoadedConfig.curator ?? {});
16721
16871
  if (curatorCfg.enabled && curatorCfg.postmortem_enabled) {
16722
- const pmResult = await _internals24.runCuratorPostMortem(ctx.directory, {
16723
- llmDelegate: _internals24.createCuratorLLMDelegate(ctx.directory, "postmortem", ctx.options.sessionID),
16872
+ const pmResult = await _internals25.runCuratorPostMortem(ctx.directory, {
16873
+ llmDelegate: _internals25.createCuratorLLMDelegate(ctx.directory, "postmortem", ctx.options.sessionID),
16724
16874
  scope: "project",
16725
16875
  sessionID: ctx.options.sessionID
16726
16876
  });
@@ -16746,7 +16896,7 @@ async function copySqliteSafe(srcPath, destPath, laneEnv) {
16746
16896
  }
16747
16897
  let checkpointVerified = false;
16748
16898
  try {
16749
- const result = _internals24.spawnSync("sqlite3", [srcPath, "PRAGMA wal_checkpoint(TRUNCATE);"], {
16899
+ const result = _internals25.spawnSync("sqlite3", [srcPath, "PRAGMA wal_checkpoint(TRUNCATE);"], {
16750
16900
  cwd: path31.dirname(srcPath),
16751
16901
  encoding: "utf-8",
16752
16902
  stdio: ["ignore", "pipe", "pipe"],
@@ -16913,7 +17063,7 @@ async function runArchiveEvidenceRetention(ctx) {
16913
17063
  let maxAgeDays = 30;
16914
17064
  let maxBundles = 10;
16915
17065
  try {
16916
- const { config: evidenceLoadedConfig } = _internals24.loadPluginConfigWithMeta(ctx.directory);
17066
+ const { config: evidenceLoadedConfig } = _internals25.loadPluginConfigWithMeta(ctx.directory);
16917
17067
  const evidenceCfg = evidenceLoadedConfig.evidence ?? {};
16918
17068
  if (typeof evidenceCfg.max_age_days === "number") {
16919
17069
  maxAgeDays = evidenceCfg.max_age_days;
@@ -16923,7 +17073,7 @@ async function runArchiveEvidenceRetention(ctx) {
16923
17073
  }
16924
17074
  } catch {}
16925
17075
  try {
16926
- await _internals24.archiveEvidence(ctx.directory, maxAgeDays, maxBundles);
17076
+ await _internals25.archiveEvidence(ctx.directory, maxAgeDays, maxBundles);
16927
17077
  } catch (error2) {
16928
17078
  const msg = error2 instanceof Error ? error2.message : String(error2);
16929
17079
  ctx.warnings.push(`Evidence retention archive failed: ${msg}`);
@@ -17126,9 +17276,9 @@ async function runAlignStage(ctx) {
17126
17276
  const pruneBranches = ctx.args.includes("--prune-branches");
17127
17277
  let gitAlignResult = "";
17128
17278
  const prunedBranches = [];
17129
- const gitStatus = _internals24.getGitRepositoryStatus(ctx.directory);
17279
+ const gitStatus = _internals25.getGitRepositoryStatus(ctx.directory);
17130
17280
  if (gitStatus.isRepo) {
17131
- const aggressiveResult = await _internals24.resetToMainAfterMerge(ctx.directory, {
17281
+ const aggressiveResult = await _internals25.resetToMainAfterMerge(ctx.directory, {
17132
17282
  pruneBranches
17133
17283
  });
17134
17284
  if (aggressiveResult.success) {
@@ -17140,7 +17290,7 @@ async function runAlignStage(ctx) {
17140
17290
  ctx.warnings.push("Uncommitted changes were discarded during git alignment");
17141
17291
  }
17142
17292
  } else {
17143
- const alignResult = await _internals24.resetToRemoteBranch(ctx.directory, {
17293
+ const alignResult = await _internals25.resetToRemoteBranch(ctx.directory, {
17144
17294
  pruneBranches
17145
17295
  });
17146
17296
  gitAlignResult = alignResult.message;
@@ -17176,7 +17326,7 @@ async function runFinalizeDryRun(directory, swarmDir, planData, planExists) {
17176
17326
  const wouldArchiveDirs = ACTIVE_STATE_DIRS_TO_CLEAN.filter(existsInSwarm);
17177
17327
  const wouldRemoveTerminal = TERMINAL_STATE_FILES.filter(existsInSwarm);
17178
17328
  const wouldCleanFiles = ACTIVE_STATE_TO_CLEAN.filter((f) => existsInSwarm(f) && !TERMINAL_STATE_FILES.includes(f));
17179
- const gitStatus = _internals24.getGitRepositoryStatus(directory);
17329
+ const gitStatus = _internals25.getGitRepositoryStatus(directory);
17180
17330
  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)";
17181
17331
  const lines = [
17182
17332
  "## /swarm finalize \u2014 DRY RUN (no changes made)",
@@ -17248,12 +17398,12 @@ async function handleCloseCommand(directory, args, options = {}) {
17248
17398
  }
17249
17399
  }
17250
17400
  if (args.includes("--dry-run")) {
17251
- return _internals24.runFinalizeDryRun(directory, swarmDir, planData, planExists);
17401
+ return _internals25.runFinalizeDryRun(directory, swarmDir, planData, planExists);
17252
17402
  }
17253
17403
  let finalizeLock = {
17254
17404
  acquired: false
17255
17405
  };
17256
- finalizeLock = await _internals24.acquireFinalizeLock(directory);
17406
+ finalizeLock = await _internals25.acquireFinalizeLock(directory);
17257
17407
  if (!finalizeLock.acquired) {
17258
17408
  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.`;
17259
17409
  }
@@ -17284,7 +17434,7 @@ This project was already finalized in a previous /swarm close run. The plan has
17284
17434
  if (planExists) {
17285
17435
  planAlreadyDone = phases.length > 0 && phases.every((p) => p.status === "complete" || p.status === "completed" || p.status === "blocked" || p.status === "closed");
17286
17436
  }
17287
- const { config: loadedConfig } = _internals24.loadPluginConfigWithMeta(directory);
17437
+ const { config: loadedConfig } = _internals25.loadPluginConfigWithMeta(directory);
17288
17438
  const config = KnowledgeConfigSchema.parse(loadedConfig.knowledge ?? {});
17289
17439
  const ctx = {
17290
17440
  directory,
@@ -17328,7 +17478,7 @@ This project was already finalized in a previous /swarm close run. The plan has
17328
17478
  args
17329
17479
  };
17330
17480
  await runFinalizeStage(ctx);
17331
- await _internals24.runFinalizeRewardSweep({
17481
+ await _internals25.runFinalizeRewardSweep({
17332
17482
  directory,
17333
17483
  closedTaskIds: ctx.guaranteeResult.closedTaskIds,
17334
17484
  memoryConfig: loadedConfig.memory
@@ -17410,9 +17560,9 @@ This project was already finalized in a previous /swarm close run. The plan has
17410
17560
  try {
17411
17561
  const sessionIdsToEnd = [...swarmState.agentSessions.keys()];
17412
17562
  for (const sessionId of sessionIdsToEnd) {
17413
- _internals24.endAgentSession(sessionId);
17563
+ _internals25.endAgentSession(sessionId);
17414
17564
  }
17415
- _internals24.resetSwarmStatePreservingSingletons();
17565
+ _internals25.resetSwarmStatePreservingSingletons();
17416
17566
  } catch (teardownError) {
17417
17567
  const msg = teardownError instanceof Error ? teardownError.message : String(teardownError);
17418
17568
  ctx.warnings.push(`Session teardown encountered an error after finalization completed (state may not be fully reset): ${msg}`);
@@ -17486,7 +17636,7 @@ async function acquireFinalizeLock(directory) {
17486
17636
  }
17487
17637
  return { acquired: false };
17488
17638
  }
17489
- var _internals24 = {
17639
+ var _internals25 = {
17490
17640
  ACTIVE_STATE_DIRS_TO_CLEAN,
17491
17641
  countSessionKnowledgeEntries,
17492
17642
  CLOSE_SKILL_REVIEW_TIMEOUT_MS,
@@ -17779,7 +17929,7 @@ async function handleConfigCommand(directory, _args) {
17779
17929
 
17780
17930
  // src/services/skill-consolidation.ts
17781
17931
  import { existsSync as existsSync19 } from "fs";
17782
- import { mkdir as mkdir11, readFile as readFile10, rename as rename6, writeFile as writeFile10 } from "fs/promises";
17932
+ import { mkdir as mkdir12, readFile as readFile11, rename as rename7, writeFile as writeFile11 } from "fs/promises";
17783
17933
  import * as path33 from "path";
17784
17934
  var DEFAULT_CONSOLIDATION_INTERVAL_HOURS = 24;
17785
17935
  var DEFAULT_CONSOLIDATION_MAX_CALLS_PER_RUN = 1;
@@ -17793,7 +17943,7 @@ async function readState2(directory) {
17793
17943
  if (!existsSync19(filePath))
17794
17944
  return {};
17795
17945
  try {
17796
- const parsed = JSON.parse(await readFile10(filePath, "utf-8"));
17946
+ const parsed = JSON.parse(await readFile11(filePath, "utf-8"));
17797
17947
  if (!parsed || typeof parsed !== "object")
17798
17948
  return {};
17799
17949
  return parsed;
@@ -17802,10 +17952,10 @@ async function readState2(directory) {
17802
17952
  }
17803
17953
  }
17804
17954
  async function atomicWrite2(filePath, content) {
17805
- await mkdir11(path33.dirname(filePath), { recursive: true });
17955
+ await mkdir12(path33.dirname(filePath), { recursive: true });
17806
17956
  const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
17807
- await writeFile10(tmp, content, "utf-8");
17808
- await rename6(tmp, filePath);
17957
+ await writeFile11(tmp, content, "utf-8");
17958
+ await rename7(tmp, filePath);
17809
17959
  }
17810
17960
  async function writeState2(directory, state) {
17811
17961
  await atomicWrite2(consolidationStatePath(directory), `${JSON.stringify(state, null, 2)}
@@ -18092,7 +18242,7 @@ import { promisify as promisify2 } from "util";
18092
18242
  // src/tools/co-change-analyzer.ts
18093
18243
  import * as child_process4 from "child_process";
18094
18244
  import { randomUUID as randomUUID5 } from "crypto";
18095
- import { readdir, readFile as readFile11, stat as stat3 } from "fs/promises";
18245
+ import { readdir, readFile as readFile12, stat as stat3 } from "fs/promises";
18096
18246
  import * as path34 from "path";
18097
18247
  import { promisify } from "util";
18098
18248
  function getExecFileAsync() {
@@ -18219,7 +18369,7 @@ async function getStaticEdges(directory) {
18219
18369
  const sourceFiles = await scanSourceFiles(directory);
18220
18370
  for (const sourceFile of sourceFiles) {
18221
18371
  try {
18222
- const content = await readFile11(sourceFile, "utf-8");
18372
+ const content = await readFile12(sourceFile, "utf-8");
18223
18373
  const importRegex = /(?:import|require)\s*(?:\(?\s*['"`]|.*?from\s+['"`])([^'"`]+)['"`]/g;
18224
18374
  for (let match = importRegex.exec(content);match !== null; match = importRegex.exec(content)) {
18225
18375
  const importPath = match[1].trim();
@@ -18314,9 +18464,9 @@ async function detectDarkMatter(directory, options) {
18314
18464
  } catch {
18315
18465
  return [];
18316
18466
  }
18317
- const commitMap = await _internals25.parseGitLog(directory, maxCommitsToAnalyze);
18318
- const matrix = _internals25.buildCoChangeMatrix(commitMap, maxFilesPerCommit);
18319
- const staticEdges = await _internals25.getStaticEdges(directory);
18467
+ const commitMap = await _internals26.parseGitLog(directory, maxCommitsToAnalyze);
18468
+ const matrix = _internals26.buildCoChangeMatrix(commitMap, maxFilesPerCommit);
18469
+ const staticEdges = await _internals26.getStaticEdges(directory);
18320
18470
  const results = [];
18321
18471
  for (const entry of matrix.values()) {
18322
18472
  const key = `${entry.fileA}::${entry.fileB}`;
@@ -18432,11 +18582,11 @@ var co_change_analyzer = createSwarmTool({
18432
18582
  npmiThreshold,
18433
18583
  maxCommitsToAnalyze
18434
18584
  };
18435
- const pairs = await _internals25.detectDarkMatter(directory, options);
18436
- return _internals25.formatDarkMatterOutput(pairs);
18585
+ const pairs = await _internals26.detectDarkMatter(directory, options);
18586
+ return _internals26.formatDarkMatterOutput(pairs);
18437
18587
  }
18438
18588
  });
18439
- var _internals25 = {
18589
+ var _internals26 = {
18440
18590
  parseGitLog,
18441
18591
  buildCoChangeMatrix,
18442
18592
  getStaticEdges,
@@ -18453,7 +18603,7 @@ var DEFAULT_MAX_COMMITS = 500;
18453
18603
  var cache = new Map;
18454
18604
  async function readGitHead(directory) {
18455
18605
  try {
18456
- const { stdout } = await _internals26.execFile("git", ["rev-parse", "HEAD"], {
18606
+ const { stdout } = await _internals27.execFile("git", ["rev-parse", "HEAD"], {
18457
18607
  cwd: directory,
18458
18608
  timeout: GIT_HEAD_TIMEOUT_MS
18459
18609
  });
@@ -18479,9 +18629,9 @@ async function getCoChangeData(directory, options) {
18479
18629
  let entries;
18480
18630
  let commitsObserved;
18481
18631
  try {
18482
- const commitMap = await _internals26.parseGitLog(directory, maxCommits);
18632
+ const commitMap = await _internals27.parseGitLog(directory, maxCommits);
18483
18633
  commitsObserved = commitMap.size;
18484
- const matrix = _internals26.buildCoChangeMatrix(commitMap);
18634
+ const matrix = _internals27.buildCoChangeMatrix(commitMap);
18485
18635
  entries = Array.from(matrix.values());
18486
18636
  } catch {
18487
18637
  return { pairs: [], commitsObserved: 0 };
@@ -18505,10 +18655,10 @@ async function getCoChangePairs(directory, options) {
18505
18655
  const data = await getCoChangeData(directory, options);
18506
18656
  return data.pairs;
18507
18657
  }
18508
- var _internals26 = {
18658
+ var _internals27 = {
18509
18659
  execFile: execFileAsync,
18510
- parseGitLog: _internals25.parseGitLog,
18511
- buildCoChangeMatrix: _internals25.buildCoChangeMatrix
18660
+ parseGitLog: _internals26.parseGitLog,
18661
+ buildCoChangeMatrix: _internals26.buildCoChangeMatrix
18512
18662
  };
18513
18663
 
18514
18664
  // src/turbo/epic/cochange-conflict.ts
@@ -18790,7 +18940,7 @@ async function handleCouplingCommand(directory, args) {
18790
18940
 
18791
18941
  Usage: /swarm coupling [--phase <n>] [--threshold <-1..1>] [--min-co-changes <n>] [--format markdown|json] [--persist]`;
18792
18942
  }
18793
- const plan = await _internals27.loadPlanJsonOnly(directory);
18943
+ const plan = await _internals28.loadPlanJsonOnly(directory);
18794
18944
  if (plan === null) {
18795
18945
  return "No plan found at `.swarm/plan.json`. Run `/swarm plan` to create one before measuring coupling.";
18796
18946
  }
@@ -18814,7 +18964,7 @@ Usage: /swarm coupling [--phase <n>] [--threshold <-1..1>] [--min-co-changes <n>
18814
18964
  const scope = scopeFiles ?? task.files_touched ?? [];
18815
18965
  return { id: task.id, scope };
18816
18966
  });
18817
- const cochangePairs = await _internals27.getCoChangePairs(directory);
18967
+ const cochangePairs = await _internals28.getCoChangePairs(directory);
18818
18968
  const report = computeCouplingReport(tasks, cochangePairs, {
18819
18969
  npmi: parsed.threshold,
18820
18970
  minCoChanges: parsed.minCoChanges
@@ -18853,13 +19003,13 @@ _Warning: failed to persist report (${persistStatus.error})._`;
18853
19003
  }
18854
19004
  return `${formatCouplingReportMarkdown(report)}${persistTrailer}`;
18855
19005
  }
18856
- var _internals27 = {
19006
+ var _internals28 = {
18857
19007
  loadPlanJsonOnly,
18858
19008
  getCoChangePairs
18859
19009
  };
18860
19010
 
18861
19011
  // src/commands/curate.ts
18862
- var _internals28 = {
19012
+ var _internals29 = {
18863
19013
  checkHivePromotions,
18864
19014
  readKnowledge,
18865
19015
  resolveSwarmKnowledgePath,
@@ -18867,8 +19017,8 @@ var _internals28 = {
18867
19017
  loadCuratorDeps: async () => {
18868
19018
  const [{ CuratorConfigSchema }, curator, { createCuratorLLMDelegate: createCuratorLLMDelegate2 }] = await Promise.all([
18869
19019
  import("./schema-vwxpsk6j.js"),
18870
- import("./curator-ed91r7rw.js"),
18871
- import("./curator-llm-factory-q9veqj3h.js")
19020
+ import("./curator-3rze3pd4.js"),
19021
+ import("./curator-llm-factory-8rg0f77t.js")
18872
19022
  ]);
18873
19023
  return { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 };
18874
19024
  }
@@ -18876,15 +19026,15 @@ var _internals28 = {
18876
19026
  async function handleCurateCommand(directory, _args, options) {
18877
19027
  try {
18878
19028
  const config = KnowledgeConfigSchema.parse({});
18879
- const swarmPath = _internals28.resolveSwarmKnowledgePath(directory);
18880
- const swarmEntries = await _internals28.readKnowledge(swarmPath) ?? [];
18881
- const summary = await _internals28.checkHivePromotions(swarmEntries, config, directory);
19029
+ const swarmPath = _internals29.resolveSwarmKnowledgePath(directory);
19030
+ const swarmEntries = await _internals29.readKnowledge(swarmPath) ?? [];
19031
+ const summary = await _internals29.checkHivePromotions(swarmEntries, config, directory);
18882
19032
  if (options?.sessionID) {
18883
19033
  let onDemandPhase = 1;
18884
19034
  try {
18885
- const { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 } = await _internals28.loadCuratorDeps();
19035
+ const { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 } = await _internals29.loadCuratorDeps();
18886
19036
  const curatorConfig = CuratorConfigSchema.parse({});
18887
- const priorSummary = await _internals28.readSwarmFileAsync(directory, "curator-summary.json");
19037
+ const priorSummary = await _internals29.readSwarmFileAsync(directory, "curator-summary.json");
18888
19038
  if (priorSummary) {
18889
19039
  try {
18890
19040
  const parsed = JSON.parse(priorSummary);
@@ -18895,7 +19045,7 @@ async function handleCurateCommand(directory, _args, options) {
18895
19045
  }
18896
19046
  let planPhaseCount = Infinity;
18897
19047
  try {
18898
- const planRaw = await _internals28.readSwarmFileAsync(directory, "plan.json");
19048
+ const planRaw = await _internals29.readSwarmFileAsync(directory, "plan.json");
18899
19049
  if (planRaw) {
18900
19050
  const plan = JSON.parse(planRaw);
18901
19051
  if (Array.isArray(plan.phases))
@@ -18914,8 +19064,8 @@ async function handleCurateCommand(directory, _args, options) {
18914
19064
  summary.knowledge_skipped = applied.skipped;
18915
19065
  summary.curator_phase = onDemandPhase;
18916
19066
  try {
18917
- const updatedEntries = await _internals28.readKnowledge(swarmPath) ?? [];
18918
- const postUpdateHive = await _internals28.checkHivePromotions(updatedEntries, config, directory);
19067
+ const updatedEntries = await _internals29.readKnowledge(swarmPath) ?? [];
19068
+ const postUpdateHive = await _internals29.checkHivePromotions(updatedEntries, config, directory);
18919
19069
  summary.new_promotions += postUpdateHive.new_promotions;
18920
19070
  summary.encounters_incremented += postUpdateHive.encounters_incremented;
18921
19071
  summary.advancements += postUpdateHive.advancements;
@@ -18981,7 +19131,7 @@ async function handleDarkMatterCommand(directory, args) {
18981
19131
  }
18982
19132
  let pairs;
18983
19133
  try {
18984
- pairs = await _internals25.detectDarkMatter(directory, options);
19134
+ pairs = await _internals26.detectDarkMatter(directory, options);
18985
19135
  } catch (err) {
18986
19136
  const errMsg = err instanceof Error ? err.message : String(err);
18987
19137
  return `## Dark Matter Analysis Failed
@@ -19245,7 +19395,7 @@ ${USAGE5}`;
19245
19395
 
19246
19396
  // src/commands/design-docs.ts
19247
19397
  var MAX_DESC_LEN = 2000;
19248
- var _internals29 = { loadPluginConfigWithMeta };
19398
+ var _internals30 = { loadPluginConfigWithMeta };
19249
19399
  var USAGE6 = `Usage: /swarm design-docs <description> [--out <dir>] [--lang <name>] [--update]
19250
19400
 
19251
19401
  Generate or sync language-agnostic design docs for the project under build:
@@ -19341,7 +19491,7 @@ async function handleDesignDocsCommand(directory, args) {
19341
19491
  ${USAGE6}`;
19342
19492
  }
19343
19493
  try {
19344
- const { config } = _internals29.loadPluginConfigWithMeta(directory);
19494
+ const { config } = _internals30.loadPluginConfigWithMeta(directory);
19345
19495
  if (config.design_docs?.enabled !== true) {
19346
19496
  return "Error: design docs are disabled. Set `design_docs.enabled: true` in " + `opencode-swarm.json to enable the docs_design agent and this command.
19347
19497
 
@@ -19366,7 +19516,7 @@ import { fileURLToPath } from "url";
19366
19516
  // package.json
19367
19517
  var package_default = {
19368
19518
  name: "opencode-swarm",
19369
- version: "7.121.3",
19519
+ version: "7.122.0",
19370
19520
  description: "Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",
19371
19521
  main: "dist/index.js",
19372
19522
  types: "dist/index.d.ts",
@@ -19466,7 +19616,8 @@ var package_default = {
19466
19616
  "package:smoke": "node scripts/package-smoke.mjs",
19467
19617
  prepare: "bun run build",
19468
19618
  "repro:704": "node scripts/repro-704.mjs",
19469
- "repro:1144": "bun scripts/repro-1144.mjs"
19619
+ "repro:1144": "bun scripts/repro-1144.mjs",
19620
+ "repro:1873": "bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs"
19470
19621
  },
19471
19622
  dependencies: {
19472
19623
  "@opencode-ai/plugin": "^1.1.53",
@@ -19539,7 +19690,7 @@ init_executor();
19539
19690
 
19540
19691
  // src/services/knowledge-diagnostics.ts
19541
19692
  import { existsSync as existsSync21 } from "fs";
19542
- import { readFile as readFile12 } from "fs/promises";
19693
+ import { readFile as readFile13 } from "fs/promises";
19543
19694
  import { join as join32 } from "path";
19544
19695
 
19545
19696
  // src/services/version-check.ts
@@ -19616,7 +19767,7 @@ var INSIGHT_BACKLOG_WARN = 50;
19616
19767
  async function readRawLines(filePath) {
19617
19768
  if (!existsSync21(filePath))
19618
19769
  return { entries: [], corrupt: 0 };
19619
- const content = await readFile12(filePath, "utf-8");
19770
+ const content = await readFile13(filePath, "utf-8");
19620
19771
  const entries = [];
19621
19772
  let corrupt = 0;
19622
19773
  for (const line of content.split(`
@@ -19780,7 +19931,15 @@ async function computeKnowledgeDebug(directory) {
19780
19931
  synonym_pairs: synonymPairs,
19781
19932
  enforced_directives: enforcedDirectives,
19782
19933
  escalated_directives: escalatedDirectives,
19783
- events_by_type: eventsByType
19934
+ events_by_type: eventsByType,
19935
+ shown_vs_applied: {
19936
+ shown: eventsByType.retrieved ?? 0,
19937
+ applied_explicit: eventsByType.applied ?? 0,
19938
+ ignored: eventsByType.ignored ?? 0,
19939
+ contradicted: eventsByType.contradicted ?? 0,
19940
+ violated: eventsByType.violated ?? 0,
19941
+ no_relevant: eventsByType.no_relevant ?? 0
19942
+ }
19784
19943
  },
19785
19944
  cohort: {
19786
19945
  linked: cohortLinked,
@@ -19806,7 +19965,7 @@ async function computeCurationDiagnostics(directory, entries) {
19806
19965
  let scanCompleted = false;
19807
19966
  let scanRemaining = 0;
19808
19967
  try {
19809
- const { getScanStatus } = await import("./scan-cursor-qmsmmg1b.js");
19968
+ const { getScanStatus } = await import("./scan-cursor-nx5y5k7r.js");
19810
19969
  const status = await getScanStatus(directory);
19811
19970
  scanGeneration = status.generation;
19812
19971
  scanCompleted = status.completed;
@@ -19826,7 +19985,7 @@ async function computeCurationDiagnostics(directory, entries) {
19826
19985
  config = KnowledgeConfigSchema2.parse({});
19827
19986
  }
19828
19987
  const { cohortConfigFingerprint: cohortConfigFingerprint2 } = await import("./config-fingerprint-v22xh5a2.js");
19829
- const { buildConfigFingerprintInput: buildConfigFingerprintInput2, readCohortConfigFingerprint } = await import("./curation-policy-10wnhpwn.js");
19988
+ const { buildConfigFingerprintInput: buildConfigFingerprintInput2, readCohortConfigFingerprint } = await import("./curation-policy-cj1tpzr5.js");
19830
19989
  const currentFp = cohortConfigFingerprint2(buildConfigFingerprintInput2(config));
19831
19990
  const cohortFp = await readCohortConfigFingerprint(directory);
19832
19991
  configMatch = cohortFp === null ? null : currentFp === cohortFp;
@@ -19861,7 +20020,7 @@ async function countPendingProposals(directory) {
19861
20020
  if (!existsSync21(proposalsPath))
19862
20021
  return 0;
19863
20022
  try {
19864
- const content = await readFile12(proposalsPath, "utf-8");
20023
+ const content = await readFile13(proposalsPath, "utf-8");
19865
20024
  let n = 0;
19866
20025
  for (const line of content.split(`
19867
20026
  `)) {
@@ -19883,7 +20042,7 @@ async function safeJsonlCount(filePath) {
19883
20042
  if (!filePath || !existsSync21(filePath))
19884
20043
  return 0;
19885
20044
  try {
19886
- const content = await readFile12(filePath, "utf-8");
20045
+ const content = await readFile13(filePath, "utf-8");
19887
20046
  let n = 0;
19888
20047
  for (const line of content.split(`
19889
20048
  `)) {
@@ -19987,7 +20146,7 @@ function resolveCachePackageRoot(cachePath) {
19987
20146
  const nestedPackageRoot = path38.join(cachePath, "node_modules", "opencode-swarm");
19988
20147
  return existsSync22(nestedPackageRoot) ? nestedPackageRoot : cachePath;
19989
20148
  }
19990
- var _internals30 = {
20149
+ var _internals31 = {
19991
20150
  detectSandboxCapability: () => sandboxCapabilityProbe.detect(),
19992
20151
  getSandboxExecutor: getExecutor
19993
20152
  };
@@ -20571,9 +20730,9 @@ async function checkCurator(directory) {
20571
20730
  }
20572
20731
  async function getSandboxStatus() {
20573
20732
  try {
20574
- const capability = await _internals30.detectSandboxCapability();
20733
+ const capability = await _internals31.detectSandboxCapability();
20575
20734
  const mechanism = capability.mechanism ?? "none";
20576
- const executor = await _internals30.getSandboxExecutor();
20735
+ const executor = await _internals31.getSandboxExecutor();
20577
20736
  const hasExecutor = executor !== null;
20578
20737
  if (hasExecutor) {
20579
20738
  const executorStrength = executor?.strength;
@@ -21325,7 +21484,7 @@ function readPromotionEvidence(directory) {
21325
21484
  }
21326
21485
 
21327
21486
  // src/commands/epic.ts
21328
- var _internals31 = {
21487
+ var _internals32 = {
21329
21488
  loadPluginConfigWithMeta,
21330
21489
  loadPlanJsonOnly,
21331
21490
  getCoChangeData,
@@ -21347,7 +21506,7 @@ async function handleEpicCommand(directory, args, sessionID) {
21347
21506
  if (!sessionID || sessionID.trim() === "") {
21348
21507
  return "Error: No active session context. Epic Mode requires an active session. Use /swarm epic from within an OpenCode session.";
21349
21508
  }
21350
- const session = _internals31.ensureAgentSession(sessionID, undefined, directory);
21509
+ const session = _internals32.ensureAgentSession(sessionID, undefined, directory);
21351
21510
  const arg0 = args[0]?.toLowerCase();
21352
21511
  switch (arg0) {
21353
21512
  case "status":
@@ -21374,7 +21533,7 @@ Usage:
21374
21533
  }
21375
21534
  function enableAndAck(directory, sessionID, session) {
21376
21535
  try {
21377
- _internals31.enableEpicMode(directory, sessionID);
21536
+ _internals32.enableEpicMode(directory, sessionID);
21378
21537
  } catch (err) {
21379
21538
  return `Error enabling Epic Mode: ${err instanceof Error ? err.message : String(err)}`;
21380
21539
  }
@@ -21390,7 +21549,7 @@ function enableAndAck(directory, sessionID, session) {
21390
21549
  }
21391
21550
  function disableAndAck(directory, sessionID, session) {
21392
21551
  try {
21393
- _internals31.disableEpicMode(directory, sessionID);
21552
+ _internals32.disableEpicMode(directory, sessionID);
21394
21553
  } catch (err) {
21395
21554
  return `Error disabling Epic Mode: ${err instanceof Error ? err.message : String(err)}`;
21396
21555
  }
@@ -21399,12 +21558,12 @@ function disableAndAck(directory, sessionID, session) {
21399
21558
  }
21400
21559
  function renderStatus(directory, sessionID) {
21401
21560
  const lines = ["## Epic Mode \u2014 Status", ""];
21402
- if (_internals31.isStateUnreadable(directory)) {
21561
+ if (_internals32.isStateUnreadable(directory)) {
21403
21562
  lines.push("**Epic Mode state is unreadable** (`.swarm/epic-state.json` is corrupt or has an unexpected shape). Status cannot be reported until the file is repaired or removed. The fail-closed marker means `epic_decide_phase` will refuse to compute a verdict in this state.");
21404
21563
  return lines.join(`
21405
21564
  `);
21406
21565
  }
21407
- const state = _internals31.loadEpicSessionState(directory, sessionID);
21566
+ const state = _internals32.loadEpicSessionState(directory, sessionID);
21408
21567
  if (!state) {
21409
21568
  lines.push("Epic Mode has not been toggled for this session.");
21410
21569
  return lines.join(`
@@ -21456,7 +21615,7 @@ function formatGreenfieldDetail(input) {
21456
21615
  function renderLast(directory) {
21457
21616
  let records;
21458
21617
  try {
21459
- records = _internals31.readPromotionEvidence(directory);
21618
+ records = _internals32.readPromotionEvidence(directory);
21460
21619
  } catch (err) {
21461
21620
  return `Error reading epic-promotions.jsonl: ${err instanceof Error ? err.message : String(err)}`;
21462
21621
  }
@@ -21511,7 +21670,7 @@ function renderLast(directory) {
21511
21670
  `);
21512
21671
  }
21513
21672
  function renderCalibration(directory) {
21514
- if (_internals31.isCalibrationStateUnreadable(directory)) {
21673
+ if (_internals32.isCalibrationStateUnreadable(directory)) {
21515
21674
  return [
21516
21675
  "## Epic Mode \u2014 Calibration",
21517
21676
  "",
@@ -21523,11 +21682,11 @@ function renderCalibration(directory) {
21523
21682
  }
21524
21683
  let state;
21525
21684
  try {
21526
- state = _internals31.loadCalibrationState(directory);
21685
+ state = _internals32.loadCalibrationState(directory);
21527
21686
  } catch (err) {
21528
21687
  return `Error reading calibration state: ${err instanceof Error ? err.message : String(err)}`;
21529
21688
  }
21530
- const { config } = _internals31.loadPluginConfigWithMeta(directory);
21689
+ const { config } = _internals32.loadPluginConfigWithMeta(directory);
21531
21690
  const staticThreshold = config.turbo?.epic?.mode?.activation_threshold ?? 0.3;
21532
21691
  const calibrationCfg = config.turbo?.epic?.calibration;
21533
21692
  const loosenWindow = calibrationCfg?.loosen_window ?? 10;
@@ -21575,7 +21734,7 @@ function renderCalibration(directory) {
21575
21734
  lines.push("");
21576
21735
  let recentDivergent = [];
21577
21736
  try {
21578
- const all = _internals31.readDivergenceHistory(directory, { limit: 50 });
21737
+ const all = _internals32.readDivergenceHistory(directory, { limit: 50 });
21579
21738
  recentDivergent = all.filter((r) => !r.isClean).slice(-5);
21580
21739
  } catch {}
21581
21740
  lines.push("### Recent divergent tasks (tightened the threshold)");
@@ -21592,11 +21751,11 @@ function renderCalibration(directory) {
21592
21751
  `);
21593
21752
  }
21594
21753
  async function renderDecide(directory) {
21595
- const plan = await _internals31.loadPlanJsonOnly(directory);
21754
+ const plan = await _internals32.loadPlanJsonOnly(directory);
21596
21755
  if (!plan) {
21597
21756
  return "No plan found at `.swarm/plan.json`. Run `/swarm plan` first.";
21598
21757
  }
21599
- const { config } = _internals31.loadPluginConfigWithMeta(directory);
21758
+ const { config } = _internals32.loadPluginConfigWithMeta(directory);
21600
21759
  const modeCfg = config.turbo?.epic?.mode;
21601
21760
  const cochangeCfg = config.turbo?.epic?.cochange;
21602
21761
  const activationThreshold = modeCfg?.activation_threshold ?? 0.3;
@@ -21606,20 +21765,20 @@ async function renderDecide(directory) {
21606
21765
  const tasks = [];
21607
21766
  for (const phase of plan.phases) {
21608
21767
  for (const task of phase.tasks) {
21609
- const scopeFiles = _internals31.readTaskScopes(directory, task.id);
21768
+ const scopeFiles = _internals32.readTaskScopes(directory, task.id);
21610
21769
  const scope = scopeFiles ?? task.files_touched ?? [];
21611
21770
  tasks.push({ id: task.id, scope });
21612
21771
  }
21613
21772
  }
21614
- const { pairs, commitsObserved } = await _internals31.getCoChangeData(directory);
21773
+ const { pairs, commitsObserved } = await _internals32.getCoChangeData(directory);
21615
21774
  const isGitProject = (() => {
21616
21775
  try {
21617
- return _internals31.isGitRepo(directory);
21776
+ return _internals32.isGitRepo(directory);
21618
21777
  } catch {
21619
21778
  return false;
21620
21779
  }
21621
21780
  })();
21622
- const verdict = _internals31.decideEpicActivation(tasks, pairs, commitsObserved, {
21781
+ const verdict = _internals32.decideEpicActivation(tasks, pairs, commitsObserved, {
21623
21782
  activationThreshold,
21624
21783
  minCommitsForSignal,
21625
21784
  cochangeNpmiThreshold,
@@ -21663,7 +21822,7 @@ function formatVerdict(verdict) {
21663
21822
  }
21664
21823
 
21665
21824
  // src/services/evidence-service.ts
21666
- var _internals32 = {
21825
+ var _internals33 = {
21667
21826
  loadEvidence,
21668
21827
  listEvidenceTaskIds
21669
21828
  };
@@ -21708,7 +21867,7 @@ function getVerdictEmoji(verdict) {
21708
21867
  return getVerdictIcon(verdict);
21709
21868
  }
21710
21869
  async function getTaskEvidenceData(directory, taskId) {
21711
- const result = await _internals32.loadEvidence(directory, taskId);
21870
+ const result = await _internals33.loadEvidence(directory, taskId);
21712
21871
  if (result.status !== "found") {
21713
21872
  return {
21714
21873
  hasEvidence: false,
@@ -21731,13 +21890,13 @@ async function getTaskEvidenceData(directory, taskId) {
21731
21890
  };
21732
21891
  }
21733
21892
  async function getEvidenceListData(directory) {
21734
- const taskIds = await _internals32.listEvidenceTaskIds(directory);
21893
+ const taskIds = await _internals33.listEvidenceTaskIds(directory);
21735
21894
  if (taskIds.length === 0) {
21736
21895
  return { hasEvidence: false, tasks: [] };
21737
21896
  }
21738
21897
  const tasks = [];
21739
21898
  for (const taskId of taskIds) {
21740
- const result = await _internals32.loadEvidence(directory, taskId);
21899
+ const result = await _internals33.loadEvidence(directory, taskId);
21741
21900
  if (result.status === "found") {
21742
21901
  tasks.push({
21743
21902
  taskId,
@@ -22632,7 +22791,7 @@ function isStaticallyEquivalent(originalCode, mutatedCode) {
22632
22791
  const strippedMutated = stripCode(mutatedCode);
22633
22792
  return strippedOriginal === strippedMutated;
22634
22793
  }
22635
- var _internals33 = {
22794
+ var _internals34 = {
22636
22795
  isStaticallyEquivalent,
22637
22796
  checkEquivalence,
22638
22797
  batchCheckEquivalence
@@ -22672,7 +22831,7 @@ async function batchCheckEquivalence(patches, llmJudge) {
22672
22831
  const results = [];
22673
22832
  for (const { patch, originalCode, mutatedCode } of patches) {
22674
22833
  try {
22675
- const result = await _internals33.checkEquivalence(patch, originalCode, mutatedCode, llmJudge);
22834
+ const result = await _internals34.checkEquivalence(patch, originalCode, mutatedCode, llmJudge);
22676
22835
  results.push(result);
22677
22836
  } catch (err) {
22678
22837
  results.push({
@@ -22746,10 +22905,10 @@ function isMissingExecutableFailure(message) {
22746
22905
  return /\bENOENT\b/i.test(message) || /\bexecutable\b[^\r\n]*\bnot found\b/i.test(message) || /\bnot found in (?:the )?\$?PATH\b/i.test(message);
22747
22906
  }
22748
22907
  var runMutationCommand = async (args) => {
22749
- const resolvedExecutable = _internals34.resolveExecutableFromPath([
22908
+ const resolvedExecutable = _internals35.resolveExecutableFromPath([
22750
22909
  args.executable
22751
22910
  ]);
22752
- const result = await _internals34.runExternalTool({
22911
+ const result = await _internals35.runExternalTool({
22753
22912
  executable: resolvedExecutable ?? args.executable,
22754
22913
  args: args.args,
22755
22914
  cwd: args.cwd,
@@ -22768,7 +22927,7 @@ var runMutationCommand = async (args) => {
22768
22927
  };
22769
22928
  var runLegacyTestSeam = async (args) => {
22770
22929
  try {
22771
- const result = _internals34.spawnSync(args.executable, args.args, {
22930
+ const result = _internals35.spawnSync(args.executable, args.args, {
22772
22931
  cwd: args.cwd,
22773
22932
  timeout: args.timeoutMs,
22774
22933
  stdio: "pipe"
@@ -22802,11 +22961,11 @@ var runLegacyTestSeam = async (args) => {
22802
22961
  function selectRunner(options) {
22803
22962
  if (options.runner)
22804
22963
  return options.runner;
22805
- if (_internals34.spawnSync !== defaultLegacySpawnSync)
22964
+ if (_internals35.spawnSync !== defaultLegacySpawnSync)
22806
22965
  return runLegacyTestSeam;
22807
- return _internals34.runCommand;
22966
+ return _internals35.runCommand;
22808
22967
  }
22809
- var _internals34 = {
22968
+ var _internals35 = {
22810
22969
  executeMutation,
22811
22970
  computeReport,
22812
22971
  executeMutationSuite,
@@ -24047,11 +24206,11 @@ var quality_budget = createSwarmTool({
24047
24206
  }).optional().describe("Quality budget thresholds")
24048
24207
  },
24049
24208
  async execute(args, directory) {
24050
- const result = await _internals35.qualityBudget(args, directory);
24209
+ const result = await _internals36.qualityBudget(args, directory);
24051
24210
  return JSON.stringify(result);
24052
24211
  }
24053
24212
  });
24054
- var _internals35 = {
24213
+ var _internals36 = {
24055
24214
  qualityBudget
24056
24215
  };
24057
24216
 
@@ -24919,7 +25078,7 @@ var DEFAULT_RULES_DIR = ".swarm/semgrep-rules";
24919
25078
  var DEFAULT_TIMEOUT_MS = 30000;
24920
25079
  var MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
24921
25080
  var KILL_GRACE_MS = 2000;
24922
- var _internals36 = {
25081
+ var _internals37 = {
24923
25082
  isSemgrepAvailable,
24924
25083
  checkSemgrepAvailable,
24925
25084
  resetSemgrepCache,
@@ -24945,7 +25104,7 @@ function isSemgrepAvailable() {
24945
25104
  }
24946
25105
  }
24947
25106
  async function checkSemgrepAvailable() {
24948
- return _internals36.isSemgrepAvailable();
25107
+ return _internals37.isSemgrepAvailable();
24949
25108
  }
24950
25109
  function resetSemgrepCache() {
24951
25110
  semgrepAvailableCache = null;
@@ -25132,12 +25291,12 @@ async function runSemgrep(options) {
25132
25291
  const timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS;
25133
25292
  if (files.length === 0) {
25134
25293
  return {
25135
- available: _internals36.isSemgrepAvailable(),
25294
+ available: _internals37.isSemgrepAvailable(),
25136
25295
  findings: [],
25137
25296
  engine: "tier_a"
25138
25297
  };
25139
25298
  }
25140
- if (!_internals36.isSemgrepAvailable()) {
25299
+ if (!_internals37.isSemgrepAvailable()) {
25141
25300
  return {
25142
25301
  available: false,
25143
25302
  findings: [],
@@ -25299,7 +25458,7 @@ function assignOccurrenceIndices(findings, directory) {
25299
25458
  }
25300
25459
  const occIdx = countMap.get(baseKey) ?? 0;
25301
25460
  countMap.set(baseKey, occIdx + 1);
25302
- const fp = _internals37.fingerprintFinding(finding, directory, occIdx);
25461
+ const fp = _internals38.fingerprintFinding(finding, directory, occIdx);
25303
25462
  return {
25304
25463
  finding,
25305
25464
  index: occIdx,
@@ -25368,7 +25527,7 @@ async function captureOrMergeBaseline(directory, phase, findings, engine, scanne
25368
25527
  }
25369
25528
  } catch {}
25370
25529
  const scannedRelFiles = new Set(scannedFiles.map((f) => normalizeFindingPath(directory, f)));
25371
- const indexed = _internals37.assignOccurrenceIndices(findings, directory);
25530
+ const indexed = _internals38.assignOccurrenceIndices(findings, directory);
25372
25531
  if (existing && !opts?.force) {
25373
25532
  const prunedFingerprints = existing.fingerprints.filter((fp) => {
25374
25533
  const relFile = fp.slice(0, fp.indexOf("|"));
@@ -25508,7 +25667,7 @@ function loadBaseline(directory, phase) {
25508
25667
  };
25509
25668
  }
25510
25669
  }
25511
- var _internals37 = {
25670
+ var _internals38 = {
25512
25671
  fingerprintFinding,
25513
25672
  assignOccurrenceIndices,
25514
25673
  captureOrMergeBaseline,
@@ -25622,7 +25781,7 @@ async function sastScan(input, directory, config) {
25622
25781
  let filesScanned = 0;
25623
25782
  let _filesSkipped = 0;
25624
25783
  const scannedFilePaths = [];
25625
- const semgrepAvailable = !offline_only && _internals38.isSemgrepAvailable();
25784
+ const semgrepAvailable = !offline_only && _internals39.isSemgrepAvailable();
25626
25785
  const engine = semgrepAvailable ? "tier_a+tier_b" : "tier_a";
25627
25786
  const filesByLanguage = new Map;
25628
25787
  for (const filePath of changed_files) {
@@ -25685,13 +25844,13 @@ async function sastScan(input, directory, config) {
25685
25844
  let semgrepResult;
25686
25845
  if (bucketKey.startsWith("auto:")) {
25687
25846
  const lang = bucketKey.slice("auto:".length);
25688
- semgrepResult = await _internals38.runSemgrep({
25847
+ semgrepResult = await _internals39.runSemgrep({
25689
25848
  files: bucketFiles,
25690
25849
  lang,
25691
25850
  useAutoConfig: true
25692
25851
  });
25693
25852
  } else {
25694
- semgrepResult = await _internals38.runSemgrep({
25853
+ semgrepResult = await _internals39.runSemgrep({
25695
25854
  files: bucketFiles
25696
25855
  });
25697
25856
  }
@@ -25933,11 +26092,11 @@ var sast_scan = createSwarmTool({
25933
26092
  capture_baseline: safeArgs.capture_baseline,
25934
26093
  phase: safeArgs.phase
25935
26094
  };
25936
- const result = await _internals38.sastScan(input, directory);
26095
+ const result = await _internals39.sastScan(input, directory);
25937
26096
  return JSON.stringify(result, null, 2);
25938
26097
  }
25939
26098
  });
25940
- var _internals38 = {
26099
+ var _internals39 = {
25941
26100
  sastScan,
25942
26101
  sast_scan,
25943
26102
  isSemgrepAvailable: () => isSemgrepAvailable(),
@@ -25969,10 +26128,10 @@ class DisposableWorktreeCleanupError extends Error {
25969
26128
  }
25970
26129
  }
25971
26130
  async function git(projectRoot, args, abortSignal) {
25972
- const executable = _internals39.resolveExecutableFromPath(["git"]);
26131
+ const executable = _internals40.resolveExecutableFromPath(["git"]);
25973
26132
  if (!executable)
25974
26133
  throw new Error("git executable not found");
25975
- const result = await _internals39.runExternalTool({
26134
+ const result = await _internals40.runExternalTool({
25976
26135
  executable,
25977
26136
  args: ["-C", projectRoot, ...args],
25978
26137
  cwd: projectRoot,
@@ -26008,7 +26167,7 @@ async function createDisposableWorktree(projectRoot, baseRef, abortSignal) {
26008
26167
  if (!/^[A-Fa-f0-9]{40,64}$/.test(baseRef)) {
26009
26168
  throw new Error("Evaluation baseRef must be a full commit hash");
26010
26169
  }
26011
- const parent = path49.join(_internals39.tmpdir(), WORKTREE_PARENT);
26170
+ const parent = path49.join(_internals40.tmpdir(), WORKTREE_PARENT);
26012
26171
  fs22.mkdirSync(parent, { recursive: true });
26013
26172
  const canonicalParent = fs22.realpathSync(parent);
26014
26173
  const worktreePath = path49.join(canonicalParent, crypto4.randomUUID());
@@ -26017,7 +26176,7 @@ async function createDisposableWorktree(projectRoot, baseRef, abortSignal) {
26017
26176
  }
26018
26177
  async function removeDisposableWorktree(projectRoot, worktreePath) {
26019
26178
  const canonicalRoot = fs22.realpathSync(projectRoot);
26020
- const expectedParent = fs22.realpathSync(path49.join(_internals39.tmpdir(), WORKTREE_PARENT));
26179
+ const expectedParent = fs22.realpathSync(path49.join(_internals40.tmpdir(), WORKTREE_PARENT));
26021
26180
  const resolved = path49.resolve(worktreePath);
26022
26181
  const relative7 = path49.relative(expectedParent, resolved);
26023
26182
  if (!relative7 || relative7 === ".." || relative7.startsWith(`..${path49.sep}`) || path49.isAbsolute(relative7)) {
@@ -26030,7 +26189,7 @@ async function removeDisposableWorktree(projectRoot, worktreePath) {
26030
26189
  cleanupErrors.push(`git-remove: ${error2 instanceof Error ? error2.message : String(error2)}`);
26031
26190
  }
26032
26191
  try {
26033
- _internals39.rmSync(resolved, { recursive: true, force: true });
26192
+ _internals40.rmSync(resolved, { recursive: true, force: true });
26034
26193
  } catch (error2) {
26035
26194
  cleanupErrors.push(`filesystem-remove: ${error2 instanceof Error ? error2.message : String(error2)}`);
26036
26195
  }
@@ -26039,7 +26198,7 @@ async function removeDisposableWorktree(projectRoot, worktreePath) {
26039
26198
  } catch (error2) {
26040
26199
  cleanupErrors.push(`git-prune: ${error2 instanceof Error ? error2.message : String(error2)}`);
26041
26200
  }
26042
- const pathPresent = _internals39.existsSync(resolved);
26201
+ const pathPresent = _internals40.existsSync(resolved);
26043
26202
  let registrationPresent;
26044
26203
  try {
26045
26204
  const listed = await git(canonicalRoot, [
@@ -26061,7 +26220,7 @@ function normalizeWorktreePath(value) {
26061
26220
  const resolved = path49.resolve(value);
26062
26221
  return process.platform === "win32" ? resolved.toLowerCase() : resolved;
26063
26222
  }
26064
- var _internals39 = {
26223
+ var _internals40 = {
26065
26224
  runExternalTool,
26066
26225
  resolveExecutableFromPath,
26067
26226
  tmpdir: os7.tmpdir,
@@ -26895,7 +27054,7 @@ function extractCurrentPhaseFromPlan(plan) {
26895
27054
  if (!plan) {
26896
27055
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
26897
27056
  }
26898
- if (!_internals40.validatePlanPhases(plan)) {
27057
+ if (!_internals41.validatePlanPhases(plan)) {
26899
27058
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
26900
27059
  }
26901
27060
  let currentPhase = null;
@@ -27037,9 +27196,9 @@ function extractPhaseMetrics(content) {
27037
27196
  async function getHandoffData(directory) {
27038
27197
  const now = new Date().toISOString();
27039
27198
  const sessionContent = await readSwarmFileAsync(directory, "session/state.json");
27040
- const sessionState = _internals40.parseSessionState(sessionContent);
27199
+ const sessionState = _internals41.parseSessionState(sessionContent);
27041
27200
  const plan = await loadPlanJsonOnly(directory);
27042
- const planInfo = _internals40.extractCurrentPhaseFromPlan(plan);
27201
+ const planInfo = _internals41.extractCurrentPhaseFromPlan(plan);
27043
27202
  if (!plan) {
27044
27203
  const planMdContent = await readSwarmFileAsync(directory, "plan.md");
27045
27204
  if (planMdContent) {
@@ -27058,8 +27217,8 @@ async function getHandoffData(directory) {
27058
27217
  }
27059
27218
  }
27060
27219
  const contextContent = await readSwarmFileAsync(directory, "context.md");
27061
- const recentDecisions = _internals40.extractDecisions(contextContent);
27062
- const rawPhaseMetrics = _internals40.extractPhaseMetrics(contextContent);
27220
+ const recentDecisions = _internals41.extractDecisions(contextContent);
27221
+ const rawPhaseMetrics = _internals41.extractPhaseMetrics(contextContent);
27063
27222
  const phaseMetrics = sanitizeString(rawPhaseMetrics, 1000);
27064
27223
  let delegationState = null;
27065
27224
  if (sessionState?.delegationState) {
@@ -27223,7 +27382,7 @@ ${lines.join(`
27223
27382
  `)}
27224
27383
  \`\`\``;
27225
27384
  }
27226
- var _internals40 = {
27385
+ var _internals41 = {
27227
27386
  getHandoffData,
27228
27387
  formatHandoffMarkdown,
27229
27388
  formatContinuationPrompt,
@@ -27333,6 +27492,9 @@ function serializeAgentSession(s) {
27333
27492
  },
27334
27493
  ...s.autoProceedNudgeDone !== undefined && {
27335
27494
  autoProceedNudgeDone: s.autoProceedNudgeDone
27495
+ },
27496
+ ...s.cachedCohortId !== undefined && {
27497
+ cachedCohortId: s.cachedCohortId
27336
27498
  }
27337
27499
  };
27338
27500
  }
@@ -27372,15 +27534,15 @@ async function writeSnapshot(directory, state) {
27372
27534
  }
27373
27535
  function createSnapshotWriterHook(directory) {
27374
27536
  return (_input, _output) => {
27375
- _writeInFlight = _writeInFlight.then(() => _internals41.writeSnapshot(directory, swarmState), () => _internals41.writeSnapshot(directory, swarmState));
27537
+ _writeInFlight = _writeInFlight.then(() => _internals42.writeSnapshot(directory, swarmState), () => _internals42.writeSnapshot(directory, swarmState));
27376
27538
  return _writeInFlight;
27377
27539
  };
27378
27540
  }
27379
27541
  async function flushPendingSnapshot(directory) {
27380
- _writeInFlight = _writeInFlight.then(() => _internals41.writeSnapshot(directory, swarmState), () => _internals41.writeSnapshot(directory, swarmState));
27542
+ _writeInFlight = _writeInFlight.then(() => _internals42.writeSnapshot(directory, swarmState), () => _internals42.writeSnapshot(directory, swarmState));
27381
27543
  await _writeInFlight;
27382
27544
  }
27383
- var _internals41 = {
27545
+ var _internals42 = {
27384
27546
  writeSnapshot,
27385
27547
  createSnapshotWriterHook,
27386
27548
  flushPendingSnapshot
@@ -27665,7 +27827,7 @@ function parseIssueRef(input, directory) {
27665
27827
  }
27666
27828
  return null;
27667
27829
  }
27668
- var _internals42 = {
27830
+ var _internals43 = {
27669
27831
  writeFileSync: fs24.writeFileSync,
27670
27832
  mkdirSync: fs24.mkdirSync,
27671
27833
  renameSync: fs24.renameSync,
@@ -27676,18 +27838,18 @@ var _internals42 = {
27676
27838
  function atomicWriteFileSync(dir, filename, content) {
27677
27839
  const tmpPath = path53.join(dir, `.tmp-${filename}-${Date.now()}-${process.pid}`);
27678
27840
  const finalPath = path53.join(dir, filename);
27679
- _internals42.writeFileSync(tmpPath, content, "utf-8");
27841
+ _internals43.writeFileSync(tmpPath, content, "utf-8");
27680
27842
  try {
27681
- _internals42.renameSync(tmpPath, finalPath);
27843
+ _internals43.renameSync(tmpPath, finalPath);
27682
27844
  } catch {
27683
27845
  try {
27684
- _internals42.unlinkSync(finalPath);
27846
+ _internals43.unlinkSync(finalPath);
27685
27847
  } catch {}
27686
27848
  try {
27687
- _internals42.renameSync(tmpPath, finalPath);
27849
+ _internals43.renameSync(tmpPath, finalPath);
27688
27850
  } catch (retryErr) {
27689
27851
  try {
27690
- _internals42.unlinkSync(tmpPath);
27852
+ _internals43.unlinkSync(tmpPath);
27691
27853
  } catch {}
27692
27854
  throw retryErr;
27693
27855
  }
@@ -27740,10 +27902,10 @@ ${USAGE7}`;
27740
27902
  };
27741
27903
  let oldTraceState = null;
27742
27904
  try {
27743
- oldTraceState = _internals42.readFileSync(path53.join(swarmDir, "issue-trace-state.json"), "utf-8");
27905
+ oldTraceState = _internals43.readFileSync(path53.join(swarmDir, "issue-trace-state.json"), "utf-8");
27744
27906
  } catch {}
27745
27907
  try {
27746
- _internals42.mkdirSync(swarmDir, { recursive: true });
27908
+ _internals43.mkdirSync(swarmDir, { recursive: true });
27747
27909
  atomicWriteFileSync(swarmDir, "issue-trace-state.json", JSON.stringify(traceState, null, 2));
27748
27910
  atomicWriteFileSync(swarmDir, "issue-reference.json", JSON.stringify(issueReference, null, 2));
27749
27911
  } catch (e) {
@@ -27753,11 +27915,11 @@ ${USAGE7}`;
27753
27915
  } catch {}
27754
27916
  } else {
27755
27917
  try {
27756
- _internals42.unlinkSync(path53.join(swarmDir, "issue-trace-state.json"));
27918
+ _internals43.unlinkSync(path53.join(swarmDir, "issue-trace-state.json"));
27757
27919
  } catch {}
27758
27920
  }
27759
27921
  try {
27760
- _internals42.unlinkSync(path53.join(swarmDir, "issue-reference.json"));
27922
+ _internals43.unlinkSync(path53.join(swarmDir, "issue-reference.json"));
27761
27923
  } catch {}
27762
27924
  const errMsg = e instanceof Error ? e.message : String(e);
27763
27925
  return `Error: Failed to persist issue reference durably: ${errMsg}
@@ -27782,13 +27944,13 @@ import { join as join45 } from "path";
27782
27944
  init_logger();
27783
27945
  import { randomUUID as randomUUID7 } from "crypto";
27784
27946
  import { existsSync as existsSync32, readFileSync as readFileSync21 } from "fs";
27785
- import { mkdir as mkdir12, readFile as readFile13, writeFile as writeFile11 } from "fs/promises";
27947
+ import { mkdir as mkdir13, readFile as readFile14, writeFile as writeFile12 } from "fs/promises";
27786
27948
  import * as os9 from "os";
27787
27949
  import * as path54 from "path";
27788
27950
  async function migrateKnowledgeToExternal(_directory, _config) {
27789
27951
  const externalSentinelPath = path54.join(_directory, ".swarm", ".knowledge-external-migrated");
27790
27952
  const contextPath = path54.join(_directory, ".swarm", "context.md");
27791
- if (_internals43.existsSync(externalSentinelPath)) {
27953
+ if (_internals44.existsSync(externalSentinelPath)) {
27792
27954
  return {
27793
27955
  migrated: false,
27794
27956
  entriesMigrated: 0,
@@ -27797,7 +27959,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
27797
27959
  skippedReason: "external-sentinel-exists"
27798
27960
  };
27799
27961
  }
27800
- if (!_internals43.existsSync(contextPath)) {
27962
+ if (!_internals44.existsSync(contextPath)) {
27801
27963
  return {
27802
27964
  migrated: false,
27803
27965
  entriesMigrated: 0,
@@ -27806,7 +27968,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
27806
27968
  skippedReason: "no-context-file"
27807
27969
  };
27808
27970
  }
27809
- const contextContent = await _internals43.readFile(contextPath, "utf-8");
27971
+ const contextContent = await _internals44.readFile(contextPath, "utf-8");
27810
27972
  if (contextContent.trim().length === 0) {
27811
27973
  return {
27812
27974
  migrated: false,
@@ -27824,7 +27986,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
27824
27986
  entriesCount++;
27825
27987
  }
27826
27988
  }
27827
- await _internals43.writeSentinel(externalSentinelPath, entriesCount, entriesCount);
27989
+ await _internals44.writeSentinel(externalSentinelPath, entriesCount, entriesCount);
27828
27990
  return {
27829
27991
  migrated: true,
27830
27992
  entriesMigrated: entriesCount,
@@ -27832,7 +27994,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
27832
27994
  entriesTotal: entriesCount
27833
27995
  };
27834
27996
  }
27835
- var _internals43 = {
27997
+ var _internals44 = {
27836
27998
  appendKnowledge,
27837
27999
  migrateContextToKnowledge,
27838
28000
  migrateKnowledgeToExternal,
@@ -27847,9 +28009,9 @@ var _internals43 = {
27847
28009
  resolveLegacyHiveKnowledgePath,
27848
28010
  existsSync: existsSync32,
27849
28011
  readFileSync: readFileSync21,
27850
- readFile: readFile13,
27851
- mkdir: mkdir12,
27852
- writeFile: writeFile11
28012
+ readFile: readFile14,
28013
+ mkdir: mkdir13,
28014
+ writeFile: writeFile12
27853
28015
  };
27854
28016
  async function migrateContextToKnowledge(directory, config) {
27855
28017
  const sentinelPath = path54.join(directory, ".swarm", ".knowledge-migrated");
@@ -27873,7 +28035,7 @@ async function migrateContextToKnowledge(directory, config) {
27873
28035
  skippedReason: "no-context-file"
27874
28036
  };
27875
28037
  }
27876
- const contextContent = await readFile13(contextPath, "utf-8");
28038
+ const contextContent = await readFile14(contextPath, "utf-8");
27877
28039
  if (contextContent.trim().length === 0) {
27878
28040
  return {
27879
28041
  migrated: false,
@@ -27883,9 +28045,9 @@ async function migrateContextToKnowledge(directory, config) {
27883
28045
  skippedReason: "empty-context"
27884
28046
  };
27885
28047
  }
27886
- const rawEntries = _internals43.parseContextMd(contextContent);
28048
+ const rawEntries = _internals44.parseContextMd(contextContent);
27887
28049
  if (rawEntries.length === 0) {
27888
- await _internals43.writeSentinel(sentinelPath, 0, 0);
28050
+ await _internals44.writeSentinel(sentinelPath, 0, 0);
27889
28051
  return {
27890
28052
  migrated: true,
27891
28053
  entriesMigrated: 0,
@@ -27896,10 +28058,10 @@ async function migrateContextToKnowledge(directory, config) {
27896
28058
  const existing = await readKnowledge(knowledgePath);
27897
28059
  let migrated = 0;
27898
28060
  let dropped = 0;
27899
- const projectName = _internals43.inferProjectName(directory);
28061
+ const projectName = _internals44.inferProjectName(directory);
27900
28062
  for (const raw of rawEntries) {
27901
28063
  if (config.validation_enabled !== false) {
27902
- const category = raw.categoryHint ?? _internals43.inferCategoryFromText(raw.text);
28064
+ const category = raw.categoryHint ?? _internals44.inferCategoryFromText(raw.text);
27903
28065
  const result = validateLesson(raw.text, existing.map((e) => e.lesson), {
27904
28066
  category,
27905
28067
  scope: "global",
@@ -27919,8 +28081,8 @@ async function migrateContextToKnowledge(directory, config) {
27919
28081
  const entry = {
27920
28082
  id: randomUUID7(),
27921
28083
  tier: "swarm",
27922
- lesson: _internals43.truncateLesson(raw.text),
27923
- category: raw.categoryHint ?? _internals43.inferCategoryFromText(raw.text),
28084
+ lesson: _internals44.truncateLesson(raw.text),
28085
+ category: raw.categoryHint ?? _internals44.inferCategoryFromText(raw.text),
27924
28086
  tags: [...inferredTags, `migration:${raw.sourceSection}`],
27925
28087
  scope: "global",
27926
28088
  confidence: 0.3,
@@ -27943,7 +28105,7 @@ async function migrateContextToKnowledge(directory, config) {
27943
28105
  if (migrated > 0) {
27944
28106
  await rewriteKnowledge(knowledgePath, existing);
27945
28107
  }
27946
- await _internals43.writeSentinel(sentinelPath, migrated, dropped);
28108
+ await _internals44.writeSentinel(sentinelPath, migrated, dropped);
27947
28109
  log(`[knowledge-migrator] Migrated ${migrated} entries, dropped ${dropped}`);
27948
28110
  return {
27949
28111
  migrated: true,
@@ -27953,7 +28115,7 @@ async function migrateContextToKnowledge(directory, config) {
27953
28115
  };
27954
28116
  }
27955
28117
  async function migrateHiveKnowledgeLegacy(config) {
27956
- const legacyHivePath = _internals43.resolveLegacyHiveKnowledgePath();
28118
+ const legacyHivePath = _internals44.resolveLegacyHiveKnowledgePath();
27957
28119
  const canonicalHivePath = resolveHiveKnowledgePath2();
27958
28120
  const sentinelPath = path54.join(path54.dirname(canonicalHivePath), ".hive-knowledge-migrated");
27959
28121
  if (existsSync32(sentinelPath)) {
@@ -27976,7 +28138,7 @@ async function migrateHiveKnowledgeLegacy(config) {
27976
28138
  }
27977
28139
  const legacyEntries = await readKnowledge(legacyHivePath);
27978
28140
  if (legacyEntries.length === 0) {
27979
- await _internals43.writeSentinel(sentinelPath, 0, 0);
28141
+ await _internals44.writeSentinel(sentinelPath, 0, 0);
27980
28142
  return {
27981
28143
  migrated: true,
27982
28144
  entriesMigrated: 0,
@@ -28024,7 +28186,7 @@ async function migrateHiveKnowledgeLegacy(config) {
28024
28186
  const newHiveEntry = {
28025
28187
  id: resolvedId,
28026
28188
  tier: "hive",
28027
- lesson: _internals43.truncateLesson(lesson),
28189
+ lesson: _internals44.truncateLesson(lesson),
28028
28190
  category,
28029
28191
  tags: ["migration:legacy-hive"],
28030
28192
  scope: scopeTag,
@@ -28043,7 +28205,7 @@ async function migrateHiveKnowledgeLegacy(config) {
28043
28205
  encounter_score: 1
28044
28206
  };
28045
28207
  try {
28046
- await _internals43.appendKnowledge(canonicalHivePath, newHiveEntry);
28208
+ await _internals44.appendKnowledge(canonicalHivePath, newHiveEntry);
28047
28209
  existingHiveEntries.push(newHiveEntry);
28048
28210
  migrated++;
28049
28211
  } catch (appendError) {
@@ -28059,7 +28221,7 @@ async function migrateHiveKnowledgeLegacy(config) {
28059
28221
  dropped++;
28060
28222
  }
28061
28223
  }
28062
- await _internals43.writeSentinel(sentinelPath, migrated, dropped);
28224
+ await _internals44.writeSentinel(sentinelPath, migrated, dropped);
28063
28225
  log(`[knowledge-migrator] Migrated ${migrated} legacy hive entries, dropped ${dropped}`);
28064
28226
  return {
28065
28227
  migrated: true,
@@ -28070,7 +28232,7 @@ async function migrateHiveKnowledgeLegacy(config) {
28070
28232
  };
28071
28233
  }
28072
28234
  function parseContextMd(content) {
28073
- const sections = _internals43.splitIntoSections(content);
28235
+ const sections = _internals44.splitIntoSections(content);
28074
28236
  const entries = [];
28075
28237
  const seen = new Set;
28076
28238
  const sectionPatterns = [
@@ -28086,7 +28248,7 @@ function parseContextMd(content) {
28086
28248
  const match = sectionPatterns.find((sp) => sp.pattern.test(section.heading));
28087
28249
  if (!match)
28088
28250
  continue;
28089
- const bullets = _internals43.extractBullets(section.body);
28251
+ const bullets = _internals44.extractBullets(section.body);
28090
28252
  for (const bullet of bullets) {
28091
28253
  if (bullet.length < 15)
28092
28254
  continue;
@@ -28095,9 +28257,9 @@ function parseContextMd(content) {
28095
28257
  continue;
28096
28258
  seen.add(normalized);
28097
28259
  entries.push({
28098
- text: _internals43.truncateLesson(bullet),
28260
+ text: _internals44.truncateLesson(bullet),
28099
28261
  sourceSection: match.sourceSection,
28100
- categoryHint: _internals43.inferCategoryFromText(bullet)
28262
+ categoryHint: _internals44.inferCategoryFromText(bullet)
28101
28263
  });
28102
28264
  }
28103
28265
  }
@@ -28187,8 +28349,8 @@ async function writeSentinel(sentinelPath, migrated, dropped) {
28187
28349
  schema_version: 1,
28188
28350
  migration_tool: "knowledge-migrator.ts"
28189
28351
  };
28190
- await _internals43.mkdir(path54.dirname(sentinelPath), { recursive: true });
28191
- await _internals43.writeFile(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
28352
+ await _internals44.mkdir(path54.dirname(sentinelPath), { recursive: true });
28353
+ await _internals44.writeFile(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
28192
28354
  }
28193
28355
  function resolveLegacyHiveKnowledgePath() {
28194
28356
  const platform = process.platform;
@@ -28600,7 +28762,7 @@ function timeoutMessage(timeoutMs) {
28600
28762
  async function computeWithTimeout(directory, currentPhase, timeoutMs) {
28601
28763
  const controller = new AbortController;
28602
28764
  let timeout;
28603
- const metricsPromise = _internals44.computeLearningMetrics(directory, {
28765
+ const metricsPromise = _internals45.computeLearningMetrics(directory, {
28604
28766
  currentPhase,
28605
28767
  signal: controller.signal
28606
28768
  });
@@ -28657,18 +28819,18 @@ ${JSON.stringify({
28657
28819
  return `Error computing learning metrics: ${message}. Run /swarm diagnose to check .swarm/ health.`;
28658
28820
  }
28659
28821
  }
28660
- var _internals44 = {
28822
+ var _internals45 = {
28661
28823
  computeLearningMetrics
28662
28824
  };
28663
28825
 
28664
28826
  // src/commands/link.ts
28665
- import { mkdir as mkdir14, writeFile as writeFile12 } from "fs/promises";
28827
+ import { mkdir as mkdir15, writeFile as writeFile13 } from "fs/promises";
28666
28828
  import * as path56 from "path";
28667
28829
 
28668
28830
  // src/knowledge/family-migration.ts
28669
28831
  var import_proper_lockfile5 = __toESM(require_proper_lockfile(), 1);
28670
28832
  import { existsSync as existsSync33, readFileSync as readFileSync22 } from "fs";
28671
- import { mkdir as mkdir13 } from "fs/promises";
28833
+ import { mkdir as mkdir14 } from "fs/promises";
28672
28834
  import * as path55 from "path";
28673
28835
 
28674
28836
  // src/knowledge/family-manifest.ts
@@ -29053,7 +29215,7 @@ async function snapshotSourceFamily(storeDir) {
29053
29215
  const snapshot = {};
29054
29216
  let release = null;
29055
29217
  try {
29056
- await mkdir13(storeDir, { recursive: true });
29218
+ await mkdir14(storeDir, { recursive: true });
29057
29219
  } catch {}
29058
29220
  try {
29059
29221
  release = await import_proper_lockfile5.default.lock(storeDir, {
@@ -29072,7 +29234,7 @@ async function snapshotSourceFamily(storeDir) {
29072
29234
  return snapshot;
29073
29235
  }
29074
29236
  async function migrateKnowledgeFamily(destinationDir, sourceDir) {
29075
- await mkdir13(destinationDir, { recursive: true });
29237
+ await mkdir14(destinationDir, { recursive: true });
29076
29238
  let destRelease = null;
29077
29239
  try {
29078
29240
  destRelease = await import_proper_lockfile5.default.lock(destinationDir, {
@@ -29222,8 +29384,8 @@ ${formatStatus(directory)}`;
29222
29384
  const { config: loadedConfig } = loadPluginConfigWithMeta(directory);
29223
29385
  const config = KnowledgeConfigSchema.parse(loadedConfig.knowledge ?? {});
29224
29386
  const fingerprint = cohortConfigFingerprint(buildConfigFingerprintInput(config));
29225
- await mkdir14(linkDir, { recursive: true });
29226
- await writeFile12(path56.join(linkDir, "cohort-config.json"), JSON.stringify({ fingerprint, updated_at: new Date().toISOString() }, null, 2), "utf-8");
29387
+ await mkdir15(linkDir, { recursive: true });
29388
+ await writeFile13(path56.join(linkDir, "cohort-config.json"), JSON.stringify({ fingerprint, updated_at: new Date().toISOString() }, null, 2), "utf-8");
29227
29389
  } catch {}
29228
29390
  const relinkNote = existing ? `
29229
29391
  (Re-linked from previous link "${existing.linkId}".)` : "";
@@ -29279,7 +29441,7 @@ async function readLatestLoopState(directory) {
29279
29441
  return null;
29280
29442
  }
29281
29443
  }
29282
- var _internals45 = {
29444
+ var _internals46 = {
29283
29445
  readLatestLoopState
29284
29446
  };
29285
29447
  var USAGE8 = `Usage: /swarm loop <objective> [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]
@@ -29392,7 +29554,7 @@ ${USAGE8}`;
29392
29554
  }
29393
29555
  let autonomy = parsed.autonomy;
29394
29556
  if (parsed.resume && !parsed.autonomyExplicit) {
29395
- const state = await _internals45.readLatestLoopState(_directory);
29557
+ const state = await _internals46.readLatestLoopState(_directory);
29396
29558
  if (state?.autonomy && AUTONOMY_LEVELS.has(state.autonomy)) {
29397
29559
  autonomy = state.autonomy;
29398
29560
  }
@@ -29765,14 +29927,14 @@ var CuratorOutputMemoryDecisionSchema = exports_external.object({
29765
29927
  curatorMemoryDecisions: exports_external.array(CuratorMemoryDecisionSchema).max(20).optional()
29766
29928
  }).passthrough();
29767
29929
  // src/memory/consolidation-log.ts
29768
- import { appendFile as appendFile4, mkdir as mkdir15, readFile as readFile15 } from "fs/promises";
29930
+ import { appendFile as appendFile5, mkdir as mkdir16, readFile as readFile16 } from "fs/promises";
29769
29931
  import * as path58 from "path";
29770
29932
  var LOG_RELATIVE_PATH = path58.join("memory", "consolidation-log.jsonl");
29771
29933
  async function readConsolidationLog(directory) {
29772
29934
  const filePath = validateSwarmPath(directory, LOG_RELATIVE_PATH);
29773
29935
  let raw;
29774
29936
  try {
29775
- raw = await readFile15(filePath, "utf-8");
29937
+ raw = await readFile16(filePath, "utf-8");
29776
29938
  } catch {
29777
29939
  return [];
29778
29940
  }
@@ -30328,15 +30490,15 @@ function truncate(value, maxLength) {
30328
30490
  }
30329
30491
 
30330
30492
  // src/services/plan-service.ts
30331
- var _internals46 = {
30493
+ var _internals47 = {
30332
30494
  loadPlanJsonOnly,
30333
30495
  derivePlanMarkdown,
30334
30496
  readSwarmFileAsync
30335
30497
  };
30336
30498
  async function getPlanData(directory, phaseArg) {
30337
- const plan = await _internals46.loadPlanJsonOnly(directory);
30499
+ const plan = await _internals47.loadPlanJsonOnly(directory);
30338
30500
  if (plan) {
30339
- const fullMarkdown = _internals46.derivePlanMarkdown(plan);
30501
+ const fullMarkdown = _internals47.derivePlanMarkdown(plan);
30340
30502
  if (phaseArg === undefined || phaseArg === null || phaseArg === "") {
30341
30503
  return {
30342
30504
  hasPlan: true,
@@ -30379,7 +30541,7 @@ async function getPlanData(directory, phaseArg) {
30379
30541
  isLegacy: false
30380
30542
  };
30381
30543
  }
30382
- const planContent = await _internals46.readSwarmFileAsync(directory, "plan.md");
30544
+ const planContent = await _internals47.readSwarmFileAsync(directory, "plan.md");
30383
30545
  if (!planContent) {
30384
30546
  return {
30385
30547
  hasPlan: false,
@@ -30476,7 +30638,7 @@ async function handlePlanCommand(directory, args) {
30476
30638
  return formatPlanMarkdown(planData);
30477
30639
  }
30478
30640
  // src/commands/post-mortem.ts
30479
- var _internals47 = {
30641
+ var _internals48 = {
30480
30642
  createCuratorLLMDelegate,
30481
30643
  runCuratorPostMortem
30482
30644
  };
@@ -30524,10 +30686,10 @@ async function handlePostMortemCommand(directory, args, options) {
30524
30686
  };
30525
30687
  if (options?.sessionID) {
30526
30688
  try {
30527
- pmOptions.llmDelegate = _internals47.createCuratorLLMDelegate(directory, "postmortem", options.sessionID);
30689
+ pmOptions.llmDelegate = _internals48.createCuratorLLMDelegate(directory, "postmortem", options.sessionID);
30528
30690
  } catch {}
30529
30691
  }
30530
- const result = await _internals47.runCuratorPostMortem(directory, pmOptions);
30692
+ const result = await _internals48.runCuratorPostMortem(directory, pmOptions);
30531
30693
  const lines = [];
30532
30694
  if (result.success) {
30533
30695
  lines.push("## Post-Mortem Report Generated");
@@ -30684,7 +30846,7 @@ function formatMergeGroupStatus(status, conclusion, htmlUrl) {
30684
30846
  }
30685
30847
  return parts.join(" ");
30686
30848
  }
30687
- var _internals48 = {
30849
+ var _internals49 = {
30688
30850
  formatRelativeTime,
30689
30851
  formatMergeGroupStatus,
30690
30852
  listActive,
@@ -30692,7 +30854,7 @@ var _internals48 = {
30692
30854
  parseMergeGroupRuns
30693
30855
  };
30694
30856
  async function handlePrMonitorStatusCommand(directory, _args, sessionID, source) {
30695
- const allActive = await _internals48.listActive(directory);
30857
+ const allActive = await _internals49.listActive(directory);
30696
30858
  const allSessions = source === "cli";
30697
30859
  const subs = allSessions ? allActive : allActive.filter((record) => record.sessionID === sessionID);
30698
30860
  if (subs.length === 0) {
@@ -30708,7 +30870,7 @@ async function handlePrMonitorStatusCommand(directory, _args, sessionID, source)
30708
30870
  const index = i + 1;
30709
30871
  lines.push(` ${index}. ${sub.repoFullName}#${sub.prNumber}`);
30710
30872
  lines.push(` URL: ${sub.prUrl}`);
30711
- const mergeGroupRuns = await _internals48.listMergeGroupRuns(directory, sub.repoFullName, sub.prNumber);
30873
+ const mergeGroupRuns = await _internals49.listMergeGroupRuns(directory, sub.repoFullName, sub.prNumber);
30712
30874
  if (mergeGroupRuns.runs.length > 0) {
30713
30875
  lines.push(" Merge-group runs:");
30714
30876
  for (const run of mergeGroupRuns.runs) {
@@ -30848,7 +31010,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
30848
31010
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
30849
31011
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
30850
31012
  try {
30851
- const config = _internals49.loadPluginConfig(directory);
31013
+ const config = _internals50.loadPluginConfig(directory);
30852
31014
  const prMonitorConfig = config.pr_monitor;
30853
31015
  if (!prMonitorConfig?.enabled) {
30854
31016
  return [
@@ -30858,7 +31020,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
30858
31020
  ].join(`
30859
31021
  `);
30860
31022
  }
30861
- await _internals49.subscribe(directory, {
31023
+ await _internals50.subscribe(directory, {
30862
31024
  sessionID,
30863
31025
  prNumber: prInfo.number,
30864
31026
  repoFullName,
@@ -30886,7 +31048,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
30886
31048
  `);
30887
31049
  }
30888
31050
  }
30889
- var _internals49 = {
31051
+ var _internals50 = {
30890
31052
  loadPluginConfig,
30891
31053
  subscribe
30892
31054
  };
@@ -30909,9 +31071,9 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
30909
31071
  `);
30910
31072
  }
30911
31073
  const refToken = rest[0];
30912
- const prInfo = _internals50.parsePrRef(refToken, directory);
31074
+ const prInfo = _internals51.parsePrRef(refToken, directory);
30913
31075
  if (!prInfo) {
30914
- if (_internals50.looksLikePrRef(refToken)) {
31076
+ if (_internals51.looksLikePrRef(refToken)) {
30915
31077
  return [
30916
31078
  `Error: Could not resolve PR reference from "${refToken}".`,
30917
31079
  "",
@@ -30932,8 +31094,8 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
30932
31094
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
30933
31095
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
30934
31096
  try {
30935
- const correlationId = _internals50.buildCorrelationId(sessionID, repoFullName, prInfo.number);
30936
- const result = await _internals50.unsubscribe(directory, correlationId);
31097
+ const correlationId = _internals51.buildCorrelationId(sessionID, repoFullName, prInfo.number);
31098
+ const result = await _internals51.unsubscribe(directory, correlationId);
30937
31099
  if (!result) {
30938
31100
  return [
30939
31101
  `Not subscribed to ${prUrl}`,
@@ -30960,7 +31122,7 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
30960
31122
  `);
30961
31123
  }
30962
31124
  }
30963
- var _internals50 = {
31125
+ var _internals51 = {
30964
31126
  unsubscribe,
30965
31127
  buildCorrelationId,
30966
31128
  parsePrRef,
@@ -31442,15 +31604,15 @@ var lint = createSwarmTool({
31442
31604
  }
31443
31605
  const { mode } = args;
31444
31606
  const cwd = directory;
31445
- const linter = await _internals51.detectAvailableLinter(directory);
31607
+ const linter = await _internals52.detectAvailableLinter(directory);
31446
31608
  if (linter) {
31447
- const result = await _internals51.runLint(linter, mode, directory);
31609
+ const result = await _internals52.runLint(linter, mode, directory);
31448
31610
  return JSON.stringify(result, null, 2);
31449
31611
  }
31450
- const additionalLinter = _internals51.detectAdditionalLinter(cwd);
31612
+ const additionalLinter = _internals52.detectAdditionalLinter(cwd);
31451
31613
  if (additionalLinter) {
31452
31614
  warn(`[lint] Using ${additionalLinter} linter for this project`);
31453
- const result = await _internals51.runAdditionalLint(additionalLinter, mode, cwd);
31615
+ const result = await _internals52.runAdditionalLint(additionalLinter, mode, cwd);
31454
31616
  return JSON.stringify(result, null, 2);
31455
31617
  }
31456
31618
  const errorResult = {
@@ -31464,7 +31626,7 @@ For Rust: rustup component add clippy`
31464
31626
  return JSON.stringify(errorResult, null, 2);
31465
31627
  }
31466
31628
  });
31467
- var _internals51 = {
31629
+ var _internals52 = {
31468
31630
  detectAvailableLinter,
31469
31631
  runLint,
31470
31632
  detectAdditionalLinter,
@@ -32152,7 +32314,7 @@ var secretscan = createSwarmTool({
32152
32314
  });
32153
32315
  async function runSecretscan(directory) {
32154
32316
  try {
32155
- const result = await _internals52.secretscan.execute({ directory }, {});
32317
+ const result = await _internals53.secretscan.execute({ directory }, {});
32156
32318
  const jsonStr = typeof result === "string" ? result : result.output;
32157
32319
  return JSON.parse(jsonStr);
32158
32320
  } catch (e) {
@@ -32224,7 +32386,7 @@ async function runSecretscanOnFiles(files, directory) {
32224
32386
  };
32225
32387
  }
32226
32388
  }
32227
- var _internals52 = {
32389
+ var _internals53 = {
32228
32390
  secretscan,
32229
32391
  runSecretscan,
32230
32392
  runSecretscanOnFiles,
@@ -32500,7 +32662,7 @@ async function buildImpactMapInternal(cwd) {
32500
32662
  }
32501
32663
  return impactMap;
32502
32664
  }
32503
- var _internals53 = {
32665
+ var _internals54 = {
32504
32666
  validateProjectRoot,
32505
32667
  normalizePath: normalizePath2,
32506
32668
  isCacheStale,
@@ -32515,8 +32677,8 @@ var _internals53 = {
32515
32677
  _clearGoModuleCache
32516
32678
  };
32517
32679
  async function buildImpactMap(cwd) {
32518
- const impactMap = await _internals53.buildImpactMapInternal(cwd);
32519
- await _internals53.saveImpactMap(cwd, impactMap);
32680
+ const impactMap = await _internals54.buildImpactMapInternal(cwd);
32681
+ await _internals54.saveImpactMap(cwd, impactMap);
32520
32682
  return impactMap;
32521
32683
  }
32522
32684
  async function loadImpactMap(cwd, options) {
@@ -32530,7 +32692,7 @@ async function loadImpactMap(cwd, options) {
32530
32692
  const hasValidValues = Object.values(map).every((v) => Array.isArray(v) && v.every((item) => typeof item === "string"));
32531
32693
  if (hasValidValues) {
32532
32694
  const generatedAt = new Date(data.generatedAt).getTime();
32533
- if (!_internals53.isCacheStale(map, generatedAt)) {
32695
+ if (!_internals54.isCacheStale(map, generatedAt)) {
32534
32696
  return map;
32535
32697
  }
32536
32698
  if (options?.skipRebuild) {
@@ -32550,13 +32712,13 @@ async function loadImpactMap(cwd, options) {
32550
32712
  if (options?.skipRebuild) {
32551
32713
  return {};
32552
32714
  }
32553
- return _internals53.buildImpactMap(cwd);
32715
+ return _internals54.buildImpactMap(cwd);
32554
32716
  }
32555
32717
  async function saveImpactMap(cwd, impactMap) {
32556
32718
  if (!path62.isAbsolute(cwd)) {
32557
32719
  throw new Error(`saveImpactMap requires an absolute project root path, got: "${cwd}"`);
32558
32720
  }
32559
- _internals53.validateProjectRoot(cwd);
32721
+ _internals54.validateProjectRoot(cwd);
32560
32722
  const cacheDir2 = path62.join(cwd, ".swarm", "cache");
32561
32723
  const cachePath = path62.join(cacheDir2, "impact-map.json");
32562
32724
  if (!fs28.existsSync(cacheDir2)) {
@@ -32580,7 +32742,7 @@ async function analyzeImpact(changedFiles, cwd, budget) {
32580
32742
  };
32581
32743
  }
32582
32744
  const validFiles = changedFiles.filter((f) => typeof f === "string" && f.length > 0 && !f.includes("\x00"));
32583
- const impactMap = await _internals53.loadImpactMap(cwd);
32745
+ const impactMap = await _internals54.loadImpactMap(cwd);
32584
32746
  const impactedTestsSet = new Set;
32585
32747
  const untestedFiles = [];
32586
32748
  let visitedCount = 0;
@@ -32857,7 +33019,7 @@ function batchAppendTestRuns(records, workingDir) {
32857
33019
  }
32858
33020
  const historyPath = getHistoryPath(workingDir);
32859
33021
  const historyDir = path63.dirname(historyPath);
32860
- _internals54.validateProjectRoot(workingDir);
33022
+ _internals55.validateProjectRoot(workingDir);
32861
33023
  if (!fs29.existsSync(historyDir)) {
32862
33024
  fs29.mkdirSync(historyDir, { recursive: true });
32863
33025
  }
@@ -32980,7 +33142,7 @@ function getAllHistory(workingDir) {
32980
33142
  records.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
32981
33143
  return records;
32982
33144
  }
32983
- var _internals54 = {
33145
+ var _internals55 = {
32984
33146
  validateProjectRoot
32985
33147
  };
32986
33148
 
@@ -34957,9 +35119,9 @@ function getVersionFileVersion(dir) {
34957
35119
  async function runVersionCheck(dir, _timeoutMs) {
34958
35120
  const startTime = Date.now();
34959
35121
  try {
34960
- const packageVersion = _internals55.getPackageVersion(dir);
34961
- const changelogVersion = _internals55.getChangelogVersion(dir);
34962
- const versionFileVersion = _internals55.getVersionFileVersion(dir);
35122
+ const packageVersion = _internals56.getPackageVersion(dir);
35123
+ const changelogVersion = _internals56.getChangelogVersion(dir);
35124
+ const versionFileVersion = _internals56.getVersionFileVersion(dir);
34963
35125
  const versions = [];
34964
35126
  if (packageVersion)
34965
35127
  versions.push(`package.json: ${packageVersion}`);
@@ -35323,7 +35485,7 @@ async function runPreflight(dir, phase, config) {
35323
35485
  const reportId = `preflight-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
35324
35486
  let validatedDir;
35325
35487
  try {
35326
- validatedDir = _internals55.validateDirectoryPath(dir);
35488
+ validatedDir = _internals56.validateDirectoryPath(dir);
35327
35489
  } catch (error2) {
35328
35490
  return {
35329
35491
  id: reportId,
@@ -35343,7 +35505,7 @@ async function runPreflight(dir, phase, config) {
35343
35505
  }
35344
35506
  let validatedTimeout;
35345
35507
  try {
35346
- validatedTimeout = _internals55.validateTimeout(config?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
35508
+ validatedTimeout = _internals56.validateTimeout(config?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
35347
35509
  } catch (error2) {
35348
35510
  return {
35349
35511
  id: reportId,
@@ -35384,12 +35546,12 @@ async function runPreflight(dir, phase, config) {
35384
35546
  });
35385
35547
  const checks = [];
35386
35548
  log("[Preflight] Running lint check...");
35387
- const lintResult = await _internals55.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
35549
+ const lintResult = await _internals56.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
35388
35550
  checks.push(lintResult);
35389
35551
  log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`);
35390
35552
  if (!cfg.skipTests) {
35391
35553
  log("[Preflight] Running tests check...");
35392
- const testsResult = await _internals55.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
35554
+ const testsResult = await _internals56.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
35393
35555
  checks.push(testsResult);
35394
35556
  log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`);
35395
35557
  } else {
@@ -35401,7 +35563,7 @@ async function runPreflight(dir, phase, config) {
35401
35563
  }
35402
35564
  if (!cfg.skipSecrets) {
35403
35565
  log("[Preflight] Running secrets check...");
35404
- const secretsResult = await _internals55.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
35566
+ const secretsResult = await _internals56.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
35405
35567
  checks.push(secretsResult);
35406
35568
  log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`);
35407
35569
  } else {
@@ -35413,7 +35575,7 @@ async function runPreflight(dir, phase, config) {
35413
35575
  }
35414
35576
  if (!cfg.skipEvidence) {
35415
35577
  log("[Preflight] Running evidence check...");
35416
- const evidenceResult = await _internals55.runEvidenceCheck(validatedDir);
35578
+ const evidenceResult = await _internals56.runEvidenceCheck(validatedDir);
35417
35579
  checks.push(evidenceResult);
35418
35580
  log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`);
35419
35581
  } else {
@@ -35424,12 +35586,12 @@ async function runPreflight(dir, phase, config) {
35424
35586
  });
35425
35587
  }
35426
35588
  log("[Preflight] Running requirement coverage check...");
35427
- const reqCoverageResult = await _internals55.runRequirementCoverageCheck(validatedDir, phase);
35589
+ const reqCoverageResult = await _internals56.runRequirementCoverageCheck(validatedDir, phase);
35428
35590
  checks.push(reqCoverageResult);
35429
35591
  log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`);
35430
35592
  if (!cfg.skipVersion) {
35431
35593
  log("[Preflight] Running version check...");
35432
- const versionResult = await _internals55.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
35594
+ const versionResult = await _internals56.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
35433
35595
  checks.push(versionResult);
35434
35596
  log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`);
35435
35597
  } else {
@@ -35492,10 +35654,10 @@ function formatPreflightMarkdown(report) {
35492
35654
  async function handlePreflightCommand(directory, _args) {
35493
35655
  const plan = await loadPlan(directory);
35494
35656
  const phase = plan?.current_phase ?? 1;
35495
- const report = await _internals55.runPreflight(directory, phase);
35496
- return _internals55.formatPreflightMarkdown(report);
35657
+ const report = await _internals56.runPreflight(directory, phase);
35658
+ return _internals56.formatPreflightMarkdown(report);
35497
35659
  }
35498
- var _internals55 = {
35660
+ var _internals56 = {
35499
35661
  runPreflight,
35500
35662
  formatPreflightMarkdown,
35501
35663
  handlePreflightCommand,
@@ -36466,7 +36628,7 @@ function pruneOldResetBackups(backupsRoot, warnings) {
36466
36628
  }
36467
36629
 
36468
36630
  // src/commands/reset.ts
36469
- var _internals56 = {
36631
+ var _internals57 = {
36470
36632
  backupSwarmStateBeforeReset
36471
36633
  };
36472
36634
  async function handleResetCommand(directory, args) {
@@ -36500,7 +36662,7 @@ async function handleResetCommand(directory, args) {
36500
36662
  ];
36501
36663
  const results = [];
36502
36664
  try {
36503
- const backup = _internals56.backupSwarmStateBeforeReset(directory, "reset", [
36665
+ const backup = _internals57.backupSwarmStateBeforeReset(directory, "reset", [
36504
36666
  ...filesToReset,
36505
36667
  "summaries"
36506
36668
  ]);
@@ -37122,7 +37284,7 @@ async function recordReplayEntry(artifactPath, sessionID, entry) {
37122
37284
  }
37123
37285
 
37124
37286
  // src/prm/index.ts
37125
- var _internals57 = {
37287
+ var _internals58 = {
37126
37288
  getAgentSession,
37127
37289
  readTrajectory,
37128
37290
  getInMemoryTrajectory,
@@ -37145,12 +37307,12 @@ function resetPrmSessionState(session, sessionId) {
37145
37307
  session.prmTrajectoryStep = 0;
37146
37308
  session.replayArtifactPath = null;
37147
37309
  if (sessionId) {
37148
- _internals57.clearTrajectoryCache(sessionId);
37310
+ _internals58.clearTrajectoryCache(sessionId);
37149
37311
  }
37150
37312
  }
37151
37313
 
37152
37314
  // src/commands/reset-session.ts
37153
- var _internals58 = {
37315
+ var _internals59 = {
37154
37316
  cleanupOrphanedBranches,
37155
37317
  backupSwarmStateBeforeReset
37156
37318
  };
@@ -37162,7 +37324,7 @@ function errorMessage(err) {
37162
37324
  async function handleResetSessionCommand(directory, _args) {
37163
37325
  const results = [];
37164
37326
  try {
37165
- const backup = _internals58.backupSwarmStateBeforeReset(directory, "reset-session", ["session"]);
37327
+ const backup = _internals59.backupSwarmStateBeforeReset(directory, "reset-session", ["session"]);
37166
37328
  if (backup.backupDir && backup.copied.length > 0) {
37167
37329
  const rel = path71.relative(directory, backup.backupDir);
37168
37330
  results.push(`\uD83D\uDCE6 Backed up session state to ${rel}/ (restore by copying files back into .swarm/session/)`);
@@ -37229,7 +37391,7 @@ async function handleResetSessionCommand(directory, _args) {
37229
37391
  results.push(`\u26A0\uFE0F Failed to remove .swarm-worktrees/: ${errorMessage(err)}`);
37230
37392
  }
37231
37393
  try {
37232
- const branchResult = await _internals58.cleanupOrphanedBranches(directory, []);
37394
+ const branchResult = await _internals59.cleanupOrphanedBranches(directory, []);
37233
37395
  if (branchResult.removed.length > 0) {
37234
37396
  results.push(`\u2705 Removed ${branchResult.removed.length} orphan swarm-lane branch(es)`);
37235
37397
  }
@@ -37567,7 +37729,7 @@ async function handleRollbackCommand(directory, args) {
37567
37729
  // src/commands/sdd.ts
37568
37730
  import * as fs39 from "fs";
37569
37731
  import * as path74 from "path";
37570
- var _internals59 = {
37732
+ var _internals60 = {
37571
37733
  writeProjectedSpecSync
37572
37734
  };
37573
37735
  var SWARM_SPEC_REL = path74.join(".swarm", "spec.md");
@@ -37963,7 +38125,7 @@ ${USAGE10}`;
37963
38125
 
37964
38126
  ${USAGE10}`;
37965
38127
  }
37966
- const result2 = _internals59.writeProjectedSpecSync(directory, {
38128
+ const result2 = _internals60.writeProjectedSpecSync(directory, {
37967
38129
  source: "speckit",
37968
38130
  feature: resolution.feature,
37969
38131
  dryRun: parsed.dryRun,
@@ -38021,7 +38183,7 @@ ${formatList(result2.projection.warnings)}` : ""
38021
38183
  ].join(`
38022
38184
  `);
38023
38185
  }
38024
- const result = _internals59.writeProjectedSpecSync(directory, {
38186
+ const result = _internals60.writeProjectedSpecSync(directory, {
38025
38187
  changeId: parsed.changeId,
38026
38188
  dryRun: parsed.dryRun,
38027
38189
  overwrite: parsed.overwrite
@@ -38102,7 +38264,7 @@ async function handleSimulateCommand(directory, args) {
38102
38264
  }
38103
38265
  let darkMatterPairs;
38104
38266
  try {
38105
- darkMatterPairs = await _internals25.detectDarkMatter(directory, options);
38267
+ darkMatterPairs = await _internals26.detectDarkMatter(directory, options);
38106
38268
  } catch (err) {
38107
38269
  const errMsg = err instanceof Error ? err.message : String(err);
38108
38270
  return `## Simulate Report
@@ -38163,7 +38325,7 @@ async function handleSpecifyCommand(_directory, args) {
38163
38325
 
38164
38326
  // src/services/status-service.ts
38165
38327
  import * as fsSync2 from "fs";
38166
- import { readFile as readFile17 } from "fs/promises";
38328
+ import { readFile as readFile18 } from "fs/promises";
38167
38329
  import * as path76 from "path";
38168
38330
 
38169
38331
  // src/hooks/extractors.ts
@@ -38408,7 +38570,7 @@ var DEFAULT_CONTEXT_BUDGET_CONFIG = {
38408
38570
  };
38409
38571
 
38410
38572
  // src/services/status-service.ts
38411
- var _internals60 = {
38573
+ var _internals61 = {
38412
38574
  loadLeanTurboRunState,
38413
38575
  hasActiveLeanTurbo,
38414
38576
  hasActiveFullAuto,
@@ -38529,11 +38691,11 @@ async function getStatusData(directory, agents) {
38529
38691
  } catch {
38530
38692
  status.cohort = { linked: false };
38531
38693
  }
38532
- status.fullAutoActive = _internals60.hasActiveFullAuto();
38694
+ status.fullAutoActive = _internals61.hasActiveFullAuto();
38533
38695
  if (status.fullAutoActive) {
38534
- const sid = _internals60.getActiveFullAutoSessionID();
38696
+ const sid = _internals61.getActiveFullAutoSessionID();
38535
38697
  if (sid) {
38536
- const runState = _internals60.loadFullAutoRunState(directory, sid);
38698
+ const runState = _internals61.loadFullAutoRunState(directory, sid);
38537
38699
  if (runState?.lastEscalation) {
38538
38700
  status.fullAutoEscalation = {
38539
38701
  reason: runState.lastEscalation.reason,
@@ -38548,7 +38710,7 @@ async function getStatusData(directory, agents) {
38548
38710
  }
38549
38711
  function enrichWithLeanTurbo(status, directory) {
38550
38712
  const turboMode = hasActiveTurboMode();
38551
- const leanActive = _internals60.hasActiveLeanTurbo();
38713
+ const leanActive = _internals61.hasActiveLeanTurbo();
38552
38714
  let turboStrategy = "off";
38553
38715
  if (leanActive) {
38554
38716
  turboStrategy = "lean";
@@ -38567,7 +38729,7 @@ function enrichWithLeanTurbo(status, directory) {
38567
38729
  }
38568
38730
  }
38569
38731
  if (leanSessionID) {
38570
- const runState = _internals60.loadLeanTurboRunState(directory, leanSessionID);
38732
+ const runState = _internals61.loadLeanTurboRunState(directory, leanSessionID);
38571
38733
  if (runState) {
38572
38734
  status.leanTurboPhase = runState.phase;
38573
38735
  status.leanMaxParallelCoders = runState.maxParallelCoders;
@@ -38724,7 +38886,7 @@ async function safeLineCount(filePath) {
38724
38886
  try {
38725
38887
  if (!fsSync2.existsSync(filePath))
38726
38888
  return 0;
38727
- const content = await readFile17(filePath, "utf-8");
38889
+ const content = await readFile18(filePath, "utf-8");
38728
38890
  let n = 0;
38729
38891
  for (const line of content.split(`
38730
38892
  `)) {
@@ -38774,7 +38936,7 @@ No active swarm plan found. Nothing to sync.`;
38774
38936
 
38775
38937
  // src/commands/turbo.ts
38776
38938
  init_logger();
38777
- var _internals61 = {
38939
+ var _internals62 = {
38778
38940
  loadPluginConfigWithMeta
38779
38941
  };
38780
38942
  async function handleTurboCommand(directory, args, sessionID) {
@@ -38834,7 +38996,7 @@ async function handleTurboCommand(directory, args, sessionID) {
38834
38996
  if (arg0 === "on") {
38835
38997
  let strategy = "standard";
38836
38998
  try {
38837
- const { config } = _internals61.loadPluginConfigWithMeta(directory);
38999
+ const { config } = _internals62.loadPluginConfigWithMeta(directory);
38838
39000
  if (config.turbo?.strategy === "lean") {
38839
39001
  strategy = "lean";
38840
39002
  }
@@ -38931,7 +39093,7 @@ function enableLeanTurbo(session, directory, sessionID) {
38931
39093
  let maxParallelCoders = 4;
38932
39094
  let conflictPolicy = "serialize";
38933
39095
  try {
38934
- const { config } = _internals61.loadPluginConfigWithMeta(directory);
39096
+ const { config } = _internals62.loadPluginConfigWithMeta(directory);
38935
39097
  const leanConfig = config.turbo?.lean;
38936
39098
  if (leanConfig) {
38937
39099
  maxParallelCoders = leanConfig.max_parallel_coders ?? 4;
@@ -39136,7 +39298,7 @@ function findSimilarCommands(query) {
39136
39298
  }
39137
39299
  const scored = VALID_COMMANDS.map((cmd) => {
39138
39300
  const cmdLower = cmd.toLowerCase();
39139
- const fullScore = _internals62.levenshteinDistance(q, cmdLower);
39301
+ const fullScore = _internals63.levenshteinDistance(q, cmdLower);
39140
39302
  let tokenScore = Infinity;
39141
39303
  if (cmd.includes(" ") || cmd.includes("-")) {
39142
39304
  const qTokens = q.split(/[\s-]+/);
@@ -39149,7 +39311,7 @@ function findSimilarCommands(query) {
39149
39311
  for (const ct of cmdTokens) {
39150
39312
  if (ct.length === 0)
39151
39313
  continue;
39152
- const dist = _internals62.levenshteinDistance(qt, ct);
39314
+ const dist = _internals63.levenshteinDistance(qt, ct);
39153
39315
  if (dist < minDist)
39154
39316
  minDist = dist;
39155
39317
  }
@@ -39159,7 +39321,7 @@ function findSimilarCommands(query) {
39159
39321
  }
39160
39322
  const dashStrippedQ = q.replace(/-/g, "");
39161
39323
  const dashStrippedCmd = cmdLower.replace(/-/g, "");
39162
- const dashScore = _internals62.levenshteinDistance(dashStrippedQ, dashStrippedCmd);
39324
+ const dashScore = _internals63.levenshteinDistance(dashStrippedQ, dashStrippedCmd);
39163
39325
  const score = Math.min(fullScore, tokenScore, dashScore);
39164
39326
  return { cmd, score };
39165
39327
  });
@@ -39194,16 +39356,16 @@ function buildDetailedHelp(commandName, entry) {
39194
39356
  async function handleHelpCommand(ctx) {
39195
39357
  const targetCommand = ctx.args.join(" ");
39196
39358
  if (!targetCommand) {
39197
- const { buildHelpText } = await import("./index-g9eg7z93.js");
39359
+ const { buildHelpText } = await import("./index-jzpv74mq.js");
39198
39360
  return buildHelpText();
39199
39361
  }
39200
39362
  const tokens = targetCommand.split(/\s+/);
39201
- const resolved = _internals62.resolveCommand(tokens);
39363
+ const resolved = _internals63.resolveCommand(tokens);
39202
39364
  if (resolved) {
39203
- return _internals62.buildDetailedHelp(resolved.key, resolved.entry);
39365
+ return _internals63.buildDetailedHelp(resolved.key, resolved.entry);
39204
39366
  }
39205
- const similar = _internals62.findSimilarCommands(targetCommand);
39206
- const { buildHelpText: fullHelp } = await import("./index-g9eg7z93.js");
39367
+ const similar = _internals63.findSimilarCommands(targetCommand);
39368
+ const { buildHelpText: fullHelp } = await import("./index-jzpv74mq.js");
39207
39369
  if (similar.length > 0) {
39208
39370
  return `Command '/swarm ${targetCommand}' not found.
39209
39371
 
@@ -39267,7 +39429,7 @@ var COMMAND_REGISTRY = {
39267
39429
  toolNoArgs: true
39268
39430
  },
39269
39431
  help: {
39270
- handler: (ctx) => _internals62.handleHelpCommand(ctx),
39432
+ handler: (ctx) => _internals63.handleHelpCommand(ctx),
39271
39433
  description: "Show help for swarm commands",
39272
39434
  category: "core",
39273
39435
  args: "[command]",
@@ -39336,7 +39498,7 @@ var COMMAND_REGISTRY = {
39336
39498
  },
39337
39499
  "guardrail explain": {
39338
39500
  handler: async (ctx) => {
39339
- const { handleGuardrailExplain } = await import("./guardrail-explain-0vcaa7hj.js");
39501
+ const { handleGuardrailExplain } = await import("./guardrail-explain-hdsxa2c5.js");
39340
39502
  return handleGuardrailExplain(ctx.directory, ctx.args);
39341
39503
  },
39342
39504
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -39346,7 +39508,7 @@ var COMMAND_REGISTRY = {
39346
39508
  },
39347
39509
  "guardrail-explain": {
39348
39510
  handler: async (ctx) => {
39349
- const { handleGuardrailExplain } = await import("./guardrail-explain-0vcaa7hj.js");
39511
+ const { handleGuardrailExplain } = await import("./guardrail-explain-hdsxa2c5.js");
39350
39512
  return handleGuardrailExplain(ctx.directory, ctx.args);
39351
39513
  },
39352
39514
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -40207,7 +40369,7 @@ function validateToolPolicy() {
40207
40369
  }
40208
40370
  return { valid: warnings.length === 0, warnings };
40209
40371
  }
40210
- var _internals62 = {
40372
+ var _internals63 = {
40211
40373
  handleHelpCommand,
40212
40374
  validateAliases,
40213
40375
  validateToolPolicy,
@@ -40217,16 +40379,16 @@ var _internals62 = {
40217
40379
  findSimilarCommands,
40218
40380
  buildDetailedHelp
40219
40381
  };
40220
- var validation = _internals62.validateAliases();
40382
+ var validation = _internals63.validateAliases();
40221
40383
  if (!validation.valid) {
40222
40384
  throw new Error(`COMMAND_REGISTRY alias validation failed:
40223
40385
  ${validation.errors.join(`
40224
40386
  `)}`);
40225
40387
  }
40226
- _internals62.emitValidationWarnings("COMMAND_REGISTRY alias warnings", validation.warnings);
40388
+ _internals63.emitValidationWarnings("COMMAND_REGISTRY alias warnings", validation.warnings);
40227
40389
  try {
40228
- const toolPolicyValidation = _internals62.validateToolPolicy();
40229
- _internals62.emitValidationWarnings("COMMAND_REGISTRY toolPolicy warnings", toolPolicyValidation.warnings);
40390
+ const toolPolicyValidation = _internals63.validateToolPolicy();
40391
+ _internals63.emitValidationWarnings("COMMAND_REGISTRY toolPolicy warnings", toolPolicyValidation.warnings);
40230
40392
  } catch (e) {
40231
40393
  warn(`COMMAND_REGISTRY toolPolicy validation failed (non-fatal): ${e.message}`);
40232
40394
  }
@@ -42918,9 +43080,6 @@ var loggedFirstCalls = new Set;
42918
43080
  // src/hooks/guardrails/messages-transform.ts
42919
43081
  var TRANSIENT_STATUS_CODES = new Set([408, 429, 500, 502, 503, 504, 529]);
42920
43082
 
42921
- // src/hooks/guardrails/stored-input-args.ts
42922
- var storedInputArgs = new Map;
42923
-
42924
43083
  // src/commands/command-dispatch.ts
42925
43084
  function normalizeSwarmCommandInput(command, argumentText) {
42926
43085
  if (command !== "swarm" && !command.startsWith("swarm-")) {
@@ -42946,7 +43105,7 @@ function formatCommandNotFound(tokens) {
42946
43105
  const attemptedCommand = tokens[0] || "";
42947
43106
  const MAX_DISPLAY = 100;
42948
43107
  const displayCommand = attemptedCommand.length > MAX_DISPLAY ? `${attemptedCommand.slice(0, MAX_DISPLAY)}...` : attemptedCommand;
42949
- const similar = _internals62.findSimilarCommands(attemptedCommand);
43108
+ const similar = _internals63.findSimilarCommands(attemptedCommand);
42950
43109
  const header = `Command \`/swarm ${displayCommand}\` not found.`;
42951
43110
  const suggestions = similar.length > 0 ? `Did you mean:
42952
43111
  ${similar.map((cmd) => ` - /swarm ${cmd}`).join(`
@@ -44906,10 +45065,10 @@ function startAgentSession(sessionId, agentName, staleDurationMs = STALE_SESSION
44906
45065
  }
44907
45066
  telemetry.sessionStarted(sessionId, agentName);
44908
45067
  swarmState.activeAgent.set(sessionId, agentName);
44909
- _internals65.applyRehydrationCache(sessionState);
45068
+ _internals66.applyRehydrationCache(sessionState);
44910
45069
  if (directory) {
44911
45070
  let rehydrationPromise;
44912
- rehydrationPromise = _internals65.rehydrateSessionFromDisk(directory, sessionState).then(async () => {
45071
+ rehydrationPromise = _internals66.rehydrateSessionFromDisk(directory, sessionState).then(async () => {
44913
45072
  try {
44914
45073
  sessionState.prSubscriptions = await rehydratePrSubscriptions(sessionId, directory);
44915
45074
  } catch (err) {
@@ -45090,7 +45249,7 @@ function ensureAgentSession(sessionId, agentName, directory) {
45090
45249
  maybeSweepStaleSessions();
45091
45250
  return session;
45092
45251
  }
45093
- _internals65.startAgentSession(sessionId, agentName ?? "unknown", 7200000, directory);
45252
+ _internals66.startAgentSession(sessionId, agentName ?? "unknown", 7200000, directory);
45094
45253
  session = swarmState.agentSessions.get(sessionId);
45095
45254
  if (!session) {
45096
45255
  throw new Error(`Failed to create guardrail session for ${sessionId}`);
@@ -45378,8 +45537,8 @@ function applyRehydrationCache(session) {
45378
45537
  }
45379
45538
  }
45380
45539
  async function rehydrateSessionFromDisk(directory, session) {
45381
- await _internals65.buildRehydrationCache(directory);
45382
- _internals65.applyRehydrationCache(session);
45540
+ await _internals66.buildRehydrationCache(directory);
45541
+ _internals66.applyRehydrationCache(session);
45383
45542
  }
45384
45543
  function hasActiveTurboMode(sessionID) {
45385
45544
  if (sessionID) {
@@ -45467,7 +45626,7 @@ async function rehydratePrSubscriptions(sessionID, directory) {
45467
45626
  }
45468
45627
  return map;
45469
45628
  }
45470
- var _internals65 = {
45629
+ var _internals66 = {
45471
45630
  swarmState,
45472
45631
  resetSwarmState,
45473
45632
  ensureAgentSession,
@@ -45606,4 +45765,4 @@ function createCuratorLLMDelegate(directory, mode = "init", sessionId) {
45606
45765
  };
45607
45766
  }
45608
45767
 
45609
- export { package_default, handleAcknowledgeSpecDriftCommand, handleAgentsCommand, handleAnalyzeCommand, handleArchiveCommand, DC_SAFE_TARGETS, dcNormalizeCommand, dcUnwrapWrappers, dcSplitSegments, dcValidateTargets, dcCheckJunctionCreation, dcExtractWindowsCmdTargets, dcExtractPowerShellTargets, normalizeSwarmCommandInput, canonicalCommandKey, formatCommandNotFound, executeSwarmCommand, SWARM_COMMAND_TOOL_COMMANDS, SWARM_COMMAND_TOOL_ALLOWLIST, HUMAN_ONLY_SWARM_COMMANDS, classifySwarmCommandToolUse, classifySwarmCommandChatFallbackUse, detectPosixWrites, detectWindowsWrites, resolveWriteTargets, handleAutoProceedCommand, handleBenchmarkCommand, handleBrainstormCommand, handleCheckpointCommand, handleCiSimulateCommand, handleClarifyCommand, createCuratorLLMDelegate, _internals14 as _internals, normalizeRecommendationEntryIdToken, parseKnowledgeRecommendations, parseKnowledgeRecommendationsWithDiagnostics, parseStructuredCuratorBlocks, readCuratorSummary, writeCuratorSummary, appendCuratorRecommendation, mergeCuratorPhaseSummary, filterPhaseEvents, checkPhaseCompliance, runCuratorInit, runCuratorPhase, applyCuratorKnowledgeUpdates, isHiveEligible, countDistinctProjects, checkHivePromotions, _internals17 as _internals1, createHivePromoterHook, promoteToHive, promoteFromSwarm, handleCloseCommand, handleCodebaseReviewCommand, handleConcurrencyCommand, handleConfigCommand, handleConsolidateCommand, handleCostsCommand, handleCouncilCommand, handleCurateCommand, handleDarkMatterCommand, handleDeepDiveCommand, handleDeepResearchCommand, getPluginConfigDir, getPluginCachePaths, getPluginLockFilePaths, handleDiagnoseCommand, handleDoctorCommand, handleEvidenceCommand, handleEvidenceSummaryCommand, handleExportCommand, handleFullAutoCommand, handleGateAuditCommand, handleGateStatsCommand, handleHandoffCommand, handleHistoryCommand, handleKnowledgeQuarantineCommand, handleKnowledgeRestoreCommand, handleKnowledgeMigrateCommand, handleKnowledgeListCommand, handleKnowledgeUnactionableCommand, handleKnowledgeRetryHardeningCommand, handleLearningCommand, handleLinkCommand, handleMemoryCommand, handleMemoryStatusCommand, handleMemoryValueLogCommand, handleMemoryMigrateCommand, handleMemoryImportCommand, handleMemoryExportCommand, handlePlanCommand, handlePreflightCommand, handlePromoteCommand, handleQaGatesCommand, handleResetCommand, handleResetSessionCommand, handleRetrieveCommand, handleRollbackCommand, handleSddStatusCommand, handleSddValidateCommand, handleSddProjectCommand, handleSddCommand, handleSimulateCommand, handleSpecifyCommand, handleStatusCommand, handleSyncPlanCommand, handleTurboCommand, handleUnlinkCommand, handleWriteRetroCommand, handleHelpCommand, COMMAND_REGISTRY, VALID_COMMANDS, _internals62 as _internals2, resolveCommand };
45768
+ export { package_default, handleAcknowledgeSpecDriftCommand, handleAgentsCommand, handleAnalyzeCommand, handleArchiveCommand, DC_SAFE_TARGETS, dcNormalizeCommand, dcUnwrapWrappers, dcSplitSegments, dcValidateTargets, dcCheckJunctionCreation, dcExtractWindowsCmdTargets, dcExtractPowerShellTargets, normalizeSwarmCommandInput, canonicalCommandKey, formatCommandNotFound, executeSwarmCommand, SWARM_COMMAND_TOOL_COMMANDS, SWARM_COMMAND_TOOL_ALLOWLIST, HUMAN_ONLY_SWARM_COMMANDS, classifySwarmCommandToolUse, classifySwarmCommandChatFallbackUse, detectPosixWrites, detectWindowsWrites, resolveWriteTargets, handleAutoProceedCommand, handleBenchmarkCommand, handleBrainstormCommand, handleCheckpointCommand, handleCiSimulateCommand, handleClarifyCommand, createCuratorLLMDelegate, _internals15 as _internals, normalizeRecommendationEntryIdToken, parseKnowledgeRecommendations, parseKnowledgeRecommendationsWithDiagnostics, parseStructuredCuratorBlocks, readCuratorSummary, writeCuratorSummary, appendCuratorRecommendation, mergeCuratorPhaseSummary, filterPhaseEvents, checkPhaseCompliance, runCuratorInit, runCuratorPhase, applyCuratorKnowledgeUpdates, isHiveEligible, countDistinctProjects, checkHivePromotions, _internals18 as _internals1, createHivePromoterHook, promoteToHive, promoteFromSwarm, handleCloseCommand, handleCodebaseReviewCommand, handleConcurrencyCommand, handleConfigCommand, handleConsolidateCommand, handleCostsCommand, handleCouncilCommand, handleCurateCommand, handleDarkMatterCommand, handleDeepDiveCommand, handleDeepResearchCommand, getPluginConfigDir, getPluginCachePaths, getPluginLockFilePaths, handleDiagnoseCommand, handleDoctorCommand, handleEvidenceCommand, handleEvidenceSummaryCommand, handleExportCommand, handleFullAutoCommand, handleGateAuditCommand, handleGateStatsCommand, handleHandoffCommand, handleHistoryCommand, handleKnowledgeQuarantineCommand, handleKnowledgeRestoreCommand, handleKnowledgeMigrateCommand, handleKnowledgeListCommand, handleKnowledgeUnactionableCommand, handleKnowledgeRetryHardeningCommand, handleLearningCommand, handleLinkCommand, handleMemoryCommand, handleMemoryStatusCommand, handleMemoryValueLogCommand, handleMemoryMigrateCommand, handleMemoryImportCommand, handleMemoryExportCommand, handlePlanCommand, handlePreflightCommand, handlePromoteCommand, handleQaGatesCommand, handleResetCommand, handleResetSessionCommand, handleRetrieveCommand, handleRollbackCommand, handleSddStatusCommand, handleSddValidateCommand, handleSddProjectCommand, handleSddCommand, handleSimulateCommand, handleSpecifyCommand, handleStatusCommand, handleSyncPlanCommand, handleTurboCommand, handleUnlinkCommand, handleWriteRetroCommand, handleHelpCommand, COMMAND_REGISTRY, VALID_COMMANDS, _internals63 as _internals2, resolveCommand };