opencode-swarm 7.77.4 → 7.77.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -52,7 +52,7 @@ var package_default;
52
52
  var init_package = __esm(() => {
53
53
  package_default = {
54
54
  name: "opencode-swarm",
55
- version: "7.77.4",
55
+ version: "7.77.5",
56
56
  description: "Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",
57
57
  main: "dist/index.js",
58
58
  types: "dist/index.d.ts",
@@ -23085,6 +23085,291 @@ var init_stored_input_args = __esm(() => {
23085
23085
  storedInputArgs = new Map;
23086
23086
  });
23087
23087
 
23088
+ // src/commands/command-dispatch.ts
23089
+ function normalizeSwarmCommandInput(command, argumentText) {
23090
+ if (command !== "swarm" && !command.startsWith("swarm-")) {
23091
+ return { isSwarmCommand: false, tokens: [] };
23092
+ }
23093
+ if (command === "swarm") {
23094
+ return {
23095
+ isSwarmCommand: true,
23096
+ tokens: argumentText.trim().split(/\s+/).filter(Boolean)
23097
+ };
23098
+ }
23099
+ const subcommand = command.slice("swarm-".length);
23100
+ const extraArgs = argumentText.trim().split(/\s+/).filter(Boolean);
23101
+ return {
23102
+ isSwarmCommand: true,
23103
+ tokens: [subcommand, ...extraArgs].filter(Boolean)
23104
+ };
23105
+ }
23106
+ function canonicalCommandKey(resolved) {
23107
+ return resolved.entry.aliasOf ?? resolved.key;
23108
+ }
23109
+ function formatCommandNotFound(tokens) {
23110
+ const attemptedCommand = tokens[0] || "";
23111
+ const MAX_DISPLAY = 100;
23112
+ const displayCommand = attemptedCommand.length > MAX_DISPLAY ? `${attemptedCommand.slice(0, MAX_DISPLAY)}...` : attemptedCommand;
23113
+ const similar = _internals11.findSimilarCommands(attemptedCommand);
23114
+ const header = `Command \`/swarm ${displayCommand}\` not found.`;
23115
+ const suggestions = similar.length > 0 ? `Did you mean:
23116
+ ${similar.map((cmd) => ` - /swarm ${cmd}`).join(`
23117
+ `)}` : "";
23118
+ const footer = "Run `/swarm help` for all commands.";
23119
+ return [header, suggestions, footer].filter(Boolean).join(`
23120
+
23121
+ `);
23122
+ }
23123
+ async function executeSwarmCommand(args) {
23124
+ const {
23125
+ directory,
23126
+ agents,
23127
+ sessionID,
23128
+ tokens,
23129
+ packageRoot,
23130
+ buildHelpText,
23131
+ policy
23132
+ } = args;
23133
+ let text;
23134
+ const resolved = resolveCommand(tokens);
23135
+ if (!resolved) {
23136
+ text = tokens.length === 0 && buildHelpText ? buildHelpText() : formatCommandNotFound(tokens);
23137
+ } else {
23138
+ const policyResult = policy?.(resolved) ?? { allowed: true };
23139
+ if (!policyResult.allowed) {
23140
+ text = policyResult.message;
23141
+ } else {
23142
+ try {
23143
+ text = await resolved.entry.handler({
23144
+ directory,
23145
+ args: resolved.remainingArgs,
23146
+ sessionID,
23147
+ agents,
23148
+ packageRoot,
23149
+ source: "chat"
23150
+ });
23151
+ } catch (_err) {
23152
+ const cmdName = tokens[0] || "unknown";
23153
+ const errMsg = _err instanceof Error ? _err.message : String(_err);
23154
+ text = `Error executing /swarm ${cmdName}: ${errMsg}`;
23155
+ }
23156
+ if (resolved.warning) {
23157
+ text = `${resolved.warning}
23158
+
23159
+ ${text}`;
23160
+ }
23161
+ }
23162
+ }
23163
+ return {
23164
+ text,
23165
+ resolved: resolved ?? undefined,
23166
+ canonicalKey: resolved ? canonicalCommandKey(resolved) : undefined
23167
+ };
23168
+ }
23169
+ var init_command_dispatch = __esm(() => {
23170
+ init_registry();
23171
+ });
23172
+
23173
+ // src/commands/tool-policy.ts
23174
+ function lazySet(getValues) {
23175
+ let cached2 = null;
23176
+ const ensure = () => {
23177
+ if (cached2 === null)
23178
+ cached2 = new Set(getValues());
23179
+ return cached2;
23180
+ };
23181
+ return new Proxy({}, {
23182
+ get(_target, prop) {
23183
+ const set2 = ensure();
23184
+ const value = Reflect.get(set2, prop);
23185
+ return typeof value === "function" ? value.bind(set2) : value;
23186
+ }
23187
+ });
23188
+ }
23189
+ function lazyArray(getValues) {
23190
+ let cached2 = null;
23191
+ const ensure = () => {
23192
+ if (cached2 === null)
23193
+ cached2 = getValues();
23194
+ return cached2;
23195
+ };
23196
+ return new Proxy([], {
23197
+ get(_target, prop) {
23198
+ const arr = ensure();
23199
+ const value = Reflect.get(arr, prop);
23200
+ return typeof value === "function" ? value.bind(arr) : value;
23201
+ }
23202
+ });
23203
+ }
23204
+ function classifySwarmCommandToolUse(resolved) {
23205
+ const canonicalKey = canonicalCommandKey(resolved);
23206
+ const args = resolved.remainingArgs;
23207
+ if (!SWARM_COMMAND_TOOL_ALLOWLIST.has(canonicalKey)) {
23208
+ if (HUMAN_ONLY_SWARM_COMMANDS.has(canonicalKey)) {
23209
+ return {
23210
+ allowed: false,
23211
+ message: `/swarm ${canonicalKey} is a human-only command. ` + `Present the situation to the user and ask them to run \`/swarm ${canonicalKey}\` themselves ` + `(or \`bunx opencode-swarm run ${canonicalKey}\` from a terminal). ` + `You MUST NOT run it yourself via Bash, swarm_command, or any other tool \u2014 ` + `the runtime guardrail will block such attempts.`
23212
+ };
23213
+ }
23214
+ return {
23215
+ allowed: false,
23216
+ message: `/swarm ${canonicalKey} is not available through the chat tool yet.
23217
+
23218
+ ` + `Use the canonical CLI path for now: \`bunx opencode-swarm run ${canonicalKey}\`.
23219
+ ` + `Commands with state changes, auto-heal behavior, or subprocesses need confirmation gates before chat-tool support.`
23220
+ };
23221
+ }
23222
+ if (canonicalKey === "config doctor" && args.some((arg) => arg === "--fix" || arg === "-f")) {
23223
+ return {
23224
+ allowed: false,
23225
+ message: "/swarm config doctor --fix is not available through swarm_command. Run the CLI command directly when you intend to modify config files."
23226
+ };
23227
+ }
23228
+ if (NO_ARGS.has(canonicalKey) && args.length > 0) {
23229
+ return {
23230
+ allowed: false,
23231
+ message: `/swarm ${canonicalKey} does not accept arguments through swarm_command.`
23232
+ };
23233
+ }
23234
+ if (canonicalKey === "knowledge") {
23235
+ if (args.length === 0)
23236
+ return { allowed: true };
23237
+ if (args.length === 1 && (args[0] === "list" || args[0] === "unactionable"))
23238
+ return { allowed: true };
23239
+ return {
23240
+ allowed: false,
23241
+ message: "Only `/swarm knowledge`, `/swarm knowledge list`, and `/swarm knowledge unactionable` are available through swarm_command. Knowledge migrate/quarantine/restore/retry-hardening are intentionally excluded."
23242
+ };
23243
+ }
23244
+ if (canonicalKey === "memory") {
23245
+ if (args.length === 0)
23246
+ return { allowed: true };
23247
+ return {
23248
+ allowed: false,
23249
+ message: "Use `/swarm memory status`, `/swarm memory pending`, `/swarm memory recall-log`, `/swarm memory stale`, `/swarm memory export`, or `/swarm memory evaluate --json` through swarm_command. Memory import, migrate, and compact are intentionally excluded from chat-tool execution."
23250
+ };
23251
+ }
23252
+ if (canonicalKey === "memory evaluate") {
23253
+ if (args.length === 0)
23254
+ return { allowed: true };
23255
+ if (args.length === 1 && args[0] === "--json")
23256
+ return { allowed: true };
23257
+ return {
23258
+ allowed: false,
23259
+ message: "Usage through swarm_command: `/swarm memory evaluate --json`. Custom fixture directories are only available through direct user command execution."
23260
+ };
23261
+ }
23262
+ if (canonicalKey === "sdd status") {
23263
+ if (args.length === 0)
23264
+ return { allowed: true };
23265
+ if (args.length === 1 && args[0] === "--json")
23266
+ return { allowed: true };
23267
+ return {
23268
+ allowed: false,
23269
+ message: "Usage through swarm_command: `/swarm sdd status` or `/swarm sdd status --json`."
23270
+ };
23271
+ }
23272
+ if (canonicalKey === "sdd validate") {
23273
+ if (args.length === 0)
23274
+ return { allowed: true };
23275
+ if (args.length === 1 && args[0] === "--json")
23276
+ return { allowed: true };
23277
+ if (args.length === 2 && args[0] === "--change" && /^[A-Za-z0-9_.-]{1,128}$/.test(args[1])) {
23278
+ return { allowed: true };
23279
+ }
23280
+ return {
23281
+ allowed: false,
23282
+ message: "Usage through swarm_command: `/swarm sdd validate`, `/swarm sdd validate --json`, or `/swarm sdd validate --change <id>`."
23283
+ };
23284
+ }
23285
+ if (canonicalKey === "memory pending" || canonicalKey === "memory recall-log" || canonicalKey === "memory stale") {
23286
+ if (args.length === 0)
23287
+ return { allowed: true };
23288
+ if (args.length === 2 && args[0] === "--limit" && /^\d+$/.test(args[1])) {
23289
+ return { allowed: true };
23290
+ }
23291
+ return {
23292
+ allowed: false,
23293
+ message: `Usage through swarm_command: \`/swarm ${canonicalKey}\` or ` + `\`/swarm ${canonicalKey} --limit <n>\`.`
23294
+ };
23295
+ }
23296
+ if (canonicalKey === "retrieve") {
23297
+ if (args.length !== 1 || !SUMMARY_ID_PATTERN.test(args[0])) {
23298
+ return {
23299
+ allowed: false,
23300
+ message: "Usage through swarm_command: `/swarm retrieve <summary-id>` with a single summary ID such as S1."
23301
+ };
23302
+ }
23303
+ }
23304
+ if (canonicalKey === "benchmark") {
23305
+ const allowedFlags = new Set(["--cumulative", "--ci-gate"]);
23306
+ const invalid = args.filter((arg) => !allowedFlags.has(arg));
23307
+ if (invalid.length > 0) {
23308
+ return {
23309
+ allowed: false,
23310
+ message: "Only `--cumulative` and `--ci-gate` are supported for `/swarm benchmark` through swarm_command."
23311
+ };
23312
+ }
23313
+ }
23314
+ if (canonicalKey === "show-plan") {
23315
+ if (args.length > 1 || args[0] && !/^\d+$/.test(args[0])) {
23316
+ return {
23317
+ allowed: false,
23318
+ message: "Usage through swarm_command: `/swarm show-plan` or `/swarm show-plan <phase-number>`."
23319
+ };
23320
+ }
23321
+ }
23322
+ if (canonicalKey === "evidence") {
23323
+ if (args.length > 1 || args[0] && !TASK_ID_PATTERN.test(args[0])) {
23324
+ return {
23325
+ allowed: false,
23326
+ message: "Usage through swarm_command: `/swarm evidence` or `/swarm evidence <task-id>`."
23327
+ };
23328
+ }
23329
+ }
23330
+ if (canonicalKey === "help" && args.length > 2) {
23331
+ return {
23332
+ allowed: false,
23333
+ message: "Usage through swarm_command: `/swarm help` or `/swarm help <command>`."
23334
+ };
23335
+ }
23336
+ return { allowed: true };
23337
+ }
23338
+ function classifySwarmCommandChatFallbackUse(resolved) {
23339
+ const canonicalKey = canonicalCommandKey(resolved);
23340
+ const args = resolved.remainingArgs;
23341
+ if (canonicalKey === "config doctor" && args.some((arg) => arg === "--fix" || arg === "-f")) {
23342
+ return {
23343
+ allowed: false,
23344
+ message: "/swarm config doctor --fix is not available through chat fallback because it can modify configuration files. Run the CLI command directly when you intend to apply fixes."
23345
+ };
23346
+ }
23347
+ if (canonicalKey === "knowledge migrate" || canonicalKey === "knowledge quarantine" || canonicalKey === "knowledge restore" || canonicalKey === "memory import" || canonicalKey === "memory migrate" || canonicalKey === "memory compact" || canonicalKey === "sdd project") {
23348
+ return {
23349
+ allowed: false,
23350
+ message: `/swarm ${canonicalKey} is not available through chat fallback because it mutates .swarm state. ` + "Run the CLI command directly after confirming the intended state change."
23351
+ };
23352
+ }
23353
+ return { allowed: true };
23354
+ }
23355
+ var SWARM_COMMAND_TOOL_COMMANDS, SWARM_COMMAND_TOOL_ALLOWLIST, HUMAN_ONLY_SWARM_COMMANDS, NO_ARGS, SUMMARY_ID_PATTERN, TASK_ID_PATTERN;
23356
+ var init_tool_policy = __esm(() => {
23357
+ init_command_dispatch();
23358
+ init_registry();
23359
+ SWARM_COMMAND_TOOL_COMMANDS = lazyArray(() => VALID_COMMANDS.filter((cmd) => {
23360
+ const policy = COMMAND_REGISTRY[cmd]?.toolPolicy;
23361
+ return policy === "agent" || policy === "human-only";
23362
+ }).sort());
23363
+ SWARM_COMMAND_TOOL_ALLOWLIST = lazySet(() => VALID_COMMANDS.filter((cmd) => COMMAND_REGISTRY[cmd]?.toolPolicy === "agent"));
23364
+ HUMAN_ONLY_SWARM_COMMANDS = lazySet(() => VALID_COMMANDS.filter((cmd) => {
23365
+ const policy = COMMAND_REGISTRY[cmd]?.toolPolicy;
23366
+ return policy === "human-only" || policy === "restricted";
23367
+ }));
23368
+ NO_ARGS = lazySet(() => VALID_COMMANDS.filter((cmd) => COMMAND_REGISTRY[cmd]?.toolNoArgs === true));
23369
+ SUMMARY_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
23370
+ TASK_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,64}$/;
23371
+ });
23372
+
23088
23373
  // src/sandbox/executor.ts
23089
23374
  var init_executor = () => {};
23090
23375
 
@@ -23217,6 +23502,7 @@ var init_helpers = __esm(() => {
23217
23502
 
23218
23503
  // src/hooks/guardrails/tool-before.ts
23219
23504
  var init_tool_before = __esm(() => {
23505
+ init_tool_policy();
23220
23506
  init_constants();
23221
23507
  init_schema();
23222
23508
  init_executor();
@@ -37061,7 +37347,7 @@ function resetToRemoteBranch(cwd, options) {
37061
37347
  const prunedBranches = [];
37062
37348
  try {
37063
37349
  const currentBranch = getCurrentBranch(cwd);
37064
- const defaultRemoteBranch = _internals13.detectDefaultRemoteBranch(cwd);
37350
+ const defaultRemoteBranch = _internals14.detectDefaultRemoteBranch(cwd);
37065
37351
  if (!defaultRemoteBranch) {
37066
37352
  return {
37067
37353
  success: false,
@@ -37243,7 +37529,7 @@ function resetToRemoteBranch(cwd, options) {
37243
37529
  function resetToMainAfterMerge(cwd, options) {
37244
37530
  const warnings = [];
37245
37531
  try {
37246
- const defaultBranch = _internals13.detectDefaultRemoteBranch(cwd);
37532
+ const defaultBranch = _internals14.detectDefaultRemoteBranch(cwd);
37247
37533
  if (!defaultBranch) {
37248
37534
  return {
37249
37535
  success: false,
@@ -37270,7 +37556,7 @@ function resetToMainAfterMerge(cwd, options) {
37270
37556
  }
37271
37557
  if (currentBranch === defaultBranch) {
37272
37558
  try {
37273
- const logOutput = _internals13.gitExec(["log", `${targetBranch}..HEAD`, "--oneline"], cwd);
37559
+ const logOutput = _internals14.gitExec(["log", `${targetBranch}..HEAD`, "--oneline"], cwd);
37274
37560
  if (logOutput.trim().length > 0) {
37275
37561
  return {
37276
37562
  success: false,
@@ -37285,11 +37571,11 @@ function resetToMainAfterMerge(cwd, options) {
37285
37571
  } catch {}
37286
37572
  } else {
37287
37573
  try {
37288
- _internals13.gitExec(["rev-parse", "--abbrev-ref", `${currentBranch}@{upstream}`], cwd);
37574
+ _internals14.gitExec(["rev-parse", "--abbrev-ref", `${currentBranch}@{upstream}`], cwd);
37289
37575
  } catch {
37290
37576
  try {
37291
- const localSha = _internals13.gitExec(["rev-parse", "HEAD"], cwd).trim();
37292
- const remoteSha = _internals13.gitExec(["rev-parse", targetBranch], cwd).trim();
37577
+ const localSha = _internals14.gitExec(["rev-parse", "HEAD"], cwd).trim();
37578
+ const remoteSha = _internals14.gitExec(["rev-parse", targetBranch], cwd).trim();
37293
37579
  if (localSha !== remoteSha) {
37294
37580
  return {
37295
37581
  success: false,
@@ -37315,7 +37601,7 @@ function resetToMainAfterMerge(cwd, options) {
37315
37601
  }
37316
37602
  }
37317
37603
  try {
37318
- _internals13.gitExec(["fetch", "--prune", "origin"], cwd);
37604
+ _internals14.gitExec(["fetch", "--prune", "origin"], cwd);
37319
37605
  } catch (err) {
37320
37606
  return {
37321
37607
  success: false,
@@ -37331,7 +37617,7 @@ function resetToMainAfterMerge(cwd, options) {
37331
37617
  let switchedBranch = false;
37332
37618
  if (currentBranch !== defaultBranch) {
37333
37619
  try {
37334
- _internals13.gitExec(["checkout", defaultBranch], cwd);
37620
+ _internals14.gitExec(["checkout", defaultBranch], cwd);
37335
37621
  switchedBranch = true;
37336
37622
  } catch (err) {
37337
37623
  return {
@@ -37346,7 +37632,7 @@ function resetToMainAfterMerge(cwd, options) {
37346
37632
  }
37347
37633
  }
37348
37634
  try {
37349
- _internals13.gitExec(["reset", "--hard", targetBranch], cwd);
37635
+ _internals14.gitExec(["reset", "--hard", targetBranch], cwd);
37350
37636
  } catch (err) {
37351
37637
  return {
37352
37638
  success: false,
@@ -37367,7 +37653,7 @@ function resetToMainAfterMerge(cwd, options) {
37367
37653
  while (Date.now() < endTime) {}
37368
37654
  }
37369
37655
  try {
37370
- _internals13.gitExec(["checkout", "--", "."], cwd);
37656
+ _internals14.gitExec(["checkout", "--", "."], cwd);
37371
37657
  discardSucceeded = true;
37372
37658
  break;
37373
37659
  } catch {}
@@ -37378,18 +37664,18 @@ function resetToMainAfterMerge(cwd, options) {
37378
37664
  changesDiscarded = discardSucceeded;
37379
37665
  }
37380
37666
  try {
37381
- _internals13.gitExec(["clean", "-fd"], cwd);
37667
+ _internals14.gitExec(["clean", "-fd"], cwd);
37382
37668
  } catch {
37383
37669
  warnings.push("Could not clean untracked files");
37384
37670
  }
37385
37671
  let branchDeleted = false;
37386
37672
  if (switchedBranch && previousBranch !== defaultBranch) {
37387
37673
  try {
37388
- const mergedOutput = _internals13.gitExec(["branch", "--merged", defaultBranch], cwd);
37674
+ const mergedOutput = _internals14.gitExec(["branch", "--merged", defaultBranch], cwd);
37389
37675
  const isMerged = mergedOutput.split(`
37390
37676
  `).some((line) => line.trim() === previousBranch || line.trim() === `* ${previousBranch}`);
37391
37677
  if (isMerged) {
37392
- _internals13.gitExec(["branch", "-d", previousBranch], cwd);
37678
+ _internals14.gitExec(["branch", "-d", previousBranch], cwd);
37393
37679
  branchDeleted = true;
37394
37680
  } else {
37395
37681
  warnings.push(`Branch ${previousBranch} is not merged into ${defaultBranch} \u2014 keeping it`);
@@ -37400,7 +37686,7 @@ function resetToMainAfterMerge(cwd, options) {
37400
37686
  }
37401
37687
  if (options?.pruneBranches) {
37402
37688
  try {
37403
- const mergedOutput = _internals13.gitExec(["branch", "--merged", defaultBranch], cwd);
37689
+ const mergedOutput = _internals14.gitExec(["branch", "--merged", defaultBranch], cwd);
37404
37690
  const mergedLines = mergedOutput.split(`
37405
37691
  `);
37406
37692
  for (const line of mergedLines) {
@@ -37409,7 +37695,7 @@ function resetToMainAfterMerge(cwd, options) {
37409
37695
  continue;
37410
37696
  }
37411
37697
  try {
37412
- _internals13.gitExec(["branch", "-d", trimmedLine], cwd);
37698
+ _internals14.gitExec(["branch", "-d", trimmedLine], cwd);
37413
37699
  } catch {
37414
37700
  warnings.push(`Could not prune branch: ${trimmedLine}`);
37415
37701
  }
@@ -37439,10 +37725,10 @@ function resetToMainAfterMerge(cwd, options) {
37439
37725
  };
37440
37726
  }
37441
37727
  }
37442
- var GIT_TIMEOUT_MS2 = 30000, _internals13;
37728
+ var GIT_TIMEOUT_MS2 = 30000, _internals14;
37443
37729
  var init_branch = __esm(() => {
37444
37730
  init_logger();
37445
- _internals13 = {
37731
+ _internals14 = {
37446
37732
  gitExec: gitExec2,
37447
37733
  detectDefaultRemoteBranch,
37448
37734
  getDefaultBaseBranch,
@@ -37661,18 +37947,18 @@ async function atomicWriteFile(targetPath, content) {
37661
37947
  const tempPath = `${targetPath}.tmp.${Date.now()}.${Math.floor(Math.random() * 1e9)}`;
37662
37948
  try {
37663
37949
  await bunWrite(tempPath, content);
37664
- _internals14.renameSync(tempPath, targetPath);
37950
+ _internals15.renameSync(tempPath, targetPath);
37665
37951
  } finally {
37666
37952
  try {
37667
- _internals14.unlinkSync(tempPath);
37953
+ _internals15.unlinkSync(tempPath);
37668
37954
  } catch {}
37669
37955
  }
37670
37956
  }
37671
- var _internals14;
37957
+ var _internals15;
37672
37958
  var init_task_file = __esm(() => {
37673
37959
  init_bun_compat();
37674
37960
  init_lock();
37675
- _internals14 = {
37961
+ _internals15 = {
37676
37962
  renameSync: renameSync6,
37677
37963
  unlinkSync: unlinkSync4
37678
37964
  };
@@ -40333,7 +40619,7 @@ async function activateProposal(directory, slug, force = false, options = {}) {
40333
40619
  try {
40334
40620
  await stampSourceEntries(directory, cleanSlug, fm.sourceKnowledgeIds);
40335
40621
  try {
40336
- _internals15.unlinkSync(from);
40622
+ _internals16.unlinkSync(from);
40337
40623
  } catch {}
40338
40624
  return {
40339
40625
  activated: true,
@@ -40438,7 +40724,7 @@ async function autoApplyProposals(directory, llmDelegate) {
40438
40724
  }
40439
40725
  } else if (verdict === "REJECT") {
40440
40726
  try {
40441
- _internals15.unlinkSync(proposal.path);
40727
+ _internals16.unlinkSync(proposal.path);
40442
40728
  warn(`[skill-generator] auto-apply rejected proposal "${proposal.slug}"; deleted ${proposal.path}`);
40443
40729
  result.rejected.push(proposal.slug);
40444
40730
  } catch (delErr) {
@@ -40548,7 +40834,7 @@ async function regenerateSkill(directory, slug, options = {}) {
40548
40834
  matchedEntries = all.filter((e) => idSet.has(e.id));
40549
40835
  if (matchedEntries.length === idSet.size && idSet.size > 0 && matchedEntries.every((e) => e.status === "archived")) {
40550
40836
  try {
40551
- await _internals15.retireSkill(directory, cleanSlug, "auto-retire: all source knowledge entries archived at regeneration time");
40837
+ await _internals16.retireSkill(directory, cleanSlug, "auto-retire: all source knowledge entries archived at regeneration time");
40552
40838
  } catch {}
40553
40839
  return {
40554
40840
  regenerated: false,
@@ -40571,7 +40857,7 @@ async function regenerateSkill(directory, slug, options = {}) {
40571
40857
  const activeEntries = matchedEntries.filter((e) => e.status !== "archived");
40572
40858
  if (activeEntries.length === 0) {
40573
40859
  try {
40574
- await _internals15.retireSkill(directory, cleanSlug, "auto-retire: all matched source knowledge entries archived at regeneration time");
40860
+ await _internals16.retireSkill(directory, cleanSlug, "auto-retire: all matched source knowledge entries archived at regeneration time");
40575
40861
  } catch {}
40576
40862
  return {
40577
40863
  regenerated: false,
@@ -40688,7 +40974,7 @@ async function regenerateSkill(directory, slug, options = {}) {
40688
40974
  evaluation
40689
40975
  };
40690
40976
  }
40691
- var SLUG_PATTERN2, DEFAULT_SKILL_MIN_CONFIDENCE = 0.7, DEFAULT_SKILL_MIN_CONFIRMATIONS = 2, STRONG_SKILL_OUTCOME_COUNT = 3, MIN_CLUSTER_SIZE = 2, JACCARD_THRESHOLD = 0.5, AUTO_APPLY_BATCH_LIMIT = 5, _internals15;
40977
+ var SLUG_PATTERN2, DEFAULT_SKILL_MIN_CONFIDENCE = 0.7, DEFAULT_SKILL_MIN_CONFIRMATIONS = 2, STRONG_SKILL_OUTCOME_COUNT = 3, MIN_CLUSTER_SIZE = 2, JACCARD_THRESHOLD = 0.5, AUTO_APPLY_BATCH_LIMIT = 5, _internals16;
40692
40978
  var init_skill_generator = __esm(() => {
40693
40979
  init_knowledge_events();
40694
40980
  init_knowledge_store();
@@ -40697,7 +40983,7 @@ var init_skill_generator = __esm(() => {
40697
40983
  init_skill_changelog();
40698
40984
  init_skill_evaluator();
40699
40985
  SLUG_PATTERN2 = /^[a-z0-9][a-z0-9-]{0,63}$/;
40700
- _internals15 = {
40986
+ _internals16 = {
40701
40987
  sanitizeSlug,
40702
40988
  isValidSlug: isValidSlug2,
40703
40989
  selectCandidateEntries,
@@ -40920,9 +41206,9 @@ function parseFeedbackMarker(raw) {
40920
41206
  function readFeedbackAppliedEntryIds(directory) {
40921
41207
  const resolved = resolveLogPath(directory);
40922
41208
  const processed = new Set;
40923
- if (!_internals16.existsSync(resolved))
41209
+ if (!_internals17.existsSync(resolved))
40924
41210
  return processed;
40925
- const raw = _internals16.readFileSync(resolved, "utf-8");
41211
+ const raw = _internals17.readFileSync(resolved, "utf-8");
40926
41212
  for (const line of raw.split(`
40927
41213
  `)) {
40928
41214
  const trimmed = line.trim();
@@ -40943,15 +41229,15 @@ function appendFeedbackAppliedMarker(directory, processedEntryIds) {
40943
41229
  return;
40944
41230
  const resolved = resolveLogPath(directory);
40945
41231
  const dir = path20.dirname(resolved);
40946
- if (!_internals16.existsSync(dir)) {
40947
- _internals16.mkdirSync(dir, { recursive: true });
41232
+ if (!_internals17.existsSync(dir)) {
41233
+ _internals17.mkdirSync(dir, { recursive: true });
40948
41234
  }
40949
41235
  const marker = {
40950
41236
  type: "feedback_applied",
40951
41237
  timestamp: new Date().toISOString(),
40952
41238
  processedEntryIds: [...new Set(processedEntryIds)]
40953
41239
  };
40954
- _internals16.appendFileSync(resolved, `${JSON.stringify(marker)}
41240
+ _internals17.appendFileSync(resolved, `${JSON.stringify(marker)}
40955
41241
  `, "utf-8");
40956
41242
  }
40957
41243
  function appendSkillUsageEntry(directory, entry) {
@@ -40988,11 +41274,11 @@ function appendSkillUsageEntry(directory, entry) {
40988
41274
  }
40989
41275
  const resolved = validateSwarmPath(directory, "skill-usage.jsonl");
40990
41276
  const dir = path20.dirname(resolved);
40991
- if (!_internals16.existsSync(dir)) {
40992
- _internals16.mkdirSync(dir, { recursive: true });
41277
+ if (!_internals17.existsSync(dir)) {
41278
+ _internals17.mkdirSync(dir, { recursive: true });
40993
41279
  }
40994
41280
  const fullEntry = {
40995
- id: _internals16.generateId(),
41281
+ id: _internals17.generateId(),
40996
41282
  skillPath,
40997
41283
  agentName,
40998
41284
  taskID,
@@ -41002,21 +41288,21 @@ function appendSkillUsageEntry(directory, entry) {
41002
41288
  ...reviewerNotes !== undefined && { reviewerNotes },
41003
41289
  ...skillVersion !== undefined && { skillVersion }
41004
41290
  };
41005
- _internals16.appendFileSync(resolved, `${JSON.stringify(fullEntry)}
41291
+ _internals17.appendFileSync(resolved, `${JSON.stringify(fullEntry)}
41006
41292
  `, "utf-8");
41007
41293
  try {
41008
- const stat5 = _internals16.statSync(resolved);
41294
+ const stat5 = _internals17.statSync(resolved);
41009
41295
  if (stat5.size > SKILL_USAGE_LOG_ROTATE_BYTES) {
41010
- _internals16.pruneSkillUsageLog(directory, SKILL_USAGE_LOG_MAX_ENTRIES_PER_SKILL);
41296
+ _internals17.pruneSkillUsageLog(directory, SKILL_USAGE_LOG_MAX_ENTRIES_PER_SKILL);
41011
41297
  }
41012
41298
  } catch {}
41013
41299
  }
41014
41300
  function readSkillUsageEntries(directory, options) {
41015
41301
  const resolved = resolveLogPath(directory);
41016
- if (!_internals16.existsSync(resolved)) {
41302
+ if (!_internals17.existsSync(resolved)) {
41017
41303
  return [];
41018
41304
  }
41019
- const raw = _internals16.readFileSync(resolved, "utf-8");
41305
+ const raw = _internals17.readFileSync(resolved, "utf-8");
41020
41306
  const entries = [];
41021
41307
  for (const line of raw.split(`
41022
41308
  `)) {
@@ -41055,20 +41341,20 @@ function readSkillUsageEntries(directory, options) {
41055
41341
  }
41056
41342
  function readSkillUsageEntriesTail(directory, filters, maxBytes = TAIL_BYTES_DEFAULT) {
41057
41343
  const logPath = resolveLogPath(directory);
41058
- if (!_internals16.existsSync(logPath))
41344
+ if (!_internals17.existsSync(logPath))
41059
41345
  return [];
41060
41346
  try {
41061
41347
  const normalizedMaxBytes = Number.isFinite(maxBytes) ? maxBytes : TAIL_BYTES_DEFAULT;
41062
41348
  const boundedMaxBytes = Math.min(Math.max(1, normalizedMaxBytes), MAX_TAIL_BYTES);
41063
- const stat5 = _internals16.statSync(logPath);
41349
+ const stat5 = _internals17.statSync(logPath);
41064
41350
  const start = Math.max(0, stat5.size - boundedMaxBytes);
41065
- const fd = _internals16.openSync(logPath, "r");
41351
+ const fd = _internals17.openSync(logPath, "r");
41066
41352
  try {
41067
41353
  const readLen = stat5.size - start;
41068
41354
  if (readLen === 0)
41069
41355
  return [];
41070
41356
  const buf = Buffer.alloc(readLen);
41071
- _internals16.readSync(fd, buf, 0, buf.length, start);
41357
+ _internals17.readSync(fd, buf, 0, buf.length, start);
41072
41358
  const content = buf.toString("utf-8");
41073
41359
  let usable;
41074
41360
  if (start > 0) {
@@ -41095,7 +41381,7 @@ function readSkillUsageEntriesTail(directory, filters, maxBytes = TAIL_BYTES_DEF
41095
41381
  }
41096
41382
  return entries;
41097
41383
  } finally {
41098
- _internals16.closeSync(fd);
41384
+ _internals17.closeSync(fd);
41099
41385
  }
41100
41386
  } catch {
41101
41387
  return [];
@@ -41132,7 +41418,7 @@ function computeComplianceByVersion(entries, skillPath) {
41132
41418
  }
41133
41419
  function pruneSkillUsageLog(directory, maxEntriesPerSkill = 500) {
41134
41420
  const resolved = resolveLogPath(directory);
41135
- if (!_internals16.existsSync(resolved)) {
41421
+ if (!_internals17.existsSync(resolved)) {
41136
41422
  return { pruned: 0, remaining: 0 };
41137
41423
  }
41138
41424
  const allEntries = readSkillUsageEntries(directory);
@@ -41168,13 +41454,13 @@ function pruneSkillUsageLog(directory, maxEntriesPerSkill = 500) {
41168
41454
  `).concat(`
41169
41455
  `);
41170
41456
  try {
41171
- _internals16.writeFileSync(tmpPath, content, "utf-8");
41172
- _internals16.renameSync(tmpPath, resolved);
41457
+ _internals17.writeFileSync(tmpPath, content, "utf-8");
41458
+ _internals17.renameSync(tmpPath, resolved);
41173
41459
  } catch (writeErr) {
41174
41460
  const msg = writeErr instanceof Error ? writeErr.message : String(writeErr);
41175
41461
  try {
41176
- if (_internals16.existsSync(tmpPath)) {
41177
- _internals16.writeFileSync(tmpPath, "", "utf-8");
41462
+ if (_internals17.existsSync(tmpPath)) {
41463
+ _internals17.writeFileSync(tmpPath, "", "utf-8");
41178
41464
  }
41179
41465
  } catch {}
41180
41466
  return { pruned: 0, remaining: allEntries.length, error: msg };
@@ -41196,10 +41482,10 @@ async function resolveSourceKnowledgeIds(directory, skillPath) {
41196
41482
  if (!isContained) {
41197
41483
  return [];
41198
41484
  }
41199
- if (!_internals16.existsSync(absolute)) {
41485
+ if (!_internals17.existsSync(absolute)) {
41200
41486
  return [];
41201
41487
  }
41202
- const content = _internals16.readFileSync(absolute, "utf-8");
41488
+ const content = _internals17.readFileSync(absolute, "utf-8");
41203
41489
  return parseGeneratedFromKnowledge(content);
41204
41490
  } catch (err) {
41205
41491
  console.warn("[skill-usage-log] resolveSourceKnowledgeIds failed (fail-open):", err instanceof Error ? err.message : String(err));
@@ -41299,11 +41585,11 @@ async function applySkillUsageFeedback(directory, options) {
41299
41585
  }
41300
41586
  return { processed, bumps };
41301
41587
  }
41302
- var _internals16, TAIL_BYTES_DEFAULT, MAX_TAIL_BYTES, SKILL_USAGE_LOG_ROTATE_BYTES, SKILL_USAGE_LOG_MAX_ENTRIES_PER_SKILL = 500, COMPLIANCE_BOOST = 0.05, VIOLATION_DECAY = 0.1;
41588
+ var _internals17, TAIL_BYTES_DEFAULT, MAX_TAIL_BYTES, SKILL_USAGE_LOG_ROTATE_BYTES, SKILL_USAGE_LOG_MAX_ENTRIES_PER_SKILL = 500, COMPLIANCE_BOOST = 0.05, VIOLATION_DECAY = 0.1;
41303
41589
  var init_skill_usage_log = __esm(() => {
41304
41590
  init_knowledge_store();
41305
41591
  init_utils2();
41306
- _internals16 = {
41592
+ _internals17 = {
41307
41593
  generateId: () => crypto3.randomUUID(),
41308
41594
  appendFileSync: fs9.appendFileSync.bind(fs9),
41309
41595
  readFileSync: fs9.readFileSync.bind(fs9),
@@ -42099,7 +42385,7 @@ function rankSkillsForContext(skills, taskContext, directory) {
42099
42385
  const results = [];
42100
42386
  for (const skillPath of skills) {
42101
42387
  const skillEntries = allEntries.filter((e) => e.skillPath === skillPath);
42102
- const metadata = _internals17.readSkillMetadata(skillPath, directory);
42388
+ const metadata = _internals18.readSkillMetadata(skillPath, directory);
42103
42389
  const score = computeSkillRelevanceScore(skillPath, taskContext, skillEntries, metadata);
42104
42390
  const entriesWithVerdict = skillEntries.filter((e) => e.complianceVerdict !== undefined && e.complianceVerdict !== "not_checked");
42105
42391
  const compliantCount = entriesWithVerdict.filter((e) => e.complianceVerdict === "compliant").length;
@@ -42154,7 +42440,7 @@ function formatSkillIndexWithContext(skills, directory) {
42154
42440
  } catch {}
42155
42441
  if (!hasHistory) {
42156
42442
  return skills.map((sp) => {
42157
- const meta3 = _internals17.readSkillMetadata(sp, directory);
42443
+ const meta3 = _internals18.readSkillMetadata(sp, directory);
42158
42444
  return ` - file:${meta3.path} - ${meta3.name}: ${meta3.description}`;
42159
42445
  }).join(`
42160
42446
  `);
@@ -42162,7 +42448,7 @@ function formatSkillIndexWithContext(skills, directory) {
42162
42448
  const lines = [];
42163
42449
  for (const skillPath of skills) {
42164
42450
  const stats = getSkillStats(skillPath, directory);
42165
- const meta3 = _internals17.readSkillMetadata(skillPath, directory);
42451
+ const meta3 = _internals18.readSkillMetadata(skillPath, directory);
42166
42452
  const compliancePct = Math.round(stats.complianceRate * 100);
42167
42453
  const topAgentNames = stats.topAgents.slice(0, 3).map((a) => a.agent).join(", ");
42168
42454
  lines.push(` - file:${meta3.path} - ${meta3.name}: ${meta3.description} (used: ${stats.totalUsage}, compliance: ${compliancePct}%)` + (stats.topAgents.length > 0 ? ` \u2192 ${topAgentNames}` : ""));
@@ -42170,12 +42456,12 @@ function formatSkillIndexWithContext(skills, directory) {
42170
42456
  return lines.join(`
42171
42457
  `);
42172
42458
  }
42173
- var FREQUENCY_CAP = 10, FREQUENCY_WEIGHT = 0.3, COMPLIANCE_WEIGHT = 0.3, RECENCY_WEIGHT = 0.15, TASK_DIVERSITY_WEIGHT = 0.05, CONTEXT_WEIGHT = 0.2, WORKFLOW_BOOST = 0.1, SKILL_TRIGGER_BOOST = 0.3, SKILL_TRIGGER_MIN_LENGTH = 3, MAX_SKILL_TRIGGERS = 20, MAX_SKILL_TRIGGER_LENGTH = 120, WORKFLOW_BOOST_MIN_CONTEXT = 0.05, RECENCY_DECAY_MS, SKILL_FRONTMATTER_READ_BYTES, _internals17, MIN_KEYWORD_LENGTH = 3;
42459
+ var FREQUENCY_CAP = 10, FREQUENCY_WEIGHT = 0.3, COMPLIANCE_WEIGHT = 0.3, RECENCY_WEIGHT = 0.15, TASK_DIVERSITY_WEIGHT = 0.05, CONTEXT_WEIGHT = 0.2, WORKFLOW_BOOST = 0.1, SKILL_TRIGGER_BOOST = 0.3, SKILL_TRIGGER_MIN_LENGTH = 3, MAX_SKILL_TRIGGERS = 20, MAX_SKILL_TRIGGER_LENGTH = 120, WORKFLOW_BOOST_MIN_CONTEXT = 0.05, RECENCY_DECAY_MS, SKILL_FRONTMATTER_READ_BYTES, _internals18, MIN_KEYWORD_LENGTH = 3;
42174
42460
  var init_skill_scoring = __esm(() => {
42175
42461
  init_skill_usage_log();
42176
42462
  RECENCY_DECAY_MS = 30 * 24 * 60 * 60 * 1000;
42177
42463
  SKILL_FRONTMATTER_READ_BYTES = 16 * 1024;
42178
- _internals17 = {
42464
+ _internals18 = {
42179
42465
  computeSkillRelevanceScore: null,
42180
42466
  rankSkillsForContext: null,
42181
42467
  getSkillStats: null,
@@ -42187,16 +42473,16 @@ var init_skill_scoring = __esm(() => {
42187
42473
  computeContextMatchScore: null,
42188
42474
  computeTriggerMatchBoost: null
42189
42475
  };
42190
- _internals17.computeSkillRelevanceScore = computeSkillRelevanceScore;
42191
- _internals17.rankSkillsForContext = rankSkillsForContext;
42192
- _internals17.getSkillStats = getSkillStats;
42193
- _internals17.formatSkillIndexWithContext = formatSkillIndexWithContext;
42194
- _internals17.parseSkillFrontmatter = parseSkillFrontmatter;
42195
- _internals17.readSkillMetadata = readSkillMetadata;
42196
- _internals17.extractSkillName = extractSkillName;
42197
- _internals17.computeRecencyScore = computeRecencyScore;
42198
- _internals17.computeContextMatchScore = computeContextMatchScore;
42199
- _internals17.computeTriggerMatchBoost = computeTriggerMatchBoost;
42476
+ _internals18.computeSkillRelevanceScore = computeSkillRelevanceScore;
42477
+ _internals18.rankSkillsForContext = rankSkillsForContext;
42478
+ _internals18.getSkillStats = getSkillStats;
42479
+ _internals18.formatSkillIndexWithContext = formatSkillIndexWithContext;
42480
+ _internals18.parseSkillFrontmatter = parseSkillFrontmatter;
42481
+ _internals18.readSkillMetadata = readSkillMetadata;
42482
+ _internals18.extractSkillName = extractSkillName;
42483
+ _internals18.computeRecencyScore = computeRecencyScore;
42484
+ _internals18.computeContextMatchScore = computeContextMatchScore;
42485
+ _internals18.computeTriggerMatchBoost = computeTriggerMatchBoost;
42200
42486
  });
42201
42487
 
42202
42488
  // src/hooks/skill-propagation-gate.ts
@@ -42301,10 +42587,10 @@ function parseYamlValue(value) {
42301
42587
  }
42302
42588
  function loadRoutingSkills(directory, targetAgent) {
42303
42589
  const routingPath = path24.join(directory, ".opencode", "skill-routing.yaml");
42304
- if (!_internals18.existsSync(routingPath))
42590
+ if (!_internals19.existsSync(routingPath))
42305
42591
  return [];
42306
42592
  try {
42307
- const content = _internals18.readFileSync(routingPath, "utf-8");
42593
+ const content = _internals19.readFileSync(routingPath, "utf-8");
42308
42594
  const config3 = parseSimpleYaml(content);
42309
42595
  if (!config3?.routing)
42310
42596
  return [];
@@ -42321,11 +42607,11 @@ function discoverAvailableSkills(directory) {
42321
42607
  const results = [];
42322
42608
  for (const root of SKILL_SEARCH_ROOTS) {
42323
42609
  const rootPath = path24.join(directory, root);
42324
- if (!_internals18.existsSync(rootPath))
42610
+ if (!_internals19.existsSync(rootPath))
42325
42611
  continue;
42326
42612
  let entries;
42327
42613
  try {
42328
- entries = _internals18.readdirSync(rootPath);
42614
+ entries = _internals19.readdirSync(rootPath);
42329
42615
  } catch {
42330
42616
  continue;
42331
42617
  }
@@ -42333,11 +42619,11 @@ function discoverAvailableSkills(directory) {
42333
42619
  if (entry.startsWith("."))
42334
42620
  continue;
42335
42621
  const skillDir = path24.join(rootPath, entry);
42336
- if (_internals18.existsSync(path24.join(skillDir, "retired.marker")))
42622
+ if (_internals19.existsSync(path24.join(skillDir, "retired.marker")))
42337
42623
  continue;
42338
42624
  const skillFile = path24.join(skillDir, "SKILL.md");
42339
42625
  try {
42340
- if (_internals18.statSync(skillDir).isDirectory() && _internals18.existsSync(skillFile)) {
42626
+ if (_internals19.statSync(skillDir).isDirectory() && _internals19.existsSync(skillFile)) {
42341
42627
  results.push(path24.join(root, entry, "SKILL.md").replace(/\\/g, "/"));
42342
42628
  }
42343
42629
  } catch (err) {
@@ -42369,7 +42655,7 @@ function parseDelegationArgs(args) {
42369
42655
  }
42370
42656
  if (!targetAgent)
42371
42657
  return null;
42372
- const skillsField = prompt ? _internals18.extractSkillsFieldFromPrompt(prompt) : "";
42658
+ const skillsField = prompt ? _internals19.extractSkillsFieldFromPrompt(prompt) : "";
42373
42659
  return { targetAgent, skillsField };
42374
42660
  }
42375
42661
  function extractSkillsFieldFromPrompt(prompt) {
@@ -42410,10 +42696,10 @@ function writeWarnEvent(directory, record3) {
42410
42696
  const filePath = path24.join(directory, ".swarm", "events.jsonl");
42411
42697
  try {
42412
42698
  const dir = path24.dirname(filePath);
42413
- if (!_internals18.existsSync(dir)) {
42414
- _internals18.mkdirSync(dir, { recursive: true });
42699
+ if (!_internals19.existsSync(dir)) {
42700
+ _internals19.mkdirSync(dir, { recursive: true });
42415
42701
  }
42416
- _internals18.appendFileSync(filePath, `${JSON.stringify(record3)}
42702
+ _internals19.appendFileSync(filePath, `${JSON.stringify(record3)}
42417
42703
  `, "utf-8");
42418
42704
  } catch (err) {
42419
42705
  warn(`[skill-propagation-gate] failed to write warning event: ${err instanceof Error ? err.message : String(err)}`);
@@ -42464,19 +42750,19 @@ async function skillPropagationGateBefore(directory, input, config3) {
42464
42750
  const baseAgent = stripKnownSwarmPrefix(agentRaw);
42465
42751
  if (baseAgent !== "architect")
42466
42752
  return { blocked: false, reason: null, recommendedSkills: undefined };
42467
- const parsed = _internals18.parseDelegationArgs(input.args);
42753
+ const parsed = _internals19.parseDelegationArgs(input.args);
42468
42754
  if (!parsed)
42469
42755
  return { blocked: false, reason: null, recommendedSkills: undefined };
42470
42756
  const targetBase = stripKnownSwarmPrefix(parsed.targetAgent);
42471
- if (!_internals18.SKILL_CAPABLE_AGENTS.has(targetBase))
42757
+ if (!_internals19.SKILL_CAPABLE_AGENTS.has(targetBase))
42472
42758
  return { blocked: false, reason: null, recommendedSkills: undefined };
42473
42759
  const sessionID = typeof input.sessionID === "string" ? input.sessionID : "unknown";
42474
- const availableSkills = _internals18.discoverAvailableSkills(directory);
42760
+ const availableSkills = _internals19.discoverAvailableSkills(directory);
42475
42761
  const skillsValue = parsed.skillsField.trim();
42476
42762
  if (skillsValue && skillsValue.toLowerCase() !== "none") {
42477
42763
  const prompt = typeof input.args?.prompt === "string" ? String(input.args.prompt) : "";
42478
- const taskId = _internals18.extractTaskIdFromPrompt(prompt);
42479
- const skillPaths = _internals18.parseSkillPaths(skillsValue);
42764
+ const taskId = _internals19.extractTaskIdFromPrompt(prompt);
42765
+ const skillPaths = _internals19.parseSkillPaths(skillsValue);
42480
42766
  let coderSkillPaths = [];
42481
42767
  if (prompt) {
42482
42768
  for (const line of prompt.split(`
@@ -42484,7 +42770,7 @@ async function skillPropagationGateBefore(directory, input, config3) {
42484
42770
  const trimmed = line.trim();
42485
42771
  if (trimmed.startsWith("SKILLS_USED_BY_CODER:")) {
42486
42772
  const fieldVal = trimmed.slice("SKILLS_USED_BY_CODER:".length).trim();
42487
- coderSkillPaths = _internals18.parseSkillPaths(fieldVal);
42773
+ coderSkillPaths = _internals19.parseSkillPaths(fieldVal);
42488
42774
  break;
42489
42775
  }
42490
42776
  }
@@ -42492,7 +42778,7 @@ async function skillPropagationGateBefore(directory, input, config3) {
42492
42778
  const allPaths = [...new Set([...skillPaths, ...coderSkillPaths])];
42493
42779
  for (const skillPath of allPaths) {
42494
42780
  try {
42495
- _internals18.appendSkillUsageEntry(directory, {
42781
+ _internals19.appendSkillUsageEntry(directory, {
42496
42782
  skillPath,
42497
42783
  agentName: targetBase,
42498
42784
  taskID: taskId,
@@ -42509,18 +42795,18 @@ async function skillPropagationGateBefore(directory, input, config3) {
42509
42795
  let scored = [];
42510
42796
  if (skillsValue.toLowerCase() !== "none" && availableSkills.length > 0) {
42511
42797
  try {
42512
- const sessionEntries = _internals18.readSkillUsageEntriesTail(directory, {
42798
+ const sessionEntries = _internals19.readSkillUsageEntriesTail(directory, {
42513
42799
  sessionID
42514
42800
  });
42515
- if (sessionEntries.length > _internals18.MAX_SCORING_SESSION_ENTRIES) {
42801
+ if (sessionEntries.length > _internals19.MAX_SCORING_SESSION_ENTRIES) {
42516
42802
  scoringSkipped = true;
42517
- warn(`[skill-propagation-gate] skipping scoring \u2014 tail window has ${sessionEntries.length} session entries (limit: ${_internals18.MAX_SCORING_SESSION_ENTRIES})`);
42803
+ warn(`[skill-propagation-gate] skipping scoring \u2014 tail window has ${sessionEntries.length} session entries (limit: ${_internals19.MAX_SCORING_SESSION_ENTRIES})`);
42518
42804
  } else {
42519
42805
  const prompt = typeof input.args?.prompt === "string" ? String(input.args.prompt) : "";
42520
42806
  scored = availableSkills.map((skillPath) => {
42521
42807
  const skillEntries = sessionEntries.filter((e) => e.skillPath === skillPath);
42522
- const metadata = _internals18.readSkillMetadata(skillPath, directory);
42523
- const score = _internals18.computeSkillRelevanceScore(skillPath, prompt, skillEntries, metadata);
42808
+ const metadata = _internals19.readSkillMetadata(skillPath, directory);
42809
+ const score = _internals19.computeSkillRelevanceScore(skillPath, prompt, skillEntries, metadata);
42524
42810
  return { skillPath, score, usageCount: skillEntries.length };
42525
42811
  }).sort((a, b) => b.score - a.score || b.usageCount - a.usageCount);
42526
42812
  if (scored.length > 0) {
@@ -42534,12 +42820,12 @@ async function skillPropagationGateBefore(directory, input, config3) {
42534
42820
  }
42535
42821
  }
42536
42822
  try {
42537
- const routingPaths = _internals18.loadRoutingSkills(directory, targetBase);
42823
+ const routingPaths = _internals19.loadRoutingSkills(directory, targetBase);
42538
42824
  if (routingPaths.length > 0) {
42539
42825
  const existingPaths = new Set(scored.map((s) => s.skillPath));
42540
42826
  for (const routingPath of routingPaths) {
42541
42827
  const routedSkillDir = path24.dirname(path24.join(directory, routingPath));
42542
- if (_internals18.existsSync(path24.join(routedSkillDir, "retired.marker")))
42828
+ if (_internals19.existsSync(path24.join(routedSkillDir, "retired.marker")))
42543
42829
  continue;
42544
42830
  if (!existingPaths.has(routingPath)) {
42545
42831
  scored.push({
@@ -42565,12 +42851,12 @@ async function skillPropagationGateBefore(directory, input, config3) {
42565
42851
  } else if (typeof scored !== "undefined" && scored.length > 0) {
42566
42852
  skillsForIndex = scored.map((r) => r.skillPath);
42567
42853
  }
42568
- const formattedIndex = _internals18.formatSkillIndexWithContext(skillsForIndex, directory);
42854
+ const formattedIndex = _internals19.formatSkillIndexWithContext(skillsForIndex, directory);
42569
42855
  if (formattedIndex.length > 0) {
42570
42856
  const contextPath = path24.join(directory, ".swarm", "context.md");
42571
42857
  let existingContent = "";
42572
- if (_internals18.existsSync(contextPath)) {
42573
- existingContent = _internals18.readFileSync(contextPath, "utf-8");
42858
+ if (_internals19.existsSync(contextPath)) {
42859
+ existingContent = _internals19.readFileSync(contextPath, "utf-8");
42574
42860
  }
42575
42861
  const sectionHeader = "## Available Skills";
42576
42862
  const newSection = `${sectionHeader}
@@ -42590,10 +42876,10 @@ ${newSection}`;
42590
42876
  }
42591
42877
  }
42592
42878
  const swarmDir = path24.dirname(contextPath);
42593
- if (!_internals18.existsSync(swarmDir)) {
42594
- _internals18.mkdirSync(swarmDir, { recursive: true });
42879
+ if (!_internals19.existsSync(swarmDir)) {
42880
+ _internals19.mkdirSync(swarmDir, { recursive: true });
42595
42881
  }
42596
- _internals18.writeFileSync(contextPath, updatedContent, "utf-8");
42882
+ _internals19.writeFileSync(contextPath, updatedContent, "utf-8");
42597
42883
  }
42598
42884
  } catch (err) {
42599
42885
  warn(`[skill-propagation-gate] failed to write skill index to context.md: ${err instanceof Error ? err.message : String(err)}`);
@@ -42619,7 +42905,7 @@ ${newSection}`;
42619
42905
  });
42620
42906
  const warningMsg = `Skill propagation warning: Delegating to ${targetBase} without SKILLS field. ` + `Available skills: ${skillNames.join(", ")}`;
42621
42907
  try {
42622
- _internals18.writeWarnEvent(directory, {
42908
+ _internals19.writeWarnEvent(directory, {
42623
42909
  type: "skill_propagation_warn",
42624
42910
  timestamp: new Date().toISOString(),
42625
42911
  tool: toolName,
@@ -42646,7 +42932,7 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
42646
42932
  let dedupKeys = new Set;
42647
42933
  let existingEntries = [];
42648
42934
  try {
42649
- existingEntries = _internals18.readSkillUsageEntriesTail(directory, {
42935
+ existingEntries = _internals19.readSkillUsageEntriesTail(directory, {
42650
42936
  sessionID
42651
42937
  });
42652
42938
  dedupKeys = new Set(existingEntries.map((e, i) => {
@@ -42684,7 +42970,7 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
42684
42970
  }
42685
42971
  const coderMatch = trimmed.match(CODER_SKILLS_PATTERN);
42686
42972
  if (coderMatch) {
42687
- const parsed = _internals18.parseSkillPaths(coderMatch[1]);
42973
+ const parsed = _internals19.parseSkillPaths(coderMatch[1]);
42688
42974
  skillPaths.push(...parsed);
42689
42975
  }
42690
42976
  }
@@ -42717,7 +43003,7 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
42717
43003
  if (isDuplicate(skillPath, "reviewer", resolvedTaskID))
42718
43004
  continue;
42719
43005
  try {
42720
- _internals18.appendSkillUsageEntry(directory, {
43006
+ _internals19.appendSkillUsageEntry(directory, {
42721
43007
  skillPath,
42722
43008
  agentName: "reviewer",
42723
43009
  taskID: resolvedTaskID,
@@ -42761,15 +43047,15 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
42761
43047
  skillsField = trimmed.slice("SKILLS:".length).trim();
42762
43048
  }
42763
43049
  if (currentTargetAgent && skillsField && skillsField.toLowerCase() !== "none") {
42764
- const skillPaths = _internals18.parseSkillPaths(skillsField);
42765
- const taskId = _internals18.extractTaskIdFromPrompt(text);
43050
+ const skillPaths = _internals19.parseSkillPaths(skillsField);
43051
+ const taskId = _internals19.extractTaskIdFromPrompt(text);
42766
43052
  for (const skillPath of skillPaths) {
42767
43053
  if (hadRecordingError)
42768
43054
  break;
42769
43055
  if (isDuplicate(skillPath, currentTargetAgent, taskId))
42770
43056
  continue;
42771
43057
  try {
42772
- _internals18.appendSkillUsageEntry(directory, {
43058
+ _internals19.appendSkillUsageEntry(directory, {
42773
43059
  skillPath,
42774
43060
  agentName: currentTargetAgent,
42775
43061
  taskID: taskId,
@@ -42789,7 +43075,7 @@ async function skillPropagationTransformScan(directory, output, sessionID) {
42789
43075
  break;
42790
43076
  }
42791
43077
  }
42792
- var SKILL_CAPABLE_AGENTS, SKILL_SEARCH_ROOTS, MAX_SCORING_SESSION_ENTRIES = 500, _internals18, COMPLIANCE_PATTERN, CODER_SKILLS_PATTERN, REVIEWER_TASK_PATTERN;
43078
+ var SKILL_CAPABLE_AGENTS, SKILL_SEARCH_ROOTS, MAX_SCORING_SESSION_ENTRIES = 500, _internals19, COMPLIANCE_PATTERN, CODER_SKILLS_PATTERN, REVIEWER_TASK_PATTERN;
42793
43079
  var init_skill_propagation_gate = __esm(() => {
42794
43080
  init_schema();
42795
43081
  init_logger();
@@ -42808,7 +43094,7 @@ var init_skill_propagation_gate = __esm(() => {
42808
43094
  ".opencode/skills/generated",
42809
43095
  ".claude/skills"
42810
43096
  ];
42811
- _internals18 = {
43097
+ _internals19 = {
42812
43098
  readdirSync: fs11.readdirSync.bind(fs11),
42813
43099
  existsSync: fs11.existsSync.bind(fs11),
42814
43100
  statSync: fs11.statSync.bind(fs11),
@@ -42837,16 +43123,16 @@ var init_skill_propagation_gate = __esm(() => {
42837
43123
  COMPLIANCE_PATTERN = /SKILL_COMPLIANCE\s*:\s*(COMPLIANT|PARTIAL|VIOLATED)(?:\s*(?:\u2014|-)\s*(.*))?\s*$/i;
42838
43124
  CODER_SKILLS_PATTERN = /SKILLS_USED_BY_CODER\s*:\s*(.+)/i;
42839
43125
  REVIEWER_TASK_PATTERN = /TASK\s*:\s*(\S+)/i;
42840
- _internals18.skillPropagationGateBefore = skillPropagationGateBefore;
42841
- _internals18.skillPropagationTransformScan = skillPropagationTransformScan;
42842
- _internals18.writeWarnEvent = writeWarnEvent;
42843
- _internals18.discoverAvailableSkills = discoverAvailableSkills;
42844
- _internals18.parseDelegationArgs = parseDelegationArgs;
42845
- _internals18.parseSkillPaths = parseSkillPaths;
42846
- _internals18.extractTaskIdFromPrompt = extractTaskIdFromPrompt;
42847
- _internals18.extractSkillsFieldFromPrompt = extractSkillsFieldFromPrompt;
42848
- _internals18.formatSkillIndexWithContext = formatSkillIndexWithContext;
42849
- _internals18.loadRoutingSkills = loadRoutingSkills;
43126
+ _internals19.skillPropagationGateBefore = skillPropagationGateBefore;
43127
+ _internals19.skillPropagationTransformScan = skillPropagationTransformScan;
43128
+ _internals19.writeWarnEvent = writeWarnEvent;
43129
+ _internals19.discoverAvailableSkills = discoverAvailableSkills;
43130
+ _internals19.parseDelegationArgs = parseDelegationArgs;
43131
+ _internals19.parseSkillPaths = parseSkillPaths;
43132
+ _internals19.extractTaskIdFromPrompt = extractTaskIdFromPrompt;
43133
+ _internals19.extractSkillsFieldFromPrompt = extractSkillsFieldFromPrompt;
43134
+ _internals19.formatSkillIndexWithContext = formatSkillIndexWithContext;
43135
+ _internals19.loadRoutingSkills = loadRoutingSkills;
42850
43136
  });
42851
43137
 
42852
43138
  // src/hooks/micro-reflector.ts
@@ -43447,7 +43733,7 @@ async function curateAndStoreSwarm(lessons, projectName, phaseInfo, directory, c
43447
43733
  } catch {}
43448
43734
  }
43449
43735
  if (!options?.skipAutoPromotion) {
43450
- await _internals19.runAutoPromotion(directory, config3);
43736
+ await _internals20.runAutoPromotion(directory, config3);
43451
43737
  }
43452
43738
  return { stored, reinforced, skipped, rejected, quarantined };
43453
43739
  }
@@ -43530,7 +43816,7 @@ function createKnowledgeCuratorHook(directory, config3, options = {}) {
43530
43816
  recordSeenRetroSection(evidenceKey, evidenceHash, Date.now());
43531
43817
  const projectName2 = evidenceData.project_name ?? "unknown";
43532
43818
  const phaseNumber2 = typeof evidenceData.phase_number === "number" ? evidenceData.phase_number : 1;
43533
- await _internals19.curateAndStoreSwarm(lessons, projectName2, { phase_number: phaseNumber2 }, directory, config3, {
43819
+ await _internals20.curateAndStoreSwarm(lessons, projectName2, { phase_number: phaseNumber2 }, directory, config3, {
43534
43820
  llmDelegate: options.llmDelegateFactory?.(sessionID),
43535
43821
  enrichmentQuota: options.enrichmentQuota
43536
43822
  });
@@ -43555,14 +43841,14 @@ function createKnowledgeCuratorHook(directory, config3, options = {}) {
43555
43841
  const projectName = projectNameMatch ? projectNameMatch[1].trim() : "unknown";
43556
43842
  const phaseMatch = /^Phase:\s*(\d+)/m.exec(planContent);
43557
43843
  const phaseNumber = phaseMatch ? parseInt(phaseMatch[1], 10) : 1;
43558
- await _internals19.curateAndStoreSwarm(normalLessons, projectName, { phase_number: phaseNumber }, directory, config3, {
43844
+ await _internals20.curateAndStoreSwarm(normalLessons, projectName, { phase_number: phaseNumber }, directory, config3, {
43559
43845
  llmDelegate: options.llmDelegateFactory?.(sessionID),
43560
43846
  enrichmentQuota: options.enrichmentQuota
43561
43847
  });
43562
43848
  };
43563
43849
  return safeHook(handler);
43564
43850
  }
43565
- var seenRetroSections, MAX_TRACKED_RETRO_SECTIONS = 500, ENRICHMENT_ALLOWED_FIELDS, ENRICHMENT_LLM_TIMEOUT_MS = 60000, MESO_INSIGHT_BATCH_LIMIT = 20, KNOWLEDGE_CATEGORIES, OUTCOME_PROMOTION_BLOCK = -0.3, _internals19;
43851
+ var seenRetroSections, MAX_TRACKED_RETRO_SECTIONS = 500, ENRICHMENT_ALLOWED_FIELDS, ENRICHMENT_LLM_TIMEOUT_MS = 60000, MESO_INSIGHT_BATCH_LIMIT = 20, KNOWLEDGE_CATEGORIES, OUTCOME_PROMOTION_BLOCK = -0.3, _internals20;
43566
43852
  var init_knowledge_curator = __esm(() => {
43567
43853
  init_skill_improver_quota();
43568
43854
  init_synonym_map();
@@ -43595,7 +43881,7 @@ var init_knowledge_curator = __esm(() => {
43595
43881
  "todo",
43596
43882
  "other"
43597
43883
  ]);
43598
- _internals19 = {
43884
+ _internals20 = {
43599
43885
  isWriteToEvidenceFile,
43600
43886
  curateAndStoreSwarm,
43601
43887
  runAutoPromotion,
@@ -44843,7 +45129,7 @@ async function executeWriteRetro(args, directory) {
44843
45129
  }, null, 2);
44844
45130
  }
44845
45131
  }
44846
- var write_retro, _internals20;
45132
+ var write_retro, _internals21;
44847
45133
  var init_write_retro = __esm(() => {
44848
45134
  init_zod();
44849
45135
  init_evidence_schema();
@@ -44890,13 +45176,13 @@ var init_write_retro = __esm(() => {
44890
45176
  task_id: args.task_id !== undefined ? String(args.task_id) : undefined,
44891
45177
  metadata: args.metadata
44892
45178
  };
44893
- return await _internals20.executeWriteRetro(writeRetroArgs, directory);
45179
+ return await _internals21.executeWriteRetro(writeRetroArgs, directory);
44894
45180
  } catch {
44895
45181
  return JSON.stringify({ success: false, phase: rawPhase, message: "Invalid arguments" }, null, 2);
44896
45182
  }
44897
45183
  }
44898
45184
  });
44899
- _internals20 = {
45185
+ _internals21 = {
44900
45186
  executeWriteRetro,
44901
45187
  write_retro
44902
45188
  };
@@ -44906,7 +45192,7 @@ var init_write_retro = __esm(() => {
44906
45192
  var exports_curator_postmortem = {};
44907
45193
  __export(exports_curator_postmortem, {
44908
45194
  runCuratorPostMortem: () => runCuratorPostMortem,
44909
- _internals: () => _internals21
45195
+ _internals: () => _internals22
44910
45196
  });
44911
45197
  import { existsSync as existsSync19, readdirSync as readdirSync6, readFileSync as readFileSync9 } from "fs";
44912
45198
  import * as path29 from "path";
@@ -45260,13 +45546,13 @@ ${llmOutput}`;
45260
45546
  warnings
45261
45547
  };
45262
45548
  }
45263
- var _internals21;
45549
+ var _internals22;
45264
45550
  var init_curator_postmortem = __esm(() => {
45265
45551
  init_manager();
45266
45552
  init_knowledge_events();
45267
45553
  init_knowledge_store();
45268
45554
  init_utils2();
45269
- _internals21 = {
45555
+ _internals22 = {
45270
45556
  collectKnowledgeSummary,
45271
45557
  collectRetrospectives,
45272
45558
  collectDriftReports,
@@ -46778,9 +47064,9 @@ async function detectDarkMatter(directory, options) {
46778
47064
  } catch {
46779
47065
  return [];
46780
47066
  }
46781
- const commitMap = await _internals22.parseGitLog(directory, maxCommitsToAnalyze);
46782
- const matrix = _internals22.buildCoChangeMatrix(commitMap, maxFilesPerCommit);
46783
- const staticEdges = await _internals22.getStaticEdges(directory);
47067
+ const commitMap = await _internals23.parseGitLog(directory, maxCommitsToAnalyze);
47068
+ const matrix = _internals23.buildCoChangeMatrix(commitMap, maxFilesPerCommit);
47069
+ const staticEdges = await _internals23.getStaticEdges(directory);
46784
47070
  const results = [];
46785
47071
  for (const entry of matrix.values()) {
46786
47072
  const key = `${entry.fileA}::${entry.fileB}`;
@@ -46868,7 +47154,7 @@ ${rows}
46868
47154
  These pairs likely share an architectural concern invisible to static analysis.
46869
47155
  Consider adding explicit documentation or extracting the shared concern.`;
46870
47156
  }
46871
- var co_change_analyzer, _internals22;
47157
+ var co_change_analyzer, _internals23;
46872
47158
  var init_co_change_analyzer = __esm(() => {
46873
47159
  init_zod();
46874
47160
  init_create_tool();
@@ -46900,11 +47186,11 @@ var init_co_change_analyzer = __esm(() => {
46900
47186
  npmiThreshold,
46901
47187
  maxCommitsToAnalyze
46902
47188
  };
46903
- const pairs = await _internals22.detectDarkMatter(directory, options);
46904
- return _internals22.formatDarkMatterOutput(pairs);
47189
+ const pairs = await _internals23.detectDarkMatter(directory, options);
47190
+ return _internals23.formatDarkMatterOutput(pairs);
46905
47191
  }
46906
47192
  });
46907
- _internals22 = {
47193
+ _internals23 = {
46908
47194
  parseGitLog,
46909
47195
  buildCoChangeMatrix,
46910
47196
  getStaticEdges,
@@ -46935,7 +47221,7 @@ async function handleDarkMatterCommand(directory, args) {
46935
47221
  }
46936
47222
  let pairs;
46937
47223
  try {
46938
- pairs = await _internals22.detectDarkMatter(directory, options);
47224
+ pairs = await _internals23.detectDarkMatter(directory, options);
46939
47225
  } catch (err) {
46940
47226
  const errMsg = err instanceof Error ? err.message : String(err);
46941
47227
  return `## Dark Matter Analysis Failed
@@ -50987,7 +51273,7 @@ function isCommandAvailable(command) {
50987
51273
  const isWindows = process.platform === "win32";
50988
51274
  const cmd = isWindows ? `${command}.exe` : command;
50989
51275
  try {
50990
- const result = _internals23.spawnSyncImpl(isWindows ? ["where", cmd] : ["which", cmd], {
51276
+ const result = _internals24.spawnSyncImpl(isWindows ? ["where", cmd] : ["which", cmd], {
50991
51277
  cwd: process.cwd(),
50992
51278
  stdin: "ignore",
50993
51279
  stdout: "ignore",
@@ -51137,7 +51423,7 @@ async function discoverBuildCommands(workingDir, options) {
51137
51423
  const scope = options?.scope ?? "all";
51138
51424
  const changedFiles = options?.changedFiles ?? [];
51139
51425
  const _filesToCheck = filterByScope(workingDir, scope, changedFiles);
51140
- const profileResult = await _internals23.discoverBuildCommandsFromProfiles(workingDir);
51426
+ const profileResult = await _internals24.discoverBuildCommandsFromProfiles(workingDir);
51141
51427
  const profileCommands = profileResult.commands;
51142
51428
  const profileSkipped = profileResult.skipped;
51143
51429
  const coveredEcosystems = new Set;
@@ -51200,7 +51486,7 @@ function clearToolchainCache() {
51200
51486
  function getEcosystems() {
51201
51487
  return ECOSYSTEMS.map((e) => e.ecosystem);
51202
51488
  }
51203
- var ECOSYSTEMS, PROFILE_TO_ECOSYSTEM_NAMES, toolchainCache, IS_COMMAND_AVAILABLE_TIMEOUT_MS = 3000, _internals23, build_discovery;
51489
+ var ECOSYSTEMS, PROFILE_TO_ECOSYSTEM_NAMES, toolchainCache, IS_COMMAND_AVAILABLE_TIMEOUT_MS = 3000, _internals24, build_discovery;
51204
51490
  var init_discovery = __esm(() => {
51205
51491
  init_dist();
51206
51492
  init_detector();
@@ -51318,7 +51604,7 @@ var init_discovery = __esm(() => {
51318
51604
  php: ["php-composer"]
51319
51605
  };
51320
51606
  toolchainCache = new Map;
51321
- _internals23 = {
51607
+ _internals24 = {
51322
51608
  isCommandAvailable,
51323
51609
  discoverBuildCommandsFromProfiles,
51324
51610
  discoverBuildCommands,
@@ -51597,7 +51883,7 @@ var exports_evidence_summary_service = {};
51597
51883
  __export(exports_evidence_summary_service, {
51598
51884
  isAutoSummaryEnabled: () => isAutoSummaryEnabled,
51599
51885
  buildEvidenceSummary: () => buildEvidenceSummary,
51600
- _internals: () => _internals24,
51886
+ _internals: () => _internals25,
51601
51887
  REQUIRED_EVIDENCE_TYPES: () => REQUIRED_EVIDENCE_TYPES,
51602
51888
  EVIDENCE_SUMMARY_VERSION: () => EVIDENCE_SUMMARY_VERSION
51603
51889
  });
@@ -51635,7 +51921,7 @@ function getTaskStatus(task, bundle) {
51635
51921
  if (task?.status) {
51636
51922
  return task.status;
51637
51923
  }
51638
- const entries = _internals24.normalizeBundleEntries(bundle);
51924
+ const entries = _internals25.normalizeBundleEntries(bundle);
51639
51925
  if (entries.length > 0) {
51640
51926
  return "completed";
51641
51927
  }
@@ -51661,7 +51947,7 @@ function evidenceCompleteFromEntries(entries) {
51661
51947
  };
51662
51948
  }
51663
51949
  function isEvidenceComplete(bundle) {
51664
- return evidenceCompleteFromEntries(_internals24.normalizeBundleEntries(bundle));
51950
+ return evidenceCompleteFromEntries(_internals25.normalizeBundleEntries(bundle));
51665
51951
  }
51666
51952
  function getTaskBlockers(task, summary, status) {
51667
51953
  const blockers = [];
@@ -51681,9 +51967,9 @@ async function buildTaskSummary(directory, task, taskId) {
51681
51967
  const bundle = result.status === "found" ? result.bundle : null;
51682
51968
  const gateEvidence = await readDurableGateEvidence(directory, taskId);
51683
51969
  const phase = task?.phase ?? 0;
51684
- const status = _internals24.getTaskStatus(task, bundle);
51685
- const entries = mergeDurableGateEntriesFromEvidence(taskId, _internals24.normalizeBundleEntries(bundle), gateEvidence);
51686
- let evidenceCheck = _internals24.evidenceCompleteFromEntries(entries);
51970
+ const status = _internals25.getTaskStatus(task, bundle);
51971
+ const entries = mergeDurableGateEntriesFromEvidence(taskId, _internals25.normalizeBundleEntries(bundle), gateEvidence);
51972
+ let evidenceCheck = _internals25.evidenceCompleteFromEntries(entries);
51687
51973
  if (gateEvidence) {
51688
51974
  const gateStatus = getDurableGateEvidenceStatus(gateEvidence);
51689
51975
  evidenceCheck = gateStatus.isComplete ? { isComplete: true, missingEvidence: [] } : {
@@ -51691,7 +51977,7 @@ async function buildTaskSummary(directory, task, taskId) {
51691
51977
  missingEvidence: gateStatus.missingGates.map((gate) => `gate:${gate}`)
51692
51978
  };
51693
51979
  }
51694
- const blockers = _internals24.getTaskBlockers(task, evidenceCheck, status);
51980
+ const blockers = _internals25.getTaskBlockers(task, evidenceCheck, status);
51695
51981
  const hasReview = entries.some((e) => e.type === "review");
51696
51982
  const hasTest = entries.some((e) => e.type === "test");
51697
51983
  const hasApproval = entries.some((e) => e.type === "approval");
@@ -51720,12 +52006,12 @@ async function buildPhaseSummary(directory, phase) {
51720
52006
  const taskSummaries = [];
51721
52007
  const _taskMap = new Map(phase.tasks.map((t) => [t.id, t]));
51722
52008
  for (const task of phase.tasks) {
51723
- const summary = await _internals24.buildTaskSummary(directory, task, task.id);
52009
+ const summary = await _internals25.buildTaskSummary(directory, task, task.id);
51724
52010
  taskSummaries.push(summary);
51725
52011
  }
51726
52012
  const extraTaskIds = taskIds.filter((id) => !phaseTaskIds.has(id));
51727
52013
  for (const taskId of extraTaskIds) {
51728
- const summary = await _internals24.buildTaskSummary(directory, undefined, taskId);
52014
+ const summary = await _internals25.buildTaskSummary(directory, undefined, taskId);
51729
52015
  if (summary.phase === phase.id) {
51730
52016
  taskSummaries.push(summary);
51731
52017
  }
@@ -51826,7 +52112,7 @@ async function buildEvidenceSummary(directory, currentPhase) {
51826
52112
  let totalTasks = 0;
51827
52113
  let completedTasks = 0;
51828
52114
  for (const phase of phasesToProcess) {
51829
- const summary = await _internals24.buildPhaseSummary(directory, phase);
52115
+ const summary = await _internals25.buildPhaseSummary(directory, phase);
51830
52116
  phaseSummaries.push(summary);
51831
52117
  totalTasks += summary.totalTasks;
51832
52118
  completedTasks += summary.completedTasks;
@@ -51848,7 +52134,7 @@ async function buildEvidenceSummary(directory, currentPhase) {
51848
52134
  overallBlockers,
51849
52135
  summaryText: ""
51850
52136
  };
51851
- artifact.summaryText = _internals24.generateSummaryText(artifact);
52137
+ artifact.summaryText = _internals25.generateSummaryText(artifact);
51852
52138
  log("[EvidenceSummary] Summary built", {
51853
52139
  phases: phaseSummaries.length,
51854
52140
  totalTasks,
@@ -51867,7 +52153,7 @@ function isAutoSummaryEnabled(automationConfig) {
51867
52153
  }
51868
52154
  return automationConfig.capabilities?.evidence_auto_summaries === true;
51869
52155
  }
51870
- var VALID_EVIDENCE_TYPES2, REQUIRED_EVIDENCE_TYPES, EVIDENCE_SUMMARY_VERSION = "1.0.0", _internals24;
52156
+ var VALID_EVIDENCE_TYPES2, REQUIRED_EVIDENCE_TYPES, EVIDENCE_SUMMARY_VERSION = "1.0.0", _internals25;
51871
52157
  var init_evidence_summary_service = __esm(() => {
51872
52158
  init_gate_bridge();
51873
52159
  init_manager2();
@@ -51882,7 +52168,7 @@ var init_evidence_summary_service = __esm(() => {
51882
52168
  "retrospective"
51883
52169
  ]);
51884
52170
  REQUIRED_EVIDENCE_TYPES = ["review", "test"];
51885
- _internals24 = {
52171
+ _internals25 = {
51886
52172
  buildEvidenceSummary,
51887
52173
  isAutoSummaryEnabled,
51888
52174
  normalizeBundleEntries,
@@ -51938,7 +52224,7 @@ function getVerdictEmoji(verdict) {
51938
52224
  return getVerdictIcon(verdict);
51939
52225
  }
51940
52226
  async function getTaskEvidenceData(directory, taskId) {
51941
- const result = await _internals25.loadEvidence(directory, taskId);
52227
+ const result = await _internals26.loadEvidence(directory, taskId);
51942
52228
  if (result.status !== "found") {
51943
52229
  return {
51944
52230
  hasEvidence: false,
@@ -51961,13 +52247,13 @@ async function getTaskEvidenceData(directory, taskId) {
51961
52247
  };
51962
52248
  }
51963
52249
  async function getEvidenceListData(directory) {
51964
- const taskIds = await _internals25.listEvidenceTaskIds(directory);
52250
+ const taskIds = await _internals26.listEvidenceTaskIds(directory);
51965
52251
  if (taskIds.length === 0) {
51966
52252
  return { hasEvidence: false, tasks: [] };
51967
52253
  }
51968
52254
  const tasks = [];
51969
52255
  for (const taskId of taskIds) {
51970
- const result = await _internals25.loadEvidence(directory, taskId);
52256
+ const result = await _internals26.loadEvidence(directory, taskId);
51971
52257
  if (result.status === "found") {
51972
52258
  tasks.push({
51973
52259
  taskId,
@@ -52081,10 +52367,10 @@ async function handleEvidenceSummaryCommand(directory) {
52081
52367
  return lines.join(`
52082
52368
  `);
52083
52369
  }
52084
- var _internals25;
52370
+ var _internals26;
52085
52371
  var init_evidence_service = __esm(() => {
52086
52372
  init_manager2();
52087
- _internals25 = {
52373
+ _internals26 = {
52088
52374
  loadEvidence,
52089
52375
  listEvidenceTaskIds
52090
52376
  };
@@ -52612,7 +52898,7 @@ function extractCurrentPhaseFromPlan2(plan) {
52612
52898
  if (!plan) {
52613
52899
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
52614
52900
  }
52615
- if (!_internals26.validatePlanPhases(plan)) {
52901
+ if (!_internals27.validatePlanPhases(plan)) {
52616
52902
  return { currentPhase: null, currentTask: null, incompleteTasks: [] };
52617
52903
  }
52618
52904
  let currentPhase = null;
@@ -52754,9 +53040,9 @@ function extractPhaseMetrics(content) {
52754
53040
  async function getHandoffData(directory) {
52755
53041
  const now = new Date().toISOString();
52756
53042
  const sessionContent = await readSwarmFileAsync(directory, "session/state.json");
52757
- const sessionState = _internals26.parseSessionState(sessionContent);
53043
+ const sessionState = _internals27.parseSessionState(sessionContent);
52758
53044
  const plan = await loadPlanJsonOnly(directory);
52759
- const planInfo = _internals26.extractCurrentPhaseFromPlan(plan);
53045
+ const planInfo = _internals27.extractCurrentPhaseFromPlan(plan);
52760
53046
  if (!plan) {
52761
53047
  const planMdContent = await readSwarmFileAsync(directory, "plan.md");
52762
53048
  if (planMdContent) {
@@ -52775,8 +53061,8 @@ async function getHandoffData(directory) {
52775
53061
  }
52776
53062
  }
52777
53063
  const contextContent = await readSwarmFileAsync(directory, "context.md");
52778
- const recentDecisions = _internals26.extractDecisions(contextContent);
52779
- const rawPhaseMetrics = _internals26.extractPhaseMetrics(contextContent);
53064
+ const recentDecisions = _internals27.extractDecisions(contextContent);
53065
+ const rawPhaseMetrics = _internals27.extractPhaseMetrics(contextContent);
52780
53066
  const phaseMetrics = sanitizeString(rawPhaseMetrics, 1000);
52781
53067
  let delegationState = null;
52782
53068
  if (sessionState?.delegationState) {
@@ -52940,13 +53226,13 @@ ${lines.join(`
52940
53226
  `)}
52941
53227
  \`\`\``;
52942
53228
  }
52943
- var RTL_OVERRIDE_PATTERN, MAX_TASK_ID_LENGTH = 100, MAX_DECISION_LENGTH = 500, MAX_INCOMPLETE_TASKS = 20, _internals26;
53229
+ var RTL_OVERRIDE_PATTERN, MAX_TASK_ID_LENGTH = 100, MAX_DECISION_LENGTH = 500, MAX_INCOMPLETE_TASKS = 20, _internals27;
52944
53230
  var init_handoff_service = __esm(() => {
52945
53231
  init_utils2();
52946
53232
  init_manager();
52947
53233
  init_utils();
52948
53234
  RTL_OVERRIDE_PATTERN = /[\u202e\u202d\u202c\u200f]/g;
52949
- _internals26 = {
53235
+ _internals27 = {
52950
53236
  getHandoffData,
52951
53237
  formatHandoffMarkdown,
52952
53238
  formatContinuationPrompt,
@@ -53089,22 +53375,22 @@ async function writeSnapshot(directory, state) {
53089
53375
  }
53090
53376
  function createSnapshotWriterHook(directory) {
53091
53377
  return (_input, _output) => {
53092
- _writeInFlight = _writeInFlight.then(() => _internals27.writeSnapshot(directory, swarmState), () => _internals27.writeSnapshot(directory, swarmState));
53378
+ _writeInFlight = _writeInFlight.then(() => _internals28.writeSnapshot(directory, swarmState), () => _internals28.writeSnapshot(directory, swarmState));
53093
53379
  return _writeInFlight;
53094
53380
  };
53095
53381
  }
53096
53382
  async function flushPendingSnapshot(directory) {
53097
- _writeInFlight = _writeInFlight.then(() => _internals27.writeSnapshot(directory, swarmState), () => _internals27.writeSnapshot(directory, swarmState));
53383
+ _writeInFlight = _writeInFlight.then(() => _internals28.writeSnapshot(directory, swarmState), () => _internals28.writeSnapshot(directory, swarmState));
53098
53384
  await _writeInFlight;
53099
53385
  }
53100
- var _writeInFlight, _internals27;
53386
+ var _writeInFlight, _internals28;
53101
53387
  var init_snapshot_writer = __esm(() => {
53102
53388
  init_utils2();
53103
53389
  init_state();
53104
53390
  init_utils();
53105
53391
  init_bun_compat();
53106
53392
  _writeInFlight = Promise.resolve();
53107
- _internals27 = {
53393
+ _internals28 = {
53108
53394
  writeSnapshot,
53109
53395
  createSnapshotWriterHook,
53110
53396
  flushPendingSnapshot
@@ -53424,7 +53710,7 @@ function validateAndSanitizeGithubUrl(rawUrl, resource) {
53424
53710
  }
53425
53711
  function detectGitRemote(cwd) {
53426
53712
  try {
53427
- const result = _internals28.spawnSync("git", ["remote", "get-url", "origin"], {
53713
+ const result = _internals29.spawnSync("git", ["remote", "get-url", "origin"], {
53428
53714
  encoding: "utf-8",
53429
53715
  stdio: ["ignore", "pipe", "pipe"],
53430
53716
  timeout: 5000,
@@ -53469,7 +53755,7 @@ function parseGitRemoteUrl(remoteUrl) {
53469
53755
  }
53470
53756
  return null;
53471
53757
  }
53472
- var MAX_URL_LEN = 2048, IPV4_PRIVATE, IPV4_LOOPBACK, IPV4_LINK_LOCAL, IPV4_PRIVATE_172, IPV4_PRIVATE_192, IPV4_ZERO_NETWORK, IPV6_LINK_LOCAL, IPV6_UNIQUE_LOCAL, _internals28;
53758
+ var MAX_URL_LEN = 2048, IPV4_PRIVATE, IPV4_LOOPBACK, IPV4_LINK_LOCAL, IPV4_PRIVATE_172, IPV4_PRIVATE_192, IPV4_ZERO_NETWORK, IPV6_LINK_LOCAL, IPV6_UNIQUE_LOCAL, _internals29;
53473
53759
  var init_url_security = __esm(() => {
53474
53760
  IPV4_PRIVATE = /^10\./;
53475
53761
  IPV4_LOOPBACK = /^127\./;
@@ -53479,7 +53765,7 @@ var init_url_security = __esm(() => {
53479
53765
  IPV4_ZERO_NETWORK = /^0\./;
53480
53766
  IPV6_LINK_LOCAL = /^fe80:/i;
53481
53767
  IPV6_UNIQUE_LOCAL = /^f[cd][0-9a-f]{2}:/i;
53482
- _internals28 = { spawnSync: spawnSync3 };
53768
+ _internals29 = { spawnSync: spawnSync3 };
53483
53769
  });
53484
53770
 
53485
53771
  // src/commands/issue.ts
@@ -53653,9 +53939,9 @@ async function migrateContextToKnowledge(directory, config3) {
53653
53939
  skippedReason: "empty-context"
53654
53940
  };
53655
53941
  }
53656
- const rawEntries = _internals29.parseContextMd(contextContent);
53942
+ const rawEntries = _internals30.parseContextMd(contextContent);
53657
53943
  if (rawEntries.length === 0) {
53658
- await _internals29.writeSentinel(sentinelPath, 0, 0);
53944
+ await _internals30.writeSentinel(sentinelPath, 0, 0);
53659
53945
  return {
53660
53946
  migrated: true,
53661
53947
  entriesMigrated: 0,
@@ -53666,10 +53952,10 @@ async function migrateContextToKnowledge(directory, config3) {
53666
53952
  const existing = await readKnowledge(knowledgePath);
53667
53953
  let migrated = 0;
53668
53954
  let dropped = 0;
53669
- const projectName = _internals29.inferProjectName(directory);
53955
+ const projectName = _internals30.inferProjectName(directory);
53670
53956
  for (const raw of rawEntries) {
53671
53957
  if (config3.validation_enabled !== false) {
53672
- const category = raw.categoryHint ?? _internals29.inferCategoryFromText(raw.text);
53958
+ const category = raw.categoryHint ?? _internals30.inferCategoryFromText(raw.text);
53673
53959
  const result = validateLesson(raw.text, existing.map((e) => e.lesson), {
53674
53960
  category,
53675
53961
  scope: "global",
@@ -53689,8 +53975,8 @@ async function migrateContextToKnowledge(directory, config3) {
53689
53975
  const entry = {
53690
53976
  id: randomUUID3(),
53691
53977
  tier: "swarm",
53692
- lesson: _internals29.truncateLesson(raw.text),
53693
- category: raw.categoryHint ?? _internals29.inferCategoryFromText(raw.text),
53978
+ lesson: _internals30.truncateLesson(raw.text),
53979
+ category: raw.categoryHint ?? _internals30.inferCategoryFromText(raw.text),
53694
53980
  tags: [...inferredTags, `migration:${raw.sourceSection}`],
53695
53981
  scope: "global",
53696
53982
  confidence: 0.3,
@@ -53713,7 +53999,7 @@ async function migrateContextToKnowledge(directory, config3) {
53713
53999
  if (migrated > 0) {
53714
54000
  await rewriteKnowledge(knowledgePath, existing);
53715
54001
  }
53716
- await _internals29.writeSentinel(sentinelPath, migrated, dropped);
54002
+ await _internals30.writeSentinel(sentinelPath, migrated, dropped);
53717
54003
  log(`[knowledge-migrator] Migrated ${migrated} entries, dropped ${dropped}`);
53718
54004
  return {
53719
54005
  migrated: true,
@@ -53723,7 +54009,7 @@ async function migrateContextToKnowledge(directory, config3) {
53723
54009
  };
53724
54010
  }
53725
54011
  async function migrateHiveKnowledgeLegacy(config3) {
53726
- const legacyHivePath = _internals29.resolveLegacyHiveKnowledgePath();
54012
+ const legacyHivePath = _internals30.resolveLegacyHiveKnowledgePath();
53727
54013
  const canonicalHivePath = resolveHiveKnowledgePath();
53728
54014
  const sentinelPath = path41.join(path41.dirname(canonicalHivePath), ".hive-knowledge-migrated");
53729
54015
  if (existsSync27(sentinelPath)) {
@@ -53746,7 +54032,7 @@ async function migrateHiveKnowledgeLegacy(config3) {
53746
54032
  }
53747
54033
  const legacyEntries = await readKnowledge(legacyHivePath);
53748
54034
  if (legacyEntries.length === 0) {
53749
- await _internals29.writeSentinel(sentinelPath, 0, 0);
54035
+ await _internals30.writeSentinel(sentinelPath, 0, 0);
53750
54036
  return {
53751
54037
  migrated: true,
53752
54038
  entriesMigrated: 0,
@@ -53794,7 +54080,7 @@ async function migrateHiveKnowledgeLegacy(config3) {
53794
54080
  const newHiveEntry = {
53795
54081
  id: resolvedId,
53796
54082
  tier: "hive",
53797
- lesson: _internals29.truncateLesson(lesson),
54083
+ lesson: _internals30.truncateLesson(lesson),
53798
54084
  category,
53799
54085
  tags: ["migration:legacy-hive"],
53800
54086
  scope: scopeTag,
@@ -53813,7 +54099,7 @@ async function migrateHiveKnowledgeLegacy(config3) {
53813
54099
  encounter_score: 1
53814
54100
  };
53815
54101
  try {
53816
- await _internals29.appendKnowledge(canonicalHivePath, newHiveEntry);
54102
+ await _internals30.appendKnowledge(canonicalHivePath, newHiveEntry);
53817
54103
  existingHiveEntries.push(newHiveEntry);
53818
54104
  migrated++;
53819
54105
  } catch (appendError) {
@@ -53829,7 +54115,7 @@ async function migrateHiveKnowledgeLegacy(config3) {
53829
54115
  dropped++;
53830
54116
  }
53831
54117
  }
53832
- await _internals29.writeSentinel(sentinelPath, migrated, dropped);
54118
+ await _internals30.writeSentinel(sentinelPath, migrated, dropped);
53833
54119
  log(`[knowledge-migrator] Migrated ${migrated} legacy hive entries, dropped ${dropped}`);
53834
54120
  return {
53835
54121
  migrated: true,
@@ -53840,7 +54126,7 @@ async function migrateHiveKnowledgeLegacy(config3) {
53840
54126
  };
53841
54127
  }
53842
54128
  function parseContextMd(content) {
53843
- const sections = _internals29.splitIntoSections(content);
54129
+ const sections = _internals30.splitIntoSections(content);
53844
54130
  const entries = [];
53845
54131
  const seen = new Set;
53846
54132
  const sectionPatterns = [
@@ -53856,7 +54142,7 @@ function parseContextMd(content) {
53856
54142
  const match = sectionPatterns.find((sp) => sp.pattern.test(section.heading));
53857
54143
  if (!match)
53858
54144
  continue;
53859
- const bullets = _internals29.extractBullets(section.body);
54145
+ const bullets = _internals30.extractBullets(section.body);
53860
54146
  for (const bullet of bullets) {
53861
54147
  if (bullet.length < 15)
53862
54148
  continue;
@@ -53865,9 +54151,9 @@ function parseContextMd(content) {
53865
54151
  continue;
53866
54152
  seen.add(normalized);
53867
54153
  entries.push({
53868
- text: _internals29.truncateLesson(bullet),
54154
+ text: _internals30.truncateLesson(bullet),
53869
54155
  sourceSection: match.sourceSection,
53870
- categoryHint: _internals29.inferCategoryFromText(bullet)
54156
+ categoryHint: _internals30.inferCategoryFromText(bullet)
53871
54157
  });
53872
54158
  }
53873
54159
  }
@@ -53973,12 +54259,12 @@ function resolveLegacyHiveKnowledgePath() {
53973
54259
  }
53974
54260
  return path41.join(dataDir, "hive-knowledge.jsonl");
53975
54261
  }
53976
- var _internals29;
54262
+ var _internals30;
53977
54263
  var init_knowledge_migrator = __esm(() => {
53978
54264
  init_logger();
53979
54265
  init_knowledge_store();
53980
54266
  init_knowledge_validator();
53981
- _internals29 = {
54267
+ _internals30 = {
53982
54268
  appendKnowledge,
53983
54269
  migrateContextToKnowledge,
53984
54270
  migrateKnowledgeToExternal,
@@ -57572,9 +57858,9 @@ var init_memory2 = __esm(() => {
57572
57858
 
57573
57859
  // src/services/plan-service.ts
57574
57860
  async function getPlanData(directory, phaseArg) {
57575
- const plan = await _internals30.loadPlanJsonOnly(directory);
57861
+ const plan = await _internals31.loadPlanJsonOnly(directory);
57576
57862
  if (plan) {
57577
- const fullMarkdown = _internals30.derivePlanMarkdown(plan);
57863
+ const fullMarkdown = _internals31.derivePlanMarkdown(plan);
57578
57864
  if (phaseArg === undefined || phaseArg === null || phaseArg === "") {
57579
57865
  return {
57580
57866
  hasPlan: true,
@@ -57617,7 +57903,7 @@ async function getPlanData(directory, phaseArg) {
57617
57903
  isLegacy: false
57618
57904
  };
57619
57905
  }
57620
- const planContent = await _internals30.readSwarmFileAsync(directory, "plan.md");
57906
+ const planContent = await _internals31.readSwarmFileAsync(directory, "plan.md");
57621
57907
  if (!planContent) {
57622
57908
  return {
57623
57909
  hasPlan: false,
@@ -57713,11 +57999,11 @@ async function handlePlanCommand(directory, args) {
57713
57999
  const planData = await getPlanData(directory, phaseArg);
57714
58000
  return formatPlanMarkdown(planData);
57715
58001
  }
57716
- var _internals30;
58002
+ var _internals31;
57717
58003
  var init_plan_service = __esm(() => {
57718
58004
  init_utils2();
57719
58005
  init_manager();
57720
- _internals30 = {
58006
+ _internals31 = {
57721
58007
  loadPlanJsonOnly,
57722
58008
  derivePlanMarkdown,
57723
58009
  readSwarmFileAsync
@@ -58060,7 +58346,7 @@ function formatRelativeTime(epochMs) {
58060
58346
  return `${diffDays} day${diffDays === 1 ? "" : "s"} ago`;
58061
58347
  }
58062
58348
  async function handlePrMonitorStatusCommand(directory, _args, sessionID) {
58063
- const allActive = await _internals31.listActive(directory);
58349
+ const allActive = await _internals32.listActive(directory);
58064
58350
  const sessionSubs = allActive.filter((record3) => record3.sessionID === sessionID);
58065
58351
  if (sessionSubs.length === 0) {
58066
58352
  return "No active PR subscriptions for this session.";
@@ -58089,10 +58375,10 @@ async function handlePrMonitorStatusCommand(directory, _args, sessionID) {
58089
58375
  return lines.join(`
58090
58376
  `);
58091
58377
  }
58092
- var _internals31;
58378
+ var _internals32;
58093
58379
  var init_pr_monitor_status = __esm(() => {
58094
58380
  init_pr_subscriptions();
58095
- _internals31 = {
58381
+ _internals32 = {
58096
58382
  formatRelativeTime,
58097
58383
  listActive
58098
58384
  };
@@ -58197,7 +58483,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
58197
58483
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
58198
58484
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
58199
58485
  try {
58200
- const config3 = _internals32.loadPluginConfig(directory);
58486
+ const config3 = _internals33.loadPluginConfig(directory);
58201
58487
  const prMonitorConfig = config3.pr_monitor;
58202
58488
  if (!prMonitorConfig?.enabled) {
58203
58489
  return [
@@ -58207,7 +58493,7 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
58207
58493
  ].join(`
58208
58494
  `);
58209
58495
  }
58210
- await _internals32.subscribe(directory, {
58496
+ await _internals33.subscribe(directory, {
58211
58497
  sessionID,
58212
58498
  prNumber: prInfo.number,
58213
58499
  repoFullName,
@@ -58231,12 +58517,12 @@ async function handlePrSubscribeCommand(directory, args, sessionID) {
58231
58517
  `);
58232
58518
  }
58233
58519
  }
58234
- var _internals32;
58520
+ var _internals33;
58235
58521
  var init_pr_subscribe = __esm(() => {
58236
58522
  init_pr_subscriptions();
58237
58523
  init_loader();
58238
58524
  init_pr_ref();
58239
- _internals32 = {
58525
+ _internals33 = {
58240
58526
  loadPluginConfig,
58241
58527
  subscribe
58242
58528
  };
@@ -58260,9 +58546,9 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
58260
58546
  `);
58261
58547
  }
58262
58548
  const refToken = rest[0];
58263
- const prInfo = _internals33.parsePrRef(refToken, directory);
58549
+ const prInfo = _internals34.parsePrRef(refToken, directory);
58264
58550
  if (!prInfo) {
58265
- if (_internals33.looksLikePrRef(refToken)) {
58551
+ if (_internals34.looksLikePrRef(refToken)) {
58266
58552
  return [
58267
58553
  `Error: Could not resolve PR reference from "${refToken}".`,
58268
58554
  "",
@@ -58283,8 +58569,8 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
58283
58569
  const repoFullName = `${prInfo.owner}/${prInfo.repo}`;
58284
58570
  const prUrl = `https://github.com/${prInfo.owner}/${prInfo.repo}/pull/${prInfo.number}`;
58285
58571
  try {
58286
- const correlationId = _internals33.buildCorrelationId(sessionID, repoFullName, prInfo.number);
58287
- const result = await _internals33.unsubscribe(directory, correlationId);
58572
+ const correlationId = _internals34.buildCorrelationId(sessionID, repoFullName, prInfo.number);
58573
+ const result = await _internals34.unsubscribe(directory, correlationId);
58288
58574
  if (!result) {
58289
58575
  return [
58290
58576
  `Not subscribed to ${prUrl}`,
@@ -58311,11 +58597,11 @@ async function handlePrUnsubscribeCommand(directory, args, sessionID) {
58311
58597
  `);
58312
58598
  }
58313
58599
  }
58314
- var _internals33;
58600
+ var _internals34;
58315
58601
  var init_pr_unsubscribe = __esm(() => {
58316
58602
  init_pr_subscriptions();
58317
58603
  init_pr_ref();
58318
- _internals33 = {
58604
+ _internals34 = {
58319
58605
  unsubscribe,
58320
58606
  buildCorrelationId,
58321
58607
  parsePrRef,
@@ -58719,7 +59005,7 @@ async function runAdditionalLint(linter, mode, cwd) {
58719
59005
  };
58720
59006
  }
58721
59007
  }
58722
- var MAX_OUTPUT_BYTES = 512000, MAX_COMMAND_LENGTH = 500, lint, _internals34;
59008
+ var MAX_OUTPUT_BYTES = 512000, MAX_COMMAND_LENGTH = 500, lint, _internals35;
58723
59009
  var init_lint = __esm(() => {
58724
59010
  init_zod();
58725
59011
  init_discovery();
@@ -58751,15 +59037,15 @@ var init_lint = __esm(() => {
58751
59037
  }
58752
59038
  const { mode } = args;
58753
59039
  const cwd = directory;
58754
- const linter = await _internals34.detectAvailableLinter(directory);
59040
+ const linter = await _internals35.detectAvailableLinter(directory);
58755
59041
  if (linter) {
58756
- const result = await _internals34.runLint(linter, mode, directory);
59042
+ const result = await _internals35.runLint(linter, mode, directory);
58757
59043
  return JSON.stringify(result, null, 2);
58758
59044
  }
58759
- const additionalLinter = _internals34.detectAdditionalLinter(cwd);
59045
+ const additionalLinter = _internals35.detectAdditionalLinter(cwd);
58760
59046
  if (additionalLinter) {
58761
59047
  warn(`[lint] Using ${additionalLinter} linter for this project`);
58762
- const result = await _internals34.runAdditionalLint(additionalLinter, mode, cwd);
59048
+ const result = await _internals35.runAdditionalLint(additionalLinter, mode, cwd);
58763
59049
  return JSON.stringify(result, null, 2);
58764
59050
  }
58765
59051
  const errorResult = {
@@ -58773,7 +59059,7 @@ For Rust: rustup component add clippy`
58773
59059
  return JSON.stringify(errorResult, null, 2);
58774
59060
  }
58775
59061
  });
58776
- _internals34 = {
59062
+ _internals35 = {
58777
59063
  detectAvailableLinter,
58778
59064
  runLint,
58779
59065
  detectAdditionalLinter,
@@ -59087,7 +59373,7 @@ function findScannableFiles(dir, excludeExact, excludeGlobs, scanDir, visited, s
59087
59373
  }
59088
59374
  async function runSecretscan(directory) {
59089
59375
  try {
59090
- const result = await _internals35.secretscan.execute({ directory }, {});
59376
+ const result = await _internals36.secretscan.execute({ directory }, {});
59091
59377
  const jsonStr = typeof result === "string" ? result : result.output;
59092
59378
  return JSON.parse(jsonStr);
59093
59379
  } catch (e) {
@@ -59102,7 +59388,7 @@ async function runSecretscan(directory) {
59102
59388
  return errorResult;
59103
59389
  }
59104
59390
  }
59105
- var MAX_FILE_PATH_LENGTH = 500, MAX_FILE_SIZE_BYTES, MAX_FILES_SCANNED = 1000, MAX_FINDINGS = 100, MAX_OUTPUT_BYTES2 = 512000, MAX_LINE_LENGTH = 1e4, MAX_CONTENT_BYTES, BINARY_SIGNATURES, BINARY_PREFIX_BYTES = 4, BINARY_NULL_CHECK_BYTES = 8192, BINARY_NULL_THRESHOLD = 0.1, DEFAULT_EXCLUDE_DIRS, DEFAULT_EXCLUDE_EXTENSIONS, SECRET_PATTERNS2, O_NOFOLLOW, secretscan, _internals35;
59391
+ var MAX_FILE_PATH_LENGTH = 500, MAX_FILE_SIZE_BYTES, MAX_FILES_SCANNED = 1000, MAX_FINDINGS = 100, MAX_OUTPUT_BYTES2 = 512000, MAX_LINE_LENGTH = 1e4, MAX_CONTENT_BYTES, BINARY_SIGNATURES, BINARY_PREFIX_BYTES = 4, BINARY_NULL_CHECK_BYTES = 8192, BINARY_NULL_THRESHOLD = 0.1, DEFAULT_EXCLUDE_DIRS, DEFAULT_EXCLUDE_EXTENSIONS, SECRET_PATTERNS2, O_NOFOLLOW, secretscan, _internals36;
59106
59392
  var init_secretscan = __esm(() => {
59107
59393
  init_zod();
59108
59394
  init_path_security();
@@ -59474,7 +59760,7 @@ var init_secretscan = __esm(() => {
59474
59760
  }
59475
59761
  }
59476
59762
  });
59477
- _internals35 = {
59763
+ _internals36 = {
59478
59764
  secretscan,
59479
59765
  runSecretscan
59480
59766
  };
@@ -60066,14 +60352,14 @@ function buildGoBackend() {
60066
60352
  selectEntryPoints
60067
60353
  };
60068
60354
  }
60069
- var PROFILE_ID = "go", IMPORT_REGEX_SINGLE, IMPORT_REGEX_GROUP, IMPORT_REGEX_GROUP_LINE, _internals36;
60355
+ var PROFILE_ID = "go", IMPORT_REGEX_SINGLE, IMPORT_REGEX_GROUP, IMPORT_REGEX_GROUP_LINE, _internals37;
60070
60356
  var init_go = __esm(() => {
60071
60357
  init_default_backend();
60072
60358
  init_profiles();
60073
60359
  IMPORT_REGEX_SINGLE = /^\s*import\s+(?:[a-zA-Z_.][a-zA-Z0-9_]*\s+)?"([^"]+)"/gm;
60074
60360
  IMPORT_REGEX_GROUP = /^\s*import\s*\(([\s\S]*?)\)/gm;
60075
60361
  IMPORT_REGEX_GROUP_LINE = /(?:[a-zA-Z_.][a-zA-Z0-9_]*\s+)?"([^"]+)"/g;
60076
- _internals36 = { extractImports };
60362
+ _internals37 = { extractImports };
60077
60363
  });
60078
60364
 
60079
60365
  // src/lang/backends/python.ts
@@ -60185,13 +60471,13 @@ function buildPythonBackend() {
60185
60471
  selectEntryPoints: selectEntryPoints2
60186
60472
  };
60187
60473
  }
60188
- var PROFILE_ID2 = "python", IMPORT_REGEX_FROM_WITH_TARGETS, IMPORT_REGEX_IMPORT, _internals37;
60474
+ var PROFILE_ID2 = "python", IMPORT_REGEX_FROM_WITH_TARGETS, IMPORT_REGEX_IMPORT, _internals38;
60189
60475
  var init_python = __esm(() => {
60190
60476
  init_default_backend();
60191
60477
  init_profiles();
60192
60478
  IMPORT_REGEX_FROM_WITH_TARGETS = /^\s*from\s+(\.*[\w.]*)\s+import\s+(\([^)]*\)|[^\n#]+)/gm;
60193
60479
  IMPORT_REGEX_IMPORT = /^\s*import\s+([^\n#]+)/gm;
60194
- _internals37 = { extractImports: extractImports2 };
60480
+ _internals38 = { extractImports: extractImports2 };
60195
60481
  });
60196
60482
 
60197
60483
  // src/test-impact/analyzer.ts
@@ -60415,7 +60701,7 @@ function addImpactEdgesForTestFile(testFile, content, impactMap) {
60415
60701
  return;
60416
60702
  }
60417
60703
  if (PYTHON_EXTENSIONS.has(ext)) {
60418
- const modules = _internals37.extractImports(testFile, content);
60704
+ const modules = _internals38.extractImports(testFile, content);
60419
60705
  for (const mod of modules) {
60420
60706
  const resolved = resolvePythonImport(testDir, mod);
60421
60707
  if (resolved !== null)
@@ -60424,7 +60710,7 @@ function addImpactEdgesForTestFile(testFile, content, impactMap) {
60424
60710
  return;
60425
60711
  }
60426
60712
  if (GO_EXTENSIONS.has(ext)) {
60427
- const imports = _internals36.extractImports(testFile, content);
60713
+ const imports = _internals37.extractImports(testFile, content);
60428
60714
  for (const importPath of imports) {
60429
60715
  const sourceFiles = resolveGoImport(testDir, importPath);
60430
60716
  for (const source of sourceFiles)
@@ -60451,8 +60737,8 @@ async function buildImpactMapInternal(cwd) {
60451
60737
  return impactMap;
60452
60738
  }
60453
60739
  async function buildImpactMap(cwd) {
60454
- const impactMap = await _internals38.buildImpactMapInternal(cwd);
60455
- await _internals38.saveImpactMap(cwd, impactMap);
60740
+ const impactMap = await _internals39.buildImpactMapInternal(cwd);
60741
+ await _internals39.saveImpactMap(cwd, impactMap);
60456
60742
  return impactMap;
60457
60743
  }
60458
60744
  async function loadImpactMap(cwd, options) {
@@ -60466,7 +60752,7 @@ async function loadImpactMap(cwd, options) {
60466
60752
  const hasValidValues = Object.values(map3).every((v) => Array.isArray(v) && v.every((item) => typeof item === "string"));
60467
60753
  if (hasValidValues) {
60468
60754
  const generatedAt = new Date(data.generatedAt).getTime();
60469
- if (!_internals38.isCacheStale(map3, generatedAt)) {
60755
+ if (!_internals39.isCacheStale(map3, generatedAt)) {
60470
60756
  return map3;
60471
60757
  }
60472
60758
  if (options?.skipRebuild) {
@@ -60486,13 +60772,13 @@ async function loadImpactMap(cwd, options) {
60486
60772
  if (options?.skipRebuild) {
60487
60773
  return {};
60488
60774
  }
60489
- return _internals38.buildImpactMap(cwd);
60775
+ return _internals39.buildImpactMap(cwd);
60490
60776
  }
60491
60777
  async function saveImpactMap(cwd, impactMap) {
60492
60778
  if (!path53.isAbsolute(cwd)) {
60493
60779
  throw new Error(`saveImpactMap requires an absolute project root path, got: "${cwd}"`);
60494
60780
  }
60495
- _internals38.validateProjectRoot(cwd);
60781
+ _internals39.validateProjectRoot(cwd);
60496
60782
  const cacheDir2 = path53.join(cwd, ".swarm", "cache");
60497
60783
  const cachePath = path53.join(cacheDir2, "impact-map.json");
60498
60784
  if (!fs23.existsSync(cacheDir2)) {
@@ -60516,7 +60802,7 @@ async function analyzeImpact(changedFiles, cwd, budget) {
60516
60802
  };
60517
60803
  }
60518
60804
  const validFiles = changedFiles.filter((f) => typeof f === "string" && f.length > 0 && !f.includes("\x00"));
60519
- const impactMap = await _internals38.loadImpactMap(cwd);
60805
+ const impactMap = await _internals39.loadImpactMap(cwd);
60520
60806
  const impactedTestsSet = new Set;
60521
60807
  const untestedFiles = [];
60522
60808
  let visitedCount = 0;
@@ -60601,7 +60887,7 @@ async function analyzeImpact(changedFiles, cwd, budget) {
60601
60887
  budgetExceeded
60602
60888
  };
60603
60889
  }
60604
- var IMPORT_REGEX_ES, IMPORT_REGEX_REQUIRE, IMPORT_REGEX_REEXPORT, TS_EXTENSIONS, PYTHON_EXTENSIONS, GO_EXTENSIONS, EXTENSIONS_TO_TRY, goModuleCache, _internals38;
60890
+ var IMPORT_REGEX_ES, IMPORT_REGEX_REQUIRE, IMPORT_REGEX_REEXPORT, TS_EXTENSIONS, PYTHON_EXTENSIONS, GO_EXTENSIONS, EXTENSIONS_TO_TRY, goModuleCache, _internals39;
60605
60891
  var init_analyzer = __esm(() => {
60606
60892
  init_manager2();
60607
60893
  init_go();
@@ -60614,7 +60900,7 @@ var init_analyzer = __esm(() => {
60614
60900
  GO_EXTENSIONS = new Set([".go"]);
60615
60901
  EXTENSIONS_TO_TRY = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
60616
60902
  goModuleCache = new Map;
60617
- _internals38 = {
60903
+ _internals39 = {
60618
60904
  validateProjectRoot,
60619
60905
  normalizePath,
60620
60906
  isCacheStale,
@@ -60997,7 +61283,7 @@ function batchAppendTestRuns(records, workingDir) {
60997
61283
  }
60998
61284
  const historyPath = getHistoryPath(workingDir);
60999
61285
  const historyDir = path54.dirname(historyPath);
61000
- _internals39.validateProjectRoot(workingDir);
61286
+ _internals40.validateProjectRoot(workingDir);
61001
61287
  if (!fs24.existsSync(historyDir)) {
61002
61288
  fs24.mkdirSync(historyDir, { recursive: true });
61003
61289
  }
@@ -61120,7 +61406,7 @@ function getAllHistory(workingDir) {
61120
61406
  records.sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
61121
61407
  return records;
61122
61408
  }
61123
- var MAX_HISTORY_PER_TEST = 20, MAX_ERROR_LENGTH = 500, MAX_STACK_LENGTH = 200, MAX_CHANGED_FILES = 50, HISTORY_WRITE_LOCK_TIMEOUT_MS = 5000, HISTORY_WRITE_LOCK_STALE_MS = 60000, HISTORY_WRITE_LOCK_BACKOFF_MS = 10, DANGEROUS_PROPERTY_NAMES, _internals39;
61409
+ var MAX_HISTORY_PER_TEST = 20, MAX_ERROR_LENGTH = 500, MAX_STACK_LENGTH = 200, MAX_CHANGED_FILES = 50, HISTORY_WRITE_LOCK_TIMEOUT_MS = 5000, HISTORY_WRITE_LOCK_STALE_MS = 60000, HISTORY_WRITE_LOCK_BACKOFF_MS = 10, DANGEROUS_PROPERTY_NAMES, _internals40;
61124
61410
  var init_history_store = __esm(() => {
61125
61411
  init_manager2();
61126
61412
  DANGEROUS_PROPERTY_NAMES = new Set([
@@ -61128,7 +61414,7 @@ var init_history_store = __esm(() => {
61128
61414
  "constructor",
61129
61415
  "prototype"
61130
61416
  ]);
61131
- _internals39 = {
61417
+ _internals40 = {
61132
61418
  validateProjectRoot
61133
61419
  };
61134
61420
  });
@@ -61333,7 +61619,7 @@ function readPackageJsonRaw(dir) {
61333
61619
  }
61334
61620
  }
61335
61621
  function readPackageJson(dir) {
61336
- return _internals40.readPackageJsonRaw(dir);
61622
+ return _internals41.readPackageJsonRaw(dir);
61337
61623
  }
61338
61624
  function readPackageJsonTestScript(dir) {
61339
61625
  return readPackageJson(dir)?.scripts?.test ?? null;
@@ -61503,7 +61789,7 @@ function buildTypescriptBackend() {
61503
61789
  selectEntryPoints: selectEntryPoints3
61504
61790
  };
61505
61791
  }
61506
- var PROFILE_ID4 = "typescript", IMPORT_REGEX_ES2, IMPORT_REGEX_BARE, IMPORT_REGEX_REQUIRE2, IMPORT_REGEX_DYNAMIC, IMPORT_REGEX_REEXPORT2, _internals40;
61792
+ var PROFILE_ID4 = "typescript", IMPORT_REGEX_ES2, IMPORT_REGEX_BARE, IMPORT_REGEX_REQUIRE2, IMPORT_REGEX_DYNAMIC, IMPORT_REGEX_REEXPORT2, _internals41;
61507
61793
  var init_typescript = __esm(() => {
61508
61794
  init_default_backend();
61509
61795
  init_profiles();
@@ -61512,7 +61798,7 @@ var init_typescript = __esm(() => {
61512
61798
  IMPORT_REGEX_REQUIRE2 = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
61513
61799
  IMPORT_REGEX_DYNAMIC = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
61514
61800
  IMPORT_REGEX_REEXPORT2 = /export\s+(?:\{[^}]*\}|\*)\s+from\s+['"]([^'"]+)['"]/g;
61515
- _internals40 = {
61801
+ _internals41 = {
61516
61802
  readPackageJsonRaw,
61517
61803
  readPackageJsonTestScript,
61518
61804
  frameworkFromScriptsTest
@@ -61545,7 +61831,7 @@ __export(exports_dispatch, {
61545
61831
  pickedProfiles: () => pickedProfiles,
61546
61832
  pickBackend: () => pickBackend,
61547
61833
  clearDispatchCache: () => clearDispatchCache,
61548
- _internals: () => _internals41
61834
+ _internals: () => _internals42
61549
61835
  });
61550
61836
  import * as fs28 from "fs";
61551
61837
  import * as path58 from "path";
@@ -61600,7 +61886,7 @@ function findManifestRoot(start) {
61600
61886
  return start;
61601
61887
  }
61602
61888
  function evictIfNeeded() {
61603
- if (cache.size <= _internals41.cacheCapacity)
61889
+ if (cache.size <= _internals42.cacheCapacity)
61604
61890
  return;
61605
61891
  let oldestKey;
61606
61892
  let oldestOrder = Infinity;
@@ -61631,7 +61917,7 @@ async function pickBackend(dir) {
61631
61917
  evictIfNeeded();
61632
61918
  return null;
61633
61919
  }
61634
- const profiles = await _internals41.detectProjectLanguages(root);
61920
+ const profiles = await _internals42.detectProjectLanguages(root);
61635
61921
  if (profiles.length === 0) {
61636
61922
  cache.set(cacheKey, {
61637
61923
  hash: hash4,
@@ -61663,12 +61949,12 @@ function clearDispatchCache() {
61663
61949
  manifestRootCache.clear();
61664
61950
  insertCounter = 0;
61665
61951
  }
61666
- var _internals41, cache, insertCounter = 0, MANIFEST_FILES, _MANIFEST_SET, manifestRootCache;
61952
+ var _internals42, cache, insertCounter = 0, MANIFEST_FILES, _MANIFEST_SET, manifestRootCache;
61667
61953
  var init_dispatch = __esm(() => {
61668
61954
  init_backends();
61669
61955
  init_detector();
61670
61956
  init_registry_backend();
61671
- _internals41 = {
61957
+ _internals42 = {
61672
61958
  detectProjectLanguages,
61673
61959
  cacheCapacity: 64
61674
61960
  };
@@ -63524,9 +63810,9 @@ function getVersionFileVersion(dir) {
63524
63810
  async function runVersionCheck(dir, _timeoutMs) {
63525
63811
  const startTime = Date.now();
63526
63812
  try {
63527
- const packageVersion = _internals42.getPackageVersion(dir);
63528
- const changelogVersion = _internals42.getChangelogVersion(dir);
63529
- const versionFileVersion = _internals42.getVersionFileVersion(dir);
63813
+ const packageVersion = _internals43.getPackageVersion(dir);
63814
+ const changelogVersion = _internals43.getChangelogVersion(dir);
63815
+ const versionFileVersion = _internals43.getVersionFileVersion(dir);
63530
63816
  const versions3 = [];
63531
63817
  if (packageVersion)
63532
63818
  versions3.push(`package.json: ${packageVersion}`);
@@ -63890,7 +64176,7 @@ async function runPreflight(dir, phase, config3) {
63890
64176
  const reportId = `preflight-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
63891
64177
  let validatedDir;
63892
64178
  try {
63893
- validatedDir = _internals42.validateDirectoryPath(dir);
64179
+ validatedDir = _internals43.validateDirectoryPath(dir);
63894
64180
  } catch (error93) {
63895
64181
  return {
63896
64182
  id: reportId,
@@ -63910,7 +64196,7 @@ async function runPreflight(dir, phase, config3) {
63910
64196
  }
63911
64197
  let validatedTimeout;
63912
64198
  try {
63913
- validatedTimeout = _internals42.validateTimeout(config3?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
64199
+ validatedTimeout = _internals43.validateTimeout(config3?.checkTimeoutMs, DEFAULT_CONFIG.checkTimeoutMs);
63914
64200
  } catch (error93) {
63915
64201
  return {
63916
64202
  id: reportId,
@@ -63951,12 +64237,12 @@ async function runPreflight(dir, phase, config3) {
63951
64237
  });
63952
64238
  const checks5 = [];
63953
64239
  log("[Preflight] Running lint check...");
63954
- const lintResult = await _internals42.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
64240
+ const lintResult = await _internals43.runLintCheck(validatedDir, cfg.linter, cfg.checkTimeoutMs);
63955
64241
  checks5.push(lintResult);
63956
64242
  log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`);
63957
64243
  if (!cfg.skipTests) {
63958
64244
  log("[Preflight] Running tests check...");
63959
- const testsResult = await _internals42.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
64245
+ const testsResult = await _internals43.runTestsCheck(validatedDir, cfg.testScope, cfg.checkTimeoutMs);
63960
64246
  checks5.push(testsResult);
63961
64247
  log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`);
63962
64248
  } else {
@@ -63968,7 +64254,7 @@ async function runPreflight(dir, phase, config3) {
63968
64254
  }
63969
64255
  if (!cfg.skipSecrets) {
63970
64256
  log("[Preflight] Running secrets check...");
63971
- const secretsResult = await _internals42.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
64257
+ const secretsResult = await _internals43.runSecretsCheck(validatedDir, cfg.checkTimeoutMs);
63972
64258
  checks5.push(secretsResult);
63973
64259
  log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`);
63974
64260
  } else {
@@ -63980,7 +64266,7 @@ async function runPreflight(dir, phase, config3) {
63980
64266
  }
63981
64267
  if (!cfg.skipEvidence) {
63982
64268
  log("[Preflight] Running evidence check...");
63983
- const evidenceResult = await _internals42.runEvidenceCheck(validatedDir);
64269
+ const evidenceResult = await _internals43.runEvidenceCheck(validatedDir);
63984
64270
  checks5.push(evidenceResult);
63985
64271
  log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`);
63986
64272
  } else {
@@ -63991,12 +64277,12 @@ async function runPreflight(dir, phase, config3) {
63991
64277
  });
63992
64278
  }
63993
64279
  log("[Preflight] Running requirement coverage check...");
63994
- const reqCoverageResult = await _internals42.runRequirementCoverageCheck(validatedDir, phase);
64280
+ const reqCoverageResult = await _internals43.runRequirementCoverageCheck(validatedDir, phase);
63995
64281
  checks5.push(reqCoverageResult);
63996
64282
  log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`);
63997
64283
  if (!cfg.skipVersion) {
63998
64284
  log("[Preflight] Running version check...");
63999
- const versionResult = await _internals42.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
64285
+ const versionResult = await _internals43.runVersionCheck(validatedDir, cfg.checkTimeoutMs);
64000
64286
  checks5.push(versionResult);
64001
64287
  log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`);
64002
64288
  } else {
@@ -64059,10 +64345,10 @@ function formatPreflightMarkdown(report) {
64059
64345
  async function handlePreflightCommand(directory, _args) {
64060
64346
  const plan = await loadPlan(directory);
64061
64347
  const phase = plan?.current_phase ?? 1;
64062
- const report = await _internals42.runPreflight(directory, phase);
64063
- return _internals42.formatPreflightMarkdown(report);
64348
+ const report = await _internals43.runPreflight(directory, phase);
64349
+ return _internals43.formatPreflightMarkdown(report);
64064
64350
  }
64065
- var MIN_CHECK_TIMEOUT_MS = 5000, MAX_CHECK_TIMEOUT_MS = 300000, DEFAULT_CONFIG, _internals42;
64351
+ var MIN_CHECK_TIMEOUT_MS = 5000, MAX_CHECK_TIMEOUT_MS = 300000, DEFAULT_CONFIG, _internals43;
64066
64352
  var init_preflight_service = __esm(() => {
64067
64353
  init_gate_bridge();
64068
64354
  init_manager2();
@@ -64081,7 +64367,7 @@ var init_preflight_service = __esm(() => {
64081
64367
  testScope: "convention",
64082
64368
  linter: "biome"
64083
64369
  };
64084
- _internals42 = {
64370
+ _internals43 = {
64085
64371
  runPreflight,
64086
64372
  formatPreflightMarkdown,
64087
64373
  handlePreflightCommand,
@@ -65506,7 +65792,7 @@ async function handleSimulateCommand(directory, args) {
65506
65792
  }
65507
65793
  let darkMatterPairs;
65508
65794
  try {
65509
- darkMatterPairs = await _internals22.detectDarkMatter(directory, options);
65795
+ darkMatterPairs = await _internals23.detectDarkMatter(directory, options);
65510
65796
  } catch (err) {
65511
65797
  const errMsg = err instanceof Error ? err.message : String(err);
65512
65798
  return `## Simulate Report
@@ -65876,7 +66162,7 @@ async function getStatusData(directory, agents) {
65876
66162
  }
65877
66163
  function enrichWithLeanTurbo(status, directory) {
65878
66164
  const turboMode = hasActiveTurboMode();
65879
- const leanActive = _internals43.hasActiveLeanTurbo();
66165
+ const leanActive = _internals44.hasActiveLeanTurbo();
65880
66166
  let turboStrategy = "off";
65881
66167
  if (leanActive) {
65882
66168
  turboStrategy = "lean";
@@ -65895,7 +66181,7 @@ function enrichWithLeanTurbo(status, directory) {
65895
66181
  }
65896
66182
  }
65897
66183
  if (leanSessionID) {
65898
- const runState = _internals43.loadLeanTurboRunState(directory, leanSessionID);
66184
+ const runState = _internals44.loadLeanTurboRunState(directory, leanSessionID);
65899
66185
  if (runState) {
65900
66186
  status.leanTurboPhase = runState.phase;
65901
66187
  status.leanMaxParallelCoders = runState.maxParallelCoders;
@@ -65927,7 +66213,7 @@ function enrichWithLeanTurbo(status, directory) {
65927
66213
  }
65928
66214
  }
65929
66215
  }
65930
- status.fullAutoActive = _internals43.hasActiveFullAuto();
66216
+ status.fullAutoActive = _internals44.hasActiveFullAuto();
65931
66217
  return status;
65932
66218
  }
65933
66219
  function formatStatusMarkdown(status) {
@@ -66055,7 +66341,7 @@ async function countProposals(directory) {
66055
66341
  return 0;
66056
66342
  }
66057
66343
  }
66058
- var _internals43;
66344
+ var _internals44;
66059
66345
  var init_status_service = __esm(() => {
66060
66346
  init_extractors();
66061
66347
  init_knowledge_escalator();
@@ -66065,7 +66351,7 @@ var init_status_service = __esm(() => {
66065
66351
  init_state3();
66066
66352
  init_compaction_service();
66067
66353
  init_context_budget_service();
66068
- _internals43 = {
66354
+ _internals44 = {
66069
66355
  loadLeanTurboRunState,
66070
66356
  hasActiveLeanTurbo,
66071
66357
  hasActiveFullAuto
@@ -66156,7 +66442,7 @@ async function handleTurboCommand(directory, args, sessionID) {
66156
66442
  if (arg0 === "on") {
66157
66443
  let strategy = "standard";
66158
66444
  try {
66159
- const { config: config3 } = _internals44.loadPluginConfigWithMeta(directory);
66445
+ const { config: config3 } = _internals45.loadPluginConfigWithMeta(directory);
66160
66446
  if (config3.turbo?.strategy === "lean") {
66161
66447
  strategy = "lean";
66162
66448
  }
@@ -66211,7 +66497,7 @@ function enableLeanTurbo(session, directory, sessionID) {
66211
66497
  let maxParallelCoders = 4;
66212
66498
  let conflictPolicy = "serialize";
66213
66499
  try {
66214
- const { config: config3 } = _internals44.loadPluginConfigWithMeta(directory);
66500
+ const { config: config3 } = _internals45.loadPluginConfigWithMeta(directory);
66215
66501
  const leanConfig = config3.turbo?.lean;
66216
66502
  if (leanConfig) {
66217
66503
  maxParallelCoders = leanConfig.max_parallel_coders ?? 4;
@@ -66281,13 +66567,13 @@ function buildStatusMessage2(session, directory, sessionID) {
66281
66567
  ].join(`
66282
66568
  `);
66283
66569
  }
66284
- var _internals44;
66570
+ var _internals45;
66285
66571
  var init_turbo = __esm(() => {
66286
66572
  init_config();
66287
66573
  init_state();
66288
66574
  init_state3();
66289
66575
  init_logger();
66290
- _internals44 = {
66576
+ _internals45 = {
66291
66577
  loadPluginConfigWithMeta
66292
66578
  };
66293
66579
  });
@@ -66353,342 +66639,6 @@ var init_write_retro2 = __esm(() => {
66353
66639
  init_write_retro();
66354
66640
  });
66355
66641
 
66356
- // src/commands/command-dispatch.ts
66357
- function normalizeSwarmCommandInput(command, argumentText) {
66358
- if (command !== "swarm" && !command.startsWith("swarm-")) {
66359
- return { isSwarmCommand: false, tokens: [] };
66360
- }
66361
- if (command === "swarm") {
66362
- return {
66363
- isSwarmCommand: true,
66364
- tokens: argumentText.trim().split(/\s+/).filter(Boolean)
66365
- };
66366
- }
66367
- const subcommand = command.slice("swarm-".length);
66368
- const extraArgs = argumentText.trim().split(/\s+/).filter(Boolean);
66369
- return {
66370
- isSwarmCommand: true,
66371
- tokens: [subcommand, ...extraArgs].filter(Boolean)
66372
- };
66373
- }
66374
- function canonicalCommandKey(resolved) {
66375
- return resolved.entry.aliasOf ?? resolved.key;
66376
- }
66377
- function formatCommandNotFound(tokens) {
66378
- const attemptedCommand = tokens[0] || "";
66379
- const MAX_DISPLAY = 100;
66380
- const displayCommand = attemptedCommand.length > MAX_DISPLAY ? `${attemptedCommand.slice(0, MAX_DISPLAY)}...` : attemptedCommand;
66381
- const similar = _internals45.findSimilarCommands(attemptedCommand);
66382
- const header = `Command \`/swarm ${displayCommand}\` not found.`;
66383
- const suggestions = similar.length > 0 ? `Did you mean:
66384
- ${similar.map((cmd) => ` - /swarm ${cmd}`).join(`
66385
- `)}` : "";
66386
- const footer = "Run `/swarm help` for all commands.";
66387
- return [header, suggestions, footer].filter(Boolean).join(`
66388
-
66389
- `);
66390
- }
66391
- async function executeSwarmCommand(args) {
66392
- const {
66393
- directory,
66394
- agents,
66395
- sessionID,
66396
- tokens,
66397
- packageRoot,
66398
- buildHelpText,
66399
- policy
66400
- } = args;
66401
- let text;
66402
- const resolved = resolveCommand(tokens);
66403
- if (!resolved) {
66404
- text = tokens.length === 0 && buildHelpText ? buildHelpText() : formatCommandNotFound(tokens);
66405
- } else {
66406
- const policyResult = policy?.(resolved) ?? { allowed: true };
66407
- if (!policyResult.allowed) {
66408
- text = policyResult.message;
66409
- } else {
66410
- try {
66411
- text = await resolved.entry.handler({
66412
- directory,
66413
- args: resolved.remainingArgs,
66414
- sessionID,
66415
- agents,
66416
- packageRoot,
66417
- source: "chat"
66418
- });
66419
- } catch (_err) {
66420
- const cmdName = tokens[0] || "unknown";
66421
- const errMsg = _err instanceof Error ? _err.message : String(_err);
66422
- text = `Error executing /swarm ${cmdName}: ${errMsg}`;
66423
- }
66424
- if (resolved.warning) {
66425
- text = `${resolved.warning}
66426
-
66427
- ${text}`;
66428
- }
66429
- }
66430
- }
66431
- return {
66432
- text,
66433
- resolved: resolved ?? undefined,
66434
- canonicalKey: resolved ? canonicalCommandKey(resolved) : undefined
66435
- };
66436
- }
66437
- var init_command_dispatch = __esm(() => {
66438
- init_registry();
66439
- });
66440
-
66441
- // src/commands/tool-policy.ts
66442
- function classifySwarmCommandToolUse(resolved) {
66443
- const canonicalKey = canonicalCommandKey(resolved);
66444
- const args = resolved.remainingArgs;
66445
- if (!SWARM_COMMAND_TOOL_ALLOWLIST.has(canonicalKey)) {
66446
- if (HUMAN_ONLY_SWARM_COMMANDS.has(canonicalKey)) {
66447
- return {
66448
- allowed: false,
66449
- message: `/swarm ${canonicalKey} is a human-only command. ` + `Present the situation to the user and ask them to run \`/swarm ${canonicalKey}\` themselves ` + `(or \`bunx opencode-swarm run ${canonicalKey}\` from a terminal). ` + `You MUST NOT run it yourself via Bash, swarm_command, or any other tool \u2014 ` + `the runtime guardrail will block such attempts.`
66450
- };
66451
- }
66452
- return {
66453
- allowed: false,
66454
- message: `/swarm ${canonicalKey} is not available through the chat tool yet.
66455
-
66456
- ` + `Use the canonical CLI path for now: \`bunx opencode-swarm run ${canonicalKey}\`.
66457
- ` + `Commands with state changes, auto-heal behavior, or subprocesses need confirmation gates before chat-tool support.`
66458
- };
66459
- }
66460
- if (canonicalKey === "config doctor" && args.some((arg) => arg === "--fix" || arg === "-f")) {
66461
- return {
66462
- allowed: false,
66463
- message: "/swarm config doctor --fix is not available through swarm_command. Run the CLI command directly when you intend to modify config files."
66464
- };
66465
- }
66466
- if (NO_ARGS.has(canonicalKey) && args.length > 0) {
66467
- return {
66468
- allowed: false,
66469
- message: `/swarm ${canonicalKey} does not accept arguments through swarm_command.`
66470
- };
66471
- }
66472
- if (canonicalKey === "knowledge") {
66473
- if (args.length === 0)
66474
- return { allowed: true };
66475
- if (args.length === 1 && (args[0] === "list" || args[0] === "unactionable"))
66476
- return { allowed: true };
66477
- return {
66478
- allowed: false,
66479
- message: "Only `/swarm knowledge`, `/swarm knowledge list`, and `/swarm knowledge unactionable` are available through swarm_command. Knowledge migrate/quarantine/restore/retry-hardening are intentionally excluded."
66480
- };
66481
- }
66482
- if (canonicalKey === "memory") {
66483
- if (args.length === 0)
66484
- return { allowed: true };
66485
- return {
66486
- allowed: false,
66487
- message: "Use `/swarm memory status`, `/swarm memory pending`, `/swarm memory recall-log`, `/swarm memory stale`, `/swarm memory export`, or `/swarm memory evaluate --json` through swarm_command. Memory import, migrate, and compact are intentionally excluded from chat-tool execution."
66488
- };
66489
- }
66490
- if (canonicalKey === "memory evaluate") {
66491
- if (args.length === 0)
66492
- return { allowed: true };
66493
- if (args.length === 1 && args[0] === "--json")
66494
- return { allowed: true };
66495
- return {
66496
- allowed: false,
66497
- message: "Usage through swarm_command: `/swarm memory evaluate --json`. Custom fixture directories are only available through direct user command execution."
66498
- };
66499
- }
66500
- if (canonicalKey === "sdd status") {
66501
- if (args.length === 0)
66502
- return { allowed: true };
66503
- if (args.length === 1 && args[0] === "--json")
66504
- return { allowed: true };
66505
- return {
66506
- allowed: false,
66507
- message: "Usage through swarm_command: `/swarm sdd status` or `/swarm sdd status --json`."
66508
- };
66509
- }
66510
- if (canonicalKey === "sdd validate") {
66511
- if (args.length === 0)
66512
- return { allowed: true };
66513
- if (args.length === 1 && args[0] === "--json")
66514
- return { allowed: true };
66515
- if (args.length === 2 && args[0] === "--change" && /^[A-Za-z0-9_.-]{1,128}$/.test(args[1])) {
66516
- return { allowed: true };
66517
- }
66518
- return {
66519
- allowed: false,
66520
- message: "Usage through swarm_command: `/swarm sdd validate`, `/swarm sdd validate --json`, or `/swarm sdd validate --change <id>`."
66521
- };
66522
- }
66523
- if (canonicalKey === "memory pending" || canonicalKey === "memory recall-log" || canonicalKey === "memory stale") {
66524
- if (args.length === 0)
66525
- return { allowed: true };
66526
- if (args.length === 2 && args[0] === "--limit" && /^\d+$/.test(args[1])) {
66527
- return { allowed: true };
66528
- }
66529
- return {
66530
- allowed: false,
66531
- message: `Usage through swarm_command: \`/swarm ${canonicalKey}\` or ` + `\`/swarm ${canonicalKey} --limit <n>\`.`
66532
- };
66533
- }
66534
- if (canonicalKey === "retrieve") {
66535
- if (args.length !== 1 || !SUMMARY_ID_PATTERN.test(args[0])) {
66536
- return {
66537
- allowed: false,
66538
- message: "Usage through swarm_command: `/swarm retrieve <summary-id>` with a single summary ID such as S1."
66539
- };
66540
- }
66541
- }
66542
- if (canonicalKey === "benchmark") {
66543
- const allowedFlags = new Set(["--cumulative", "--ci-gate"]);
66544
- const invalid = args.filter((arg) => !allowedFlags.has(arg));
66545
- if (invalid.length > 0) {
66546
- return {
66547
- allowed: false,
66548
- message: "Only `--cumulative` and `--ci-gate` are supported for `/swarm benchmark` through swarm_command."
66549
- };
66550
- }
66551
- }
66552
- if (canonicalKey === "show-plan") {
66553
- if (args.length > 1 || args[0] && !/^\d+$/.test(args[0])) {
66554
- return {
66555
- allowed: false,
66556
- message: "Usage through swarm_command: `/swarm show-plan` or `/swarm show-plan <phase-number>`."
66557
- };
66558
- }
66559
- }
66560
- if (canonicalKey === "evidence") {
66561
- if (args.length > 1 || args[0] && !TASK_ID_PATTERN.test(args[0])) {
66562
- return {
66563
- allowed: false,
66564
- message: "Usage through swarm_command: `/swarm evidence` or `/swarm evidence <task-id>`."
66565
- };
66566
- }
66567
- }
66568
- if (canonicalKey === "help" && args.length > 2) {
66569
- return {
66570
- allowed: false,
66571
- message: "Usage through swarm_command: `/swarm help` or `/swarm help <command>`."
66572
- };
66573
- }
66574
- return { allowed: true };
66575
- }
66576
- function classifySwarmCommandChatFallbackUse(resolved) {
66577
- const canonicalKey = canonicalCommandKey(resolved);
66578
- const args = resolved.remainingArgs;
66579
- if (canonicalKey === "config doctor" && args.some((arg) => arg === "--fix" || arg === "-f")) {
66580
- return {
66581
- allowed: false,
66582
- message: "/swarm config doctor --fix is not available through chat fallback because it can modify configuration files. Run the CLI command directly when you intend to apply fixes."
66583
- };
66584
- }
66585
- if (canonicalKey === "knowledge migrate" || canonicalKey === "knowledge quarantine" || canonicalKey === "knowledge restore" || canonicalKey === "memory import" || canonicalKey === "memory migrate" || canonicalKey === "memory compact" || canonicalKey === "sdd project") {
66586
- return {
66587
- allowed: false,
66588
- message: `/swarm ${canonicalKey} is not available through chat fallback because it mutates .swarm state. ` + "Run the CLI command directly after confirming the intended state change."
66589
- };
66590
- }
66591
- return { allowed: true };
66592
- }
66593
- var SWARM_COMMAND_TOOL_COMMANDS, SWARM_COMMAND_TOOL_ALLOWLIST, HUMAN_ONLY_SWARM_COMMANDS, NO_ARGS, SUMMARY_ID_PATTERN, TASK_ID_PATTERN;
66594
- var init_tool_policy = __esm(() => {
66595
- init_command_dispatch();
66596
- SWARM_COMMAND_TOOL_COMMANDS = [
66597
- "agents",
66598
- "config",
66599
- "config doctor",
66600
- "doctor tools",
66601
- "status",
66602
- "show-plan",
66603
- "help",
66604
- "history",
66605
- "evidence",
66606
- "evidence summary",
66607
- "retrieve",
66608
- "diagnose",
66609
- "preflight",
66610
- "benchmark",
66611
- "knowledge",
66612
- "memory",
66613
- "memory status",
66614
- "memory pending",
66615
- "memory recall-log",
66616
- "memory compact",
66617
- "memory stale",
66618
- "memory export",
66619
- "memory evaluate",
66620
- "memory import",
66621
- "memory migrate",
66622
- "sdd",
66623
- "sdd status",
66624
- "sdd validate",
66625
- "sdd project",
66626
- "sync-plan",
66627
- "export",
66628
- "auto-proceed"
66629
- ];
66630
- SWARM_COMMAND_TOOL_ALLOWLIST = new Set([
66631
- "agents",
66632
- "config",
66633
- "config doctor",
66634
- "doctor tools",
66635
- "status",
66636
- "show-plan",
66637
- "help",
66638
- "history",
66639
- "evidence",
66640
- "evidence summary",
66641
- "retrieve",
66642
- "diagnose",
66643
- "preflight",
66644
- "benchmark",
66645
- "knowledge",
66646
- "memory",
66647
- "memory status",
66648
- "memory pending",
66649
- "memory recall-log",
66650
- "memory stale",
66651
- "memory export",
66652
- "memory evaluate",
66653
- "sdd",
66654
- "sdd status",
66655
- "sdd validate",
66656
- "sync-plan",
66657
- "export",
66658
- "auto-proceed"
66659
- ]);
66660
- HUMAN_ONLY_SWARM_COMMANDS = new Set([
66661
- "acknowledge-spec-drift",
66662
- "reset",
66663
- "reset-session",
66664
- "rollback",
66665
- "checkpoint",
66666
- "consolidate",
66667
- "memory import",
66668
- "memory migrate",
66669
- "memory compact",
66670
- "sdd project"
66671
- ]);
66672
- NO_ARGS = new Set([
66673
- "agents",
66674
- "config",
66675
- "config doctor",
66676
- "doctor tools",
66677
- "status",
66678
- "history",
66679
- "evidence summary",
66680
- "diagnose",
66681
- "preflight",
66682
- "sync-plan",
66683
- "export",
66684
- "memory",
66685
- "memory status",
66686
- "memory export"
66687
- ]);
66688
- SUMMARY_ID_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
66689
- TASK_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,64}$/;
66690
- });
66691
-
66692
66642
  // src/commands/command-names.ts
66693
66643
  var COMMAND_NAMES, COMMAND_NAME_SET;
66694
66644
  var init_command_names = __esm(() => {
@@ -66906,7 +66856,7 @@ async function buildSwarmCommandPrompt(args) {
66906
66856
  packageRoot,
66907
66857
  registeredAgents
66908
66858
  } = args;
66909
- const resolved = _internals45.resolveCommand(tokens);
66859
+ const resolved = _internals11.resolveCommand(tokens);
66910
66860
  if (!resolved) {
66911
66861
  if (tokens.length === 0) {
66912
66862
  return buildHelpText();
@@ -67079,7 +67029,7 @@ function findSimilarCommands(query) {
67079
67029
  }
67080
67030
  const scored = VALID_COMMANDS.map((cmd) => {
67081
67031
  const cmdLower = cmd.toLowerCase();
67082
- const fullScore = _internals45.levenshteinDistance(q, cmdLower);
67032
+ const fullScore = _internals11.levenshteinDistance(q, cmdLower);
67083
67033
  let tokenScore = Infinity;
67084
67034
  if (cmd.includes(" ") || cmd.includes("-")) {
67085
67035
  const qTokens = q.split(/[\s-]+/);
@@ -67092,7 +67042,7 @@ function findSimilarCommands(query) {
67092
67042
  for (const ct of cmdTokens) {
67093
67043
  if (ct.length === 0)
67094
67044
  continue;
67095
- const dist = _internals45.levenshteinDistance(qt, ct);
67045
+ const dist = _internals11.levenshteinDistance(qt, ct);
67096
67046
  if (dist < minDist)
67097
67047
  minDist = dist;
67098
67048
  }
@@ -67102,7 +67052,7 @@ function findSimilarCommands(query) {
67102
67052
  }
67103
67053
  const dashStrippedQ = q.replace(/-/g, "");
67104
67054
  const dashStrippedCmd = cmdLower.replace(/-/g, "");
67105
- const dashScore = _internals45.levenshteinDistance(dashStrippedQ, dashStrippedCmd);
67055
+ const dashScore = _internals11.levenshteinDistance(dashStrippedQ, dashStrippedCmd);
67106
67056
  const score = Math.min(fullScore, tokenScore, dashScore);
67107
67057
  return { cmd, score };
67108
67058
  });
@@ -67134,11 +67084,11 @@ async function handleHelpCommand(ctx) {
67134
67084
  return buildHelpText2();
67135
67085
  }
67136
67086
  const tokens = targetCommand.split(/\s+/);
67137
- const resolved = _internals45.resolveCommand(tokens);
67087
+ const resolved = _internals11.resolveCommand(tokens);
67138
67088
  if (resolved) {
67139
- return _internals45.buildDetailedHelp(resolved.key, resolved.entry);
67089
+ return _internals11.buildDetailedHelp(resolved.key, resolved.entry);
67140
67090
  }
67141
- const similar = _internals45.findSimilarCommands(targetCommand);
67091
+ const similar = _internals11.findSimilarCommands(targetCommand);
67142
67092
  const { buildHelpText: fullHelp } = await Promise.resolve().then(() => (init_commands(), exports_commands));
67143
67093
  if (similar.length > 0) {
67144
67094
  return `Command '/swarm ${targetCommand}' not found.
@@ -67209,6 +67159,18 @@ function validateAliases() {
67209
67159
  }
67210
67160
  return { valid: errors5.length === 0, errors: errors5, warnings };
67211
67161
  }
67162
+ function validateToolPolicy() {
67163
+ const warnings = [];
67164
+ for (const [name, entry] of Object.entries(COMMAND_REGISTRY)) {
67165
+ const cmdEntry = entry;
67166
+ if (cmdEntry.aliasOf || cmdEntry.subcommandOf)
67167
+ continue;
67168
+ if (cmdEntry.toolPolicy === undefined) {
67169
+ warnings.push(`Command '${name}' has no toolPolicy field \u2014 it will not be available through the swarm_command tool. Add toolPolicy: 'agent' | 'human-only' | 'restricted' | 'none'.`);
67170
+ }
67171
+ }
67172
+ return { valid: warnings.length === 0, warnings };
67173
+ }
67212
67174
  function resolveCommand(tokens) {
67213
67175
  if (tokens.length === 0)
67214
67176
  return null;
@@ -67238,7 +67200,7 @@ function resolveCommand(tokens) {
67238
67200
  }
67239
67201
  return null;
67240
67202
  }
67241
- var COMMAND_REGISTRY, VALID_COMMANDS, _internals45, validation;
67203
+ var COMMAND_REGISTRY, VALID_COMMANDS, _internals11, validation;
67242
67204
  var init_registry = __esm(() => {
67243
67205
  init_bundled_skills();
67244
67206
  init_acknowledge_spec_drift();
@@ -67294,19 +67256,23 @@ var init_registry = __esm(() => {
67294
67256
  handler: (ctx) => handleAcknowledgeSpecDriftCommand(ctx.directory, ctx.args, ctx.source === "cli" ? "cli" : ctx.source === "chat" ? "user" : "unknown"),
67295
67257
  description: "Acknowledge that the spec has drifted from the plan and suppress further warnings",
67296
67258
  args: "",
67297
- category: "diagnostics"
67259
+ category: "diagnostics",
67260
+ toolPolicy: "restricted"
67298
67261
  },
67299
67262
  status: {
67300
67263
  handler: (ctx) => handleStatusCommand(ctx.directory, ctx.agents),
67301
67264
  description: "Show current swarm state",
67302
67265
  category: "core",
67303
- clashesWithNativeCcCommand: "/status"
67266
+ clashesWithNativeCcCommand: "/status",
67267
+ toolPolicy: "agent",
67268
+ toolNoArgs: true
67304
67269
  },
67305
67270
  "show-plan": {
67306
67271
  handler: (ctx) => handlePlanCommand(ctx.directory, ctx.args),
67307
67272
  description: "Show current plan (optionally filter by phase number)",
67308
67273
  category: "core",
67309
- args: "[phase-number]"
67274
+ args: "[phase-number]",
67275
+ toolPolicy: "agent"
67310
67276
  },
67311
67277
  plan: {
67312
67278
  handler: (ctx) => handlePlanCommand(ctx.directory, ctx.args),
@@ -67320,32 +67286,41 @@ var init_registry = __esm(() => {
67320
67286
  handler: (ctx) => Promise.resolve(handleAgentsCommand(ctx.agents, undefined)),
67321
67287
  description: "List registered agents",
67322
67288
  category: "core",
67323
- clashesWithNativeCcCommand: "/agents"
67289
+ clashesWithNativeCcCommand: "/agents",
67290
+ toolPolicy: "agent",
67291
+ toolNoArgs: true
67324
67292
  },
67325
67293
  help: {
67326
- handler: (ctx) => _internals45.handleHelpCommand(ctx),
67294
+ handler: (ctx) => _internals11.handleHelpCommand(ctx),
67327
67295
  description: "Show help for swarm commands",
67328
67296
  category: "core",
67329
67297
  args: "[command]",
67330
- details: "Without argument, shows full command listing. With argument, shows detailed help for a specific command."
67298
+ details: "Without argument, shows full command listing. With argument, shows detailed help for a specific command.",
67299
+ toolPolicy: "agent"
67331
67300
  },
67332
67301
  history: {
67333
67302
  handler: (ctx) => handleHistoryCommand(ctx.directory, ctx.args),
67334
67303
  description: "Show completed phases summary",
67335
67304
  category: "utility",
67336
- clashesWithNativeCcCommand: "/history"
67305
+ clashesWithNativeCcCommand: "/history",
67306
+ toolPolicy: "agent",
67307
+ toolNoArgs: true
67337
67308
  },
67338
67309
  config: {
67339
67310
  handler: (ctx) => handleConfigCommand(ctx.directory, ctx.args),
67340
67311
  description: "Show current resolved configuration",
67341
67312
  category: "config",
67342
- clashesWithNativeCcCommand: "/config"
67313
+ clashesWithNativeCcCommand: "/config",
67314
+ toolPolicy: "agent",
67315
+ toolNoArgs: true
67343
67316
  },
67344
67317
  "config doctor": {
67345
67318
  handler: (ctx) => handleDoctorCommand(ctx.directory, ctx.args),
67346
67319
  description: "Run config doctor checks",
67347
67320
  subcommandOf: "config",
67348
- category: "diagnostics"
67321
+ category: "diagnostics",
67322
+ toolPolicy: "agent",
67323
+ toolNoArgs: true
67349
67324
  },
67350
67325
  "config-doctor": {
67351
67326
  handler: (ctx) => handleDoctorCommand(ctx.directory, ctx.args),
@@ -67358,7 +67333,9 @@ var init_registry = __esm(() => {
67358
67333
  "doctor tools": {
67359
67334
  handler: (ctx) => handleDoctorToolsCommand(ctx.directory, ctx.args),
67360
67335
  description: "Run tool registration coherence check",
67361
- category: "diagnostics"
67336
+ category: "diagnostics",
67337
+ toolPolicy: "agent",
67338
+ toolNoArgs: true
67362
67339
  },
67363
67340
  "doctor-tools": {
67364
67341
  handler: (ctx) => handleDoctorToolsCommand(ctx.directory, ctx.args),
@@ -67370,7 +67347,9 @@ var init_registry = __esm(() => {
67370
67347
  diagnose: {
67371
67348
  handler: (ctx) => handleDiagnoseCommand(ctx.directory, ctx.args),
67372
67349
  description: "Run health check on swarm state",
67373
- category: "diagnostics"
67350
+ category: "diagnostics",
67351
+ toolPolicy: "agent",
67352
+ toolNoArgs: true
67374
67353
  },
67375
67354
  diagnosis: {
67376
67355
  handler: (ctx) => handleDiagnoseCommand(ctx.directory, ctx.args),
@@ -67382,26 +67361,32 @@ var init_registry = __esm(() => {
67382
67361
  preflight: {
67383
67362
  handler: (ctx) => handlePreflightCommand(ctx.directory, ctx.args),
67384
67363
  description: "Run preflight automation checks",
67385
- category: "diagnostics"
67364
+ category: "diagnostics",
67365
+ toolPolicy: "agent",
67366
+ toolNoArgs: true
67386
67367
  },
67387
67368
  "sync-plan": {
67388
67369
  handler: (ctx) => handleSyncPlanCommand(ctx.directory, ctx.args),
67389
67370
  description: "Ensure plan.json and plan.md are synced",
67390
67371
  args: "",
67391
- category: "config"
67372
+ category: "config",
67373
+ toolPolicy: "agent",
67374
+ toolNoArgs: true
67392
67375
  },
67393
67376
  benchmark: {
67394
67377
  handler: (ctx) => handleBenchmarkCommand(ctx.directory, ctx.args),
67395
67378
  description: "Show performance metrics [--cumulative] [--ci-gate]",
67396
67379
  args: "--cumulative, --ci-gate",
67397
- category: "diagnostics"
67380
+ category: "diagnostics",
67381
+ toolPolicy: "agent"
67398
67382
  },
67399
67383
  learning: {
67400
67384
  handler: (ctx) => handleLearningCommand(ctx.directory, ctx.args),
67401
67385
  description: "Show learning metrics and violation trends",
67402
67386
  args: "--json, --phase <N>",
67403
67387
  details: "Computes aggregate learning metrics from knowledge events: violation-rate trends, directive application rates, escalation frequency, per-entry ROI, and never-applied entries. Surfaces a learning summary for the curator digest.",
67404
- category: "diagnostics"
67388
+ category: "diagnostics",
67389
+ toolPolicy: "agent"
67405
67390
  },
67406
67391
  export: {
67407
67392
  handler: (ctx) => handleExportCommand(ctx.directory, ctx.args),
@@ -67409,14 +67394,17 @@ var init_registry = __esm(() => {
67409
67394
  args: "",
67410
67395
  details: "Exports the current plan and context as JSON to stdout. Useful for piping to external tools or debugging swarm state.",
67411
67396
  category: "utility",
67412
- clashesWithNativeCcCommand: "/export"
67397
+ clashesWithNativeCcCommand: "/export",
67398
+ toolPolicy: "agent",
67399
+ toolNoArgs: true
67413
67400
  },
67414
67401
  evidence: {
67415
67402
  handler: (ctx) => handleEvidenceCommand(ctx.directory, ctx.args),
67416
67403
  description: "Show evidence bundles [taskId]",
67417
67404
  args: "<taskId>",
67418
67405
  details: 'Displays review results, test verdicts, and other evidence bundles for the given task ID (e.g., "2.1").',
67419
- category: "utility"
67406
+ category: "utility",
67407
+ toolPolicy: "agent"
67420
67408
  },
67421
67409
  "evidence summary": {
67422
67410
  handler: (ctx) => handleEvidenceSummaryCommand(ctx.directory),
@@ -67424,7 +67412,9 @@ var init_registry = __esm(() => {
67424
67412
  subcommandOf: "evidence",
67425
67413
  args: "",
67426
67414
  details: "Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",
67427
- category: "utility"
67415
+ category: "utility",
67416
+ toolPolicy: "agent",
67417
+ toolNoArgs: true
67428
67418
  },
67429
67419
  "evidence-summary": {
67430
67420
  handler: (ctx) => handleEvidenceSummaryCommand(ctx.directory),
@@ -67484,13 +67474,15 @@ var init_registry = __esm(() => {
67484
67474
  description: "Archive old evidence bundles [--dry-run]",
67485
67475
  details: "Archives evidence bundles older than max_age_days (config, default 90) or beyond max_bundles cap (config, default 1000). --dry-run previews which bundles would be archived without deleting them. Applies two-tier retention: age-based first, then count-based on oldest remaining.",
67486
67476
  args: "--dry-run",
67487
- category: "utility"
67477
+ category: "utility",
67478
+ toolPolicy: "none"
67488
67479
  },
67489
67480
  curate: {
67490
67481
  handler: (ctx) => handleCurateCommand(ctx.directory, ctx.args),
67491
67482
  description: "Run knowledge curation and hive promotion review",
67492
67483
  args: "",
67493
- category: "utility"
67484
+ category: "utility",
67485
+ toolPolicy: "none"
67494
67486
  },
67495
67487
  consolidate: {
67496
67488
  handler: (ctx) => handleConsolidateCommand(ctx.directory, ctx.args, {
@@ -67499,13 +67491,15 @@ var init_registry = __esm(() => {
67499
67491
  description: "Run quota-bounded skill-improver consolidation and stage skill proposals",
67500
67492
  details: "Runs the same consolidation pass used by scheduled skill_improver trigger points: queue hardening, skill-improver proposal writing, and optional draft-skill generation. It never auto-activates skills. Use --respect-interval to obey the configured cadence instead of forcing a run.",
67501
67493
  args: "--force, --respect-interval, --evaluate",
67502
- category: "utility"
67494
+ category: "utility",
67495
+ toolPolicy: "restricted"
67503
67496
  },
67504
67497
  "dark-matter": {
67505
67498
  handler: (ctx) => handleDarkMatterCommand(ctx.directory, ctx.args),
67506
67499
  description: "Detect hidden file couplings via co-change NPMI analysis",
67507
67500
  args: "--threshold <number>, --min-commits <number>",
67508
- category: "diagnostics"
67501
+ category: "diagnostics",
67502
+ toolPolicy: "none"
67509
67503
  },
67510
67504
  finalize: {
67511
67505
  handler: (ctx) => handleCloseCommand(ctx.directory, ctx.args, {
@@ -67514,7 +67508,8 @@ var init_registry = __esm(() => {
67514
67508
  description: "Use /swarm finalize to finalize the swarm project and archive evidence",
67515
67509
  details: "Idempotent 4-stage terminal finalization: (1) finalize writes retrospectives for in-progress phases, (2) archive creates timestamped bundle of swarm artifacts and evidence, (3) clean removes active-state files for a clean slate, (4) align performs safe git ff-only to main. Resets agent sessions and delegation chains. Reads .swarm/close-lessons.md for explicit lessons and runs curation. Use --skill-review to run the quota-bounded skill_improver in proposal mode.",
67516
67510
  args: "--prune-branches, --skill-review",
67517
- category: "core"
67511
+ category: "core",
67512
+ toolPolicy: "none"
67518
67513
  },
67519
67514
  close: {
67520
67515
  handler: (ctx) => handleCloseCommand(ctx.directory, ctx.args, {
@@ -67534,7 +67529,8 @@ var init_registry = __esm(() => {
67534
67529
  description: "Run the post-mortem agent: project-end synthesis, queue triage, and final curation pass",
67535
67530
  details: "Reads .swarm/ evidence (knowledge entries, events, curator digests, proposals, retrospectives, drift reports) and produces a post-mortem report at .swarm/post-mortem-{planId}.md. Idempotent: re-runs skip if report exists unless --force is passed.",
67536
67531
  args: "--force",
67537
- category: "core"
67532
+ category: "core",
67533
+ toolPolicy: "agent"
67538
67534
  },
67539
67535
  concurrency: {
67540
67536
  handler: (ctx) => handleConcurrencyCommand(ctx.directory, ctx.args, ctx.sessionID),
@@ -67551,115 +67547,133 @@ Subcommands:
67551
67547
  ` + ` concurrency reset \u2014 Clear the session concurrency override
67552
67548
  ` + `
67553
67549
  ` + "Session-scoped \u2014 resets on new session.",
67554
- category: "utility"
67550
+ category: "utility",
67551
+ toolPolicy: "none"
67555
67552
  },
67556
67553
  simulate: {
67557
67554
  handler: (ctx) => handleSimulateCommand(ctx.directory, ctx.args),
67558
67555
  description: "Dry-run hidden coupling analysis with configurable thresholds",
67559
67556
  args: "--threshold <number>, --min-commits <number>",
67560
- category: "diagnostics"
67557
+ category: "diagnostics",
67558
+ toolPolicy: "none"
67561
67559
  },
67562
67560
  sdd: {
67563
67561
  handler: (ctx) => handleSddCommand(ctx.directory, ctx.args),
67564
67562
  description: "Manage OpenSpec-compatible SDD artifacts and effective spec projection",
67565
67563
  args: "status|validate|project [--json] [--change <id>] [--dry-run]",
67566
67564
  details: "Parent command for spec-driven development artifacts. Use sdd status to inspect .swarm/spec.md plus openspec/ artifacts, sdd validate to validate OpenSpec-compatible deltas, and sdd project to materialize the effective spec into .swarm/spec.md for planning.",
67567
- category: "utility"
67565
+ category: "utility",
67566
+ toolPolicy: "agent"
67568
67567
  },
67569
67568
  "sdd status": {
67570
67569
  handler: (ctx) => handleSddStatusCommand(ctx.directory, ctx.args),
67571
67570
  description: "Show OpenSpec-compatible SDD status and effective spec source",
67572
67571
  subcommandOf: "sdd",
67573
67572
  args: "[--json]",
67574
- category: "utility"
67573
+ category: "utility",
67574
+ toolPolicy: "agent"
67575
67575
  },
67576
67576
  "sdd validate": {
67577
67577
  handler: (ctx) => handleSddValidateCommand(ctx.directory, ctx.args),
67578
67578
  description: "Validate OpenSpec-compatible artifacts and effective spec projection",
67579
67579
  subcommandOf: "sdd",
67580
67580
  args: "[--json] [--change <id>]",
67581
- category: "utility"
67581
+ category: "utility",
67582
+ toolPolicy: "agent"
67582
67583
  },
67583
67584
  "sdd project": {
67584
67585
  handler: (ctx) => handleSddProjectCommand(ctx.directory, ctx.args),
67585
67586
  description: "Materialize the OpenSpec-compatible effective spec into .swarm/spec.md",
67586
67587
  subcommandOf: "sdd",
67587
67588
  args: "[--dry-run] [--json] [--change <id>]",
67588
- category: "utility"
67589
+ category: "utility",
67590
+ toolPolicy: "human-only"
67589
67591
  },
67590
67592
  analyze: {
67591
67593
  handler: (ctx) => handleAnalyzeCommand(ctx.directory, ctx.args),
67592
67594
  description: "Analyze spec.md vs plan.md for requirement coverage gaps",
67593
67595
  args: "",
67594
- category: "agent"
67596
+ category: "agent",
67597
+ toolPolicy: "none"
67595
67598
  },
67596
67599
  clarify: {
67597
67600
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handleClarifyCommand),
67598
67601
  description: "Clarify and refine an existing feature specification",
67599
67602
  args: "[description-text]",
67600
- category: "agent"
67603
+ category: "agent",
67604
+ toolPolicy: "none"
67601
67605
  },
67602
67606
  specify: {
67603
67607
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handleSpecifyCommand),
67604
67608
  description: "Generate or import a feature specification [description]",
67605
67609
  args: "[description-text]",
67606
- category: "agent"
67610
+ category: "agent",
67611
+ toolPolicy: "none"
67607
67612
  },
67608
67613
  brainstorm: {
67609
67614
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handleBrainstormCommand),
67610
67615
  description: "Enter architect MODE: BRAINSTORM \u2014 structured seven-phase planning workflow [topic]",
67611
67616
  args: "[topic-text]",
67612
67617
  details: "Triggers the architect to run the brainstorm workflow: CONTEXT SCAN, single-question DIALOGUE, APPROACHES, DESIGN SECTIONS, SPEC WRITE + SELF-REVIEW, QA GATE SELECTION, TRANSITION. Use for new plans where requirements need to be drawn out before writing spec.md / plan.md.",
67613
- category: "agent"
67618
+ category: "agent",
67619
+ toolPolicy: "none"
67614
67620
  },
67615
67621
  council: {
67616
67622
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handleCouncilCommand),
67617
67623
  description: "Enter architect MODE: COUNCIL \u2014 multi-model deliberation [question] [--preset <name>] [--spec-review]",
67618
67624
  args: "<question> [--preset <name>] [--spec-review]",
67619
67625
  details: "Triggers the architect to convene a three-agent General Council: Generalist (reviewer model), Skeptic (critic model), and Domain Expert (SME model). Use --preset <name> to choose a named member preset from council.general.presets. " + "The architect first runs 1\u20133 targeted web searches and passes a compiled RESEARCH CONTEXT " + "to all three agents before dispatching them in parallel. Agents deliberate using the NSED peer-review protocol (Round 1 independent analysis, Round 2 MAINTAIN/CONCEDE/NUANCE for disagreements). The architect synthesizes the final answer directly from convene_general_council output. --spec-review switches to single-pass advisory mode for spec review. Requires council.general.enabled: true and a search API key in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",
67620
- category: "agent"
67626
+ category: "agent",
67627
+ toolPolicy: "none"
67621
67628
  },
67622
67629
  "pr-review": {
67623
67630
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handlePrReviewCommand),
67624
67631
  description: "Launch deep PR review with multi-lane analysis [url] [--council]",
67625
67632
  args: "<pr-url|owner/repo#N|N> [--council]",
67626
67633
  details: "Launches a structured PR review: reconstructs PR intent via obligation extraction cascade, runs 6 parallel explorer lanes through the deterministic dispatch_lanes join barrier (correctness, security, dependencies, docs-intent-vs-actual, tests, performance-architecture), validates findings through independent reviewer confirmation, applies critic challenge to HIGH/CRITICAL findings, synthesizes structured report. --council variant fires adversarial multi-model review. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolves against origin remote).",
67627
- category: "agent"
67634
+ category: "agent",
67635
+ toolPolicy: "none"
67628
67636
  },
67629
67637
  "pr-feedback": {
67630
67638
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handlePrFeedbackCommand),
67631
67639
  description: "Ingest and close known PR feedback (review comments, CI failures, conflicts) [pr] [instructions]",
67632
67640
  args: "[url|owner/repo#N|N] [instructions...]",
67633
67641
  details: "Triggers MODE: PR_FEEDBACK \u2014 ingests existing pull-request feedback (review threads, requested changes, CI/check failures, merge conflicts, stale branch state, pasted notes), verifies every claim against source, clusters related problems, fixes confirmed items, validates the branch, and reports closure status for every ledger item. Distinct from /swarm pr-review, which discovers new findings. The PR reference is optional: with none, the architect builds the ledger from the current PR/branch; text after the reference is forwarded as extra instructions. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",
67634
- category: "agent"
67642
+ category: "agent",
67643
+ toolPolicy: "none"
67635
67644
  },
67636
67645
  "pr subscribe": {
67637
67646
  handler: (ctx) => handlePrSubscribeCommand(ctx.directory, ctx.args, ctx.sessionID),
67638
67647
  description: "Subscribe the current session to PR state-change notifications",
67639
67648
  args: "<pr-url|owner/repo#N|N>",
67640
67649
  details: "Subscribes the current session to receive advisory notifications for the specified PR. When pr_monitor.enabled is true, the background polling worker will detect CI failures, new comments, merge conflicts, review state changes, and merge/close events. Notifications are delivered as session-scoped advisories with dedup tokens. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin). Requires pr_monitor.enabled: true in config.",
67641
- category: "agent"
67650
+ category: "agent",
67651
+ toolPolicy: "human-only"
67642
67652
  },
67643
67653
  "pr unsubscribe": {
67644
67654
  handler: (ctx) => handlePrUnsubscribeCommand(ctx.directory, ctx.args, ctx.sessionID),
67645
67655
  description: "Unsubscribe the current session from PR state-change notifications",
67646
67656
  args: "<pr-url|owner/repo#N|N>",
67647
67657
  details: "Unsubscribes the current session from receiving advisory notifications for the specified PR. Removes the active subscription record. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",
67648
- category: "agent"
67658
+ category: "agent",
67659
+ toolPolicy: "human-only"
67649
67660
  },
67650
67661
  "pr status": {
67651
67662
  handler: (ctx) => handlePrMonitorStatusCommand(ctx.directory, ctx.args, ctx.sessionID),
67652
67663
  description: "Show PR monitor subscription status for the current session",
67653
67664
  args: "",
67654
67665
  details: "Displays all active PR subscriptions for the current session. Shows PR URL, last checked time, watching status, and error count per subscription. Also shows total active subscriptions across all sessions.",
67655
- category: "agent"
67666
+ category: "agent",
67667
+ toolPolicy: "agent",
67668
+ toolNoArgs: true
67656
67669
  },
67657
67670
  "deep-dive": {
67658
67671
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handleDeepDiveCommand),
67659
67672
  description: "Launch deep codebase audit with parallel explorer waves, dual reviewers, and critic challenge [scope]",
67660
67673
  args: "<scope> [--profile standard|security|ux|architecture|full] [--max-explorers 1..8] [--json] [--skip-update] [--allow-dirty]",
67661
67674
  details: "Runs a read-only deep audit of the specified scope using parallel explorer waves (8-file cap per mission, ~3500 line guardrail), always 2 parallel reviewers for verification, and sequential critic challenge on HIGH/CRITICAL findings. Profiles select explorer lanes: standard (5 lanes), security, ux, architecture, full (all 8 lanes). Emits a structured findings report without mutating source code.",
67662
- category: "agent"
67675
+ category: "agent",
67676
+ toolPolicy: "none"
67663
67677
  },
67664
67678
  "deep dive": {
67665
67679
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handleDeepDiveCommand),
@@ -67673,7 +67687,8 @@ Subcommands:
67673
67687
  description: "Launch a multi-source, fact-checked deep research pass and synthesize a cited report [question]",
67674
67688
  args: "<question> [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]",
67675
67689
  details: "Runs the orchestrator-worker deep-research protocol: the architect decomposes the question into subtopics, gathers evidence with web_search and web_fetch across up to N iterative rounds, dispatches parallel sme synthesis workers, verifies every claim against cited sources with dual reviewers, challenges high-stakes claims with the critic, and presents a cited report in chat. Read-only \u2014 does not mutate source code, delegate to coder, or call declare_scope. Requires council.general.enabled and a search API key.",
67676
- category: "agent"
67690
+ category: "agent",
67691
+ toolPolicy: "none"
67677
67692
  },
67678
67693
  "deep research": {
67679
67694
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handleDeepResearchCommand),
@@ -67687,7 +67702,8 @@ Subcommands:
67687
67702
  description: "Launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit",
67688
67703
  args: "[scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]",
67689
67704
  details: "Runs the codebase-review-swarm workflow: Phase 0 inventory, selected-track depth planning, non-diluting review passes, coverage closure, reviewer validation, critic challenge, and .swarm/review-v8 artifacts. Materializes the bundled skill package if missing, then emits a MODE signal; the architect workflow must not mutate source files.",
67690
- category: "agent"
67705
+ category: "agent",
67706
+ toolPolicy: "none"
67691
67707
  },
67692
67708
  "codebase review": {
67693
67709
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handleCodebaseReviewCommand),
@@ -67701,7 +67717,8 @@ Subcommands:
67701
67717
  description: "Generate or sync language-agnostic design docs (domain, technical-spec, behavior-spec, reference/) for the project under build [description]",
67702
67718
  args: "<description> [--out <dir>] [--lang <name>] [--update]",
67703
67719
  details: "Triggers the architect to enter MODE: DESIGN_DOCS \u2014 delegates to the docs_design agent to author/sync docs/domain.md, docs/technical-spec.md, docs/behavior-spec.md, and docs/reference/* (plus reference/traceability.json and design-changelog.md). Normative docs are 100% language-agnostic; all framework-specific material is quarantined under reference/. --update syncs existing docs to current code/spec instead of generating fresh. Requires design_docs.enabled: true.",
67704
- category: "agent"
67720
+ category: "agent",
67721
+ toolPolicy: "none"
67705
67722
  },
67706
67723
  "design docs": {
67707
67724
  handler: (ctx) => handleModeCommandWithBundledSkills(ctx, handleDesignDocsCommand),
@@ -67715,21 +67732,24 @@ Subcommands:
67715
67732
  description: "Ingest a GitHub issue into the swarm workflow [url] [--plan] [--trace] [--no-repro]",
67716
67733
  args: "<issue-url|owner/repo#N|N> [--plan] [--trace] [--no-repro]",
67717
67734
  details: "Triggers the architect to enter MODE: ISSUE_INGEST \u2014 ingests a GitHub issue, restructures it into a normalized intake note, localizes root cause through hypothesis-driven tracing, and outputs a resolution spec. --plan transitions to plan creation after spec generation. --trace runs the full fix-and-PR workflow (implies --plan). --no-repro skips the reproduction step. Supports full GitHub URL, owner/repo#N shorthand, or bare issue number (resolves against origin remote).",
67718
- category: "agent"
67735
+ category: "agent",
67736
+ toolPolicy: "none"
67719
67737
  },
67720
67738
  "qa-gates": {
67721
67739
  handler: (ctx) => handleQaGatesCommand(ctx.directory, ctx.args, ctx.sessionID),
67722
67740
  description: "View or modify QA gate profile for the current plan [enable|override <gate>...]",
67723
67741
  args: "[show|enable|override] <gate>...",
67724
67742
  details: "show: display spec-level, session-override, and effective QA gates for the current plan. enable: persist gate(s) into the locked-once profile (architect; rejected after critic approval lock). override: session-only ratchet-tighter enable. Valid gates: reviewer, test_engineer, council_mode, sme_enabled, critic_pre_plan, hallucination_guard, sast_enabled, mutation_test, phase_council, drift_check, final_council.",
67725
- category: "config"
67743
+ category: "config",
67744
+ toolPolicy: "none"
67726
67745
  },
67727
67746
  promote: {
67728
67747
  handler: (ctx) => handlePromoteCommand(ctx.directory, ctx.args),
67729
67748
  description: "Manually promote lesson to hive knowledge",
67730
67749
  details: "Promotes a lesson directly to hive knowledge (--category flag sets category) or references an existing swarm lesson by ID (--from-swarm). Validates lesson text before promotion. Either direct text or --from-swarm ID is required.",
67731
67750
  args: "--category <category>, --from-swarm <lesson-id>, <lesson-text>",
67732
- category: "utility"
67751
+ category: "utility",
67752
+ toolPolicy: "none"
67733
67753
  },
67734
67754
  reset: {
67735
67755
  handler: (ctx) => handleResetCommand(ctx.directory, ctx.args),
@@ -67737,35 +67757,40 @@ Subcommands:
67737
67757
  details: "DELETES plan.md, context.md, and summaries/ directory from .swarm/. Stops background automation and clears in-memory queues. SAFETY: requires --confirm flag \u2014 without it, displays a warning and tips to export first.",
67738
67758
  args: "--confirm (required)",
67739
67759
  category: "utility",
67740
- clashesWithNativeCcCommand: "/reset"
67760
+ clashesWithNativeCcCommand: "/reset",
67761
+ toolPolicy: "restricted"
67741
67762
  },
67742
67763
  "reset-session": {
67743
67764
  handler: (ctx) => handleResetSessionCommand(ctx.directory, ctx.args),
67744
67765
  description: "Clear session state while preserving plan, evidence, and knowledge",
67745
67766
  details: "Deletes only .swarm/session/state.json and any other session files. Clears in-memory agent sessions and delegation chains. Preserves plan, evidence, and knowledge for cross-session continuity.",
67746
67767
  args: "",
67747
- category: "utility"
67768
+ category: "utility",
67769
+ toolPolicy: "restricted"
67748
67770
  },
67749
67771
  rollback: {
67750
67772
  handler: (ctx) => handleRollbackCommand(ctx.directory, ctx.args),
67751
67773
  description: "Restore swarm state to a checkpoint <phase>",
67752
67774
  details: "Restores .swarm/ state by directly overwriting files from a checkpoint directory (checkpoints/phase-<N>). Writes rollback event to events.jsonl. Without phase argument, lists available checkpoints. Partial failures are reported but processing continues.",
67753
67775
  args: "<phase-number>",
67754
- category: "utility"
67776
+ category: "utility",
67777
+ toolPolicy: "restricted"
67755
67778
  },
67756
67779
  retrieve: {
67757
67780
  handler: (ctx) => handleRetrieveCommand(ctx.directory, ctx.args),
67758
67781
  description: "Retrieve full output from a summary <id>",
67759
67782
  args: "<summary-id>",
67760
67783
  details: "Loads the full tool output that was previously summarized (referenced by IDs like S1, S2). Use when you need the complete output instead of the truncated summary.",
67761
- category: "utility"
67784
+ category: "utility",
67785
+ toolPolicy: "agent"
67762
67786
  },
67763
67787
  handoff: {
67764
67788
  handler: (ctx) => handleHandoffCommand(ctx.directory, ctx.args),
67765
67789
  description: "Prepare state for clean model switch (new session)",
67766
67790
  args: "",
67767
67791
  details: "Generates handoff.md with full session state snapshot, including plan progress, recent decisions, and agent delegation history. Prepended to the next session prompt for seamless model switches.",
67768
- category: "core"
67792
+ category: "core",
67793
+ toolPolicy: "none"
67769
67794
  },
67770
67795
  turbo: {
67771
67796
  handler: (ctx) => handleTurboCommand(ctx.directory, ctx.args, ctx.sessionID),
@@ -67787,28 +67812,32 @@ Subcommands:
67787
67812
  ` + ` turbo status \u2014 show detailed status including active strategy and lanes
67788
67813
  ` + `
67789
67814
  ` + "Session-scoped \u2014 resets on new session.",
67790
- category: "utility"
67815
+ category: "utility",
67816
+ toolPolicy: "none"
67791
67817
  },
67792
67818
  "full-auto": {
67793
67819
  handler: (ctx) => handleFullAutoCommand(ctx.directory, ctx.args, ctx.sessionID),
67794
67820
  description: "Toggle Full-Auto Mode for the active session [on [mode]|off|status]",
67795
67821
  args: "on [assisted|supervised|strict], off, status",
67796
67822
  details: 'First-class toggle for Full-Auto Mode \u2014 autonomous execution with the critic reviewing escalations on your behalf. No config-level enablement is required: "on" activates immediately (unless full_auto.locked is true in config), "off" disarms the run and returns the session to normal interactive operation, "status" reports the durable run state. ' + 'An optional mode after "on" overrides full_auto.mode for this run: assisted (critic consulted only on policy escalations), supervised (default \u2014 risky/high-impact actions reviewed by the critic), strict (ALL plan mutations reviewed by the critic). ' + "While active, the critic answers architect questions and reviews phase boundaries, delegations, and risky actions on your behalf; only ESCALATE_TO_HUMAN verdicts halt the run for your input. The run state is durable (.swarm/full-auto-state.json) and survives restarts; toggle with no argument flips the current state.",
67797
- category: "utility"
67823
+ category: "utility",
67824
+ toolPolicy: "none"
67798
67825
  },
67799
67826
  "auto-proceed": {
67800
67827
  handler: (ctx) => handleAutoProceedCommand(ctx.directory, ctx.args, ctx.sessionID),
67801
67828
  description: "Toggle or set auto-proceed override for the active session",
67802
67829
  args: "[on|off]",
67803
67830
  category: "config",
67804
- details: 'Without argument, toggles auto-proceed mode. With "on" or "off", sets the state explicitly.'
67831
+ details: 'Without argument, toggles auto-proceed mode. With "on" or "off", sets the state explicitly.',
67832
+ toolPolicy: "agent"
67805
67833
  },
67806
67834
  "write-retro": {
67807
67835
  handler: (ctx) => handleWriteRetroCommand(ctx.directory, ctx.args),
67808
67836
  description: "Write a retrospective evidence bundle for a completed phase <json>",
67809
67837
  details: "Writes retrospective evidence bundle to .swarm/evidence/retro-{phase}/evidence.json. Required JSON: phase, summary, task_count, task_complexity, total_tool_calls, coder_revisions, reviewer_rejections, test_failures, security_findings, integration_issues. Optional: lessons_learned (max 5), top_rejection_reasons, task_id, metadata.",
67810
67838
  args: "<json: {phase, summary, task_count, task_complexity, ...}>",
67811
- category: "utility"
67839
+ category: "utility",
67840
+ toolPolicy: "none"
67812
67841
  },
67813
67842
  "knowledge migrate": {
67814
67843
  handler: (ctx) => handleKnowledgeMigrateCommand(ctx.directory, ctx.args),
@@ -67852,75 +67881,89 @@ Subcommands:
67852
67881
  knowledge: {
67853
67882
  handler: (ctx) => handleKnowledgeListCommand(ctx.directory, ctx.args),
67854
67883
  description: "List knowledge entries",
67855
- category: "utility"
67884
+ category: "utility",
67885
+ toolPolicy: "agent"
67856
67886
  },
67857
67887
  memory: {
67858
67888
  handler: (ctx) => handleMemoryCommand(ctx.directory, ctx.args),
67859
67889
  description: "Show Swarm memory commands",
67860
- category: "utility"
67890
+ category: "utility",
67891
+ toolPolicy: "agent",
67892
+ toolNoArgs: true
67861
67893
  },
67862
67894
  "memory status": {
67863
67895
  handler: (ctx) => handleMemoryStatusCommand(ctx.directory, ctx.args),
67864
67896
  description: "Show Swarm memory provider, JSONL, and migration status",
67865
67897
  subcommandOf: "memory",
67866
67898
  args: "",
67867
- category: "diagnostics"
67899
+ category: "diagnostics",
67900
+ toolPolicy: "agent",
67901
+ toolNoArgs: true
67868
67902
  },
67869
67903
  "memory pending": {
67870
67904
  handler: (ctx) => handleMemoryPendingCommand(ctx.directory, ctx.args),
67871
67905
  description: "Show pending Swarm memory proposals and rejection reasons",
67872
67906
  subcommandOf: "memory",
67873
67907
  args: "--limit <n>",
67874
- category: "diagnostics"
67908
+ category: "diagnostics",
67909
+ toolPolicy: "agent"
67875
67910
  },
67876
67911
  "memory recall-log": {
67877
67912
  handler: (ctx) => handleMemoryRecallLogCommand(ctx.directory, ctx.args),
67878
67913
  description: "Summarize Swarm memory recall usage",
67879
67914
  subcommandOf: "memory",
67880
67915
  args: "--limit <n>",
67881
- category: "diagnostics"
67916
+ category: "diagnostics",
67917
+ toolPolicy: "agent"
67882
67918
  },
67883
67919
  "memory compact": {
67884
67920
  handler: (ctx) => handleMemoryCompactCommand(ctx.directory, ctx.args),
67885
67921
  description: "Compact deleted, superseded, and expired scratch memories",
67886
67922
  subcommandOf: "memory",
67887
67923
  args: "--confirm",
67888
- category: "utility"
67924
+ category: "utility",
67925
+ toolPolicy: "human-only"
67889
67926
  },
67890
67927
  "memory stale": {
67891
67928
  handler: (ctx) => handleMemoryStaleCommand(ctx.directory, ctx.args),
67892
67929
  description: "List stale and low-utility Swarm memories",
67893
67930
  subcommandOf: "memory",
67894
67931
  args: "--limit <n>",
67895
- category: "diagnostics"
67932
+ category: "diagnostics",
67933
+ toolPolicy: "agent"
67896
67934
  },
67897
67935
  "memory export": {
67898
67936
  handler: (ctx) => handleMemoryExportCommand(ctx.directory, ctx.args),
67899
67937
  description: "Export current Swarm memory to JSONL files",
67900
67938
  subcommandOf: "memory",
67901
67939
  args: "",
67902
- category: "utility"
67940
+ category: "utility",
67941
+ toolPolicy: "agent",
67942
+ toolNoArgs: true
67903
67943
  },
67904
67944
  "memory evaluate": {
67905
67945
  handler: (ctx) => handleMemoryEvaluateCommand(ctx.directory, ctx.args),
67906
67946
  description: "Run golden Swarm memory recall evaluation fixtures",
67907
67947
  subcommandOf: "memory",
67908
67948
  args: "--json, --fixtures <directory>",
67909
- category: "diagnostics"
67949
+ category: "diagnostics",
67950
+ toolPolicy: "agent"
67910
67951
  },
67911
67952
  "memory import": {
67912
67953
  handler: (ctx) => handleMemoryImportCommand(ctx.directory, ctx.args),
67913
67954
  description: "Import legacy JSONL memory into SQLite",
67914
67955
  subcommandOf: "memory",
67915
67956
  args: "",
67916
- category: "utility"
67957
+ category: "utility",
67958
+ toolPolicy: "human-only"
67917
67959
  },
67918
67960
  "memory migrate": {
67919
67961
  handler: (ctx) => handleMemoryMigrateCommand(ctx.directory, ctx.args),
67920
67962
  description: "Run the one-time legacy JSONL to SQLite migration",
67921
67963
  subcommandOf: "memory",
67922
67964
  args: "",
67923
- category: "utility"
67965
+ category: "utility",
67966
+ toolPolicy: "human-only"
67924
67967
  },
67925
67968
  checkpoint: {
67926
67969
  handler: (ctx) => handleCheckpointCommand(ctx.directory, ctx.args),
@@ -67928,19 +67971,21 @@ Subcommands:
67928
67971
  details: "save: creates named snapshot of current .swarm/ state. restore: soft-resets to checkpoint by overwriting current .swarm/ files. delete: removes named checkpoint. list: shows all checkpoints with timestamps. All subcommands require a label except list.",
67929
67972
  args: "<save|restore|delete|list> <label>",
67930
67973
  category: "utility",
67931
- clashesWithNativeCcCommand: "/checkpoint"
67974
+ clashesWithNativeCcCommand: "/checkpoint",
67975
+ toolPolicy: "restricted"
67932
67976
  }
67933
67977
  };
67934
67978
  VALID_COMMANDS = Object.keys(COMMAND_REGISTRY);
67935
- _internals45 = {
67979
+ _internals11 = {
67936
67980
  handleHelpCommand,
67937
67981
  validateAliases,
67982
+ validateToolPolicy,
67938
67983
  resolveCommand,
67939
67984
  levenshteinDistance: levenshteinDistance2,
67940
67985
  findSimilarCommands,
67941
67986
  buildDetailedHelp
67942
67987
  };
67943
- validation = _internals45.validateAliases();
67988
+ validation = _internals11.validateAliases();
67944
67989
  if (!validation.valid) {
67945
67990
  throw new Error(`COMMAND_REGISTRY alias validation failed:
67946
67991
  ${validation.errors.join(`
@@ -67951,6 +67996,16 @@ ${validation.errors.join(`
67951
67996
  ${validation.warnings.join(`
67952
67997
  `)}`);
67953
67998
  }
67999
+ try {
68000
+ const toolPolicyValidation = _internals11.validateToolPolicy();
68001
+ if (toolPolicyValidation.warnings.length > 0) {
68002
+ console.warn(`COMMAND_REGISTRY toolPolicy warnings:
68003
+ ${toolPolicyValidation.warnings.join(`
68004
+ `)}`);
68005
+ }
68006
+ } catch (e) {
68007
+ console.warn(`COMMAND_REGISTRY toolPolicy validation failed (non-fatal): ${e.message}`);
68008
+ }
67954
68009
  });
67955
68010
 
67956
68011
  // src/cli/index.ts