buddy-agent-harness 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/.cursor-plugin/plugin.json +1 -1
  4. package/bin/buddy-agent-harness.mjs +1 -3
  5. package/dist/cli.mjs +15755 -3090
  6. package/dist/index.d.mts +219 -78
  7. package/dist/index.d.mts.map +1 -1
  8. package/dist/index.mjs +2209 -203
  9. package/dist/index.mjs.map +1 -1
  10. package/dist/skill-scripts/doctor.mjs +247 -77
  11. package/dist/skill-scripts/init.mjs +247 -77
  12. package/dist/skill-scripts/mcp.mjs +473 -0
  13. package/dist/skill-scripts/reference.mjs +473 -0
  14. package/package.json +7 -3
  15. package/plugin.json +1 -1
  16. package/skills/doctor-buddy-agent-harness/SKILL.md +1 -1
  17. package/skills/doctor-buddy-agent-harness/references/harnesses/codex.md +1 -1
  18. package/skills/doctor-buddy-agent-harness/references/mcp.md +5 -5
  19. package/skills/doctor-buddy-agent-harness/scripts/doctor.mjs +247 -77
  20. package/skills/enhance/SKILL.md +61 -18
  21. package/skills/enhance/references/delegation.history.md +10 -0
  22. package/skills/enhance/references/delegation.md +13 -55
  23. package/skills/enhance/references/list-identifiers.history.md +9 -0
  24. package/skills/enhance/references/list-identifiers.md +67 -0
  25. package/skills/init-buddy-agent-harness/SKILL.md +3 -3
  26. package/skills/init-buddy-agent-harness/scripts/doctor.mjs +247 -77
  27. package/skills/init-buddy-agent-harness/scripts/init.mjs +247 -77
  28. package/skills/load-reference/README.md +33 -0
  29. package/skills/load-reference/SKILL.md +64 -0
  30. package/skills/load-reference/scripts/reference.mjs +473 -0
  31. package/skills/repair/SKILL.md +3 -3
  32. package/skills/repair/references/classes.md +51 -2
  33. package/skills/repair/scripts/doctor.mjs +247 -77
  34. package/skills/repair/scripts/mcp.mjs +473 -0
  35. package/src/cli.ts +4 -3
  36. package/src/config-edit/config-edit.ts +11 -0
  37. package/src/config-edit/jsonc-edit.ts +54 -0
  38. package/src/config-edit/toml-edit.ts +155 -0
  39. package/src/diagnose-bridges/doctor-guidance.ts +20 -12
  40. package/src/diagnose-bridges/doctor.command.ts +27 -29
  41. package/src/diagnose-mcp/diagnose-mcp.ts +4 -17
  42. package/src/diagnose-mcp/mcp-baseline.ts +8 -1
  43. package/src/diagnose-mcp/mcp-model.ts +52 -1
  44. package/src/diagnose-mcp/mcp-sources.ts +24 -50
  45. package/src/governance-overrides/governance-overrides.ts +1 -11
  46. package/src/governance-overrides/governance.command.ts +7 -1
  47. package/src/harness-registry/harness-registry.ts +41 -11
  48. package/src/harness-registry/mcp-config.ts +6 -1
  49. package/src/index.ts +21 -1
  50. package/src/initialize-harnesses/init.command.ts +2 -1
  51. package/src/initialize-harnesses/initialize-harnesses.ts +10 -6
  52. package/src/mcp-dialects/mcp-dialects.ts +277 -0
  53. package/src/mcp-inventory/mcp-inventory.ts +16 -7
  54. package/src/project-mcp/mcp-edit.ts +44 -0
  55. package/src/project-mcp/mcp.command.ts +83 -0
  56. package/src/project-mcp/project-mcp.ts +220 -0
  57. package/src/reconcile-mcp/reconcile-mcp.ts +343 -0
  58. package/src/reconcile-mcp/reconcile.command.ts +80 -0
  59. package/src/references/harness-layers.ts +150 -0
  60. package/src/references/load-reference-invocation.ts +25 -0
  61. package/src/references/reference-catalog.ts +130 -0
  62. package/src/references/reference-document.ts +220 -0
  63. package/src/references/reference-layers.ts +171 -0
  64. package/src/references/reference.command.ts +251 -0
  65. package/src/references/resolve-reference.ts +257 -0
  66. package/src/skill-scripts/doctor.ts +2 -4
  67. package/src/skill-scripts/init.ts +2 -4
  68. package/src/skill-scripts/launchers.ts +2 -0
  69. package/src/skill-scripts/mcp.ts +7 -0
  70. package/src/skill-scripts/reference.ts +7 -0
package/dist/index.mjs CHANGED
@@ -2,11 +2,15 @@ import { createRequire } from "node:module";
2
2
  import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
3
3
  import { cli, command, exitCodes, z } from "clibuilder";
4
4
  import { homedir, platform } from "node:os";
5
- import { basename, dirname, join, posix, relative, resolve, sep } from "node:path";
5
+ import { basename, dirname, join, posix, relative, resolve, sep, win32 } from "node:path";
6
6
  import { encode } from "@toon-format/toon";
7
- import { parse } from "smol-toml";
7
+ import { detectHarness, enabledPlugins, installedPlugins, managedPolicyLocations, skillsDirectories } from "@cyberuni/agent-harness";
8
+ import { parse, stringify } from "smol-toml";
9
+ import { parse as parse$1 } from "yaml";
8
10
  import { fileURLToPath } from "node:url";
9
11
  import { execFileSync } from "node:child_process";
12
+ import { parseTOML } from "toml-eslint-parser";
13
+ import { findNodeAtLocation, parseTree } from "jsonc-parser";
10
14
  //#region src/is-record/is-record.ts
11
15
  function isRecord(value) {
12
16
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -140,7 +144,7 @@ function serializeCatalog(catalog) {
140
144
  }
141
145
  //#endregion
142
146
  //#region src/dep-plugins/resolve.ts
143
- function readJson$1(path) {
147
+ function readJson$2(path) {
144
148
  try {
145
149
  return JSON.parse(readFileSync(path, "utf8"));
146
150
  } catch {
@@ -178,7 +182,7 @@ function readDepPlugin(pkg, fromManifest) {
178
182
  package: pkg,
179
183
  reason: "unresolved"
180
184
  };
181
- const manifest = readJson$1(join(dir, "plugin.json"));
185
+ const manifest = readJson$2(join(dir, "plugin.json"));
182
186
  if (!manifest || typeof manifest !== "object") return {
183
187
  ok: false,
184
188
  package: pkg,
@@ -191,7 +195,7 @@ function readDepPlugin(pkg, fromManifest) {
191
195
  package: pkg,
192
196
  reason: "unnamed"
193
197
  };
194
- const installed = readJson$1(join(dir, "package.json"));
198
+ const installed = readJson$2(join(dir, "package.json"));
195
199
  const version = typeof installed?.version === "string" ? installed.version : void 0;
196
200
  if (!version) return {
197
201
  ok: false,
@@ -284,7 +288,7 @@ function writeCatalog(root, catalog) {
284
288
  //#endregion
285
289
  //#region src/dep-plugins/harness-plugins.ts
286
290
  const COPILOT_LIMITATION = "Copilot CLI rejects an npm marketplace source, so it cannot install from this catalog. It needs a path-sourced catalog, which cannot reach node_modules from a subdirectory.";
287
- function readJson(path) {
291
+ function readJson$1(path) {
288
292
  try {
289
293
  return JSON.parse(readFileSync(path, "utf8"));
290
294
  } catch {
@@ -302,7 +306,7 @@ function claudeConfigDir(home, env = process.env) {
302
306
  return env["CLAUDE_CONFIG_DIR"] || join(home, ".claude");
303
307
  }
304
308
  function readClaudeState(configDir) {
305
- const installedFile = readJson(join(configDir, "plugins", "installed_plugins.json"));
309
+ const installedFile = readJson$1(join(configDir, "plugins", "installed_plugins.json"));
306
310
  const installed = [];
307
311
  for (const [id, entries] of Object.entries(installedFile?.plugins ?? {})) {
308
312
  if (!Array.isArray(entries)) continue;
@@ -325,7 +329,7 @@ function readClaudeState(configDir) {
325
329
  });
326
330
  }
327
331
  }
328
- const knownFile = readJson(join(configDir, "plugins", "known_marketplaces.json"));
332
+ const knownFile = readJson$1(join(configDir, "plugins", "known_marketplaces.json"));
329
333
  const marketplaces = [];
330
334
  for (const [name, value] of Object.entries(knownFile ?? {})) marketplaces.push({
331
335
  name,
@@ -336,7 +340,7 @@ function readClaudeState(configDir) {
336
340
  marketplaces
337
341
  };
338
342
  }
339
- const claudeCode = {
343
+ const claudeCode$1 = {
340
344
  name: "claude-code",
341
345
  scoped: true,
342
346
  installedOnMachine: (home, env = process.env) => existsSync(claudeConfigDir(home, env)),
@@ -388,7 +392,7 @@ function readCodexState(home) {
388
392
  marketplaces
389
393
  };
390
394
  }
391
- const runtimes = [claudeCode, {
395
+ const runtimes = [claudeCode$1, {
392
396
  name: "codex",
393
397
  scoped: false,
394
398
  installedOnMachine: (home, env = process.env) => existsSync(codexHome(home, env)),
@@ -559,13 +563,26 @@ function filesUnder(directory) {
559
563
  }
560
564
  //#endregion
561
565
  //#region src/harness-registry/harness-registry.ts
562
- /** See `.research/agentic-configuration-standards/` for the per-harness sources. */
566
+ /**
567
+ * Throws on a harness `skillsDirectories` does not confirm: treating it as native would silently
568
+ * drop a projection it may need.
569
+ */
570
+ function skillsProjection(harness, scope, directories = skillsDirectories(harness)?.[scope]) {
571
+ const listed = directories ?? [];
572
+ const [first] = listed;
573
+ if (first === void 0) throw new Error(`@cyberuni/agent-harness records no ${scope} skills directories for ${harness}.`);
574
+ return listed.includes(".agents/skills") ? {} : { skillsDirectory: first };
575
+ }
576
+ /**
577
+ * Skills directories come from `@cyberuni/agent-harness`, except for the harnesses it does not know
578
+ * (`devin-desktop`, `windsurf`); see `.research/agentic-configuration-standards/` for the rest.
579
+ */
563
580
  const harnessRegistry = [
564
581
  {
565
582
  name: "claude-code",
566
583
  project: {
567
584
  detect: ".claude",
568
- skillsDirectory: ".claude/skills",
585
+ ...skillsProjection("claude-code", "project"),
569
586
  shadowedBy: [
570
587
  "CLAUDE.md",
571
588
  ".claude/CLAUDE.md",
@@ -574,7 +591,8 @@ const harnessRegistry = [
574
591
  mcpConfig: {
575
592
  path: ".mcp.json",
576
593
  key: "mcpServers",
577
- format: "json"
594
+ format: "json",
595
+ dialect: "claude-code"
578
596
  },
579
597
  nonstandard: [
580
598
  {
@@ -596,17 +614,19 @@ const harnessRegistry = [
596
614
  },
597
615
  user: {
598
616
  detect: ".claude",
599
- skillsDirectory: ".claude/skills"
617
+ ...skillsProjection("claude-code", "user")
600
618
  }
601
619
  },
602
620
  {
603
621
  name: "cursor",
604
622
  project: {
605
623
  detect: ".cursor",
624
+ ...skillsProjection("cursor", "project"),
606
625
  mcpConfig: {
607
626
  path: ".cursor/mcp.json",
608
627
  key: "mcpServers",
609
- format: "json"
628
+ format: "json",
629
+ dialect: "cursor"
610
630
  },
611
631
  nonstandard: [
612
632
  {
@@ -631,16 +651,22 @@ const harnessRegistry = [
631
651
  }
632
652
  ]
633
653
  },
634
- user: { detect: ".cursor" }
654
+ user: {
655
+ detect: ".cursor",
656
+ ...skillsProjection("cursor", "user")
657
+ }
635
658
  },
636
659
  {
637
660
  name: "codex",
638
661
  project: {
639
662
  detect: ".codex",
663
+ ...skillsProjection("codex", "project"),
640
664
  mcpConfig: {
641
665
  path: ".codex/config.toml",
642
666
  key: "mcp_servers",
643
- format: "toml"
667
+ format: "toml",
668
+ dialect: "codex",
669
+ shared: true
644
670
  },
645
671
  nonstandard: [{
646
672
  path: ".codex/skills",
@@ -648,12 +674,16 @@ const harnessRegistry = [
648
674
  kind: "skill"
649
675
  }]
650
676
  },
651
- user: { detect: ".codex" }
677
+ user: {
678
+ detect: ".codex",
679
+ ...skillsProjection("codex", "user")
680
+ }
652
681
  },
653
682
  {
654
683
  name: "copilot-cli",
655
684
  project: {
656
685
  detect: ".github/skills",
686
+ ...skillsProjection("copilot-cli", "project"),
657
687
  nonstandard: [
658
688
  {
659
689
  path: ".github/copilot-instructions.md",
@@ -672,12 +702,16 @@ const harnessRegistry = [
672
702
  }
673
703
  ]
674
704
  },
675
- user: { detect: ".copilot" }
705
+ user: {
706
+ detect: ".copilot",
707
+ ...skillsProjection("copilot-cli", "user")
708
+ }
676
709
  },
677
710
  {
678
711
  name: "gemini-cli",
679
712
  project: {
680
713
  detect: ".gemini",
714
+ ...skillsProjection("gemini-cli", "project"),
681
715
  instructionBridge: {
682
716
  kind: "settings-entry",
683
717
  path: ".gemini/settings.json",
@@ -687,6 +721,7 @@ const harnessRegistry = [
687
721
  path: ".gemini/settings.json",
688
722
  key: "mcpServers",
689
723
  format: "json",
724
+ dialect: "gemini-cli",
690
725
  shared: true
691
726
  },
692
727
  nonstandard: [{
@@ -699,7 +734,10 @@ const harnessRegistry = [
699
734
  kind: "skill"
700
735
  }]
701
736
  },
702
- user: { detect: ".gemini" }
737
+ user: {
738
+ detect: ".gemini",
739
+ ...skillsProjection("gemini-cli", "user")
740
+ }
703
741
  },
704
742
  {
705
743
  name: "devin-desktop",
@@ -974,33 +1012,33 @@ const mcpTable = {
974
1012
  detail: "the golden set declares this server and the harness config does not carry it",
975
1013
  repair: ({ file, server }) => ({
976
1014
  command: "",
977
- instruction: `add the server ${server} to ${file}, or drop it from the golden set`
1015
+ instruction: `add the server ${server} to ${file}, or drop it from the golden set — \`${repairSkillInvocation}\` offers the correction`
978
1016
  }),
979
- skillRepair: (at) => `add the server at ${locatorText(at)} to that file from its golden entry, or drop it from the golden set`
1017
+ skillRepair: (at) => `hand ${locatorText(at)} to \`${repairSkillInvocation}\`, which projects it from its golden entry with \`mcp project\` — or drop it from the golden set`
980
1018
  },
981
1019
  "mcp-undeclared": {
982
1020
  detail: "the harness config carries this server and the golden set does not declare it",
983
1021
  repair: ({ file, server }) => ({
984
1022
  command: "",
985
- instruction: `add the server ${server} to ${goldenSet}, or drop it from ${file}`
1023
+ instruction: `add the server ${server} to ${goldenSet}, or drop it from ${file} — \`${repairSkillInvocation}\` offers the import`
986
1024
  }),
987
- skillRepair: (at) => `copy the server at ${locatorText(at)} into ${goldenSet}, refusing any literal credential it carries, or drop it from ${at.file}`
1025
+ skillRepair: (at) => `hand ${locatorText(at)} to \`${repairSkillInvocation}\`, which imports it field by field with \`mcp reconcile\`, refusing any literal credential — or drop it from ${at.file}`
988
1026
  },
989
1027
  "mcp-diverged-target": {
990
1028
  detail: "only the harness config changed since the two last agreed — the edit was made through the copy",
991
1029
  repair: (at) => ({
992
1030
  command: "",
993
- instruction: `reconcile the value at ${locatorText(at)} back into ${goldenSet}`
1031
+ instruction: `reconcile the value at ${locatorText(at)} back into ${goldenSet} — \`${repairSkillInvocation}\` offers the import`
994
1032
  }),
995
- skillRepair: (at) => `reconcile the value at ${locatorText(at)} back into ${goldenSet}, field by field`
1033
+ skillRepair: (at) => `hand ${locatorText(at)} to \`${repairSkillInvocation}\`, which imports the field into ${goldenSet} with \`mcp reconcile\` once approved`
996
1034
  },
997
1035
  "mcp-diverged-golden": {
998
1036
  detail: "only the golden set changed since the two last agreed — the harness copy is stale",
999
1037
  repair: (at) => ({
1000
1038
  command: "",
1001
- instruction: `update ${locatorText(at)} from the golden entry`
1039
+ instruction: `update ${locatorText(at)} from the golden entry — \`${repairSkillInvocation}\` offers the correction`
1002
1040
  }),
1003
- skillRepair: (at) => `update ${locatorText(at)} from the golden entry`
1041
+ skillRepair: (at) => `hand ${locatorText(at)} to \`${repairSkillInvocation}\`, which updates it from the golden entry with \`mcp project\``
1004
1042
  },
1005
1043
  "mcp-diverged-both": {
1006
1044
  detail: "both sides changed since they last agreed — merging either way would discard the other",
@@ -1225,52 +1263,6 @@ function diagnoseConfiguration({ root, git, cli }) {
1225
1263
  return findings;
1226
1264
  }
1227
1265
  //#endregion
1228
- //#region src/diagnose-bridges/json-with-comments.ts
1229
- function stripJsonComments(source) {
1230
- let output = "";
1231
- let index = 0;
1232
- let inString = false;
1233
- let escaped = false;
1234
- while (index < source.length) {
1235
- const character = source[index];
1236
- if (inString) {
1237
- output += character;
1238
- if (escaped) escaped = false;
1239
- else if (character === "\\") escaped = true;
1240
- else if (character === "\"") inString = false;
1241
- index += 1;
1242
- continue;
1243
- }
1244
- if (character === "\"") {
1245
- inString = true;
1246
- output += character;
1247
- index += 1;
1248
- continue;
1249
- }
1250
- if (character === "/" && source[index + 1] === "/") {
1251
- while (index < source.length && source[index] !== "\n") index += 1;
1252
- continue;
1253
- }
1254
- if (character === "/" && source[index + 1] === "*") {
1255
- index += 2;
1256
- while (index < source.length && !(source[index] === "*" && source[index + 1] === "/")) index += 1;
1257
- index += 2;
1258
- continue;
1259
- }
1260
- output += character;
1261
- index += 1;
1262
- }
1263
- return output;
1264
- }
1265
- /** The parsed value, or `undefined` when the file is not JSON even once its comments are gone. */
1266
- function parseJsonWithComments(source) {
1267
- try {
1268
- return JSON.parse(stripJsonComments(source));
1269
- } catch {
1270
- return;
1271
- }
1272
- }
1273
- //#endregion
1274
1266
  //#region src/diagnose-mcp/mcp-model.ts
1275
1267
  /** Every field of the model, in the order a finding reports them. */
1276
1268
  const mcpFields = [
@@ -1295,8 +1287,10 @@ function sameValue(field, left, right) {
1295
1287
  }
1296
1288
  return JSON.stringify(left) === JSON.stringify(right);
1297
1289
  }
1298
- function divergingFields(golden, target) {
1290
+ /** Only over `fields`: a golden field the target has no place for is dropped on write, not drift. */
1291
+ function divergingFields(golden, target, fields = new Set(mcpFields)) {
1299
1292
  return mcpFields.filter((field) => {
1293
+ if (!fields.has(field)) return false;
1300
1294
  const declared = golden[field];
1301
1295
  if (declared === void 0) return false;
1302
1296
  if (mapFields.has(field) && isRecord(declared) && isRecord(target[field])) {
@@ -1310,11 +1304,6 @@ function divergingFields(golden, target) {
1310
1304
  function sameField(field, left, right) {
1311
1305
  return sameValue(field, left?.[field], right?.[field]);
1312
1306
  }
1313
- //#endregion
1314
- //#region src/diagnose-mcp/mcp-sources.ts
1315
- /** Where the golden set lives, and why it is namespaced rather than sitting at `.agents/mcp.json`. */
1316
- const goldenSetPath = ".agents/buddy-agent-harness/mcp.toml";
1317
- const goldenKey = "servers";
1318
1307
  function stringMap(value) {
1319
1308
  if (!isRecord(value)) return void 0;
1320
1309
  const entries = Object.entries(value).filter(([, item]) => typeof item === "string");
@@ -1359,10 +1348,334 @@ function serverFrom(entry) {
1359
1348
  ...typeof entry["source"] === "string" ? { source: entry["source"] } : {}
1360
1349
  };
1361
1350
  }
1362
- function serversUnder(document, key) {
1351
+ //#endregion
1352
+ //#region src/mcp-dialects/mcp-dialects.ts
1353
+ /** `${NAME}` — the golden set's one reference form, translated per target. */
1354
+ const plainReference = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
1355
+ /** Any reference form a harness might expand, plain or not. */
1356
+ const anyReference = /\$\{[^}]*\}|\$[A-Za-z_]/;
1357
+ var Refusal = class extends Error {
1358
+ field;
1359
+ reason;
1360
+ constructor(field, reason) {
1361
+ super(reason);
1362
+ this.field = field;
1363
+ this.reason = reason;
1364
+ }
1365
+ };
1366
+ function refuse(field, reason) {
1367
+ throw new Refusal(field, reason);
1368
+ }
1369
+ function rendering(render) {
1370
+ try {
1371
+ return {
1372
+ kind: "entry",
1373
+ entry: render()
1374
+ };
1375
+ } catch (error) {
1376
+ if (!(error instanceof Refusal)) throw error;
1377
+ return {
1378
+ kind: "refused",
1379
+ field: error.field,
1380
+ reason: error.reason
1381
+ };
1382
+ }
1383
+ }
1384
+ /** Either a runnable command or an address — a server with neither has nothing to write. */
1385
+ function assertRunnable(server) {
1386
+ if (server.transport === "stdio" ? !server.command : !server.url) refuse(server.transport === "stdio" ? "command" : "url", "the golden set leaves it unset and the target requires it");
1387
+ }
1388
+ function defined(entry) {
1389
+ return Object.fromEntries(Object.entries(entry).filter(([, value]) => value !== void 0));
1390
+ }
1391
+ function mapValues(values, map) {
1392
+ return values && Object.fromEntries(Object.entries(values).map(([key, value]) => [key, map(value)]));
1393
+ }
1394
+ /** The fields that run a server, restricted to a target that expands no reference in them. */
1395
+ function noReferenceIn(server, fields, harness) {
1396
+ for (const field of fields) {
1397
+ const value = server[field];
1398
+ if ((Array.isArray(value) ? value : [value]).some((item) => typeof item === "string" && anyReference.test(item))) refuse(field, `${harness} documents no reference expansion here`);
1399
+ }
1400
+ }
1401
+ const claudeCode = {
1402
+ fields: /* @__PURE__ */ new Set([
1403
+ "transport",
1404
+ "command",
1405
+ "args",
1406
+ "env",
1407
+ "url",
1408
+ "headers",
1409
+ "description",
1410
+ "timeout"
1411
+ ]),
1412
+ read: serverFrom,
1413
+ write: (server) => rendering(() => {
1414
+ assertRunnable(server);
1415
+ return defined({
1416
+ type: server.transport,
1417
+ command: server.command,
1418
+ args: server.args,
1419
+ env: server.env,
1420
+ url: server.url,
1421
+ headers: server.headers,
1422
+ description: server.description,
1423
+ timeout: server.timeout
1424
+ });
1425
+ })
1426
+ };
1427
+ /** Cursor spells a reference `${env:NAME}` and has no default form (E-MCP-13). */
1428
+ function toCursor(value, field) {
1429
+ return value.replace(/\$\{([^}]*)\}|\$[A-Za-z_]/g, (match, name) => {
1430
+ if (name === void 0 || !plainReference.test(match)) refuse(field, "Cursor expands only a plain variable reference, with no default");
1431
+ return `\${env:${name}}`;
1432
+ });
1433
+ }
1434
+ function fromCursor(value) {
1435
+ return value.replace(/\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => `\${${name}}`);
1436
+ }
1437
+ function fromCursorEntry(entry) {
1438
+ const strings = (value) => typeof value === "string" ? fromCursor(value) : value;
1439
+ const map = (value) => isRecord(value) ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, strings(item)])) : value;
1440
+ return {
1441
+ ...entry,
1442
+ command: strings(entry["command"]),
1443
+ args: Array.isArray(entry["args"]) ? entry["args"].map(strings) : entry["args"],
1444
+ env: map(entry["env"]),
1445
+ url: strings(entry["url"]),
1446
+ headers: map(entry["headers"])
1447
+ };
1448
+ }
1449
+ /**
1450
+ * Cursor documents `type: "stdio"` and no field choosing between SSE and streamable HTTP (E-MCP-13),
1451
+ * so a remote server's transport is not a field it holds.
1452
+ */
1453
+ const cursor = {
1454
+ fields: /* @__PURE__ */ new Set([
1455
+ "command",
1456
+ "args",
1457
+ "env",
1458
+ "url",
1459
+ "headers"
1460
+ ]),
1461
+ read: (entry) => serverFrom(fromCursorEntry(entry)),
1462
+ write: (server) => rendering(() => {
1463
+ assertRunnable(server);
1464
+ return defined({
1465
+ type: server.transport === "stdio" ? "stdio" : void 0,
1466
+ command: server.command && toCursor(server.command, "command"),
1467
+ args: server.args?.map((arg) => toCursor(arg, "args")),
1468
+ env: mapValues(server.env, (value) => toCursor(value, "env")),
1469
+ url: server.url && toCursor(server.url, "url"),
1470
+ headers: mapValues(server.headers, (value) => toCursor(value, "headers"))
1471
+ });
1472
+ })
1473
+ };
1474
+ const bearer = /^Bearer \$\{([A-Za-z_][A-Za-z0-9_]*)\}$/;
1475
+ /**
1476
+ * Codex expands no reference in a string and reaches the environment only through named fields
1477
+ * (E-MCP-14): `env_vars` passes a variable through under its own name, `env_http_headers` and
1478
+ * `bearer_token_env_var` fill a header from one.
1479
+ */
1480
+ function codexEnv(env) {
1481
+ const literal = {};
1482
+ const passed = [];
1483
+ for (const [key, value] of Object.entries(env ?? {})) if (plainReference.exec(value)?.[1] === key) passed.push(key);
1484
+ else if (anyReference.test(value)) refuse("env", "Codex passes a variable through only under its own name");
1485
+ else literal[key] = value;
1486
+ return defined({
1487
+ env: Object.keys(literal).length ? literal : void 0,
1488
+ env_vars: passed.length ? passed : void 0
1489
+ });
1490
+ }
1491
+ function codexHeaders(headers) {
1492
+ const literal = {};
1493
+ const fromEnv = {};
1494
+ let token;
1495
+ for (const [key, value] of Object.entries(headers ?? {})) {
1496
+ const name = plainReference.exec(value)?.[1];
1497
+ const bearerName = bearer.exec(value)?.[1];
1498
+ if (bearerName && key === "Authorization") token = bearerName;
1499
+ else if (name) fromEnv[key] = name;
1500
+ else if (anyReference.test(value)) refuse("headers", "Codex fills a header only from a whole variable reference, or Bearer and one");
1501
+ else literal[key] = value;
1502
+ }
1503
+ return defined({
1504
+ http_headers: Object.keys(literal).length ? literal : void 0,
1505
+ env_http_headers: Object.keys(fromEnv).length ? fromEnv : void 0,
1506
+ bearer_token_env_var: token
1507
+ });
1508
+ }
1509
+ function stringRecord(value) {
1510
+ if (!isRecord(value)) return {};
1511
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => typeof item === "string"));
1512
+ }
1513
+ function fromCodex(entry) {
1514
+ const passed = Array.isArray(entry["env_vars"]) ? entry["env_vars"].filter((name) => typeof name === "string") : [];
1515
+ const env = {
1516
+ ...stringRecord(entry["env"]),
1517
+ ...Object.fromEntries(passed.map((name) => [name, `\${${name}}`]))
1518
+ };
1519
+ const token = entry["bearer_token_env_var"];
1520
+ const headers = {
1521
+ ...stringRecord(entry["http_headers"]),
1522
+ ...Object.fromEntries(Object.entries(stringRecord(entry["env_http_headers"])).map(([key, name]) => [key, `\${${name}}`])),
1523
+ ...typeof token === "string" ? { Authorization: `Bearer \${${token}}` } : {}
1524
+ };
1525
+ const seconds = entry["tool_timeout_sec"];
1526
+ return {
1527
+ command: entry["command"],
1528
+ args: entry["args"],
1529
+ env,
1530
+ url: entry["url"],
1531
+ headers,
1532
+ enabled: entry["enabled"],
1533
+ timeout: typeof seconds === "number" ? Math.round(seconds * 1e3) : void 0
1534
+ };
1535
+ }
1536
+ const codex = {
1537
+ fields: /* @__PURE__ */ new Set([
1538
+ "transport",
1539
+ "command",
1540
+ "args",
1541
+ "env",
1542
+ "url",
1543
+ "headers",
1544
+ "enabled",
1545
+ "timeout"
1546
+ ]),
1547
+ defaults: { timeout: 6e4 },
1548
+ read: (entry) => serverFrom(fromCodex(entry)),
1549
+ write: (server) => rendering(() => {
1550
+ if (server.transport === "sse") refuse("transport", "Codex supports no SSE transport");
1551
+ assertRunnable(server);
1552
+ noReferenceIn(server, [
1553
+ "command",
1554
+ "args",
1555
+ "url"
1556
+ ], "Codex");
1557
+ return defined({
1558
+ command: server.command,
1559
+ args: server.args,
1560
+ ...codexEnv(server.env),
1561
+ url: server.url,
1562
+ ...codexHeaders(server.headers),
1563
+ enabled: server.enabled,
1564
+ tool_timeout_sec: server.timeout === void 0 ? void 0 : server.timeout / 1e3
1565
+ });
1566
+ })
1567
+ };
1568
+ /**
1569
+ * Gemini CLI splits the two remote transports into two fields (E-MCP-15), and expands `${NAME}` and
1570
+ * `${NAME:-default}` in every string of its settings file (E-MCP-18), so a reference passes through.
1571
+ */
1572
+ function fromGemini(entry) {
1573
+ const { httpUrl, url, ...rest } = entry;
1574
+ if (typeof httpUrl === "string") return {
1575
+ ...rest,
1576
+ type: "http",
1577
+ url: httpUrl
1578
+ };
1579
+ return typeof url === "string" ? {
1580
+ ...rest,
1581
+ type: "sse",
1582
+ url
1583
+ } : rest;
1584
+ }
1585
+ const mcpDialects = {
1586
+ "claude-code": claudeCode,
1587
+ cursor,
1588
+ codex,
1589
+ "gemini-cli": {
1590
+ fields: /* @__PURE__ */ new Set([
1591
+ "transport",
1592
+ "command",
1593
+ "args",
1594
+ "env",
1595
+ "url",
1596
+ "headers",
1597
+ "timeout"
1598
+ ]),
1599
+ defaults: { timeout: 6e5 },
1600
+ read: (entry) => serverFrom(fromGemini(entry)),
1601
+ write: (server) => rendering(() => {
1602
+ assertRunnable(server);
1603
+ return defined({
1604
+ command: server.command,
1605
+ args: server.args,
1606
+ env: server.env,
1607
+ url: server.transport === "sse" ? server.url : void 0,
1608
+ httpUrl: server.transport === "http" ? server.url : void 0,
1609
+ headers: server.headers,
1610
+ timeout: server.timeout
1611
+ });
1612
+ })
1613
+ }
1614
+ };
1615
+ //#endregion
1616
+ //#region src/diagnose-bridges/json-with-comments.ts
1617
+ function stripJsonComments(source) {
1618
+ let output = "";
1619
+ let index = 0;
1620
+ let inString = false;
1621
+ let escaped = false;
1622
+ while (index < source.length) {
1623
+ const character = source[index];
1624
+ if (inString) {
1625
+ output += character;
1626
+ if (escaped) escaped = false;
1627
+ else if (character === "\\") escaped = true;
1628
+ else if (character === "\"") inString = false;
1629
+ index += 1;
1630
+ continue;
1631
+ }
1632
+ if (character === "\"") {
1633
+ inString = true;
1634
+ output += character;
1635
+ index += 1;
1636
+ continue;
1637
+ }
1638
+ if (character === "/" && source[index + 1] === "/") {
1639
+ while (index < source.length && source[index] !== "\n") index += 1;
1640
+ continue;
1641
+ }
1642
+ if (character === "/" && source[index + 1] === "*") {
1643
+ index += 2;
1644
+ while (index < source.length && !(source[index] === "*" && source[index + 1] === "/")) index += 1;
1645
+ index += 2;
1646
+ continue;
1647
+ }
1648
+ output += character;
1649
+ index += 1;
1650
+ }
1651
+ return output;
1652
+ }
1653
+ /** The parsed value, or `undefined` when the file is not JSON even once its comments are gone. */
1654
+ function parseJsonWithComments(source) {
1655
+ try {
1656
+ return JSON.parse(stripJsonComments(source));
1657
+ } catch {
1658
+ return;
1659
+ }
1660
+ }
1661
+ //#endregion
1662
+ //#region src/diagnose-mcp/mcp-sources.ts
1663
+ /** Where the golden set lives, and why it is namespaced rather than sitting at `.agents/mcp.json`. */
1664
+ const goldenSetPath = ".agents/buddy-agent-harness/mcp.toml";
1665
+ const goldenKey = "servers";
1666
+ /**
1667
+ * The distinct MCP files the enabled harnesses read. No `--harness` preference is accepted: every
1668
+ * harness documenting an MCP file is already selected without one, so a preference could never add
1669
+ * a target.
1670
+ */
1671
+ function mcpTargets(root) {
1672
+ const seen = /* @__PURE__ */ new Set();
1673
+ return selectHarnesses(root, []).map((harness) => harness.project.mcpConfig).filter((config) => config !== void 0).filter((config) => !seen.has(config.path) && seen.add(config.path));
1674
+ }
1675
+ function serversUnder(document, key, read = serverFrom) {
1363
1676
  const table = isRecord(document) ? document[key] : void 0;
1364
1677
  if (!isRecord(table)) return /* @__PURE__ */ new Map();
1365
- return new Map(Object.entries(table).filter(([, entry]) => isRecord(entry)).map(([name, entry]) => [name, serverFrom(entry)]));
1678
+ return new Map(Object.entries(table).filter(([, entry]) => isRecord(entry)).map(([name, entry]) => [name, read(entry)]));
1366
1679
  }
1367
1680
  /**
1368
1681
  * Only line and column — never `message` or `codeblock`, which quote the source line and could echo
@@ -1400,7 +1713,7 @@ function parseTarget(config, source) {
1400
1713
  if (config.format === "toml") try {
1401
1714
  return {
1402
1715
  kind: "servers",
1403
- servers: serversUnder(parse(source), config.key)
1716
+ servers: serversUnder(parse(source), config.key, mcpDialects[config.dialect].read)
1404
1717
  };
1405
1718
  } catch {
1406
1719
  return { kind: "unreadable" };
@@ -1409,7 +1722,7 @@ function parseTarget(config, source) {
1409
1722
  if (document === void 0) return { kind: "unreadable" };
1410
1723
  return {
1411
1724
  kind: "servers",
1412
- servers: serversUnder(document, config.key)
1725
+ servers: serversUnder(document, config.key, mcpDialects[config.dialect].read)
1413
1726
  };
1414
1727
  }
1415
1728
  //#endregion
@@ -1425,6 +1738,11 @@ function parseProjectionRecord(source) {
1425
1738
  if (!isRecord(targets)) return /* @__PURE__ */ new Map();
1426
1739
  return new Map(Object.entries(targets).filter(([, servers]) => isRecord(servers)).map(([path, servers]) => [path, new Map(Object.entries(servers).filter(([, server]) => isRecord(server)).map(([name, server]) => [name, server]))]));
1427
1740
  }
1741
+ /** The record as written back: one object per target, one golden model per server. */
1742
+ function formatProjectionRecord(record) {
1743
+ const targets = Object.fromEntries([...record].map(([path, servers]) => [path, Object.fromEntries(servers)]));
1744
+ return `${JSON.stringify({ targets }, null, 2)}\n`;
1745
+ }
1428
1746
  var McpBaseline = class {
1429
1747
  options;
1430
1748
  constructor(options) {
@@ -1445,6 +1763,7 @@ var McpBaseline = class {
1445
1763
  if (goldenMoved && targetMoved) return "both";
1446
1764
  return targetMoved ? "target" : "golden";
1447
1765
  }
1766
+ /** The server as the two sides last agreed on `field`, or `undefined` when no baseline can say. */
1448
1767
  baseFor(config, name, field) {
1449
1768
  const recorded = this.options.record.get(config.path)?.get(name);
1450
1769
  if (recorded) return recorded;
@@ -1539,14 +1858,14 @@ function urlHoldsCredential(value) {
1539
1858
  for (const [key, parameter] of url.searchParams) if (credentialKey(key) && holdsLiteral(parameter)) return true;
1540
1859
  return false;
1541
1860
  }
1542
- function literalsIn(field, values) {
1861
+ function literalsIn$1(field, values) {
1543
1862
  return Object.entries(values ?? {}).filter(([key, value]) => credentialKey(key) && holdsLiteral(value)).map(([key]) => `${field}.${key}`);
1544
1863
  }
1545
1864
  /** Field paths only — never a truncated value; `sk-ab…` is still a leak into the same transcript. */
1546
1865
  function credentialFields(server) {
1547
1866
  return [
1548
- ...literalsIn("env", server.env),
1549
- ...literalsIn("headers", server.headers),
1867
+ ...literalsIn$1("env", server.env),
1868
+ ...literalsIn$1("headers", server.headers),
1550
1869
  ...server.url && urlHoldsCredential(server.url) ? ["url"] : []
1551
1870
  ];
1552
1871
  }
@@ -1563,19 +1882,10 @@ function nonSecretArgs(args) {
1563
1882
  }
1564
1883
  //#endregion
1565
1884
  //#region src/diagnose-mcp/diagnose-mcp.ts
1566
- function read$1(root, path) {
1885
+ function read$3(root, path) {
1567
1886
  const absolute = join(root, path);
1568
1887
  return existsSync(absolute) ? readFileSync(absolute, "utf8") : void 0;
1569
1888
  }
1570
- /**
1571
- * The distinct MCP files the enabled harnesses read. No `--harness` preference is accepted: every
1572
- * harness documenting an MCP file is already selected without one, so a preference could never add
1573
- * a finding.
1574
- */
1575
- function targetsOf(root) {
1576
- const seen = /* @__PURE__ */ new Set();
1577
- return selectHarnesses(root, []).map((harness) => harness.project.mcpConfig).filter((config) => config !== void 0).filter((config) => !seen.has(config.path) && seen.add(config.path));
1578
- }
1579
1889
  const divergence = {
1580
1890
  target: "mcp-diverged-target",
1581
1891
  golden: "mcp-diverged-golden",
@@ -1603,8 +1913,8 @@ function diagnoseMcp({ root, git, cli }) {
1603
1913
  };
1604
1914
  const targets = /* @__PURE__ */ new Map();
1605
1915
  const configs = [];
1606
- for (const config of targetsOf(root)) {
1607
- const parsed = parseTarget(config, read$1(root, config.path));
1916
+ for (const config of mcpTargets(root)) {
1917
+ const parsed = parseTarget(config, read$3(root, config.path));
1608
1918
  if (parsed.kind === "unreadable") {
1609
1919
  add({ file: config.path }, "mcp-target-unreadable");
1610
1920
  continue;
@@ -1614,7 +1924,7 @@ function diagnoseMcp({ root, git, cli }) {
1614
1924
  targets.set(config.path, parsed.servers);
1615
1925
  configs.push(config);
1616
1926
  }
1617
- const golden = parseGoldenSet(read$1(root, goldenSetPath));
1927
+ const golden = parseGoldenSet(read$3(root, goldenSetPath));
1618
1928
  if (golden.kind === "unreadable") {
1619
1929
  add({
1620
1930
  file: goldenSetPath,
@@ -1626,7 +1936,7 @@ function diagnoseMcp({ root, git, cli }) {
1626
1936
  reportSecrets(goldenSetPath, golden.servers);
1627
1937
  const baseline = new McpBaseline({
1628
1938
  git,
1629
- record: parseProjectionRecord(read$1(root, projectionRecordPath))
1939
+ record: parseProjectionRecord(read$3(root, projectionRecordPath))
1630
1940
  });
1631
1941
  for (const config of configs) {
1632
1942
  const servers = targets.get(config.path);
@@ -1639,7 +1949,7 @@ function diagnoseMcp({ root, git, cli }) {
1639
1949
  }, "mcp-unprojected");
1640
1950
  continue;
1641
1951
  }
1642
- for (const field of divergingFields(declared, carried)) add({
1952
+ for (const field of divergingFields(declared, carried, mcpDialects[config.dialect].fields)) add({
1643
1953
  file: config.path,
1644
1954
  server: name,
1645
1955
  field
@@ -1713,55 +2023,543 @@ function diagnoseNonstandard({ root, cli }) {
1713
2023
  return findings.sort((left, right) => left.path.localeCompare(right.path));
1714
2024
  }
1715
2025
  //#endregion
1716
- //#region src/governance-overrides/governance-overrides.ts
1717
- function managedGovernancesDir(platform, programData) {
1718
- if (platform === "darwin") return "/Library/Application Support/BuddyAgentHarness/governances";
1719
- if (platform === "win32") return join(programData || "C:\\ProgramData", "BuddyAgentHarness", "governances");
1720
- return "/etc/buddy-agent-harness/governances";
2026
+ //#region src/references/reference-document.ts
2027
+ const mergeModes = [
2028
+ "first-wins",
2029
+ "combine",
2030
+ "merge-sections"
2031
+ ];
2032
+ const frontmatterPattern = /^---[ \t]*\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/;
2033
+ /** Frontmatter that is not a YAML mapping is dropped with a warning, never passed off as body text. */
2034
+ function parseDocument(raw, warn) {
2035
+ const match = frontmatterPattern.exec(raw);
2036
+ if (!match) return {
2037
+ metadata: {},
2038
+ body: raw
2039
+ };
2040
+ const body = raw.slice(match[0].length);
2041
+ try {
2042
+ const value = parse$1(match[1]);
2043
+ if (value === null || value === void 0) return {
2044
+ metadata: {},
2045
+ body
2046
+ };
2047
+ if (isRecord(value)) return {
2048
+ metadata: value,
2049
+ body
2050
+ };
2051
+ } catch {}
2052
+ warn("frontmatter is not a YAML mapping; it is ignored");
2053
+ return {
2054
+ metadata: {},
2055
+ body
2056
+ };
2057
+ }
2058
+ function readMergeMode(metadata, warn) {
2059
+ const value = metadata["merge"];
2060
+ if (value === void 0) return "first-wins";
2061
+ if (mergeModes.includes(value)) return value;
2062
+ warn(`unknown merge mode "${String(value)}"; read as first-wins`);
2063
+ return "first-wins";
1721
2064
  }
2065
+ const mergeCommentPattern = /^\s*<!--\s*merge:\s*([\w-]*)\s*-->\s*$/;
2066
+ const headingPattern = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
2067
+ const fenceOpenPattern = /^ {0,3}(`{3,}|~{3,})/;
1722
2068
  /**
1723
- * Still read below the layer above, so a machine already using it keeps working; reported as
1724
- * deprecated so an admin knows to move it.
2069
+ * Tracks fenced code blocks line by line — a `#` or a merge comment inside one is body text, and the
2070
+ * one thing a Markdown-unaware split gets wrong.
1725
2071
  */
1726
- function deprecatedManagedGovernancesDir(platform, programData) {
1727
- if (platform === "darwin") return "/Library/Application Support/UniPlugin/governances";
1728
- if (platform === "win32") return join(programData || "C:\\ProgramData", "UniPlugin", "governances");
1729
- return "/etc/universal-plugin/governances";
2072
+ function fenceTracker() {
2073
+ let fence;
2074
+ return (line) => {
2075
+ if (fence) {
2076
+ if (new RegExp(`^ {0,3}${fence[0] === "`" ? "`" : "~"}{${fence.length},}\\s*$`).test(line)) fence = void 0;
2077
+ return true;
2078
+ }
2079
+ const open = fenceOpenPattern.exec(line);
2080
+ if (open) {
2081
+ fence = open[1];
2082
+ return true;
2083
+ }
2084
+ return false;
2085
+ };
1730
2086
  }
1731
- function projectGovernancesDir(root) {
1732
- return join(root, ".agents", "governances");
2087
+ function stripMergeComments(body) {
2088
+ const inFence = fenceTracker();
2089
+ return body.split("\n").filter((line) => inFence(line) || !mergeCommentPattern.test(line)).join("\n");
1733
2090
  }
1734
- function userGovernancesDir(home) {
1735
- return join(home, ".agents", "governances");
2091
+ function sectionKey(title) {
2092
+ return title.trim().replace(/\s+/g, " ").toLowerCase();
1736
2093
  }
1737
- /**
1738
- * Walks up to the nearest `package.json` rather than a relative literal — this module sits at a
1739
- * different depth in `src/` vs the bundle.
1740
- */
1741
- function packageGovernancesDir(from = fileURLToPath(import.meta.url)) {
1742
- let dir = dirname(from);
1743
- for (;;) {
1744
- if (existsSync(join(dir, "package.json"))) return join(dir, "governances");
1745
- const parent = dirname(dir);
1746
- if (parent === dir) return join(dir, "governances");
1747
- dir = parent;
2094
+ function displayHeading(section) {
2095
+ return `${"#".repeat(section.level)} ${section.title}`;
2096
+ }
2097
+ function parseSections(body, warn) {
2098
+ const tree = {
2099
+ preamble: [],
2100
+ children: []
2101
+ };
2102
+ const stack = [];
2103
+ const inFence = fenceTracker();
2104
+ let awaitingOp;
2105
+ for (const line of body.split("\n")) {
2106
+ const current = stack.at(-1);
2107
+ const fenced = inFence(line);
2108
+ const heading = fenced ? null : headingPattern.exec(line);
2109
+ if (heading) {
2110
+ const level = heading[1].length;
2111
+ const section = {
2112
+ level,
2113
+ title: (heading[2] ?? "").trim(),
2114
+ heading: line.trimEnd(),
2115
+ op: "replace",
2116
+ body: [],
2117
+ children: []
2118
+ };
2119
+ while ((stack.at(-1)?.level ?? 0) >= level) stack.pop();
2120
+ (stack.at(-1)?.children ?? tree.children).push(section);
2121
+ stack.push(section);
2122
+ awaitingOp = section;
2123
+ continue;
2124
+ }
2125
+ if (awaitingOp && !fenced) {
2126
+ if (!line.trim()) continue;
2127
+ const comment = mergeCommentPattern.exec(line);
2128
+ if (comment) {
2129
+ const op = comment[1];
2130
+ if (op === "replace" || op === "combine" || op === "remove") awaitingOp.op = op;
2131
+ else warn(`unknown section merge "${op}" under "${displayHeading(awaitingOp)}"; read as replace`);
2132
+ awaitingOp = void 0;
2133
+ continue;
2134
+ }
2135
+ }
2136
+ awaitingOp = void 0;
2137
+ (current?.body ?? tree.preamble).push(line);
1748
2138
  }
2139
+ return tree;
1749
2140
  }
1750
- function governanceLayers({ root, home, platform, programData }) {
1751
- return [
1752
- {
1753
- scope: "project",
1754
- dir: projectGovernancesDir(root)
1755
- },
1756
- {
1757
- scope: "user",
1758
- dir: userGovernancesDir(home)
1759
- },
1760
- {
1761
- scope: "managed",
1762
- dir: managedGovernancesDir(platform, programData)
1763
- },
1764
- {
2141
+ function trimBlank(lines) {
2142
+ let start = 0;
2143
+ let end = lines.length;
2144
+ while (start < end && !lines[start].trim()) start++;
2145
+ while (end > start && !lines[end - 1].trim()) end--;
2146
+ return lines.slice(start, end);
2147
+ }
2148
+ function warnDuplicates(sections, path, where, warn) {
2149
+ const seen = /* @__PURE__ */ new Set();
2150
+ for (const section of sections) {
2151
+ const key = sectionKey(section.title);
2152
+ if (seen.has(key)) warn(`heading path "${path}${displayHeading(section)}" appears more than once in ${where}; the first is matched`);
2153
+ seen.add(key);
2154
+ }
2155
+ }
2156
+ function warnUnmatched(section, path, where, warn) {
2157
+ warn(`"<!-- merge: ${section.op} -->" on "${path}${displayHeading(section)}" in ${where} matches no section below`);
2158
+ }
2159
+ /** A section placed without merging has nothing below its subsections, so their merge comments match nothing. */
2160
+ function place(section, path, where, warn) {
2161
+ const childPath = `${path}${displayHeading(section)} > `;
2162
+ const children = section.children.flatMap((child) => {
2163
+ if (child.op !== "replace") warnUnmatched(child, childPath, where, warn);
2164
+ return child.op === "remove" ? [] : [place(child, childPath, where, warn)];
2165
+ });
2166
+ return {
2167
+ ...section,
2168
+ children
2169
+ };
2170
+ }
2171
+ function mergeChildren(base, overlay, path, where, warn) {
2172
+ warnDuplicates(base, path, "the layers below", warn);
2173
+ warnDuplicates(overlay, path, where, warn);
2174
+ const slots = [...base];
2175
+ const appended = [];
2176
+ const matched = /* @__PURE__ */ new Set();
2177
+ for (const section of overlay) {
2178
+ const key = sectionKey(section.title);
2179
+ const index = base.findIndex((candidate, i) => !matched.has(i) && sectionKey(candidate.title) === key);
2180
+ if (index === -1) {
2181
+ if (section.op !== "replace") warnUnmatched(section, path, where, warn);
2182
+ if (section.op !== "remove") appended.push(place(section, path, where, warn));
2183
+ continue;
2184
+ }
2185
+ for (let i = 0; i < base.length; i++) if (sectionKey(base[i].title) === key) matched.add(i);
2186
+ const target = base[index];
2187
+ if (section.op === "remove") slots[index] = void 0;
2188
+ else if (section.op === "combine") {
2189
+ const baseBody = trimBlank(target.body);
2190
+ const overlayBody = trimBlank(section.body);
2191
+ slots[index] = {
2192
+ ...target,
2193
+ body: baseBody.length && overlayBody.length ? [
2194
+ ...baseBody,
2195
+ "",
2196
+ ...overlayBody
2197
+ ] : [...baseBody, ...overlayBody],
2198
+ children: mergeChildren(target.children, section.children, `${path}${displayHeading(target)} > `, where, warn)
2199
+ };
2200
+ } else slots[index] = place(section, path, where, warn);
2201
+ }
2202
+ return [...slots.filter((slot) => slot !== void 0), ...appended];
2203
+ }
2204
+ /** `where` names the overlay in warnings, so a person can find the heading it is about. */
2205
+ function mergeSections(base, overlay, where, warn) {
2206
+ const overlayPreamble = trimBlank(overlay.preamble);
2207
+ return {
2208
+ preamble: overlayPreamble.length ? overlayPreamble : base.preamble,
2209
+ children: mergeChildren(base.children, overlay.children, "", where, warn)
2210
+ };
2211
+ }
2212
+ function renderSections(tree) {
2213
+ const blocks = [];
2214
+ const preamble = trimBlank(tree.preamble);
2215
+ if (preamble.length) blocks.push(preamble.join("\n"));
2216
+ const visit = (section) => {
2217
+ const body = trimBlank(section.body);
2218
+ blocks.push(body.length ? `${section.heading}\n\n${body.join("\n")}` : section.heading);
2219
+ for (const child of section.children) visit(child);
2220
+ };
2221
+ for (const section of tree.children) visit(section);
2222
+ return `${blocks.join("\n\n")}\n`;
2223
+ }
2224
+ //#endregion
2225
+ //#region src/references/resolve-reference.ts
2226
+ const namePattern$1 = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/i;
2227
+ const pluginPattern = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i;
2228
+ /**
2229
+ * Rejects rather than sanitizes — silently answering a different question is how untrusted input
2230
+ * reads a file outside the layer. The plugin qualifier is only ever compared with known plugin
2231
+ * names, never joined into a path.
2232
+ */
2233
+ function parseReferenceName(value) {
2234
+ if (value.endsWith(".md")) throw new Error(`"${value}" names a file. Ask for the reference by name, without the .md extension.`);
2235
+ const slash = value.lastIndexOf("/");
2236
+ const name = slash === -1 ? value : value.slice(slash + 1);
2237
+ const plugin = slash === -1 ? void 0 : value.slice(0, slash);
2238
+ if (!namePattern$1.test(name) || plugin !== void 0 && !pluginPattern.test(plugin)) throw new Error(`"${value}" is not a reference name. A name is letters, digits, hyphens, and dots, optionally after "<plugin>/" — not a path.`);
2239
+ return {
2240
+ name,
2241
+ plugin,
2242
+ raw: value
2243
+ };
2244
+ }
2245
+ const folderCandidates = [
2246
+ "README.md",
2247
+ "index.md",
2248
+ "SKILL.md"
2249
+ ];
2250
+ /** Search order within one layer; the first that reads wins. */
2251
+ function candidateFiles(name) {
2252
+ return [`${name}.md`, ...folderCandidates.map((file) => `${name}/${file}`)];
2253
+ }
2254
+ function tryRead(path) {
2255
+ try {
2256
+ return readFileSync(path, "utf8");
2257
+ } catch {
2258
+ return;
2259
+ }
2260
+ }
2261
+ function pluginLabel(layer) {
2262
+ return layer.plugins[0] ?? "";
2263
+ }
2264
+ function layerName(layer) {
2265
+ return layer.tier === "plugin" ? `plugin ${pluginLabel(layer)}` : layer.tier;
2266
+ }
2267
+ function layersFor$2(ref, layers) {
2268
+ const plugin = ref.plugin;
2269
+ if (plugin === void 0) return [...layers];
2270
+ const named = layers.filter((layer) => layer.tier !== "plugin" || layer.plugins.includes(plugin));
2271
+ if (named.some((layer) => layer.tier === "plugin")) return named;
2272
+ return [...named, {
2273
+ tier: "plugin",
2274
+ dir: `(no dependency named ${plugin})`,
2275
+ plugins: [plugin],
2276
+ status: ""
2277
+ }];
2278
+ }
2279
+ function resolveReference(ref, layers, { display = (path) => path } = {}) {
2280
+ const warnings = [];
2281
+ const trace = [];
2282
+ const found = [];
2283
+ for (const layer of layersFor$2(ref, layers)) {
2284
+ const entry = {
2285
+ tier: layer.tier,
2286
+ plugin: pluginLabel(layer),
2287
+ path: layer.dir,
2288
+ found: false,
2289
+ candidate: "",
2290
+ merge: "",
2291
+ outcome: "missing",
2292
+ description: ""
2293
+ };
2294
+ trace.push(entry);
2295
+ if (layer.skipped) {
2296
+ entry.outcome = layer.skipped;
2297
+ continue;
2298
+ }
2299
+ const [hit, ...ignored] = candidateFiles(ref.name).flatMap((candidate) => {
2300
+ const raw = tryRead(join(layer.dir, candidate));
2301
+ return raw === void 0 ? [] : [{
2302
+ candidate,
2303
+ raw
2304
+ }];
2305
+ });
2306
+ if (!hit) continue;
2307
+ for (const other of ignored) warnings.push(`${display(join(layer.dir, other.candidate))} is ignored: ${hit.candidate} answers first in that folder`);
2308
+ const path = join(layer.dir, hit.candidate);
2309
+ const warn = (message) => warnings.push(`${display(path)}: ${message}`);
2310
+ const { metadata, body } = parseDocument(hit.raw, warn);
2311
+ const merge = readMergeMode(metadata, warn);
2312
+ const description = typeof metadata["description"] === "string" ? metadata["description"] : "";
2313
+ Object.assign(entry, {
2314
+ path,
2315
+ found: true,
2316
+ candidate: hit.candidate,
2317
+ merge,
2318
+ outcome: "",
2319
+ description
2320
+ });
2321
+ found.push({
2322
+ layer,
2323
+ entry,
2324
+ metadata,
2325
+ body,
2326
+ merge
2327
+ });
2328
+ }
2329
+ const result = {
2330
+ name: ref.raw,
2331
+ status: "missing",
2332
+ layers: [],
2333
+ warnings,
2334
+ plugins: [],
2335
+ trace
2336
+ };
2337
+ const stop = found.findIndex(({ merge }) => merge === "first-wins");
2338
+ const chain = stop === -1 ? found : found.slice(0, stop + 1);
2339
+ const shadowed = stop === -1 ? [] : found.slice(stop + 1);
2340
+ const base = chain.at(-1);
2341
+ const holders = [...new Set(found.filter(({ layer }) => layer.tier === "plugin").map(({ entry }) => entry.plugin))];
2342
+ if (ref.plugin === void 0 && holders.length > 1 && chain.some(({ layer }) => layer.tier === "plugin")) {
2343
+ for (const { entry } of found) entry.outcome = "ambiguous";
2344
+ result.status = "ambiguous";
2345
+ result.plugins = holders.map((plugin) => `${plugin}/${ref.name}`);
2346
+ return result;
2347
+ }
2348
+ for (const document of shadowed) document.entry.outcome = `shadowed by ${base.layer.tier} (first-wins)`;
2349
+ if (!base) return result;
2350
+ for (const { entry } of chain) entry.outcome = "used";
2351
+ const top = chain[0];
2352
+ return {
2353
+ ...result,
2354
+ status: "found",
2355
+ tier: top.layer.tier,
2356
+ plugin: top.entry.plugin,
2357
+ path: top.entry.path,
2358
+ merge: top.merge,
2359
+ metadata: Object.assign({}, ...[...chain].reverse().map(({ metadata }) => metadata)),
2360
+ content: withNewline(stripMergeComments(fold(chain, display, (message) => warnings.push(message)))),
2361
+ layers: chain.map(({ layer, entry, merge }) => ({
2362
+ tier: layer.tier,
2363
+ plugin: entry.plugin,
2364
+ path: entry.path,
2365
+ merge
2366
+ }))
2367
+ };
2368
+ }
2369
+ /** Bottom-up: the base is the lowest document read, and each document above says how it applies. */
2370
+ function fold(chain, display, warn) {
2371
+ const label = ({ layer, entry }) => `${layerName(layer)} ${display(entry.path)}`;
2372
+ const [base, ...above] = [...chain].reverse();
2373
+ let parts = [{
2374
+ labels: [label(base)],
2375
+ body: base.body
2376
+ }];
2377
+ for (const document of above) {
2378
+ if (document.merge === "combine") {
2379
+ parts = [{
2380
+ labels: [label(document)],
2381
+ body: document.body
2382
+ }, ...parts];
2383
+ continue;
2384
+ }
2385
+ const merged = mergeSections(parseSections(parts.map(({ body }) => body.trim()).join("\n\n"), warn), parseSections(document.body, warn), label(document), warn);
2386
+ parts = [{
2387
+ labels: [label(document), ...parts.flatMap(({ labels }) => labels)],
2388
+ body: renderSections(merged)
2389
+ }];
2390
+ }
2391
+ if (parts.length === 1) return parts[0].body;
2392
+ return [`> Combined from ${parts.length} layers, highest precedence first. Where they conflict, the first layer wins.`, ...parts.map(({ labels, body }) => `<!-- layer: ${labels.join(", ")} -->\n\n${body.trim()}`)].join("\n\n");
2393
+ }
2394
+ function withNewline(content) {
2395
+ return content.endsWith("\n") ? content : `${content}\n`;
2396
+ }
2397
+ /** Every name a layer holds in any candidate form; empty for a layer that is missing or unreadable. */
2398
+ function layerNames(dir) {
2399
+ let entries;
2400
+ try {
2401
+ entries = readdirSync(dir, { withFileTypes: true });
2402
+ } catch {
2403
+ return [];
2404
+ }
2405
+ const names = /* @__PURE__ */ new Set();
2406
+ for (const entry of entries) {
2407
+ const name = entry.isFile() && entry.name.endsWith(".md") ? entry.name.slice(0, -3) : entry.name;
2408
+ if (!namePattern$1.test(name)) continue;
2409
+ if (entry.isFile() ? entry.name.endsWith(".md") : folderCandidates.some((file) => tryRead(join(dir, name, file)) !== void 0)) names.add(name);
2410
+ }
2411
+ return [...names];
2412
+ }
2413
+ function referenceNames(layers) {
2414
+ return [...new Set(layers.flatMap(({ dir, skipped }) => skipped ? [] : layerNames(dir)))].sort((a, b) => a.localeCompare(b));
2415
+ }
2416
+ //#endregion
2417
+ //#region src/references/reference-catalog.ts
2418
+ /** One row per name per layer holding it, with the status resolution gave that layer. */
2419
+ function listReferences(layers, options = {}) {
2420
+ const rows = [];
2421
+ const warnings = /* @__PURE__ */ new Set();
2422
+ for (const name of referenceNames(layers)) {
2423
+ const resolved = resolveReference(parseReferenceName(name), layers, options);
2424
+ for (const warning of resolved.warnings) warnings.add(warning);
2425
+ for (const entry of resolved.trace) {
2426
+ if (!entry.found) continue;
2427
+ rows.push({
2428
+ name,
2429
+ tier: entry.tier,
2430
+ plugin: entry.plugin,
2431
+ path: entry.path,
2432
+ status: entry.outcome === "ambiguous" ? `ambiguous — ask for one of ${resolved.plugins.join(", ")}` : entry.outcome,
2433
+ description: entry.description
2434
+ });
2435
+ }
2436
+ }
2437
+ return {
2438
+ rows,
2439
+ warnings: [...warnings]
2440
+ };
2441
+ }
2442
+ const matchOrder = [
2443
+ "name",
2444
+ "prefix",
2445
+ "close name",
2446
+ "description",
2447
+ "heading",
2448
+ "body"
2449
+ ];
2450
+ function distance(a, b) {
2451
+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
2452
+ for (let i = 1; i <= a.length; i++) {
2453
+ const current = [i];
2454
+ for (let j = 1; j <= b.length; j++) {
2455
+ const substitution = previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1);
2456
+ current.push(Math.min(previous[j] + 1, current[j - 1] + 1, substitution));
2457
+ }
2458
+ previous = current;
2459
+ }
2460
+ return previous[b.length];
2461
+ }
2462
+ function headings(content) {
2463
+ let fenced = false;
2464
+ const lines = [];
2465
+ for (const line of content.split("\n")) if (/^ {0,3}(`{3,}|~{3,})/.test(line)) fenced = !fenced;
2466
+ else if (!fenced && /^ {0,3}#{1,6}\s/.test(line)) lines.push(line);
2467
+ return lines.join("\n");
2468
+ }
2469
+ function tagText(value) {
2470
+ if (Array.isArray(value)) return value.map(String).join(" ");
2471
+ return typeof value === "string" ? value : "";
2472
+ }
2473
+ function matchKind(name, reference, query) {
2474
+ const bare = name.slice(name.lastIndexOf("/") + 1).toLowerCase();
2475
+ if (bare === query || name.toLowerCase() === query) return "name";
2476
+ if (bare.startsWith(query)) return "prefix";
2477
+ if (bare.includes(query) || distance(bare, query) <= Math.max(1, Math.floor(query.length / 4))) return "close name";
2478
+ const terms = query.split(/\s+/);
2479
+ const holds = (text) => {
2480
+ const lower = text.toLowerCase();
2481
+ return terms.every((term) => lower.includes(term));
2482
+ };
2483
+ const metadata = reference.metadata;
2484
+ if (holds(`${typeof metadata["description"] === "string" ? metadata["description"] : ""} ${tagText(metadata["tags"])}`)) return "description";
2485
+ const content = reference.content;
2486
+ if (holds(headings(content))) return "heading";
2487
+ if (holds(content)) return "body";
2488
+ }
2489
+ /**
2490
+ * Every name resolves the way `show` would; a name two plugins hold is searched once per plugin, as
2491
+ * the qualified name `show` would need.
2492
+ */
2493
+ function searchReferences(query, layers, options = {}) {
2494
+ const normalized = query.trim().toLowerCase();
2495
+ const matches = [];
2496
+ for (const name of referenceNames(layers)) {
2497
+ const resolved = resolveReference(parseReferenceName(name), layers, options);
2498
+ const candidates = resolved.status === "ambiguous" ? resolved.plugins.map((qualified) => resolveReference(parseReferenceName(qualified), layers, options)) : [resolved];
2499
+ for (const reference of candidates.filter(({ status }) => status === "found")) {
2500
+ const match = matchKind(reference.name, reference, normalized);
2501
+ if (!match) continue;
2502
+ const description = reference.metadata["description"];
2503
+ matches.push({
2504
+ name: reference.name,
2505
+ tier: reference.tier,
2506
+ match,
2507
+ description: typeof description === "string" ? description.split("\n")[0]?.trim() || "" : ""
2508
+ });
2509
+ }
2510
+ }
2511
+ return matches.sort((a, b) => matchOrder.indexOf(a.match) - matchOrder.indexOf(b.match) || a.name.localeCompare(b.name));
2512
+ }
2513
+ //#endregion
2514
+ //#region src/governance-overrides/governance-overrides.ts
2515
+ function managedGovernancesDir(platform, programData) {
2516
+ if (platform === "darwin") return "/Library/Application Support/BuddyAgentHarness/governances";
2517
+ if (platform === "win32") return join(programData || "C:\\ProgramData", "BuddyAgentHarness", "governances");
2518
+ return "/etc/buddy-agent-harness/governances";
2519
+ }
2520
+ /**
2521
+ * Still read below the layer above, so a machine already using it keeps working; reported as
2522
+ * deprecated so an admin knows to move it.
2523
+ */
2524
+ function deprecatedManagedGovernancesDir(platform, programData) {
2525
+ if (platform === "darwin") return "/Library/Application Support/UniPlugin/governances";
2526
+ if (platform === "win32") return join(programData || "C:\\ProgramData", "UniPlugin", "governances");
2527
+ return "/etc/universal-plugin/governances";
2528
+ }
2529
+ function projectGovernancesDir(root) {
2530
+ return join(root, ".agents", "governances");
2531
+ }
2532
+ function userGovernancesDir(home) {
2533
+ return join(home, ".agents", "governances");
2534
+ }
2535
+ /**
2536
+ * Walks up to the nearest `package.json` rather than a relative literal — this module sits at a
2537
+ * different depth in `src/` vs the bundle.
2538
+ */
2539
+ function packageGovernancesDir(from = fileURLToPath(import.meta.url)) {
2540
+ let dir = dirname(from);
2541
+ for (;;) {
2542
+ if (existsSync(join(dir, "package.json"))) return join(dir, "governances");
2543
+ const parent = dirname(dir);
2544
+ if (parent === dir) return join(dir, "governances");
2545
+ dir = parent;
2546
+ }
2547
+ }
2548
+ function governanceLayers({ root, home, platform, programData }) {
2549
+ return [
2550
+ {
2551
+ scope: "project",
2552
+ dir: projectGovernancesDir(root)
2553
+ },
2554
+ {
2555
+ scope: "user",
2556
+ dir: userGovernancesDir(home)
2557
+ },
2558
+ {
2559
+ scope: "managed",
2560
+ dir: managedGovernancesDir(platform, programData)
2561
+ },
2562
+ {
1765
2563
  scope: "managed-deprecated",
1766
2564
  dir: deprecatedManagedGovernancesDir(platform, programData)
1767
2565
  },
@@ -1826,14 +2624,246 @@ function listGovernances(layers) {
1826
2624
  });
1827
2625
  return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
1828
2626
  }
2627
+ //#endregion
2628
+ //#region src/references/harness-layers.ts
2629
+ /** Nested harnesses leave `detectHarness` at `unknown`; each candidate is still a harness in play. */
2630
+ function detectedHarnesses(env) {
2631
+ return detectHarness({ env }).candidates;
2632
+ }
2633
+ const unreadableKind = {
2634
+ "macos-managed-preferences": "a macOS managed-preferences domain delivered by MDM",
2635
+ "windows-registry": "a Windows registry key delivered by MDM or Group Policy",
2636
+ server: "server-side settings"
2637
+ };
2638
+ function skippedLayer(tier, dir, skipped, plugins = []) {
2639
+ return {
2640
+ tier,
2641
+ dir,
2642
+ plugins,
2643
+ status: skipped,
2644
+ skipped
2645
+ };
2646
+ }
2647
+ /**
2648
+ * The folder holding a harness's managed files gets a `references/` beside them. A `directory`
2649
+ * location inside that folder, such as a drop-in `managed-settings.d`, is part of it, not a folder
2650
+ * of its own.
2651
+ */
2652
+ function managedFolders(harness, platform, env) {
2653
+ const path = platform === "win32" ? win32 : posix;
2654
+ const locations = managedPolicyLocations(harness, {
2655
+ platform,
2656
+ env
2657
+ });
2658
+ const folders = [...new Set(locations.flatMap(({ kind, location }) => kind === "file" ? [path.dirname(location)] : kind === "directory" ? [location] : []))];
2659
+ return {
2660
+ read: folders.filter((folder) => !folders.some((other) => folder.startsWith(other + path.sep))).map((folder) => path.join(folder, "references")),
2661
+ unread: locations.flatMap(({ kind, location }) => {
2662
+ const where = unreadableKind[kind];
2663
+ return where ? [{
2664
+ location,
2665
+ reason: `not read — ${harness} keeps this policy in ${where}, which cannot be read locally`
2666
+ }] : [];
2667
+ })
2668
+ };
2669
+ }
2670
+ function harnessManagedLayers(harnesses, platform, env) {
2671
+ if (!harnesses.length) return [skippedLayer("managed", "(no harness detected)", "not read — no harness detected, so no harness managed folder")];
2672
+ return harnesses.flatMap((harness) => {
2673
+ const { read, unread } = managedFolders(harness, platform, env);
2674
+ return [...read.map((dir) => ({
2675
+ tier: "managed",
2676
+ dir,
2677
+ plugins: [],
2678
+ status: ""
2679
+ })), ...unread.map(({ location, reason }) => skippedLayer("managed", location, reason))];
2680
+ });
2681
+ }
2682
+ /**
2683
+ * Claude Code installs one plugin at several scopes; a project- or local-scoped install loads only in
2684
+ * its own project, so the nearest folder of the walk picks it, and a user install answers elsewhere.
2685
+ */
2686
+ function activeInstall(installs, chain) {
2687
+ for (const dir of chain) {
2688
+ const install = installs.find(({ projectPath }) => projectPath === dir);
2689
+ if (install) return install;
2690
+ }
2691
+ return installs.find(({ projectPath }) => projectPath === void 0);
2692
+ }
2693
+ /**
2694
+ * Only plugins the harness has enabled: installing a plugin never activates it, and a reference is
2695
+ * instruction text an agent follows.
2696
+ */
2697
+ async function enabledPluginLayers(harnesses, chain, environment) {
2698
+ const layers = [];
2699
+ for (const harness of harnesses) {
2700
+ const [enabled, installed] = await Promise.all([enabledPlugins(harness, environment), installedPlugins(harness, environment)]);
2701
+ if (!enabled.supported) {
2702
+ layers.push(skippedLayer("plugin", `(${harness} enabled plugins)`, `not read — ${harness} keeps no readable record of enabled plugins`));
2703
+ continue;
2704
+ }
2705
+ if (enabled.unread.length) layers.push(skippedLayer("plugin", `(${harness} plugin policy)`, `not read — ${enabled.unread.join("; ")} may also enable or disable ${harness} plugins`));
2706
+ for (const { id, enabled: on } of enabled.plugins) {
2707
+ if (!on) continue;
2708
+ const plugin = id.split("@")[0];
2709
+ const install = activeInstall(installed.plugins.filter((candidate) => candidate.id === id), chain);
2710
+ if (install) {
2711
+ layers.push({
2712
+ tier: "plugin",
2713
+ dir: join(install.path, "references"),
2714
+ plugins: [plugin],
2715
+ status: ""
2716
+ });
2717
+ continue;
2718
+ }
2719
+ layers.push(skippedLayer("plugin", `(${id})`, `not read — enabled in ${harness}, but no install folder for this project is recorded`, [plugin]));
2720
+ }
2721
+ }
2722
+ return layers;
2723
+ }
2724
+ //#endregion
2725
+ //#region src/references/reference-layers.ts
2726
+ const PACKAGE_PLUGIN = "buddy-agent-harness";
2727
+ const LEGACY_STATUS = "legacy — move these documents to references/ beside it";
2728
+ const DEPRECATED_STATUS = "deprecated — move these documents to the managed references/ layer";
2729
+ function managedReferencesDir(platform, programData) {
2730
+ return join(dirname(managedGovernancesDir(platform, programData)), "references");
2731
+ }
2732
+ function projectReferencesDir(root) {
2733
+ return join(root, ".agents", "references");
2734
+ }
2735
+ function projectReferenceLayers(root) {
2736
+ return [{
2737
+ tier: "project",
2738
+ dir: projectReferencesDir(root),
2739
+ plugins: [],
2740
+ status: ""
2741
+ }, {
2742
+ tier: "project",
2743
+ dir: join(root, ".agents", "governances"),
2744
+ plugins: [],
2745
+ status: LEGACY_STATUS
2746
+ }];
2747
+ }
2748
+ function readJson(path) {
2749
+ try {
2750
+ return JSON.parse(readFileSync(path, "utf8"));
2751
+ } catch {
2752
+ return;
2753
+ }
2754
+ }
2755
+ function isRepositoryRoot(dir) {
2756
+ if (existsSync(join(dir, ".git")) || existsSync(join(dir, "pnpm-workspace.yaml"))) return true;
2757
+ const manifest = readJson(join(dir, "package.json"));
2758
+ return isRecord(manifest) && manifest["workspaces"] !== void 0;
2759
+ }
2760
+ /**
2761
+ * `root` and each folder above it up to the repository root, nearest first. With no repository root
2762
+ * above, `root` alone: a walk that never finds one would read every ancestor up to the filesystem root.
2763
+ */
2764
+ function projectChain(root) {
2765
+ const start = resolve(root);
2766
+ const chain = [];
2767
+ let dir = start;
2768
+ for (;;) {
2769
+ chain.push(dir);
2770
+ if (isRepositoryRoot(dir)) return chain;
2771
+ const parent = dirname(dir);
2772
+ if (parent === dir) return [start];
2773
+ dir = parent;
2774
+ }
2775
+ }
2776
+ function isDirectory$1(path) {
2777
+ try {
2778
+ return statSync(path).isDirectory();
2779
+ } catch {
2780
+ return false;
2781
+ }
2782
+ }
2783
+ function nearestManifest(root) {
2784
+ let dir = root;
2785
+ for (;;) {
2786
+ const path = join(dir, "package.json");
2787
+ if (existsSync(path)) return path;
2788
+ const parent = dirname(dir);
2789
+ if (parent === dir) return void 0;
2790
+ dir = parent;
2791
+ }
2792
+ }
2793
+ function canonical(path) {
2794
+ try {
2795
+ return realpathSync(path);
2796
+ } catch {
2797
+ return path;
2798
+ }
2799
+ }
1829
2800
  /**
1830
- * Creates the directory if absent — a fresh repository gets one obvious place to put an override,
1831
- * and a count of zero.
2801
+ * Declared dependencies only: a transitive package never becomes a plugin, because a reference is
2802
+ * instruction text an agent follows.
1832
2803
  */
1833
- function countProjectGovernances(root) {
1834
- const dir = projectGovernancesDir(root);
1835
- mkdirSync(dir, { recursive: true });
1836
- return documentNames(dir).length;
2804
+ function dependencyLayers(root, skip) {
2805
+ const manifestPath = nearestManifest(root);
2806
+ if (!manifestPath) return [];
2807
+ const layers = [];
2808
+ for (const pkg of declaredDependencies(readJson(manifestPath))) {
2809
+ const dir = packageDir(pkg, manifestPath);
2810
+ if (!dir || skip.has(canonical(dir))) continue;
2811
+ const references = join(dir, "references");
2812
+ if (!isDirectory$1(references)) continue;
2813
+ const manifest = readJson(join(dir, "plugin.json"));
2814
+ const manifestName = isRecord(manifest) && typeof manifest["name"] === "string" ? manifest["name"] : void 0;
2815
+ const plugins = manifestName && manifestName !== pkg ? [pkg, manifestName] : [pkg];
2816
+ layers.push({
2817
+ tier: "plugin",
2818
+ dir: references,
2819
+ plugins,
2820
+ status: ""
2821
+ });
2822
+ }
2823
+ return layers;
2824
+ }
2825
+ async function referenceLayers({ root, home, platform, programData, packageRoot = dirname(packageGovernancesDir()), env = process.env }) {
2826
+ const layer = (tier, dir, status = "") => ({
2827
+ tier,
2828
+ dir,
2829
+ plugins: [],
2830
+ status
2831
+ });
2832
+ const self = [PACKAGE_PLUGIN];
2833
+ const harnesses = detectedHarnesses(env);
2834
+ const chain = projectChain(root);
2835
+ const ownRoot = canonical(packageRoot);
2836
+ const enabled = await enabledPluginLayers(harnesses, chain, {
2837
+ env,
2838
+ homedir: home,
2839
+ cwd: resolve(root),
2840
+ platform
2841
+ });
2842
+ const layers = [
2843
+ layer("managed", managedReferencesDir(platform, programData)),
2844
+ ...harnessManagedLayers(harnesses, platform, env),
2845
+ layer("managed", managedGovernancesDir(platform, programData), LEGACY_STATUS),
2846
+ layer("managed", deprecatedManagedGovernancesDir(platform, programData), DEPRECATED_STATUS),
2847
+ ...chain.flatMap(projectReferenceLayers),
2848
+ layer("user", join(home, ".agents", "references")),
2849
+ layer("user", join(home, ".agents", "governances"), LEGACY_STATUS),
2850
+ {
2851
+ tier: "plugin",
2852
+ dir: join(packageRoot, "references"),
2853
+ plugins: self,
2854
+ status: ""
2855
+ },
2856
+ {
2857
+ tier: "plugin",
2858
+ dir: join(packageRoot, "governances"),
2859
+ plugins: self,
2860
+ status: LEGACY_STATUS
2861
+ },
2862
+ ...enabled.filter(({ dir, skipped }) => skipped || isDirectory$1(dir) && canonical(dirname(dir)) !== ownRoot),
2863
+ ...dependencyLayers(root, /* @__PURE__ */ new Set([ownRoot]))
2864
+ ];
2865
+ const seen = /* @__PURE__ */ new Set();
2866
+ return layers.filter(({ dir }) => !seen.has(dir) && seen.add(dir));
1837
2867
  }
1838
2868
  //#endregion
1839
2869
  //#region src/skill-projection/skill-projection.ts
@@ -2354,9 +3384,9 @@ function diagnoseBridges({ root, harnesses: preferred = [], cli }) {
2354
3384
  * AXI §5: the healthy answer states the zero with context, so an agent doesn't re-run to confirm
2355
3385
  * nothing was wrong.
2356
3386
  */
2357
- function buildDoctorReport(bin, result, configuration = [], overrides = []) {
3387
+ function buildDoctorReport(bin, result, configuration = [], held = []) {
2358
3388
  const findings = [...result.findings, ...configuration];
2359
- const governances = overrides.length ? overrides : "0 governance overrides — no .agents/governances at project, user, or machine scope";
3389
+ const references = held.length ? held : "0 references — no layer outside the plugin tier holds one";
2360
3390
  if (!findings.length) {
2361
3391
  const count = result.bridges.length + result.instructions.length;
2362
3392
  const bridges = count === 1 ? "the 1 bridge resolves" : `all ${count} bridges resolve`;
@@ -2364,7 +3394,7 @@ function buildDoctorReport(bin, result, configuration = [], overrides = []) {
2364
3394
  bin,
2365
3395
  bridges: result.bridges,
2366
3396
  instructions: result.instructions,
2367
- governances,
3397
+ references,
2368
3398
  findings: `0 problems found — ${bridges} and the configuration around them is current`
2369
3399
  };
2370
3400
  }
@@ -2372,7 +3402,7 @@ function buildDoctorReport(bin, result, configuration = [], overrides = []) {
2372
3402
  bin,
2373
3403
  bridges: result.bridges,
2374
3404
  instructions: result.instructions,
2375
- governances,
3405
+ references,
2376
3406
  ...result.divergence.length ? { divergence: result.divergence } : {},
2377
3407
  findings: findings.map(({ path, problem, detail }) => ({
2378
3408
  path,
@@ -2400,7 +3430,7 @@ const doctorCommand = command({
2400
3430
  default: "toon"
2401
3431
  }
2402
3432
  },
2403
- run(args) {
3433
+ async run(args) {
2404
3434
  try {
2405
3435
  const format = parseFormat(args.format);
2406
3436
  const harnesses = parseHarnesses(args.harness);
@@ -2428,17 +3458,20 @@ const doctorCommand = command({
2428
3458
  cli: commandInvocation
2429
3459
  })
2430
3460
  ];
2431
- const overrides = listGovernances(overrideLayers(governanceLayers({
3461
+ const { rows } = listReferences(await referenceLayers({
2432
3462
  root,
2433
3463
  home,
2434
3464
  platform: process.platform,
2435
- programData: process.env["ProgramData"]
2436
- }))).map(({ name, scope, path }) => ({
3465
+ programData: process.env["ProgramData"],
3466
+ env: process.env
3467
+ }));
3468
+ const held = rows.filter(({ tier }) => tier !== "plugin").map(({ name, tier, path, status }) => ({
2437
3469
  name,
2438
- scope,
2439
- path: collapseHome(home, path)
3470
+ tier,
3471
+ path: collapseHome(home, path),
3472
+ status
2440
3473
  }));
2441
- writeResult(buildDoctorReport(displayBinPath(home, process.argv[1]), result, configuration, overrides), format);
3474
+ writeResult(buildDoctorReport(displayBinPath(home, process.argv[1]), result, configuration, held), format);
2442
3475
  return exitCodes.success;
2443
3476
  } catch (error) {
2444
3477
  process.stderr.write(`error: ${error instanceof Error ? error.message : "Harness diagnosis failed."}\n`);
@@ -2448,7 +3481,7 @@ const doctorCommand = command({
2448
3481
  });
2449
3482
  //#endregion
2450
3483
  //#region src/governance-overrides/governance.command.ts
2451
- function layersFor(args) {
3484
+ function layersFor$1(args) {
2452
3485
  const layers = governanceLayers({
2453
3486
  root: args.root ?? process.cwd(),
2454
3487
  home: homedir(),
@@ -2457,8 +3490,9 @@ function layersFor(args) {
2457
3490
  });
2458
3491
  return args["overrides-only"] ? overrideLayers(layers) : layers;
2459
3492
  }
3493
+ const GOVERNANCE_DEPRECATED = "warning: \"governance\" is deprecated and will be removed in the next major version; use \"reference show|list\" instead.\n";
2460
3494
  const DEPRECATED_MANAGED = "deprecated — move these documents to the managed layer above";
2461
- const rootOption = {
3495
+ const rootOption$1 = {
2462
3496
  description: "Repository or package directory. Defaults to the current directory.",
2463
3497
  type: z.optional(z.string())
2464
3498
  };
@@ -2470,7 +3504,7 @@ const governanceListCommand = command({
2470
3504
  name: "list",
2471
3505
  description: "List every governance the override layers hold, each at the layer that would win.",
2472
3506
  options: {
2473
- root: rootOption,
3507
+ root: rootOption$1,
2474
3508
  "overrides-only": overridesOnlyOption,
2475
3509
  format: {
2476
3510
  description: "Output format: toon (default), json, or text for a human-readable report.",
@@ -2479,10 +3513,11 @@ const governanceListCommand = command({
2479
3513
  }
2480
3514
  },
2481
3515
  run(args) {
3516
+ process.stderr.write(GOVERNANCE_DEPRECATED);
2482
3517
  try {
2483
3518
  const format = parseFormat(args.format);
2484
3519
  const home = homedir();
2485
- const layers = layersFor(args);
3520
+ const layers = layersFor$1(args);
2486
3521
  const entries = listGovernances(layers);
2487
3522
  writeResult({
2488
3523
  layers: layers.map(({ scope, dir }) => ({
@@ -2512,7 +3547,7 @@ const governanceShowCommand = command({
2512
3547
  type: z.string()
2513
3548
  }],
2514
3549
  options: {
2515
- root: rootOption,
3550
+ root: rootOption$1,
2516
3551
  "overrides-only": overridesOnlyOption,
2517
3552
  format: {
2518
3553
  description: "Output format: text (default) writes the document itself; toon and json wrap it with the layer it came from.",
@@ -2521,10 +3556,11 @@ const governanceShowCommand = command({
2521
3556
  }
2522
3557
  },
2523
3558
  run(args) {
3559
+ process.stderr.write(GOVERNANCE_DEPRECATED);
2524
3560
  try {
2525
3561
  const format = parseFormat(args.format);
2526
3562
  const name = parseGovernanceName(args.name);
2527
- const found = resolveGovernance(name, layersFor(args));
3563
+ const found = resolveGovernance(name, layersFor$1(args));
2528
3564
  if (!found) {
2529
3565
  process.stderr.write(args["overrides-only"] ? `error: no override for governance "${name}" in the project, user, or machine-wide layer.\n` : `error: no governance named "${name}" in any layer.\n`);
2530
3566
  return exitCodes.error;
@@ -2545,41 +3581,228 @@ const governanceShowCommand = command({
2545
3581
  });
2546
3582
  const governanceCommand = command({
2547
3583
  name: "governance",
2548
- description: "Read the governance documents the project, user, and machine-wide override layers hold. Read-only.",
3584
+ description: "Deprecated: use `reference`. Read the governance documents the project, user, and machine-wide override layers hold. Read-only.",
2549
3585
  commands: [governanceListCommand, governanceShowCommand]
2550
3586
  });
2551
3587
  //#endregion
2552
- //#region src/initialize-harnesses/initialize-harnesses.ts
2553
- function initializeHarnesses({ root, harnesses: preferred = [], copy = false, force = false }) {
2554
- const canonicalSkills = join(root, ".agents", "skills");
2555
- const skills = countSkills(canonicalSkills);
2556
- const governances = countProjectGovernances(root);
2557
- const harnesses = selectHarnesses(root, preferred);
2558
- const { linked, skipped } = projectSkills({
2559
- root,
2560
- canonicalSkills,
2561
- harnesses,
2562
- copy,
2563
- force
3588
+ //#region src/references/reference.command.ts
3589
+ const rootOption = {
3590
+ description: "Directory the project tier is read from, and each folder above it up to the repository root. Defaults to the current directory.",
3591
+ type: z.optional(z.string())
3592
+ };
3593
+ function layersFor(args, home) {
3594
+ return referenceLayers({
3595
+ root: args.root ?? process.cwd(),
3596
+ home,
3597
+ platform: process.platform,
3598
+ programData: process.env["ProgramData"],
3599
+ env: process.env
2564
3600
  });
2565
- return {
2566
- root,
2567
- harnesses: harnesses.map((harness) => harness.name),
2568
- native: harnesses.filter((harness) => !harness.project.skillsDirectory).map((harness) => harness.name),
2569
- linked,
2570
- skipped,
2571
- deprecated: harnesses.filter((harness) => harness.deprecated).map((harness) => ({
2572
- name: harness.name,
2573
- replacedBy: harness.deprecated
2574
- })),
2575
- skills,
2576
- governances,
2577
- copied: copy
3601
+ }
3602
+ function fail(error, fallback) {
3603
+ process.stderr.write(`error: ${error instanceof Error ? error.message : fallback}\n`);
3604
+ return exitCodes.error;
3605
+ }
3606
+ function showEntry(resolved, home, suggestions, trace) {
3607
+ const entry = {
3608
+ name: resolved.name,
3609
+ status: resolved.status,
3610
+ warnings: []
2578
3611
  };
3612
+ if (resolved.status === "found") Object.assign(entry, {
3613
+ tier: resolved.tier,
3614
+ plugin: resolved.plugin,
3615
+ path: collapseHome(home, resolved.path),
3616
+ merge: resolved.merge,
3617
+ metadata: resolved.metadata,
3618
+ content: resolved.content,
3619
+ layers: resolved.layers.map((layer) => ({
3620
+ ...layer,
3621
+ path: collapseHome(home, layer.path)
3622
+ }))
3623
+ });
3624
+ if (resolved.status === "missing") entry.suggestions = suggestions;
3625
+ if (resolved.status === "ambiguous") entry.plugins = resolved.plugins;
3626
+ entry.warnings = resolved.warnings;
3627
+ if (trace) entry.trace = resolved.trace.map(({ description: _, ...step }) => ({
3628
+ ...step,
3629
+ path: collapseHome(home, step.path)
3630
+ }));
3631
+ return entry;
2579
3632
  }
2580
- //#endregion
2581
- //#region src/initialize-harnesses/init.command.ts
2582
- const initCommand = command({
3633
+ function missReason(entry) {
3634
+ if (entry.status === "ambiguous") return `"${entry.name}" is held by more than one plugin; ask for one of ${entry.plugins.join(", ")}.`;
3635
+ const hint = entry.suggestions?.length ? ` Did you mean: ${entry.suggestions.join(", ")}?` : "";
3636
+ return `no reference named "${entry.name}" in any tier.${hint}`;
3637
+ }
3638
+ function writeShowText(entries) {
3639
+ if (entries.length === 1) {
3640
+ const [entry] = entries;
3641
+ if (entry.content !== void 0) writeDocument(entry.content);
3642
+ return;
3643
+ }
3644
+ writeDocument(entries.map((entry) => entry.content === void 0 ? `<reference name="${entry.name}" status="${entry.status}" />` : `<reference name="${entry.name}" tier="${entry.tier}">\n${entry.content}</reference>`).join("\n\n"));
3645
+ }
3646
+ function writeShowStderr(entries, format) {
3647
+ for (const entry of entries) {
3648
+ if (format === "text") {
3649
+ for (const warning of entry.warnings) process.stderr.write(`warning: ${warning}\n`);
3650
+ if (entry.trace) process.stderr.write(`${renderText({ [`trace ${entry.name}`]: entry.trace })}\n`);
3651
+ }
3652
+ if (entry.status !== "found") process.stderr.write(`error: ${missReason(entry)}\n`);
3653
+ }
3654
+ }
3655
+ const referenceShowCommand = command({
3656
+ name: "show",
3657
+ description: "Print one or more references, each resolved through the tiers and combined as its layers ask.",
3658
+ arguments: [{
3659
+ name: "names",
3660
+ description: "Reference names, without the `.md` extension; `<plugin>/<name>` picks one plugin.",
3661
+ type: z.array(z.string())
3662
+ }],
3663
+ options: {
3664
+ root: rootOption,
3665
+ trace: {
3666
+ description: "Report every path checked, the file that matched, the merge mode, and why a layer was dropped.",
3667
+ type: z.optional(z.boolean())
3668
+ },
3669
+ format: {
3670
+ description: "Output format: text (default) writes the documents themselves; toon and json return an array with metadata.",
3671
+ type: z.optional(z.string()),
3672
+ default: "text"
3673
+ }
3674
+ },
3675
+ async run(args) {
3676
+ try {
3677
+ const format = parseFormat(args.format);
3678
+ const names = args.names.map(parseReferenceName);
3679
+ if (!names.length) throw new Error("Name at least one reference.");
3680
+ const home = homedir();
3681
+ const layers = await layersFor(args, home);
3682
+ const display = (path) => collapseHome(home, path);
3683
+ const entries = names.map((name) => {
3684
+ const resolved = resolveReference(name, layers, { display });
3685
+ const suggestions = resolved.status === "missing" ? searchReferences(name.name, layers, { display }).slice(0, 3).map((match) => match.name) : [];
3686
+ return showEntry(resolved, home, suggestions, Boolean(args.trace));
3687
+ });
3688
+ if (format === "text") writeShowText(entries);
3689
+ else writeResult(entries, format);
3690
+ writeShowStderr(entries, format);
3691
+ return entries.every((entry) => entry.status === "found") ? exitCodes.success : exitCodes.error;
3692
+ } catch (error) {
3693
+ return fail(error, "Reference lookup failed.");
3694
+ }
3695
+ }
3696
+ });
3697
+ const listFormatOption = {
3698
+ description: "Output format: toon (default), json, or text for a human-readable report.",
3699
+ type: z.optional(z.string()),
3700
+ default: "toon"
3701
+ };
3702
+ const referenceListCommand = command({
3703
+ name: "list",
3704
+ description: "List every layer, and every reference at every layer that holds it, marked used or shadowed.",
3705
+ options: {
3706
+ root: rootOption,
3707
+ format: listFormatOption
3708
+ },
3709
+ async run(args) {
3710
+ try {
3711
+ const format = parseFormat(args.format);
3712
+ const home = homedir();
3713
+ const layers = await layersFor(args, home);
3714
+ const { rows, warnings } = listReferences(layers, { display: (path) => collapseHome(home, path) });
3715
+ const report = {
3716
+ layers: layers.map(({ tier, plugins, dir, status }) => ({
3717
+ tier,
3718
+ plugin: plugins[0] ?? "",
3719
+ path: collapseHome(home, dir),
3720
+ status
3721
+ })),
3722
+ references: rows.length ? rows.map((row) => ({
3723
+ ...row,
3724
+ path: collapseHome(home, row.path)
3725
+ })) : "0 references — no layer holds one"
3726
+ };
3727
+ if (warnings.length) report.warnings = warnings;
3728
+ writeResult(report, format);
3729
+ return exitCodes.success;
3730
+ } catch (error) {
3731
+ return fail(error, "Reference listing failed.");
3732
+ }
3733
+ }
3734
+ });
3735
+ const referenceSearchCommand = command({
3736
+ name: "search",
3737
+ description: "Find references by name, description, tags, headings, or body, best match first.",
3738
+ arguments: [{
3739
+ name: "query",
3740
+ description: "What the reference is about.",
3741
+ type: z.string()
3742
+ }],
3743
+ options: {
3744
+ root: rootOption,
3745
+ format: listFormatOption
3746
+ },
3747
+ async run(args) {
3748
+ try {
3749
+ const format = parseFormat(args.format);
3750
+ const query = args.query.trim();
3751
+ if (!query) throw new Error("Search needs a query.");
3752
+ const home = homedir();
3753
+ const matches = searchReferences(query, await layersFor(args, home), { display: (path) => collapseHome(home, path) });
3754
+ writeResult({
3755
+ query,
3756
+ references: matches.length ? matches : `0 references match "${query}"`
3757
+ }, format);
3758
+ return exitCodes.success;
3759
+ } catch (error) {
3760
+ return fail(error, "Reference search failed.");
3761
+ }
3762
+ }
3763
+ });
3764
+ const referenceCommand = command({
3765
+ name: "reference",
3766
+ description: "Read on-demand reference documents by name, layered across the managed, project, user, and plugin tiers. Read-only.",
3767
+ commands: [
3768
+ referenceShowCommand,
3769
+ referenceListCommand,
3770
+ referenceSearchCommand
3771
+ ]
3772
+ });
3773
+ //#endregion
3774
+ //#region src/initialize-harnesses/initialize-harnesses.ts
3775
+ function initializeHarnesses({ root, harnesses: preferred = [], copy = false, force = false }) {
3776
+ const canonicalSkills = join(root, ".agents", "skills");
3777
+ const skills = countSkills(canonicalSkills);
3778
+ mkdirSync(projectReferencesDir(root), { recursive: true });
3779
+ const references = referenceNames(projectReferenceLayers(root)).length;
3780
+ const harnesses = selectHarnesses(root, preferred);
3781
+ const { linked, skipped } = projectSkills({
3782
+ root,
3783
+ canonicalSkills,
3784
+ harnesses,
3785
+ copy,
3786
+ force
3787
+ });
3788
+ return {
3789
+ root,
3790
+ harnesses: harnesses.map((harness) => harness.name),
3791
+ native: harnesses.filter((harness) => !harness.project.skillsDirectory).map((harness) => harness.name),
3792
+ linked,
3793
+ skipped,
3794
+ deprecated: harnesses.filter((harness) => harness.deprecated).map((harness) => ({
3795
+ name: harness.name,
3796
+ replacedBy: harness.deprecated
3797
+ })),
3798
+ skills,
3799
+ references,
3800
+ copied: copy
3801
+ };
3802
+ }
3803
+ //#endregion
3804
+ //#region src/initialize-harnesses/init.command.ts
3805
+ const initCommand = command({
2583
3806
  name: "init",
2584
3807
  description: "Set up canonical agent skills for the harnesses already enabled in a repository.",
2585
3808
  options: {
@@ -2628,6 +3851,7 @@ const harnessCommand = command({
2628
3851
  commands: [
2629
3852
  initCommand,
2630
3853
  doctorCommand,
3854
+ referenceCommand,
2631
3855
  governanceCommand
2632
3856
  ]
2633
3857
  });
@@ -2635,6 +3859,783 @@ function activate({ addCommand }) {
2635
3859
  addCommand(harnessCommand);
2636
3860
  }
2637
3861
  //#endregion
3862
+ //#region src/config-edit/toml-edit.ts
3863
+ function nested(path, value) {
3864
+ return path.reduceRight((inner, key) => ({ [key]: inner }), value);
3865
+ }
3866
+ /** `value` as the table at `path`, with its sub-tables, in the form `smol-toml` writes it. */
3867
+ function renderTomlTable(path, value) {
3868
+ return stringify(nested(path, value));
3869
+ }
3870
+ /** Appends the table at `path` after the last byte of `source`, which stays as it is. */
3871
+ function appendTomlTable(source, path, value) {
3872
+ return `${source}${source === "" || source.endsWith("\n") ? "" : "\n"}\n${renderTomlTable(path, value)}`;
3873
+ }
3874
+ function keyNames(key) {
3875
+ return key.keys.map((part) => part.type === "TOMLBare" ? part.name : part.value);
3876
+ }
3877
+ function startsWith(key, prefix) {
3878
+ return prefix.length <= key.length && prefix.every((part, index) => key[index] === part);
3879
+ }
3880
+ /** Either key names a place inside the other, so a value at one defines or holds the other. */
3881
+ function overlaps(key, path) {
3882
+ return startsWith(key, path) || startsWith(path, key);
3883
+ }
3884
+ /**
3885
+ * Replaces the table at `path` and every `[path.*]` sub-table, wherever they sit, keeping every
3886
+ * byte outside them. Only the `[table]` header form is replaced: a table written inline or as
3887
+ * dotted keys, or holding an array of tables, is refused as `shape`, and so is one whose header is
3888
+ * only implied by a sub-table. `smol-toml` keeps no source offsets, so `toml-eslint-parser`
3889
+ * locates the tables; values still come from `smol-toml`.
3890
+ */
3891
+ function replaceTomlTable(source, path, value) {
3892
+ let program;
3893
+ try {
3894
+ program = parseTOML(source);
3895
+ } catch {
3896
+ return {
3897
+ kind: "refused",
3898
+ reason: "unreadable"
3899
+ };
3900
+ }
3901
+ const owned = [];
3902
+ for (const node of program.body[0].body) {
3903
+ if (node.type === "TOMLKeyValue") {
3904
+ if (overlaps(keyNames(node.key), path)) return {
3905
+ kind: "refused",
3906
+ reason: "shape"
3907
+ };
3908
+ continue;
3909
+ }
3910
+ if (startsWith(node.resolvedKey, path)) {
3911
+ if (node.kind === "array") return {
3912
+ kind: "refused",
3913
+ reason: "shape"
3914
+ };
3915
+ owned.push(node);
3916
+ continue;
3917
+ }
3918
+ const table = node.resolvedKey;
3919
+ if (node.body.some((pair) => overlaps([...table, ...keyNames(pair.key)], path))) return {
3920
+ kind: "refused",
3921
+ reason: "shape"
3922
+ };
3923
+ }
3924
+ if (!owned.length) return {
3925
+ kind: "refused",
3926
+ reason: "absent"
3927
+ };
3928
+ if (!owned.some((table) => table.resolvedKey.length === path.length)) return {
3929
+ kind: "refused",
3930
+ reason: "shape"
3931
+ };
3932
+ const spans = owned.map((table) => {
3933
+ const lineEnd = source.slice(table.range[1]).search(/\r?\n/);
3934
+ return [table.range[0], lineEnd < 0 ? source.length : table.range[1] + lineEnd];
3935
+ });
3936
+ const inside = (offset) => spans.some(([start, end]) => start <= offset && offset < end);
3937
+ if (program.comments.some((comment) => inside(comment.range[0]))) return {
3938
+ kind: "refused",
3939
+ reason: "comment"
3940
+ };
3941
+ const [first, ...rest] = spans;
3942
+ let text = source;
3943
+ for (const [start, end] of rest.reverse()) {
3944
+ const before = text.slice(0, start);
3945
+ const after = text.slice(end).replace(/^\r?\n/, "");
3946
+ text = /\n\r?\n$/.test(before) ? `${before}${after.replace(/^\r?\n/, "")}` : `${before}${after}`;
3947
+ }
3948
+ const rendered = renderTomlTable(path, value).trimEnd();
3949
+ return {
3950
+ kind: "edited",
3951
+ text: `${text.slice(0, first[0])}${rendered}${text.slice(first[1])}`
3952
+ };
3953
+ }
3954
+ const bareKey = /^[A-Za-z0-9_-]+$/;
3955
+ function tomlKey(name) {
3956
+ return bareKey.test(name) ? name : JSON.stringify(name);
3957
+ }
3958
+ /** One value in TOML inline syntax: a map stays on its line as an inline table, not a sub-table. */
3959
+ function renderTomlInline(value) {
3960
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) return `{ ${Object.entries(value).map(([name, item]) => `${tomlKey(name)} = ${renderTomlInline(item)}`).join(", ")} }`;
3961
+ return stringify({ v: value }).slice(4).trimEnd();
3962
+ }
3963
+ /**
3964
+ * Appends the table at `path` with every value inline, so a later field edit finds each value on
3965
+ * one line of that table rather than in a sub-table.
3966
+ */
3967
+ function appendInlineTomlTable(source, path, value) {
3968
+ const separator = source === "" || source.endsWith("\n") ? "" : "\n";
3969
+ const lines = Object.entries(value).map(([name, item]) => `${tomlKey(name)} = ${renderTomlInline(item)}\n`);
3970
+ return `${source}${separator}\n[${path.map(tomlKey).join(".")}]\n${lines.join("")}`;
3971
+ }
3972
+ function lineEndAt(source, offset) {
3973
+ const end = source.indexOf("\n", offset);
3974
+ return end === -1 ? source.length : end;
3975
+ }
3976
+ /**
3977
+ * Sets, adds, or (with `undefined`) removes the one key `name` of the `[path]` table, keeping every
3978
+ * byte outside that key-value line. Only a key written directly in the table's own `[header]` form
3979
+ * is taken apart: a table written inline or as dotted keys is `absent`, and a key spread over dotted
3980
+ * keys or a sub-table is `shape`.
3981
+ */
3982
+ function setTomlKey(source, path, name, value) {
3983
+ let program;
3984
+ try {
3985
+ program = parseTOML(source);
3986
+ } catch {
3987
+ return {
3988
+ kind: "refused",
3989
+ reason: "unreadable"
3990
+ };
3991
+ }
3992
+ const tables = program.body[0].body.filter((node) => node.type === "TOMLTable");
3993
+ const table = tables.find((node) => node.kind === "standard" && node.resolvedKey.length === path.length && startsWith(node.resolvedKey, path));
3994
+ if (!table) return {
3995
+ kind: "refused",
3996
+ reason: "absent"
3997
+ };
3998
+ const pairs = table.body;
3999
+ if (tables.some((node) => startsWith(node.resolvedKey, [...path, name])) || pairs.some((pair) => keyNames(pair.key)[0] === name && pair.key.keys.length > 1)) return {
4000
+ kind: "refused",
4001
+ reason: "shape"
4002
+ };
4003
+ const pair = pairs.find((item) => item.key.keys.length === 1 && keyNames(item.key)[0] === name);
4004
+ if (pair && value !== void 0) return {
4005
+ kind: "edited",
4006
+ text: `${source.slice(0, pair.value.range[0])}${renderTomlInline(value)}${source.slice(pair.value.range[1])}`
4007
+ };
4008
+ if (pair) {
4009
+ const start = source.lastIndexOf("\n", pair.range[0] - 1) + 1;
4010
+ const end = lineEndAt(source, pair.range[1]);
4011
+ return {
4012
+ kind: "edited",
4013
+ text: `${source.slice(0, start)}${source.slice(Math.min(end + 1, source.length))}`
4014
+ };
4015
+ }
4016
+ if (value === void 0) return {
4017
+ kind: "edited",
4018
+ text: source
4019
+ };
4020
+ const after = lineEndAt(source, pairs.at(-1)?.range[1] ?? table.range[0]);
4021
+ return {
4022
+ kind: "edited",
4023
+ text: `${source.slice(0, after)}\n${tomlKey(name)} = ${renderTomlInline(value)}${source.slice(after)}`
4024
+ };
4025
+ }
4026
+ //#endregion
4027
+ //#region src/reconcile-mcp/reconcile-mcp.ts
4028
+ function read$2(root, path) {
4029
+ const absolute = join(root, path);
4030
+ return existsSync(absolute) ? readFileSync(absolute, "utf8") : void 0;
4031
+ }
4032
+ const held = {
4033
+ both: "both sides changed since the last projection — a three-way conflict for a person to settle, never imported",
4034
+ unknown: "no baseline says which side changed — compare the two by hand; never imported"
4035
+ };
4036
+ /** Transport the golden set would infer anyway: stating it would record the harness's spelling, not a choice. */
4037
+ function inferredTransport(server) {
4038
+ return server.url === void 0 ? "stdio" : "http";
4039
+ }
4040
+ /** Only the names the golden set speaks for: a name only the harness carries is never compared, so never pulled. */
4041
+ function mapValue(declared, carried) {
4042
+ const kept = Object.entries(declared).flatMap(([name]) => {
4043
+ const value = isRecord(carried) ? carried[name] : void 0;
4044
+ return typeof value === "string" ? [[name, value]] : [];
4045
+ });
4046
+ return kept.length ? Object.fromEntries(kept) : void 0;
4047
+ }
4048
+ function reconcileMcp({ root, git, accept }) {
4049
+ const goldenSource = read$2(root, goldenSetPath);
4050
+ const golden = parseGoldenSet(goldenSource);
4051
+ if (golden.kind !== "servers") return golden;
4052
+ const record = parseProjectionRecord(read$2(root, projectionRecordPath));
4053
+ const baseline = new McpBaseline({
4054
+ git,
4055
+ record
4056
+ });
4057
+ const rows = [];
4058
+ const offers = [];
4059
+ for (const config of mcpTargets(root)) {
4060
+ const parsed = parseTarget(config, read$2(root, config.path));
4061
+ if (parsed.kind === "unreadable") {
4062
+ rows.push({
4063
+ path: config.path,
4064
+ action: "refuse",
4065
+ detail: "the target does not parse"
4066
+ });
4067
+ continue;
4068
+ }
4069
+ if (parsed.kind === "absent") continue;
4070
+ const dialect = mcpDialects[config.dialect];
4071
+ for (const [server, carried] of parsed.servers) {
4072
+ const declared = golden.servers.get(server);
4073
+ const at = (field) => locatorText({
4074
+ file: config.path,
4075
+ server,
4076
+ field
4077
+ });
4078
+ const offer = (field, proposed) => {
4079
+ const literals = literalsIn(field, proposed);
4080
+ for (const literal of literals) rows.push({
4081
+ path: at(literal),
4082
+ action: "refuse",
4083
+ detail: `${literal} holds a literal credential, which never enters the golden set — set it in the environment and reference it as \${VAR}`
4084
+ });
4085
+ const value = withoutLiterals(field, proposed, literals, declared);
4086
+ if (literals.length && (value === void 0 || sameField(field, { [field]: value }, declared))) return;
4087
+ const fallback = dialect.defaults?.[field];
4088
+ if (fallback !== void 0 && sameField(field, { [field]: value }, { [field]: fallback })) {
4089
+ rows.push({
4090
+ path: at(field),
4091
+ action: "skip",
4092
+ detail: `${config.dialect} fills this in by default, so it may not be the user's — set it in the golden set by hand if it is`
4093
+ });
4094
+ return;
4095
+ }
4096
+ const row = {
4097
+ path: at(field),
4098
+ action: "import",
4099
+ detail: declared ? "only the harness changed it — approve to take it into the golden set" : "the golden set does not declare this server — approve each field to add it",
4100
+ value: value === void 0 ? "(unset)" : `${field} = ${renderTomlInline(value)}`
4101
+ };
4102
+ rows.push(row);
4103
+ offers.push({
4104
+ row,
4105
+ config,
4106
+ server,
4107
+ field,
4108
+ value,
4109
+ carried,
4110
+ adds: !declared
4111
+ });
4112
+ };
4113
+ if (!declared) {
4114
+ for (const field of mcpFields) {
4115
+ if (!dialect.fields.has(field) || carried[field] === void 0) continue;
4116
+ if (field === "transport" && carried.transport === inferredTransport(carried)) continue;
4117
+ offer(field, carried[field]);
4118
+ }
4119
+ continue;
4120
+ }
4121
+ for (const field of divergingFields(declared, carried, dialect.fields)) {
4122
+ const direction = baseline.directionOf(config, server, field, declared, carried);
4123
+ if (direction === "golden") continue;
4124
+ if (direction === "target") offer(field, field === "env" || field === "headers" ? mapValue(declared[field], carried[field]) : carried[field]);
4125
+ else rows.push({
4126
+ path: at(field),
4127
+ action: "skip",
4128
+ detail: held[direction]
4129
+ });
4130
+ }
4131
+ }
4132
+ }
4133
+ if (!accept.length) return {
4134
+ kind: "planned",
4135
+ rows,
4136
+ written: false
4137
+ };
4138
+ const approved = approve(offers, rows, accept);
4139
+ if (approved.kind === "rejected") return approved;
4140
+ let source = goldenSource;
4141
+ const imported = [];
4142
+ for (const [server, group] of groupByServer(approved.offers)) {
4143
+ if (group[0]?.adds) {
4144
+ const added = Object.fromEntries(mcpFields.flatMap((field) => {
4145
+ const offer = group.find((item) => item.field === field);
4146
+ return offer ? [[field, offer.value]] : [];
4147
+ }));
4148
+ source = land(source, appendInlineTomlTable(source, ["servers", server], added), server, added, group, imported);
4149
+ continue;
4150
+ }
4151
+ for (const offer of group) {
4152
+ const expected = {
4153
+ ...parseGoldenSet(source).servers.get(server),
4154
+ [offer.field]: offer.value
4155
+ };
4156
+ if (offer.value === void 0) delete expected[offer.field];
4157
+ const edit = setTomlKey(source, ["servers", server], offer.field, offer.value);
4158
+ source = land(source, edit.kind === "edited" ? edit.text : void 0, server, expected, [offer], imported);
4159
+ }
4160
+ }
4161
+ if (source !== goldenSource) {
4162
+ writeFileSync(join(root, goldenSetPath), source);
4163
+ writeRecord$1(root, record, baseline, imported, parseGoldenSet(source));
4164
+ }
4165
+ return {
4166
+ kind: "planned",
4167
+ rows,
4168
+ written: true
4169
+ };
4170
+ }
4171
+ function literalsIn(field, value) {
4172
+ if (value === void 0) return [];
4173
+ if (field === "args") return nonSecretArgs(value).length === value.length ? [] : ["args"];
4174
+ if (field !== "env" && field !== "headers" && field !== "url") return [];
4175
+ return credentialFields({ [field]: value });
4176
+ }
4177
+ /**
4178
+ * A map keeps its other names, and a refused name keeps what the golden set already says for it;
4179
+ * any other field holding a literal is refused whole.
4180
+ */
4181
+ function withoutLiterals(field, value, literals, declared) {
4182
+ if (!literals.length) return value;
4183
+ if (field !== "env" && field !== "headers") return void 0;
4184
+ const kept = { ...value };
4185
+ for (const literal of literals) {
4186
+ const name = literal.slice(field.length + 1);
4187
+ const golden = declared?.[field]?.[name];
4188
+ if (golden === void 0) delete kept[name];
4189
+ else kept[name] = golden;
4190
+ }
4191
+ return Object.keys(kept).length ? kept : void 0;
4192
+ }
4193
+ function approve(offers, rows, accept) {
4194
+ const reasons = [];
4195
+ const chosen = [];
4196
+ for (const path of new Set(accept)) {
4197
+ const offer = offers.find((item) => item.row.path === path);
4198
+ if (offer) chosen.push(offer);
4199
+ else {
4200
+ const row = rows.find((item) => item.path === path);
4201
+ reasons.push(row ? `${path} is ${row.action}, not importable: ${row.detail}` : `${path} names no importable field`);
4202
+ }
4203
+ }
4204
+ for (const [server, group] of groupByServer(chosen)) {
4205
+ for (const field of new Set(group.map((offer) => offer.field))) {
4206
+ const values = group.filter((offer) => offer.field === field);
4207
+ if (values.some((offer) => !sameField(field, { [field]: offer.value }, { [field]: values[0]?.value }))) reasons.push(`servers.${server}.${field} is approved from more than one target with different values — approve one`);
4208
+ }
4209
+ if (group[0]?.adds && !group.some((offer) => offer.field === "command" || offer.field === "url")) reasons.push(`servers.${server} would be added with nothing to run — approve its command or url too`);
4210
+ }
4211
+ return reasons.length ? {
4212
+ kind: "rejected",
4213
+ reasons
4214
+ } : {
4215
+ kind: "approved",
4216
+ offers: chosen
4217
+ };
4218
+ }
4219
+ function groupByServer(offers) {
4220
+ const groups = /* @__PURE__ */ new Map();
4221
+ for (const offer of offers) groups.set(offer.server, [...groups.get(offer.server) ?? [], offer]);
4222
+ return groups;
4223
+ }
4224
+ /**
4225
+ * Accepts the new text only when it reads back as the expected server with every other server
4226
+ * untouched; anything else is handed over as an `edit`, never written on trust.
4227
+ */
4228
+ function land(source, next, server, expected, offers, imported) {
4229
+ const before = parseGoldenSet(source);
4230
+ const after = next === void 0 ? void 0 : parseGoldenSet(next);
4231
+ const holds = after?.kind === "servers" && mcpFields.every((field) => field === "transport" && expected.transport === void 0 || sameField(field, after.servers.get(server), expected)) && [...before.servers].every(([name, kept]) => name === server || JSON.stringify(after.servers.get(name)) === JSON.stringify(kept));
4232
+ for (const offer of offers) {
4233
+ offer.row.action = holds ? "imported" : "edit";
4234
+ offer.row.detail = holds ? "written into the golden set" : "the golden set writes this server in a shape that cannot be edited byte-safely — apply the value by hand";
4235
+ }
4236
+ if (!holds) return source;
4237
+ imported.push(...offers);
4238
+ return next;
4239
+ }
4240
+ /**
4241
+ * The imported field now agrees on both sides. A server the record has no entry for is recorded
4242
+ * only when every other field's baseline is known, so the record never asserts an agreement no
4243
+ * baseline supports.
4244
+ */
4245
+ function writeRecord$1(root, record, baseline, imported, golden) {
4246
+ for (const offer of imported) {
4247
+ const servers = record.get(offer.config.path) ?? /* @__PURE__ */ new Map();
4248
+ const recorded = servers.get(offer.server);
4249
+ const entry = recorded ? {
4250
+ ...recorded,
4251
+ [offer.field]: offer.value
4252
+ } : baseEntry(offer, baseline, golden.servers.get(offer.server));
4253
+ if (!entry) continue;
4254
+ if (offer.value === void 0) delete entry[offer.field];
4255
+ servers.set(offer.server, entry);
4256
+ record.set(offer.config.path, servers);
4257
+ }
4258
+ const absolute = join(root, projectionRecordPath);
4259
+ mkdirSync(dirname(absolute), { recursive: true });
4260
+ writeFileSync(absolute, formatProjectionRecord(record));
4261
+ }
4262
+ function baseEntry(offer, baseline, golden) {
4263
+ if (offer.adds) return { ...golden };
4264
+ const entry = {};
4265
+ for (const field of mcpDialects[offer.config.dialect].fields) {
4266
+ if (golden[field] === void 0) continue;
4267
+ if (sameField(field, golden, offer.carried)) {
4268
+ entry[field] = golden[field];
4269
+ continue;
4270
+ }
4271
+ const base = baseline.baseFor(offer.config, offer.server, field);
4272
+ if (!base) return void 0;
4273
+ entry[field] = base[field];
4274
+ }
4275
+ return entry;
4276
+ }
4277
+ //#endregion
4278
+ //#region src/reconcile-mcp/reconcile.command.ts
4279
+ const mcpReconcileCommand = command({
4280
+ name: "reconcile",
4281
+ description: "Import a harness-side MCP change into the golden set, one approved field at a time. A dry run unless --accept names a field.",
4282
+ options: {
4283
+ root: {
4284
+ description: "Repository or package directory. Defaults to the current directory.",
4285
+ type: z.optional(z.string())
4286
+ },
4287
+ accept: {
4288
+ description: "Approve one field by the path a dry run lists for it; repeat for each field. There is no approve-all.",
4289
+ type: z.optional(z.array(z.string()))
4290
+ },
4291
+ format: {
4292
+ description: "Output format: toon (default), json, or text for a human-readable report.",
4293
+ type: z.optional(z.string()),
4294
+ default: "toon"
4295
+ }
4296
+ },
4297
+ run(args) {
4298
+ try {
4299
+ const format = parseFormat(args.format);
4300
+ const root = args.root ?? process.cwd();
4301
+ const accept = args.accept ?? [];
4302
+ const plan = reconcileMcp({
4303
+ root,
4304
+ git: new GitBridgeState(root),
4305
+ accept
4306
+ });
4307
+ if (plan.kind === "unreadable") {
4308
+ const at = plan.position ? ` at line ${plan.position.line}, column ${plan.position.column}` : "";
4309
+ process.stderr.write(`error: ${goldenSetPath} does not parse${at}.\n`);
4310
+ return exitCodes.error;
4311
+ }
4312
+ if (plan.kind === "rejected") {
4313
+ process.stderr.write(`error: nothing written.\n${plan.reasons.map((reason) => `- ${reason}\n`).join("")}`);
4314
+ return exitCodes.error;
4315
+ }
4316
+ if (plan.kind === "absent") {
4317
+ writeResult({
4318
+ golden: `0 servers — no golden set at ${goldenSetPath}`,
4319
+ mode: "nothing to reconcile into",
4320
+ fields: "0 fields",
4321
+ record: "not written"
4322
+ }, format);
4323
+ return exitCodes.success;
4324
+ }
4325
+ writeResult({
4326
+ golden: goldenSetPath,
4327
+ mode: plan.written ? "written — only the fields named by --accept" : "dry run — nothing written; re-run with --accept <path> for each approved field",
4328
+ fields: plan.rows.length ? plan.rows : "0 fields — no harness holds a change the golden set lacks",
4329
+ record: plan.written ? projectionRecordPath : "not written — dry run"
4330
+ }, format);
4331
+ return exitCodes.success;
4332
+ } catch (error) {
4333
+ process.stderr.write(`error: ${error instanceof Error ? error.message : "MCP reconcile failed."}\n`);
4334
+ return exitCodes.error;
4335
+ }
4336
+ }
4337
+ });
4338
+ //#endregion
4339
+ //#region src/config-edit/jsonc-edit.ts
4340
+ /** The one indent unit a file already uses, so an inserted value reads like its neighbours. */
4341
+ function indentUnit(source) {
4342
+ const indented = /\n([ \t]+)\S/.exec(source);
4343
+ return indented ? indented[1] : " ";
4344
+ }
4345
+ function jsonAt(value, unit, depth) {
4346
+ return JSON.stringify(value, null, unit).replaceAll("\n", `\n${unit.repeat(depth)}`);
4347
+ }
4348
+ function objectAt(root, path) {
4349
+ const node = root && (path.length ? findNodeAtLocation(root, path) : root);
4350
+ return node?.type === "object" ? node : void 0;
4351
+ }
4352
+ /**
4353
+ * Adds `name` to the object at `path`, or `undefined` when there is no object there or it already
4354
+ * holds `name`. `jsonc-parser`'s own `modify` reformats the properties beside the one it inserts,
4355
+ * so the text is spliced at the parse tree's offsets instead: every byte outside the insertion
4356
+ * survives, comments included.
4357
+ */
4358
+ function insertJsonProperty(source, path, name, value) {
4359
+ const container = objectAt(parseTree(source), path);
4360
+ if (!container || findNodeAtLocation(container, [name])) return void 0;
4361
+ const depth = path.length + 1;
4362
+ const unit = indentUnit(source);
4363
+ const property = `${unit.repeat(depth)}${JSON.stringify(name)}: ${jsonAt(value, unit, depth)}`;
4364
+ const last = container.children?.at(-1);
4365
+ if (last) {
4366
+ const end = last.offset + last.length;
4367
+ return `${source.slice(0, end)},\n${property}${source.slice(end)}`;
4368
+ }
4369
+ const open = container.offset + 1;
4370
+ const close = container.offset + container.length - 1;
4371
+ return `${source.slice(0, open)}\n${property}\n${unit.repeat(depth - 1)}${source.slice(close)}`;
4372
+ }
4373
+ /** Replaces the value at `path`, keeping every byte outside it. A comment inside the value is refused. */
4374
+ function replaceJsonValue(source, path, value) {
4375
+ const root = parseTree(source);
4376
+ const node = root && findNodeAtLocation(root, path);
4377
+ if (!node) return {
4378
+ kind: "refused",
4379
+ reason: "absent"
4380
+ };
4381
+ const end = node.offset + node.length;
4382
+ const text = source.slice(node.offset, end);
4383
+ if (stripJsonComments(text) !== text) return {
4384
+ kind: "refused",
4385
+ reason: "comment"
4386
+ };
4387
+ return {
4388
+ kind: "edited",
4389
+ text: `${source.slice(0, node.offset)}${jsonAt(value, indentUnit(source), path.length)}${source.slice(end)}`
4390
+ };
4391
+ }
4392
+ //#endregion
4393
+ //#region src/project-mcp/mcp-edit.ts
4394
+ /** A new file holding only the MCP key, in the format the target reads. */
4395
+ function createFile(config, name, entry) {
4396
+ return config.format === "toml" ? renderTomlTable([config.key, name], entry) : `${JSON.stringify({ [config.key]: { [name]: entry } }, null, 2)}\n`;
4397
+ }
4398
+ /**
4399
+ * Adds one server to an existing file without touching a byte of what is already there, or
4400
+ * `undefined` when the file's shape leaves no safe place to put it.
4401
+ */
4402
+ function appendServer(config, source, name, entry) {
4403
+ if (config.format === "toml") return appendTomlTable(source, [config.key, name], entry);
4404
+ return insertJsonProperty(source, [config.key], name, entry) ?? insertJsonProperty(source, [], config.key, { [name]: entry });
4405
+ }
4406
+ /**
4407
+ * Replaces one server's entry in place, keeping every byte outside it, or `undefined` when it cannot:
4408
+ * the entry holds a comment the replacement would drop, which is the user's and not this command's
4409
+ * to drop, or is written in a form the editor does not replace.
4410
+ */
4411
+ function replaceServer(config, source, name, entry) {
4412
+ const edit = config.format === "toml" ? replaceTomlTable(source, [config.key, name], entry) : replaceJsonValue(source, [config.key, name], entry);
4413
+ return edit.kind === "edited" ? edit.text : void 0;
4414
+ }
4415
+ /** The entry as it would read in the target, for a person or a skill to apply by hand. */
4416
+ function renderEntry(config, name, entry) {
4417
+ return config.format === "toml" ? renderTomlTable([config.key, name], entry) : JSON.stringify({ [name]: entry }, null, 2);
4418
+ }
4419
+ //#endregion
4420
+ //#region src/project-mcp/project-mcp.ts
4421
+ function read$1(root, path) {
4422
+ const absolute = join(root, path);
4423
+ return existsSync(absolute) ? readFileSync(absolute, "utf8") : void 0;
4424
+ }
4425
+ const moved = {
4426
+ target: "the target changed since the last projection — reconcile it into the golden set first",
4427
+ both: "both sides changed since the last projection — a three-way conflict for a person to settle",
4428
+ unknown: "no baseline says which side changed — compare the two by hand"
4429
+ };
4430
+ /** The worst direction among the diverged fields: one field the target moved is enough to hold back. */
4431
+ function heldBack(directions) {
4432
+ return [
4433
+ "both",
4434
+ "unknown",
4435
+ "target"
4436
+ ].find((direction) => directions.includes(direction));
4437
+ }
4438
+ /**
4439
+ * Projects the golden set into every enabled harness's MCP file. Only a server the golden set is
4440
+ * plainly ahead on is written — absent from the target, or changed on the golden side alone. A
4441
+ * target-side change is never overwritten: that is reconcile's, and needs a person.
4442
+ */
4443
+ function projectMcp({ root, git, write }) {
4444
+ const golden = parseGoldenSet(read$1(root, goldenSetPath));
4445
+ if (golden.kind !== "servers") return golden;
4446
+ const record = parseProjectionRecord(read$1(root, projectionRecordPath));
4447
+ const baseline = new McpBaseline({
4448
+ git,
4449
+ record
4450
+ });
4451
+ const rows = [];
4452
+ const entries = [];
4453
+ const plans = [];
4454
+ for (const config of mcpTargets(root)) {
4455
+ const source = read$1(root, config.path);
4456
+ const parsed = parseTarget(config, source);
4457
+ if (parsed.kind === "unreadable") {
4458
+ rows.push({
4459
+ target: config.path,
4460
+ server: "",
4461
+ action: "refuse",
4462
+ detail: "the target does not parse"
4463
+ });
4464
+ continue;
4465
+ }
4466
+ const plan = {
4467
+ config,
4468
+ source,
4469
+ created: source === void 0,
4470
+ servers: parsed.kind === "servers" ? parsed.servers : /* @__PURE__ */ new Map(),
4471
+ agreed: /* @__PURE__ */ new Map()
4472
+ };
4473
+ plans.push(plan);
4474
+ const dialect = mcpDialects[config.dialect];
4475
+ for (const [name, declared] of golden.servers) {
4476
+ const row = (action, detail) => rows.push({
4477
+ target: config.path,
4478
+ server: name,
4479
+ action,
4480
+ detail
4481
+ });
4482
+ const literal = credentialFields(declared)[0];
4483
+ if (literal) {
4484
+ row("refuse", `the golden set holds a literal credential at ${literal} — reference it as \${VAR} first`);
4485
+ continue;
4486
+ }
4487
+ const rendering = dialect.write(declared);
4488
+ if (rendering.kind === "refused") {
4489
+ row("refuse", `${rendering.field}: ${rendering.reason}`);
4490
+ continue;
4491
+ }
4492
+ const carried = plan.servers.get(name);
4493
+ if (!carried) {
4494
+ const next = plan.source === void 0 ? createFile(config, name, rendering.entry) : appendServer(config, plan.source, name, rendering.entry);
4495
+ apply(plan, name, declared, rendering.entry, next, plan.created ? "creates the file" : "appends the server", row, entries);
4496
+ continue;
4497
+ }
4498
+ const diverged = divergingFields(declared, carried, dialect.fields);
4499
+ if (!diverged.length) {
4500
+ plan.agreed.set(name, declared);
4501
+ continue;
4502
+ }
4503
+ const direction = heldBack(diverged.map((field) => baseline.directionOf(config, name, field, declared, carried)));
4504
+ if (direction) {
4505
+ row("skip", moved[direction]);
4506
+ continue;
4507
+ }
4508
+ const next = replaceServer(config, plan.source, name, rendering.entry);
4509
+ apply(plan, name, declared, rendering.entry, next, `replaces ${diverged.join(", ")}`, row, entries);
4510
+ }
4511
+ }
4512
+ if (write) {
4513
+ for (const plan of plans) if (plan.source !== void 0 && plan.source !== read$1(root, plan.config.path)) writeTarget(root, plan);
4514
+ writeRecord(root, record, plans);
4515
+ }
4516
+ return {
4517
+ kind: "planned",
4518
+ rows,
4519
+ entries,
4520
+ written: write
4521
+ };
4522
+ }
4523
+ /**
4524
+ * Accepts the new text only when it reads back as the golden server with every other server
4525
+ * untouched; anything else becomes an `edit` for a person, rather than a write this command
4526
+ * cannot vouch for.
4527
+ */
4528
+ function apply(plan, name, declared, entry, next, detail, row, entries) {
4529
+ const adding = !plan.servers.has(name);
4530
+ const accepted = next !== void 0 && readsBack(plan, name, declared, next);
4531
+ const action = accepted ? adding ? "add" : "update" : "edit";
4532
+ entries.push({
4533
+ target: plan.config.path,
4534
+ server: name,
4535
+ action,
4536
+ entry: renderEntry(plan.config, name, entry)
4537
+ });
4538
+ if (!accepted) {
4539
+ row("edit", adding ? "the file has no safe place to add it — apply the entry by hand" : "an in-place change here is applied by hand");
4540
+ return;
4541
+ }
4542
+ plan.source = next;
4543
+ plan.servers = parseTarget(plan.config, next).servers;
4544
+ plan.agreed.set(name, declared);
4545
+ row(action, detail);
4546
+ }
4547
+ function readsBack(plan, name, declared, next) {
4548
+ const parsed = parseTarget(plan.config, next);
4549
+ if (parsed.kind !== "servers") return false;
4550
+ const written = parsed.servers.get(name);
4551
+ const fields = mcpDialects[plan.config.dialect].fields;
4552
+ if (!written || divergingFields(declared, written, fields).length) return false;
4553
+ return [...plan.servers].every(([other, server]) => {
4554
+ if (other === name) return true;
4555
+ const kept = parsed.servers.get(other);
4556
+ return kept !== void 0 && JSON.stringify(kept) === JSON.stringify(server);
4557
+ });
4558
+ }
4559
+ function writeTarget(root, plan) {
4560
+ const absolute = join(root, plan.config.path);
4561
+ mkdirSync(dirname(absolute), { recursive: true });
4562
+ writeFileSync(absolute, plan.source);
4563
+ }
4564
+ /** What each target last agreed on, kept per server so a server this run did not touch keeps its entry. */
4565
+ function writeRecord(root, record, plans) {
4566
+ for (const plan of plans) {
4567
+ const servers = record.get(plan.config.path) ?? /* @__PURE__ */ new Map();
4568
+ for (const [name, server] of plan.agreed) servers.set(name, server);
4569
+ if (servers.size) record.set(plan.config.path, servers);
4570
+ }
4571
+ const absolute = join(root, projectionRecordPath);
4572
+ mkdirSync(dirname(absolute), { recursive: true });
4573
+ writeFileSync(absolute, formatProjectionRecord(record));
4574
+ }
4575
+ //#endregion
4576
+ //#region src/project-mcp/mcp.command.ts
4577
+ const mcpProjectCommand = command({
4578
+ name: "project",
4579
+ description: "Project the golden MCP server set into each enabled harness. A dry run unless --write; never overwrites a change made on the harness side.",
4580
+ options: {
4581
+ root: {
4582
+ description: "Repository or package directory. Defaults to the current directory.",
4583
+ type: z.optional(z.string())
4584
+ },
4585
+ write: {
4586
+ description: "Apply the plan and record what was projected. Without it nothing on disk changes.",
4587
+ type: z.optional(z.boolean())
4588
+ },
4589
+ format: {
4590
+ description: "Output format: toon (default), json, or text for a human-readable report.",
4591
+ type: z.optional(z.string()),
4592
+ default: "toon"
4593
+ }
4594
+ },
4595
+ run(args) {
4596
+ try {
4597
+ const format = parseFormat(args.format);
4598
+ const root = args.root ?? process.cwd();
4599
+ const write = args.write === true;
4600
+ const plan = projectMcp({
4601
+ root,
4602
+ git: new GitBridgeState(root),
4603
+ write
4604
+ });
4605
+ if (plan.kind === "unreadable") {
4606
+ const at = plan.position ? ` at line ${plan.position.line}, column ${plan.position.column}` : "";
4607
+ process.stderr.write(`error: ${goldenSetPath} does not parse${at}.\n`);
4608
+ return exitCodes.error;
4609
+ }
4610
+ if (plan.kind === "absent") {
4611
+ writeResult({
4612
+ golden: `0 servers — no golden set at ${goldenSetPath}`,
4613
+ mode: "nothing to project",
4614
+ actions: "0 changes",
4615
+ record: "not written"
4616
+ }, format);
4617
+ return exitCodes.success;
4618
+ }
4619
+ writeResult({
4620
+ golden: goldenSetPath,
4621
+ mode: write ? "written" : "dry run — nothing written; re-run with --write to apply",
4622
+ actions: plan.rows.length ? plan.rows : "0 changes — every enabled harness already carries the golden set",
4623
+ ...plan.entries.length ? { entries: plan.entries } : {},
4624
+ record: write ? projectionRecordPath : "not written — dry run"
4625
+ }, format);
4626
+ return exitCodes.success;
4627
+ } catch (error) {
4628
+ process.stderr.write(`error: ${error instanceof Error ? error.message : "MCP projection failed."}\n`);
4629
+ return exitCodes.error;
4630
+ }
4631
+ }
4632
+ });
4633
+ const mcpCommand = command({
4634
+ name: "mcp",
4635
+ description: "Work with the golden MCP server set at .agents/buddy-agent-harness/mcp.toml.",
4636
+ commands: [mcpProjectCommand, mcpReconcileCommand]
4637
+ });
4638
+ //#endregion
2638
4639
  //#region src/cli.ts
2639
4640
  const version = typeof __PACKAGE_VERSION__ !== "undefined" ? __PACKAGE_VERSION__ : JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
2640
4641
  function app() {
@@ -2642,7 +4643,7 @@ function app() {
2642
4643
  name: "buddy-agent-harness",
2643
4644
  version,
2644
4645
  description: "Initialize agent harness skill compatibility in consumer repositories."
2645
- }).command(initCommand).command(doctorCommand).command(depPluginsCommand).command(governanceCommand);
4646
+ }).command(initCommand).command(doctorCommand).command(mcpCommand).command(depPluginsCommand).command(referenceCommand).command(governanceCommand);
2646
4647
  }
2647
4648
  /**
2648
4649
  * The application boundary: argv in, exit code out — returned rather than written, so a caller that
@@ -2667,7 +4668,8 @@ function userScopeConfig(harness, home, env) {
2667
4668
  config: {
2668
4669
  path: ".claude.json",
2669
4670
  key: "mcpServers",
2670
- format: "json"
4671
+ format: "json",
4672
+ dialect: "claude-code"
2671
4673
  }
2672
4674
  };
2673
4675
  case "cursor": return {
@@ -2675,7 +4677,8 @@ function userScopeConfig(harness, home, env) {
2675
4677
  config: {
2676
4678
  path: ".cursor/mcp.json",
2677
4679
  key: "mcpServers",
2678
- format: "json"
4680
+ format: "json",
4681
+ dialect: "cursor"
2679
4682
  }
2680
4683
  };
2681
4684
  case "codex": return {
@@ -2683,7 +4686,8 @@ function userScopeConfig(harness, home, env) {
2683
4686
  config: {
2684
4687
  path: "config.toml",
2685
4688
  key: "mcp_servers",
2686
- format: "toml"
4689
+ format: "toml",
4690
+ dialect: "codex"
2687
4691
  }
2688
4692
  };
2689
4693
  case "copilot-cli": return {
@@ -2691,7 +4695,8 @@ function userScopeConfig(harness, home, env) {
2691
4695
  config: {
2692
4696
  path: "mcp-config.json",
2693
4697
  key: "mcpServers",
2694
- format: "json"
4698
+ format: "json",
4699
+ dialect: "claude-code"
2695
4700
  }
2696
4701
  };
2697
4702
  case "gemini-cli": return {
@@ -2700,6 +4705,7 @@ function userScopeConfig(harness, home, env) {
2700
4705
  path: ".gemini/settings.json",
2701
4706
  key: "mcpServers",
2702
4707
  format: "json",
4708
+ dialect: "gemini-cli",
2703
4709
  shared: true
2704
4710
  }
2705
4711
  };
@@ -2849,7 +4855,7 @@ function claudeLocalEntries(home, projectDir) {
2849
4855
  return entriesFromDocument("claude-code", "local", file, project, "mcpServers");
2850
4856
  }
2851
4857
  /** `enabledPlugins`, merged from global settings up through project-local settings, last write wins. */
2852
- function enabledPlugins(home, projectDir) {
4858
+ function enabledPlugins$1(home, projectDir) {
2853
4859
  const enabled = {};
2854
4860
  for (const file of [
2855
4861
  join(home, ".claude", "settings.json"),
@@ -2875,7 +4881,7 @@ function pluginEntries(home, projectDir) {
2875
4881
  const document = parseJsonWithComments(text);
2876
4882
  const installed = isRecord(document) ? document["plugins"] : void 0;
2877
4883
  if (!isRecord(installed)) return [];
2878
- const enabled = enabledPlugins(home, projectDir);
4884
+ const enabled = enabledPlugins$1(home, projectDir);
2879
4885
  const absoluteProject = resolve(projectDir);
2880
4886
  const entries = [];
2881
4887
  for (const [id, list] of Object.entries(installed)) {
@@ -2929,6 +4935,6 @@ function listMcpServers(options) {
2929
4935
  return entries;
2930
4936
  }
2931
4937
  //#endregion
2932
- export { activate, bridgeRepairs, buildDoctorReport, deprecatedManagedGovernancesDir, diagnoseBridges, diagnoseInstructions, diagnoseMcp, doctorCommand, doctorRepairs, doctorSkill, goldenSetPath, governanceCommand, governanceLayers, harnessCommand, harnessRegistry, initCommand, initializeHarnesses, instructionRepairs, listGovernances, listMcpServers, managedGovernancesDir, overrideLayers, parseGovernanceName, renderDoctorSkill, resolveGovernance, run };
4938
+ export { activate, bridgeRepairs, buildDoctorReport, deprecatedManagedGovernancesDir, diagnoseBridges, diagnoseInstructions, diagnoseMcp, doctorCommand, doctorRepairs, doctorSkill, goldenSetPath, governanceCommand, governanceLayers, harnessCommand, harnessRegistry, initCommand, initializeHarnesses, instructionRepairs, listGovernances, listMcpServers, listReferences, managedGovernancesDir, managedReferencesDir, overrideLayers, parseGovernanceName, parseReferenceName, referenceCommand, referenceLayers, renderDoctorSkill, resolveGovernance, resolveReference, run, searchReferences };
2933
4939
 
2934
4940
  //# sourceMappingURL=index.mjs.map