@mmerterden/multi-agent-pipeline 20.41.0 → 20.43.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 (114) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +8 -6
  3. package/README.tr.md +8 -6
  4. package/docs/architecture.md +3 -3
  5. package/docs/ecosystem.md +50 -13
  6. package/docs/facts.json +9 -9
  7. package/docs/features.md +9 -4
  8. package/install/claude.mjs +34 -1
  9. package/install/templates/claude-hooks.json +12 -1
  10. package/manifest.json +117 -90
  11. package/package.json +3 -2
  12. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  13. package/pipeline/commands/multi-agent/clean-disk/SKILL.md +134 -0
  14. package/pipeline/commands/multi-agent/review-priority/SKILL.md +143 -0
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/commands/multi-agent/sync/SKILL.md +4 -4
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/credential-store.sh +11 -1
  20. package/pipeline/lib/hook-once.mjs +134 -0
  21. package/pipeline/lib/isotonic.mjs +73 -0
  22. package/pipeline/lib/low-disk.mjs +154 -0
  23. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  24. package/pipeline/lib/md2confluence-v3.py +8 -7
  25. package/pipeline/lib/model-dispatch.sh +26 -2
  26. package/pipeline/lib/normalize-text.mjs +135 -0
  27. package/pipeline/lib/outbound-gate.mjs +21 -3
  28. package/pipeline/lib/plan-todos.sh +17 -4
  29. package/pipeline/lib/redact.mjs +12 -3
  30. package/pipeline/lib/risky-settings.mjs +198 -0
  31. package/pipeline/lib/route-state.sh +1 -0
  32. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  33. package/pipeline/lib/session-usage.mjs +232 -0
  34. package/pipeline/lib/source-digest.mjs +211 -0
  35. package/pipeline/lib/tdd-evidence.mjs +250 -17
  36. package/pipeline/lib/untrusted-fence.mjs +132 -1
  37. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  38. package/pipeline/multi-agent-refs/cross-cli-contract.md +5 -5
  39. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  40. package/pipeline/multi-agent-refs/features/doctor.md +66 -4
  41. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  42. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  43. package/pipeline/multi-agent-refs/features/review-priority.md +123 -0
  44. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  45. package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
  46. package/pipeline/multi-agent-refs/help/en.md +3 -1
  47. package/pipeline/multi-agent-refs/help/tr.md +3 -1
  48. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  49. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
  50. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  51. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  52. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  53. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  54. package/pipeline/multi-agent-refs/review-priority/rules/example.md +137 -0
  55. package/pipeline/office/toolkit.json +1 -1
  56. package/pipeline/rules/outside-the-pipeline.md +1 -1
  57. package/pipeline/schemas/doctor-report.schema.json +47 -0
  58. package/pipeline/schemas/plan-todos.schema.json +29 -1
  59. package/pipeline/schemas/prefs.schema.json +81 -0
  60. package/pipeline/schemas/route-config.schema.json +51 -0
  61. package/pipeline/schemas/secret-patterns.json +17 -1
  62. package/pipeline/schemas/toolkit-path-params.json +15 -1
  63. package/pipeline/scripts/_cost-advise.mjs +357 -0
  64. package/pipeline/scripts/_cost-budget.mjs +78 -0
  65. package/pipeline/scripts/_cost.mjs +29 -0
  66. package/pipeline/scripts/_decode_text.py +107 -0
  67. package/pipeline/scripts/_guard-probe.mjs +406 -0
  68. package/pipeline/scripts/_guard_rules.py +206 -0
  69. package/pipeline/scripts/_memory-policy.mjs +1 -25
  70. package/pipeline/scripts/_retrieval.mjs +148 -2
  71. package/pipeline/scripts/_secret-scan.mjs +6 -1
  72. package/pipeline/scripts/_stack-routing.mjs +1 -0
  73. package/pipeline/scripts/_test-gaming.mjs +346 -0
  74. package/pipeline/scripts/agent-guard.py +8 -1
  75. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  76. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  77. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  78. package/pipeline/scripts/capture-resume.sh +9 -1
  79. package/pipeline/scripts/cost-analyze.mjs +66 -4
  80. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  81. package/pipeline/scripts/disk-cleaner.mjs +1432 -0
  82. package/pipeline/scripts/doctor.mjs +302 -47
  83. package/pipeline/scripts/evidence-gate.mjs +90 -0
  84. package/pipeline/scripts/gate-ledger.mjs +76 -21
  85. package/pipeline/scripts/gc-tmp.sh +5 -0
  86. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  87. package/pipeline/scripts/learnings-ledger.mjs +16 -12
  88. package/pipeline/scripts/note-agent-event.mjs +2 -0
  89. package/pipeline/scripts/note-mcp-failure.mjs +9 -2
  90. package/pipeline/scripts/note-skill-use.mjs +4 -1
  91. package/pipeline/scripts/pre-commit-check.sh +2 -2
  92. package/pipeline/scripts/pre-push-check.sh +8 -1
  93. package/pipeline/scripts/priority-review.mjs +912 -0
  94. package/pipeline/scripts/publish-staged.mjs +324 -0
  95. package/pipeline/scripts/route-learn.mjs +628 -0
  96. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  97. package/pipeline/scripts/scan-agent-config.sh +1 -1
  98. package/pipeline/scripts/statusline.mjs +309 -0
  99. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  100. package/pipeline/scripts/triage-memory.mjs +12 -4
  101. package/pipeline/scripts/uninstall.mjs +1 -0
  102. package/pipeline/skills/.skill-manifest.json +17 -5
  103. package/pipeline/skills/.skills-index.json +36 -3
  104. package/pipeline/skills/shared/README.md +9 -6
  105. package/pipeline/skills/shared/core/multi-agent-clean-disk/SKILL.md +34 -0
  106. package/pipeline/skills/shared/core/multi-agent-review-priority/SKILL.md +36 -0
  107. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +4 -4
  108. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  109. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +111 -0
  110. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  111. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1432 -0
  112. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  113. package/pipeline/skills/skill-copies.json +4 -0
  114. package/pipeline/skills/skills-index.md +5 -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 {
@@ -51,7 +58,7 @@ import {
51
58
  } from "node:fs";
52
59
  import { basename, join, dirname } from "node:path";
53
60
  import { homedir } from "node:os";
54
- import { execFileSync } from "node:child_process";
61
+ import { execFileSync, spawnSync } from "node:child_process";
55
62
  import { fileURLToPath, pathToFileURL } from "node:url";
56
63
  import { runMain } from "../lib/fatal.mjs";
57
64
  import { hostCommand } from "../lib/user-facing.mjs";
@@ -62,8 +69,11 @@ import {
62
69
  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
- import { PREFS_ENV, prefsFileIn } from "../lib/prefs-value.mjs";
72
+ import { PREFS_ENV, globalPref, 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 ${hostCommand("clean-disk", HERE)}: it measures every category first and deletes only the ones 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,31 +1452,156 @@ function checkXcodeSkills() {
1359
1452
  ok("xcode-skills");
1360
1453
  }
1361
1454
 
1362
- function checkDiskSpace() {
1363
- let freeGb = null;
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). What could be freed comes from the newest disk-cleaner dry
1458
+ // run under ~/.claude/logs/disk-cleaner, never from a fresh measurement: a
1459
+ // full measurement walks every cache and would make doctor slow. --probe runs
1460
+ // one under a time cap; a timeout is reported, never a failure. Nothing here
1461
+ // deletes anything.
1462
+ const DISK_REPORT_MAX_AGE_MS = 24 * 3_600_000;
1463
+ const DISK_PROBE_TIMEOUT_MS = 60_000;
1464
+ const DISK_TOP = 3;
1465
+ const GB = 1e9;
1466
+ const gb = (bytes) => `${(bytes / GB).toFixed(1)} GB`;
1467
+
1468
+ function newestDiskReport(dir) {
1469
+ let names;
1364
1470
  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;
1471
+ names = readdirSync(dir)
1472
+ .filter((n) => /^report-.*\.json$/.test(n))
1473
+ .sort()
1474
+ .reverse();
1370
1475
  } catch {
1371
- /* df is not everywhere */
1476
+ return null;
1372
1477
  }
1373
- if (freeGb === null) {
1374
- skip("disk-space", "df did not report a usable figure on this host");
1375
- return;
1478
+ for (const n of names) {
1479
+ const data = readJson(join(dir, n));
1480
+ if (data && data.mode === "dry-run" && Array.isArray(data.categories)) {
1481
+ return { file: join(dir, n), data };
1482
+ }
1483
+ }
1484
+ return null;
1485
+ }
1486
+
1487
+ function probeDiskReport() {
1488
+ const timeout = Number(process.env.DOCTOR_DISK_PROBE_TIMEOUT_MS) || DISK_PROBE_TIMEOUT_MS;
1489
+ const r = spawnSync(
1490
+ process.execPath,
1491
+ [join(HERE, "disk-cleaner.mjs"), "--dry-run", "--json", `--top=${DISK_TOP}`],
1492
+ { encoding: "utf8", timeout, maxBuffer: 256 * 1024 * 1024 },
1493
+ );
1494
+ if (r.error?.code === "ETIMEDOUT" || r.signal) {
1495
+ return { timedOut: true, seconds: Math.round(timeout / 1000) };
1496
+ }
1497
+ try {
1498
+ return { data: JSON.parse(r.stdout) };
1499
+ } catch {
1500
+ return { error: (r.stderr || "no JSON on stdout").trim().split("\n")[0] };
1376
1501
  }
1377
- if (freeGb < 2) {
1502
+ }
1503
+
1504
+ function reclaimSummary(data, source, file) {
1505
+ const measuredAt = Date.parse(data.startedAt);
1506
+ const ageMs = Number.isFinite(measuredAt) ? Date.now() - measuredAt : null;
1507
+ const top = [...data.categories]
1508
+ .filter((c) => c.bytes > 0)
1509
+ .sort((a, b) => b.bytes - a.bytes)
1510
+ .slice(0, DISK_TOP)
1511
+ .map((c) => ({ id: c.id, bytes: c.bytes }));
1512
+ return {
1513
+ source,
1514
+ file,
1515
+ measuredAt: data.startedAt || null,
1516
+ ageHours: ageMs == null ? null : Math.round((ageMs / 3_600_000) * 10) / 10,
1517
+ stale: ageMs == null || ageMs > DISK_REPORT_MAX_AGE_MS,
1518
+ totalBytes: data.reclaimableBytes ?? data.totalBytes ?? 0,
1519
+ top,
1520
+ };
1521
+ }
1522
+
1523
+ function ageText(hours) {
1524
+ if (hours == null) return "at an unknown time";
1525
+ if (hours < 1) return `${Math.max(1, Math.round(hours * 60))} min ago`;
1526
+ if (hours < 48) return `${Math.round(hours)} h ago`;
1527
+ return `${Math.round(hours / 24)} days ago`;
1528
+ }
1529
+
1530
+ function checkDiskSpace() {
1531
+ const r = lowDiskCheck({ path: HOME });
1532
+ if (r.freeBytes == null) {
1533
+ skip("disk-space", "statfs did not report a usable figure on this host");
1534
+ return;
1535
+ }
1536
+ const cmd = hostCommand("clean-disk", HERE);
1537
+ const pct = r.totalBytes ? (r.freeBytes / r.totalBytes) * 100 : null;
1538
+ const freeText = `${gb(r.freeBytes)} (${pct == null ? "?" : pct.toFixed(1)}%) free on the volume holding $HOME`;
1539
+ const threshold = Number(globalPref("diskCleaner.reclaimableGb", 10));
1540
+ const reclaimGb = Number.isFinite(threshold) && threshold >= 0 ? threshold : 10;
1541
+
1542
+ let reclaim = null;
1543
+ let probe = null;
1544
+ if (PROBE) {
1545
+ const p = probeDiskReport();
1546
+ probe = p.data
1547
+ ? { ok: true }
1548
+ : p.timedOut
1549
+ ? { timedOut: true, seconds: p.seconds }
1550
+ : { error: p.error };
1551
+ if (p.data) reclaim = reclaimSummary(p.data, "probe", null);
1552
+ }
1553
+ if (!reclaim) {
1554
+ const found = newestDiskReport(join(CLAUDE, "logs", "disk-cleaner"));
1555
+ if (found) reclaim = reclaimSummary(found.data, "report", found.file);
1556
+ }
1557
+
1558
+ let measured;
1559
+ if (probe?.timedOut) {
1560
+ measured = `the measurement timed out after ${probe.seconds} s`;
1561
+ if (reclaim && !reclaim.stale) measured += `; the last one, ${ageText(reclaim.ageHours)}`;
1562
+ } else if (probe?.error) {
1563
+ measured = `the measurement failed (${probe.error})`;
1564
+ } else if (!reclaim) {
1565
+ measured = `nothing measured yet; ${cmd} measures what can be freed`;
1566
+ } else if (reclaim.stale) {
1567
+ measured = `the last measurement is ${ageText(reclaim.ageHours).replace(/ ago$/, " old")}; ${cmd} measures again`;
1568
+ } else {
1569
+ measured = `measured ${ageText(reclaim.ageHours)}`;
1570
+ }
1571
+ const fresh = reclaim && !reclaim.stale;
1572
+ const reclaimText = fresh
1573
+ ? `${gb(reclaim.totalBytes)} can be freed${reclaim.top.length ? ` (${reclaim.top.map((c) => `${c.id} ${gb(c.bytes)}`).join(", ")})` : ""}, ${measured}`
1574
+ : measured;
1575
+ const detail = {
1576
+ freeBytes: r.freeBytes,
1577
+ totalBytes: r.totalBytes,
1578
+ freePercent: pct == null ? null : Math.round(pct * 10) / 10,
1579
+ lowGb: r.lowGb,
1580
+ lowPercent: r.lowPercent,
1581
+ reclaimableGb: reclaimGb,
1582
+ reclaimable: reclaim,
1583
+ probe,
1584
+ summary: `${freeText}; ${reclaimText}`,
1585
+ };
1586
+ const freeStep = fresh
1587
+ ? `run ${cmd}: ${gb(reclaim.totalBytes)} can be freed`
1588
+ : `run ${cmd} to measure what can be freed; it deletes only what you choose`;
1589
+
1590
+ if (r.low) {
1378
1591
  report(
1379
1592
  "disk-space",
1380
1593
  "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",
1594
+ `${freeText}, under the ${r.lowGb} GB / ${r.lowPercent}% floor; a worktree plus a build needs more; ${reclaimText}`,
1595
+ freeStep,
1596
+ detail,
1383
1597
  );
1384
1598
  return;
1385
1599
  }
1386
- ok("disk-space");
1600
+ if (fresh && reclaim.totalBytes >= reclaimGb * GB) {
1601
+ report("disk-space", "INFO", `${freeText}; ${reclaimText}`, freeStep, detail);
1602
+ return;
1603
+ }
1604
+ report("disk-space", "OK", null, null, detail);
1387
1605
  }
1388
1606
 
1389
1607
  // A finished task removes its own worktree at PR time, but a run that dies
@@ -1585,6 +1803,13 @@ function checkServerProfile(resolved) {
1585
1803
  }
1586
1804
  }
1587
1805
 
1806
+ const KNOWN_FLAGS = ["probe", "json", "explain", "list-checks", "task-tools", "profile", "only"];
1807
+
1808
+ /** The --json document: schemas/doctor-report.schema.json. */
1809
+ function jsonReport(exit, checks) {
1810
+ return { schemaVersion: SCHEMA_VERSION, exit, selection: SELECTION, checks };
1811
+ }
1812
+
1588
1813
  function main() {
1589
1814
  if (LIST) {
1590
1815
  // Lists what THIS invocation would run, which is what the name promises
@@ -1598,15 +1823,30 @@ function main() {
1598
1823
  }
1599
1824
  const unknown = argv.filter(
1600
1825
  (a) =>
1601
- a.startsWith("--") && !/^--(probe|json|explain|list-checks|task-tools=|profile=)/.test(a),
1826
+ a.startsWith("--") &&
1827
+ !/^--(probe|json|explain|list-checks|task-tools=|profile=|only(=|$))/.test(a),
1602
1828
  );
1603
1829
  if (unknown.length) {
1830
+ const flag = unknown[0].slice(2).split("=")[0];
1831
+ const hint = didYouMean(flag, KNOWN_FLAGS, { prefix: "--" });
1604
1832
  process.stderr.write(
1605
- `usage: doctor.mjs [--probe] [--json] [--explain] [--task-tools=yes|no] [--profile=server] | --list-checks\n`,
1833
+ `${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
1834
  );
1607
1835
  process.exitCode = 3;
1608
1836
  return;
1609
1837
  }
1838
+ if (SELECTION !== null) {
1839
+ const known = [...CHECK_IDS, ...SERVER_CHECK_IDS];
1840
+ const bad = SELECTION.filter((id) => !known.includes(id));
1841
+ if (!SELECTION.length || bad.length) {
1842
+ const hint = bad.length ? didYouMean(bad[0], known) : "";
1843
+ process.stderr.write(
1844
+ `usage: --only takes check ids from --list-checks${bad.length ? ` (unknown: ${bad.join(", ")}${hint})` : ""}\n`,
1845
+ );
1846
+ process.exitCode = 3;
1847
+ return;
1848
+ }
1849
+ }
1610
1850
  if (PROFILE && PROFILE !== "server") {
1611
1851
  process.stderr.write(`usage: --profile takes "server" (got "${PROFILE}")\n`);
1612
1852
  process.exitCode = 3;
@@ -1627,7 +1867,7 @@ function main() {
1627
1867
  // that never ran.
1628
1868
  const line = results[results.length - 1];
1629
1869
  if (JSON_OUT) {
1630
- process.stdout.write(`${JSON.stringify({ exit: 4, checks: results }, null, 2)}\n`);
1870
+ process.stdout.write(`${JSON.stringify(jsonReport(4, results), null, 2)}\n`);
1631
1871
  } else {
1632
1872
  process.stdout.write(`${line.severity} ${line.id} - ${line.problem} - ${line.step}\n`);
1633
1873
  process.stdout.write(
@@ -1638,30 +1878,44 @@ function main() {
1638
1878
  return;
1639
1879
  }
1640
1880
 
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);
1881
+ // Each step names the ids it reports, so --only can leave out the work of
1882
+ // a check nobody asked for. A step that feeds another (the registration
1883
+ // probe feeds the schema load) lists both.
1884
+ const steps = [
1885
+ [["install-version"], checkInstallVersion],
1886
+ [["update-policy"], checkUpdatePolicy],
1887
+ [["script-surface"], checkScriptSurface],
1888
+ [["skill-siblings"], checkSkillSiblings],
1889
+ [["state-writable"], checkStateWritable],
1890
+ [["prefs-valid"], checkPrefsValid],
1891
+ [["identity"], checkIdentity],
1892
+ [["hook-coverage"], checkHookCoverage],
1893
+ [["hook-reachability"], checkHookReachability],
1894
+ [["guard-rules"], checkGuardRules],
1895
+ [["credential-mapping", "credential-liveness"], () => checkCredentials(credentialInventory())],
1896
+ [["store-reference"], checkStoreReference],
1897
+ [["embedded-credentials"], checkEmbeddedCredentials],
1898
+ [["task-tools"], checkTaskTools],
1899
+ [["mcp-registration", "mcp-schema-load"], checkMcpRegistration],
1900
+ [["mcp-surface"], checkMcpSurface],
1901
+ [["mcp-schema-load"], checkMcpSchemaLoad],
1902
+ [["mcp-failures"], checkMcpFailures],
1903
+ [["disk-space"], checkDiskSpace],
1904
+ [["worktree-residue"], checkWorktreeResidue],
1905
+ [["usage-report"], checkUsageReport],
1906
+ [["usage-register"], checkUsageRegister],
1907
+ [["free-models"], checkFreeModels],
1908
+ [["xcode-skills"], checkXcodeSkills],
1909
+ ];
1910
+ if (PROFILE === "server") steps.push([SERVER_CHECK_IDS, () => checkServerProfile(resolved)]);
1911
+ for (const [ids, run] of steps) {
1912
+ if (SELECTION === null || ids.some((id) => SELECTION.includes(id))) run();
1913
+ }
1914
+ if (SELECTION !== null) {
1915
+ const keep = results.filter((r) => SELECTION.includes(r.id));
1916
+ results.length = 0;
1917
+ results.push(...keep);
1918
+ }
1665
1919
 
1666
1920
  const blocked = results.filter((r) => r.severity === "BLOCK");
1667
1921
  const warned = results.filter((r) => r.severity === "WARN");
@@ -1669,7 +1923,7 @@ function main() {
1669
1923
  const code = blocked.length ? 2 : warned.length ? 1 : 0;
1670
1924
 
1671
1925
  if (JSON_OUT) {
1672
- process.stdout.write(`${JSON.stringify({ exit: code, checks: results }, null, 2)}\n`);
1926
+ process.stdout.write(`${JSON.stringify(jsonReport(code, results), null, 2)}\n`);
1673
1927
  process.exitCode = code;
1674
1928
  return;
1675
1929
  }
@@ -1681,7 +1935,8 @@ function main() {
1681
1935
  const r = results.find((x) => x.id === id);
1682
1936
  if (!r) continue;
1683
1937
  if (r.severity === "OK") {
1684
- process.stdout.write(`OK ${id}\n`);
1938
+ const note = typeof r.detail?.summary === "string" ? ` - ${r.detail.summary}` : "";
1939
+ process.stdout.write(`OK ${id}${note}\n`);
1685
1940
  } else if (r.severity === "SKIP") {
1686
1941
  process.stdout.write(`SKIP ${id} - ${r.problem}\n`);
1687
1942
  } else {
@@ -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");