opencode-swarm 7.140.3 → 7.140.4

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 (112) hide show
  1. package/.opencode/skills/brainstorm/SKILL.md +1 -1
  2. package/.opencode/skills/ci-failure-batching/SKILL.md +11 -1
  3. package/.opencode/skills/ci-fix-monitor/SKILL.md +6 -4
  4. package/.opencode/skills/discover/SKILL.md +1 -1
  5. package/.opencode/skills/durable-session-state/SKILL.md +82 -0
  6. package/.opencode/skills/engineering-conventions/SKILL.md +1 -1
  7. package/.opencode/skills/issue-ingest/SKILL.md +13 -7
  8. package/.opencode/skills/issue-tracer/SKILL.md +1 -1
  9. package/.opencode/skills/orchestrating-subagents/SKILL.md +113 -0
  10. package/.opencode/skills/parallel-work-check/SKILL.md +1 -1
  11. package/.opencode/skills/swarm-ci-monitor/SKILL.md +5 -3
  12. package/.opencode/skills/swarm-pr-feedback/SKILL.md +30 -4
  13. package/.opencode/skills/writing-tests/SKILL.md +1 -1
  14. package/dist/agents/reviewer-directive-compliance.d.ts +19 -5
  15. package/dist/cli/{config-doctor-fnmfd35x.js → config-doctor-qqe6172n.js} +3 -3
  16. package/dist/cli/{core-p5cyej3r.js → core-52k057mf.js} +2 -2
  17. package/dist/cli/{curation-policy-d52h4g8t.js → curation-policy-9291bdat.js} +5 -7
  18. package/dist/cli/{curator-3zpdqt9r.js → curator-04xqq68e.js} +28 -28
  19. package/dist/cli/{curator-llm-factory-2h0xb62t.js → curator-llm-factory-cfm8fhdw.js} +28 -28
  20. package/dist/cli/{evidence-summary-service-nfdc1ht9.js → evidence-summary-service-em58myd7.js} +8 -8
  21. package/dist/cli/{gate-evidence-46qeyfc1.js → gate-evidence-ezxfkb22.js} +4 -4
  22. package/dist/cli/{guardrail-explain-yktan15c.js → guardrail-explain-pn1bcgfz.js} +29 -29
  23. package/dist/cli/{guardrail-log-82da8y5a.js → guardrail-log-vb5zkegf.js} +4 -4
  24. package/dist/cli/{hive-promoter-af5yaxvt.js → hive-promoter-z09khawt.js} +28 -28
  25. package/dist/cli/index-2rb3x0fk.js +2554 -0
  26. package/dist/cli/{index-hfvxhk4z.js → index-35qep0v7.js} +1 -1
  27. package/dist/cli/{index-h2waehqq.js → index-4hp8nvwb.js} +1 -1
  28. package/dist/cli/{index-8n4c3vec.js → index-7begd9aq.js} +4 -4
  29. package/dist/cli/{index-q1q8b85k.js → index-a1fjhx4w.js} +822 -688
  30. package/dist/cli/{index-xz8f1n1a.js → index-arza4m4j.js} +2 -2
  31. package/dist/cli/{index-ry0hgg3m.js → index-bfhwtdsw.js} +34 -0
  32. package/dist/cli/{index-jfjnn408.js → index-bn17ycxn.js} +1 -1
  33. package/dist/cli/{index-1m1ksyqt.js → index-c5kr20nz.js} +1 -1
  34. package/dist/cli/{index-pj9h75cc.js → index-djbhe0yh.js} +30 -30
  35. package/dist/cli/{index-p9dsb0tw.js → index-dtam929z.js} +2 -19
  36. package/dist/cli/{index-n0pja0qs.js → index-dtyeabmj.js} +2 -2
  37. package/dist/cli/{index-7kdd75se.js → index-hfjvepk2.js} +11 -9
  38. package/dist/cli/{index-j1xmren9.js → index-hfwzxh3j.js} +3 -3
  39. package/dist/cli/{index-n408rw7n.js → index-hxvkfx6t.js} +12 -0
  40. package/dist/cli/{index-brh827g0.js → index-hz0refz4.js} +10 -10
  41. package/dist/cli/{index-gtbmabws.js → index-mpytsq6k.js} +2 -2
  42. package/dist/cli/{index-rs1f1bh0.js → index-mrpfd1jx.js} +1 -1
  43. package/dist/cli/{index-8bnzzv3b.js → index-pp5m7xga.js} +2 -2
  44. package/dist/cli/{index-b9rd29ge.js → index-rrb6cz2f.js} +1 -1
  45. package/dist/cli/{index-adyxbmt5.js → index-ryq97w1x.js} +2 -2
  46. package/dist/cli/{index-95bj4kaw.js → index-s8g7jh1k.js} +2 -2
  47. package/dist/cli/{index-7d5jseea.js → index-tj04dj06.js} +5 -2
  48. package/dist/cli/{index-jvk119ck.js → index-v1an91bq.js} +54 -19
  49. package/dist/cli/{index-898f16j9.js → index-v3x7j9ey.js} +2 -2
  50. package/dist/cli/{index-pg7n141e.js → index-v3xhc7kg.js} +1 -1
  51. package/dist/cli/{index-qksjaxpd.js → index-vrmkg8fm.js} +46 -15
  52. package/dist/cli/{index-yyyk63kk.js → index-w4etfamq.js} +2 -2
  53. package/dist/cli/{index-kbfsp07d.js → index-wk8s1m7b.js} +2 -2
  54. package/dist/cli/{index-wf35ka4z.js → index-ysa38bnr.js} +2 -2
  55. package/dist/cli/index.js +28 -28
  56. package/dist/cli/{knowledge-escalator-7q59skqg.js → knowledge-escalator-gdjnwszd.js} +19 -7
  57. package/dist/cli/{knowledge-events-3nwfdpq7.js → knowledge-events-581x4q7n.js} +18 -5
  58. package/dist/cli/{knowledge-link-q46k9adx.js → knowledge-link-axx45d1h.js} +4 -4
  59. package/dist/cli/{knowledge-store-0d83rhh3.js → knowledge-store-ttg33482.js} +5 -5
  60. package/dist/cli/{knowledge-validator-6mfx91a2.js → knowledge-validator-8kywqt8b.js} +7 -8
  61. package/dist/cli/{pending-delegations-qzrx38y9.js → pending-delegations-btwqsvz4.js} +3 -3
  62. package/dist/cli/{pr-subscriptions-5s59h4dd.js → pr-subscriptions-83y1cdwv.js} +3 -3
  63. package/dist/cli/{runner-y78d7ryb.js → runner-fh3r41nw.js} +5 -5
  64. package/dist/cli/{scan-cursor-rc8q12ss.js → scan-cursor-j8ytdpam.js} +6 -6
  65. package/dist/cli/{schema-n9eaxp3a.js → schema-6xfqtpvn.js} +2 -2
  66. package/dist/cli/{scope-persistence-dr1msqxw.js → scope-persistence-8c72jrgp.js} +4 -4
  67. package/dist/cli/{skill-generator-q7c6vadg.js → skill-generator-n8vm1yhn.js} +18 -9
  68. package/dist/cli/{telemetry-sc57xtb0.js → telemetry-fb44gpba.js} +1 -1
  69. package/dist/cli/{worktree-collision-ownership-7a8e6gr9.js → worktree-collision-ownership-f28r473k.js} +3 -3
  70. package/dist/commands/ci-simulate.d.ts +7 -3
  71. package/dist/commands/close.d.ts +8 -0
  72. package/dist/commands/registry.d.ts +2 -2
  73. package/dist/commands/sdd.d.ts +15 -0
  74. package/dist/config/bundled-skills.d.ts +1 -1
  75. package/dist/config/schema.d.ts +2 -0
  76. package/dist/git/branch.d.ts +1 -1
  77. package/dist/hooks/delegate-ack-collector.d.ts +5 -0
  78. package/dist/hooks/hive-promoter.d.ts +4 -4
  79. package/dist/hooks/issue-trace-reducer.d.ts +7 -1
  80. package/dist/hooks/issue-trace-state.d.ts +18 -0
  81. package/dist/hooks/issue-trace.d.ts +3 -1
  82. package/dist/hooks/knowledge-application-gate.d.ts +8 -3
  83. package/dist/hooks/knowledge-application.d.ts +8 -5
  84. package/dist/hooks/knowledge-escalator.d.ts +9 -5
  85. package/dist/hooks/knowledge-events.d.ts +21 -8
  86. package/dist/hooks/knowledge-injector.d.ts +9 -0
  87. package/dist/hooks/knowledge-receipt-ledger-storage.d.ts +49 -0
  88. package/dist/hooks/knowledge-receipt-ledger.d.ts +305 -0
  89. package/dist/hooks/knowledge-receipt-observability.d.ts +28 -0
  90. package/dist/hooks/knowledge-receipt-validator.d.ts +13 -50
  91. package/dist/hooks/knowledge-store.d.ts +6 -1
  92. package/dist/hooks/knowledge-types.d.ts +12 -0
  93. package/dist/hooks/phase-complete-directive-gate.d.ts +3 -1
  94. package/dist/hooks/phase-directives.d.ts +4 -4
  95. package/dist/hooks/pr-workflow-gate.d.ts +34 -1
  96. package/dist/hooks/promotion-evidence-store.d.ts +14 -8
  97. package/dist/hooks/reviewer-verdict-parser.d.ts +34 -10
  98. package/dist/index.js +550 -531
  99. package/dist/knowledge/curation-policy.d.ts +0 -2
  100. package/dist/observability/catalog.d.ts +5 -3
  101. package/dist/observability/legacy.d.ts +4 -3
  102. package/dist/telemetry.d.ts +1 -1
  103. package/dist/tools/index.d.ts +3 -0
  104. package/dist/tools/manifest.d.ts +3 -0
  105. package/dist/tools/phase-complete.d.ts +9 -0
  106. package/dist/tools/rebind-pr-feedback-head.d.ts +17 -0
  107. package/dist/tools/record-implementation-review.d.ts +19 -0
  108. package/dist/tools/record-recurrence-sweep.d.ts +17 -0
  109. package/dist/tools/run-pr-feedback-stage-a.d.ts +8 -0
  110. package/dist/tools/tool-metadata.d.ts +12 -0
  111. package/package.json +3 -1
  112. package/dist/cli/index-n8jncheh.js +0 -666
@@ -13,16 +13,16 @@ import {
13
13
  resolveExecutableFromPath,
14
14
  runEvaluation,
15
15
  runExternalTool
16
- } from "./index-1m1ksyqt.js";
16
+ } from "./index-c5kr20nz.js";
17
17
  import {
18
18
  stableCanonicalStringify
19
- } from "./index-wf35ka4z.js";
19
+ } from "./index-ysa38bnr.js";
20
20
  import {
21
21
  detectStraySwarmDirs,
22
22
  readDoctorArtifact,
23
23
  removeStraySwarmDir,
24
24
  runConfigDoctor
25
- } from "./index-xz8f1n1a.js";
25
+ } from "./index-arza4m4j.js";
26
26
  import {
27
27
  MAX_TRANSIENT_RETRIES,
28
28
  archiveEvidence,
@@ -34,6 +34,7 @@ import {
34
34
  containsControlChars,
35
35
  containsPathTraversal,
36
36
  derivePlanMarkdown,
37
+ detectDefaultRemoteBranch,
37
38
  disableEpicMode,
38
39
  enableEpicMode,
39
40
  ensureTaskCheckpointReceipt,
@@ -67,7 +68,7 @@ import {
67
68
  transientBackoff,
68
69
  updateTaskCheckpointReceipt,
69
70
  validateProjectRoot
70
- } from "./index-brh827g0.js";
71
+ } from "./index-hz0refz4.js";
71
72
  import {
72
73
  EvaluationTaskV1Schema,
73
74
  GateAuditManifestV1Schema,
@@ -84,7 +85,7 @@ import {
84
85
  saveGateAuditResult,
85
86
  savePromotionDecision,
86
87
  saveTaskSetSnapshot
87
- } from "./index-yyyk63kk.js";
88
+ } from "./index-w4etfamq.js";
88
89
  import {
89
90
  canonicalHash,
90
91
  canonicalJson,
@@ -122,15 +123,15 @@ import {
122
123
  retireSkill,
123
124
  selectCandidateEntries,
124
125
  syncBundledProjectSkillsIfMissingAsync
125
- } from "./index-7kdd75se.js";
126
+ } from "./index-hfjvepk2.js";
126
127
  import {
127
128
  readRecentEscalations
128
- } from "./index-jvk119ck.js";
129
+ } from "./index-v1an91bq.js";
129
130
  import {
130
131
  alreadyCuratedThisGeneration,
131
132
  claimNextScanBatch,
132
133
  resolveCohortId
133
- } from "./index-gtbmabws.js";
134
+ } from "./index-mpytsq6k.js";
134
135
  import {
135
136
  CURATOR_INIT_PROMPT,
136
137
  CURATOR_PHASE_PROMPT,
@@ -153,13 +154,13 @@ import {
153
154
  listActive,
154
155
  subscribe,
155
156
  unsubscribe
156
- } from "./index-jfjnn408.js";
157
+ } from "./index-bn17ycxn.js";
157
158
  import {
158
159
  MAX_PENDING_SCOPE_BINDINGS,
159
160
  clearAllScopes,
160
161
  clearScopeBindingFromDisk,
161
162
  clearScopeBindings
162
- } from "./index-adyxbmt5.js";
163
+ } from "./index-ryq97w1x.js";
163
164
  import {
164
165
  appendLedgerEvent,
165
166
  computePlanHash,
@@ -169,7 +170,7 @@ import {
169
170
  initLedger,
170
171
  readLedgerEvents,
171
172
  takeSnapshotEvent
172
- } from "./index-kbfsp07d.js";
173
+ } from "./index-wk8s1m7b.js";
173
174
  import {
174
175
  getAllWorktreeMergeFailures,
175
176
  initDurableStatusPath
@@ -177,12 +178,7 @@ import {
177
178
  import {
178
179
  findByBatchId,
179
180
  readDelegations
180
- } from "./index-b9rd29ge.js";
181
- import {
182
- readSwarmFileAsync,
183
- safeHook,
184
- validateSwarmPath
185
- } from "./index-k46me75h.js";
181
+ } from "./index-rrb6cz2f.js";
186
182
  import {
187
183
  parsePorcelainV2Snapshot,
188
184
  resolveCommitCountSince,
@@ -212,6 +208,25 @@ import {
212
208
  SandboxCapabilityProbe,
213
209
  init_capability_probe
214
210
  } from "./index-8fwhhayc.js";
211
+ import {
212
+ MAX_EVENT_LOG_ENTRIES,
213
+ _internals,
214
+ effectiveRetrievalOutcomes,
215
+ queryHistoricalOutcomes,
216
+ readAuthoritativeKnowledgeCounterRollups,
217
+ readKnowledgeCounterRollups,
218
+ readKnowledgeEvents,
219
+ reconcilePhaseClose,
220
+ recordHiveKnowledgeEvent,
221
+ recordKnowledgeEvent,
222
+ recordPhaseCloseIntent,
223
+ resolveKnowledgeEventsPath
224
+ } from "./index-2rb3x0fk.js";
225
+ import {
226
+ readSwarmFileAsync,
227
+ safeHook,
228
+ validateSwarmPath
229
+ } from "./index-k46me75h.js";
215
230
  import {
216
231
  appendUnactionable,
217
232
  quarantineEntry,
@@ -222,11 +237,11 @@ import {
222
237
  validateActionableFields,
223
238
  validateLesson,
224
239
  validateSkillPath
225
- } from "./index-8n4c3vec.js";
240
+ } from "./index-7begd9aq.js";
226
241
  import {
227
242
  authorizeCuration,
228
243
  buildConfigFingerprintInput
229
- } from "./index-p9dsb0tw.js";
244
+ } from "./index-dtam929z.js";
230
245
  import {
231
246
  cohortConfigFingerprint
232
247
  } from "./index-rtry5xyf.js";
@@ -259,17 +274,7 @@ import {
259
274
  transactFile,
260
275
  transactKnowledge,
261
276
  wordBigrams
262
- } from "./index-qksjaxpd.js";
263
- import {
264
- MAX_EVENT_LOG_ENTRIES,
265
- _internals,
266
- effectiveRetrievalOutcomes,
267
- readKnowledgeCounterRollups,
268
- readKnowledgeEvents,
269
- recordHiveKnowledgeEvent,
270
- recordKnowledgeEvent,
271
- resolveKnowledgeEventsPath
272
- } from "./index-n8jncheh.js";
277
+ } from "./index-vrmkg8fm.js";
273
278
  import {
274
279
  resolveHiveDataDir,
275
280
  resolveHiveEventsPath,
@@ -285,10 +290,10 @@ import {
285
290
  resolveLinkDir,
286
291
  sanitizeLinkId,
287
292
  writeLinkPointer
288
- } from "./index-rs1f1bh0.js";
293
+ } from "./index-mrpfd1jx.js";
289
294
  import {
290
295
  atomicWriteFile
291
- } from "./index-h2waehqq.js";
296
+ } from "./index-4hp8nvwb.js";
292
297
  import {
293
298
  invalidateCachedArtifact,
294
299
  resetSwarmArtifactCache
@@ -299,7 +304,7 @@ import {
299
304
  isStrictPathDescendant,
300
305
  tryAcquireLock,
301
306
  withEvidenceLock
302
- } from "./index-hfvxhk4z.js";
307
+ } from "./index-35qep0v7.js";
303
308
  import {
304
309
  require_proper_lockfile
305
310
  } from "./index-7g4c7s5r.js";
@@ -313,7 +318,7 @@ import {
313
318
  init_loader,
314
319
  loadPluginConfig,
315
320
  loadPluginConfigWithMeta
316
- } from "./index-8bnzzv3b.js";
321
+ } from "./index-pp5m7xga.js";
317
322
  import {
318
323
  RetrospectiveEvidenceSchema
319
324
  } from "./index-gprxjmm7.js";
@@ -345,7 +350,7 @@ import {
345
350
  package_default,
346
351
  resolveAutoReviewConfig,
347
352
  stripKnownSwarmPrefix
348
- } from "./index-7d5jseea.js";
353
+ } from "./index-tj04dj06.js";
349
354
  import {
350
355
  AGENT_TOOL_MAP,
351
356
  ALL_AGENT_NAMES,
@@ -357,7 +362,7 @@ import {
357
362
  init_agent_names,
358
363
  init_constants,
359
364
  init_tool_metadata
360
- } from "./index-n408rw7n.js";
365
+ } from "./index-hxvkfx6t.js";
361
366
  import {
362
367
  KNOWLEDGE_SCHEMA_VERSION,
363
368
  OUTCOME_BLOCK_THRESHOLD,
@@ -368,7 +373,7 @@ import {
368
373
  emit,
369
374
  getLastHeartbeat,
370
375
  telemetry
371
- } from "./index-ry0hgg3m.js";
376
+ } from "./index-bfhwtdsw.js";
372
377
  import {
373
378
  exports_external,
374
379
  init_zod
@@ -2245,7 +2250,15 @@ var PrFeedbackStageACheckReceiptSchema = exports_external.object({
2245
2250
  feedbackTargets: exports_external.array(exports_external.object({
2246
2251
  feedbackItemId: exports_external.string().min(1),
2247
2252
  target: exports_external.string().min(1),
2248
- expectedBehavior: exports_external.string().min(8)
2253
+ expectedBehavior: exports_external.string().min(8),
2254
+ proofKind: exports_external.enum([
2255
+ "defect",
2256
+ "metadata",
2257
+ "source-proof",
2258
+ "conflict",
2259
+ "ci",
2260
+ "user-decision"
2261
+ ]).optional()
2249
2262
  }).strict()).min(1).optional(),
2250
2263
  durationMs: exports_external.number().nonnegative()
2251
2264
  }).strict();
@@ -2379,6 +2392,7 @@ var PrWorkflowGateStateSchema = exports_external.object({
2379
2392
  prFeedbackStageA: PrFeedbackStageARecordSchema.optional(),
2380
2393
  prFeedbackGateBatches: exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),
2381
2394
  prFeedbackReadyToPublish: PrFeedbackReadyToPublishRecordSchema.optional(),
2395
+ prFeedbackRebindCount: exports_external.number().int().nonnegative().optional(),
2382
2396
  prFeedbackScopes: exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()
2383
2397
  }).passthrough();
2384
2398
  function formatCheckoutRecoveryBlock(state) {
@@ -4311,6 +4325,12 @@ var FEEDBACK_CLASSIFICATIONS = new Set([
4311
4325
  "NEEDS_MORE_EVIDENCE",
4312
4326
  "NEEDS_USER_DECISION"
4313
4327
  ]);
4328
+ var FEEDBACK_NO_CHANGE_CLASSIFICATIONS = new Set([
4329
+ "DISPROVED",
4330
+ "PRE_EXISTING",
4331
+ "NEEDS_MORE_EVIDENCE",
4332
+ "NEEDS_USER_DECISION"
4333
+ ]);
4314
4334
  function parseReviewerVerdictFields(text, itemId) {
4315
4335
  const rows = text.split(/\r?\n/).map(pipeFields).filter((fields2) => fields2[0] === "[REVIEWED]" && fields2[1] === itemId);
4316
4336
  if (rows.length !== 1)
@@ -9506,7 +9526,7 @@ function getDisplayBudget() {
9506
9526
  async function rehydratePrSubscriptions(sessionID, directory) {
9507
9527
  const map = new Map;
9508
9528
  try {
9509
- const { listActive: listActive2 } = await import("./pr-subscriptions-5s59h4dd.js");
9529
+ const { listActive: listActive2 } = await import("./pr-subscriptions-83y1cdwv.js");
9510
9530
  const records = await listActive2(directory);
9511
9531
  for (const record of records) {
9512
9532
  if (record.sessionID !== sessionID)
@@ -20196,11 +20216,13 @@ var OUTPUT_LIMIT_BYTES = 12000;
20196
20216
  var _internals24 = {
20197
20217
  runExternalTool,
20198
20218
  getDefaultBaseBranch,
20219
+ detectDefaultRemoteBranch,
20199
20220
  platform: process.platform,
20200
20221
  osTmpdir: () => os4.tmpdir(),
20201
20222
  fs: {
20202
20223
  existsSync: fs13.existsSync,
20203
- rmSync: fs13.rmSync
20224
+ rmSync: fs13.rmSync,
20225
+ realpathSync: fs13.realpathSync.native
20204
20226
  }
20205
20227
  };
20206
20228
  async function runGit3(args, cwd, timeoutMs = GIT_TIMEOUT_MS4) {
@@ -20250,10 +20272,11 @@ async function getCurrentBranchOrRef(directory) {
20250
20272
  return hashResult.stdout.trim();
20251
20273
  }
20252
20274
  async function setupWorktree(projectRoot, prRef, baseBranch, onWorktreeCreated) {
20253
- const worktreeBase = path31.join(_internals24.osTmpdir(), "swarm-ci-simulate");
20275
+ const rawBase = path31.join(_internals24.osTmpdir(), "swarm-ci-simulate");
20276
+ await fsPromises2.mkdir(rawBase, { recursive: true });
20277
+ const worktreeBase = _internals24.fs.realpathSync(rawBase);
20254
20278
  const worktreeName = `pr-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
20255
20279
  const worktreePath = path31.join(worktreeBase, worktreeName);
20256
- await fsPromises2.mkdir(worktreeBase, { recursive: true });
20257
20280
  const addResult = await runGit3(["worktree", "add", "--detach", worktreePath, baseBranch], projectRoot);
20258
20281
  if (addResult.exitCode !== 0) {
20259
20282
  throw new Error(`Failed to create worktree: ${addResult.stderr.trim() || addResult.stdout.trim()}`);
@@ -20266,15 +20289,37 @@ async function setupWorktree(projectRoot, prRef, baseBranch, onWorktreeCreated)
20266
20289
  return worktreePath;
20267
20290
  }
20268
20291
  async function cleanupWorktree(worktreePath, projectRoot) {
20269
- const removeResult = await runGit3(["worktree", "remove", "--force", worktreePath], projectRoot);
20270
- try {
20271
- if (_internals24.fs.existsSync(worktreePath)) {
20272
- _internals24.fs.rmSync(worktreePath, { recursive: true, force: true });
20273
- }
20274
- } catch {}
20292
+ const rawBase = path31.resolve(_internals24.osTmpdir(), "swarm-ci-simulate");
20293
+ const worktreeBase = _internals24.fs.existsSync(rawBase) ? _internals24.fs.realpathSync(rawBase) : rawBase;
20294
+ const resolved = _internals24.fs.existsSync(worktreePath) ? _internals24.fs.realpathSync(worktreePath) : path31.resolve(worktreePath);
20295
+ const pathEq = _internals24.platform === "win32" ? (a, b) => a.toLowerCase() === b.toLowerCase() : (a, b) => a === b;
20296
+ const pathStartsWith = _internals24.platform === "win32" ? (a, b) => a.toLowerCase().startsWith(b.toLowerCase()) : (a, b) => a.startsWith(b);
20297
+ if (!pathEq(resolved, worktreeBase) && !pathStartsWith(resolved, `${worktreeBase}${path31.sep}`)) {
20298
+ return `[ci-simulate] refusing to clean up non-contained path ${worktreePath}`;
20299
+ }
20300
+ const listResult = await runGit3(["worktree", "list", "--porcelain"], projectRoot);
20301
+ if (listResult.exitCode !== 0) {
20302
+ return `[ci-simulate] could not verify worktree registration: ${listResult.stderr.trim() || listResult.stdout.trim()}`;
20303
+ }
20304
+ const registered = listResult.stdout.split(/\r?\n/).some((line) => {
20305
+ if (!line.startsWith("worktree "))
20306
+ return false;
20307
+ const raw = line.slice("worktree ".length).trim();
20308
+ const canon = _internals24.fs.existsSync(raw) ? _internals24.fs.realpathSync(raw) : path31.resolve(raw);
20309
+ return pathEq(canon, resolved);
20310
+ });
20311
+ if (!registered) {
20312
+ if (!_internals24.fs.existsSync(resolved))
20313
+ return null;
20314
+ return `[ci-simulate] path ${worktreePath} exists but is not a registered git worktree; remove it manually`;
20315
+ }
20316
+ const removeResult = await runGit3(["worktree", "remove", worktreePath], projectRoot);
20275
20317
  if (removeResult.exitCode !== 0) {
20318
+ await runGit3(["worktree", "prune"], projectRoot);
20276
20319
  log(`[ci-simulate] git worktree remove failed: ${removeResult.stderr.trim() || removeResult.stdout.trim()}`);
20320
+ return `[ci-simulate] worktree removal BLOCKED for ${worktreePath}: ${removeResult.stderr.trim() || removeResult.stdout.trim()}. The directory was left in place intentionally \u2014 resolve the block (dirty files or lock) and remove it manually with 'git worktree remove'.`;
20277
20321
  }
20322
+ return null;
20278
20323
  }
20279
20324
  async function runValidationSuite(worktreePath) {
20280
20325
  const steps = [];
@@ -20334,7 +20379,19 @@ function extractFileLineReferences(output) {
20334
20379
  return Array.from(new Set(lines));
20335
20380
  }
20336
20381
  async function handleCiSimulateCommand(directory, args) {
20337
- const prRef = args[0] ?? await getCurrentBranchOrRef(directory);
20382
+ const baseFlagIndex = args.findIndex((token) => token === "--base");
20383
+ let explicitBase;
20384
+ let positional;
20385
+ if (baseFlagIndex !== -1) {
20386
+ explicitBase = args[baseFlagIndex + 1];
20387
+ if (!explicitBase || !isSafeGitRef(explicitBase)) {
20388
+ return "CI simulation failed: --base must be followed by a safe git branch or commit reference (e.g. --base origin/release-1.x).";
20389
+ }
20390
+ positional = args.slice(0, baseFlagIndex).concat(args.slice(baseFlagIndex + 2));
20391
+ } else {
20392
+ positional = args;
20393
+ }
20394
+ const prRef = positional[0] ?? await getCurrentBranchOrRef(directory);
20338
20395
  if (!isSafeGitRef(prRef)) {
20339
20396
  return "CI simulation failed: PR ref must be a safe git branch or commit reference.";
20340
20397
  }
@@ -20351,9 +20408,29 @@ async function handleCiSimulateCommand(directory, args) {
20351
20408
  steps: []
20352
20409
  };
20353
20410
  try {
20354
- const baseBranch = _internals24.getDefaultBaseBranch(directory);
20355
- if (!isSafeGitRef(baseBranch)) {
20356
- throw new Error("Detected default branch is not a safe git reference.");
20411
+ const detectedBranch = _internals24.detectDefaultRemoteBranch(directory);
20412
+ let baseBranch = null;
20413
+ if (explicitBase) {
20414
+ const verify = await runGit3(["rev-parse", "--verify", "--quiet", explicitBase], directory);
20415
+ if (verify.exitCode !== 0) {
20416
+ throw new Error(`Explicit --base "${explicitBase}" does not resolve in this repository (git rev-parse --verify failed). Fetch it or correct the ref.`);
20417
+ }
20418
+ baseBranch = explicitBase;
20419
+ }
20420
+ if (!baseBranch) {
20421
+ for (const candidate of [detectedBranch, "main", "master"].filter((branch) => Boolean(branch))) {
20422
+ const candidateRef = `origin/${candidate}`;
20423
+ if (!isSafeGitRef(candidateRef))
20424
+ continue;
20425
+ const verify = await runGit3(["rev-parse", "--verify", "--quiet", candidateRef], directory);
20426
+ if (verify.exitCode === 0) {
20427
+ baseBranch = candidateRef;
20428
+ break;
20429
+ }
20430
+ }
20431
+ }
20432
+ if (!baseBranch) {
20433
+ throw new Error("Could not resolve an existing default remote branch (origin/HEAD, init.defaultBranch, origin/main, origin/master). Fetch first, or pass an explicit validated base with --base <ref>.");
20357
20434
  }
20358
20435
  lines.push("## Setup");
20359
20436
  lines.push("");
@@ -20432,8 +20509,16 @@ ${step.stderr}`);
20432
20509
  lines.push("---");
20433
20510
  lines.push("");
20434
20511
  lines.push("*Cleaning up temporary worktree...*");
20435
- await cleanupWorktree(worktreePath, directory);
20436
- lines.push(`Worktree removed: \`${worktreePath}\``);
20512
+ const cleanupError = await cleanupWorktree(worktreePath, directory);
20513
+ if (cleanupError) {
20514
+ lines.push("");
20515
+ lines.push(`## \u26A0\uFE0F WORKTREE CLEANUP BLOCKED`);
20516
+ lines.push("");
20517
+ lines.push(cleanupError);
20518
+ result.success = false;
20519
+ } else {
20520
+ lines.push(`Worktree removed: \`${worktreePath}\``);
20521
+ }
20437
20522
  }
20438
20523
  }
20439
20524
  return lines.join(`
@@ -22270,7 +22355,7 @@ function planMerges(active, threshold, maxComparisons, maxMerges) {
22270
22355
  };
22271
22356
  }
22272
22357
  async function sweepActiveNearDuplicates(directory, options = {}) {
22273
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-j1xmren9.js");
22358
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-hfwzxh3j.js");
22274
22359
  const { config } = loadPluginConfigWithMeta2(directory);
22275
22360
  const sweepConfig = config.learning?.dedup_sweep;
22276
22361
  if (sweepConfig?.enabled === false)
@@ -23354,7 +23439,7 @@ async function runCuratorPhase(directory, phase, agentsDispatched, config, knowl
23354
23439
  }
23355
23440
  if (config.skill_generation_enabled === true && skillCandidates.length > 0) {
23356
23441
  try {
23357
- const skillModule = await import("./skill-generator-q7c6vadg.js");
23442
+ const skillModule = await import("./skill-generator-n8vm1yhn.js");
23358
23443
  for (const cand of skillCandidates) {
23359
23444
  if (cand.confidence < (config.min_skill_confidence ?? DEFAULT_SKILL_MIN_CONFIDENCE)) {
23360
23445
  continue;
@@ -23814,7 +23899,7 @@ async function applyCuratorKnowledgeUpdates(directory, recommendations, knowledg
23814
23899
  } catch {}
23815
23900
  }
23816
23901
  if (contradictedEntries.length > 0 && knowledgeConfig.contradiction_threshold_action === "quarantine") {
23817
- const { maybeQuarantineOnContradiction } = await import("./knowledge-escalator-7q59skqg.js");
23902
+ const { maybeQuarantineOnContradiction } = await import("./knowledge-escalator-gdjnwszd.js");
23818
23903
  for (const { id } of contradictedEntries) {
23819
23904
  try {
23820
23905
  await maybeQuarantineOnContradiction(directory, id, knowledgeConfig.contradiction_quarantine_threshold, knowledgeConfig.contradiction_quarantine_window_days);
@@ -24633,7 +24718,7 @@ async function runCuratorPostMortem(directory, options = {}) {
24633
24718
  warnings.push("Failed to collect knowledge summary.");
24634
24719
  }
24635
24720
  try {
24636
- const { getScanStatus } = await import("./scan-cursor-rc8q12ss.js");
24721
+ const { getScanStatus } = await import("./scan-cursor-j8ytdpam.js");
24637
24722
  const scanStatus = await getScanStatus(directory);
24638
24723
  if (scanStatus.remaining_estimate > 0) {
24639
24724
  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.`);
@@ -24805,9 +24890,9 @@ var _internals28 = {
24805
24890
  verifyPostMortemKnowledgeActions,
24806
24891
  repairPostMortemActions,
24807
24892
  loadDefaultKnowledgeConfig: async (directory) => {
24808
- const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-n9eaxp3a.js");
24893
+ const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-6xfqtpvn.js");
24809
24894
  try {
24810
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-j1xmren9.js");
24895
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-hfwzxh3j.js");
24811
24896
  const loaded = loadPluginConfigWithMeta2(directory);
24812
24897
  return KnowledgeConfigSchema2.parse(loaded.config.knowledge ?? {});
24813
24898
  } catch {
@@ -24815,11 +24900,11 @@ var _internals28 = {
24815
24900
  }
24816
24901
  },
24817
24902
  applyCuratorKnowledgeUpdates: async (directory, recommendations, knowledgeConfig, generation) => {
24818
- const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-3zpdqt9r.js");
24903
+ const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-04xqq68e.js");
24819
24904
  return applyCuratorKnowledgeUpdates2(directory, recommendations, knowledgeConfig, generation);
24820
24905
  },
24821
24906
  checkHivePromotions: async (entries, knowledgeConfig, directory) => {
24822
- const { checkHivePromotions } = await import("./hive-promoter-af5yaxvt.js");
24907
+ const { checkHivePromotions } = await import("./hive-promoter-z09khawt.js");
24823
24908
  return checkHivePromotions(entries, knowledgeConfig, directory);
24824
24909
  },
24825
24910
  applyProposalTriage: async (directory, triage) => {
@@ -24828,7 +24913,7 @@ var _internals28 = {
24828
24913
  activateProposal,
24829
24914
  listSkills: listSkills2,
24830
24915
  sanitizeSlug
24831
- } = await import("./skill-generator-q7c6vadg.js");
24916
+ } = await import("./skill-generator-n8vm1yhn.js");
24832
24917
  const result = {
24833
24918
  approved: [],
24834
24919
  rejected: [],
@@ -25082,52 +25167,59 @@ var _internals29 = {
25082
25167
  init_knowledge_types();
25083
25168
 
25084
25169
  // src/hooks/promotion-evidence-store.ts
25085
- import {
25086
- appendFile as appendFile5,
25087
- mkdir as mkdir9,
25088
- readFile as readFile11,
25089
- rename as rename5,
25090
- writeFile as writeFile7
25091
- } from "fs/promises";
25092
25170
  init_logger();
25093
- function resolvePromotionEvidencePath(directory) {
25094
- return validateSwarmPath(directory, "knowledge-promotion-evidence.jsonl");
25171
+ function terminalHistory(membership) {
25172
+ const compatible = membership;
25173
+ const candidates = [
25174
+ ...compatible.terminal_history ?? [],
25175
+ ...compatible.historical_terminals ?? [],
25176
+ ...membership.terminal ? [membership.terminal] : []
25177
+ ];
25178
+ const seen = new Set;
25179
+ return candidates.filter((terminal) => {
25180
+ if (seen.has(terminal.event_id))
25181
+ return false;
25182
+ seen.add(terminal.event_id);
25183
+ return true;
25184
+ });
25095
25185
  }
25096
- function parseRecord(line) {
25186
+ async function loadPromotionEvidenceByEntry(directory, canonicalCohortId) {
25097
25187
  try {
25098
- const o = JSON.parse(line);
25099
- 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") {
25100
- return o;
25188
+ const history = await _internals30.queryHistoricalOutcomes(directory);
25189
+ if (!history.ok)
25190
+ return {};
25191
+ const out = {};
25192
+ for (const membership of history.memberships) {
25193
+ if (typeof membership.cohort_id !== "string" || membership.cohort_id.length === 0 || canonicalCohortId !== undefined && membership.cohort_id !== canonicalCohortId) {
25194
+ continue;
25195
+ }
25196
+ for (const terminal of terminalHistory(membership)) {
25197
+ if (terminal.outcome !== "applied" && terminal.outcome !== "violated" && terminal.outcome !== "contradicted") {
25198
+ continue;
25199
+ }
25200
+ const record = {
25201
+ cohort_id: membership.cohort_id,
25202
+ source_link_id: membership.source_link_id,
25203
+ entry_id: membership.entry_id,
25204
+ retrieval_trace_id: membership.trace_id,
25205
+ receipt_outcome: terminal.outcome,
25206
+ receipt_event_id: terminal.event_id,
25207
+ phase: membership.phase,
25208
+ timestamp: terminal.committed_at
25209
+ };
25210
+ const bucket = out[record.entry_id];
25211
+ if (bucket)
25212
+ bucket.push(record);
25213
+ else
25214
+ out[record.entry_id] = [record];
25215
+ }
25101
25216
  }
25102
- } catch {}
25103
- return null;
25104
- }
25105
- async function loadPromotionEvidenceByEntry(directory) {
25106
- const filePath = resolvePromotionEvidencePath(directory);
25107
- let content;
25108
- try {
25109
- content = await readFile11(filePath, "utf-8");
25217
+ return out;
25110
25218
  } catch {
25111
25219
  return {};
25112
25220
  }
25113
- const out = {};
25114
- for (const line of content.split(`
25115
- `)) {
25116
- const trimmed = line.trim();
25117
- if (!trimmed)
25118
- continue;
25119
- const rec = parseRecord(trimmed);
25120
- if (!rec)
25121
- continue;
25122
- const bucket = out[rec.entry_id];
25123
- if (bucket) {
25124
- bucket.push(rec);
25125
- } else {
25126
- out[rec.entry_id] = [rec];
25127
- }
25128
- }
25129
- return out;
25130
25221
  }
25222
+ var _internals30 = { queryHistoricalOutcomes };
25131
25223
 
25132
25224
  // src/hooks/hive-promoter.ts
25133
25225
  function carryActionableFields(source) {
@@ -25236,8 +25328,8 @@ async function checkHivePromotions(swarmEntries, config, directory) {
25236
25328
  if (config.hive_enabled === false) {
25237
25329
  return empty;
25238
25330
  }
25239
- const sourceCohort = await _internals30.resolveCohortId(directory);
25240
- const evidence2 = await _internals30.loadPromotionEvidence(directory);
25331
+ const sourceCohort = await _internals31.resolveCohortId(directory);
25332
+ const evidence2 = await _internals31.loadPromotionEvidence(directory, sourceCohort.cohortId);
25241
25333
  const diagnostics = [];
25242
25334
  const activeSwarm = swarmEntries.filter((e) => isActiveStatus(e.status));
25243
25335
  const activeSwarmBigrams = activeSwarm.map((e) => typeof e.lesson === "string" ? wordBigrams(e.lesson) : new Set);
@@ -25257,7 +25349,7 @@ async function checkHivePromotions(swarmEntries, config, directory) {
25257
25349
  diagnostics.push(`skip promote '${swarmEntry.lesson.slice(0, 40)}\u2026': ${decision.reason}`);
25258
25350
  continue;
25259
25351
  }
25260
- const validationResult = _internals30.validateLesson(swarmEntry.lesson, [], {
25352
+ const validationResult = _internals31.validateLesson(swarmEntry.lesson, [], {
25261
25353
  category: swarmEntry.category,
25262
25354
  scope: swarmEntry.scope,
25263
25355
  confidence: swarmEntry.confidence
@@ -25279,7 +25371,7 @@ async function checkHivePromotions(swarmEntries, config, directory) {
25279
25371
  });
25280
25372
  }
25281
25373
  const hiveDir = resolveHiveDataDir();
25282
- const result = await _internals30.transactHiveStore(async (ctx) => {
25374
+ const result = await _internals31.transactHiveStore(async (ctx) => {
25283
25375
  let newPromotions = 0;
25284
25376
  let encounters = 0;
25285
25377
  let advancements = 0;
@@ -25505,7 +25597,7 @@ async function authorizeAndRecordHiveMerge(args) {
25505
25597
  let authorized = true;
25506
25598
  let basis = "config-skipped-unlinked";
25507
25599
  try {
25508
- const decision = await _internals30.authorizeCuration({
25600
+ const decision = await _internals31.authorizeCuration({
25509
25601
  directory: hiveDir,
25510
25602
  action: "merge",
25511
25603
  entryId: survivingEntry.id,
@@ -25535,7 +25627,7 @@ async function authorizeAndRecordHiveMerge(args) {
25535
25627
  authorizationBasis: basis
25536
25628
  });
25537
25629
  }
25538
- var _internals30 = {
25630
+ var _internals31 = {
25539
25631
  readSwarmEntries: (directory) => readKnowledge(resolveSwarmKnowledgePath(directory)),
25540
25632
  checkHivePromotions,
25541
25633
  readCuratorSummary,
@@ -25544,20 +25636,20 @@ var _internals30 = {
25544
25636
  transactHiveStore,
25545
25637
  validateLesson,
25546
25638
  authorizeCuration,
25547
- loadPromotionEvidence: async (directory) => loadPromotionEvidenceByEntry(directory),
25639
+ loadPromotionEvidence: async (directory, canonicalCohortId) => loadPromotionEvidenceByEntry(directory, canonicalCohortId),
25548
25640
  loadDefaultKnowledgeConfig: () => KnowledgeConfigSchema.parse({})
25549
25641
  };
25550
25642
  function createHivePromoterHook(directory, config) {
25551
25643
  const hook = async (_input, _output) => {
25552
- const swarmEntries = await _internals30.readSwarmEntries(directory);
25553
- const promotionSummary = await _internals30.checkHivePromotions(swarmEntries, config, directory);
25554
- const curatorSummary = await _internals30.readCuratorSummary(directory);
25644
+ const swarmEntries = await _internals31.readSwarmEntries(directory);
25645
+ const promotionSummary = await _internals31.checkHivePromotions(swarmEntries, config, directory);
25646
+ const curatorSummary = await _internals31.readCuratorSummary(directory);
25555
25647
  if (!curatorSummary)
25556
25648
  return;
25557
25649
  const hasActivity = promotionSummary.new_promotions > 0 || promotionSummary.encounters_incremented > 0 || promotionSummary.advancements > 0;
25558
25650
  if (!hasActivity)
25559
25651
  return;
25560
- await _internals30.appendCuratorRecommendation(directory, {
25652
+ await _internals31.appendCuratorRecommendation(directory, {
25561
25653
  action: "promote",
25562
25654
  lesson: `Hive promotion: ${promotionSummary.new_promotions} new, ${promotionSummary.encounters_incremented} encounters, ${promotionSummary.advancements} advancements, ${promotionSummary.total_hive_entries} total entries`,
25563
25655
  reason: JSON.stringify({
@@ -25595,16 +25687,16 @@ function normalizeManualActionability(fields) {
25595
25687
  async function promoteToHive(directory, lesson, category, options, config, actionable) {
25596
25688
  const trimmedLesson = lesson.trim();
25597
25689
  const actionableFields = normalizeManualActionability(actionable);
25598
- const sourceCohort = await _internals30.resolveCohortId(directory);
25599
- const policyConfig = config ?? _internals30.loadDefaultKnowledgeConfig();
25600
- const result = await _internals30.transactHiveStore(async (ctx) => {
25690
+ const sourceCohort = await _internals31.resolveCohortId(directory);
25691
+ const policyConfig = config ?? _internals31.loadDefaultKnowledgeConfig();
25692
+ const result = await _internals31.transactHiveStore(async (ctx) => {
25601
25693
  if (findNearDuplicate(trimmedLesson, ctx.entries, policyConfig.dedup_threshold)) {
25602
25694
  return {
25603
25695
  kind: "noop",
25604
25696
  return: `Lesson already exists in hive (near-duplicate).`
25605
25697
  };
25606
25698
  }
25607
- const validationResult = _internals30.validateLesson(trimmedLesson, ctx.entries.map((e) => e.lesson), {
25699
+ const validationResult = _internals31.validateLesson(trimmedLesson, ctx.entries.map((e) => e.lesson), {
25608
25700
  category: category || "process",
25609
25701
  scope: "global",
25610
25702
  confidence: 1
@@ -25715,16 +25807,16 @@ async function promoteFromSwarm(directory, lessonId, options, config) {
25715
25807
  if (!swarmEntry) {
25716
25808
  throw new Error(`Lesson ${lessonId} not found in .swarm/knowledge.jsonl`);
25717
25809
  }
25718
- const sourceCohort = await _internals30.resolveCohortId(directory);
25719
- const policyConfig = config ?? _internals30.loadDefaultKnowledgeConfig();
25720
- const result = await _internals30.transactHiveStore(async (ctx) => {
25810
+ const sourceCohort = await _internals31.resolveCohortId(directory);
25811
+ const policyConfig = config ?? _internals31.loadDefaultKnowledgeConfig();
25812
+ const result = await _internals31.transactHiveStore(async (ctx) => {
25721
25813
  if (findNearDuplicate(swarmEntry.lesson, ctx.entries, policyConfig.dedup_threshold)) {
25722
25814
  return {
25723
25815
  kind: "noop",
25724
25816
  return: `Lesson already exists in hive (near-duplicate).`
25725
25817
  };
25726
25818
  }
25727
- const validationResult = _internals30.validateLesson(swarmEntry.lesson, ctx.entries.map((e) => e.lesson), {
25819
+ const validationResult = _internals31.validateLesson(swarmEntry.lesson, ctx.entries.map((e) => e.lesson), {
25728
25820
  category: swarmEntry.category,
25729
25821
  scope: swarmEntry.scope,
25730
25822
  confidence: swarmEntry.confidence
@@ -25815,23 +25907,23 @@ async function promoteFromSwarm(directory, lessonId, options, config) {
25815
25907
  import { createHash as createHash9 } from "crypto";
25816
25908
  import { existsSync as existsSync20 } from "fs";
25817
25909
  import {
25818
- appendFile as appendFile6,
25819
- mkdir as mkdir11,
25820
- readFile as readFile13,
25910
+ appendFile as appendFile5,
25911
+ mkdir as mkdir10,
25912
+ readFile as readFile12,
25821
25913
  realpath as realpath2,
25822
- writeFile as writeFile9
25914
+ writeFile as writeFile8
25823
25915
  } from "fs/promises";
25824
25916
  import * as path41 from "path";
25825
25917
 
25826
25918
  // src/services/synonym-map.ts
25827
25919
  var import_proper_lockfile5 = __toESM(require_proper_lockfile(), 1);
25828
25920
  import {
25829
- mkdir as mkdir10,
25830
- readFile as readFile12,
25831
- rename as rename6,
25921
+ mkdir as mkdir9,
25922
+ readFile as readFile11,
25923
+ rename as rename5,
25832
25924
  stat as stat4,
25833
25925
  unlink as unlink2,
25834
- writeFile as writeFile8
25926
+ writeFile as writeFile7
25835
25927
  } from "fs/promises";
25836
25928
  import * as path40 from "path";
25837
25929
  var SYNONYM_MAP_FILENAME = "synonym-map.json";
@@ -25981,18 +26073,18 @@ async function readSynonymMap(directory, maxPairs = DEFAULT_MAX_PAIRS) {
25981
26073
  const st = await stat4(filePath);
25982
26074
  if (st.size > ceiling)
25983
26075
  return emptySynonymMap();
25984
- const raw = await readFile12(filePath, "utf-8");
26076
+ const raw = await readFile11(filePath, "utf-8");
25985
26077
  return coerceSynonymMap(JSON.parse(raw), maxPairs);
25986
26078
  } catch {
25987
26079
  return emptySynonymMap();
25988
26080
  }
25989
26081
  }
25990
26082
  async function writeSynonymMapAtomic(filePath, map) {
25991
- await mkdir10(path40.dirname(filePath), { recursive: true });
26083
+ await mkdir9(path40.dirname(filePath), { recursive: true });
25992
26084
  const tmp = `${filePath}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`;
25993
26085
  try {
25994
- await writeFile8(tmp, JSON.stringify(map, null, 2), "utf-8");
25995
- await rename6(tmp, filePath);
26086
+ await writeFile7(tmp, JSON.stringify(map, null, 2), "utf-8");
26087
+ await rename5(tmp, filePath);
25996
26088
  } finally {
25997
26089
  try {
25998
26090
  await unlink2(tmp);
@@ -26002,7 +26094,7 @@ async function writeSynonymMapAtomic(filePath, map) {
26002
26094
  async function rebuildSynonymMap(directory, entries, maxPairs = DEFAULT_MAX_PAIRS) {
26003
26095
  const filePath = resolveSynonymMapPath(directory);
26004
26096
  const dir = path40.dirname(filePath);
26005
- await mkdir10(dir, { recursive: true });
26097
+ await mkdir9(dir, { recursive: true });
26006
26098
  let release = null;
26007
26099
  try {
26008
26100
  release = await import_proper_lockfile5.default.lock(dir, {
@@ -26053,9 +26145,9 @@ function hashContent(content) {
26053
26145
  return createHash9("sha1").update(content).digest("hex");
26054
26146
  }
26055
26147
  async function loadConfigForPolicyCurator(directory) {
26056
- const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-n9eaxp3a.js");
26148
+ const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-6xfqtpvn.js");
26057
26149
  try {
26058
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-j1xmren9.js");
26150
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-hfwzxh3j.js");
26059
26151
  const { config: loadedConfig } = loadPluginConfigWithMeta2(directory);
26060
26152
  return KnowledgeConfigSchema2.parse(loadedConfig.knowledge ?? {});
26061
26153
  } catch {
@@ -26065,7 +26157,7 @@ async function loadConfigForPolicyCurator(directory) {
26065
26157
  async function canonicalExistingPath(candidate) {
26066
26158
  let resolved = path41.resolve(candidate);
26067
26159
  try {
26068
- resolved = await _internals31.realpath(resolved);
26160
+ resolved = await _internals32.realpath(resolved);
26069
26161
  } catch {}
26070
26162
  return resolved;
26071
26163
  }
@@ -26534,8 +26626,8 @@ RETRY: your last output was missing ${result.missing.join("; ")}; produce valid
26534
26626
  async function appendCuratorSkippedEvent(directory, record) {
26535
26627
  try {
26536
26628
  const filePath = path41.join(directory, ".swarm", "events.jsonl");
26537
- await mkdir11(path41.dirname(filePath), { recursive: true });
26538
- await appendFile6(filePath, `${JSON.stringify({
26629
+ await mkdir10(path41.dirname(filePath), { recursive: true });
26630
+ await appendFile5(filePath, `${JSON.stringify({
26539
26631
  timestamp: new Date().toISOString(),
26540
26632
  event: "curator_skipped",
26541
26633
  entry_id: record.entry_id,
@@ -26577,11 +26669,11 @@ async function consumeInsightCandidates(directory, batchLimit = MESO_INSIGHT_BAT
26577
26669
  if (!existsSync20(filePath))
26578
26670
  return [];
26579
26671
  const consumed = [];
26580
- await transactFile(filePath, async (p) => readInsightJsonl2(await readFile13(p, "utf-8").catch(() => "")), async (p, data) => {
26672
+ await transactFile(filePath, async (p) => readInsightJsonl2(await readFile12(p, "utf-8").catch(() => "")), async (p, data) => {
26581
26673
  const body = data.length === 0 ? "" : `${data.map((c) => JSON.stringify(c)).join(`
26582
26674
  `)}
26583
26675
  `;
26584
- await writeFile9(p, body, "utf-8");
26676
+ await writeFile8(p, body, "utf-8");
26585
26677
  }, (all) => {
26586
26678
  if (all.length === 0)
26587
26679
  return null;
@@ -26900,9 +26992,9 @@ async function curateAndStoreSwarm(lessons, projectName, phaseInfo, directory, c
26900
26992
  } catch {}
26901
26993
  }
26902
26994
  if (!options?.skipAutoPromotion) {
26903
- await _internals31.runAutoPromotion(directory, config);
26995
+ await _internals32.runAutoPromotion(directory, config);
26904
26996
  if (phaseInfo.phase_number > 0) {
26905
- await _internals31.runAutoDemotion(directory, config, phaseInfo.phase_number);
26997
+ await _internals32.runAutoDemotion(directory, config, phaseInfo.phase_number);
26906
26998
  }
26907
26999
  }
26908
27000
  return { stored, reinforced, skipped, rejected, quarantined };
@@ -26911,7 +27003,7 @@ var OUTCOME_PROMOTION_BLOCK = OUTCOME_BLOCK_THRESHOLD;
26911
27003
  async function runAutoPromotion(directory, config) {
26912
27004
  const knowledgePath = resolveSwarmKnowledgePath(directory);
26913
27005
  const entries = await readKnowledge(knowledgePath) ?? [];
26914
- const counterRollups = await readKnowledgeCounterRollups(directory);
27006
+ const counterRollups = await readAuthoritativeKnowledgeCounterRollups(directory);
26915
27007
  let changed = false;
26916
27008
  for (const entry of entries) {
26917
27009
  if (entry.status === "promoted")
@@ -26945,7 +27037,7 @@ async function runAutoPromotion(directory, config) {
26945
27037
  async function runAutoDemotion(directory, config, phaseNumber) {
26946
27038
  const knowledgePath = resolveSwarmKnowledgePath(directory);
26947
27039
  const entries = await readKnowledge(knowledgePath) ?? [];
26948
- const counterRollups = await readKnowledgeCounterRollups(directory);
27040
+ const counterRollups = await readAuthoritativeKnowledgeCounterRollups(directory);
26949
27041
  let changed = false;
26950
27042
  for (const entry of entries) {
26951
27043
  if (entry.status !== "promoted")
@@ -27017,7 +27109,7 @@ function createKnowledgeCuratorHook(directory, config, options = {}) {
27017
27109
  }
27018
27110
  inFlightEvidenceEntries.add(evidenceKey);
27019
27111
  try {
27020
- await _internals31.curateAndStoreSwarm(batch.lessons, batch.projectName, { phase_number: batch.phaseNumber }, directory, config, {
27112
+ await _internals32.curateAndStoreSwarm(batch.lessons, batch.projectName, { phase_number: batch.phaseNumber }, directory, config, {
27021
27113
  llmDelegate: options.llmDelegateFactory?.(trigger.sessionID),
27022
27114
  enrichmentQuota: options.enrichmentQuota
27023
27115
  });
@@ -27049,14 +27141,14 @@ function createKnowledgeCuratorHook(directory, config, options = {}) {
27049
27141
  const projectName = projectNameMatch ? projectNameMatch[1].trim() : "unknown";
27050
27142
  const phaseMatch = /^Phase:\s*(\d+)/m.exec(planContent);
27051
27143
  const phaseNumber = phaseMatch ? parseInt(phaseMatch[1], 10) : 1;
27052
- await _internals31.curateAndStoreSwarm(normalLessons, projectName, { phase_number: phaseNumber }, directory, config, {
27144
+ await _internals32.curateAndStoreSwarm(normalLessons, projectName, { phase_number: phaseNumber }, directory, config, {
27053
27145
  llmDelegate: options.llmDelegateFactory?.(trigger.sessionID),
27054
27146
  enrichmentQuota: options.enrichmentQuota
27055
27147
  });
27056
27148
  };
27057
27149
  return safeHook(handler);
27058
27150
  }
27059
- var _internals31 = {
27151
+ var _internals32 = {
27060
27152
  isWriteToEvidenceFile,
27061
27153
  curateAndStoreSwarm,
27062
27154
  runAutoPromotion,
@@ -27096,7 +27188,7 @@ async function runFinalizeRewardSweep(args) {
27096
27188
  }
27097
27189
  const timestamp = args.timestamp ?? new Date().toISOString();
27098
27190
  const vettedRoot = resolveVettedMemoryRoot(directory, memoryConfig);
27099
- const provider = _internals32.createConfiguredMemoryProviderForRoot(vettedRoot, memoryConfig);
27191
+ const provider = _internals33.createConfiguredMemoryProviderForRoot(vettedRoot, memoryConfig);
27100
27192
  try {
27101
27193
  result.swept = true;
27102
27194
  for (const taskId of taskIds) {
@@ -27116,7 +27208,7 @@ async function runFinalizeRewardSweep(args) {
27116
27208
  }
27117
27209
  let taskRewarded = 0;
27118
27210
  for (const runId of runIds) {
27119
- const { memoriesRewarded } = await _internals32.applyCouncilReward(provider, {
27211
+ const { memoriesRewarded } = await _internals33.applyCouncilReward(provider, {
27120
27212
  runId,
27121
27213
  unitId: taskId,
27122
27214
  reward: FINALIZE_NEGATIVE_TERMINAL_REWARD,
@@ -27142,7 +27234,7 @@ async function runFinalizeRewardSweep(args) {
27142
27234
  }
27143
27235
  return result;
27144
27236
  }
27145
- var _internals32 = {
27237
+ var _internals33 = {
27146
27238
  createConfiguredMemoryProvider,
27147
27239
  createConfiguredMemoryProviderForRoot,
27148
27240
  applyCouncilReward
@@ -27169,7 +27261,7 @@ async function boundedSessionCall(call, timeoutMs, timeoutLabel, failureLabel, s
27169
27261
  })
27170
27262
  ]);
27171
27263
  } catch (error2) {
27172
- _internals33.log(`${failureLabel} for ephemeral session`, {
27264
+ _internals34.log(`${failureLabel} for ephemeral session`, {
27173
27265
  sessionId,
27174
27266
  error: error2 instanceof Error ? error2.message : String(error2)
27175
27267
  });
@@ -27181,21 +27273,21 @@ async function boundedSessionCall(call, timeoutMs, timeoutLabel, failureLabel, s
27181
27273
  async function boundedAbortEphemeralSession(session, sessionId, timeoutMs = DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS) {
27182
27274
  if (typeof session.abort !== "function")
27183
27275
  return;
27184
- await _internals33.boundedSessionCall(() => session.abort({ path: { id: sessionId } }), timeoutMs, "ephemeral session abort timed out", "ephemeral session abort failed", sessionId);
27276
+ await _internals34.boundedSessionCall(() => session.abort({ path: { id: sessionId } }), timeoutMs, "ephemeral session abort timed out", "ephemeral session abort failed", sessionId);
27185
27277
  }
27186
27278
  async function boundedDeleteEphemeralSession(session, sessionId, timeoutMs = DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS) {
27187
- await _internals33.boundedSessionCall(() => session.delete({ path: { id: sessionId } }), timeoutMs, "ephemeral session delete timed out", "ephemeral session delete failed", sessionId);
27279
+ await _internals34.boundedSessionCall(() => session.delete({ path: { id: sessionId } }), timeoutMs, "ephemeral session delete timed out", "ephemeral session delete failed", sessionId);
27188
27280
  }
27189
27281
  async function teardownEphemeralSession(session, sessionId, options = {}) {
27190
27282
  const abortTimeoutMs = options.abortTimeoutMs ?? DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS;
27191
27283
  const deleteTimeoutMs = options.deleteTimeoutMs ?? DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS;
27192
27284
  const skipAbort = options.skipAbort ?? false;
27193
27285
  if (!skipAbort) {
27194
- await _internals33.boundedAbort(session, sessionId, abortTimeoutMs);
27286
+ await _internals34.boundedAbort(session, sessionId, abortTimeoutMs);
27195
27287
  }
27196
- await _internals33.boundedDelete(session, sessionId, deleteTimeoutMs);
27288
+ await _internals34.boundedDelete(session, sessionId, deleteTimeoutMs);
27197
27289
  }
27198
- var _internals33 = {
27290
+ var _internals34 = {
27199
27291
  boundedSessionCall,
27200
27292
  boundedAbort: boundedAbortEphemeralSession,
27201
27293
  boundedDelete: boundedDeleteEphemeralSession,
@@ -27216,7 +27308,7 @@ function parseModelString(model) {
27216
27308
  };
27217
27309
  }
27218
27310
  var defaultBackoff = (retryAttempt) => 2 ** (retryAttempt - 1) * 1000;
27219
- var defaultSleep = (ms) => new Promise((resolve13) => setTimeout(resolve13, ms));
27311
+ var defaultSleep = (ms) => new Promise((resolve14) => setTimeout(resolve14, ms));
27220
27312
  async function dispatchWithModelFallback(opts) {
27221
27313
  const maxRetries = Math.max(0, opts.maxTransientRetriesPerModel ?? 1);
27222
27314
  const backoff = opts.backoffMs ?? defaultBackoff;
@@ -27518,7 +27610,7 @@ function gatherSkillViolations(directory, sessionId) {
27518
27610
  if (!sessionId)
27519
27611
  return [];
27520
27612
  try {
27521
- const entries = _internals34.readSkillUsageEntriesTail(directory, {
27613
+ const entries = _internals35.readSkillUsageEntriesTail(directory, {
27522
27614
  sessionID: sessionId
27523
27615
  });
27524
27616
  const bySkill = new Map;
@@ -27551,7 +27643,7 @@ async function gatherContradictionCandidates(directory, sessionStart, dedupThres
27551
27643
  if (!Number.isFinite(sessionStartMs))
27552
27644
  return [];
27553
27645
  try {
27554
- const all = await _internals34.readKnowledge(resolveSwarmKnowledgePath(directory));
27646
+ const all = await _internals35.readKnowledge(resolveSwarmKnowledgePath(directory));
27555
27647
  const sessionCreated = all.filter((e) => {
27556
27648
  if (typeof e.created_at !== "string")
27557
27649
  return false;
@@ -27599,7 +27691,7 @@ async function gatherRealtimeAdmissionCounts(directory, sessionStart) {
27599
27691
  if (!Number.isFinite(sessionStartMs))
27600
27692
  return;
27601
27693
  try {
27602
- const entries = await _internals34.readKnowledge(resolveSwarmKnowledgePath(directory));
27694
+ const entries = await _internals35.readKnowledge(resolveSwarmKnowledgePath(directory));
27603
27695
  let admitted = 0;
27604
27696
  let reinforced = 0;
27605
27697
  for (const e of entries) {
@@ -27618,7 +27710,7 @@ async function gatherRealtimeAdmissionCounts(directory, sessionStart) {
27618
27710
  }
27619
27711
  let rejected = 0;
27620
27712
  try {
27621
- const rejectedLessons = await _internals34.readRejectedLessons(directory);
27713
+ const rejectedLessons = await _internals35.readRejectedLessons(directory);
27622
27714
  rejected = rejectedLessons.filter((r) => {
27623
27715
  const ms = Date.parse(r.rejected_at ?? "");
27624
27716
  return Number.isFinite(ms) && ms >= sessionStartMs;
@@ -27914,9 +28006,9 @@ async function runSessionReflection(input) {
27914
28006
  const agentDispatches = gatherAgentDispatches(input.agentSessions);
27915
28007
  const { lessons, taxonomy } = await gatherRetroLessonsAndTaxonomy(input.directory);
27916
28008
  const gateFailures = await gatherGateFailures(input.directory);
27917
- const skillViolations = _internals34.gatherSkillViolations(input.directory, input.sessionId);
27918
- const contradictionCandidates = await _internals34.gatherContradictionCandidates(input.directory, input.sessionStart, input.dedupThreshold ?? DEFAULT_DEDUP_THRESHOLD2);
27919
- const realtimeCounts = await _internals34.gatherRealtimeAdmissionCounts(input.directory, input.sessionStart);
28009
+ const skillViolations = _internals35.gatherSkillViolations(input.directory, input.sessionId);
28010
+ const contradictionCandidates = await _internals35.gatherContradictionCandidates(input.directory, input.sessionStart, input.dedupThreshold ?? DEFAULT_DEDUP_THRESHOLD2);
28011
+ const realtimeCounts = await _internals35.gatherRealtimeAdmissionCounts(input.directory, input.sessionStart);
27920
28012
  const knowledgeDelta = input.knowledgeDelta ? {
27921
28013
  ...input.knowledgeDelta,
27922
28014
  admitted: realtimeCounts?.admitted ?? input.knowledgeDelta.admitted,
@@ -27976,7 +28068,7 @@ async function writeSessionReflection(directory, result) {
27976
28068
  await fs16.writeFile(reflectionPath, content, "utf-8");
27977
28069
  return reflectionPath;
27978
28070
  }
27979
- var _internals34 = {
28071
+ var _internals35 = {
27980
28072
  gatherToolProblems,
27981
28073
  gatherAgentDispatches,
27982
28074
  gatherRetroLessonsAndTaxonomy,
@@ -27996,12 +28088,12 @@ var _internals34 = {
27996
28088
 
27997
28089
  // src/services/skill-improver.ts
27998
28090
  import { existsSync as existsSync22 } from "fs";
27999
- import { mkdir as mkdir13, readFile as readFile14, rename as rename7, writeFile as writeFile11 } from "fs/promises";
28091
+ import { mkdir as mkdir12, readFile as readFile13, rename as rename6, writeFile as writeFile10 } from "fs/promises";
28000
28092
  import * as path44 from "path";
28001
28093
  init_logger();
28002
28094
 
28003
28095
  // src/services/trajectory-cluster.ts
28004
- import { mkdir as mkdir12, writeFile as writeFile10 } from "fs/promises";
28096
+ import { mkdir as mkdir11, writeFile as writeFile9 } from "fs/promises";
28005
28097
  import * as path43 from "path";
28006
28098
  init_logger();
28007
28099
  var MACRO_TRAJECTORY_WINDOW = 200;
@@ -28162,15 +28254,15 @@ async function writeMotifProposals(directory, opts = {}) {
28162
28254
  return result;
28163
28255
  const max = opts.maxProposals ?? 10;
28164
28256
  const selected = motifs.slice(0, max);
28165
- const producedAt = _internals35.now().toISOString();
28257
+ const producedAt = _internals36.now().toISOString();
28166
28258
  const candidates = selected.map((motif) => buildMotifCandidate(motif, opts.sessionId));
28167
- const dedupCheck = await _internals35.checkRecommendations(directory, candidates);
28259
+ const dedupCheck = await _internals36.checkRecommendations(directory, candidates);
28168
28260
  const emitted = dedupCheck.decisions.filter((decision) => decision.emit);
28169
28261
  result.duplicatesSuppressed = dedupCheck.decisions.length - emitted.length;
28170
28262
  if (emitted.length === 0)
28171
28263
  return result;
28172
28264
  const proposalsDir = validateSwarmPath(directory, path43.join("skills", "proposals"));
28173
- await mkdir12(proposalsDir, { recursive: true });
28265
+ await mkdir11(proposalsDir, { recursive: true });
28174
28266
  const written = [];
28175
28267
  for (const decision of emitted) {
28176
28268
  const motif = selected[decision.index];
@@ -28179,14 +28271,14 @@ async function writeMotifProposals(directory, opts = {}) {
28179
28271
  continue;
28180
28272
  const slug = `motif-${slugify(motif.signature)}`;
28181
28273
  const filePath = path43.join(proposalsDir, `${slug}.md`);
28182
- await writeFile10(filePath, buildMotifProposal(motif, {
28274
+ await writeFile9(filePath, buildMotifProposal(motif, {
28183
28275
  fingerprint: decision.fingerprint,
28184
28276
  producedAt
28185
28277
  }), "utf-8");
28186
28278
  result.proposalsWritten.push(filePath);
28187
28279
  written.push(candidate);
28188
28280
  }
28189
- await _internals35.recordEmittedRecommendations(directory, written, {
28281
+ await _internals36.recordEmittedRecommendations(directory, written, {
28190
28282
  producedAt
28191
28283
  });
28192
28284
  return result;
@@ -28352,15 +28444,15 @@ async function writeSuccessMotifProposals(directory, opts = {}) {
28352
28444
  return result;
28353
28445
  const max = opts.maxProposals ?? 10;
28354
28446
  const selected = motifs.slice(0, max);
28355
- const producedAt = _internals35.now().toISOString();
28447
+ const producedAt = _internals36.now().toISOString();
28356
28448
  const candidates = selected.map((motif) => buildWorkflowCandidate(motif, opts.sessionId));
28357
- const dedupCheck = await _internals35.checkRecommendations(directory, candidates);
28449
+ const dedupCheck = await _internals36.checkRecommendations(directory, candidates);
28358
28450
  const emitted = dedupCheck.decisions.filter((decision) => decision.emit);
28359
28451
  result.duplicatesSuppressed = dedupCheck.decisions.length - emitted.length;
28360
28452
  if (emitted.length === 0)
28361
28453
  return result;
28362
28454
  const proposalsDir = validateSwarmPath(directory, path43.join("skills", "proposals"));
28363
- await mkdir12(proposalsDir, { recursive: true });
28455
+ await mkdir11(proposalsDir, { recursive: true });
28364
28456
  const written = [];
28365
28457
  for (const decision of emitted) {
28366
28458
  const motif = selected[decision.index];
@@ -28369,14 +28461,14 @@ async function writeSuccessMotifProposals(directory, opts = {}) {
28369
28461
  continue;
28370
28462
  const slug = workflowSlug(motif.signature);
28371
28463
  const filePath = path43.join(proposalsDir, `${slug}.md`);
28372
- await writeFile10(filePath, buildWorkflowProposal(motif, {
28464
+ await writeFile9(filePath, buildWorkflowProposal(motif, {
28373
28465
  fingerprint: decision.fingerprint,
28374
28466
  producedAt
28375
28467
  }), "utf-8");
28376
28468
  result.proposalsWritten.push(filePath);
28377
28469
  written.push(candidate);
28378
28470
  }
28379
- await _internals35.recordEmittedRecommendations(directory, written, {
28471
+ await _internals36.recordEmittedRecommendations(directory, written, {
28380
28472
  producedAt
28381
28473
  });
28382
28474
  return result;
@@ -28385,7 +28477,7 @@ async function writeSuccessMotifProposals(directory, opts = {}) {
28385
28477
  return result;
28386
28478
  }
28387
28479
  }
28388
- var _internals35 = {
28480
+ var _internals36 = {
28389
28481
  now: () => new Date,
28390
28482
  checkRecommendations,
28391
28483
  recordEmittedRecommendations
@@ -28503,10 +28595,10 @@ function timestampSlug(d) {
28503
28595
  return d.toISOString().replace(/[:.]/g, "-");
28504
28596
  }
28505
28597
  async function atomicWrite(p, content) {
28506
- await mkdir13(path44.dirname(p), { recursive: true });
28598
+ await mkdir12(path44.dirname(p), { recursive: true });
28507
28599
  const tmp = `${p}.tmp-${process.pid}-${Date.now()}`;
28508
- await writeFile11(tmp, content, "utf-8");
28509
- await rename7(tmp, p);
28600
+ await writeFile10(tmp, content, "utf-8");
28601
+ await rename6(tmp, p);
28510
28602
  }
28511
28603
  async function gatherInventory(directory) {
28512
28604
  const swarm = await readKnowledge(resolveSwarmKnowledgePath(directory));
@@ -28520,7 +28612,7 @@ async function gatherInventory(directory) {
28520
28612
  for (const skill of skills.active) {
28521
28613
  let content;
28522
28614
  try {
28523
- content = await readFile14(skill.path, "utf-8");
28615
+ content = await readFile13(skill.path, "utf-8");
28524
28616
  } catch {
28525
28617
  continue;
28526
28618
  }
@@ -28696,7 +28788,7 @@ async function reconcileStaleActiveSkills(directory, options = {}) {
28696
28788
  for (const skill of skills.active) {
28697
28789
  let content;
28698
28790
  try {
28699
- content = await readFile14(skill.path, "utf-8");
28791
+ content = await readFile13(skill.path, "utf-8");
28700
28792
  } catch {
28701
28793
  continue;
28702
28794
  }
@@ -28714,7 +28806,7 @@ async function reconcileStaleActiveSkills(directory, options = {}) {
28714
28806
  continue;
28715
28807
  }
28716
28808
  try {
28717
- const regen = await _internals36.regenerateSkill(directory, skill.slug, {
28809
+ const regen = await _internals37.regenerateSkill(directory, skill.slug, {
28718
28810
  evaluate: false
28719
28811
  });
28720
28812
  if (regen.regenerated) {
@@ -28970,7 +29062,7 @@ async function runSkillImprover(req) {
28970
29062
  autoApply
28971
29063
  };
28972
29064
  }
28973
- var _internals36 = {
29065
+ var _internals37 = {
28974
29066
  runSkillImprover,
28975
29067
  buildDeterministicProposal,
28976
29068
  buildLLMProposalFrame,
@@ -29332,13 +29424,13 @@ var write_retro = createSwarmTool({
29332
29424
  task_id: args.task_id !== undefined ? String(args.task_id) : undefined,
29333
29425
  metadata: args.metadata
29334
29426
  };
29335
- return await _internals37.executeWriteRetro(writeRetroArgs, directory);
29427
+ return await _internals38.executeWriteRetro(writeRetroArgs, directory);
29336
29428
  } catch {
29337
29429
  return JSON.stringify({ success: false, phase: rawPhase, message: "Invalid arguments" }, null, 2);
29338
29430
  }
29339
29431
  }
29340
29432
  });
29341
- var _internals37 = {
29433
+ var _internals38 = {
29342
29434
  executeWriteRetro,
29343
29435
  write_retro
29344
29436
  };
@@ -29351,7 +29443,7 @@ import * as fsSync2 from "fs";
29351
29443
  import path46 from "path";
29352
29444
  var DEFAULT_MAX_SOURCE_BYTES = 2 * 1024 * 1024 * 1024;
29353
29445
  var DEFAULT_BUSY_TIMEOUT_MS = 5000;
29354
- var _internals38 = {
29446
+ var _internals39 = {
29355
29447
  existsSync: fsSync2.existsSync,
29356
29448
  statSync: fsSync2.statSync,
29357
29449
  renameSync: fsSync2.renameSync,
@@ -29361,11 +29453,11 @@ var _internals38 = {
29361
29453
  DatabaseCtor: null
29362
29454
  };
29363
29455
  function resolveDatabaseCtor() {
29364
- return _internals38.DatabaseCtor ?? loadDatabaseCtor();
29456
+ return _internals39.DatabaseCtor ?? loadDatabaseCtor();
29365
29457
  }
29366
29458
  function safeRemoveTemp(tempPath) {
29367
29459
  try {
29368
- _internals38.rmSync(tempPath, {
29460
+ _internals39.rmSync(tempPath, {
29369
29461
  force: true,
29370
29462
  recursive: true,
29371
29463
  maxRetries: 3,
@@ -29421,7 +29513,7 @@ function captureRowCounts(db) {
29421
29513
  async function archiveSqliteSnapshot(opts) {
29422
29514
  const maxSourceBytes = opts.maxSourceBytes ?? DEFAULT_MAX_SOURCE_BYTES;
29423
29515
  const busyTimeoutMs = opts.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS;
29424
- if (!_internals38.existsSync(opts.sourcePath)) {
29516
+ if (!_internals39.existsSync(opts.sourcePath)) {
29425
29517
  return {
29426
29518
  requiredness: "required",
29427
29519
  attempt: "not_attempted",
@@ -29434,10 +29526,10 @@ async function archiveSqliteSnapshot(opts) {
29434
29526
  let sourceBytes = 0;
29435
29527
  for (const suffix of ["", "-wal", "-shm"]) {
29436
29528
  const sidecar = opts.sourcePath + suffix;
29437
- if (!_internals38.existsSync(sidecar))
29529
+ if (!_internals39.existsSync(sidecar))
29438
29530
  continue;
29439
29531
  try {
29440
- sourceBytes += _internals38.statSync(sidecar).size;
29532
+ sourceBytes += _internals39.statSync(sidecar).size;
29441
29533
  } catch (err) {
29442
29534
  if (suffix === "") {
29443
29535
  return {
@@ -29464,7 +29556,7 @@ async function archiveSqliteSnapshot(opts) {
29464
29556
  };
29465
29557
  }
29466
29558
  const destFinal = path46.join(opts.destDir, opts.destName);
29467
- const destTemp = path46.join(opts.destDir, `.${opts.destName}.tmp.${_internals38.now()}.${_internals38.randomSuffix()}`);
29559
+ const destTemp = path46.join(opts.destDir, `.${opts.destName}.tmp.${_internals39.now()}.${_internals39.randomSuffix()}`);
29468
29560
  let Db;
29469
29561
  try {
29470
29562
  Db = resolveDatabaseCtor();
@@ -29563,7 +29655,7 @@ async function archiveSqliteSnapshot(opts) {
29563
29655
  };
29564
29656
  }
29565
29657
  try {
29566
- _internals38.renameSync(destTemp, destFinal);
29658
+ _internals39.renameSync(destTemp, destFinal);
29567
29659
  } catch (err) {
29568
29660
  safeRemoveTemp(destTemp);
29569
29661
  return {
@@ -29590,6 +29682,10 @@ async function archiveSqliteSnapshot(opts) {
29590
29682
  }
29591
29683
 
29592
29684
  // src/commands/close.ts
29685
+ var closeReceiptLifecycleInternals = {
29686
+ recordPhaseCloseIntent,
29687
+ reconcilePhaseClose
29688
+ };
29593
29689
  var CLOSE_SKILL_REVIEW_TIMEOUT_MS = 120000;
29594
29690
  var CLOSE_REFLECTION_TIMEOUT_MS = 90000;
29595
29691
  async function runAbortableReflection(input, timeoutMs) {
@@ -29699,6 +29795,9 @@ var ARCHIVE_ARTIFACTS = [
29699
29795
  "close-lessons.md",
29700
29796
  "knowledge.jsonl",
29701
29797
  "knowledge-rejected.jsonl",
29798
+ "knowledge-receipts-v2.jsonl",
29799
+ "knowledge-receipts-v2.snapshot.json",
29800
+ "knowledge-receipts-v2-archive.jsonl",
29702
29801
  "run-memory.jsonl",
29703
29802
  "repo-graph.json",
29704
29803
  "doc-manifest.json",
@@ -29929,8 +30028,8 @@ async function runFinalizeStage(ctx) {
29929
30028
  ];
29930
30029
  ctx.curationSucceeded = false;
29931
30030
  try {
29932
- ctx.curationResult = await _internals39.curateAndStoreSwarm(ctx.allLessons, ctx.projectName, { phase_number: 0 }, ctx.directory, ctx.config, {
29933
- llmDelegate: _internals39.createCuratorLLMDelegate(ctx.directory, "phase", ctx.options.sessionID),
30031
+ ctx.curationResult = await _internals40.curateAndStoreSwarm(ctx.allLessons, ctx.projectName, { phase_number: 0 }, ctx.directory, ctx.config, {
30032
+ llmDelegate: _internals40.createCuratorLLMDelegate(ctx.directory, "phase", ctx.options.sessionID),
29934
30033
  enrichmentQuota: {
29935
30034
  maxCalls: ctx.config.enrichment.max_calls_per_day,
29936
30035
  window: ctx.config.enrichment.quota_window
@@ -29949,7 +30048,7 @@ async function runFinalizeStage(ctx) {
29949
30048
  if (ctx.config.hive_enabled === false) {} else {
29950
30049
  try {
29951
30050
  const entries = await readKnowledge(resolveSwarmKnowledgePath(ctx.directory));
29952
- const result = await _internals39.checkHivePromotions(entries, ctx.config, ctx.directory);
30051
+ const result = await _internals40.checkHivePromotions(entries, ctx.config, ctx.directory);
29953
30052
  ctx.hivePromoted = result.new_promotions;
29954
30053
  } catch (hiveErr) {
29955
30054
  const msg = hiveErr instanceof Error ? hiveErr.message : String(hiveErr);
@@ -29970,7 +30069,7 @@ async function runFinalizeStage(ctx) {
29970
30069
  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.` : "";
29971
30070
  if (ctx.runSkillReview) {
29972
30071
  try {
29973
- const { config: loadedConfig } = _internals39.loadPluginConfigWithMeta(ctx.directory);
30072
+ const { config: loadedConfig } = _internals40.loadPluginConfigWithMeta(ctx.directory);
29974
30073
  const skillImproverConfig = SkillImproverConfigSchema.parse(loadedConfig.skill_improver ?? {});
29975
30074
  const skillReviewResult = await runAbortableSkillReview({
29976
30075
  directory: ctx.directory,
@@ -30035,6 +30134,22 @@ async function runFinalizeStage(ctx) {
30035
30134
  const planDataSnapshot = structuredClone(ctx.planData);
30036
30135
  const closedPhasesLenBefore = ctx.closedPhases.length;
30037
30136
  const closedTasksLenBefore = ctx.closedTasks.length;
30137
+ const receiptPhaseLabels = new Map;
30138
+ for (const phase of ctx.planData.phases ?? []) {
30139
+ const label = extractCurrentPhaseFromPlan({
30140
+ ...ctx.planData,
30141
+ current_phase: phase.id
30142
+ }) ?? `Phase ${phase.id}`;
30143
+ receiptPhaseLabels.set(phase.id, label);
30144
+ const intent = await closeReceiptLifecycleInternals.recordPhaseCloseIntent(ctx.directory, label, ctx.options.sessionID);
30145
+ if (!intent.ok) {
30146
+ if (intent.detail === "no exact receipt lifecycle scope exists for phase closure") {
30147
+ continue;
30148
+ }
30149
+ ctx.warnings.push(`Receipt phase-close intent failed for phase ${phase.id}: ${intent.detail}. Plan terminalization was not attempted.`);
30150
+ return;
30151
+ }
30152
+ }
30038
30153
  ctx.guaranteeResult = guaranteeAllPlansComplete(ctx.planData);
30039
30154
  for (const phaseId of ctx.guaranteeResult.closedPhaseIds) {
30040
30155
  if (!ctx.closedPhases.includes(phaseId)) {
@@ -30046,13 +30161,15 @@ async function runFinalizeStage(ctx) {
30046
30161
  ctx.closedTasks.push(taskId);
30047
30162
  }
30048
30163
  }
30164
+ let terminalPlanPersisted = ctx.planAlreadyDone;
30049
30165
  if (!ctx.planAlreadyDone || ctx.guaranteeResult.closedPhaseIds.length > 0 || ctx.guaranteeResult.closedTaskIds.length > 0) {
30050
30166
  try {
30051
- await _internals39.closePlanTerminalState(ctx.directory, ctx.planData, {
30167
+ await _internals40.closePlanTerminalState(ctx.directory, ctx.planData, {
30052
30168
  closedPhaseIds: ctx.guaranteeResult.closedPhaseIds,
30053
30169
  closedTaskIds: ctx.guaranteeResult.closedTaskIds,
30054
30170
  originalStatuses: ctx.originalStatuses
30055
30171
  });
30172
+ terminalPlanPersisted = true;
30056
30173
  } catch (error2) {
30057
30174
  const msg = error2 instanceof Error ? error2.message : String(error2);
30058
30175
  ctx.warnings.push(`Failed to persist terminal plan state: ${msg}`);
@@ -30062,14 +30179,20 @@ async function runFinalizeStage(ctx) {
30062
30179
  ctx.closedTasks.length = closedTasksLenBefore;
30063
30180
  }
30064
30181
  }
30182
+ for (const phase of terminalPlanPersisted ? ctx.planData.phases ?? [] : []) {
30183
+ const reconciled = await closeReceiptLifecycleInternals.reconcilePhaseClose(ctx.directory, receiptPhaseLabels.get(phase.id) ?? `Phase ${phase.id}`, true, ctx.options.sessionID);
30184
+ if (!reconciled.ok) {
30185
+ ctx.warnings.push(`Receipt phase-close reconciliation remains pending for phase ${phase.id}: ${reconciled.detail}`);
30186
+ }
30187
+ }
30065
30188
  }
30066
30189
  try {
30067
- const { CuratorConfigSchema: CCS } = await import("./schema-n9eaxp3a.js");
30068
- const { config: pmLoadedConfig } = _internals39.loadPluginConfigWithMeta(ctx.directory);
30190
+ const { CuratorConfigSchema: CCS } = await import("./schema-6xfqtpvn.js");
30191
+ const { config: pmLoadedConfig } = _internals40.loadPluginConfigWithMeta(ctx.directory);
30069
30192
  const curatorCfg = CCS.parse(pmLoadedConfig.curator ?? {});
30070
30193
  if (curatorCfg.enabled && curatorCfg.postmortem_enabled) {
30071
- const pmResult = await _internals39.runCuratorPostMortem(ctx.directory, {
30072
- llmDelegate: _internals39.createCuratorLLMDelegate(ctx.directory, "postmortem", ctx.options.sessionID),
30194
+ const pmResult = await _internals40.runCuratorPostMortem(ctx.directory, {
30195
+ llmDelegate: _internals40.createCuratorLLMDelegate(ctx.directory, "postmortem", ctx.options.sessionID),
30073
30196
  scope: "project",
30074
30197
  sessionID: ctx.options.sessionID
30075
30198
  });
@@ -30092,7 +30215,7 @@ async function runArchiveStage(ctx) {
30092
30215
  try {
30093
30216
  await fs17.mkdir(ctx.archiveDir, { recursive: true });
30094
30217
  try {
30095
- await _internals39.flushAndDrainTelemetry();
30218
+ await _internals40.flushAndDrainTelemetry();
30096
30219
  } catch (flushErr) {
30097
30220
  const msg = flushErr instanceof Error ? flushErr.message : String(flushErr);
30098
30221
  ctx.warnings.push(`Telemetry flush before archive failed: ${msg}`);
@@ -30271,7 +30394,7 @@ async function runArchiveEvidenceRetention(ctx) {
30271
30394
  let cacheMaxBytes;
30272
30395
  let cacheMaxRecords;
30273
30396
  try {
30274
- const { config: evidenceLoadedConfig } = _internals39.loadPluginConfigWithMeta(ctx.directory);
30397
+ const { config: evidenceLoadedConfig } = _internals40.loadPluginConfigWithMeta(ctx.directory);
30275
30398
  const evidenceCfg = evidenceLoadedConfig.evidence ?? {};
30276
30399
  if (typeof evidenceCfg.max_age_days === "number") {
30277
30400
  maxAgeDays = evidenceCfg.max_age_days;
@@ -30287,7 +30410,7 @@ async function runArchiveEvidenceRetention(ctx) {
30287
30410
  }
30288
30411
  } catch {}
30289
30412
  try {
30290
- await _internals39.archiveEvidence(ctx.directory, maxAgeDays, maxBundles, {
30413
+ await _internals40.archiveEvidence(ctx.directory, maxAgeDays, maxBundles, {
30291
30414
  report: true,
30292
30415
  cacheMaxBytes,
30293
30416
  cacheMaxRecords
@@ -30500,9 +30623,9 @@ async function runAlignStage(ctx) {
30500
30623
  const pruneBranches = ctx.args.includes("--prune-branches");
30501
30624
  let gitAlignResult = "";
30502
30625
  const prunedBranches = [];
30503
- const gitStatus = _internals39.getGitRepositoryStatus(ctx.directory);
30626
+ const gitStatus = _internals40.getGitRepositoryStatus(ctx.directory);
30504
30627
  if (gitStatus.isRepo) {
30505
- const aggressiveResult = await _internals39.resetToMainAfterMerge(ctx.directory, {
30628
+ const aggressiveResult = await _internals40.resetToMainAfterMerge(ctx.directory, {
30506
30629
  pruneBranches
30507
30630
  });
30508
30631
  if (aggressiveResult.success) {
@@ -30514,7 +30637,7 @@ async function runAlignStage(ctx) {
30514
30637
  ctx.warnings.push("Uncommitted changes were discarded during git alignment");
30515
30638
  }
30516
30639
  } else {
30517
- const alignResult = await _internals39.resetToRemoteBranch(ctx.directory, {
30640
+ const alignResult = await _internals40.resetToRemoteBranch(ctx.directory, {
30518
30641
  pruneBranches
30519
30642
  });
30520
30643
  gitAlignResult = alignResult.message;
@@ -30550,7 +30673,7 @@ async function runFinalizeDryRun(directory, swarmDir, planData, planExists) {
30550
30673
  const wouldArchiveDirs = ACTIVE_STATE_DIRS_TO_CLEAN.filter(existsInSwarm);
30551
30674
  const wouldRemoveTerminal = TERMINAL_STATE_FILES.filter(existsInSwarm);
30552
30675
  const wouldCleanFiles = ACTIVE_STATE_TO_CLEAN.filter((f) => existsInSwarm(f) && !TERMINAL_STATE_FILES.includes(f));
30553
- const gitStatus = _internals39.getGitRepositoryStatus(directory);
30676
+ const gitStatus = _internals40.getGitRepositoryStatus(directory);
30554
30677
  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)";
30555
30678
  const lines = [
30556
30679
  "## /swarm finalize \u2014 DRY RUN (no changes made)",
@@ -30622,12 +30745,12 @@ async function handleCloseCommand(directory, args, options = {}) {
30622
30745
  }
30623
30746
  }
30624
30747
  if (args.includes("--dry-run")) {
30625
- return _internals39.runFinalizeDryRun(directory, swarmDir, planData, planExists);
30748
+ return _internals40.runFinalizeDryRun(directory, swarmDir, planData, planExists);
30626
30749
  }
30627
30750
  let finalizeLock = {
30628
30751
  acquired: false
30629
30752
  };
30630
- finalizeLock = await _internals39.acquireFinalizeLock(directory);
30753
+ finalizeLock = await _internals40.acquireFinalizeLock(directory);
30631
30754
  if (!finalizeLock.acquired) {
30632
30755
  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.`;
30633
30756
  }
@@ -30658,7 +30781,7 @@ This project was already finalized in a previous /swarm close run. The plan has
30658
30781
  if (planExists) {
30659
30782
  planAlreadyDone = phases.length > 0 && phases.every((p) => p.status === "complete" || p.status === "completed" || p.status === "blocked" || p.status === "closed");
30660
30783
  }
30661
- const { config: loadedConfig } = _internals39.loadPluginConfigWithMeta(directory);
30784
+ const { config: loadedConfig } = _internals40.loadPluginConfigWithMeta(directory);
30662
30785
  const config = KnowledgeConfigSchema.parse(loadedConfig.knowledge ?? {});
30663
30786
  const ctx = {
30664
30787
  directory,
@@ -30707,9 +30830,9 @@ This project was already finalized in a previous /swarm close run. The plan has
30707
30830
  archiveSuffix: "",
30708
30831
  args
30709
30832
  };
30710
- ctx.fullAuto = options.sessionID ? _internals39.detectFullAuto(directory, options.sessionID) : false;
30833
+ ctx.fullAuto = options.sessionID ? _internals40.detectFullAuto(directory, options.sessionID) : false;
30711
30834
  await runFinalizeStage(ctx);
30712
- await _internals39.runFinalizeRewardSweep({
30835
+ await _internals40.runFinalizeRewardSweep({
30713
30836
  directory,
30714
30837
  closedTaskIds: ctx.guaranteeResult.closedTaskIds,
30715
30838
  memoryConfig: loadedConfig.memory
@@ -30793,9 +30916,9 @@ This project was already finalized in a previous /swarm close run. The plan has
30793
30916
  try {
30794
30917
  const sessionIdsToEnd = [...swarmState.agentSessions.keys()];
30795
30918
  for (const sessionId of sessionIdsToEnd) {
30796
- _internals39.endAgentSession(sessionId);
30919
+ _internals40.endAgentSession(sessionId);
30797
30920
  }
30798
- _internals39.resetSwarmStatePreservingSingletons();
30921
+ _internals40.resetSwarmStatePreservingSingletons();
30799
30922
  } catch (teardownError) {
30800
30923
  const msg = teardownError instanceof Error ? teardownError.message : String(teardownError);
30801
30924
  ctx.warnings.push(`Session teardown encountered an error after finalization completed (state may not be fully reset): ${msg}`);
@@ -30892,7 +31015,7 @@ function detectFullAuto(directory, sessionID) {
30892
31015
  return false;
30893
31016
  }
30894
31017
  }
30895
- var _internals39 = {
31018
+ var _internals40 = {
30896
31019
  ACTIVE_STATE_DIRS_TO_CLEAN,
30897
31020
  countSessionKnowledgeEntries,
30898
31021
  CLOSE_SKILL_REVIEW_TIMEOUT_MS,
@@ -30921,7 +31044,7 @@ var _internals39 = {
30921
31044
  closePlanTerminalState,
30922
31045
  endAgentSession,
30923
31046
  flushAndDrainTelemetry: async () => {
30924
- const { flushAndDrainTelemetry } = await import("./telemetry-sc57xtb0.js");
31047
+ const { flushAndDrainTelemetry } = await import("./telemetry-fb44gpba.js");
30925
31048
  return flushAndDrainTelemetry();
30926
31049
  }
30927
31050
  };
@@ -31187,7 +31310,7 @@ init_schema();
31187
31310
 
31188
31311
  // src/services/skill-consolidation.ts
31189
31312
  import { existsSync as existsSync26 } from "fs";
31190
- import { mkdir as mkdir14, readFile as readFile15, rename as rename8, writeFile as writeFile12 } from "fs/promises";
31313
+ import { mkdir as mkdir13, readFile as readFile14, rename as rename7, writeFile as writeFile11 } from "fs/promises";
31191
31314
  import * as path49 from "path";
31192
31315
  var DEFAULT_CONSOLIDATION_INTERVAL_HOURS = 24;
31193
31316
  var DEFAULT_CONSOLIDATION_MAX_CALLS_PER_RUN = 1;
@@ -31201,7 +31324,7 @@ async function readState2(directory) {
31201
31324
  if (!existsSync26(filePath))
31202
31325
  return {};
31203
31326
  try {
31204
- const parsed = JSON.parse(await readFile15(filePath, "utf-8"));
31327
+ const parsed = JSON.parse(await readFile14(filePath, "utf-8"));
31205
31328
  if (!parsed || typeof parsed !== "object")
31206
31329
  return {};
31207
31330
  return parsed;
@@ -31210,10 +31333,10 @@ async function readState2(directory) {
31210
31333
  }
31211
31334
  }
31212
31335
  async function atomicWrite2(filePath, content) {
31213
- await mkdir14(path49.dirname(filePath), { recursive: true });
31336
+ await mkdir13(path49.dirname(filePath), { recursive: true });
31214
31337
  const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
31215
- await writeFile12(tmp, content, "utf-8");
31216
- await rename8(tmp, filePath);
31338
+ await writeFile11(tmp, content, "utf-8");
31339
+ await rename7(tmp, filePath);
31217
31340
  }
31218
31341
  async function writeState2(directory, state) {
31219
31342
  await atomicWrite2(consolidationStatePath(directory), `${JSON.stringify(state, null, 2)}
@@ -31388,7 +31511,7 @@ function isValidTelemetryEntry(value) {
31388
31511
  const obj = value;
31389
31512
  return typeof obj.timestamp === "string" && typeof obj.task_id === "string" && typeof obj.agent_role === "string" && typeof obj.delegation_reason === "string" && typeof obj.token_estimate === "number" && typeof obj.cache_hits === "number" && typeof obj.cache_misses === "number" && typeof obj.stale_entries === "number" && typeof obj.recommended_reads === "number" && typeof obj.skipped_reads === "number" && typeof obj.success === "boolean";
31390
31513
  }
31391
- var _internals40 = {
31514
+ var _internals41 = {
31392
31515
  appendFileSync: fs18.appendFileSync,
31393
31516
  readFileSync: fs18.readFileSync,
31394
31517
  existsSync: fs18.existsSync,
@@ -31401,10 +31524,10 @@ function readTelemetry(directory) {
31401
31524
  const filePath = telemetryFilePath(directory);
31402
31525
  const entries = [];
31403
31526
  try {
31404
- if (!_internals40.existsSync(filePath)) {
31527
+ if (!_internals41.existsSync(filePath)) {
31405
31528
  return entries;
31406
31529
  }
31407
- const raw = _internals40.readFileSync(filePath, "utf-8");
31530
+ const raw = _internals41.readFileSync(filePath, "utf-8");
31408
31531
  const lines = raw.split(`
31409
31532
  `);
31410
31533
  for (const line of lines) {
@@ -31619,7 +31742,7 @@ import { promisify as promisify2 } from "util";
31619
31742
  init_zod();
31620
31743
  import * as child_process3 from "child_process";
31621
31744
  import { randomUUID as randomUUID7 } from "crypto";
31622
- import { readdir as readdir3, readFile as readFile16, stat as stat5 } from "fs/promises";
31745
+ import { readdir as readdir3, readFile as readFile15, stat as stat5 } from "fs/promises";
31623
31746
  import * as path51 from "path";
31624
31747
  import { promisify } from "util";
31625
31748
  function getExecFileAsync() {
@@ -31746,7 +31869,7 @@ async function getStaticEdges(directory) {
31746
31869
  const sourceFiles = await scanSourceFiles(directory);
31747
31870
  for (const sourceFile of sourceFiles) {
31748
31871
  try {
31749
- const content = await readFile16(sourceFile, "utf-8");
31872
+ const content = await readFile15(sourceFile, "utf-8");
31750
31873
  const importRegex = /(?:import|require)\s*(?:\(?\s*['"`]|.*?from\s+['"`])([^'"`]+)['"`]/g;
31751
31874
  for (let match = importRegex.exec(content);match !== null; match = importRegex.exec(content)) {
31752
31875
  const importPath = match[1].trim();
@@ -31841,9 +31964,9 @@ async function detectDarkMatter(directory, options) {
31841
31964
  } catch {
31842
31965
  return [];
31843
31966
  }
31844
- const commitMap = await _internals41.parseGitLog(directory, maxCommitsToAnalyze);
31845
- const matrix = _internals41.buildCoChangeMatrix(commitMap, maxFilesPerCommit);
31846
- const staticEdges = await _internals41.getStaticEdges(directory);
31967
+ const commitMap = await _internals42.parseGitLog(directory, maxCommitsToAnalyze);
31968
+ const matrix = _internals42.buildCoChangeMatrix(commitMap, maxFilesPerCommit);
31969
+ const staticEdges = await _internals42.getStaticEdges(directory);
31847
31970
  const results = [];
31848
31971
  for (const entry of matrix.values()) {
31849
31972
  const key = `${entry.fileA}::${entry.fileB}`;
@@ -31959,11 +32082,11 @@ var co_change_analyzer = createSwarmTool({
31959
32082
  npmiThreshold,
31960
32083
  maxCommitsToAnalyze
31961
32084
  };
31962
- const pairs = await _internals41.detectDarkMatter(directory, options);
31963
- return _internals41.formatDarkMatterOutput(pairs);
32085
+ const pairs = await _internals42.detectDarkMatter(directory, options);
32086
+ return _internals42.formatDarkMatterOutput(pairs);
31964
32087
  }
31965
32088
  });
31966
- var _internals41 = {
32089
+ var _internals42 = {
31967
32090
  parseGitLog,
31968
32091
  buildCoChangeMatrix,
31969
32092
  getStaticEdges,
@@ -31980,7 +32103,7 @@ var DEFAULT_MAX_COMMITS = 500;
31980
32103
  var cache = new Map;
31981
32104
  async function readGitHead(directory) {
31982
32105
  try {
31983
- const { stdout } = await _internals42.execFile("git", ["rev-parse", "HEAD"], {
32106
+ const { stdout } = await _internals43.execFile("git", ["rev-parse", "HEAD"], {
31984
32107
  cwd: directory,
31985
32108
  timeout: GIT_HEAD_TIMEOUT_MS
31986
32109
  });
@@ -32006,9 +32129,9 @@ async function getCoChangeData(directory, options) {
32006
32129
  let entries;
32007
32130
  let commitsObserved;
32008
32131
  try {
32009
- const commitMap = await _internals42.parseGitLog(directory, maxCommits);
32132
+ const commitMap = await _internals43.parseGitLog(directory, maxCommits);
32010
32133
  commitsObserved = commitMap.size;
32011
- const matrix = _internals42.buildCoChangeMatrix(commitMap);
32134
+ const matrix = _internals43.buildCoChangeMatrix(commitMap);
32012
32135
  entries = Array.from(matrix.values());
32013
32136
  } catch {
32014
32137
  return { pairs: [], commitsObserved: 0 };
@@ -32032,10 +32155,10 @@ async function getCoChangePairs(directory, options) {
32032
32155
  const data = await getCoChangeData(directory, options);
32033
32156
  return data.pairs;
32034
32157
  }
32035
- var _internals42 = {
32158
+ var _internals43 = {
32036
32159
  execFile: execFileAsync,
32037
- parseGitLog: _internals41.parseGitLog,
32038
- buildCoChangeMatrix: _internals41.buildCoChangeMatrix
32160
+ parseGitLog: _internals42.parseGitLog,
32161
+ buildCoChangeMatrix: _internals42.buildCoChangeMatrix
32039
32162
  };
32040
32163
 
32041
32164
  // src/turbo/epic/coupling-report.ts
@@ -32259,7 +32382,7 @@ async function handleCouplingCommand(directory, args) {
32259
32382
 
32260
32383
  Usage: /swarm coupling [--phase <n>] [--threshold <-1..1>] [--min-co-changes <n>] [--format markdown|json] [--persist]`;
32261
32384
  }
32262
- const plan = await _internals43.loadPlanJsonOnly(directory);
32385
+ const plan = await _internals44.loadPlanJsonOnly(directory);
32263
32386
  if (plan === null) {
32264
32387
  return "No plan found at `.swarm/plan.json`. Run `/swarm plan` to create one before measuring coupling.";
32265
32388
  }
@@ -32283,7 +32406,7 @@ Usage: /swarm coupling [--phase <n>] [--threshold <-1..1>] [--min-co-changes <n>
32283
32406
  const scope = scopeFiles ?? task.files_touched ?? [];
32284
32407
  return { id: task.id, scope };
32285
32408
  });
32286
- const cochangePairs = await _internals43.getCoChangePairs(directory);
32409
+ const cochangePairs = await _internals44.getCoChangePairs(directory);
32287
32410
  const report = computeCouplingReport(tasks, cochangePairs, {
32288
32411
  npmi: parsed.threshold,
32289
32412
  minCoChanges: parsed.minCoChanges
@@ -32322,14 +32445,14 @@ _Warning: failed to persist report (${persistStatus.error})._`;
32322
32445
  }
32323
32446
  return `${formatCouplingReportMarkdown(report)}${persistTrailer}`;
32324
32447
  }
32325
- var _internals43 = {
32448
+ var _internals44 = {
32326
32449
  loadPlanJsonOnly,
32327
32450
  getCoChangePairs
32328
32451
  };
32329
32452
 
32330
32453
  // src/commands/curate.ts
32331
32454
  init_schema();
32332
- var _internals44 = {
32455
+ var _internals45 = {
32333
32456
  checkHivePromotions,
32334
32457
  readKnowledge,
32335
32458
  resolveSwarmKnowledgePath,
@@ -32337,9 +32460,9 @@ var _internals44 = {
32337
32460
  loadPluginConfigWithMeta,
32338
32461
  loadCuratorDeps: async () => {
32339
32462
  const [{ CuratorConfigSchema }, curator, { createCuratorLLMDelegate: createCuratorLLMDelegate2 }] = await Promise.all([
32340
- import("./schema-n9eaxp3a.js"),
32341
- import("./curator-3zpdqt9r.js"),
32342
- import("./curator-llm-factory-2h0xb62t.js")
32463
+ import("./schema-6xfqtpvn.js"),
32464
+ import("./curator-04xqq68e.js"),
32465
+ import("./curator-llm-factory-cfm8fhdw.js")
32343
32466
  ]);
32344
32467
  return { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 };
32345
32468
  }
@@ -32348,20 +32471,20 @@ async function handleCurateCommand(directory, _args, options) {
32348
32471
  try {
32349
32472
  let config;
32350
32473
  try {
32351
- const { config: loadedConfig } = _internals44.loadPluginConfigWithMeta(directory);
32474
+ const { config: loadedConfig } = _internals45.loadPluginConfigWithMeta(directory);
32352
32475
  config = KnowledgeConfigSchema.parse(loadedConfig.knowledge ?? {});
32353
32476
  } catch {
32354
32477
  config = KnowledgeConfigSchema.parse({});
32355
32478
  }
32356
- const swarmPath = _internals44.resolveSwarmKnowledgePath(directory);
32357
- const swarmEntries = await _internals44.readKnowledge(swarmPath) ?? [];
32358
- const summary = await _internals44.checkHivePromotions(swarmEntries, config, directory);
32479
+ const swarmPath = _internals45.resolveSwarmKnowledgePath(directory);
32480
+ const swarmEntries = await _internals45.readKnowledge(swarmPath) ?? [];
32481
+ const summary = await _internals45.checkHivePromotions(swarmEntries, config, directory);
32359
32482
  if (options?.sessionID) {
32360
32483
  let onDemandPhase = 1;
32361
32484
  try {
32362
- const { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 } = await _internals44.loadCuratorDeps();
32485
+ const { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 } = await _internals45.loadCuratorDeps();
32363
32486
  const curatorConfig = CuratorConfigSchema.parse({});
32364
- const priorSummary = await _internals44.readSwarmFileAsync(directory, "curator-summary.json");
32487
+ const priorSummary = await _internals45.readSwarmFileAsync(directory, "curator-summary.json");
32365
32488
  if (priorSummary) {
32366
32489
  try {
32367
32490
  const parsed = JSON.parse(priorSummary);
@@ -32372,7 +32495,7 @@ async function handleCurateCommand(directory, _args, options) {
32372
32495
  }
32373
32496
  let planPhaseCount = Infinity;
32374
32497
  try {
32375
- const planRaw = await _internals44.readSwarmFileAsync(directory, "plan.json");
32498
+ const planRaw = await _internals45.readSwarmFileAsync(directory, "plan.json");
32376
32499
  if (planRaw) {
32377
32500
  const plan = JSON.parse(planRaw);
32378
32501
  if (Array.isArray(plan.phases))
@@ -32391,8 +32514,8 @@ async function handleCurateCommand(directory, _args, options) {
32391
32514
  summary.knowledge_skipped = applied.skipped;
32392
32515
  summary.curator_phase = onDemandPhase;
32393
32516
  try {
32394
- const updatedEntries = await _internals44.readKnowledge(swarmPath) ?? [];
32395
- const postUpdateHive = await _internals44.checkHivePromotions(updatedEntries, config, directory);
32517
+ const updatedEntries = await _internals45.readKnowledge(swarmPath) ?? [];
32518
+ const postUpdateHive = await _internals45.checkHivePromotions(updatedEntries, config, directory);
32396
32519
  summary.new_promotions += postUpdateHive.new_promotions;
32397
32520
  summary.encounters_incremented += postUpdateHive.encounters_incremented;
32398
32521
  summary.advancements += postUpdateHive.advancements;
@@ -32458,7 +32581,7 @@ async function handleDarkMatterCommand(directory, args) {
32458
32581
  }
32459
32582
  let pairs;
32460
32583
  try {
32461
- pairs = await _internals41.detectDarkMatter(directory, options);
32584
+ pairs = await _internals42.detectDarkMatter(directory, options);
32462
32585
  } catch (err) {
32463
32586
  const errMsg = err instanceof Error ? err.message : String(err);
32464
32587
  return `## Dark Matter Analysis Failed
@@ -32723,7 +32846,7 @@ ${USAGE7}`;
32723
32846
  // src/commands/design-docs.ts
32724
32847
  init_warning_buffer();
32725
32848
  var MAX_DESC_LEN = 2000;
32726
- var _internals45 = { loadPluginConfigWithMeta };
32849
+ var _internals46 = { loadPluginConfigWithMeta };
32727
32850
  var USAGE8 = `Usage: /swarm design-docs <description> [--out <dir>] [--lang <name>] [--update]
32728
32851
 
32729
32852
  Generate or sync language-agnostic design docs for the project under build:
@@ -32819,7 +32942,7 @@ async function handleDesignDocsCommand(directory, args) {
32819
32942
  ${USAGE8}`;
32820
32943
  }
32821
32944
  try {
32822
- const { config } = _internals45.loadPluginConfigWithMeta(directory);
32945
+ const { config } = _internals46.loadPluginConfigWithMeta(directory);
32823
32946
  if (config.design_docs?.enabled !== true) {
32824
32947
  return "Error: design docs are disabled. Set `design_docs.enabled: true` in " + `opencode-swarm.json to enable the docs_design agent and this command.
32825
32948
 
@@ -32895,7 +33018,7 @@ init_executor();
32895
33018
  // src/services/knowledge-diagnostics.ts
32896
33019
  init_package();
32897
33020
  import { existsSync as existsSync29, readFileSync as readFileSync19 } from "fs";
32898
- import { readFile as readFile17 } from "fs/promises";
33021
+ import { readFile as readFile16 } from "fs/promises";
32899
33022
  import { join as join42 } from "path";
32900
33023
 
32901
33024
  // src/services/version-check.ts
@@ -32972,7 +33095,7 @@ var INSIGHT_BACKLOG_WARN = 50;
32972
33095
  async function readRawLines(filePath) {
32973
33096
  if (!existsSync29(filePath))
32974
33097
  return { entries: [], corrupt: 0 };
32975
- const content = await readFile17(filePath, "utf-8");
33098
+ const content = await readFile16(filePath, "utf-8");
32976
33099
  const entries = [];
32977
33100
  let corrupt = 0;
32978
33101
  for (const line of content.split(`
@@ -33244,7 +33367,7 @@ async function computeCurationDiagnostics(directory, entries) {
33244
33367
  let scanCompleted = false;
33245
33368
  let scanRemaining = 0;
33246
33369
  try {
33247
- const { getScanStatus } = await import("./scan-cursor-rc8q12ss.js");
33370
+ const { getScanStatus } = await import("./scan-cursor-j8ytdpam.js");
33248
33371
  const status = await getScanStatus(directory);
33249
33372
  scanGeneration = status.generation;
33250
33373
  scanCompleted = status.completed;
@@ -33252,19 +33375,19 @@ async function computeCurationDiagnostics(directory, entries) {
33252
33375
  } catch {}
33253
33376
  let configMatch = null;
33254
33377
  try {
33255
- const { isLinked: isLinked2 } = await import("./knowledge-link-q46k9adx.js");
33378
+ const { isLinked: isLinked2 } = await import("./knowledge-link-axx45d1h.js");
33256
33379
  if (isLinked2(directory)) {
33257
- const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-n9eaxp3a.js");
33380
+ const { KnowledgeConfigSchema: KnowledgeConfigSchema2 } = await import("./schema-6xfqtpvn.js");
33258
33381
  let config;
33259
33382
  try {
33260
- const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-j1xmren9.js");
33383
+ const { loadPluginConfigWithMeta: loadPluginConfigWithMeta2 } = await import("./index-hfwzxh3j.js");
33261
33384
  const loaded = loadPluginConfigWithMeta2(directory);
33262
33385
  config = KnowledgeConfigSchema2.parse(loaded.config.knowledge ?? {});
33263
33386
  } catch {
33264
33387
  config = KnowledgeConfigSchema2.parse({});
33265
33388
  }
33266
33389
  const { cohortConfigFingerprint: cohortConfigFingerprint2 } = await import("./config-fingerprint-v22xh5a2.js");
33267
- const { buildConfigFingerprintInput: buildConfigFingerprintInput2, readCohortConfigFingerprint } = await import("./curation-policy-d52h4g8t.js");
33390
+ const { buildConfigFingerprintInput: buildConfigFingerprintInput2, readCohortConfigFingerprint } = await import("./curation-policy-9291bdat.js");
33268
33391
  const currentFp = cohortConfigFingerprint2(buildConfigFingerprintInput2(config));
33269
33392
  const cohortFp = await readCohortConfigFingerprint(directory);
33270
33393
  configMatch = cohortFp === null ? null : currentFp === cohortFp;
@@ -33299,7 +33422,7 @@ async function countPendingProposals(directory) {
33299
33422
  if (!existsSync29(proposalsPath))
33300
33423
  return 0;
33301
33424
  try {
33302
- const content = await readFile17(proposalsPath, "utf-8");
33425
+ const content = await readFile16(proposalsPath, "utf-8");
33303
33426
  let n = 0;
33304
33427
  for (const line of content.split(`
33305
33428
  `)) {
@@ -33321,7 +33444,7 @@ async function safeJsonlCount(filePath) {
33321
33444
  if (!filePath || !existsSync29(filePath))
33322
33445
  return 0;
33323
33446
  try {
33324
- const content = await readFile17(filePath, "utf-8");
33447
+ const content = await readFile16(filePath, "utf-8");
33325
33448
  let n = 0;
33326
33449
  for (const line of content.split(`
33327
33450
  `)) {
@@ -33426,7 +33549,7 @@ function resolveCachePackageRoot(cachePath) {
33426
33549
  const nestedPackageRoot = path55.join(cachePath, "node_modules", "opencode-swarm");
33427
33550
  return existsSync30(nestedPackageRoot) ? nestedPackageRoot : cachePath;
33428
33551
  }
33429
- var _internals46 = {
33552
+ var _internals47 = {
33430
33553
  detectSandboxCapability: () => sandboxCapabilityProbe.detect(),
33431
33554
  getSandboxExecutor: getExecutor
33432
33555
  };
@@ -34010,9 +34133,9 @@ async function checkCurator(directory) {
34010
34133
  }
34011
34134
  async function getSandboxStatus() {
34012
34135
  try {
34013
- const capability = await _internals46.detectSandboxCapability();
34136
+ const capability = await _internals47.detectSandboxCapability();
34014
34137
  const mechanism = capability.mechanism ?? "none";
34015
- const executor = await _internals46.getSandboxExecutor();
34138
+ const executor = await _internals47.getSandboxExecutor();
34016
34139
  const hasExecutor = executor !== null;
34017
34140
  if (hasExecutor) {
34018
34141
  const executorStrength = executor?.strength;
@@ -34475,7 +34598,7 @@ async function handleDoctorCommand(directory, args) {
34475
34598
  const result = runConfigDoctor(config, directory);
34476
34599
  let output;
34477
34600
  if (enableAutoFix && result.hasAutoFixableIssues) {
34478
- const { runConfigDoctorWithFixes } = await import("./config-doctor-fnmfd35x.js");
34601
+ const { runConfigDoctorWithFixes } = await import("./config-doctor-qqe6172n.js");
34479
34602
  const fixResult = await runConfigDoctorWithFixes(directory, config, true, {
34480
34603
  applyLossy: true
34481
34604
  });
@@ -34820,7 +34943,7 @@ function readPromotionEvidence(directory) {
34820
34943
  }
34821
34944
 
34822
34945
  // src/commands/epic.ts
34823
- var _internals47 = {
34946
+ var _internals48 = {
34824
34947
  loadPluginConfigWithMeta,
34825
34948
  loadPlanJsonOnly,
34826
34949
  getCoChangeData,
@@ -34842,7 +34965,7 @@ async function handleEpicCommand(directory, args, sessionID) {
34842
34965
  if (!sessionID || sessionID.trim() === "") {
34843
34966
  return "Error: No active session context. Epic Mode requires an active session. Use /swarm epic from within an OpenCode session.";
34844
34967
  }
34845
- const session = _internals47.ensureAgentSession(sessionID, undefined, directory);
34968
+ const session = _internals48.ensureAgentSession(sessionID, undefined, directory);
34846
34969
  const arg0 = args[0]?.toLowerCase();
34847
34970
  switch (arg0) {
34848
34971
  case "status":
@@ -34869,7 +34992,7 @@ Usage:
34869
34992
  }
34870
34993
  function enableAndAck(directory, sessionID, session) {
34871
34994
  try {
34872
- _internals47.enableEpicMode(directory, sessionID);
34995
+ _internals48.enableEpicMode(directory, sessionID);
34873
34996
  } catch (err) {
34874
34997
  return `Error enabling Epic Mode: ${err instanceof Error ? err.message : String(err)}`;
34875
34998
  }
@@ -34885,7 +35008,7 @@ function enableAndAck(directory, sessionID, session) {
34885
35008
  }
34886
35009
  function disableAndAck(directory, sessionID, session) {
34887
35010
  try {
34888
- _internals47.disableEpicMode(directory, sessionID);
35011
+ _internals48.disableEpicMode(directory, sessionID);
34889
35012
  } catch (err) {
34890
35013
  return `Error disabling Epic Mode: ${err instanceof Error ? err.message : String(err)}`;
34891
35014
  }
@@ -34894,12 +35017,12 @@ function disableAndAck(directory, sessionID, session) {
34894
35017
  }
34895
35018
  function renderStatus(directory, sessionID) {
34896
35019
  const lines = ["## Epic Mode \u2014 Status", ""];
34897
- if (_internals47.isStateUnreadable(directory)) {
35020
+ if (_internals48.isStateUnreadable(directory)) {
34898
35021
  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.");
34899
35022
  return lines.join(`
34900
35023
  `);
34901
35024
  }
34902
- const state = _internals47.loadEpicSessionState(directory, sessionID);
35025
+ const state = _internals48.loadEpicSessionState(directory, sessionID);
34903
35026
  if (!state) {
34904
35027
  lines.push("Epic Mode has not been toggled for this session.");
34905
35028
  return lines.join(`
@@ -34951,7 +35074,7 @@ function formatGreenfieldDetail(input) {
34951
35074
  function renderLast(directory) {
34952
35075
  let records;
34953
35076
  try {
34954
- records = _internals47.readPromotionEvidence(directory);
35077
+ records = _internals48.readPromotionEvidence(directory);
34955
35078
  } catch (err) {
34956
35079
  return `Error reading epic-promotions.jsonl: ${err instanceof Error ? err.message : String(err)}`;
34957
35080
  }
@@ -35006,7 +35129,7 @@ function renderLast(directory) {
35006
35129
  `);
35007
35130
  }
35008
35131
  function renderCalibration(directory) {
35009
- if (_internals47.isCalibrationStateUnreadable(directory)) {
35132
+ if (_internals48.isCalibrationStateUnreadable(directory)) {
35010
35133
  return [
35011
35134
  "## Epic Mode \u2014 Calibration",
35012
35135
  "",
@@ -35018,11 +35141,11 @@ function renderCalibration(directory) {
35018
35141
  }
35019
35142
  let state;
35020
35143
  try {
35021
- state = _internals47.loadCalibrationState(directory);
35144
+ state = _internals48.loadCalibrationState(directory);
35022
35145
  } catch (err) {
35023
35146
  return `Error reading calibration state: ${err instanceof Error ? err.message : String(err)}`;
35024
35147
  }
35025
- const { config } = _internals47.loadPluginConfigWithMeta(directory);
35148
+ const { config } = _internals48.loadPluginConfigWithMeta(directory);
35026
35149
  const staticThreshold = config.turbo?.epic?.mode?.activation_threshold ?? 0.3;
35027
35150
  const calibrationCfg = config.turbo?.epic?.calibration;
35028
35151
  const loosenWindow = calibrationCfg?.loosen_window ?? 10;
@@ -35070,7 +35193,7 @@ function renderCalibration(directory) {
35070
35193
  lines.push("");
35071
35194
  let recentDivergent = [];
35072
35195
  try {
35073
- const all = _internals47.readDivergenceHistory(directory, { limit: 50 });
35196
+ const all = _internals48.readDivergenceHistory(directory, { limit: 50 });
35074
35197
  recentDivergent = all.filter((r) => !r.isClean).slice(-5);
35075
35198
  } catch {}
35076
35199
  lines.push("### Recent divergent tasks (tightened the threshold)");
@@ -35087,11 +35210,11 @@ function renderCalibration(directory) {
35087
35210
  `);
35088
35211
  }
35089
35212
  async function renderDecide(directory) {
35090
- const plan = await _internals47.loadPlanJsonOnly(directory);
35213
+ const plan = await _internals48.loadPlanJsonOnly(directory);
35091
35214
  if (!plan) {
35092
35215
  return "No plan found at `.swarm/plan.json`. Run `/swarm plan` first.";
35093
35216
  }
35094
- const { config } = _internals47.loadPluginConfigWithMeta(directory);
35217
+ const { config } = _internals48.loadPluginConfigWithMeta(directory);
35095
35218
  const modeCfg = config.turbo?.epic?.mode;
35096
35219
  const cochangeCfg = config.turbo?.epic?.cochange;
35097
35220
  const activationThreshold = modeCfg?.activation_threshold ?? 0.3;
@@ -35101,20 +35224,20 @@ async function renderDecide(directory) {
35101
35224
  const tasks = [];
35102
35225
  for (const phase of plan.phases) {
35103
35226
  for (const task of phase.tasks) {
35104
- const scopeFiles = _internals47.readTaskScopes(directory, task.id);
35227
+ const scopeFiles = _internals48.readTaskScopes(directory, task.id);
35105
35228
  const scope = scopeFiles ?? task.files_touched ?? [];
35106
35229
  tasks.push({ id: task.id, scope });
35107
35230
  }
35108
35231
  }
35109
- const { pairs, commitsObserved } = await _internals47.getCoChangeData(directory);
35232
+ const { pairs, commitsObserved } = await _internals48.getCoChangeData(directory);
35110
35233
  const isGitProject = (() => {
35111
35234
  try {
35112
- return _internals47.isGitRepo(directory);
35235
+ return _internals48.isGitRepo(directory);
35113
35236
  } catch {
35114
35237
  return false;
35115
35238
  }
35116
35239
  })();
35117
- const verdict = _internals47.decideEpicActivation(tasks, pairs, commitsObserved, {
35240
+ const verdict = _internals48.decideEpicActivation(tasks, pairs, commitsObserved, {
35118
35241
  activationThreshold,
35119
35242
  minCommitsForSignal,
35120
35243
  cochangeNpmiThreshold,
@@ -35158,7 +35281,7 @@ function formatVerdict(verdict) {
35158
35281
  }
35159
35282
 
35160
35283
  // src/services/evidence-service.ts
35161
- var _internals48 = {
35284
+ var _internals49 = {
35162
35285
  loadEvidence,
35163
35286
  listEvidenceTaskIds
35164
35287
  };
@@ -35203,7 +35326,7 @@ function getVerdictEmoji(verdict) {
35203
35326
  return getVerdictIcon(verdict);
35204
35327
  }
35205
35328
  async function getTaskEvidenceData(directory, taskId) {
35206
- const result = await _internals48.loadEvidence(directory, taskId);
35329
+ const result = await _internals49.loadEvidence(directory, taskId);
35207
35330
  if (result.status !== "found") {
35208
35331
  return {
35209
35332
  hasEvidence: false,
@@ -35226,13 +35349,13 @@ async function getTaskEvidenceData(directory, taskId) {
35226
35349
  };
35227
35350
  }
35228
35351
  async function getEvidenceListData(directory) {
35229
- const taskIds = await _internals48.listEvidenceTaskIds(directory);
35352
+ const taskIds = await _internals49.listEvidenceTaskIds(directory);
35230
35353
  if (taskIds.length === 0) {
35231
35354
  return { hasEvidence: false, tasks: [] };
35232
35355
  }
35233
35356
  const tasks = [];
35234
35357
  for (const taskId of taskIds) {
35235
- const result = await _internals48.loadEvidence(directory, taskId);
35358
+ const result = await _internals49.loadEvidence(directory, taskId);
35236
35359
  if (result.status === "found") {
35237
35360
  tasks.push({
35238
35361
  taskId,
@@ -35312,7 +35435,7 @@ async function handleEvidenceCommand(directory, args) {
35312
35435
  return formatTaskEvidenceMarkdown(evidenceData);
35313
35436
  }
35314
35437
  async function handleEvidenceSummaryCommand(directory) {
35315
- const { buildEvidenceSummary } = await import("./evidence-summary-service-nfdc1ht9.js");
35438
+ const { buildEvidenceSummary } = await import("./evidence-summary-service-em58myd7.js");
35316
35439
  const artifact = await buildEvidenceSummary(directory);
35317
35440
  if (!artifact) {
35318
35441
  return "No plan found. Run `/swarm plan` to check plan status.";
@@ -35668,7 +35791,7 @@ function isStaticallyEquivalent(originalCode, mutatedCode) {
35668
35791
  const strippedMutated = stripCode(mutatedCode);
35669
35792
  return strippedOriginal === strippedMutated;
35670
35793
  }
35671
- var _internals49 = {
35794
+ var _internals50 = {
35672
35795
  isStaticallyEquivalent,
35673
35796
  checkEquivalence,
35674
35797
  batchCheckEquivalence
@@ -35708,7 +35831,7 @@ async function batchCheckEquivalence(patches, llmJudge) {
35708
35831
  const results = [];
35709
35832
  for (const { patch, originalCode, mutatedCode } of patches) {
35710
35833
  try {
35711
- const result = await _internals49.checkEquivalence(patch, originalCode, mutatedCode, llmJudge);
35834
+ const result = await _internals50.checkEquivalence(patch, originalCode, mutatedCode, llmJudge);
35712
35835
  results.push(result);
35713
35836
  } catch (err) {
35714
35837
  results.push({
@@ -35782,10 +35905,10 @@ function isMissingExecutableFailure(message) {
35782
35905
  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);
35783
35906
  }
35784
35907
  var runMutationCommand = async (args) => {
35785
- const resolvedExecutable = _internals50.resolveExecutableFromPath([
35908
+ const resolvedExecutable = _internals51.resolveExecutableFromPath([
35786
35909
  args.executable
35787
35910
  ]);
35788
- const result = await _internals50.runExternalTool({
35911
+ const result = await _internals51.runExternalTool({
35789
35912
  executable: resolvedExecutable ?? args.executable,
35790
35913
  args: args.args,
35791
35914
  cwd: args.cwd,
@@ -35804,7 +35927,7 @@ var runMutationCommand = async (args) => {
35804
35927
  };
35805
35928
  var runLegacyTestSeam = async (args) => {
35806
35929
  try {
35807
- const result = _internals50.spawnSync(args.executable, args.args, {
35930
+ const result = _internals51.spawnSync(args.executable, args.args, {
35808
35931
  cwd: args.cwd,
35809
35932
  timeout: args.timeoutMs,
35810
35933
  stdio: "pipe"
@@ -35838,11 +35961,11 @@ var runLegacyTestSeam = async (args) => {
35838
35961
  function selectRunner(options) {
35839
35962
  if (options.runner)
35840
35963
  return options.runner;
35841
- if (_internals50.spawnSync !== defaultLegacySpawnSync)
35964
+ if (_internals51.spawnSync !== defaultLegacySpawnSync)
35842
35965
  return runLegacyTestSeam;
35843
- return _internals50.runCommand;
35966
+ return _internals51.runCommand;
35844
35967
  }
35845
- var _internals50 = {
35968
+ var _internals51 = {
35846
35969
  executeMutation,
35847
35970
  computeReport,
35848
35971
  executeMutationSuite,
@@ -37029,7 +37152,7 @@ async function qualityBudget(input, directory, abortSignal) {
37029
37152
  }
37030
37153
  };
37031
37154
  }
37032
- const metrics = await _internals51.computeQualityMetrics(changedFiles, thresholds, directory);
37155
+ const metrics = await _internals52.computeQualityMetrics(changedFiles, thresholds, directory);
37033
37156
  abortSignal?.throwIfAborted();
37034
37157
  const errorsCount = metrics.violations.filter((v) => v.severity === "error").length;
37035
37158
  const warningsCount = metrics.violations.filter((v) => v.severity === "warning").length;
@@ -37090,11 +37213,11 @@ var quality_budget = createSwarmTool({
37090
37213
  }).optional().describe("Quality budget thresholds")
37091
37214
  },
37092
37215
  async execute(args, directory, ctx) {
37093
- const result = await _internals51.qualityBudget(args, directory, ctx?.abort);
37216
+ const result = await _internals52.qualityBudget(args, directory, ctx?.abort);
37094
37217
  return JSON.stringify(result);
37095
37218
  }
37096
37219
  });
37097
- var _internals51 = {
37220
+ var _internals52 = {
37098
37221
  qualityBudget,
37099
37222
  computeQualityMetrics
37100
37223
  };
@@ -37967,7 +38090,7 @@ var SEMGREP_AVAILABILITY_MAX_STDOUT_BYTES = 16 * 1024;
37967
38090
  var SEMGREP_AVAILABILITY_MAX_STDERR_BYTES = 16 * 1024;
37968
38091
  var MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
37969
38092
  function resolveSemgrepBinary() {
37970
- return _internals52.resolveExecutableFromPath(process.platform === "win32" ? ["semgrep.exe"] : ["semgrep"]);
38093
+ return _internals53.resolveExecutableFromPath(process.platform === "win32" ? ["semgrep.exe"] : ["semgrep"]);
37971
38094
  }
37972
38095
  function getAvailabilityProbeCwd() {
37973
38096
  try {
@@ -37978,7 +38101,7 @@ function getAvailabilityProbeCwd() {
37978
38101
  }
37979
38102
  async function runSemgrepAvailabilityProbe(executable, cwd, generation) {
37980
38103
  try {
37981
- const run = await _internals52.runExternalTool({
38104
+ const run = await _internals53.runExternalTool({
37982
38105
  executable,
37983
38106
  args: ["--version"],
37984
38107
  cwd,
@@ -38000,14 +38123,14 @@ async function waitForAvailabilityProbe(probe, abortSignal) {
38000
38123
  return probe;
38001
38124
  if (abortSignal.aborted)
38002
38125
  return false;
38003
- return new Promise((resolve17) => {
38126
+ return new Promise((resolve18) => {
38004
38127
  let settled = false;
38005
38128
  const finish = (available) => {
38006
38129
  if (settled)
38007
38130
  return;
38008
38131
  settled = true;
38009
38132
  abortSignal.removeEventListener("abort", onAbort);
38010
- resolve17(available);
38133
+ resolve18(available);
38011
38134
  };
38012
38135
  const onAbort = () => finish(false);
38013
38136
  abortSignal.addEventListener("abort", onAbort, { once: true });
@@ -38024,7 +38147,7 @@ function describeExternalToolFailure(status) {
38024
38147
  return "Semgrep process failed to start or terminate safely";
38025
38148
  }
38026
38149
  }
38027
- var _internals52 = {
38150
+ var _internals53 = {
38028
38151
  isSemgrepAvailable,
38029
38152
  checkSemgrepAvailable,
38030
38153
  resetSemgrepCache,
@@ -38040,7 +38163,7 @@ function isSemgrepAvailable() {
38040
38163
  if (semgrepAvailableCache !== null) {
38041
38164
  return semgrepAvailableCache;
38042
38165
  }
38043
- return _internals52.resolveSemgrepBinary() !== null;
38166
+ return _internals53.resolveSemgrepBinary() !== null;
38044
38167
  }
38045
38168
  async function checkSemgrepAvailable(cwd, abortSignal) {
38046
38169
  if (abortSignal?.aborted)
@@ -38048,14 +38171,14 @@ async function checkSemgrepAvailable(cwd, abortSignal) {
38048
38171
  if (semgrepAvailableCache !== null) {
38049
38172
  return semgrepAvailableCache;
38050
38173
  }
38051
- const executable = _internals52.resolveSemgrepBinary();
38174
+ const executable = _internals53.resolveSemgrepBinary();
38052
38175
  if (!executable) {
38053
38176
  semgrepAvailableCache = false;
38054
38177
  return false;
38055
38178
  }
38056
38179
  if (!semgrepAvailabilityProbe) {
38057
38180
  const generation = semgrepAvailabilityGeneration;
38058
- const probe = runSemgrepAvailabilityProbe(executable, cwd ?? _internals52.getAvailabilityProbeCwd(), generation);
38181
+ const probe = runSemgrepAvailabilityProbe(executable, cwd ?? _internals53.getAvailabilityProbeCwd(), generation);
38059
38182
  semgrepAvailabilityProbe = probe;
38060
38183
  probe.then(() => {
38061
38184
  if (semgrepAvailabilityProbe === probe) {
@@ -38164,12 +38287,12 @@ async function runSemgrep(options) {
38164
38287
  const timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS2;
38165
38288
  if (files.length === 0) {
38166
38289
  return {
38167
- available: _internals52.isSemgrepAvailable(),
38290
+ available: _internals53.isSemgrepAvailable(),
38168
38291
  findings: [],
38169
38292
  engine: "tier_a"
38170
38293
  };
38171
38294
  }
38172
- if (!await _internals52.checkSemgrepAvailable(options.cwd, options.abortSignal)) {
38295
+ if (!await _internals53.checkSemgrepAvailable(options.cwd, options.abortSignal)) {
38173
38296
  if (options.abortSignal?.aborted) {
38174
38297
  return {
38175
38298
  available: true,
@@ -38185,7 +38308,7 @@ async function runSemgrep(options) {
38185
38308
  engine: "tier_a"
38186
38309
  };
38187
38310
  }
38188
- const executable = _internals52.resolveSemgrepBinary();
38311
+ const executable = _internals53.resolveSemgrepBinary();
38189
38312
  if (!executable) {
38190
38313
  return {
38191
38314
  available: false,
@@ -38204,10 +38327,10 @@ async function runSemgrep(options) {
38204
38327
  }
38205
38328
  args.push(...files);
38206
38329
  try {
38207
- const result = await _internals52.runExternalTool({
38330
+ const result = await _internals53.runExternalTool({
38208
38331
  executable,
38209
38332
  args,
38210
- cwd: options.cwd ?? _internals52.getAvailabilityProbeCwd(),
38333
+ cwd: options.cwd ?? _internals53.getAvailabilityProbeCwd(),
38211
38334
  timeoutMs,
38212
38335
  maxStdoutBytes: MAX_OUTPUT_BYTES,
38213
38336
  maxStderrBytes: MAX_OUTPUT_BYTES,
@@ -38361,7 +38484,7 @@ function assignOccurrenceIndices(findings, directory) {
38361
38484
  }
38362
38485
  const occIdx = countMap.get(baseKey) ?? 0;
38363
38486
  countMap.set(baseKey, occIdx + 1);
38364
- const fp = _internals53.fingerprintFinding(finding, directory, occIdx);
38487
+ const fp = _internals54.fingerprintFinding(finding, directory, occIdx);
38365
38488
  return {
38366
38489
  finding,
38367
38490
  index: occIdx,
@@ -38373,7 +38496,7 @@ function assignOccurrenceIndices(findings, directory) {
38373
38496
  async function waitForLockRetry(delayMs, abortSignal) {
38374
38497
  if (abortSignal?.aborted)
38375
38498
  return false;
38376
- return await new Promise((resolve18) => {
38499
+ return await new Promise((resolve19) => {
38377
38500
  let settled = false;
38378
38501
  const finish = (value) => {
38379
38502
  if (settled)
@@ -38381,7 +38504,7 @@ async function waitForLockRetry(delayMs, abortSignal) {
38381
38504
  settled = true;
38382
38505
  clearTimeout(timeout);
38383
38506
  abortSignal?.removeEventListener("abort", onAbort);
38384
- resolve18(value);
38507
+ resolve19(value);
38385
38508
  };
38386
38509
  const onAbort = () => finish(false);
38387
38510
  const timeout = setTimeout(() => finish(true), delayMs);
@@ -38465,7 +38588,7 @@ async function captureOrMergeBaseline(directory, phase, findings, engine, scanne
38465
38588
  }
38466
38589
  } catch {}
38467
38590
  const scannedRelFiles = new Set(scannedFiles.map((f) => normalizeFindingPath(directory, f)));
38468
- const indexed = _internals53.assignOccurrenceIndices(findings, directory);
38591
+ const indexed = _internals54.assignOccurrenceIndices(findings, directory);
38469
38592
  if (existing && !opts?.force) {
38470
38593
  const prunedFingerprints = existing.fingerprints.filter((fp) => {
38471
38594
  const relFile = fp.slice(0, fp.indexOf("|"));
@@ -38621,7 +38744,7 @@ function loadBaseline(directory, phase) {
38621
38744
  };
38622
38745
  }
38623
38746
  }
38624
- var _internals53 = {
38747
+ var _internals54 = {
38625
38748
  fingerprintFinding,
38626
38749
  assignOccurrenceIndices,
38627
38750
  captureOrMergeBaseline,
@@ -38769,7 +38892,7 @@ async function sastScan(input, directory, config) {
38769
38892
  if (abort_signal?.aborted) {
38770
38893
  return cancelledScanResult(allFindings, filesScanned);
38771
38894
  }
38772
- const semgrepAvailable = !offline_only && await _internals54.checkSemgrepAvailable(directory, abort_signal);
38895
+ const semgrepAvailable = !offline_only && await _internals55.checkSemgrepAvailable(directory, abort_signal);
38773
38896
  const engine = semgrepAvailable ? "tier_a+tier_b" : "tier_a";
38774
38897
  const filesByLanguage = new Map;
38775
38898
  let semgrepError = abort_signal?.aborted ? "SAST scan cancelled" : undefined;
@@ -38840,7 +38963,7 @@ async function sastScan(input, directory, config) {
38840
38963
  let semgrepResult;
38841
38964
  if (bucketKey.startsWith("auto:")) {
38842
38965
  const lang = bucketKey.slice("auto:".length);
38843
- semgrepResult = await _internals54.runSemgrep({
38966
+ semgrepResult = await _internals55.runSemgrep({
38844
38967
  files: bucketFiles,
38845
38968
  lang,
38846
38969
  useAutoConfig: true,
@@ -38848,7 +38971,7 @@ async function sastScan(input, directory, config) {
38848
38971
  abortSignal: abort_signal
38849
38972
  });
38850
38973
  } else {
38851
- semgrepResult = await _internals54.runSemgrep({
38974
+ semgrepResult = await _internals55.runSemgrep({
38852
38975
  files: bucketFiles,
38853
38976
  cwd: directory,
38854
38977
  abortSignal: abort_signal
@@ -39139,11 +39262,11 @@ var sast_scan = createSwarmTool({
39139
39262
  phase: safeArgs.phase,
39140
39263
  abort_signal: ctx?.abort
39141
39264
  };
39142
- const result = await _internals54.sastScan(input, directory);
39265
+ const result = await _internals55.sastScan(input, directory);
39143
39266
  return JSON.stringify(result, null, 2);
39144
39267
  }
39145
39268
  });
39146
- var _internals54 = {
39269
+ var _internals55 = {
39147
39270
  sastScan,
39148
39271
  sast_scan,
39149
39272
  checkSemgrepAvailable: (directory, abortSignal) => checkSemgrepAvailable(directory, abortSignal),
@@ -39975,7 +40098,7 @@ function extractCurrentPhaseFromPlan2(plan) {
39975
40098
  if (!plan) {
39976
40099
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
39977
40100
  }
39978
- if (!_internals55.validatePlanPhases(plan)) {
40101
+ if (!_internals56.validatePlanPhases(plan)) {
39979
40102
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
39980
40103
  }
39981
40104
  let currentPhase = null;
@@ -40117,9 +40240,9 @@ function extractPhaseMetrics(content) {
40117
40240
  async function getHandoffData(directory) {
40118
40241
  const now = new Date().toISOString();
40119
40242
  const sessionContent = await readSwarmFileAsync(directory, "session/state.json");
40120
- const sessionState = _internals55.parseSessionState(sessionContent);
40243
+ const sessionState = _internals56.parseSessionState(sessionContent);
40121
40244
  const plan = await loadPlanJsonOnly(directory);
40122
- const planInfo = _internals55.extractCurrentPhaseFromPlan(plan);
40245
+ const planInfo = _internals56.extractCurrentPhaseFromPlan(plan);
40123
40246
  if (!plan) {
40124
40247
  const planMdContent = await readSwarmFileAsync(directory, "plan.md");
40125
40248
  if (planMdContent) {
@@ -40138,8 +40261,8 @@ async function getHandoffData(directory) {
40138
40261
  }
40139
40262
  }
40140
40263
  const contextContent = await readSwarmFileAsync(directory, "context.md");
40141
- const recentDecisions = _internals55.extractDecisions(contextContent);
40142
- const rawPhaseMetrics = _internals55.extractPhaseMetrics(contextContent);
40264
+ const recentDecisions = _internals56.extractDecisions(contextContent);
40265
+ const rawPhaseMetrics = _internals56.extractPhaseMetrics(contextContent);
40143
40266
  const phaseMetrics = sanitizeString2(rawPhaseMetrics, 1000);
40144
40267
  let delegationState = null;
40145
40268
  if (sessionState?.delegationState) {
@@ -40305,7 +40428,7 @@ ${lines.join(`
40305
40428
  `)}
40306
40429
  \`\`\``;
40307
40430
  }
40308
- var _internals55 = {
40431
+ var _internals56 = {
40309
40432
  getHandoffData,
40310
40433
  formatHandoffMarkdown,
40311
40434
  formatContinuationPrompt,
@@ -40473,15 +40596,15 @@ async function writeSnapshot(directory, state) {
40473
40596
  }
40474
40597
  function createSnapshotWriterHook(directory) {
40475
40598
  return (_input, _output) => {
40476
- _writeInFlight = _writeInFlight.then(() => _internals56.writeSnapshot(directory, swarmState), () => _internals56.writeSnapshot(directory, swarmState));
40599
+ _writeInFlight = _writeInFlight.then(() => _internals57.writeSnapshot(directory, swarmState), () => _internals57.writeSnapshot(directory, swarmState));
40477
40600
  return _writeInFlight;
40478
40601
  };
40479
40602
  }
40480
40603
  async function flushPendingSnapshot(directory) {
40481
- _writeInFlight = _writeInFlight.then(() => _internals56.writeSnapshot(directory, swarmState), () => _internals56.writeSnapshot(directory, swarmState));
40604
+ _writeInFlight = _writeInFlight.then(() => _internals57.writeSnapshot(directory, swarmState), () => _internals57.writeSnapshot(directory, swarmState));
40482
40605
  await _writeInFlight;
40483
40606
  }
40484
- var _internals56 = {
40607
+ var _internals57 = {
40485
40608
  writeSnapshot,
40486
40609
  createSnapshotWriterHook,
40487
40610
  flushPendingSnapshot
@@ -40767,7 +40890,7 @@ function parseIssueRef(input, directory) {
40767
40890
  }
40768
40891
  return null;
40769
40892
  }
40770
- var _internals57 = {
40893
+ var _internals58 = {
40771
40894
  writeFileSync: fs29.writeFileSync,
40772
40895
  mkdirSync: fs29.mkdirSync,
40773
40896
  renameSync: fs29.renameSync,
@@ -40778,18 +40901,18 @@ var _internals57 = {
40778
40901
  function atomicWriteFileSync(dir, filename, content) {
40779
40902
  const tmpPath = path68.join(dir, `.tmp-${filename}-${Date.now()}-${process.pid}`);
40780
40903
  const finalPath = path68.join(dir, filename);
40781
- _internals57.writeFileSync(tmpPath, content, "utf-8");
40904
+ _internals58.writeFileSync(tmpPath, content, "utf-8");
40782
40905
  try {
40783
- _internals57.renameSync(tmpPath, finalPath);
40906
+ _internals58.renameSync(tmpPath, finalPath);
40784
40907
  } catch {
40785
40908
  try {
40786
- _internals57.unlinkSync(finalPath);
40909
+ _internals58.unlinkSync(finalPath);
40787
40910
  } catch {}
40788
40911
  try {
40789
- _internals57.renameSync(tmpPath, finalPath);
40912
+ _internals58.renameSync(tmpPath, finalPath);
40790
40913
  } catch (retryErr) {
40791
40914
  try {
40792
- _internals57.unlinkSync(tmpPath);
40915
+ _internals58.unlinkSync(tmpPath);
40793
40916
  } catch {}
40794
40917
  throw retryErr;
40795
40918
  }
@@ -40849,10 +40972,10 @@ ${USAGE9}`;
40849
40972
  };
40850
40973
  let oldTraceState = null;
40851
40974
  try {
40852
- oldTraceState = _internals57.readFileSync(path68.join(swarmDir, "issue-trace-state.json"), "utf-8");
40975
+ oldTraceState = _internals58.readFileSync(path68.join(swarmDir, "issue-trace-state.json"), "utf-8");
40853
40976
  } catch {}
40854
40977
  try {
40855
- _internals57.mkdirSync(swarmDir, { recursive: true });
40978
+ _internals58.mkdirSync(swarmDir, { recursive: true });
40856
40979
  atomicWriteFileSync(swarmDir, "issue-trace-state.json", JSON.stringify(traceState, null, 2));
40857
40980
  atomicWriteFileSync(swarmDir, "issue-reference.json", JSON.stringify(issueReference, null, 2));
40858
40981
  } catch (e) {
@@ -40862,11 +40985,11 @@ ${USAGE9}`;
40862
40985
  } catch {}
40863
40986
  } else {
40864
40987
  try {
40865
- _internals57.unlinkSync(path68.join(swarmDir, "issue-trace-state.json"));
40988
+ _internals58.unlinkSync(path68.join(swarmDir, "issue-trace-state.json"));
40866
40989
  } catch {}
40867
40990
  }
40868
40991
  try {
40869
- _internals57.unlinkSync(path68.join(swarmDir, "issue-reference.json"));
40992
+ _internals58.unlinkSync(path68.join(swarmDir, "issue-reference.json"));
40870
40993
  } catch {}
40871
40994
  const errMsg = e instanceof Error ? e.message : String(e);
40872
40995
  return `Error: Failed to persist issue reference durably: ${errMsg}
@@ -40892,14 +41015,14 @@ init_schema();
40892
41015
  init_logger();
40893
41016
  import { randomUUID as randomUUID8 } from "crypto";
40894
41017
  import { existsSync as existsSync38, readFileSync as readFileSync30 } from "fs";
40895
- import { mkdir as mkdir15, readFile as readFile18, writeFile as writeFile13 } from "fs/promises";
41018
+ import { mkdir as mkdir14, readFile as readFile17, writeFile as writeFile12 } from "fs/promises";
40896
41019
  import * as os8 from "os";
40897
41020
  import * as path69 from "path";
40898
41021
  init_knowledge_types();
40899
41022
  async function migrateKnowledgeToExternal(_directory, _config) {
40900
41023
  const externalSentinelPath = path69.join(_directory, ".swarm", ".knowledge-external-migrated");
40901
41024
  const contextPath = path69.join(_directory, ".swarm", "context.md");
40902
- if (_internals58.existsSync(externalSentinelPath)) {
41025
+ if (_internals59.existsSync(externalSentinelPath)) {
40903
41026
  return {
40904
41027
  migrated: false,
40905
41028
  entriesMigrated: 0,
@@ -40908,7 +41031,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
40908
41031
  skippedReason: "external-sentinel-exists"
40909
41032
  };
40910
41033
  }
40911
- if (!_internals58.existsSync(contextPath)) {
41034
+ if (!_internals59.existsSync(contextPath)) {
40912
41035
  return {
40913
41036
  migrated: false,
40914
41037
  entriesMigrated: 0,
@@ -40917,7 +41040,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
40917
41040
  skippedReason: "no-context-file"
40918
41041
  };
40919
41042
  }
40920
- const contextContent = await _internals58.readFile(contextPath, "utf-8");
41043
+ const contextContent = await _internals59.readFile(contextPath, "utf-8");
40921
41044
  if (contextContent.trim().length === 0) {
40922
41045
  return {
40923
41046
  migrated: false,
@@ -40935,7 +41058,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
40935
41058
  entriesCount++;
40936
41059
  }
40937
41060
  }
40938
- await _internals58.writeSentinel(externalSentinelPath, entriesCount, entriesCount);
41061
+ await _internals59.writeSentinel(externalSentinelPath, entriesCount, entriesCount);
40939
41062
  return {
40940
41063
  migrated: true,
40941
41064
  entriesMigrated: entriesCount,
@@ -40943,7 +41066,7 @@ async function migrateKnowledgeToExternal(_directory, _config) {
40943
41066
  entriesTotal: entriesCount
40944
41067
  };
40945
41068
  }
40946
- var _internals58 = {
41069
+ var _internals59 = {
40947
41070
  appendKnowledge,
40948
41071
  migrateContextToKnowledge,
40949
41072
  migrateKnowledgeToExternal,
@@ -40958,9 +41081,9 @@ var _internals58 = {
40958
41081
  resolveLegacyHiveKnowledgePath,
40959
41082
  existsSync: existsSync38,
40960
41083
  readFileSync: readFileSync30,
40961
- readFile: readFile18,
40962
- mkdir: mkdir15,
40963
- writeFile: writeFile13
41084
+ readFile: readFile17,
41085
+ mkdir: mkdir14,
41086
+ writeFile: writeFile12
40964
41087
  };
40965
41088
  async function migrateContextToKnowledge(directory, config) {
40966
41089
  const sentinelPath = path69.join(directory, ".swarm", ".knowledge-migrated");
@@ -40984,7 +41107,7 @@ async function migrateContextToKnowledge(directory, config) {
40984
41107
  skippedReason: "no-context-file"
40985
41108
  };
40986
41109
  }
40987
- const contextContent = await readFile18(contextPath, "utf-8");
41110
+ const contextContent = await readFile17(contextPath, "utf-8");
40988
41111
  if (contextContent.trim().length === 0) {
40989
41112
  return {
40990
41113
  migrated: false,
@@ -40994,9 +41117,9 @@ async function migrateContextToKnowledge(directory, config) {
40994
41117
  skippedReason: "empty-context"
40995
41118
  };
40996
41119
  }
40997
- const rawEntries = _internals58.parseContextMd(contextContent);
41120
+ const rawEntries = _internals59.parseContextMd(contextContent);
40998
41121
  if (rawEntries.length === 0) {
40999
- await _internals58.writeSentinel(sentinelPath, 0, 0);
41122
+ await _internals59.writeSentinel(sentinelPath, 0, 0);
41000
41123
  return {
41001
41124
  migrated: true,
41002
41125
  entriesMigrated: 0,
@@ -41007,10 +41130,10 @@ async function migrateContextToKnowledge(directory, config) {
41007
41130
  const existing = await readKnowledge(knowledgePath);
41008
41131
  let migrated = 0;
41009
41132
  let dropped = 0;
41010
- const projectName = _internals58.inferProjectName(directory);
41133
+ const projectName = _internals59.inferProjectName(directory);
41011
41134
  for (const raw of rawEntries) {
41012
41135
  if (config.validation_enabled !== false) {
41013
- const category = raw.categoryHint ?? _internals58.inferCategoryFromText(raw.text);
41136
+ const category = raw.categoryHint ?? _internals59.inferCategoryFromText(raw.text);
41014
41137
  const result = validateLesson(raw.text, existing.map((e) => e.lesson), {
41015
41138
  category,
41016
41139
  scope: "global",
@@ -41030,8 +41153,8 @@ async function migrateContextToKnowledge(directory, config) {
41030
41153
  const entry = {
41031
41154
  id: randomUUID8(),
41032
41155
  tier: "swarm",
41033
- lesson: _internals58.truncateLesson(raw.text),
41034
- category: raw.categoryHint ?? _internals58.inferCategoryFromText(raw.text),
41156
+ lesson: _internals59.truncateLesson(raw.text),
41157
+ category: raw.categoryHint ?? _internals59.inferCategoryFromText(raw.text),
41035
41158
  tags: [...inferredTags, `migration:${raw.sourceSection}`],
41036
41159
  scope: "global",
41037
41160
  confidence: 0.3,
@@ -41054,7 +41177,7 @@ async function migrateContextToKnowledge(directory, config) {
41054
41177
  if (migrated > 0) {
41055
41178
  await rewriteKnowledge(knowledgePath, existing);
41056
41179
  }
41057
- await _internals58.writeSentinel(sentinelPath, migrated, dropped);
41180
+ await _internals59.writeSentinel(sentinelPath, migrated, dropped);
41058
41181
  log(`[knowledge-migrator] Migrated ${migrated} entries, dropped ${dropped}`);
41059
41182
  return {
41060
41183
  migrated: true,
@@ -41064,7 +41187,7 @@ async function migrateContextToKnowledge(directory, config) {
41064
41187
  };
41065
41188
  }
41066
41189
  async function migrateHiveKnowledgeLegacy(config) {
41067
- const legacyHivePath = _internals58.resolveLegacyHiveKnowledgePath();
41190
+ const legacyHivePath = _internals59.resolveLegacyHiveKnowledgePath();
41068
41191
  const canonicalHivePath = resolveHiveKnowledgePath2();
41069
41192
  const sentinelPath = path69.join(path69.dirname(canonicalHivePath), ".hive-knowledge-migrated");
41070
41193
  if (existsSync38(sentinelPath)) {
@@ -41087,7 +41210,7 @@ async function migrateHiveKnowledgeLegacy(config) {
41087
41210
  }
41088
41211
  const legacyEntries = await readKnowledge(legacyHivePath);
41089
41212
  if (legacyEntries.length === 0) {
41090
- await _internals58.writeSentinel(sentinelPath, 0, 0);
41213
+ await _internals59.writeSentinel(sentinelPath, 0, 0);
41091
41214
  return {
41092
41215
  migrated: true,
41093
41216
  entriesMigrated: 0,
@@ -41135,7 +41258,7 @@ async function migrateHiveKnowledgeLegacy(config) {
41135
41258
  const newHiveEntry = {
41136
41259
  id: resolvedId,
41137
41260
  tier: "hive",
41138
- lesson: _internals58.truncateLesson(lesson),
41261
+ lesson: _internals59.truncateLesson(lesson),
41139
41262
  category,
41140
41263
  tags: ["migration:legacy-hive"],
41141
41264
  scope: scopeTag,
@@ -41154,7 +41277,7 @@ async function migrateHiveKnowledgeLegacy(config) {
41154
41277
  encounter_score: 1
41155
41278
  };
41156
41279
  try {
41157
- await _internals58.appendKnowledge(canonicalHivePath, newHiveEntry);
41280
+ await _internals59.appendKnowledge(canonicalHivePath, newHiveEntry);
41158
41281
  existingHiveEntries.push(newHiveEntry);
41159
41282
  migrated++;
41160
41283
  } catch (appendError) {
@@ -41170,7 +41293,7 @@ async function migrateHiveKnowledgeLegacy(config) {
41170
41293
  dropped++;
41171
41294
  }
41172
41295
  }
41173
- await _internals58.writeSentinel(sentinelPath, migrated, dropped);
41296
+ await _internals59.writeSentinel(sentinelPath, migrated, dropped);
41174
41297
  log(`[knowledge-migrator] Migrated ${migrated} legacy hive entries, dropped ${dropped}`);
41175
41298
  return {
41176
41299
  migrated: true,
@@ -41181,7 +41304,7 @@ async function migrateHiveKnowledgeLegacy(config) {
41181
41304
  };
41182
41305
  }
41183
41306
  function parseContextMd(content) {
41184
- const sections = _internals58.splitIntoSections(content);
41307
+ const sections = _internals59.splitIntoSections(content);
41185
41308
  const entries = [];
41186
41309
  const seen = new Set;
41187
41310
  const sectionPatterns = [
@@ -41197,7 +41320,7 @@ function parseContextMd(content) {
41197
41320
  const match = sectionPatterns.find((sp) => sp.pattern.test(section.heading));
41198
41321
  if (!match)
41199
41322
  continue;
41200
- const bullets = _internals58.extractBullets(section.body);
41323
+ const bullets = _internals59.extractBullets(section.body);
41201
41324
  for (const bullet of bullets) {
41202
41325
  if (bullet.length < 15)
41203
41326
  continue;
@@ -41206,9 +41329,9 @@ function parseContextMd(content) {
41206
41329
  continue;
41207
41330
  seen.add(normalized);
41208
41331
  entries.push({
41209
- text: _internals58.truncateLesson(bullet),
41332
+ text: _internals59.truncateLesson(bullet),
41210
41333
  sourceSection: match.sourceSection,
41211
- categoryHint: _internals58.inferCategoryFromText(bullet)
41334
+ categoryHint: _internals59.inferCategoryFromText(bullet)
41212
41335
  });
41213
41336
  }
41214
41337
  }
@@ -41298,8 +41421,8 @@ async function writeSentinel(sentinelPath, migrated, dropped) {
41298
41421
  schema_version: 1,
41299
41422
  migration_tool: "knowledge-migrator.ts"
41300
41423
  };
41301
- await _internals58.mkdir(path69.dirname(sentinelPath), { recursive: true });
41302
- await _internals58.writeFile(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
41424
+ await _internals59.mkdir(path69.dirname(sentinelPath), { recursive: true });
41425
+ await _internals59.writeFile(sentinelPath, JSON.stringify(sentinel, null, 2), "utf-8");
41303
41426
  }
41304
41427
  function resolveLegacyHiveKnowledgePath() {
41305
41428
  const platform = process.platform;
@@ -41711,7 +41834,7 @@ function timeoutMessage(timeoutMs) {
41711
41834
  async function computeWithTimeout(directory, currentPhase, timeoutMs) {
41712
41835
  const controller = new AbortController;
41713
41836
  let timeout;
41714
- const metricsPromise = _internals59.computeLearningMetrics(directory, {
41837
+ const metricsPromise = _internals60.computeLearningMetrics(directory, {
41715
41838
  currentPhase,
41716
41839
  signal: controller.signal
41717
41840
  });
@@ -41768,19 +41891,19 @@ ${JSON.stringify({
41768
41891
  return `Error computing learning metrics: ${message}. Run /swarm diagnose to check .swarm/ health.`;
41769
41892
  }
41770
41893
  }
41771
- var _internals59 = {
41894
+ var _internals60 = {
41772
41895
  computeLearningMetrics
41773
41896
  };
41774
41897
 
41775
41898
  // src/commands/link.ts
41776
- import { mkdir as mkdir17, writeFile as writeFile14 } from "fs/promises";
41899
+ import { mkdir as mkdir16, writeFile as writeFile13 } from "fs/promises";
41777
41900
  import * as path71 from "path";
41778
41901
  init_schema();
41779
41902
 
41780
41903
  // src/knowledge/family-migration.ts
41781
41904
  var import_proper_lockfile6 = __toESM(require_proper_lockfile(), 1);
41782
41905
  import { existsSync as existsSync39, readFileSync as readFileSync31 } from "fs";
41783
- import { mkdir as mkdir16 } from "fs/promises";
41906
+ import { mkdir as mkdir15 } from "fs/promises";
41784
41907
  import * as path70 from "path";
41785
41908
 
41786
41909
  // src/knowledge/family-manifest.ts
@@ -42063,7 +42186,7 @@ async function snapshotSourceFamily(storeDir) {
42063
42186
  const snapshot = {};
42064
42187
  let release = null;
42065
42188
  try {
42066
- await mkdir16(storeDir, { recursive: true });
42189
+ await mkdir15(storeDir, { recursive: true });
42067
42190
  } catch {}
42068
42191
  try {
42069
42192
  release = await import_proper_lockfile6.default.lock(storeDir, {
@@ -42082,7 +42205,7 @@ async function snapshotSourceFamily(storeDir) {
42082
42205
  return snapshot;
42083
42206
  }
42084
42207
  async function migrateKnowledgeFamily(destinationDir, sourceDir) {
42085
- await mkdir16(destinationDir, { recursive: true });
42208
+ await mkdir15(destinationDir, { recursive: true });
42086
42209
  let destRelease = null;
42087
42210
  try {
42088
42211
  destRelease = await import_proper_lockfile6.default.lock(destinationDir, {
@@ -42232,8 +42355,8 @@ ${formatStatus(directory)}`;
42232
42355
  const { config: loadedConfig } = loadPluginConfigWithMeta(directory);
42233
42356
  const config = KnowledgeConfigSchema.parse(loadedConfig.knowledge ?? {});
42234
42357
  const fingerprint = cohortConfigFingerprint(buildConfigFingerprintInput(config));
42235
- await mkdir17(linkDir, { recursive: true });
42236
- await writeFile14(path71.join(linkDir, "cohort-config.json"), JSON.stringify({ fingerprint, updated_at: new Date().toISOString() }, null, 2), "utf-8");
42358
+ await mkdir16(linkDir, { recursive: true });
42359
+ await writeFile13(path71.join(linkDir, "cohort-config.json"), JSON.stringify({ fingerprint, updated_at: new Date().toISOString() }, null, 2), "utf-8");
42237
42360
  } catch {}
42238
42361
  const relinkNote = existing ? `
42239
42362
  (Re-linked from previous link "${existing.linkId}".)` : "";
@@ -42289,7 +42412,7 @@ async function readLatestLoopState(directory) {
42289
42412
  return null;
42290
42413
  }
42291
42414
  }
42292
- var _internals60 = {
42415
+ var _internals61 = {
42293
42416
  readLatestLoopState
42294
42417
  };
42295
42418
  var USAGE10 = `Usage: /swarm loop <objective> [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]
@@ -42402,7 +42525,7 @@ ${USAGE10}`;
42402
42525
  }
42403
42526
  let autonomy = parsed.autonomy;
42404
42527
  if (parsed.resume && !parsed.autonomyExplicit) {
42405
- const state = await _internals60.readLatestLoopState(_directory);
42528
+ const state = await _internals61.readLatestLoopState(_directory);
42406
42529
  if (state?.autonomy && AUTONOMY_LEVELS.has(state.autonomy)) {
42407
42530
  autonomy = state.autonomy;
42408
42531
  }
@@ -42491,7 +42614,7 @@ async function rmTempRoot(tempRoot) {
42491
42614
  } catch (err) {
42492
42615
  if (attempt === 9)
42493
42616
  throw err;
42494
- await new Promise((resolve21) => setTimeout(resolve21, 50));
42617
+ await new Promise((resolve22) => setTimeout(resolve22, 50));
42495
42618
  }
42496
42619
  }
42497
42620
  }
@@ -42892,7 +43015,7 @@ function parseJsonObject(candidate) {
42892
43015
  // src/memory/injector.ts
42893
43016
  init_schema();
42894
43017
  // src/memory/consolidation-log.ts
42895
- import { appendFile as appendFile7, mkdir as mkdir18, readFile as readFile20 } from "fs/promises";
43018
+ import { appendFile as appendFile6, mkdir as mkdir17, readFile as readFile19 } from "fs/promises";
42896
43019
  import * as path73 from "path";
42897
43020
  var LOG_RELATIVE_PATH = path73.join("memory", "consolidation-log.jsonl");
42898
43021
  var LOG_BASENAME = "consolidation-log.jsonl";
@@ -42909,7 +43032,7 @@ async function readConsolidationLog(target) {
42909
43032
  const filePath = resolveLogPath2(target);
42910
43033
  let raw;
42911
43034
  try {
42912
- raw = await readFile20(filePath, "utf-8");
43035
+ raw = await readFile19(filePath, "utf-8");
42913
43036
  } catch {
42914
43037
  return [];
42915
43038
  }
@@ -43469,14 +43592,14 @@ function truncate(value, maxLength) {
43469
43592
  }
43470
43593
 
43471
43594
  // src/commands/memory-link.ts
43472
- import { mkdir as mkdir20, writeFile as writeFile15 } from "fs/promises";
43595
+ import { mkdir as mkdir19, writeFile as writeFile14 } from "fs/promises";
43473
43596
  import * as path76 from "path";
43474
43597
  init_schema();
43475
43598
 
43476
43599
  // src/memory/memory-family-migration.ts
43477
43600
  var import_proper_lockfile7 = __toESM(require_proper_lockfile(), 1);
43478
43601
  import { copyFileSync as copyFileSync4, existsSync as existsSync41, readFileSync as readFileSync32, unlinkSync as unlinkSync12 } from "fs";
43479
- import { mkdir as mkdir19, rename as rename9 } from "fs/promises";
43602
+ import { mkdir as mkdir18, rename as rename8 } from "fs/promises";
43480
43603
  import * as path75 from "path";
43481
43604
  init_logger();
43482
43605
 
@@ -43618,12 +43741,12 @@ function stageSqliteDb(sourceStoragePath, destDir) {
43618
43741
  async function mergeStagedSqlite(destStoragePath, stagedPath) {
43619
43742
  const destDbPath = path75.join(destStoragePath, "memory.db");
43620
43743
  if (!existsSync41(destDbPath)) {
43621
- await rename9(stagedPath, destDbPath);
43744
+ await rename8(stagedPath, destDbPath);
43622
43745
  for (const suffix of ["-wal", "-shm"]) {
43623
43746
  const stagedSidecar = `${stagedPath}${suffix}`;
43624
43747
  if (existsSync41(stagedSidecar)) {
43625
43748
  try {
43626
- await rename9(stagedSidecar, `${destDbPath}${suffix}`);
43749
+ await rename8(stagedSidecar, `${destDbPath}${suffix}`);
43627
43750
  } catch {}
43628
43751
  }
43629
43752
  }
@@ -43696,7 +43819,7 @@ async function countRowsSafe(dbPath) {
43696
43819
  async function migrateMemoryFamily(destRoot, sourceRoot) {
43697
43820
  const destStoragePath = rootStoragePath(destRoot);
43698
43821
  const sourceStoragePath = rootStoragePath(sourceRoot);
43699
- await mkdir19(destStoragePath, { recursive: true });
43822
+ await mkdir18(destStoragePath, { recursive: true });
43700
43823
  let destRelease = null;
43701
43824
  try {
43702
43825
  destRelease = await import_proper_lockfile7.default.lock(destStoragePath, {
@@ -43743,7 +43866,7 @@ async function migrateMemoryFamily(destRoot, sourceRoot) {
43743
43866
  }
43744
43867
  if (isCohortRoot(sourceRoot)) {
43745
43868
  const backupDir = path75.join(destStoragePath, "backups");
43746
- await mkdir19(backupDir, { recursive: true });
43869
+ await mkdir18(backupDir, { recursive: true });
43747
43870
  const stamp = new Date().toISOString().replace(/[:.]/g, "-");
43748
43871
  const sourceDbPath = path75.join(sourceStoragePath, "memory.db");
43749
43872
  if (existsSync41(sourceDbPath)) {
@@ -43879,10 +44002,10 @@ ${formatStatus2(directory)}`;
43879
44002
  return `\u274C Failed to migrate the memory family into the cohort store: ${error2 instanceof Error ? error2.message : String(error2)}`;
43880
44003
  }
43881
44004
  try {
43882
- await mkdir20(cohortRoot.cohortRoot, { recursive: true });
44005
+ await mkdir19(cohortRoot.cohortRoot, { recursive: true });
43883
44006
  const fingerprintInput = buildMemoryCohortFingerprintInput(memoryConfig);
43884
44007
  const fingerprint = computeMemoryCohortFingerprint(fingerprintInput);
43885
- await writeFile15(path76.join(cohortRoot.cohortRoot, "memory-cohort-config.json"), JSON.stringify({
44008
+ await writeFile14(path76.join(cohortRoot.cohortRoot, "memory-cohort-config.json"), JSON.stringify({
43886
44009
  fingerprint,
43887
44010
  algorithm_version: FINGERPRINT_ALGORITHM_VERSION,
43888
44011
  config: fingerprintInput,
@@ -43956,15 +44079,15 @@ async function handleMemoryUnlinkCommand(directory, args) {
43956
44079
  }
43957
44080
 
43958
44081
  // src/services/plan-service.ts
43959
- var _internals61 = {
44082
+ var _internals62 = {
43960
44083
  loadPlanJsonOnly,
43961
44084
  derivePlanMarkdown,
43962
44085
  readSwarmFileAsync
43963
44086
  };
43964
44087
  async function getPlanData(directory, phaseArg) {
43965
- const plan = await _internals61.loadPlanJsonOnly(directory);
44088
+ const plan = await _internals62.loadPlanJsonOnly(directory);
43966
44089
  if (plan) {
43967
- const fullMarkdown = _internals61.derivePlanMarkdown(plan);
44090
+ const fullMarkdown = _internals62.derivePlanMarkdown(plan);
43968
44091
  if (phaseArg === undefined || phaseArg === null || phaseArg === "") {
43969
44092
  return {
43970
44093
  hasPlan: true,
@@ -44007,7 +44130,7 @@ async function getPlanData(directory, phaseArg) {
44007
44130
  isLegacy: false
44008
44131
  };
44009
44132
  }
44010
- const planContent = await _internals61.readSwarmFileAsync(directory, "plan.md");
44133
+ const planContent = await _internals62.readSwarmFileAsync(directory, "plan.md");
44011
44134
  if (!planContent) {
44012
44135
  return {
44013
44136
  hasPlan: false,
@@ -44104,7 +44227,7 @@ async function handlePlanCommand(directory, args) {
44104
44227
  return formatPlanMarkdown(planData);
44105
44228
  }
44106
44229
  // src/commands/post-mortem.ts
44107
- var _internals62 = {
44230
+ var _internals63 = {
44108
44231
  createCuratorLLMDelegate,
44109
44232
  runCuratorPostMortem
44110
44233
  };
@@ -44152,10 +44275,10 @@ async function handlePostMortemCommand(directory, args, options) {
44152
44275
  };
44153
44276
  if (options?.sessionID) {
44154
44277
  try {
44155
- pmOptions.llmDelegate = _internals62.createCuratorLLMDelegate(directory, "postmortem", options.sessionID);
44278
+ pmOptions.llmDelegate = _internals63.createCuratorLLMDelegate(directory, "postmortem", options.sessionID);
44156
44279
  } catch {}
44157
44280
  }
44158
- const result = await _internals62.runCuratorPostMortem(directory, pmOptions);
44281
+ const result = await _internals63.runCuratorPostMortem(directory, pmOptions);
44159
44282
  const lines = [];
44160
44283
  if (result.success) {
44161
44284
  lines.push("## Post-Mortem Report Generated");
@@ -44413,7 +44536,7 @@ function formatMergeGroupStatus(status, conclusion, htmlUrl) {
44413
44536
  }
44414
44537
  return parts.join(" ");
44415
44538
  }
44416
- var _internals63 = {
44539
+ var _internals64 = {
44417
44540
  formatRelativeTime,
44418
44541
  formatMergeGroupStatus,
44419
44542
  listActive,
@@ -44421,7 +44544,7 @@ var _internals63 = {
44421
44544
  parseMergeGroupRuns
44422
44545
  };
44423
44546
  async function handlePrMonitorStatusCommand(directory, _args, sessionID, source) {
44424
- const allActive = await _internals63.listActive(directory);
44547
+ const allActive = await _internals64.listActive(directory);
44425
44548
  const allSessions = source === "cli";
44426
44549
  const subs = allSessions ? allActive : allActive.filter((record) => record.sessionID === sessionID);
44427
44550
  if (subs.length === 0) {
@@ -44437,7 +44560,7 @@ async function handlePrMonitorStatusCommand(directory, _args, sessionID, source)
44437
44560
  const index = i + 1;
44438
44561
  lines.push(` ${index}. ${sub.repoFullName}#${sub.prNumber}`);
44439
44562
  lines.push(` URL: ${sub.prUrl}`);
44440
- const mergeGroupRuns = await _internals63.listMergeGroupRuns(directory, sub.repoFullName, sub.prNumber);
44563
+ const mergeGroupRuns = await _internals64.listMergeGroupRuns(directory, sub.repoFullName, sub.prNumber);
44441
44564
  if (mergeGroupRuns.runs.length > 0) {
44442
44565
  lines.push(" Merge-group runs:");
44443
44566
  for (const run of mergeGroupRuns.runs) {
@@ -44578,7 +44701,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
44578
44701
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
44579
44702
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
44580
44703
  try {
44581
- const config = _internals64.loadPluginConfig(directory);
44704
+ const config = _internals65.loadPluginConfig(directory);
44582
44705
  const prMonitorConfig = config.pr_monitor;
44583
44706
  if (!prMonitorConfig?.enabled) {
44584
44707
  return [
@@ -44588,7 +44711,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
44588
44711
  ].join(`
44589
44712
  `);
44590
44713
  }
44591
- await _internals64.subscribe(directory, {
44714
+ await _internals65.subscribe(directory, {
44592
44715
  sessionID,
44593
44716
  prNumber: prInfo.number,
44594
44717
  repoFullName,
@@ -44616,7 +44739,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
44616
44739
  `);
44617
44740
  }
44618
44741
  }
44619
- var _internals64 = {
44742
+ var _internals65 = {
44620
44743
  loadPluginConfig,
44621
44744
  subscribe
44622
44745
  };
@@ -44639,9 +44762,9 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
44639
44762
  `);
44640
44763
  }
44641
44764
  const refToken = rest[0];
44642
- const prInfo = _internals65.parsePrRef(refToken, directory);
44765
+ const prInfo = _internals66.parsePrRef(refToken, directory);
44643
44766
  if (!prInfo) {
44644
- if (_internals65.looksLikePrRef(refToken)) {
44767
+ if (_internals66.looksLikePrRef(refToken)) {
44645
44768
  return [
44646
44769
  `Error: Could not resolve PR reference from "${refToken}".`,
44647
44770
  "",
@@ -44662,8 +44785,8 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
44662
44785
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
44663
44786
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
44664
44787
  try {
44665
- const correlationId = _internals65.buildCorrelationId(sessionID, repoFullName, prInfo.number);
44666
- const result = await _internals65.unsubscribe(directory, correlationId);
44788
+ const correlationId = _internals66.buildCorrelationId(sessionID, repoFullName, prInfo.number);
44789
+ const result = await _internals66.unsubscribe(directory, correlationId);
44667
44790
  if (!result) {
44668
44791
  return [
44669
44792
  `Not subscribed to ${prUrl}`,
@@ -44690,7 +44813,7 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
44690
44813
  `);
44691
44814
  }
44692
44815
  }
44693
- var _internals65 = {
44816
+ var _internals66 = {
44694
44817
  unsubscribe,
44695
44818
  buildCorrelationId,
44696
44819
  parsePrRef,
@@ -44739,7 +44862,7 @@ function normalizeRelativePathForPlatform(value, platform) {
44739
44862
  }
44740
44863
  function isRegularFile(candidate) {
44741
44864
  try {
44742
- return _internals66.statSync(candidate).isFile();
44865
+ return _internals67.statSync(candidate).isFile();
44743
44866
  } catch {
44744
44867
  return false;
44745
44868
  }
@@ -44747,21 +44870,21 @@ function isRegularFile(candidate) {
44747
44870
  function readTextFileBounded(filePath, maxBytes) {
44748
44871
  let fd;
44749
44872
  try {
44750
- fd = _internals66.openSync(filePath, "r");
44751
- const stats = _internals66.fstatSync(fd);
44873
+ fd = _internals67.openSync(filePath, "r");
44874
+ const stats = _internals67.fstatSync(fd);
44752
44875
  if (!stats.isFile() || !Number.isSafeInteger(stats.size) || stats.size < 0 || stats.size > maxBytes) {
44753
44876
  return null;
44754
44877
  }
44755
44878
  const bytes = Buffer.alloc(stats.size);
44756
44879
  let offset = 0;
44757
44880
  while (offset < bytes.byteLength) {
44758
- const bytesRead = _internals66.readSync(fd, bytes, offset, bytes.byteLength - offset, null);
44881
+ const bytesRead = _internals67.readSync(fd, bytes, offset, bytes.byteLength - offset, null);
44759
44882
  if (bytesRead === 0)
44760
44883
  break;
44761
44884
  offset += bytesRead;
44762
44885
  }
44763
44886
  const overflowProbe = Buffer.alloc(1);
44764
- if (_internals66.readSync(fd, overflowProbe, 0, 1, null) > 0)
44887
+ if (_internals67.readSync(fd, overflowProbe, 0, 1, null) > 0)
44765
44888
  return null;
44766
44889
  return bytes.subarray(0, offset).toString("utf8");
44767
44890
  } catch {
@@ -44769,7 +44892,7 @@ function readTextFileBounded(filePath, maxBytes) {
44769
44892
  } finally {
44770
44893
  if (fd !== undefined) {
44771
44894
  try {
44772
- _internals66.closeSync(fd);
44895
+ _internals67.closeSync(fd);
44773
44896
  } catch {}
44774
44897
  }
44775
44898
  }
@@ -44790,7 +44913,7 @@ function getAncestorDirectories(directory) {
44790
44913
  }
44791
44914
  return roots;
44792
44915
  }
44793
- function getTrustedShimNames(linter, platform = _internals66.platform()) {
44916
+ function getTrustedShimNames(linter, platform = _internals67.platform()) {
44794
44917
  const isWindows = platform === "win32";
44795
44918
  if (linter === "biome") {
44796
44919
  return isWindows ? ["biome.exe", "biome.cmd", "biome.ps1"] : ["biome"];
@@ -44807,7 +44930,7 @@ function getPackageManifestPath(searchRoot, linter) {
44807
44930
  return path77.join(getPackageRootFromSearchRoot(searchRoot, linter), "package.json");
44808
44931
  }
44809
44932
  function getPackageDisplayPath(searchRoot, linter) {
44810
- return path77.join(searchRoot, NODE_MODULES, BIN_DIRECTORY, linter === "biome" ? _internals66.platform() === "win32" ? "biome.exe" : "biome" : _internals66.platform() === "win32" ? "eslint" : "eslint");
44933
+ return path77.join(searchRoot, NODE_MODULES, BIN_DIRECTORY, linter === "biome" ? _internals67.platform() === "win32" ? "biome.exe" : "biome" : _internals67.platform() === "win32" ? "eslint" : "eslint");
44811
44934
  }
44812
44935
  function getBiomeNativePackage(platform, arch) {
44813
44936
  const archMap = platform === "darwin" ? { arm64: "@biomejs/cli-darwin-arm64", x64: "@biomejs/cli-darwin-x64" } : platform === "linux" ? {
@@ -44822,7 +44945,7 @@ function getBiomeNativePackage(platform, arch) {
44822
44945
  return null;
44823
44946
  return archMap[arch] ?? null;
44824
44947
  }
44825
- function getBiomeNativeExecutable(searchRoot, platform = _internals66.platform(), arch = _internals66.arch()) {
44948
+ function getBiomeNativeExecutable(searchRoot, platform = _internals67.platform(), arch = _internals67.arch()) {
44826
44949
  const nativePackage = getBiomeNativePackage(platform, arch);
44827
44950
  if (!nativePackage)
44828
44951
  return null;
@@ -44858,8 +44981,8 @@ function resolveCanonicalPackageCommand(searchRoot, linter, source) {
44858
44981
  let canonicalCandidate;
44859
44982
  try {
44860
44983
  const packageRoot = path77.dirname(manifestPath);
44861
- canonicalPackageRoot = _internals66.realpathSync(packageRoot);
44862
- canonicalCandidate = _internals66.realpathSync(path77.resolve(packageRoot, relativeBinPath));
44984
+ canonicalPackageRoot = _internals67.realpathSync(packageRoot);
44985
+ canonicalCandidate = _internals67.realpathSync(path77.resolve(packageRoot, relativeBinPath));
44863
44986
  } catch {
44864
44987
  return null;
44865
44988
  }
@@ -44871,7 +44994,7 @@ function resolveCanonicalPackageCommand(searchRoot, linter, source) {
44871
44994
  return null;
44872
44995
  return {
44873
44996
  linter,
44874
- executable: _internals66.execPath(),
44997
+ executable: _internals67.execPath(),
44875
44998
  argsPrefix: [canonicalCandidate],
44876
44999
  displayPrefix: [getPackageDisplayPath(searchRoot, linter)],
44877
45000
  source
@@ -44912,7 +45035,7 @@ function resolveLocalLinterCommand(linter, directory) {
44912
45035
  }
44913
45036
  return null;
44914
45037
  }
44915
- function findPathShimCandidate(linter, envPath = _internals66.pathEnv(), platform = _internals66.platform()) {
45038
+ function findPathShimCandidate(linter, envPath = _internals67.pathEnv(), platform = _internals67.platform()) {
44916
45039
  const entries = envPath.split(path77.delimiter).filter(Boolean);
44917
45040
  const shimNames = getTrustedShimNames(linter, platform).filter((name) => name.endsWith(".cmd") || name.endsWith(".ps1") || platform !== "win32");
44918
45041
  for (const entry of entries) {
@@ -44942,7 +45065,7 @@ function getExpectedShimSuffixes(linter) {
44942
45065
  normalizeRelativePathForPlatform(nodeModulesPackageOnlySuffix, "linux")
44943
45066
  ];
44944
45067
  }
44945
- function resolvePathShimTarget(shimPath, linter, platform = _internals66.platform()) {
45068
+ function resolvePathShimTarget(shimPath, linter, platform = _internals67.platform()) {
44946
45069
  const contents = readTextFileBounded(shimPath, MAX_PATH_SHIM_BYTES);
44947
45070
  if (contents === null)
44948
45071
  return null;
@@ -44989,7 +45112,7 @@ function resolvePathShimTarget(shimPath, linter, platform = _internals66.platfor
44989
45112
  return null;
44990
45113
  let canonicalShimDir;
44991
45114
  try {
44992
- canonicalShimDir = _internals66.realpathSync(path77.dirname(shimPath));
45115
+ canonicalShimDir = _internals67.realpathSync(path77.dirname(shimPath));
44993
45116
  } catch {
44994
45117
  return null;
44995
45118
  }
@@ -44998,7 +45121,7 @@ function resolvePathShimTarget(shimPath, linter, platform = _internals66.platfor
44998
45121
  return null;
44999
45122
  let canonicalTarget;
45000
45123
  try {
45001
- canonicalTarget = _internals66.realpathSync(resolvedTarget);
45124
+ canonicalTarget = _internals67.realpathSync(resolvedTarget);
45002
45125
  } catch {
45003
45126
  return null;
45004
45127
  }
@@ -45008,7 +45131,7 @@ function resolvePathShimTarget(shimPath, linter, platform = _internals66.platfor
45008
45131
  }
45009
45132
  let canonicalShimParent;
45010
45133
  try {
45011
- canonicalShimParent = _internals66.realpathSync(path77.dirname(canonicalShimDir));
45134
+ canonicalShimParent = _internals67.realpathSync(path77.dirname(canonicalShimDir));
45012
45135
  } catch {
45013
45136
  return null;
45014
45137
  }
@@ -45022,8 +45145,8 @@ function resolvePathShimTarget(shimPath, linter, platform = _internals66.platfor
45022
45145
  return canonicalTarget;
45023
45146
  }
45024
45147
  function resolvePathLinterCommand(linter, directory) {
45025
- const platform = _internals66.platform();
45026
- const envPath = _internals66.pathEnv();
45148
+ const platform = _internals67.platform();
45149
+ const envPath = _internals67.pathEnv();
45027
45150
  const nativeNames = platform === "win32" ? linter === "biome" ? ["biome.exe"] : ["eslint.exe"] : linter === "biome" ? ["biome"] : ["eslint"];
45028
45151
  const nativeExecutable = resolveExecutableFromPath(nativeNames, envPath, platform);
45029
45152
  if (nativeExecutable) {
@@ -45043,7 +45166,7 @@ function resolvePathLinterCommand(linter, directory) {
45043
45166
  return null;
45044
45167
  return {
45045
45168
  linter,
45046
- executable: _internals66.execPath(),
45169
+ executable: _internals67.execPath(),
45047
45170
  argsPrefix: [shimTarget],
45048
45171
  displayPrefix: [path77.join(directory, NODE_MODULES, BIN_DIRECTORY, linter)],
45049
45172
  source: "path-shim"
@@ -45080,7 +45203,7 @@ function buildExecutionError(mode, command, linter, result) {
45080
45203
  };
45081
45204
  }
45082
45205
  async function probeResolvedCommand(command, cwd, abortSignal) {
45083
- const result = await _internals66.runExternalTool({
45206
+ const result = await _internals67.runExternalTool({
45084
45207
  executable: command.executable,
45085
45208
  args: [...command.argsPrefix, "--version"],
45086
45209
  cwd,
@@ -45098,7 +45221,7 @@ async function resolveLinterCommand(linter, directory) {
45098
45221
  async function detectResolvedLinter(directory, abortSignal) {
45099
45222
  if (!directory)
45100
45223
  return null;
45101
- if (!_internals66.existsSync(directory))
45224
+ if (!_internals67.existsSync(directory))
45102
45225
  return null;
45103
45226
  const cwd = toAbsoluteDirectory(directory);
45104
45227
  for (const linter of SUPPORTED_LINTERS) {
@@ -45112,12 +45235,12 @@ async function detectResolvedLinter(directory, abortSignal) {
45112
45235
  return null;
45113
45236
  }
45114
45237
  function detectRuff(cwd) {
45115
- if (_internals66.existsSync(path77.join(cwd, "ruff.toml")))
45238
+ if (_internals67.existsSync(path77.join(cwd, "ruff.toml")))
45116
45239
  return hasAdditionalCommand("ruff");
45117
45240
  try {
45118
45241
  const pyproject = path77.join(cwd, "pyproject.toml");
45119
- if (_internals66.existsSync(pyproject)) {
45120
- const content = _internals66.readFileSync(pyproject, "utf-8");
45242
+ if (_internals67.existsSync(pyproject)) {
45243
+ const content = _internals67.readFileSync(pyproject, "utf-8");
45121
45244
  if (content.includes("[tool.ruff]"))
45122
45245
  return hasAdditionalCommand("ruff");
45123
45246
  }
@@ -45125,32 +45248,32 @@ function detectRuff(cwd) {
45125
45248
  return false;
45126
45249
  }
45127
45250
  function detectClippy(cwd) {
45128
- return _internals66.existsSync(path77.join(cwd, "Cargo.toml")) && hasAdditionalCommand("cargo");
45251
+ return _internals67.existsSync(path77.join(cwd, "Cargo.toml")) && hasAdditionalCommand("cargo");
45129
45252
  }
45130
45253
  function detectGolangciLint(cwd) {
45131
- return _internals66.existsSync(path77.join(cwd, "go.mod")) && hasAdditionalCommand("golangci-lint");
45254
+ return _internals67.existsSync(path77.join(cwd, "go.mod")) && hasAdditionalCommand("golangci-lint");
45132
45255
  }
45133
45256
  function readTextFileSafe(filePath) {
45134
45257
  try {
45135
- return _internals66.readFileSync(filePath, "utf-8");
45258
+ return _internals67.readFileSync(filePath, "utf-8");
45136
45259
  } catch {
45137
45260
  return "";
45138
45261
  }
45139
45262
  }
45140
45263
  function resolveAdditionalExecutable(name) {
45141
- const platform = _internals66.platform();
45264
+ const platform = _internals67.platform();
45142
45265
  if (platform !== "win32") {
45143
- return _internals66.isCommandAvailable(name) ? name : null;
45266
+ return _internals67.isCommandAvailable(name) ? name : null;
45144
45267
  }
45145
- return resolveExecutableFromPath([`${name}.exe`], _internals66.pathEnv(), platform);
45268
+ return resolveExecutableFromPath([`${name}.exe`], _internals67.pathEnv(), platform);
45146
45269
  }
45147
45270
  function resolveWindowsCommandInterpreter() {
45148
- const candidate = _internals66.comSpec();
45271
+ const candidate = _internals67.comSpec();
45149
45272
  if (!candidate || !path77.isAbsolute(candidate) || path77.basename(candidate).toLowerCase() !== "cmd.exe" || !isRegularFile(candidate)) {
45150
45273
  return null;
45151
45274
  }
45152
45275
  try {
45153
- const canonical = _internals66.realpathSync(candidate);
45276
+ const canonical = _internals67.realpathSync(candidate);
45154
45277
  return path77.basename(canonical).toLowerCase() === "cmd.exe" ? canonical : null;
45155
45278
  } catch {
45156
45279
  return null;
@@ -45162,7 +45285,7 @@ function buildWindowsBatchCommand(wrapperPath, args) {
45162
45285
  return null;
45163
45286
  let canonicalWrapper;
45164
45287
  try {
45165
- canonicalWrapper = _internals66.realpathSync(wrapperPath);
45288
+ canonicalWrapper = _internals67.realpathSync(wrapperPath);
45166
45289
  } catch {
45167
45290
  return null;
45168
45291
  }
@@ -45176,13 +45299,13 @@ function buildWindowsBatchCommand(wrapperPath, args) {
45176
45299
  return [interpreter, "/d", "/s", "/v:off", "/c", command];
45177
45300
  }
45178
45301
  function resolveWindowsBatchCommandFromPath(name, args) {
45179
- if (_internals66.platform() !== "win32")
45302
+ if (_internals67.platform() !== "win32")
45180
45303
  return null;
45181
- const wrapper = resolveExecutableFromPath(WINDOWS_BATCH_WRAPPER_EXTENSIONS.map((extension) => `${name}${extension}`), _internals66.pathEnv(), "win32");
45304
+ const wrapper = resolveExecutableFromPath(WINDOWS_BATCH_WRAPPER_EXTENSIONS.map((extension) => `${name}${extension}`), _internals67.pathEnv(), "win32");
45182
45305
  return wrapper ? buildWindowsBatchCommand(wrapper, args) : null;
45183
45306
  }
45184
45307
  function resolveContainedWindowsBatchCommand(cwd, fileName, args) {
45185
- if (_internals66.platform() !== "win32")
45308
+ if (_internals67.platform() !== "win32")
45186
45309
  return null;
45187
45310
  const candidate = path77.join(cwd, fileName);
45188
45311
  if (!isRegularFile(candidate))
@@ -45190,8 +45313,8 @@ function resolveContainedWindowsBatchCommand(cwd, fileName, args) {
45190
45313
  let canonicalCwd;
45191
45314
  let canonicalCandidate;
45192
45315
  try {
45193
- canonicalCwd = _internals66.realpathSync(cwd);
45194
- canonicalCandidate = _internals66.realpathSync(candidate);
45316
+ canonicalCwd = _internals67.realpathSync(cwd);
45317
+ canonicalCandidate = _internals67.realpathSync(candidate);
45195
45318
  } catch {
45196
45319
  return null;
45197
45320
  }
@@ -45212,22 +45335,22 @@ function hasAdditionalCommand(name) {
45212
45335
  }
45213
45336
  function resolvePhpVendorCommand(cwd, name) {
45214
45337
  const relativeProxy = path77.join("vendor", "bin", name);
45215
- if (!_internals66.existsSync(path77.join(cwd, relativeProxy)))
45338
+ if (!_internals67.existsSync(path77.join(cwd, relativeProxy)))
45216
45339
  return null;
45217
- if (_internals66.platform() !== "win32")
45340
+ if (_internals67.platform() !== "win32")
45218
45341
  return [relativeProxy];
45219
45342
  const phpExecutable = resolveAdditionalExecutable("php");
45220
45343
  return phpExecutable ? [phpExecutable, relativeProxy] : null;
45221
45344
  }
45222
45345
  function hasCheckstyleGradleSignal(cwd) {
45223
- const gradleFiles = ["build.gradle", "build.gradle.kts"].map((file) => path77.join(cwd, file)).filter((file) => _internals66.existsSync(file));
45224
- return _internals66.existsSync(path77.join(cwd, "checkstyle.xml")) || _internals66.existsSync(path77.join(cwd, "config", "checkstyle", "checkstyle.xml")) || gradleFiles.some((file) => /\bcheckstyle\b/i.test(readTextFileSafe(file)));
45346
+ const gradleFiles = ["build.gradle", "build.gradle.kts"].map((file) => path77.join(cwd, file)).filter((file) => _internals67.existsSync(file));
45347
+ return _internals67.existsSync(path77.join(cwd, "checkstyle.xml")) || _internals67.existsSync(path77.join(cwd, "config", "checkstyle", "checkstyle.xml")) || gradleFiles.some((file) => /\bcheckstyle\b/i.test(readTextFileSafe(file)));
45225
45348
  }
45226
45349
  function resolveCheckstyleCommand(cwd) {
45227
- const hasMavenProject = _internals66.existsSync(path77.join(cwd, "pom.xml"));
45350
+ const hasMavenProject = _internals67.existsSync(path77.join(cwd, "pom.xml"));
45228
45351
  const hasGradleSignal = hasCheckstyleGradleSignal(cwd);
45229
45352
  if (hasGradleSignal) {
45230
- if (_internals66.platform() === "win32") {
45353
+ if (_internals67.platform() === "win32") {
45231
45354
  const gradlew = resolveContainedWindowsBatchCommand(cwd, "gradlew.bat", [
45232
45355
  "checkstyleMain"
45233
45356
  ]);
@@ -45235,7 +45358,7 @@ function resolveCheckstyleCommand(cwd) {
45235
45358
  return gradlew;
45236
45359
  } else {
45237
45360
  const gradlew = path77.join(cwd, "gradlew");
45238
- if (_internals66.existsSync(gradlew))
45361
+ if (_internals67.existsSync(gradlew))
45239
45362
  return [gradlew, "checkstyleMain"];
45240
45363
  }
45241
45364
  const gradle = buildAdditionalCommand("gradle", ["checkstyleMain"]);
@@ -45249,7 +45372,7 @@ function resolveCheckstyleCommand(cwd) {
45249
45372
  }
45250
45373
  return null;
45251
45374
  }
45252
- function isUnsafeShellWrapperExecutable(executable, platform = _internals66.platform()) {
45375
+ function isUnsafeShellWrapperExecutable(executable, platform = _internals67.platform()) {
45253
45376
  return platform === "win32" && UNSAFE_SHELL_WRAPPER_EXTENSIONS.has(path77.extname(executable).toLowerCase());
45254
45377
  }
45255
45378
  function detectCheckstyle(cwd) {
@@ -45257,7 +45380,7 @@ function detectCheckstyle(cwd) {
45257
45380
  }
45258
45381
  function hasRootKotlinFile(cwd) {
45259
45382
  try {
45260
- return _internals66.readdirSync(cwd).some((f) => f.endsWith(".kt") || f.endsWith(".kts"));
45383
+ return _internals67.readdirSync(cwd).some((f) => f.endsWith(".kt") || f.endsWith(".kts"));
45261
45384
  } catch {
45262
45385
  return false;
45263
45386
  }
@@ -45267,27 +45390,27 @@ function buildGradleHasKotlinSignal(cwd) {
45267
45390
  return /\b(kotlin|org\.jetbrains\.kotlin|ktlint)\b/i.test(content);
45268
45391
  }
45269
45392
  function detectKtlint(cwd) {
45270
- const hasKotlin = _internals66.existsSync(path77.join(cwd, "build.gradle.kts")) || _internals66.existsSync(path77.join(cwd, "build.gradle")) && buildGradleHasKotlinSignal(cwd) || hasRootKotlinFile(cwd);
45393
+ const hasKotlin = _internals67.existsSync(path77.join(cwd, "build.gradle.kts")) || _internals67.existsSync(path77.join(cwd, "build.gradle")) && buildGradleHasKotlinSignal(cwd) || hasRootKotlinFile(cwd);
45271
45394
  return hasKotlin && hasAdditionalCommand("ktlint");
45272
45395
  }
45273
45396
  function detectPhpLinter(cwd) {
45274
- if ((_internals66.existsSync(path77.join(cwd, "phpstan.neon")) || _internals66.existsSync(path77.join(cwd, "phpstan.neon.dist"))) && resolvePhpVendorCommand(cwd, "phpstan") !== null) {
45397
+ if ((_internals67.existsSync(path77.join(cwd, "phpstan.neon")) || _internals67.existsSync(path77.join(cwd, "phpstan.neon.dist"))) && resolvePhpVendorCommand(cwd, "phpstan") !== null) {
45275
45398
  return "phpstan";
45276
45399
  }
45277
- if (_internals66.existsSync(path77.join(cwd, "pint.json")) && resolvePhpVendorCommand(cwd, "pint") !== null) {
45400
+ if (_internals67.existsSync(path77.join(cwd, "pint.json")) && resolvePhpVendorCommand(cwd, "pint") !== null) {
45278
45401
  return "pint";
45279
45402
  }
45280
- if (_internals66.existsSync(path77.join(cwd, ".php-cs-fixer.php")) && resolvePhpVendorCommand(cwd, "php-cs-fixer") !== null) {
45403
+ if (_internals67.existsSync(path77.join(cwd, ".php-cs-fixer.php")) && resolvePhpVendorCommand(cwd, "php-cs-fixer") !== null) {
45281
45404
  return "php-cs-fixer";
45282
45405
  }
45283
- if (_internals66.existsSync(path77.join(cwd, "phpcs.xml")) && resolvePhpVendorCommand(cwd, "phpcs") !== null) {
45406
+ if (_internals67.existsSync(path77.join(cwd, "phpcs.xml")) && resolvePhpVendorCommand(cwd, "phpcs") !== null) {
45284
45407
  return "phpcs";
45285
45408
  }
45286
45409
  return null;
45287
45410
  }
45288
45411
  function detectDotnetFormat(cwd) {
45289
45412
  try {
45290
- const files = _internals66.readdirSync(cwd);
45413
+ const files = _internals67.readdirSync(cwd);
45291
45414
  const hasCsproj = files.some((f) => f.endsWith(".csproj") || f.endsWith(".sln"));
45292
45415
  return hasCsproj && hasAdditionalCommand("dotnet");
45293
45416
  } catch {
@@ -45295,14 +45418,14 @@ function detectDotnetFormat(cwd) {
45295
45418
  }
45296
45419
  }
45297
45420
  function detectCppcheck(cwd) {
45298
- if (_internals66.existsSync(path77.join(cwd, "CMakeLists.txt"))) {
45421
+ if (_internals67.existsSync(path77.join(cwd, "CMakeLists.txt"))) {
45299
45422
  return hasAdditionalCommand("cppcheck");
45300
45423
  }
45301
45424
  try {
45302
45425
  const dirsToCheck = [cwd, path77.join(cwd, "src")];
45303
45426
  const hasCpp = dirsToCheck.some((dir) => {
45304
45427
  try {
45305
- return _internals66.readdirSync(dir).some((f) => /\.(c|cpp|cc|cxx|h|hpp)$/.test(f));
45428
+ return _internals67.readdirSync(dir).some((f) => /\.(c|cpp|cc|cxx|h|hpp)$/.test(f));
45306
45429
  } catch {
45307
45430
  return false;
45308
45431
  }
@@ -45313,13 +45436,13 @@ function detectCppcheck(cwd) {
45313
45436
  }
45314
45437
  }
45315
45438
  function detectSwiftlint(cwd) {
45316
- return _internals66.existsSync(path77.join(cwd, "Package.swift")) && hasAdditionalCommand("swiftlint");
45439
+ return _internals67.existsSync(path77.join(cwd, "Package.swift")) && hasAdditionalCommand("swiftlint");
45317
45440
  }
45318
45441
  function detectDartAnalyze(cwd) {
45319
- return _internals66.existsSync(path77.join(cwd, "pubspec.yaml")) && hasAdditionalCommand("dart");
45442
+ return _internals67.existsSync(path77.join(cwd, "pubspec.yaml")) && hasAdditionalCommand("dart");
45320
45443
  }
45321
45444
  function detectRubocop(cwd) {
45322
- return (_internals66.existsSync(path77.join(cwd, "Gemfile")) || _internals66.existsSync(path77.join(cwd, "gems.rb")) || _internals66.existsSync(path77.join(cwd, ".rubocop.yml"))) && (hasAdditionalCommand("rubocop") || hasAdditionalCommand("bundle"));
45445
+ return (_internals67.existsSync(path77.join(cwd, "Gemfile")) || _internals67.existsSync(path77.join(cwd, "gems.rb")) || _internals67.existsSync(path77.join(cwd, ".rubocop.yml"))) && (hasAdditionalCommand("rubocop") || hasAdditionalCommand("bundle"));
45323
45446
  }
45324
45447
  function detectAdditionalLinter(cwd) {
45325
45448
  if (detectRuff(cwd))
@@ -45364,7 +45487,7 @@ async function runResolvedLint(command, mode, directory, abortSignal) {
45364
45487
  error: "Command exceeds maximum allowed length"
45365
45488
  };
45366
45489
  }
45367
- const runResult = await _internals66.runExternalTool({
45490
+ const runResult = await _internals67.runExternalTool({
45368
45491
  executable: command.executable,
45369
45492
  args: [...command.argsPrefix, ...lintArgs],
45370
45493
  cwd: toAbsoluteDirectory(directory),
@@ -45442,7 +45565,7 @@ function getAdditionalLinterCommand(linter, mode, cwd) {
45442
45565
  }
45443
45566
  }
45444
45567
  async function runLint(linter, mode, directory, abortSignal) {
45445
- const resolved = await _internals66.resolveLinterCommand(linter, directory);
45568
+ const resolved = await _internals67.resolveLinterCommand(linter, directory);
45446
45569
  if (!resolved) {
45447
45570
  return {
45448
45571
  success: false,
@@ -45483,7 +45606,7 @@ async function runAdditionalLint(linter, mode, cwd, abortSignal) {
45483
45606
  error: `No safely executable ${linter} command found`
45484
45607
  };
45485
45608
  }
45486
- const runResult = await _internals66.runExternalTool({
45609
+ const runResult = await _internals67.runExternalTool({
45487
45610
  executable,
45488
45611
  args,
45489
45612
  cwd: toAbsoluteDirectory(cwd),
@@ -45491,7 +45614,7 @@ async function runAdditionalLint(linter, mode, cwd, abortSignal) {
45491
45614
  maxStdoutBytes: MAX_OUTPUT_BYTES2,
45492
45615
  maxStderrBytes: MAX_OUTPUT_BYTES2,
45493
45616
  abortSignal,
45494
- windowsVerbatimArguments: _internals66.platform() === "win32" && path77.basename(executable).toLowerCase() === "cmd.exe"
45617
+ windowsVerbatimArguments: _internals67.platform() === "win32" && path77.basename(executable).toLowerCase() === "cmd.exe"
45495
45618
  });
45496
45619
  if (runResult.status !== "completed") {
45497
45620
  return buildExecutionError(mode, command, linter, runResult);
@@ -45538,15 +45661,15 @@ var lint = createSwarmTool({
45538
45661
  }
45539
45662
  const { mode } = args;
45540
45663
  const cwd = directory;
45541
- const resolvedLinter = await _internals66.detectResolvedLinter(directory, ctx?.abort);
45664
+ const resolvedLinter = await _internals67.detectResolvedLinter(directory, ctx?.abort);
45542
45665
  if (resolvedLinter) {
45543
- const result = await _internals66.runResolvedLint(resolvedLinter, mode, directory, ctx?.abort);
45666
+ const result = await _internals67.runResolvedLint(resolvedLinter, mode, directory, ctx?.abort);
45544
45667
  return JSON.stringify(result, null, 2);
45545
45668
  }
45546
- const additionalLinter = _internals66.detectAdditionalLinter(cwd);
45669
+ const additionalLinter = _internals67.detectAdditionalLinter(cwd);
45547
45670
  if (additionalLinter) {
45548
45671
  warn(`[lint] Using ${additionalLinter} linter for this project`);
45549
- const result = await _internals66.runAdditionalLint(additionalLinter, mode, cwd, ctx?.abort);
45672
+ const result = await _internals67.runAdditionalLint(additionalLinter, mode, cwd, ctx?.abort);
45550
45673
  return JSON.stringify(result, null, 2);
45551
45674
  }
45552
45675
  const errorResult = {
@@ -45560,7 +45683,7 @@ For Rust: rustup component add clippy`
45560
45683
  return JSON.stringify(errorResult, null, 2);
45561
45684
  }
45562
45685
  });
45563
- var _internals66 = {
45686
+ var _internals67 = {
45564
45687
  MAX_PACKAGE_MANIFEST_BYTES,
45565
45688
  MAX_PATH_SHIM_BYTES,
45566
45689
  arch: () => process.arch,
@@ -45964,14 +46087,14 @@ function readBoundedFile(filePath, expectedPathStat) {
45964
46087
  let fd = null;
45965
46088
  try {
45966
46089
  const flags = fs32.constants.O_RDONLY | (O_NOFOLLOW !== undefined ? O_NOFOLLOW : 0);
45967
- fd = _internals67.openFile(filePath, flags);
46090
+ fd = _internals68.openFile(filePath, flags);
45968
46091
  } catch {
45969
46092
  return { status: "incomplete", reason: "read_error" };
45970
46093
  }
45971
46094
  let outcome;
45972
46095
  let closeFailed = false;
45973
46096
  try {
45974
- const stat6 = _internals67.fstatFile(fd);
46097
+ const stat6 = _internals68.fstatFile(fd);
45975
46098
  const descriptorIdentity = getStableFileIdentity(stat6);
45976
46099
  const initialSize = stat6.size;
45977
46100
  if (!stat6.isFile()) {
@@ -45983,14 +46106,14 @@ function readBoundedFile(filePath, expectedPathStat) {
45983
46106
  const buffer = Buffer.allocUnsafe(bufferLength);
45984
46107
  let bytesRead = 0;
45985
46108
  while (bytesRead < buffer.length) {
45986
- const count = _internals67.readFileChunk(fd, buffer, bytesRead, buffer.length - bytesRead, null);
46109
+ const count = _internals68.readFileChunk(fd, buffer, bytesRead, buffer.length - bytesRead, null);
45987
46110
  if (count === 0)
45988
46111
  break;
45989
46112
  bytesRead += count;
45990
46113
  }
45991
- const postStat = _internals67.fstatFile(fd);
46114
+ const postStat = _internals68.fstatFile(fd);
45992
46115
  const postDescriptorIdentity = getStableFileIdentity(postStat);
45993
- const postPathStat = _internals67.lstatFile(filePath);
46116
+ const postPathStat = _internals68.lstatFile(filePath);
45994
46117
  const postPathIdentity = getStableFileIdentity(postPathStat);
45995
46118
  if (!postStat.isFile() || postDescriptorIdentity === null || postDescriptorIdentity !== descriptorIdentity || postPathStat.isSymbolicLink() || !postPathStat.isFile() || postPathIdentity === null || postPathIdentity !== descriptorIdentity) {
45996
46119
  outcome = { status: "incomplete", reason: "read_error" };
@@ -46012,7 +46135,7 @@ function readBoundedFile(filePath, expectedPathStat) {
46012
46135
  } finally {
46013
46136
  if (fd !== null) {
46014
46137
  try {
46015
- _internals67.closeFile(fd);
46138
+ _internals68.closeFile(fd);
46016
46139
  } catch {
46017
46140
  closeFailed = true;
46018
46141
  }
@@ -46025,7 +46148,7 @@ function readBoundedFile(filePath, expectedPathStat) {
46025
46148
  function scanFileForSecrets(filePath, mode) {
46026
46149
  const findings = [];
46027
46150
  try {
46028
- const lstat3 = _internals67.lstatFile(filePath);
46151
+ const lstat3 = _internals68.lstatFile(filePath);
46029
46152
  if (lstat3.isSymbolicLink()) {
46030
46153
  return mode === "explicit" ? { status: "incomplete", reason: "symlink" } : { status: "skipped", reason: "symlink" };
46031
46154
  }
@@ -46080,7 +46203,7 @@ function assertNever(value) {
46080
46203
  throw new Error(`Unhandled secretscan outcome: ${String(value)}`);
46081
46204
  }
46082
46205
  async function yieldToEventLoop() {
46083
- await new Promise((resolve24) => setImmediate(resolve24));
46206
+ await new Promise((resolve25) => setImmediate(resolve25));
46084
46207
  }
46085
46208
  function serializeSecretscanResult(result) {
46086
46209
  let findings = result.findings;
@@ -46204,8 +46327,8 @@ async function collectScannableFiles(dir, excludeExact, excludeGlobs, scanDir, v
46204
46327
  while (true) {
46205
46328
  if (state.entriesSinceYield >= DISCOVERY_YIELD_INTERVAL) {
46206
46329
  state.entriesSinceYield = 0;
46207
- await _internals67.yieldToEventLoop();
46208
- if (_internals67.now() >= state.deadline) {
46330
+ await _internals68.yieldToEventLoop();
46331
+ if (_internals68.now() >= state.deadline) {
46209
46332
  state.deadlineExceeded = true;
46210
46333
  recordIncompletePath(state.incompletePaths, scanDir, currentDir, "deadline");
46211
46334
  stoppedEarly = true;
@@ -46268,7 +46391,7 @@ async function collectScannableFiles(dir, excludeExact, excludeGlobs, scanDir, v
46268
46391
  }
46269
46392
  } finally {
46270
46393
  try {
46271
- _internals67.closeDirectory(directory);
46394
+ _internals68.closeDirectory(directory);
46272
46395
  } catch (error2) {
46273
46396
  if (error2.code !== "ERR_DIR_CLOSED") {
46274
46397
  state.cleanupFailed = true;
@@ -46390,7 +46513,7 @@ var secretscan = createSwarmTool({
46390
46513
  symlinkSkipped: 0
46391
46514
  };
46392
46515
  const visited = new Set;
46393
- const deadline = _internals67.now() + SCAN_TIME_BUDGET_MS;
46516
+ const deadline = _internals68.now() + SCAN_TIME_BUDGET_MS;
46394
46517
  const discovery = {
46395
46518
  files: [],
46396
46519
  totalCandidates: 0,
@@ -46402,7 +46525,7 @@ var secretscan = createSwarmTool({
46402
46525
  directoriesQueued: 1,
46403
46526
  unexaminedDirectories: 0
46404
46527
  };
46405
- await _internals67.yieldToEventLoop();
46528
+ await _internals68.yieldToEventLoop();
46406
46529
  await collectScannableFiles(scanDir, excludeExact, excludeGlobs, scanDir, visited, stats, discovery);
46407
46530
  const files = discovery.files;
46408
46531
  files.sort(compareFilePaths);
@@ -46421,7 +46544,7 @@ var secretscan = createSwarmTool({
46421
46544
  let skippedFiles = stats.skippedFiles;
46422
46545
  let incompleteFiles = stats.fileErrors + Math.max(0, discovery.totalCandidates - filesToScan.length) + (discovery.deadlineExceeded || discovery.cleanupFailed ? 1 : 0) + discovery.unexaminedDirectories;
46423
46546
  for (let index = 0;index < filesToScan.length; index++) {
46424
- if (_internals67.now() >= deadline) {
46547
+ if (_internals68.now() >= deadline) {
46425
46548
  for (const remaining of filesToScan.slice(index)) {
46426
46549
  recordIncompletePath(discovery.incompletePaths, scanDir, remaining, "deadline");
46427
46550
  }
@@ -46457,7 +46580,7 @@ var secretscan = createSwarmTool({
46457
46580
  }
46458
46581
  }
46459
46582
  if (index + 1 < filesToScan.length) {
46460
- await _internals67.yieldToEventLoop();
46583
+ await _internals68.yieldToEventLoop();
46461
46584
  }
46462
46585
  }
46463
46586
  allFindings.sort((a, b) => {
@@ -46520,7 +46643,7 @@ var secretscan = createSwarmTool({
46520
46643
  });
46521
46644
  async function runSecretscan(directory) {
46522
46645
  try {
46523
- const result = await _internals67.secretscan.execute({ directory }, {});
46646
+ const result = await _internals68.secretscan.execute({ directory }, {});
46524
46647
  const jsonStr = typeof result === "string" ? result : result.output;
46525
46648
  return JSON.parse(jsonStr);
46526
46649
  } catch (e) {
@@ -46571,10 +46694,10 @@ async function runSecretscanOnFiles(files, directory) {
46571
46694
  if (files.length > filesToScan.length) {
46572
46695
  recordIncompletePath(incompletePaths, canonicalRoot, canonicalRoot, "max_files");
46573
46696
  }
46574
- const deadline = _internals67.now() + SCAN_TIME_BUDGET_MS;
46575
- await _internals67.yieldToEventLoop();
46697
+ const deadline = _internals68.now() + SCAN_TIME_BUDGET_MS;
46698
+ await _internals68.yieldToEventLoop();
46576
46699
  for (let index = 0;index < filesToScan.length; index++) {
46577
- if (_internals67.now() >= deadline) {
46700
+ if (_internals68.now() >= deadline) {
46578
46701
  for (const remaining of filesToScan.slice(index)) {
46579
46702
  const remainingPath = path78.isAbsolute(remaining) ? path78.resolve(remaining) : path78.resolve(rawRoot, remaining);
46580
46703
  recordIncompletePath(incompletePaths, canonicalRoot, remainingPath, "deadline");
@@ -46601,7 +46724,7 @@ async function runSecretscanOnFiles(files, directory) {
46601
46724
  }
46602
46725
  let lstat3;
46603
46726
  try {
46604
- lstat3 = _internals67.lstatFile(resolvedPath);
46727
+ lstat3 = _internals68.lstatFile(resolvedPath);
46605
46728
  } catch (error2) {
46606
46729
  const err = error2;
46607
46730
  if (err.code === "ENOENT") {
@@ -46670,7 +46793,7 @@ async function runSecretscanOnFiles(files, directory) {
46670
46793
  assertNever(outcome);
46671
46794
  }
46672
46795
  if (index + 1 < filesToScan.length) {
46673
- await _internals67.yieldToEventLoop();
46796
+ await _internals68.yieldToEventLoop();
46674
46797
  }
46675
46798
  }
46676
46799
  findings.sort((a, b) => {
@@ -46700,7 +46823,7 @@ async function runSecretscanOnFiles(files, directory) {
46700
46823
  };
46701
46824
  }
46702
46825
  }
46703
- var _internals67 = {
46826
+ var _internals68 = {
46704
46827
  secretscan,
46705
46828
  runSecretscan,
46706
46829
  runSecretscanOnFiles,
@@ -46984,7 +47107,7 @@ async function buildImpactMapInternal(cwd) {
46984
47107
  }
46985
47108
  return impactMap;
46986
47109
  }
46987
- var _internals68 = {
47110
+ var _internals69 = {
46988
47111
  validateProjectRoot,
46989
47112
  normalizePath: normalizePath2,
46990
47113
  isCacheStale,
@@ -46999,8 +47122,8 @@ var _internals68 = {
46999
47122
  _clearGoModuleCache
47000
47123
  };
47001
47124
  async function buildImpactMap(cwd) {
47002
- const impactMap = await _internals68.buildImpactMapInternal(cwd);
47003
- await _internals68.saveImpactMap(cwd, impactMap);
47125
+ const impactMap = await _internals69.buildImpactMapInternal(cwd);
47126
+ await _internals69.saveImpactMap(cwd, impactMap);
47004
47127
  return impactMap;
47005
47128
  }
47006
47129
  async function loadImpactMap(cwd, options) {
@@ -47014,7 +47137,7 @@ async function loadImpactMap(cwd, options) {
47014
47137
  const hasValidValues = Object.values(map).every((v) => Array.isArray(v) && v.every((item) => typeof item === "string"));
47015
47138
  if (hasValidValues) {
47016
47139
  const generatedAt = new Date(data.generatedAt).getTime();
47017
- if (!_internals68.isCacheStale(map, generatedAt)) {
47140
+ if (!_internals69.isCacheStale(map, generatedAt)) {
47018
47141
  return map;
47019
47142
  }
47020
47143
  if (options?.skipRebuild) {
@@ -47034,13 +47157,13 @@ async function loadImpactMap(cwd, options) {
47034
47157
  if (options?.skipRebuild) {
47035
47158
  return {};
47036
47159
  }
47037
- return _internals68.buildImpactMap(cwd);
47160
+ return _internals69.buildImpactMap(cwd);
47038
47161
  }
47039
47162
  async function saveImpactMap(cwd, impactMap) {
47040
47163
  if (!path79.isAbsolute(cwd)) {
47041
47164
  throw new Error(`saveImpactMap requires an absolute project root path, got: "${cwd}"`);
47042
47165
  }
47043
- _internals68.validateProjectRoot(cwd);
47166
+ _internals69.validateProjectRoot(cwd);
47044
47167
  const cacheDir2 = path79.join(cwd, ".swarm", "cache");
47045
47168
  const cachePath = path79.join(cacheDir2, "impact-map.json");
47046
47169
  if (!fs33.existsSync(cacheDir2)) {
@@ -47064,7 +47187,7 @@ async function analyzeImpact(changedFiles, cwd, budget) {
47064
47187
  };
47065
47188
  }
47066
47189
  const validFiles = changedFiles.filter((f) => typeof f === "string" && f.length > 0 && !f.includes("\x00"));
47067
- const impactMap = await _internals68.loadImpactMap(cwd);
47190
+ const impactMap = await _internals69.loadImpactMap(cwd);
47068
47191
  const impactedTestsSet = new Set;
47069
47192
  const untestedFiles = [];
47070
47193
  let visitedCount = 0;
@@ -47341,7 +47464,7 @@ function batchAppendTestRuns(records, workingDir) {
47341
47464
  }
47342
47465
  const historyPath = getHistoryPath(workingDir);
47343
47466
  const historyDir = path80.dirname(historyPath);
47344
- _internals69.validateProjectRoot(workingDir);
47467
+ _internals70.validateProjectRoot(workingDir);
47345
47468
  if (!fs34.existsSync(historyDir)) {
47346
47469
  fs34.mkdirSync(historyDir, { recursive: true });
47347
47470
  }
@@ -47464,7 +47587,7 @@ function getAllHistory(workingDir) {
47464
47587
  records.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
47465
47588
  return records;
47466
47589
  }
47467
- var _internals69 = {
47590
+ var _internals70 = {
47468
47591
  validateProjectRoot
47469
47592
  };
47470
47593
 
@@ -47575,7 +47698,7 @@ var MAX_SAFE_TEST_FILES = 50;
47575
47698
  var MAX_SAFE_SOURCE_FILES = 1;
47576
47699
  async function estimateFanOut(sourceFiles, cwd) {
47577
47700
  try {
47578
- const impactMap = await _internals70.loadImpactMap(cwd, {
47701
+ const impactMap = await _internals71.loadImpactMap(cwd, {
47579
47702
  skipRebuild: true
47580
47703
  });
47581
47704
  const uniqueTestFiles = new Set;
@@ -47665,45 +47788,45 @@ function hasDevDependency(devDeps, ...patterns) {
47665
47788
  return hasPackageJsonDependency(devDeps, ...patterns);
47666
47789
  }
47667
47790
  function detectGoTest(cwd) {
47668
- return _internals70.existsSync(path82.join(cwd, "go.mod")) && _internals70.isCommandAvailable("go");
47791
+ return _internals71.existsSync(path82.join(cwd, "go.mod")) && _internals71.isCommandAvailable("go");
47669
47792
  }
47670
47793
  function detectJavaMaven(cwd) {
47671
- return _internals70.existsSync(path82.join(cwd, "pom.xml")) && _internals70.isCommandAvailable("mvn");
47794
+ return _internals71.existsSync(path82.join(cwd, "pom.xml")) && _internals71.isCommandAvailable("mvn");
47672
47795
  }
47673
47796
  function detectGradle(cwd) {
47674
- const hasBuildFile = _internals70.existsSync(path82.join(cwd, "build.gradle")) || _internals70.existsSync(path82.join(cwd, "build.gradle.kts"));
47675
- const hasGradlew = _internals70.existsSync(path82.join(cwd, "gradlew")) || _internals70.existsSync(path82.join(cwd, "gradlew.bat"));
47676
- return hasBuildFile && (hasGradlew || _internals70.isCommandAvailable("gradle"));
47797
+ const hasBuildFile = _internals71.existsSync(path82.join(cwd, "build.gradle")) || _internals71.existsSync(path82.join(cwd, "build.gradle.kts"));
47798
+ const hasGradlew = _internals71.existsSync(path82.join(cwd, "gradlew")) || _internals71.existsSync(path82.join(cwd, "gradlew.bat"));
47799
+ return hasBuildFile && (hasGradlew || _internals71.isCommandAvailable("gradle"));
47677
47800
  }
47678
47801
  function detectDotnetTest(cwd) {
47679
47802
  try {
47680
- const files = _internals70.readdirSync(cwd);
47803
+ const files = _internals71.readdirSync(cwd);
47681
47804
  const hasCsproj = files.some((f) => f.endsWith(".csproj"));
47682
- return hasCsproj && _internals70.isCommandAvailable("dotnet");
47805
+ return hasCsproj && _internals71.isCommandAvailable("dotnet");
47683
47806
  } catch {
47684
47807
  return false;
47685
47808
  }
47686
47809
  }
47687
47810
  function detectCTest(cwd) {
47688
- const hasSource = _internals70.existsSync(path82.join(cwd, "CMakeLists.txt"));
47689
- const hasBuildCache = _internals70.existsSync(path82.join(cwd, "CMakeCache.txt")) || _internals70.existsSync(path82.join(cwd, "build", "CMakeCache.txt"));
47690
- return (hasSource || hasBuildCache) && _internals70.isCommandAvailable("ctest");
47811
+ const hasSource = _internals71.existsSync(path82.join(cwd, "CMakeLists.txt"));
47812
+ const hasBuildCache = _internals71.existsSync(path82.join(cwd, "CMakeCache.txt")) || _internals71.existsSync(path82.join(cwd, "build", "CMakeCache.txt"));
47813
+ return (hasSource || hasBuildCache) && _internals71.isCommandAvailable("ctest");
47691
47814
  }
47692
47815
  function detectSwiftTest(cwd) {
47693
- return _internals70.existsSync(path82.join(cwd, "Package.swift")) && _internals70.isCommandAvailable("swift");
47816
+ return _internals71.existsSync(path82.join(cwd, "Package.swift")) && _internals71.isCommandAvailable("swift");
47694
47817
  }
47695
47818
  function detectDartTest(cwd) {
47696
- return _internals70.existsSync(path82.join(cwd, "pubspec.yaml")) && (_internals70.isCommandAvailable("dart") || _internals70.isCommandAvailable("flutter"));
47819
+ return _internals71.existsSync(path82.join(cwd, "pubspec.yaml")) && (_internals71.isCommandAvailable("dart") || _internals71.isCommandAvailable("flutter"));
47697
47820
  }
47698
47821
  function detectRSpec(cwd) {
47699
- const hasRSpecFile = _internals70.existsSync(path82.join(cwd, ".rspec"));
47700
- const hasGemfile = _internals70.existsSync(path82.join(cwd, "Gemfile"));
47701
- const hasSpecDir = _internals70.existsSync(path82.join(cwd, "spec"));
47822
+ const hasRSpecFile = _internals71.existsSync(path82.join(cwd, ".rspec"));
47823
+ const hasGemfile = _internals71.existsSync(path82.join(cwd, "Gemfile"));
47824
+ const hasSpecDir = _internals71.existsSync(path82.join(cwd, "spec"));
47702
47825
  const hasRSpec = hasRSpecFile || hasGemfile && hasSpecDir;
47703
- return hasRSpec && (_internals70.isCommandAvailable("bundle") || _internals70.isCommandAvailable("rspec"));
47826
+ return hasRSpec && (_internals71.isCommandAvailable("bundle") || _internals71.isCommandAvailable("rspec"));
47704
47827
  }
47705
47828
  function detectMinitest(cwd) {
47706
- return _internals70.existsSync(path82.join(cwd, "test")) && (_internals70.existsSync(path82.join(cwd, "Gemfile")) || _internals70.existsSync(path82.join(cwd, "Rakefile"))) && _internals70.isCommandAvailable("ruby");
47829
+ return _internals71.existsSync(path82.join(cwd, "test")) && (_internals71.existsSync(path82.join(cwd, "Gemfile")) || _internals71.existsSync(path82.join(cwd, "Rakefile"))) && _internals71.isCommandAvailable("ruby");
47707
47830
  }
47708
47831
  var DISPATCH_FRAMEWORK_MAP = {
47709
47832
  bun: "bun",
@@ -47794,8 +47917,8 @@ async function detectTestFramework(cwd) {
47794
47917
  const baseDir = cwd;
47795
47918
  try {
47796
47919
  const packageJsonPath = path82.join(baseDir, "package.json");
47797
- if (_internals70.existsSync(packageJsonPath)) {
47798
- const content = _internals70.readFileSync(packageJsonPath, "utf-8");
47920
+ if (_internals71.existsSync(packageJsonPath)) {
47921
+ const content = _internals71.readFileSync(packageJsonPath, "utf-8");
47799
47922
  const pkg = JSON.parse(content);
47800
47923
  const _deps = pkg.dependencies || {};
47801
47924
  const devDeps = pkg.devDependencies || {};
@@ -47814,7 +47937,7 @@ async function detectTestFramework(cwd) {
47814
47937
  return "jest";
47815
47938
  if (hasDevDependency(devDeps, "mocha", "@types/mocha"))
47816
47939
  return "mocha";
47817
- if (_internals70.existsSync(path82.join(baseDir, "bun.lockb")) || _internals70.existsSync(path82.join(baseDir, "bun.lock"))) {
47940
+ if (_internals71.existsSync(path82.join(baseDir, "bun.lockb")) || _internals71.existsSync(path82.join(baseDir, "bun.lock"))) {
47818
47941
  if (scripts.test?.includes("bun"))
47819
47942
  return "bun";
47820
47943
  }
@@ -47824,28 +47947,28 @@ async function detectTestFramework(cwd) {
47824
47947
  const pyprojectTomlPath = path82.join(baseDir, "pyproject.toml");
47825
47948
  const setupCfgPath = path82.join(baseDir, "setup.cfg");
47826
47949
  const requirementsTxtPath = path82.join(baseDir, "requirements.txt");
47827
- if (_internals70.existsSync(pyprojectTomlPath)) {
47828
- const content = _internals70.readFileSync(pyprojectTomlPath, "utf-8");
47950
+ if (_internals71.existsSync(pyprojectTomlPath)) {
47951
+ const content = _internals71.readFileSync(pyprojectTomlPath, "utf-8");
47829
47952
  if (content.includes("[tool.pytest"))
47830
47953
  return "pytest";
47831
47954
  if (content.includes("pytest"))
47832
47955
  return "pytest";
47833
47956
  }
47834
- if (_internals70.existsSync(setupCfgPath)) {
47835
- const content = _internals70.readFileSync(setupCfgPath, "utf-8");
47957
+ if (_internals71.existsSync(setupCfgPath)) {
47958
+ const content = _internals71.readFileSync(setupCfgPath, "utf-8");
47836
47959
  if (content.includes("[pytest]"))
47837
47960
  return "pytest";
47838
47961
  }
47839
- if (_internals70.existsSync(requirementsTxtPath)) {
47840
- const content = _internals70.readFileSync(requirementsTxtPath, "utf-8");
47962
+ if (_internals71.existsSync(requirementsTxtPath)) {
47963
+ const content = _internals71.readFileSync(requirementsTxtPath, "utf-8");
47841
47964
  if (content.includes("pytest"))
47842
47965
  return "pytest";
47843
47966
  }
47844
47967
  } catch {}
47845
47968
  try {
47846
47969
  const cargoTomlPath = path82.join(baseDir, "Cargo.toml");
47847
- if (_internals70.existsSync(cargoTomlPath)) {
47848
- const content = _internals70.readFileSync(cargoTomlPath, "utf-8");
47970
+ if (_internals71.existsSync(cargoTomlPath)) {
47971
+ const content = _internals71.readFileSync(cargoTomlPath, "utf-8");
47849
47972
  if (content.includes("[dev-dependencies]")) {
47850
47973
  if (content.includes("tokio") || content.includes("mockall") || content.includes("pretty_assertions")) {
47851
47974
  return "cargo";
@@ -47857,7 +47980,7 @@ async function detectTestFramework(cwd) {
47857
47980
  const pesterConfigPath = path82.join(baseDir, "pester.config.ps1");
47858
47981
  const pesterConfigJsonPath = path82.join(baseDir, "pester.config.ps1.json");
47859
47982
  const pesterPs1Path = path82.join(baseDir, "tests.ps1");
47860
- if (_internals70.existsSync(pesterConfigPath) || _internals70.existsSync(pesterConfigJsonPath) || _internals70.existsSync(pesterPs1Path)) {
47983
+ if (_internals71.existsSync(pesterConfigPath) || _internals71.existsSync(pesterConfigJsonPath) || _internals71.existsSync(pesterPs1Path)) {
47861
47984
  return "pester";
47862
47985
  }
47863
47986
  } catch {}
@@ -47885,12 +48008,12 @@ async function detectTestFramework(cwd) {
47885
48008
  return "none";
47886
48009
  }
47887
48010
  function detectPhpTest(cwd) {
47888
- if (_internals70.existsSync(path82.join(cwd, "artisan")) && _internals70.existsSync(path82.join(cwd, "composer.json"))) {
48011
+ if (_internals71.existsSync(path82.join(cwd, "artisan")) && _internals71.existsSync(path82.join(cwd, "composer.json"))) {
47889
48012
  return "php-artisan";
47890
48013
  }
47891
- if (_internals70.existsSync(path82.join(cwd, "Pest.php")))
48014
+ if (_internals71.existsSync(path82.join(cwd, "Pest.php")))
47892
48015
  return "pest";
47893
- if (_internals70.existsSync(path82.join(cwd, "phpunit.xml")) || _internals70.existsSync(path82.join(cwd, "phpunit.xml.dist"))) {
48016
+ if (_internals71.existsSync(path82.join(cwd, "phpunit.xml")) || _internals71.existsSync(path82.join(cwd, "phpunit.xml.dist"))) {
47894
48017
  return "phpunit";
47895
48018
  }
47896
48019
  return null;
@@ -48272,9 +48395,9 @@ function buildTestCommand(framework, scope, files, coverage, baseDir, bail) {
48272
48395
  case "swift-test":
48273
48396
  return ["swift", "test"];
48274
48397
  case "dart-test":
48275
- return _internals70.isCommandAvailable("flutter") ? ["flutter", "test", ...files] : ["dart", "test", ...files];
48398
+ return _internals71.isCommandAvailable("flutter") ? ["flutter", "test", ...files] : ["dart", "test", ...files];
48276
48399
  case "rspec": {
48277
- const args = _internals70.isCommandAvailable("bundle") ? ["bundle", "exec", "rspec"] : ["rspec"];
48400
+ const args = _internals71.isCommandAvailable("bundle") ? ["bundle", "exec", "rspec"] : ["rspec"];
48278
48401
  if (bail)
48279
48402
  args.push("--fail-fast");
48280
48403
  if (scope !== "all" && files.length > 0) {
@@ -48754,9 +48877,9 @@ async function runTests(framework, scope, files, coverage, timeout_ms, cwd, bail
48754
48877
  stderr: "pipe",
48755
48878
  cwd
48756
48879
  });
48757
- const timeoutPromise = new Promise((resolve26) => setTimeout(() => {
48880
+ const timeoutPromise = new Promise((resolve27) => setTimeout(() => {
48758
48881
  proc.kill();
48759
- resolve26(-1);
48882
+ resolve27(-1);
48760
48883
  }, timeout_ms));
48761
48884
  const [exitCode, stdoutResult, stderrResult] = await Promise.all([
48762
48885
  Promise.race([proc.exited, timeoutPromise]),
@@ -49287,7 +49410,7 @@ var test_runner = createSwarmTool({
49287
49410
  return JSON.stringify(errorResult, null, 2);
49288
49411
  }
49289
49412
  try {
49290
- const impactResult = await _internals70.analyzeImpact(sourceFiles, workingDir, MAX_SAFE_TEST_FILES);
49413
+ const impactResult = await _internals71.analyzeImpact(sourceFiles, workingDir, MAX_SAFE_TEST_FILES);
49291
49414
  if (impactResult.budgetExceeded) {
49292
49415
  const errorResult = {
49293
49416
  success: false,
@@ -49377,7 +49500,7 @@ var test_runner = createSwarmTool({
49377
49500
  return JSON.stringify(result, null, 2);
49378
49501
  }
49379
49502
  });
49380
- var _internals70 = {
49503
+ var _internals71 = {
49381
49504
  analyzeImpact,
49382
49505
  loadImpactMap,
49383
49506
  isCommandAvailable,
@@ -49479,9 +49602,9 @@ function getVersionFileVersion(dir) {
49479
49602
  async function runVersionCheck(dir, _timeoutMs) {
49480
49603
  const startTime = Date.now();
49481
49604
  try {
49482
- const packageVersion = _internals71.getPackageVersion(dir);
49483
- const changelogVersion = _internals71.getChangelogVersion(dir);
49484
- const versionFileVersion = _internals71.getVersionFileVersion(dir);
49605
+ const packageVersion = _internals72.getPackageVersion(dir);
49606
+ const changelogVersion = _internals72.getChangelogVersion(dir);
49607
+ const versionFileVersion = _internals72.getVersionFileVersion(dir);
49485
49608
  const versions = [];
49486
49609
  if (packageVersion)
49487
49610
  versions.push(`package.json: ${packageVersion}`);
@@ -49670,7 +49793,7 @@ async function runTestsCheck(_dir, scope, timeoutMs) {
49670
49793
  async function runSecretsCheck(dir, timeoutMs) {
49671
49794
  const startTime = Date.now();
49672
49795
  try {
49673
- const secretsPromise = _internals71.runSecretscan(dir);
49796
+ const secretsPromise = _internals72.runSecretscan(dir);
49674
49797
  const timeoutPromise = new Promise((_, reject) => {
49675
49798
  setTimeout(() => {
49676
49799
  reject(new Error(`Secrets check timed out after ${timeoutMs}ms`));
@@ -49892,7 +50015,7 @@ async function runPreflight(dir, phase, config) {
49892
50015
  const reportId = `preflight-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
49893
50016
  let validatedDir;
49894
50017
  try {
49895
- validatedDir = _internals71.validateDirectoryPath(dir);
50018
+ validatedDir = _internals72.validateDirectoryPath(dir);
49896
50019
  } catch (error2) {
49897
50020
  return {
49898
50021
  id: reportId,
@@ -49912,7 +50035,7 @@ async function runPreflight(dir, phase, config) {
49912
50035
  }
49913
50036
  let validatedTimeout;
49914
50037
  try {
49915
- validatedTimeout = _internals71.validateTimeout(config?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
50038
+ validatedTimeout = _internals72.validateTimeout(config?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
49916
50039
  } catch (error2) {
49917
50040
  return {
49918
50041
  id: reportId,
@@ -49953,12 +50076,12 @@ async function runPreflight(dir, phase, config) {
49953
50076
  });
49954
50077
  const checks = [];
49955
50078
  log("[Preflight] Running lint check...");
49956
- const lintResult = await _internals71.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
50079
+ const lintResult = await _internals72.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
49957
50080
  checks.push(lintResult);
49958
50081
  log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`);
49959
50082
  if (!cfg.skipTests) {
49960
50083
  log("[Preflight] Running tests check...");
49961
- const testsResult = await _internals71.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
50084
+ const testsResult = await _internals72.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
49962
50085
  checks.push(testsResult);
49963
50086
  log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`);
49964
50087
  } else {
@@ -49970,7 +50093,7 @@ async function runPreflight(dir, phase, config) {
49970
50093
  }
49971
50094
  if (!cfg.skipSecrets) {
49972
50095
  log("[Preflight] Running secrets check...");
49973
- const secretsResult = await _internals71.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
50096
+ const secretsResult = await _internals72.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
49974
50097
  checks.push(secretsResult);
49975
50098
  log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`);
49976
50099
  } else {
@@ -49982,7 +50105,7 @@ async function runPreflight(dir, phase, config) {
49982
50105
  }
49983
50106
  if (!cfg.skipEvidence) {
49984
50107
  log("[Preflight] Running evidence check...");
49985
- const evidenceResult = await _internals71.runEvidenceCheck(validatedDir);
50108
+ const evidenceResult = await _internals72.runEvidenceCheck(validatedDir);
49986
50109
  checks.push(evidenceResult);
49987
50110
  log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`);
49988
50111
  } else {
@@ -49993,12 +50116,12 @@ async function runPreflight(dir, phase, config) {
49993
50116
  });
49994
50117
  }
49995
50118
  log("[Preflight] Running requirement coverage check...");
49996
- const reqCoverageResult = await _internals71.runRequirementCoverageCheck(validatedDir, phase);
50119
+ const reqCoverageResult = await _internals72.runRequirementCoverageCheck(validatedDir, phase);
49997
50120
  checks.push(reqCoverageResult);
49998
50121
  log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`);
49999
50122
  if (!cfg.skipVersion) {
50000
50123
  log("[Preflight] Running version check...");
50001
- const versionResult = await _internals71.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
50124
+ const versionResult = await _internals72.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
50002
50125
  checks.push(versionResult);
50003
50126
  log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`);
50004
50127
  } else {
@@ -50061,10 +50184,10 @@ function formatPreflightMarkdown(report) {
50061
50184
  async function handlePreflightCommand(directory, _args) {
50062
50185
  const plan = await loadPlan(directory);
50063
50186
  const phase = plan?.current_phase ?? 1;
50064
- const report = await _internals71.runPreflight(directory, phase);
50065
- return _internals71.formatPreflightMarkdown(report);
50187
+ const report = await _internals72.runPreflight(directory, phase);
50188
+ return _internals72.formatPreflightMarkdown(report);
50066
50189
  }
50067
- var _internals71 = {
50190
+ var _internals72 = {
50068
50191
  runPreflight,
50069
50192
  formatPreflightMarkdown,
50070
50193
  handlePreflightCommand,
@@ -50347,13 +50470,13 @@ class CircuitBreaker {
50347
50470
  if (this.config.callTimeoutMs <= 0) {
50348
50471
  return fn();
50349
50472
  }
50350
- return new Promise((resolve27, reject) => {
50473
+ return new Promise((resolve28, reject) => {
50351
50474
  const timeout = setTimeout(() => {
50352
50475
  reject(new Error(`Call timeout after ${this.config.callTimeoutMs}ms`));
50353
50476
  }, this.config.callTimeoutMs);
50354
50477
  fn().then((result) => {
50355
50478
  clearTimeout(timeout);
50356
- resolve27(result);
50479
+ resolve28(result);
50357
50480
  }).catch((error2) => {
50358
50481
  clearTimeout(timeout);
50359
50482
  reject(error2);
@@ -50652,7 +50775,7 @@ class AutomationQueue {
50652
50775
 
50653
50776
  // src/background/worker.ts
50654
50777
  function sleep(ms) {
50655
- return new Promise((resolve27) => setTimeout(resolve27, ms));
50778
+ return new Promise((resolve28) => setTimeout(resolve28, ms));
50656
50779
  }
50657
50780
 
50658
50781
  class WorkerManager {
@@ -51063,7 +51186,7 @@ function pruneOldResetBackups(backupsRoot, warnings) {
51063
51186
  }
51064
51187
 
51065
51188
  // src/commands/reset.ts
51066
- var _internals72 = {
51189
+ var _internals73 = {
51067
51190
  backupSwarmStateBeforeReset
51068
51191
  };
51069
51192
  async function handleResetCommand(directory, args) {
@@ -51096,11 +51219,13 @@ async function handleResetCommand(directory, args) {
51096
51219
  "events.jsonl",
51097
51220
  "run-memory.jsonl",
51098
51221
  "reproduction.json",
51099
- "issue-publication.json"
51222
+ "issue-publication.json",
51223
+ "recurrence-sweep.json",
51224
+ "implementation-review.json"
51100
51225
  ];
51101
51226
  const results = [];
51102
51227
  try {
51103
- const backup = _internals72.backupSwarmStateBeforeReset(directory, "reset", [
51228
+ const backup = _internals73.backupSwarmStateBeforeReset(directory, "reset", [
51104
51229
  ...filesToReset,
51105
51230
  "summaries"
51106
51231
  ]);
@@ -51210,7 +51335,7 @@ function clearTrajectoryStep(sessionId) {
51210
51335
  }
51211
51336
 
51212
51337
  // src/commands/reset-session.ts
51213
- var _internals73 = {
51338
+ var _internals74 = {
51214
51339
  cleanupOrphanedBranches,
51215
51340
  backupSwarmStateBeforeReset
51216
51341
  };
@@ -51222,7 +51347,7 @@ function errorMessage(err) {
51222
51347
  async function handleResetSessionCommand(directory, _args) {
51223
51348
  const results = [];
51224
51349
  try {
51225
- const backup = _internals73.backupSwarmStateBeforeReset(directory, "reset-session", ["session"]);
51350
+ const backup = _internals74.backupSwarmStateBeforeReset(directory, "reset-session", ["session"]);
51226
51351
  if (backup.backupDir && backup.copied.length > 0) {
51227
51352
  const rel = path86.relative(directory, backup.backupDir);
51228
51353
  results.push(`\uD83D\uDCE6 Backed up session state to ${rel}/ (restore by copying files back into .swarm/session/)`);
@@ -51289,7 +51414,7 @@ async function handleResetSessionCommand(directory, _args) {
51289
51414
  results.push(`\u26A0\uFE0F Failed to remove .swarm-worktrees/: ${errorMessage(err)}`);
51290
51415
  }
51291
51416
  try {
51292
- const branchResult = await _internals73.cleanupOrphanedBranches(directory, []);
51417
+ const branchResult = await _internals74.cleanupOrphanedBranches(directory, []);
51293
51418
  if (branchResult.removed.length > 0) {
51294
51419
  results.push(`\u2705 Removed ${branchResult.removed.length} orphan swarm-lane branch(es)`);
51295
51420
  }
@@ -51448,7 +51573,7 @@ function resolveReceiptsDir(directory) {
51448
51573
  function resolveReceiptIndexPath(directory) {
51449
51574
  return path88.join(resolveReceiptsDir(directory), "index.json");
51450
51575
  }
51451
- var _internals74 = {
51576
+ var _internals75 = {
51452
51577
  openSync: fs41.openSync,
51453
51578
  lstatBigIntSync: (path89) => fs41.lstatSync(path89, { bigint: true }),
51454
51579
  fstatBigIntSync: (fd) => fs41.fstatSync(fd, { bigint: true })
@@ -51460,7 +51585,7 @@ function pathsEqual(left, right) {
51460
51585
  }
51461
51586
  function captureCanonicalDirectory(directory, label, expected) {
51462
51587
  const resolved = path88.resolve(directory);
51463
- const stat6 = _internals74.lstatBigIntSync(resolved);
51588
+ const stat6 = _internals75.lstatBigIntSync(resolved);
51464
51589
  if (!stat6.isDirectory() || stat6.isSymbolicLink()) {
51465
51590
  throw new Error(`${label} must be a real directory`);
51466
51591
  }
@@ -51546,7 +51671,7 @@ function assertDirectReceiptFile(context, filePath, mustExist) {
51546
51671
  throw new Error("review receipt file escapes its expected directory");
51547
51672
  }
51548
51673
  try {
51549
- const stat6 = _internals74.lstatBigIntSync(resolved);
51674
+ const stat6 = _internals75.lstatBigIntSync(resolved);
51550
51675
  if (!stat6.isFile() || stat6.isSymbolicLink()) {
51551
51676
  throw new Error("review receipt path must be a real file");
51552
51677
  }
@@ -51570,7 +51695,7 @@ function readReviewReceiptText(directory, receiptPath, maxBytes = 1048576) {
51570
51695
  const resolved = assertDirectReceiptFile(context, receiptPath, true);
51571
51696
  if (path88.extname(resolved) !== ".json")
51572
51697
  return null;
51573
- const pathBeforeOpen = _internals74.lstatBigIntSync(resolved);
51698
+ const pathBeforeOpen = _internals75.lstatBigIntSync(resolved);
51574
51699
  if (!pathBeforeOpen.isFile() || pathBeforeOpen.isSymbolicLink() || pathBeforeOpen.size < 0n || pathBeforeOpen.size > BigInt(maxBytes)) {
51575
51700
  return null;
51576
51701
  }
@@ -51578,10 +51703,10 @@ function readReviewReceiptText(directory, receiptPath, maxBytes = 1048576) {
51578
51703
  if (!pathsEqual(canonicalBeforeOpen, resolved))
51579
51704
  return null;
51580
51705
  assertReceiptContextCurrent(context);
51581
- descriptor = _internals74.openSync(canonicalBeforeOpen, "r");
51582
- const openedBeforeRead = _internals74.fstatBigIntSync(descriptor);
51706
+ descriptor = _internals75.openSync(canonicalBeforeOpen, "r");
51707
+ const openedBeforeRead = _internals75.fstatBigIntSync(descriptor);
51583
51708
  assertReceiptContextCurrent(context);
51584
- const pathAfterOpen = _internals74.lstatBigIntSync(resolved);
51709
+ const pathAfterOpen = _internals75.lstatBigIntSync(resolved);
51585
51710
  const canonicalAfterOpen = fs41.realpathSync(resolved);
51586
51711
  if (!openedBeforeRead.isFile() || openedBeforeRead.size < 0n || openedBeforeRead.size > BigInt(maxBytes) || !sameFileSnapshot2(pathBeforeOpen, openedBeforeRead) || !sameFileSnapshot2(openedBeforeRead, pathAfterOpen) || !pathsEqual(canonicalBeforeOpen, canonicalAfterOpen)) {
51587
51712
  return null;
@@ -51594,9 +51719,9 @@ function readReviewReceiptText(directory, receiptPath, maxBytes = 1048576) {
51594
51719
  break;
51595
51720
  bytesRead += count;
51596
51721
  }
51597
- const openedAfterRead = _internals74.fstatBigIntSync(descriptor);
51722
+ const openedAfterRead = _internals75.fstatBigIntSync(descriptor);
51598
51723
  assertReceiptContextCurrent(context);
51599
- const pathAfterRead = _internals74.lstatBigIntSync(resolved);
51724
+ const pathAfterRead = _internals75.lstatBigIntSync(resolved);
51600
51725
  const canonicalAfterRead = fs41.realpathSync(resolved);
51601
51726
  if (bytesRead !== buffer.length || !sameFileSnapshot2(openedBeforeRead, openedAfterRead) || !sameFileSnapshot2(openedAfterRead, pathAfterRead) || !pathsEqual(canonicalBeforeOpen, canonicalAfterRead)) {
51602
51727
  return null;
@@ -52140,7 +52265,7 @@ var HEAD_TIMEOUT_MS = 5000;
52140
52265
  var HEAD_OUTPUT_BYTES = 256;
52141
52266
  var HEAD_SHA_PATTERN = /^[0-9a-f]{40,64}$/i;
52142
52267
  var REVIEWER_TASK_SCOPE_DESCRIPTION = "reviewer-task-files-v1";
52143
- var _internals75 = {
52268
+ var _internals76 = {
52144
52269
  spawn: child_process6.spawn,
52145
52270
  realpath: fs42.promises.realpath,
52146
52271
  lstatBigInt: (path90) => fs42.promises.lstat(path90, { bigint: true }),
@@ -52180,7 +52305,7 @@ async function missingPathParentIsContained(root, absolutePath2) {
52180
52305
  let current = path89.dirname(absolutePath2);
52181
52306
  for (;; ) {
52182
52307
  try {
52183
- const canonical = await _internals75.realpath(current);
52308
+ const canonical = await _internals76.realpath(current);
52184
52309
  return samePath2(root, canonical) || isContained2(root, canonical);
52185
52310
  } catch (error2) {
52186
52311
  if (error2.code !== "ENOENT")
@@ -52207,13 +52332,13 @@ async function resolveHeadSha(directory) {
52207
52332
  let child;
52208
52333
  let timeoutHandle;
52209
52334
  try {
52210
- child = _internals75.spawn("git", ["rev-parse", "--verify", "HEAD"], {
52335
+ child = _internals76.spawn("git", ["rev-parse", "--verify", "HEAD"], {
52211
52336
  cwd: directory,
52212
52337
  stdio: ["ignore", "pipe", "ignore"],
52213
52338
  timeout: HEAD_TIMEOUT_MS,
52214
52339
  windowsHide: true
52215
52340
  });
52216
- return await new Promise((resolve30) => {
52341
+ return await new Promise((resolve31) => {
52217
52342
  let settled = false;
52218
52343
  let stdoutBytes = 0;
52219
52344
  const stdoutChunks = [];
@@ -52223,7 +52348,7 @@ async function resolveHeadSha(directory) {
52223
52348
  settled = true;
52224
52349
  if (timeoutHandle !== undefined)
52225
52350
  clearTimeout(timeoutHandle);
52226
- resolve30(value);
52351
+ resolve31(value);
52227
52352
  };
52228
52353
  const killAndFail = () => {
52229
52354
  try {
@@ -52270,7 +52395,7 @@ async function buildReviewerTaskScope(directory, modifiedFiles, maxBytes = DEFAU
52270
52395
  let realRoot;
52271
52396
  try {
52272
52397
  lexicalRoot = path89.resolve(directory);
52273
- realRoot = await _internals75.realpath(lexicalRoot);
52398
+ realRoot = await _internals76.realpath(lexicalRoot);
52274
52399
  } catch {
52275
52400
  return null;
52276
52401
  }
@@ -52311,7 +52436,7 @@ async function buildReviewerTaskScope(directory, modifiedFiles, maxBytes = DEFAU
52311
52436
  for (const candidate of ordered) {
52312
52437
  let before;
52313
52438
  try {
52314
- before = await _internals75.lstatBigInt(candidate.absolutePath);
52439
+ before = await _internals76.lstatBigInt(candidate.absolutePath);
52315
52440
  } catch (error2) {
52316
52441
  if (error2.code === "ENOENT") {
52317
52442
  if (!await missingPathParentIsContained(realRoot, candidate.absolutePath)) {
@@ -52330,7 +52455,7 @@ async function buildReviewerTaskScope(directory, modifiedFiles, maxBytes = DEFAU
52330
52455
  return null;
52331
52456
  let realCandidate;
52332
52457
  try {
52333
- realCandidate = await _internals75.realpath(candidate.absolutePath);
52458
+ realCandidate = await _internals76.realpath(candidate.absolutePath);
52334
52459
  } catch {
52335
52460
  return null;
52336
52461
  }
@@ -52342,15 +52467,15 @@ async function buildReviewerTaskScope(directory, modifiedFiles, maxBytes = DEFAU
52342
52467
  let bytes;
52343
52468
  let openedBefore;
52344
52469
  try {
52345
- handle = await _internals75.open(realCandidate, "r");
52346
- openedBefore = await _internals75.fileHandleStatBigInt(handle);
52347
- const canonicalAfterOpen = await _internals75.realpath(candidate.absolutePath);
52470
+ handle = await _internals76.open(realCandidate, "r");
52471
+ openedBefore = await _internals76.fileHandleStatBigInt(handle);
52472
+ const canonicalAfterOpen = await _internals76.realpath(candidate.absolutePath);
52348
52473
  if (!openedBefore.isFile() || !sameFileSnapshot3(before, openedBefore) || !samePath2(realCandidate, canonicalAfterOpen) || !isContained2(realRoot, canonicalAfterOpen)) {
52349
52474
  return null;
52350
52475
  }
52351
52476
  bytes = await readBoundedHandle(handle, maxBytes - totalBytes);
52352
- const openedAfter = await _internals75.fileHandleStatBigInt(handle);
52353
- const canonicalAfterRead = await _internals75.realpath(candidate.absolutePath);
52477
+ const openedAfter = await _internals76.fileHandleStatBigInt(handle);
52478
+ const canonicalAfterRead = await _internals76.realpath(candidate.absolutePath);
52354
52479
  if (!sameFileSnapshot3(openedBefore, openedAfter) || !samePath2(realCandidate, canonicalAfterRead) || !isContained2(realRoot, canonicalAfterRead) || BigInt(bytes.byteLength) !== openedBefore.size) {
52355
52480
  return null;
52356
52481
  }
@@ -52374,8 +52499,8 @@ async function buildReviewerTaskScope(directory, modifiedFiles, maxBytes = DEFAU
52374
52499
  }
52375
52500
  for (const stable of stableFiles) {
52376
52501
  try {
52377
- const current = await _internals75.lstatBigInt(stable.absolutePath);
52378
- const canonical = await _internals75.realpath(stable.absolutePath);
52502
+ const current = await _internals76.lstatBigInt(stable.absolutePath);
52503
+ const canonical = await _internals76.realpath(stable.absolutePath);
52379
52504
  if (!current.isFile() || current.isSymbolicLink() || !sameFileSnapshot3(stable.stat, current) || !samePath2(stable.canonicalPath, canonical) || !isContained2(realRoot, canonical)) {
52380
52505
  return null;
52381
52506
  }
@@ -52385,7 +52510,7 @@ async function buildReviewerTaskScope(directory, modifiedFiles, maxBytes = DEFAU
52385
52510
  }
52386
52511
  for (const deletedPath of deletedPaths) {
52387
52512
  try {
52388
- await _internals75.lstatBigInt(deletedPath);
52513
+ await _internals76.lstatBigInt(deletedPath);
52389
52514
  return null;
52390
52515
  } catch (error2) {
52391
52516
  if (error2.code !== "ENOENT" || !await missingPathParentIsContained(realRoot, deletedPath)) {
@@ -52548,7 +52673,7 @@ function parseReviewerOutput(text, options = {}) {
52548
52673
  outputMode: "legacy"
52549
52674
  };
52550
52675
  }
52551
- var _internals76 = {
52676
+ var _internals77 = {
52552
52677
  delegationEnd: telemetry.delegationEnd,
52553
52678
  resolveReviewerTaskScope,
52554
52679
  buildReviewerTaskScope,
@@ -52754,7 +52879,7 @@ function scopeFreshnessMismatches(reviewed, current) {
52754
52879
  }
52755
52880
  function createScopeVerifier(input, reviewed, maxBytes) {
52756
52881
  return async () => {
52757
- const current = await _internals77.collectReviewDiff({
52882
+ const current = await _internals78.collectReviewDiff({
52758
52883
  directory: input.directory,
52759
52884
  selector: input.selector,
52760
52885
  maxBytes
@@ -52763,7 +52888,7 @@ function createScopeVerifier(input, reviewed, maxBytes) {
52763
52888
  };
52764
52889
  }
52765
52890
  async function stalePersistenceResult(input, maxBytes, message, modelCalls) {
52766
- const current = await _internals77.collectReviewDiff({
52891
+ const current = await _internals78.collectReviewDiff({
52767
52892
  directory: input.directory,
52768
52893
  selector: input.selector,
52769
52894
  maxBytes
@@ -53142,7 +53267,7 @@ async function persistErrorResult(input, diff, result, error2, dispatches, promp
53142
53267
  evidence2.review.error = error2;
53143
53268
  addCost(evidence2, dispatches);
53144
53269
  try {
53145
- result.evidencePath = await _internals77.persistEvidence(input.directory, evidence2);
53270
+ result.evidencePath = await _internals78.persistEvidence(input.directory, evidence2);
53146
53271
  } catch {
53147
53272
  if (input.config.final_review.mode === "gate") {
53148
53273
  result.blocked = true;
@@ -53158,7 +53283,7 @@ async function runReviewEngine(input) {
53158
53283
  const gateMode = input.config.final_review.mode === "gate";
53159
53284
  const maxBytes = input.trigger === "task_completion" ? input.config.max_diff_kb * 1024 : input.config.final_review.max_diff_bytes;
53160
53285
  const timeoutMs = input.trigger === "task_completion" ? input.config.timeout_ms : input.config.final_review.timeout_ms;
53161
- const diff = await _internals77.collectReviewDiff({
53286
+ const diff = await _internals78.collectReviewDiff({
53162
53287
  directory: input.directory,
53163
53288
  selector: input.selector,
53164
53289
  maxBytes
@@ -53172,7 +53297,7 @@ async function runReviewEngine(input) {
53172
53297
  const evidence3 = baseEvidence(input, diff, "clean");
53173
53298
  let evidencePath2;
53174
53299
  try {
53175
- evidencePath2 = await _internals77.persistEvidence(input.directory, evidence3, { verifyCurrent: createScopeVerifier(input, diff, maxBytes) });
53300
+ evidencePath2 = await _internals78.persistEvidence(input.directory, evidence3, { verifyCurrent: createScopeVerifier(input, diff, maxBytes) });
53176
53301
  } catch (error2) {
53177
53302
  if (error2 instanceof ReviewScopeStaleError) {
53178
53303
  return stalePersistenceResult(input, maxBytes, "Review scope changed before clean evidence could be committed.", 0);
@@ -53194,7 +53319,7 @@ async function runReviewEngine(input) {
53194
53319
  phase: input.phase
53195
53320
  });
53196
53321
  if (input.phase !== undefined && (input.trigger === "phase_completion" || input.trigger === "plan_completion")) {
53197
- const existing = _internals77.readPhaseEvidence(input.directory, input.phase);
53322
+ const existing = _internals78.readPhaseEvidence(input.directory, input.phase);
53198
53323
  const integrity = existing ? validateAutoReviewEvidenceIntegrity(input.directory, existing, {
53199
53324
  scopeHash: diff.scopeHash,
53200
53325
  phase: input.phase,
@@ -53320,7 +53445,7 @@ async function runReviewEngine(input) {
53320
53445
  validation: byId.get(finding.finding_id)
53321
53446
  }));
53322
53447
  }
53323
- const currentScope = await _internals77.collectReviewDiff({
53448
+ const currentScope = await _internals78.collectReviewDiff({
53324
53449
  directory: input.directory,
53325
53450
  selector: input.selector,
53326
53451
  maxBytes
@@ -53399,7 +53524,7 @@ async function runReviewEngine(input) {
53399
53524
  findingValidations: findings.map((finding) => finding.validation).filter((item) => Boolean(item))
53400
53525
  });
53401
53526
  receiptId = receipt.id;
53402
- receiptPath = await _internals77.persistReceipt(input.directory, receipt, {
53527
+ receiptPath = await _internals78.persistReceipt(input.directory, receipt, {
53403
53528
  verifyCurrent: createScopeVerifier(input, diff, maxBytes)
53404
53529
  });
53405
53530
  evidence2.receipt_path = receiptPath;
@@ -53429,7 +53554,7 @@ async function runReviewEngine(input) {
53429
53554
  }
53430
53555
  let evidencePath;
53431
53556
  try {
53432
- evidencePath = await _internals77.persistEvidence(input.directory, evidence2, {
53557
+ evidencePath = await _internals78.persistEvidence(input.directory, evidence2, {
53433
53558
  verifyCurrent: createScopeVerifier(input, diff, maxBytes)
53434
53559
  });
53435
53560
  } catch (error2) {
@@ -53466,7 +53591,7 @@ async function runReviewEngine(input) {
53466
53591
  input.injectAdvisory?.(input.sessionID, advisoryMessage(input, result));
53467
53592
  return result;
53468
53593
  }
53469
- var _internals77 = {
53594
+ var _internals78 = {
53470
53595
  collectReviewDiff,
53471
53596
  persistEvidence: persistAutoReviewEvidence,
53472
53597
  persistReceipt: persistReviewReceipt,
@@ -53737,7 +53862,7 @@ async function handleReviewCommand(ctx) {
53737
53862
  } catch (error2) {
53738
53863
  return `Review configuration error: ${error2 instanceof Error ? error2.message : String(error2)}`;
53739
53864
  }
53740
- const result = await _internals78.runReviewEngine({
53865
+ const result = await _internals79.runReviewEngine({
53741
53866
  directory: ctx.directory,
53742
53867
  sessionID: ctx.sessionID,
53743
53868
  trigger: "manual",
@@ -53751,10 +53876,10 @@ async function handleReviewCommand(ctx) {
53751
53876
  validatorModel,
53752
53877
  validatorFallbackModels
53753
53878
  });
53754
- const evidence2 = _internals78.readEvidence(result.evidencePath, ctx.directory);
53879
+ const evidence2 = _internals79.readEvidence(result.evidencePath, ctx.directory);
53755
53880
  return parsed.json ? renderJson(result, evidence2, parsed.selector) : renderHuman(result, evidence2, parsed.selector);
53756
53881
  }
53757
- var _internals78 = {
53882
+ var _internals79 = {
53758
53883
  runReviewEngine,
53759
53884
  readEvidence
53760
53885
  };
@@ -54000,7 +54125,7 @@ async function handleRollbackCommand(directory, args) {
54000
54125
  // src/commands/sdd.ts
54001
54126
  import * as fs47 from "fs";
54002
54127
  import * as path94 from "path";
54003
- var _internals79 = {
54128
+ var _internals80 = {
54004
54129
  writeProjectedSpecSync
54005
54130
  };
54006
54131
  var SWARM_SPEC_REL = path94.join(".swarm", "spec.md");
@@ -54023,6 +54148,9 @@ Spec-Kit SDD support:
54023
54148
  - detects .specify/ marker + specs/NNN-feature-name/spec.md layout
54024
54149
  - projects a single Spec-Kit feature into .swarm/spec.md via /swarm sdd project
54025
54150
  - use --source speckit or --source openspec to disambiguate when both are present`;
54151
+ function allowedMutationsFor(source) {
54152
+ return source === "swarm" ? ["create", "refine", "archive"] : ["none (read-only input; refine in the source tool)"];
54153
+ }
54026
54154
  function isUnsafeId(value) {
54027
54155
  return value.includes("/") || value.includes("\\") || value.includes("..") || value.includes("[") || value.includes("]") || containsControlChars(value);
54028
54156
  }
@@ -54170,7 +54298,8 @@ ${speckitDetection.features.map((f) => `- ${f.featureId}`).join(`
54170
54298
  "### Effective Spec",
54171
54299
  status.effectiveSpec ? `- source: ${status.effectiveSpec.source}
54172
54300
  - hash: ${status.effectiveSpec.hash}
54173
- - sources: ${status.effectiveSpec.sourcePaths.length}` : "- none",
54301
+ - path(s): ${status.effectiveSpec.sourcePaths.join(", ")}
54302
+ - allowed mutations: ${allowedMutationsFor(status.effectiveSpec.source).join(", ")}` : "- none",
54174
54303
  status.errors.length > 0 ? `
54175
54304
  ### Errors
54176
54305
  ${formatList(status.errors)}` : "",
@@ -54396,7 +54525,7 @@ ${USAGE12}`;
54396
54525
 
54397
54526
  ${USAGE12}`;
54398
54527
  }
54399
- const result2 = _internals79.writeProjectedSpecSync(directory, {
54528
+ const result2 = _internals80.writeProjectedSpecSync(directory, {
54400
54529
  source: "speckit",
54401
54530
  feature: resolution.feature,
54402
54531
  dryRun: parsed.dryRun,
@@ -54454,7 +54583,7 @@ ${formatList(result2.projection.warnings)}` : ""
54454
54583
  ].join(`
54455
54584
  `);
54456
54585
  }
54457
- const result = _internals79.writeProjectedSpecSync(directory, {
54586
+ const result = _internals80.writeProjectedSpecSync(directory, {
54458
54587
  changeId: parsed.changeId,
54459
54588
  dryRun: parsed.dryRun,
54460
54589
  overwrite: parsed.overwrite
@@ -54535,7 +54664,7 @@ async function handleSimulateCommand(directory, args) {
54535
54664
  }
54536
54665
  let darkMatterPairs;
54537
54666
  try {
54538
- darkMatterPairs = await _internals41.detectDarkMatter(directory, options);
54667
+ darkMatterPairs = await _internals42.detectDarkMatter(directory, options);
54539
54668
  } catch (err) {
54540
54669
  const errMsg = err instanceof Error ? err.message : String(err);
54541
54670
  return `## Simulate Report
@@ -54693,7 +54822,7 @@ function writeFileFsyncedThenRename(tempPath, targetPath, data) {
54693
54822
  throw err;
54694
54823
  }
54695
54824
  }
54696
- var _internals80 = {
54825
+ var _internals81 = {
54697
54826
  withEvidenceLock,
54698
54827
  writeFileFsyncedThenRename,
54699
54828
  writeFileSync: writeFileSyncAsync,
@@ -54712,7 +54841,7 @@ async function appendEvent(directory, eventInput) {
54712
54841
  throw new Error(`invalid candidate id: ${eventInput.candidateId}`);
54713
54842
  }
54714
54843
  const filePath = ledgerPath(directory, eventInput.skillSlug, eventInput.candidateId);
54715
- return _internals80.withEvidenceLock(directory, path95.join(".swarm", "evolution", "skills", eventInput.skillSlug, eventInput.candidateId, "lifecycle.jsonl"), "skill-opt-ledger", "append-skill-opt-event", async () => {
54844
+ return _internals81.withEvidenceLock(directory, path95.join(".swarm", "evolution", "skills", eventInput.skillSlug, eventInput.candidateId, "lifecycle.jsonl"), "skill-opt-ledger", "append-skill-opt-event", async () => {
54716
54845
  ensureCandidateDir(directory, eventInput.skillSlug, eventInput.candidateId);
54717
54846
  const existing = existsSync52(filePath) ? readFileSync39(filePath, "utf8") : "";
54718
54847
  const events = parseEventsFromText(existing);
@@ -54744,8 +54873,8 @@ async function appendEvent(directory, eventInput) {
54744
54873
  const validContent = events.map((e) => JSON.stringify(e)).join(`
54745
54874
  `) + (events.length > 0 ? `
54746
54875
  ` : "");
54747
- _internals80.writeFileFsyncedThenRename(tempPath, filePath, validContent + line);
54748
- const verify = parseEventsFromText(_internals80.readFileSync(filePath, "utf8"));
54876
+ _internals81.writeFileFsyncedThenRename(tempPath, filePath, validContent + line);
54877
+ const verify = parseEventsFromText(_internals81.readFileSync(filePath, "utf8"));
54749
54878
  const last = verify.length > 0 ? verify[verify.length - 1] : null;
54750
54879
  if (!last || last.seq !== event.seq || last.hashAfter !== event.hashAfter) {
54751
54880
  throw new Error(`skill-opt ledger append verification failed for candidate ${event.candidateId} seq ${event.seq}`);
@@ -54849,7 +54978,7 @@ function writeStateProjection(directory, skillSlug, candidateId2, replay) {
54849
54978
  updatedAt: new Date().toISOString()
54850
54979
  };
54851
54980
  const tempPath = `${target}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`;
54852
- _internals80.writeFileFsyncedThenRename(tempPath, target, `${JSON.stringify(projection, null, 2)}
54981
+ _internals81.writeFileFsyncedThenRename(tempPath, target, `${JSON.stringify(projection, null, 2)}
54853
54982
  `);
54854
54983
  }
54855
54984
  function writeArtifact(directory, skillSlug, candidateId2, fileName, content) {
@@ -54857,7 +54986,7 @@ function writeArtifact(directory, skillSlug, candidateId2, fileName, content) {
54857
54986
  const dir = ensureCandidateDir(directory, skillSlug, candidateId2);
54858
54987
  const target = path95.join(dir, fileName);
54859
54988
  const tempPath = `${target}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`;
54860
- _internals80.writeFileFsyncedThenRename(tempPath, target, content);
54989
+ _internals81.writeFileFsyncedThenRename(tempPath, target, content);
54861
54990
  return target;
54862
54991
  }
54863
54992
  function readArtifact(directory, skillSlug, candidateId2, fileName) {
@@ -54950,16 +55079,16 @@ function currentCandidateState(directory, skillSlug, candidateId2) {
54950
55079
  function writeSkillFileAtomic(targetPath, content) {
54951
55080
  const tempPath = `${targetPath}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`;
54952
55081
  try {
54953
- _internals81.writeFileSync(tempPath, content, "utf8");
54954
- _internals81.renameSync(tempPath, targetPath);
55082
+ _internals82.writeFileSync(tempPath, content, "utf8");
55083
+ _internals82.renameSync(tempPath, targetPath);
54955
55084
  } finally {
54956
55085
  try {
54957
55086
  if (existsSync53(tempPath))
54958
- _internals81.unlinkSync(tempPath);
55087
+ _internals82.unlinkSync(tempPath);
54959
55088
  } catch {}
54960
55089
  }
54961
55090
  }
54962
- var _internals81 = {
55091
+ var _internals82 = {
54963
55092
  writeFileSync: writeFileSync18,
54964
55093
  renameSync: renameSync19,
54965
55094
  unlinkSync: unlinkSync21
@@ -55416,7 +55545,7 @@ function buildGeneratorInputs(args) {
55416
55545
  }
55417
55546
  };
55418
55547
  }
55419
- var _internals82 = {
55548
+ var _internals83 = {
55420
55549
  draftDeterministic: defaultDeterministicDraft
55421
55550
  };
55422
55551
  function defaultDeterministicDraft(inputs) {
@@ -55486,7 +55615,7 @@ function countChangedLines(a, b) {
55486
55615
  return changed;
55487
55616
  }
55488
55617
  function draftCandidate(inputs) {
55489
- const candidate2 = _internals82.draftDeterministic(inputs);
55618
+ const candidate2 = _internals83.draftDeterministic(inputs);
55490
55619
  enforceTrustRegion(candidate2, inputs.budget);
55491
55620
  return candidate2;
55492
55621
  }
@@ -55523,21 +55652,21 @@ async function deterministicSeed(input) {
55523
55652
  }
55524
55653
 
55525
55654
  // src/services/skill-optimizer/smoke.ts
55526
- import { existsSync as existsSync54, lstatSync as lstatSync10, readFileSync as readFileSync41, realpathSync as realpathSync11 } from "fs";
55655
+ import { existsSync as existsSync54, lstatSync as lstatSync10, readFileSync as readFileSync41, realpathSync as realpathSync12 } from "fs";
55527
55656
  import * as path98 from "path";
55528
55657
 
55529
55658
  // src/hooks/spawn-helper.ts
55530
55659
  import * as child_process7 from "child_process";
55531
55660
  var WIN32_CMD_BINARIES = new Set(["npm", "npx", "pnpm", "yarn"]);
55532
- var _internals83 = {
55661
+ var _internals84 = {
55533
55662
  spawn: child_process7.spawn
55534
55663
  };
55535
55664
  function spawnAsync(command, cwd, timeoutMs) {
55536
- return new Promise((resolve33) => {
55665
+ return new Promise((resolve34) => {
55537
55666
  try {
55538
55667
  const [rawCmd, ...args] = command;
55539
55668
  const cmd = process.platform === "win32" && WIN32_CMD_BINARIES.has(rawCmd) && !rawCmd.includes(".") ? `${rawCmd}.cmd` : rawCmd;
55540
- const proc = _internals83.spawn(cmd, args, {
55669
+ const proc = _internals84.spawn(cmd, args, {
55541
55670
  cwd,
55542
55671
  stdio: ["ignore", "pipe", "pipe"]
55543
55672
  });
@@ -55580,30 +55709,30 @@ function spawnAsync(command, cwd, timeoutMs) {
55580
55709
  try {
55581
55710
  proc.kill();
55582
55711
  } catch {}
55583
- resolve33(null);
55712
+ resolve34(null);
55584
55713
  }, timeoutMs);
55585
55714
  proc.on("close", (code) => {
55586
55715
  if (done)
55587
55716
  return;
55588
55717
  done = true;
55589
55718
  clearTimeout(timer);
55590
- resolve33({ exitCode: code ?? 1, stdout, stderr });
55719
+ resolve34({ exitCode: code ?? 1, stdout, stderr });
55591
55720
  });
55592
55721
  proc.on("error", () => {
55593
55722
  if (done)
55594
55723
  return;
55595
55724
  done = true;
55596
55725
  clearTimeout(timer);
55597
- resolve33(null);
55726
+ resolve34(null);
55598
55727
  });
55599
55728
  } catch {
55600
- resolve33(null);
55729
+ resolve34(null);
55601
55730
  }
55602
55731
  });
55603
55732
  }
55604
55733
 
55605
55734
  // src/services/skill-optimizer/smoke.ts
55606
- var _internals84 = {
55735
+ var _internals85 = {
55607
55736
  validateSkillPath,
55608
55737
  isSymbolicLink: (p) => {
55609
55738
  try {
@@ -55616,7 +55745,7 @@ var _internals84 = {
55616
55745
  const rel = path98.relative(path98.resolve(root), path98.resolve(target));
55617
55746
  return rel.startsWith("..") || path98.isAbsolute(rel);
55618
55747
  },
55619
- realpath: (p) => realpathSync11(p),
55748
+ realpath: (p) => realpathSync12(p),
55620
55749
  evaluateSkillChange,
55621
55750
  isRejectedSkillContent,
55622
55751
  spawnAsync
@@ -55624,7 +55753,7 @@ var _internals84 = {
55624
55753
  async function validateSkillSmoke(input) {
55625
55754
  const notes = [];
55626
55755
  const repoRel = path98.join(".opencode", "skills", "generated", input.skillSlug, "SKILL.md");
55627
- if (!_internals84.validateSkillPath(repoRel)) {
55756
+ if (!_internals85.validateSkillPath(repoRel)) {
55628
55757
  return {
55629
55758
  ok: false,
55630
55759
  verdict: "VIOLATED",
@@ -55633,16 +55762,16 @@ async function validateSkillSmoke(input) {
55633
55762
  }
55634
55763
  const skillRoot = path98.join(input.directory, ".opencode", "skills", "generated", input.skillSlug);
55635
55764
  if (existsSync54(skillRoot)) {
55636
- if (_internals84.isSymbolicLink(skillRoot)) {
55765
+ if (_internals85.isSymbolicLink(skillRoot)) {
55637
55766
  return {
55638
55767
  ok: false,
55639
55768
  verdict: "VIOLATED",
55640
55769
  notes: ["skill root is a symlink (reparse denied)"]
55641
55770
  };
55642
55771
  }
55643
- const realRoot = _internals84.realpath(skillRoot);
55644
- const realProjectDir = _internals84.realpath(input.directory);
55645
- if (_internals84.escapedRoot(realProjectDir, realRoot)) {
55772
+ const realRoot = _internals85.realpath(skillRoot);
55773
+ const realProjectDir = _internals85.realpath(input.directory);
55774
+ if (_internals85.escapedRoot(realProjectDir, realRoot)) {
55646
55775
  return {
55647
55776
  ok: false,
55648
55777
  verdict: "VIOLATED",
@@ -55660,7 +55789,7 @@ async function validateSkillSmoke(input) {
55660
55789
  notes: [`frontmatter: ${fmError}`]
55661
55790
  };
55662
55791
  }
55663
- const rejected = await _internals84.isRejectedSkillContent(input.directory, input.skillSlug, input.candidateContent);
55792
+ const rejected = await _internals85.isRejectedSkillContent(input.directory, input.skillSlug, input.candidateContent);
55664
55793
  if (rejected) {
55665
55794
  return {
55666
55795
  ok: false,
@@ -55670,7 +55799,7 @@ async function validateSkillSmoke(input) {
55670
55799
  ]
55671
55800
  };
55672
55801
  }
55673
- const evalResult = await _internals84.evaluateSkillChange({
55802
+ const evalResult = await _internals85.evaluateSkillChange({
55674
55803
  directory: input.directory,
55675
55804
  slug: input.skillSlug,
55676
55805
  candidateContent: input.candidateContent,
@@ -55689,7 +55818,7 @@ async function validateSkillSmoke(input) {
55689
55818
  notes.push(`phrase-eval passed (score ${evalResult.candidateScore.toFixed(2)})`);
55690
55819
  }
55691
55820
  if (input.checkCommand && input.checkCommand.length > 0) {
55692
- const cmdResult = await _internals84.spawnAsync(input.checkCommand, input.directory, input.checkTimeoutMs ?? 60000);
55821
+ const cmdResult = await _internals85.spawnAsync(input.checkCommand, input.directory, input.checkTimeoutMs ?? 60000);
55693
55822
  if (!cmdResult || cmdResult.exitCode !== 0) {
55694
55823
  return {
55695
55824
  ok: false,
@@ -55759,7 +55888,7 @@ async function prepareCandidatePayloads(inputRoot, candidateId2, skillSlug, base
55759
55888
  candidate2.contentHash = await computeCandidateInputContentHash2(inputRoot, candidate2);
55760
55889
  return { baseline, candidate: candidate2 };
55761
55890
  }
55762
- var _internals85 = {
55891
+ var _internals86 = {
55763
55892
  tryAcquireLock,
55764
55893
  emitTelemetry: emit,
55765
55894
  evaluateCandidateV1,
@@ -55767,7 +55896,7 @@ var _internals85 = {
55767
55896
  };
55768
55897
  async function acquireProjectLock(directory) {
55769
55898
  assertProjectRoot(directory);
55770
- const result = await _internals85.tryAcquireLock(directory, PROJECT_LOCK_PATH, "skill-opt-controller", "project-run");
55899
+ const result = await _internals86.tryAcquireLock(directory, PROJECT_LOCK_PATH, "skill-opt-controller", "project-run");
55771
55900
  if (!result.acquired)
55772
55901
  return null;
55773
55902
  return async () => {
@@ -55781,7 +55910,7 @@ async function acquireProjectLock(directory) {
55781
55910
  async function acquireSkillLock(directory, skillSlug) {
55782
55911
  assertProjectRoot(directory);
55783
55912
  const lockPath = path99.join(".swarm", "evolution", "skills", skillSlug, ".skill.lock");
55784
- const result = await _internals85.tryAcquireLock(directory, lockPath, "skill-opt-controller", `skill-${skillSlug}`);
55913
+ const result = await _internals86.tryAcquireLock(directory, lockPath, "skill-opt-controller", `skill-${skillSlug}`);
55785
55914
  if (!result.acquired)
55786
55915
  return null;
55787
55916
  return async () => {
@@ -55978,13 +56107,13 @@ async function runValidationWithTransientRetry(input, candidateContent, baseline
55978
56107
  while (true) {
55979
56108
  try {
55980
56109
  const evalInputRoot = input.inputRoot ?? input.directory;
55981
- const { baseline, candidate: candidate2 } = await _internals85.prepareCandidatePayloads(evalInputRoot, candidateId2, input.skillSlug, input.baselineModel, input.candidateModel, baselineContent, candidateContent);
56110
+ const { baseline, candidate: candidate2 } = await _internals86.prepareCandidatePayloads(evalInputRoot, candidateId2, input.skillSlug, input.baselineModel, input.candidateModel, baselineContent, candidateContent);
55982
56111
  if (!input.dispatcher) {
55983
56112
  throw new Error("no evaluation dispatcher available (cannot run validation)");
55984
56113
  }
55985
- const { createModelEvaluationExecutor: createModelEvaluationExecutor2 } = await import("./runner-y78d7ryb.js");
56114
+ const { createModelEvaluationExecutor: createModelEvaluationExecutor2 } = await import("./runner-fh3r41nw.js");
55986
56115
  const executor = createModelEvaluationExecutor2(input.dispatcher, input.sessionId);
55987
- const result = await _internals85.evaluateCandidateV1({
56116
+ const result = await _internals86.evaluateCandidateV1({
55988
56117
  projectRoot: input.directory,
55989
56118
  inputRoot: input.inputRoot ?? input.directory,
55990
56119
  tasks: input.validationTasks,
@@ -56042,7 +56171,7 @@ async function runValidationWithTransientRetry(input, candidateContent, baseline
56042
56171
  deadband: input.config.deadband
56043
56172
  };
56044
56173
  }
56045
- _internals85.emitTelemetry?.("loop_detected", {
56174
+ _internals86.emitTelemetry?.("loop_detected", {
56046
56175
  skillSlug: input.skillSlug,
56047
56176
  reason: message.slice(0, 160),
56048
56177
  source: "skill-opt-controller"
@@ -56500,7 +56629,7 @@ async function handleSpecifyCommand(_directory, args) {
56500
56629
  init_loader();
56501
56630
  init_schema();
56502
56631
  import * as fsSync4 from "fs";
56503
- import { readFile as readFile22 } from "fs/promises";
56632
+ import { readFile as readFile21 } from "fs/promises";
56504
56633
  import * as path104 from "path";
56505
56634
 
56506
56635
  // src/consensus/store.ts
@@ -56891,7 +57020,7 @@ function getCompactionMetrics(sessionId) {
56891
57020
  }
56892
57021
 
56893
57022
  // src/services/status-service.ts
56894
- var _internals86 = {
57023
+ var _internals87 = {
56895
57024
  loadLeanTurboRunState,
56896
57025
  hasActiveLeanTurbo,
56897
57026
  hasActiveFullAuto,
@@ -57070,11 +57199,11 @@ async function getStatusData(directory, agents, sessionId) {
57070
57199
  } catch {
57071
57200
  status.memoryCohort = { linked: false };
57072
57201
  }
57073
- status.fullAutoActive = _internals86.hasActiveFullAuto();
57202
+ status.fullAutoActive = _internals87.hasActiveFullAuto();
57074
57203
  if (status.fullAutoActive) {
57075
- const sid = _internals86.getActiveFullAutoSessionID();
57204
+ const sid = _internals87.getActiveFullAutoSessionID();
57076
57205
  if (sid) {
57077
- const runState = _internals86.loadFullAutoRunState(directory, sid);
57206
+ const runState = _internals87.loadFullAutoRunState(directory, sid);
57078
57207
  if (runState?.lastEscalation) {
57079
57208
  status.fullAutoEscalation = {
57080
57209
  reason: runState.lastEscalation.reason,
@@ -57108,7 +57237,7 @@ async function getStatusData(directory, agents, sessionId) {
57108
57237
  }
57109
57238
  function enrichWithLeanTurbo(status, directory) {
57110
57239
  const turboMode = hasActiveTurboMode();
57111
- const leanActive = _internals86.hasActiveLeanTurbo();
57240
+ const leanActive = _internals87.hasActiveLeanTurbo();
57112
57241
  let turboStrategy = "off";
57113
57242
  if (leanActive) {
57114
57243
  turboStrategy = "lean";
@@ -57139,7 +57268,7 @@ function enrichWithLeanTurbo(status, directory) {
57139
57268
  }
57140
57269
  }
57141
57270
  if (leanSessionID) {
57142
- const runState = _internals86.loadLeanTurboRunState(directory, leanSessionID);
57271
+ const runState = _internals87.loadLeanTurboRunState(directory, leanSessionID);
57143
57272
  if (runState) {
57144
57273
  status.leanTurboPhase = runState.phase;
57145
57274
  status.leanMaxParallelCoders = runState.maxParallelCoders;
@@ -57339,7 +57468,7 @@ async function safeLineCount(filePath) {
57339
57468
  try {
57340
57469
  if (!fsSync4.existsSync(filePath))
57341
57470
  return 0;
57342
- const content = await readFile22(filePath, "utf-8");
57471
+ const content = await readFile21(filePath, "utf-8");
57343
57472
  let n = 0;
57344
57473
  for (const line of content.split(`
57345
57474
  `)) {
@@ -57394,7 +57523,7 @@ init_logger();
57394
57523
  var TURBO_BYPASS_DISCLOSURE = "Bypassed: Stage B (reviewer + test_engineer) for Tier 0-2 tasks; phase_complete Gates 1-5 " + "(completion-verify, drift-verifier, hallucination-guard, mutation-gate, phase-council). " + "Still enforced: Stage A (lint, imports, pre_check_batch); Tier 3 Stage B; Gate 5b " + "(architecture-supervisor); Gate 6 (final-council); Gate 7 (full-auto).";
57395
57524
 
57396
57525
  // src/commands/turbo.ts
57397
- var _internals87 = {
57526
+ var _internals88 = {
57398
57527
  loadPluginConfigWithMeta
57399
57528
  };
57400
57529
  async function handleTurboCommand(directory, args, sessionID) {
@@ -57454,7 +57583,7 @@ async function handleTurboCommand(directory, args, sessionID) {
57454
57583
  if (arg0 === "on") {
57455
57584
  let strategy = "standard";
57456
57585
  try {
57457
- const { config } = _internals87.loadPluginConfigWithMeta(directory);
57586
+ const { config } = _internals88.loadPluginConfigWithMeta(directory);
57458
57587
  if (config.turbo?.strategy === "lean") {
57459
57588
  strategy = "lean";
57460
57589
  }
@@ -57551,7 +57680,7 @@ function enableLeanTurbo(session, directory, sessionID) {
57551
57680
  let maxParallelCoders = 4;
57552
57681
  let conflictPolicy = "serialize";
57553
57682
  try {
57554
- const { config } = _internals87.loadPluginConfigWithMeta(directory);
57683
+ const { config } = _internals88.loadPluginConfigWithMeta(directory);
57555
57684
  const leanConfig = config.turbo?.lean;
57556
57685
  if (leanConfig) {
57557
57686
  maxParallelCoders = leanConfig.max_parallel_coders ?? 4;
@@ -57814,7 +57943,7 @@ function buildDetailedHelp(commandName, entry) {
57814
57943
  async function handleHelpCommand(ctx) {
57815
57944
  const targetCommand = ctx.args.join(" ");
57816
57945
  if (!targetCommand) {
57817
- const { buildHelpText } = await import("./index-pj9h75cc.js");
57946
+ const { buildHelpText } = await import("./index-djbhe0yh.js");
57818
57947
  return buildHelpText();
57819
57948
  }
57820
57949
  const tokens = targetCommand.split(/\s+/);
@@ -57823,7 +57952,7 @@ async function handleHelpCommand(ctx) {
57823
57952
  return _internals18.buildDetailedHelp(resolved.key, resolved.entry);
57824
57953
  }
57825
57954
  const similar = _internals18.findSimilarCommands(targetCommand);
57826
- const { buildHelpText: fullHelp } = await import("./index-pj9h75cc.js");
57955
+ const { buildHelpText: fullHelp } = await import("./index-djbhe0yh.js");
57827
57956
  if (similar.length > 0) {
57828
57957
  return `Command '/swarm ${targetCommand}' not found.
57829
57958
 
@@ -58000,7 +58129,7 @@ var COMMAND_REGISTRY = {
58000
58129
  },
58001
58130
  "guardrail explain": {
58002
58131
  handler: async (ctx) => {
58003
- const { handleGuardrailExplain } = await import("./guardrail-explain-yktan15c.js");
58132
+ const { handleGuardrailExplain } = await import("./guardrail-explain-pn1bcgfz.js");
58004
58133
  return handleGuardrailExplain(ctx.directory, ctx.args);
58005
58134
  },
58006
58135
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -58010,7 +58139,7 @@ var COMMAND_REGISTRY = {
58010
58139
  },
58011
58140
  "guardrail-explain": {
58012
58141
  handler: async (ctx) => {
58013
- const { handleGuardrailExplain } = await import("./guardrail-explain-yktan15c.js");
58142
+ const { handleGuardrailExplain } = await import("./guardrail-explain-pn1bcgfz.js");
58014
58143
  return handleGuardrailExplain(ctx.directory, ctx.args);
58015
58144
  },
58016
58145
  description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
@@ -58020,7 +58149,7 @@ var COMMAND_REGISTRY = {
58020
58149
  },
58021
58150
  "guardrail-log": {
58022
58151
  handler: async (ctx) => {
58023
- const { handleGuardrailLog } = await import("./guardrail-log-82da8y5a.js");
58152
+ const { handleGuardrailLog } = await import("./guardrail-log-vb5zkegf.js");
58024
58153
  return handleGuardrailLog(ctx.directory, ctx.args);
58025
58154
  },
58026
58155
  description: "Read the guardrail decision log (use --blocks-only for blocks)",
@@ -58548,8 +58677,8 @@ Subcommands:
58548
58677
  "ci-simulate": {
58549
58678
  handler: (ctx) => handleCiSimulateCommand(ctx.directory, ctx.args),
58550
58679
  description: "Create a temporary merge-result worktree and run CI before merge queue entry",
58551
- args: "[--base origin/main] [--head <ref>]",
58552
- details: "Creates a detached temporary worktree under .swarm/ci-simulate from the base ref, merges the current worktree HEAD (or --head ref), runs fixed local CI gates (typecheck, Biome CI, build, unit/integration/security/smoke tests, drift check), then removes the worktree and prunes metadata. Intended as a pre-queue merge_group simulation helper.",
58680
+ args: "[pr-ref] [--base <ref>]",
58681
+ details: "Creates a detached temporary worktree under the OS temp dir (swarm-ci-simulate) from the base \u2014 an explicit validated --base <ref> when given (stacked/release-branch PRs), otherwise the detected default remote branch (origin/HEAD, init.defaultBranch, origin/main, origin/master, verified to exist) \u2014 merges the given PR ref (or the current ref), runs fixed local CI gates (typecheck, lint, build, test), then removes the worktree non-force and prunes metadata. Worktree removal is fail-closed: a blocked or dirty worktree is surfaced, never force-deleted. Intended as a pre-queue merge_group simulation helper.",
58553
58682
  category: "agent",
58554
58683
  toolPolicy: "agent"
58555
58684
  },
@@ -59487,11 +59616,11 @@ record inside as a structured directive you MUST inspect before:
59487
59616
  5. Escalating or invoking skill_improve.
59488
59617
 
59489
59618
  For every applicable directive in the block:
59490
- - Cite \`KNOWLEDGE_APPLIED: <id>\` in the next plan / delegation / gate action that complies with it.
59619
+ - Copy the encoded \`trace_id\` and directive \`id\` tokens exactly and cite \`KNOWLEDGE_APPLIED:<trace_id>:<entry_id>\` in the next plan / delegation / gate action that complies with it.
59491
59620
  - If a directive references a generated skill via \`skill: file:...\`, you MUST add that path to the SKILLS: field of any matching subagent delegation.
59492
- - If a directive does NOT apply to the current action, record \`KNOWLEDGE_IGNORED: <id> reason=<short reason>\` once in your reply.
59493
- - If current system/repository/task authority or observed evidence disproves a directive, record \`KNOWLEDGE_CONTRADICTED: <id> reason=<observable conflict>\` and follow current authority.
59494
- - If runtime evidence shows a directive was violated (reviewer rejection, failing test, scope breach), record \`KNOWLEDGE_VIOLATED: <id> reason=<reason>\` and re-plan.
59621
+ - If a directive does NOT apply to the current action, record \`KNOWLEDGE_IGNORED:<trace_id>:<entry_id> reason=<short reason>\` once in your reply.
59622
+ - If current system/repository/task authority or observed evidence disproves a directive, record \`KNOWLEDGE_CONTRADICTED:<trace_id>:<entry_id> reason=<observable conflict>\` and follow current authority.
59623
+ - If runtime evidence shows a directive was violated (reviewer rejection, failing test, scope breach), record \`KNOWLEDGE_VIOLATED:<trace_id>:<entry_id> reason=<reason>\` and re-plan.
59495
59624
  - NEVER silently ignore a \`priority: critical\` directive. The knowledge_application gate may run in 'enforce' mode; in that mode an omitted ack on a critical directive blocks the action for a bounded number of retries and time window (\`max_gate_denials\`, \`gate_staleness_ms\`), after which it auto-clears and logs the bypass \u2014 do not attempt out-of-band workarounds (editing .swarm/ state files, restarting sessions) to escape it; retry the ack with a correctly-terminated marker instead.
59496
59625
 
59497
59626
  Chat-text markers (KNOWLEDGE_APPLIED/IGNORED/CONTRADICTED/VIOLATED) are the sole mechanism that satisfies the knowledge-application enforcement gate. The \`knowledge_receipt\` tool records knowledge-usage receipts for audit but does NOT satisfy the gate.
@@ -59943,7 +60072,8 @@ HARD CONSTRAINTS (apply regardless of skill load success):
59943
60072
  - RUN THE MECHANICAL GATES: after fixes, call \`run_pr_feedback_stage_a\` with distinct repository-valid array-form build, typecheck, lint, exact \`["git", "diff", "--check"]\`, and reproduction commands; the reproduction declares exact selected test/package/path \`targets\`. Arbitrary/no-op, mutating, publishing, fix/update, wrapper/eval, selector-free, or duplicate commands fail closed, and content plus HEAD/index/refs/upstream/Git-config state must remain unchanged around every command. Then dispatch exactly one fresh lane at a time, in order, with \`max_concurrent: 1\`: \`swarm-pr-feedback:stage-b-reviewer\`, \`:stage-b-test\`, \`:closeout-reviewer\`, and \`:closeout-critic\`. Every lane owns the complete immutable \`feedback_item_ids\` and uses the matching \`workflow_lane\`. Free-form verdicts, direct Task calls, parallel or out-of-order lanes, stale digests, missing or duplicate item rows, and speed/time rationalizations do not satisfy the gate.
59944
60073
  - RESTART AFTER EDITS: any content change after Stage A invalidates Stage A and all later verdicts. Restart the entire mechanical gate sequence; do not reuse a prior reviewer or critic conversation.
59945
60074
  - DO NOT PUBLISH EARLY: commits, pushes, PR comments/updates, review-thread mutations, and other remote writes remain blocked until every ordered feedback gate settles positively on the same revision digest.
59946
- - After every local gate passes, create the reviewed commit with one standalone \`git commit\`, then call \`complete_pr_workflow\` once. It requires a clean index/worktree and a non-merge direct child whose sole parent is the immutable intake head before binding that post-commit HEAD and arming publication. Push only with \`git push <bound-remote> <bound-commit>:refs/heads/<bound-branch>\`; the literal bound commit and exact bound branch are required, and force flags, wrappers, aliases, fetch-based local-ref forgery, extra refspecs, \`git -C\`, and other remote writes fail closed. Perform read-only remote checks, then call \`complete_pr_workflow\` a second time with the same immutable verification \`pr_head_sha\`; the second call clears only after both the actual remote ref and its local tracking ref resolve to the exact bound commit. Only then perform any explicitly authorized PR comment/body/thread writes.
60075
+ - After every local gate passes, EITHER path terminates: (a) content changes \u2014 create the reviewed commit with one standalone \`git commit\`, then call \`complete_pr_workflow\` once. It requires a clean index/worktree and a non-merge direct child whose sole parent is the immutable intake head before binding that post-commit HEAD and arming publication. Push only with \`git push <bound-remote> <bound-commit>:refs/heads/<bound-branch>\`; the literal bound commit and exact bound branch are required, and force flags, wrappers, aliases, fetch-based local-ref forgery, extra refspecs, \`git -C\`, and other remote writes fail closed. Perform read-only remote checks, then call \`complete_pr_workflow\` a second time with the same immutable verification \`pr_head_sha\`; the second call clears only after both the actual remote ref and its local tracking ref resolve to the exact bound commit. Only then perform any explicitly authorized PR comment/body/thread writes. (b) verified no-change \u2014 when EVERY ledger item is verified DISPROVED, PRE_EXISTING, NEEDS_MORE_EVIDENCE, or NEEDS_USER_DECISION in the settled verification lanes, call \`complete_pr_workflow\` with the intake head while HEAD equals it and the tree is clean; it returns \`verified-no-change\` and clears the gate terminally with no commit and no push (an empty commit is still forbidden).
60076
+ - BASE-SYNC REBIND: when base drift or merge conflicts force a merge/rebase, do NOT abort ad-hoc \u2014 finish the repair, fetch and check out the new authoritative PR head, then call \`rebind_pr_feedback_head\` with the new full SHA. It moves the immutable intake head, keeps the inventory, and invalidates Stage A plus every gate receipt; re-run the entire mechanical ladder on the new ancestry. It refuses a no-op rebind, an armed gate, and in-flight lanes.
59947
60077
  - Patch only confirmed items plus the tests/docs they require; report closure status for every ledger item including disproved ones.
59948
60078
  - ABORT IF UNRECOVERABLE (pre-armed only): if the PR head cannot be fetched/checked out, the verification bind is unreachable, or bounded recovery is exhausted, call \`abort_pr_workflow\` with \`mode: "PR_FEEDBACK"\`, \`kind: "recovery"\`, and a one-line \`reason\` instead of looping. The tool accepts unbound and bound workflows, refuses while PR workflow lanes are in flight (collect their results first), and refuses once \`prFeedbackReadyToPublish\` is armed \u2014 after arming, you MUST complete the workflow with \`complete_pr_workflow\` (or push the bound commit first); aborting an armed gate would drop the immutable-commit binding and leave a half-published commit. Do NOT abort while useful bounded recovery work remains.
59949
60079
  - Do NOT resolve or mark GitHub review threads resolved unless the user explicitly instructs it.
@@ -61007,6 +61137,13 @@ Do not pad responses with hedging when confidence is HIGH. A precise answer is m
61007
61137
  - Cross-platform and version-specific constraints must be flagged explicitly
61008
61138
  `;
61009
61139
 
61140
+ // src/agents/reviewer-directive-compliance.ts
61141
+ var DIRECTIVE_COMPLIANCE_OUTPUT_SPEC = `DIRECTIVE_COMPLIANCE: one line per retrieval membership shown during this phase. Copy the encoded trace_id and entry_id tokens exactly from the DIRECTIVES TO VERIFY block. Use exactly one of:
61142
+ VERIFIED:<trace_id>:<entry_id> evidence=<file:line | predicate_passed>
61143
+ VIOLATED:<trace_id>:<entry_id> evidence=<file:line | failing_predicate>
61144
+ N/A:<trace_id>:<entry_id> reason=<why it does not apply to this change>
61145
+ Every listed trace_id + entry_id pair MUST appear exactly once. The same entry_id may appear under more than one trace_id and requires one verdict per pair. If a directive carries a verification_predicate, you MUST run it and report predicate_passed / failing_predicate as the evidence. Omitting a listed CRITICAL pair is itself a VIOLATED verdict.`;
61146
+
61010
61147
  // src/agents/reviewer.ts
61011
61148
  var LEGACY_REVIEWER_PROMPT = `## PRESSURE IMMUNITY
61012
61149
 
@@ -61248,11 +61385,8 @@ ISSUES: list with line numbers, grouped by CHECK dimension
61248
61385
  ACCEPTANCE_SATISFACTION: SATISFIED | PARTIAL | NOT_SATISFIED \u2014 one line per item in the input ACCEPTANCE field, stating explicitly whether the diff satisfies it (with evidence: file:line or "no corresponding implementation found"). This is a distinct question from "does the diff look correct" \u2014 assess conformance to ACCEPTANCE even when the diff is otherwise well-written. NOT_SATISFIED on any item forces VERDICT: REJECTED.
61249
61386
  TASK: [task id being reviewed, or "unknown"]
61250
61387
  SKILL_COMPLIANCE: COMPLIANT | PARTIAL | VIOLATED \u2014 [list of violations or "all rules followed"]
61251
- DIRECTIVE_COMPLIANCE: one line per knowledge directive shown during this phase (IDs listed in the DIRECTIVES TO VERIFY block of your prompt, when present). Use exactly one of:
61252
- VERIFIED:<id> evidence=<file:line | predicate_passed>
61253
- VIOLATED:<id> evidence=<file:line | failing_predicate>
61254
- N/A:<id> reason=<why it does not apply>
61255
- Every listed directive ID MUST appear exactly once. If a directive carries a verification_predicate, RUN it and report predicate_passed / failing_predicate as evidence. Omitting a listed directive ID counts as VIOLATED. If no DIRECTIVES TO VERIFY block was provided, output "DIRECTIVE_COMPLIANCE: none".
61388
+ ${DIRECTIVE_COMPLIANCE_OUTPUT_SPEC}
61389
+ If no DIRECTIVES TO VERIFY block was provided, output "DIRECTIVE_COMPLIANCE: none".
61256
61390
  FIXES: required changes if rejected
61257
61391
  Use INFO only inside ISSUES for non-blocking suggestions. RISK reflects the highest blocking severity, so it never uses INFO.
61258
61392
 
@@ -61603,4 +61737,4 @@ function createCuratorLLMDelegate(directory, mode = "init", sessionId) {
61603
61737
  };
61604
61738
  }
61605
61739
 
61606
- export { handleAcknowledgeSpecDriftCommand, handleAgentsCommand, handleAnalyzeCommand, dcNormalizeCommand, dcUnwrapWrappers, dcSplitSegments, dcExtractRecursiveRmTargets, dcEvaluateRecursiveDeleteTargets, dcCheckJunctionCreation, dcExtractWindowsCmdTargets, dcExtractPowerShellTargets, normalizeSwarmCommandInput, canonicalCommandKey, formatCommandNotFound, executeSwarmCommand, SWARM_COMMAND_TOOL_COMMANDS, SWARM_COMMAND_TOOL_ALLOWLIST, HUMAN_ONLY_SWARM_COMMANDS, classifySwarmCommandToolUse, classifySwarmCommandChatFallbackUse, detectPosixWrites, detectWindowsWrites, resolveWriteTargets, handleArchiveCommand, handleAutoProceedCommand, handleBenchmarkCommand, handleBrainstormCommand, handleCheckpointCommand, handleCiSimulateCommand, handleClarifyCommand, createCuratorLLMDelegate, _internals27 as _internals, normalizeRecommendationEntryIdToken, parseKnowledgeRecommendations, parseKnowledgeRecommendationsWithDiagnostics, parseStructuredCuratorBlocks, readCuratorSummary, writeCuratorSummary, appendCuratorRecommendation, mergeCuratorPhaseSummary, filterPhaseEvents, checkPhaseCompliance, runCuratorInit, runCuratorPhase, applyCuratorKnowledgeUpdates, isHiveEligible, countDistinctProjects, checkHivePromotions, _internals30 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, handleReviewCommand, handleRollbackCommand, handleSddStatusCommand, handleSddValidateCommand, handleSddProjectCommand, handleSddCommand, handleSimulateCommand, handleSpecifyCommand, handleStatusCommand, handleSyncPlanCommand, handleTurboCommand, handleUnlinkCommand, handleWriteRetroCommand, handleHelpCommand, COMMAND_REGISTRY, VALID_COMMANDS, _internals18 as _internals2, resolveCommand };
61740
+ export { handleAcknowledgeSpecDriftCommand, handleAgentsCommand, handleAnalyzeCommand, dcNormalizeCommand, dcUnwrapWrappers, dcSplitSegments, dcExtractRecursiveRmTargets, dcEvaluateRecursiveDeleteTargets, dcCheckJunctionCreation, dcExtractWindowsCmdTargets, dcExtractPowerShellTargets, normalizeSwarmCommandInput, canonicalCommandKey, formatCommandNotFound, executeSwarmCommand, SWARM_COMMAND_TOOL_COMMANDS, SWARM_COMMAND_TOOL_ALLOWLIST, HUMAN_ONLY_SWARM_COMMANDS, classifySwarmCommandToolUse, classifySwarmCommandChatFallbackUse, detectPosixWrites, detectWindowsWrites, resolveWriteTargets, handleArchiveCommand, handleAutoProceedCommand, handleBenchmarkCommand, handleBrainstormCommand, handleCheckpointCommand, handleCiSimulateCommand, handleClarifyCommand, createCuratorLLMDelegate, _internals27 as _internals, normalizeRecommendationEntryIdToken, parseKnowledgeRecommendations, parseKnowledgeRecommendationsWithDiagnostics, parseStructuredCuratorBlocks, readCuratorSummary, writeCuratorSummary, appendCuratorRecommendation, mergeCuratorPhaseSummary, filterPhaseEvents, checkPhaseCompliance, runCuratorInit, runCuratorPhase, applyCuratorKnowledgeUpdates, isHiveEligible, countDistinctProjects, checkHivePromotions, _internals31 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, handleReviewCommand, handleRollbackCommand, handleSddStatusCommand, handleSddValidateCommand, handleSddProjectCommand, handleSddCommand, handleSimulateCommand, handleSpecifyCommand, handleStatusCommand, handleSyncPlanCommand, handleTurboCommand, handleUnlinkCommand, handleWriteRetroCommand, handleHelpCommand, COMMAND_REGISTRY, VALID_COMMANDS, _internals18 as _internals2, resolveCommand };