@mmerterden/multi-agent-pipeline 20.41.0 → 20.42.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 (103) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +1 -1
  3. package/README.tr.md +1 -1
  4. package/docs/ecosystem.md +45 -8
  5. package/docs/facts.json +7 -7
  6. package/docs/features.md +9 -4
  7. package/install/claude.mjs +34 -1
  8. package/install/templates/claude-hooks.json +12 -1
  9. package/manifest.json +106 -86
  10. package/package.json +3 -2
  11. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  12. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  13. package/pipeline/lib/args.mjs +131 -4
  14. package/pipeline/lib/bg-launch.mjs +5 -2
  15. package/pipeline/lib/credential-store.sh +11 -1
  16. package/pipeline/lib/hook-once.mjs +134 -0
  17. package/pipeline/lib/isotonic.mjs +73 -0
  18. package/pipeline/lib/low-disk.mjs +153 -0
  19. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  20. package/pipeline/lib/md2confluence-v3.py +8 -7
  21. package/pipeline/lib/model-dispatch.sh +26 -2
  22. package/pipeline/lib/normalize-text.mjs +135 -0
  23. package/pipeline/lib/outbound-gate.mjs +21 -3
  24. package/pipeline/lib/plan-todos.sh +17 -4
  25. package/pipeline/lib/redact.mjs +12 -3
  26. package/pipeline/lib/risky-settings.mjs +198 -0
  27. package/pipeline/lib/route-state.sh +1 -0
  28. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  29. package/pipeline/lib/session-usage.mjs +232 -0
  30. package/pipeline/lib/source-digest.mjs +211 -0
  31. package/pipeline/lib/tdd-evidence.mjs +250 -17
  32. package/pipeline/lib/untrusted-fence.mjs +132 -1
  33. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  34. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  35. package/pipeline/multi-agent-refs/features/doctor.md +51 -4
  36. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  37. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  38. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  39. package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
  40. package/pipeline/multi-agent-refs/help/en.md +1 -1
  41. package/pipeline/multi-agent-refs/help/tr.md +1 -1
  42. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  43. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
  44. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  45. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  46. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  47. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  48. package/pipeline/office/toolkit.json +1 -1
  49. package/pipeline/rules/outside-the-pipeline.md +1 -1
  50. package/pipeline/schemas/doctor-report.schema.json +47 -0
  51. package/pipeline/schemas/plan-todos.schema.json +29 -1
  52. package/pipeline/schemas/prefs.schema.json +63 -0
  53. package/pipeline/schemas/route-config.schema.json +51 -0
  54. package/pipeline/schemas/secret-patterns.json +17 -1
  55. package/pipeline/schemas/toolkit-path-params.json +15 -1
  56. package/pipeline/scripts/_cost-advise.mjs +357 -0
  57. package/pipeline/scripts/_cost-budget.mjs +78 -0
  58. package/pipeline/scripts/_cost.mjs +29 -0
  59. package/pipeline/scripts/_decode_text.py +107 -0
  60. package/pipeline/scripts/_guard-probe.mjs +406 -0
  61. package/pipeline/scripts/_guard_rules.py +206 -0
  62. package/pipeline/scripts/_memory-policy.mjs +1 -25
  63. package/pipeline/scripts/_retrieval.mjs +148 -2
  64. package/pipeline/scripts/_secret-scan.mjs +6 -1
  65. package/pipeline/scripts/_stack-routing.mjs +1 -0
  66. package/pipeline/scripts/_test-gaming.mjs +346 -0
  67. package/pipeline/scripts/agent-guard.py +8 -1
  68. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  69. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  70. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  71. package/pipeline/scripts/capture-resume.sh +9 -1
  72. package/pipeline/scripts/cost-analyze.mjs +66 -4
  73. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  74. package/pipeline/scripts/disk-cleaner.mjs +1418 -0
  75. package/pipeline/scripts/doctor.mjs +169 -44
  76. package/pipeline/scripts/evidence-gate.mjs +90 -0
  77. package/pipeline/scripts/gate-ledger.mjs +76 -21
  78. package/pipeline/scripts/gc-tmp.sh +5 -0
  79. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  80. package/pipeline/scripts/learnings-ledger.mjs +16 -12
  81. package/pipeline/scripts/note-agent-event.mjs +2 -0
  82. package/pipeline/scripts/note-mcp-failure.mjs +9 -2
  83. package/pipeline/scripts/note-skill-use.mjs +4 -1
  84. package/pipeline/scripts/pre-commit-check.sh +2 -2
  85. package/pipeline/scripts/pre-push-check.sh +8 -1
  86. package/pipeline/scripts/publish-staged.mjs +324 -0
  87. package/pipeline/scripts/route-learn.mjs +628 -0
  88. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  89. package/pipeline/scripts/scan-agent-config.sh +1 -1
  90. package/pipeline/scripts/statusline.mjs +309 -0
  91. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  92. package/pipeline/scripts/triage-memory.mjs +12 -4
  93. package/pipeline/scripts/uninstall.mjs +1 -0
  94. package/pipeline/skills/.skill-manifest.json +8 -4
  95. package/pipeline/skills/.skills-index.json +14 -3
  96. package/pipeline/skills/shared/README.md +5 -4
  97. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  98. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
  99. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  100. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
  101. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  102. package/pipeline/skills/skill-copies.json +4 -0
  103. package/pipeline/skills/skills-index.md +3 -2
@@ -37,7 +37,14 @@
37
37
  *
38
38
  * Usage:
39
39
  * doctor.mjs [--probe] [--json] [--explain] [--task-tools=yes|no]
40
+ * [--only <id,...>]
40
41
  * doctor.mjs --list-checks
42
+ *
43
+ * `--only` runs the named checks and reports only those (the layout checks
44
+ * still run first, since nothing resolves without them); an unknown id is a
45
+ * usage error that names the nearest one. `--json` prints the report whose
46
+ * shape schemas/doctor-report.schema.json fixes: schemaVersion, exit,
47
+ * selection and checks.
41
48
  */
42
49
 
43
50
  import {
@@ -63,7 +70,10 @@ import { prefsHosts, profileGaps } from "../lib/unattended-profile-check.mjs";
63
70
  import { xcodeSkillsStatus } from "../lib/xcode-plugin.mjs";
64
71
  import { hookReport, registrationGaps } from "../lib/hook-registration.mjs";
65
72
  import { PREFS_ENV, prefsFileIn } from "../lib/prefs-value.mjs";
73
+ import { check as lowDiskCheck } from "../lib/low-disk.mjs";
66
74
  import { exitOnHelp } from "../lib/cli-help.mjs";
75
+ import { didYouMean } from "../lib/args.mjs";
76
+ import { familyLine, loadFromManifest, schemaLoadByFamily } from "../lib/mcp-schema-load.mjs";
67
77
 
68
78
  exitOnHelp(import.meta.url);
69
79
 
@@ -85,6 +95,22 @@ const profileFlag = argv.find((a) => a.startsWith("--profile="));
85
95
  const PROFILE = profileFlag ? profileFlag.slice("--profile=".length) : "";
86
96
  const taskFlag = argv.find((a) => a.startsWith("--task-tools="));
87
97
  const TASK_TOOLS = taskFlag ? taskFlag.split("=")[1] : null;
98
+ const onlyAt = argv.findIndex((a) => a === "--only" || a.startsWith("--only="));
99
+ const ONLY_RAW =
100
+ onlyAt === -1
101
+ ? null
102
+ : argv[onlyAt].startsWith("--only=")
103
+ ? argv[onlyAt].slice("--only=".length)
104
+ : (argv[onlyAt + 1] ?? "");
105
+ const SELECTION =
106
+ ONLY_RAW === null
107
+ ? null
108
+ : ONLY_RAW.split(",")
109
+ .map((s) => s.trim())
110
+ .filter(Boolean);
111
+
112
+ // The report shape `--json` prints; schemas/doctor-report.schema.json.
113
+ const SCHEMA_VERSION = 1;
88
114
 
89
115
  // The id set. Kept here and in features/doctor.md, and smoke-doctor.sh asserts
90
116
  // the two are equal in BOTH directions: a check cannot ship without its entry,
@@ -109,6 +135,7 @@ const CHECK_IDS = [
109
135
  "task-tools",
110
136
  "mcp-registration",
111
137
  "mcp-surface",
138
+ "mcp-schema-load",
112
139
  "mcp-failures",
113
140
  "disk-space",
114
141
  "worktree-residue",
@@ -923,6 +950,11 @@ function checkTaskTools() {
923
950
  );
924
951
  }
925
952
 
953
+ // What checkMcpRegistration found, for checkMcpSchemaLoad: the registered
954
+ // toolkit entry and, under --probe, the tools/list it served.
955
+ let toolkitEntry = null;
956
+ let probedTools = null;
957
+
926
958
  function checkMcpRegistration() {
927
959
  // Registered is not the same as working, and the difference is what the user
928
960
  // actually hits: a half-extracted package in the npx cache left the server
@@ -966,6 +998,7 @@ function checkMcpRegistration() {
966
998
  JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
967
999
  JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" }),
968
1000
  ].join("\n");
1001
+ toolkitEntry = entry;
969
1002
  let served = 0;
970
1003
  let servedVersion = null;
971
1004
  let why = "";
@@ -983,7 +1016,10 @@ function checkMcpRegistration() {
983
1016
  const m = JSON.parse(line);
984
1017
  if (m.id === 1 && typeof m.result?.serverInfo?.version === "string")
985
1018
  servedVersion = m.result.serverInfo.version;
986
- if (m.id === 2 && m.result?.tools) served = m.result.tools.length;
1019
+ if (m.id === 2 && Array.isArray(m.result?.tools)) {
1020
+ served = m.result.tools.length;
1021
+ probedTools = m.result.tools;
1022
+ }
987
1023
  } catch {
988
1024
  /* the server may print non-JSON lines */
989
1025
  }
@@ -1085,6 +1121,51 @@ function checkMcpSurface() {
1085
1121
  );
1086
1122
  }
1087
1123
 
1124
+ // How much context the toolkit's tool list takes, per family, and what each
1125
+ // MCP_TOOLKIT_CAPS family would save. Measured from the tools/list --probe
1126
+ // served, or read from a `families` field in the tool-manifest.json beside a
1127
+ // toolkit registered by path. Tokens are bytes / 4, an estimate, and said to
1128
+ // be one. INFO above prefs.global.mcpSurface.schemaInfoAboveTokens (8000):
1129
+ // which families a repo needs is the user's call, not a health failure.
1130
+ function checkMcpSchemaLoad() {
1131
+ let load = probedTools ? schemaLoadByFamily(probedTools) : null;
1132
+ let from = "the served tools/list";
1133
+ if (!load && toolkitEntry) {
1134
+ const script = (toolkitEntry.args || []).find((a) => /index\.m?js$/.test(String(a)));
1135
+ if (script) {
1136
+ load = loadFromManifest(readJson(join(dirname(String(script)), "tool-manifest.json")));
1137
+ from = "the toolkit's tool-manifest.json";
1138
+ }
1139
+ }
1140
+ if (!load) {
1141
+ skip(
1142
+ "mcp-schema-load",
1143
+ toolkitEntry || PROBE
1144
+ ? "the toolkit served no tool list to measure"
1145
+ : "the tool-list size is measured with --probe",
1146
+ );
1147
+ return;
1148
+ }
1149
+ const raw = readJson(PREFS)?.global?.mcpSurface?.schemaInfoAboveTokens;
1150
+ const threshold = Number.isInteger(raw) && raw >= 0 ? raw : 8000;
1151
+ if (load.totalTokens < threshold) {
1152
+ ok("mcp-schema-load");
1153
+ return;
1154
+ }
1155
+ const caps = toolkitEntry?.env?.MCP_TOOLKIT_CAPS;
1156
+ const top = load.families
1157
+ .slice(0, 3)
1158
+ .map((f) => `${f.family} ~${f.tokens}`)
1159
+ .join(", ");
1160
+ report(
1161
+ "mcp-schema-load",
1162
+ "INFO",
1163
+ `the toolkit's ${load.totalTools} tools take ~${load.totalTokens} tokens of every turn (estimate, bytes/4, from ${from}); largest: ${top}${caps ? `; MCP_TOOLKIT_CAPS is ${caps}` : ""}`,
1164
+ "set MCP_TOOLKIT_CAPS in the toolkit's MCP entry to the families this repo uses (--explain lists each family's estimate)",
1165
+ load.families.map(familyLine),
1166
+ );
1167
+ }
1168
+
1088
1169
  // The local MCP failure log note-mcp-failure.sh writes. A missing sibling
1089
1170
  // leaves the check to SKIP rather than taking doctor down with it: doctor is
1090
1171
  // what a half-installed machine runs.
@@ -1109,6 +1190,18 @@ function checkMcpFailures() {
1109
1190
  return;
1110
1191
  }
1111
1192
  const summary = mcpFailureLog.failureSummary(mcpFailureLog.readFailures());
1193
+ const diskFull = summary.servers.filter((s) => s.classes["disk-full"]);
1194
+ if (diskFull.length) {
1195
+ const n = diskFull.reduce((sum, s) => sum + s.classes["disk-full"], 0);
1196
+ report(
1197
+ "mcp-failures",
1198
+ "INFO",
1199
+ `${n} MCP call(s) failed with disk-full in the last ${summary.hours} hours (${diskFull.map((s) => s.server).join(", ")})`,
1200
+ "run the disk-cleaner skill: node ~/.claude/scripts/disk-cleaner.mjs --dry-run, then --apply for the categories you choose",
1201
+ diskFull.map((s) => ({ server: s.server, diskFull: s.classes["disk-full"] })),
1202
+ );
1203
+ return;
1204
+ }
1112
1205
  const repeated = summary.servers.filter((s) => summary.repeated.includes(s.server));
1113
1206
  if (!repeated.length) {
1114
1207
  ok("mcp-failures");
@@ -1359,27 +1452,23 @@ function checkXcodeSkills() {
1359
1452
  ok("xcode-skills");
1360
1453
  }
1361
1454
 
1455
+ // One statfs call against the volume holding $HOME. Low means below
1456
+ // prefs.global.diskCleaner.lowDiskGb or lowDiskPercent (lib/low-disk.mjs owns
1457
+ // both defaults); the step names the disk-cleaner skill, which measures before
1458
+ // it deletes anything.
1362
1459
  function checkDiskSpace() {
1363
- let freeGb = null;
1364
- try {
1365
- const out = execFileSync("df", ["-k", HOME], { encoding: "utf8" });
1366
- const line = out.trim().split("\n").pop();
1367
- const cols = line.split(/\s+/);
1368
- const availKb = Number(cols[3]);
1369
- if (Number.isFinite(availKb)) freeGb = availKb / 1024 / 1024;
1370
- } catch {
1371
- /* df is not everywhere */
1372
- }
1373
- if (freeGb === null) {
1374
- skip("disk-space", "df did not report a usable figure on this host");
1460
+ const r = lowDiskCheck({ path: HOME });
1461
+ if (r.freeBytes == null) {
1462
+ skip("disk-space", "statfs did not report a usable figure on this host");
1375
1463
  return;
1376
1464
  }
1377
- if (freeGb < 2) {
1465
+ if (r.low) {
1466
+ const pct = r.totalBytes ? ((r.freeBytes / r.totalBytes) * 100).toFixed(1) : "?";
1378
1467
  report(
1379
1468
  "disk-space",
1380
1469
  "WARN",
1381
- `${freeGb.toFixed(1)} GB free on the volume holding $HOME; a worktree plus a build needs more`,
1382
- "free space before starting a run",
1470
+ `${(r.freeBytes / 1e9).toFixed(1)} GB (${pct}%) free on the volume holding $HOME, under the ${r.lowGb} GB / ${r.lowPercent}% floor; a worktree plus a build needs more`,
1471
+ "run the disk-cleaner skill: node ~/.claude/scripts/disk-cleaner.mjs --dry-run, then --apply for the categories you choose",
1383
1472
  );
1384
1473
  return;
1385
1474
  }
@@ -1585,6 +1674,13 @@ function checkServerProfile(resolved) {
1585
1674
  }
1586
1675
  }
1587
1676
 
1677
+ const KNOWN_FLAGS = ["probe", "json", "explain", "list-checks", "task-tools", "profile", "only"];
1678
+
1679
+ /** The --json document: schemas/doctor-report.schema.json. */
1680
+ function jsonReport(exit, checks) {
1681
+ return { schemaVersion: SCHEMA_VERSION, exit, selection: SELECTION, checks };
1682
+ }
1683
+
1588
1684
  function main() {
1589
1685
  if (LIST) {
1590
1686
  // Lists what THIS invocation would run, which is what the name promises
@@ -1598,15 +1694,30 @@ function main() {
1598
1694
  }
1599
1695
  const unknown = argv.filter(
1600
1696
  (a) =>
1601
- a.startsWith("--") && !/^--(probe|json|explain|list-checks|task-tools=|profile=)/.test(a),
1697
+ a.startsWith("--") &&
1698
+ !/^--(probe|json|explain|list-checks|task-tools=|profile=|only(=|$))/.test(a),
1602
1699
  );
1603
1700
  if (unknown.length) {
1701
+ const flag = unknown[0].slice(2).split("=")[0];
1702
+ const hint = didYouMean(flag, KNOWN_FLAGS, { prefix: "--" });
1604
1703
  process.stderr.write(
1605
- `usage: doctor.mjs [--probe] [--json] [--explain] [--task-tools=yes|no] [--profile=server] | --list-checks\n`,
1704
+ `${hint ? `unknown option ${unknown[0]}${hint}\n` : ""}usage: doctor.mjs [--probe] [--json] [--explain] [--task-tools=yes|no] [--profile=server] [--only <id,...>] | --list-checks\n`,
1606
1705
  );
1607
1706
  process.exitCode = 3;
1608
1707
  return;
1609
1708
  }
1709
+ if (SELECTION !== null) {
1710
+ const known = [...CHECK_IDS, ...SERVER_CHECK_IDS];
1711
+ const bad = SELECTION.filter((id) => !known.includes(id));
1712
+ if (!SELECTION.length || bad.length) {
1713
+ const hint = bad.length ? didYouMean(bad[0], known) : "";
1714
+ process.stderr.write(
1715
+ `usage: --only takes check ids from --list-checks${bad.length ? ` (unknown: ${bad.join(", ")}${hint})` : ""}\n`,
1716
+ );
1717
+ process.exitCode = 3;
1718
+ return;
1719
+ }
1720
+ }
1610
1721
  if (PROFILE && PROFILE !== "server") {
1611
1722
  process.stderr.write(`usage: --profile takes "server" (got "${PROFILE}")\n`);
1612
1723
  process.exitCode = 3;
@@ -1627,7 +1738,7 @@ function main() {
1627
1738
  // that never ran.
1628
1739
  const line = results[results.length - 1];
1629
1740
  if (JSON_OUT) {
1630
- process.stdout.write(`${JSON.stringify({ exit: 4, checks: results }, null, 2)}\n`);
1741
+ process.stdout.write(`${JSON.stringify(jsonReport(4, results), null, 2)}\n`);
1631
1742
  } else {
1632
1743
  process.stdout.write(`${line.severity} ${line.id} - ${line.problem} - ${line.step}\n`);
1633
1744
  process.stdout.write(
@@ -1638,30 +1749,44 @@ function main() {
1638
1749
  return;
1639
1750
  }
1640
1751
 
1641
- checkInstallVersion();
1642
- checkUpdatePolicy();
1643
- checkScriptSurface();
1644
- checkSkillSiblings();
1645
- checkStateWritable();
1646
- checkPrefsValid();
1647
- checkIdentity();
1648
- checkHookCoverage();
1649
- checkHookReachability();
1650
- checkGuardRules();
1651
- checkCredentials(credentialInventory());
1652
- checkStoreReference();
1653
- checkEmbeddedCredentials();
1654
- checkTaskTools();
1655
- checkMcpRegistration();
1656
- checkMcpSurface();
1657
- checkMcpFailures();
1658
- checkDiskSpace();
1659
- checkWorktreeResidue();
1660
- checkUsageReport();
1661
- checkUsageRegister();
1662
- checkFreeModels();
1663
- checkXcodeSkills();
1664
- if (PROFILE === "server") checkServerProfile(resolved);
1752
+ // Each step names the ids it reports, so --only can leave out the work of
1753
+ // a check nobody asked for. A step that feeds another (the registration
1754
+ // probe feeds the schema load) lists both.
1755
+ const steps = [
1756
+ [["install-version"], checkInstallVersion],
1757
+ [["update-policy"], checkUpdatePolicy],
1758
+ [["script-surface"], checkScriptSurface],
1759
+ [["skill-siblings"], checkSkillSiblings],
1760
+ [["state-writable"], checkStateWritable],
1761
+ [["prefs-valid"], checkPrefsValid],
1762
+ [["identity"], checkIdentity],
1763
+ [["hook-coverage"], checkHookCoverage],
1764
+ [["hook-reachability"], checkHookReachability],
1765
+ [["guard-rules"], checkGuardRules],
1766
+ [["credential-mapping", "credential-liveness"], () => checkCredentials(credentialInventory())],
1767
+ [["store-reference"], checkStoreReference],
1768
+ [["embedded-credentials"], checkEmbeddedCredentials],
1769
+ [["task-tools"], checkTaskTools],
1770
+ [["mcp-registration", "mcp-schema-load"], checkMcpRegistration],
1771
+ [["mcp-surface"], checkMcpSurface],
1772
+ [["mcp-schema-load"], checkMcpSchemaLoad],
1773
+ [["mcp-failures"], checkMcpFailures],
1774
+ [["disk-space"], checkDiskSpace],
1775
+ [["worktree-residue"], checkWorktreeResidue],
1776
+ [["usage-report"], checkUsageReport],
1777
+ [["usage-register"], checkUsageRegister],
1778
+ [["free-models"], checkFreeModels],
1779
+ [["xcode-skills"], checkXcodeSkills],
1780
+ ];
1781
+ if (PROFILE === "server") steps.push([SERVER_CHECK_IDS, () => checkServerProfile(resolved)]);
1782
+ for (const [ids, run] of steps) {
1783
+ if (SELECTION === null || ids.some((id) => SELECTION.includes(id))) run();
1784
+ }
1785
+ if (SELECTION !== null) {
1786
+ const keep = results.filter((r) => SELECTION.includes(r.id));
1787
+ results.length = 0;
1788
+ results.push(...keep);
1789
+ }
1665
1790
 
1666
1791
  const blocked = results.filter((r) => r.severity === "BLOCK");
1667
1792
  const warned = results.filter((r) => r.severity === "WARN");
@@ -1669,7 +1794,7 @@ function main() {
1669
1794
  const code = blocked.length ? 2 : warned.length ? 1 : 0;
1670
1795
 
1671
1796
  if (JSON_OUT) {
1672
- process.stdout.write(`${JSON.stringify({ exit: code, checks: results }, null, 2)}\n`);
1797
+ process.stdout.write(`${JSON.stringify(jsonReport(code, results), null, 2)}\n`);
1673
1798
  process.exitCode = code;
1674
1799
  return;
1675
1800
  }
@@ -50,6 +50,26 @@
50
50
  // --xcresult <bundle> / --xcresult-json <file>
51
51
  // where to read test counts when the log prints none
52
52
  // (Gradle on success, xcodebuild -quiet).
53
+ // --command <line> / --command-file <path>
54
+ // test claim: the command the tests ran with. A narrowed
55
+ // run (a name filter or skip list, a single test file or
56
+ // test id, --passWithNoTests; _test-gaming.mjs
57
+ // narrowedRun has the per-runner list) fails the pass
58
+ // with `gaming.kind: "narrowed-run"`: a green subset says
59
+ // nothing about the tests it left out. Without a command
60
+ // and with the quality gates active, a runner's own
61
+ // output that names a filter (jest, pytest) fails it too.
62
+ // --repo <dir> build/test claims: the work tree the evidence speaks
63
+ // for (the run's worktreePath when the quality gates are
64
+ // active). The evidence has to be on the source as it is
65
+ // now: with --ran-on, the source digest
66
+ // (lib/source-digest.mjs) taken right before the run has
67
+ // to equal the current one; without it, no uncommitted
68
+ // file may be newer than the evidence file. Either way an
69
+ // edit after the run fails the pass as stale.
70
+ // --ran-on <digest> the digest `source-digest.mjs --repo <dir>` printed
71
+ // before the build or test command started. A tree git
72
+ // cannot digest fails the claim when this is given.
53
73
  // --state <path> agent-state.json for the gate ledger. While the quality
54
74
  // gates are active (MULTI_AGENT_UNATTENDED=1, or a run
55
75
  // in autopilot mode) every verdict is appended to
@@ -76,7 +96,9 @@ import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
76
96
  import { fileURLToPath } from "node:url";
77
97
 
78
98
  import { ATTENDED_RECORDED, gateContext } from "./gate-ledger.mjs";
99
+ import { narrowedLog, narrowedRun } from "./_test-gaming.mjs";
79
100
  import { parseArgs as parseArgv } from "../lib/args.mjs";
101
+ import { sourceDigest } from "../lib/source-digest.mjs";
80
102
  import { exitOnHelp } from "../lib/cli-help.mjs";
81
103
 
82
104
  exitOnHelp(import.meta.url);
@@ -399,6 +421,74 @@ if (JSON_CLAIMS.has(claim)) {
399
421
  gateManual(claim, evidence, body, args["require-screenshot"] === true);
400
422
  }
401
423
 
424
+ /** The test command from --command or --command-file, or null when neither is given. */
425
+ function testCommand() {
426
+ if (typeof args.command === "string") return args.command;
427
+ if (args["command-file"] === undefined) return null;
428
+ try {
429
+ return readFileSync(String(args["command-file"]), "utf8");
430
+ } catch (err) {
431
+ fail(`${claim} --command-file unreadable: ${err.message} (default-FAIL)`);
432
+ }
433
+ }
434
+
435
+ /** The work tree whose source the evidence must match, or null to skip the check. */
436
+ function sourceRepo(ranOn) {
437
+ if (typeof args.repo === "string") return args.repo;
438
+ const ctx = gateContext({ statePath: ledgerState });
439
+ const wt = ctx.state?.worktreePath;
440
+ if ((ctx.active || ranOn !== null) && typeof wt === "string" && existsSync(wt)) return wt;
441
+ return ranOn !== null ? process.cwd() : null;
442
+ }
443
+
444
+ if (claim === "test") {
445
+ const command = testCommand();
446
+ const narrowed =
447
+ command !== null
448
+ ? narrowedRun(command)
449
+ : gateContext({ statePath: ledgerState }).active
450
+ ? narrowedLog(body)
451
+ : null;
452
+ if (narrowed?.narrowed) {
453
+ fail(
454
+ `${claim} evidence comes from a narrowed run (${narrowed.reasons.join(", ")}); a green subset says nothing about the tests it left out, so run the whole suite`,
455
+ {
456
+ gaming: {
457
+ kind: "narrowed-run",
458
+ runner: narrowed.runner ?? null,
459
+ reasons: narrowed.reasons,
460
+ },
461
+ },
462
+ );
463
+ }
464
+ }
465
+
466
+ if (claim === "build" || claim === "test") {
467
+ const ranOn = typeof args["ran-on"] === "string" ? args["ran-on"] : null;
468
+ const repoDir = sourceRepo(ranOn);
469
+ const digest = repoDir ? sourceDigest(repoDir) : null;
470
+ if (ranOn !== null && !digest) {
471
+ fail(`${claim} --ran-on given, but git cannot digest ${repoDir} to compare (default-FAIL)`);
472
+ }
473
+ if (ranOn !== null && digest.digest !== ranOn) {
474
+ fail(
475
+ `${claim} evidence is stale: the source changed after the run started (ran on ${ranOn}, now ${digest.digest}); run it again`,
476
+ { sourceDigest: digest.digest },
477
+ );
478
+ }
479
+ if (
480
+ ranOn === null &&
481
+ digest &&
482
+ digest.newestEditMs > statSync(evidence).mtimeMs + STAGE_SLACK_MS
483
+ ) {
484
+ fail(
485
+ `${claim} evidence is stale: a source file was edited after this evidence was written (${new Date(digest.newestEditMs).toISOString()}); run it again`,
486
+ { sourceDigest: digest.digest },
487
+ );
488
+ }
489
+ if (digest) verdictExtra = { ...verdictExtra, sourceDigest: digest.digest };
490
+ }
491
+
402
492
  const notApplicable = adapter !== null && adapter.applicable === false;
403
493
 
404
494
  const successRe = userRegExp(args["success-pattern"], DEFAULT_MARKERS[claim].success, "success");
@@ -13,6 +13,14 @@
13
13
  * required gate for that HEAD passed. A gate the run skipped leaves no entry,
14
14
  * and a missing entry blocks the commit the same way a failing one does.
15
15
  *
16
+ * The build and test gates (DIGEST_BOUND) also record `sourceDigest`, the
17
+ * digest of the working tree's content (lib/source-digest.mjs). An edit made
18
+ * after the build leaves HEAD where it was, so for those gates the digest
19
+ * decides: an entry whose digest is the tree's current one counts whatever
20
+ * HEAD it names, and one whose digest differs is stale, which blocks the
21
+ * commit like a missing entry and is reported as `stale`. An entry without a
22
+ * digest, or a tree git cannot digest, is judged by sha as before.
23
+ *
16
24
  * Entries are written while the quality gates are active (lib/unattended.mjs,
17
25
  * gatesActive): MULTI_AGENT_UNATTENDED=1, or a run in autopilot mode. A run
18
26
  * that is neither writes only the gates in ATTENDED_RECORDED, each entry marked
@@ -69,6 +77,7 @@ import { dirname, join } from "node:path";
69
77
  import { decisionEntry, withDecision } from "../lib/decisions.mjs";
70
78
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
71
79
  import { readRegularFile, readRegularJson } from "../lib/regular-file.mjs";
80
+ import { sourceDigest } from "../lib/source-digest.mjs";
72
81
  import { writeFileSafe } from "../lib/safe-write.mjs";
73
82
  import { globalPref } from "../lib/prefs-value.mjs";
74
83
  import { modeEntry } from "../lib/run-completion.mjs";
@@ -137,6 +146,35 @@ export function trailingFailures(gates, gate) {
137
146
 
138
147
  export const ATTENDED_COMMIT_EVIDENCE = ["evidence-gate/build", "evidence-gate/test"];
139
148
 
149
+ /** Gates whose entries carry the working tree's source digest. */
150
+ export const DIGEST_BOUND = new Set(["evidence-gate/build", "evidence-gate/test"]);
151
+
152
+ /** The digest of the tree at `dir`, or null when it cannot be read. */
153
+ export function currentDigestOf(dir) {
154
+ return sourceDigest(dir)?.digest ?? null;
155
+ }
156
+
157
+ /**
158
+ * Latest entry per gate among those that speak for the current content: a
159
+ * digest-bound entry with a digest is matched on the digest when the current
160
+ * one is known, every other entry on its sha. Also names the digest-bound
161
+ * gates whose only candidates were recorded on other content.
162
+ */
163
+ function evidenceFor(gates, { sha, currentDigest = null, sameTree = null }) {
164
+ const onSha = (s) => s === sha || (sameTree ? sameTree(s) : false);
165
+ const byDigest = (e) =>
166
+ DIGEST_BOUND.has(e.gate) && Boolean(currentDigest) && typeof e.sourceDigest === "string";
167
+ const latest = latestWhere(gates, (e) =>
168
+ byDigest(e) ? e.sourceDigest === currentDigest : onSha(e.sha),
169
+ );
170
+ const stale = new Set();
171
+ for (const e of Array.isArray(gates) ? gates : []) {
172
+ if (e && byDigest(e) && e.sourceDigest !== currentDigest && !latest.has(e.gate))
173
+ stale.add(e.gate);
174
+ }
175
+ return { latest, stale };
176
+ }
177
+
140
178
  /** Asked for too once the run is in its commit phase: the review verdict. */
141
179
  export const ATTENDED_REVIEW_EVIDENCE = "review-decision";
142
180
  export const ATTENDED_REVIEW_FROM_PHASE = 4;
@@ -159,16 +197,14 @@ export const ATTENDED_COMMIT_MODES = ["off", "warn", "block", "auto"];
159
197
  * @param {string} sha
160
198
  * @returns {string[]}
161
199
  */
162
- export function attendedEvidenceGaps(state, sha, { sameTree } = {}) {
200
+ export function attendedEvidenceGaps(state, sha, { sameTree, currentDigest = null } = {}) {
163
201
  const wanted = [...ATTENDED_COMMIT_EVIDENCE];
164
202
  if (Number(state?.currentPhase) >= ATTENDED_REVIEW_FROM_PHASE)
165
203
  wanted.push(ATTENDED_REVIEW_EVIDENCE);
166
204
  const asked = (Array.isArray(state?.gates) ? state.gates : []).filter((e) =>
167
205
  wanted.includes(e?.gate),
168
206
  );
169
- const latest = sameTree
170
- ? latestByGateWhere(asked, (s) => s === sha || sameTree(s))
171
- : latestByGate(asked, sha);
207
+ const { latest } = evidenceFor(asked, { sha, currentDigest, sameTree });
172
208
  return wanted.filter((g) => {
173
209
  const e = latest.get(g);
174
210
  return !e || !PASSING.has(e.verdict);
@@ -494,11 +530,13 @@ export async function record(
494
530
  const wt = ctx.state?.worktreePath;
495
531
  shaRepo = typeof wt === "string" && existsSync(wt) ? wt : process.cwd();
496
532
  }
533
+ const digest = DIGEST_BOUND.has(gate) ? currentDigestOf(shaRepo) : null;
497
534
  const entry = {
498
535
  gate,
499
536
  verdict,
500
537
  at: new Date().toISOString(),
501
538
  sha: headSha(shaRepo),
539
+ ...(digest ? { sourceDigest: digest } : {}),
502
540
  detail: detail && typeof detail === "object" ? detail : { value: detail },
503
541
  ...(attended ? { attended: true } : {}),
504
542
  };
@@ -613,9 +651,14 @@ export function latestByGate(gates, sha) {
613
651
 
614
652
  /** latestByGate over the entries whose sha `accept` takes. */
615
653
  export function latestByGateWhere(gates, accept) {
654
+ return latestWhere(gates, (e) => accept(e.sha));
655
+ }
656
+
657
+ /** Latest entry per gate over the entries `accept` takes. */
658
+ function latestWhere(gates, accept) {
616
659
  const out = new Map();
617
660
  (Array.isArray(gates) ? gates : []).forEach((e, i) => {
618
- if (!e || typeof e !== "object" || typeof e.gate !== "string" || !accept(e.sha)) return;
661
+ if (!e || typeof e !== "object" || typeof e.gate !== "string" || !accept(e)) return;
619
662
  const prev = out.get(e.gate);
620
663
  const t = Date.parse(e.at) || 0;
621
664
  if (!prev || t > prev.t || (t === prev.t && i > prev.i)) out.set(e.gate, { e, t, i });
@@ -628,24 +671,31 @@ export function latestByGateWhere(gates, accept) {
628
671
  *
629
672
  * @param {object} state
630
673
  * @param {string} sha
631
- * @param {{mandatory?: string[]}} [opts]
632
- * @returns {{ok: boolean, missing: string[], failing: object[], sha: string}}
674
+ * @param {{mandatory?: string[], currentDigest?: string|null}} [opts]
675
+ * @returns {{ok: boolean, missing: string[], failing: object[], stale: string[], sha: string}}
633
676
  */
634
- export function checkCommit(state, sha, { mandatory = MANDATORY_AT_COMMIT } = {}) {
677
+ export function checkCommit(
678
+ state,
679
+ sha,
680
+ { mandatory = MANDATORY_AT_COMMIT, currentDigest = null } = {},
681
+ ) {
635
682
  // An entry written while the gates were off says what an attended run
636
683
  // observed; it never stands in for a verdict the unattended contract requires.
637
684
  const gated = (Array.isArray(state?.gates) ? state.gates : []).filter(
638
685
  (e) => !(e && e.attended === true),
639
686
  );
640
- const latest = latestByGate(gated, sha);
687
+ const { latest, stale: staleSet } = evidenceFor(gated, { sha, currentDigest });
641
688
  const missing = [];
642
689
  const failing = [];
690
+ const stale = [];
643
691
  for (const g of mandatory) {
644
692
  const e = latest.get(g);
645
- if (!e) missing.push(g);
693
+ if (!e && staleSet.has(g)) stale.push(g);
694
+ else if (!e) missing.push(g);
646
695
  else if (!PASSING.has(e.verdict)) failing.push(e);
647
696
  }
648
- return { ok: missing.length === 0 && failing.length === 0, missing, failing, sha };
697
+ const ok = missing.length === 0 && failing.length === 0 && stale.length === 0;
698
+ return { ok, missing, failing, stale, sha };
649
699
  }
650
700
 
651
701
  // ---------------------------------------------------------------------------
@@ -705,23 +755,25 @@ async function main(argv) {
705
755
  return 3;
706
756
  }
707
757
  const state = readJson(path);
708
- const sha =
709
- opts.sha ||
710
- headSha(
711
- opts.repo || !(state?.worktreePath && existsSync(state.worktreePath))
712
- ? repo
713
- : state.worktreePath,
714
- );
758
+ const tree =
759
+ opts.repo || !(state?.worktreePath && existsSync(state.worktreePath))
760
+ ? repo
761
+ : state.worktreePath;
762
+ const sha = opts.sha || headSha(tree);
715
763
  if (!state || !sha) {
716
764
  process.stderr.write(`gate-ledger: cannot read ${path} or resolve HEAD\n`);
717
765
  return 3;
718
766
  }
719
- const r = checkCommit(state, sha);
767
+ const r = checkCommit(state, sha, { currentDigest: currentDigestOf(tree) });
720
768
  if (opts.json) writeFileSync(1, `${JSON.stringify({ statePath: path, ...r }, null, 2)}\n`);
721
769
  if (!r.ok) {
722
770
  const lines = [
723
771
  `gate-ledger: the unattended commit on ${sha.slice(0, 12)} is not backed by the gate ledger (${path})`,
724
772
  ...r.missing.map((g) => ` missing: ${g} has no entry for this HEAD`),
773
+ ...r.stale.map(
774
+ (g) =>
775
+ ` stale: ${g} was recorded on other source; a file changed after it ran, so run it again`,
776
+ ),
725
777
  ...r.failing.map(
726
778
  (e) =>
727
779
  ` failing: ${e.gate} -> ${e.verdict}${e.detail?.reason ? ` (${e.detail.reason})` : ""}`,
@@ -765,7 +817,10 @@ async function main(argv) {
765
817
  const bound =
766
818
  (session && state.hostSessionId === session) || (launched && state.sessionId === launched);
767
819
  const gateMode = effectiveCommitMode(pref, Boolean(bound));
768
- const missing = attendedEvidenceGaps(state, sha, { sameTree: sameTreeAs(repo) });
820
+ const missing = attendedEvidenceGaps(state, sha, {
821
+ sameTree: sameTreeAs(repo),
822
+ currentDigest: currentDigestOf(repo),
823
+ });
769
824
  if (opts.json)
770
825
  writeFileSync(1, `${JSON.stringify({ statePath: path, sha, gateMode, missing })}\n`);
771
826
  if (!missing.length) return 0;
@@ -773,7 +828,7 @@ async function main(argv) {
773
828
  writeFileSync(
774
829
  2,
775
830
  `${[
776
- `pre-commit-check: ${verb}: the run's gate ledger (${path}) has no passing ${missing.join(" / ")} for HEAD ${sha.slice(0, 12)}.`,
831
+ `pre-commit-check: ${verb}: the run's gate ledger (${path}) has no passing ${missing.join(" / ")} for HEAD ${sha.slice(0, 12)} and the source as it is now; an edit after the build or the tests makes their verdict stale.`,
777
832
  " Run the build and the tests through evidence-gate.mjs (Phase 2 Gate 1), and in the commit phase the review verdict (review-decision-gate.mjs), so the commit rests on recorded evidence.",
778
833
  gateMode === "block"
779
834
  ? " This session drives the run, so the commit waits for the evidence; prefs.global.attendedCommitGate.mode warn lets it through."
@@ -123,6 +123,11 @@ NAME_ARGS=(
123
123
  -o \( -name '*-wiki' -type d \)
124
124
  )
125
125
 
126
+ # `multi-agent-*` also covers lib/hook-once.mjs's claim directory
127
+ # (multi-agent-hook-once-<uid>). Its claims prune themselves after ten
128
+ # minutes; a sweep here removes the directory once no hook has claimed in it
129
+ # for the grace window.
130
+ #
126
131
  # `complaint-analysis-*` needs its own entry: find matches the basename against
127
132
  # the whole glob, so `analysis-*` never matched it. Same for the other three,
128
133
  # which were writing into $ROOT with nothing sweeping them (phase-0-init.md,
@@ -0,0 +1,3 @@
1
+ {
2
+ "holes": []
3
+ }