@mmerterden/multi-agent-pipeline 20.40.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 (143) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +5 -2
  3. package/README.tr.md +5 -2
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +51 -14
  7. package/docs/facts.json +7 -7
  8. package/docs/features.md +15 -4
  9. package/install/claude.mjs +45 -3
  10. package/install/templates/claude-hooks.json +23 -1
  11. package/manifest.json +146 -107
  12. package/package.json +3 -2
  13. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  14. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/contract/types/index.d.ts +53 -49
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/context-budget.mjs +5 -42
  20. package/pipeline/lib/credential-store.sh +11 -1
  21. package/pipeline/lib/hook-once.mjs +134 -0
  22. package/pipeline/lib/hook-registration.mjs +5 -0
  23. package/pipeline/lib/isotonic.mjs +73 -0
  24. package/pipeline/lib/low-disk.mjs +153 -0
  25. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  26. package/pipeline/lib/md2confluence-v3.py +19 -10
  27. package/pipeline/lib/model-dispatch.sh +26 -2
  28. package/pipeline/lib/normalize-text.mjs +135 -0
  29. package/pipeline/lib/outbound-gate.mjs +21 -3
  30. package/pipeline/lib/plan-todos.sh +17 -4
  31. package/pipeline/lib/redact.mjs +12 -3
  32. package/pipeline/lib/risky-settings.mjs +198 -0
  33. package/pipeline/lib/route-state.sh +1 -0
  34. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  35. package/pipeline/lib/session-usage.mjs +232 -0
  36. package/pipeline/lib/source-digest.mjs +211 -0
  37. package/pipeline/lib/tdd-evidence.mjs +250 -17
  38. package/pipeline/lib/tiered-budget.mjs +87 -0
  39. package/pipeline/lib/untrusted-fence.mjs +132 -1
  40. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  41. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  42. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  43. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  44. package/pipeline/multi-agent-refs/features/doctor.md +82 -4
  45. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  46. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  47. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  48. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  49. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  50. package/pipeline/multi-agent-refs/features/usage-reporting.md +33 -0
  51. package/pipeline/multi-agent-refs/help/en.md +2 -1
  52. package/pipeline/multi-agent-refs/help/tr.md +2 -1
  53. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  54. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  55. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  56. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +5 -1
  57. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  58. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  59. package/pipeline/multi-agent-refs/phases/phase-5-report.md +4 -0
  60. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  61. package/pipeline/office/index.html +13 -7
  62. package/pipeline/office/toolkit.json +1 -1
  63. package/pipeline/preferences-template.json +1 -0
  64. package/pipeline/rules/outside-the-pipeline.md +1 -1
  65. package/pipeline/schemas/doctor-report.schema.json +47 -0
  66. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  67. package/pipeline/schemas/office-archive.schema.json +225 -128
  68. package/pipeline/schemas/plan-todos.schema.json +29 -1
  69. package/pipeline/schemas/prefs.schema.json +146 -0
  70. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  71. package/pipeline/schemas/product-tree.schema.json +136 -0
  72. package/pipeline/schemas/route-config.schema.json +51 -0
  73. package/pipeline/schemas/secret-patterns.json +17 -1
  74. package/pipeline/schemas/toolkit-path-params.json +15 -1
  75. package/pipeline/scripts/_cost-advise.mjs +357 -0
  76. package/pipeline/scripts/_cost-budget.mjs +78 -0
  77. package/pipeline/scripts/_cost.mjs +29 -0
  78. package/pipeline/scripts/_decode_text.py +107 -0
  79. package/pipeline/scripts/_eval-stats.mjs +182 -0
  80. package/pipeline/scripts/_guard-probe.mjs +406 -0
  81. package/pipeline/scripts/_guard_rules.py +336 -1
  82. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  83. package/pipeline/scripts/_locate.mjs +539 -0
  84. package/pipeline/scripts/_memory-policy.mjs +208 -33
  85. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  86. package/pipeline/scripts/_product-tree.mjs +923 -0
  87. package/pipeline/scripts/_retrieval.mjs +161 -4
  88. package/pipeline/scripts/_secret-scan.mjs +6 -1
  89. package/pipeline/scripts/_stack-routing.mjs +2 -0
  90. package/pipeline/scripts/_test-gaming.mjs +346 -0
  91. package/pipeline/scripts/_user_guard_rules.py +744 -0
  92. package/pipeline/scripts/agent-guard.py +69 -6
  93. package/pipeline/scripts/agent-guard.sh +8 -1
  94. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  95. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  96. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  97. package/pipeline/scripts/capture-resume.sh +9 -1
  98. package/pipeline/scripts/cost-analyze.mjs +66 -4
  99. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  100. package/pipeline/scripts/disk-cleaner.mjs +1418 -0
  101. package/pipeline/scripts/doctor.mjs +324 -43
  102. package/pipeline/scripts/evidence-gate.mjs +90 -0
  103. package/pipeline/scripts/gate-ledger.mjs +76 -21
  104. package/pipeline/scripts/gc-tmp.sh +5 -0
  105. package/pipeline/scripts/graph-query.mjs +257 -17
  106. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  107. package/pipeline/scripts/learnings-ledger.mjs +680 -55
  108. package/pipeline/scripts/note-agent-event.mjs +2 -0
  109. package/pipeline/scripts/note-mcp-failure.mjs +363 -0
  110. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  111. package/pipeline/scripts/note-skill-use.mjs +96 -23
  112. package/pipeline/scripts/office-archive.mjs +23 -10
  113. package/pipeline/scripts/office-memory.mjs +4 -1
  114. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  115. package/pipeline/scripts/pre-commit-check.sh +2 -2
  116. package/pipeline/scripts/pre-push-check.sh +8 -1
  117. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  118. package/pipeline/scripts/product-tree.mjs +544 -0
  119. package/pipeline/scripts/publish-staged.mjs +324 -0
  120. package/pipeline/scripts/route-learn.mjs +628 -0
  121. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  122. package/pipeline/scripts/scan-agent-config.sh +1 -1
  123. package/pipeline/scripts/statusline.mjs +309 -0
  124. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  125. package/pipeline/scripts/triage-memory.mjs +12 -4
  126. package/pipeline/scripts/uninstall.mjs +1 -0
  127. package/pipeline/skills/.skill-manifest.json +15 -7
  128. package/pipeline/skills/.skills-index.json +25 -3
  129. package/pipeline/skills/shared/README.md +6 -4
  130. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  131. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  132. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  133. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
  134. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  135. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
  136. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  137. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  138. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  139. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  140. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  141. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  142. package/pipeline/skills/skill-copies.json +9 -1
  143. package/pipeline/skills/skills-index.md +4 -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 {
@@ -61,9 +68,12 @@ import {
61
68
  } from "../lib/unattended-settings-location.mjs";
62
69
  import { prefsHosts, profileGaps } from "../lib/unattended-profile-check.mjs";
63
70
  import { xcodeSkillsStatus } from "../lib/xcode-plugin.mjs";
64
- import { hookReport } from "../lib/hook-registration.mjs";
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,
@@ -101,6 +127,7 @@ const CHECK_IDS = [
101
127
  "identity",
102
128
  "hook-coverage",
103
129
  "hook-reachability",
130
+ "guard-rules",
104
131
  "credential-mapping",
105
132
  "credential-liveness",
106
133
  "store-reference",
@@ -108,6 +135,8 @@ const CHECK_IDS = [
108
135
  "task-tools",
109
136
  "mcp-registration",
110
137
  "mcp-surface",
138
+ "mcp-schema-load",
139
+ "mcp-failures",
111
140
  "disk-space",
112
141
  "worktree-residue",
113
142
  "usage-report",
@@ -573,6 +602,112 @@ function checkHookReachability() {
573
602
  );
574
603
  }
575
604
 
605
+ // prefs.global.guardRules as the guard reads them (_user_guard_rules.py
606
+ // --report, same file lookup), so doctor and the guard cannot disagree on
607
+ // which rule is valid. Reports rule labels and problems, never a pattern.
608
+ // A rule whose tool agent-guard.sh is not registered on does nothing; Read is
609
+ // the usual case, since the default hooks do not register the guard there.
610
+ const GUARD_COMMAND = 'bash "$HOME/.claude/scripts/agent-guard.sh"';
611
+ // The host tools a rule's tool name governs. MultiEdit is left out: the
612
+ // current host has no such tool, so requiring a registration for it would
613
+ // warn on every default install.
614
+ const GUARD_RULE_TOOLS = { Edit: ["Edit", "NotebookEdit"] };
615
+
616
+ function guardRulesReport() {
617
+ const script = join(HERE, "_user_guard_rules.py");
618
+ if (!existsSync(script)) return { skip: "_user_guard_rules.py is not installed" };
619
+ try {
620
+ const out = execFileSync("python3", [script, "--report"], {
621
+ encoding: "utf8",
622
+ timeout: 10000,
623
+ stdio: ["ignore", "pipe", "ignore"],
624
+ });
625
+ return JSON.parse(out);
626
+ } catch {
627
+ return { skip: "python3 could not read the guard rules" };
628
+ }
629
+ }
630
+
631
+ function checkGuardRules() {
632
+ const r = guardRulesReport();
633
+ if (r.skip) {
634
+ skip("guard-rules", r.skip);
635
+ return;
636
+ }
637
+ if (r.error) {
638
+ report(
639
+ "guard-rules",
640
+ "WARN",
641
+ `${r.error}: no guard rule applies; attended each call a rule could govern carries a note, and ` +
642
+ (r.holdsRules === false
643
+ ? "unattended nothing is refused, since the file does not name guardRules"
644
+ : "every such call is refused unattended"),
645
+ `set ${r.source} to valid JSON with prefs.global.guardRules as a list`,
646
+ null,
647
+ );
648
+ return;
649
+ }
650
+ if (!r.rules) {
651
+ ok("guard-rules");
652
+ return;
653
+ }
654
+ const parts = [];
655
+ const detail = [];
656
+ const step = [];
657
+ if (r.invalid.length) {
658
+ const blocks = r.invalid.filter((i) => i.action === "block" && i.tool).length;
659
+ parts.push(
660
+ `${r.invalid.length} of ${r.rules} guard rule(s) are invalid and ignored` +
661
+ (blocks ? `, and ${blocks} invalid block rule(s) refuse their tool unattended` : ""),
662
+ );
663
+ for (const i of r.invalid) detail.push(`${i.label}: ${i.problem}`);
664
+ step.push("set prefs.global.guardRules so every rule validates (--explain names each)");
665
+ }
666
+ const uncovered = r.tools.flatMap((tool) => {
667
+ const names = GUARD_RULE_TOOLS[tool] || [tool.replace(/[*?]/g, "x")];
668
+ const missing = names.filter((name) => {
669
+ const template = {
670
+ hooks: {
671
+ PreToolUse: [{ matcher: name, hooks: [{ type: "command", command: GUARD_COMMAND }] }],
672
+ },
673
+ };
674
+ return registrationGaps({ template, home: HOME }).missing.length > 0;
675
+ });
676
+ if (!missing.length) return [];
677
+ return [missing.length === names.length ? tool : `${tool} (${missing.join(", ")})`];
678
+ });
679
+ if (uncovered.length) {
680
+ parts.push(
681
+ `guard rules for ${uncovered.join(", ")} do nothing: agent-guard.sh is not registered there`,
682
+ );
683
+ for (const t of uncovered) detail.push(`PreToolUse ${t}: agent-guard.sh not registered`);
684
+ step.push(
685
+ `merge a PreToolUse entry running agent-guard.sh for ${uncovered.join(", ")} into ${join(CLAUDE, "settings.json")}`,
686
+ );
687
+ }
688
+ const slow = Array.isArray(r.slow) ? r.slow : [];
689
+ const slowNote =
690
+ `${slow.length} guard rule(s) have a slow shape and run under the 1-second matching budget, ` +
691
+ "where a block or ask rule that runs out of time refuses unattended and asks attended";
692
+ for (const i of slow) detail.push(`${i.label}: ${i.shape}`);
693
+ if (!parts.length && slow.length) {
694
+ report(
695
+ "guard-rules",
696
+ "INFO",
697
+ slowNote,
698
+ "set each named rule's match to a tighter pattern: bound the inner quantifier or make its neighbours disjoint",
699
+ detail,
700
+ );
701
+ return;
702
+ }
703
+ if (slow.length) parts.push(slowNote);
704
+ if (!parts.length) {
705
+ ok("guard-rules");
706
+ return;
707
+ }
708
+ report("guard-rules", "WARN", parts.join("; "), step.join("; then "), detail);
709
+ }
710
+
576
711
  function credentialInventory() {
577
712
  const inv = join(CLAUDE, "lib", "credential-inventory.sh");
578
713
  if (!existsSync(inv)) return null;
@@ -815,6 +950,11 @@ function checkTaskTools() {
815
950
  );
816
951
  }
817
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
+
818
958
  function checkMcpRegistration() {
819
959
  // Registered is not the same as working, and the difference is what the user
820
960
  // actually hits: a half-extracted package in the npx cache left the server
@@ -858,6 +998,7 @@ function checkMcpRegistration() {
858
998
  JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
859
999
  JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" }),
860
1000
  ].join("\n");
1001
+ toolkitEntry = entry;
861
1002
  let served = 0;
862
1003
  let servedVersion = null;
863
1004
  let why = "";
@@ -875,7 +1016,10 @@ function checkMcpRegistration() {
875
1016
  const m = JSON.parse(line);
876
1017
  if (m.id === 1 && typeof m.result?.serverInfo?.version === "string")
877
1018
  servedVersion = m.result.serverInfo.version;
878
- 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
+ }
879
1023
  } catch {
880
1024
  /* the server may print non-JSON lines */
881
1025
  }
@@ -977,6 +1121,109 @@ function checkMcpSurface() {
977
1121
  );
978
1122
  }
979
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
+
1169
+ // The local MCP failure log note-mcp-failure.sh writes. A missing sibling
1170
+ // leaves the check to SKIP rather than taking doctor down with it: doctor is
1171
+ // what a half-installed machine runs.
1172
+ let mcpFailureLog = null;
1173
+ try {
1174
+ mcpFailureLog = await import("./note-mcp-failure.mjs");
1175
+ } catch {
1176
+ mcpFailureLog = null;
1177
+ }
1178
+
1179
+ // A server whose calls keep failing, read from the failures this machine
1180
+ // already recorded. Nothing is probed. INFO, never WARN: a flaky third-party
1181
+ // server degrades a session but is not this install's health, and the step
1182
+ // names the server so the user can decide.
1183
+ function checkMcpFailures() {
1184
+ if (!mcpFailureLog) {
1185
+ skip("mcp-failures", "note-mcp-failure.mjs is not installed");
1186
+ return;
1187
+ }
1188
+ if (!mcpFailureLog.captureEnabled()) {
1189
+ skip("mcp-failures", "MCP failure counting is off (mcpFailures.enabled or usageLog.optOut)");
1190
+ return;
1191
+ }
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
+ }
1205
+ const repeated = summary.servers.filter((s) => summary.repeated.includes(s.server));
1206
+ if (!repeated.length) {
1207
+ ok("mcp-failures");
1208
+ return;
1209
+ }
1210
+ const worst = repeated[0];
1211
+ const others = repeated.length > 1 ? ` (and ${repeated.length - 1} more server(s))` : "";
1212
+ report(
1213
+ "mcp-failures",
1214
+ "INFO",
1215
+ `${worst.server} failed ${worst.failures} times in the last ${summary.hours} hours${others}`,
1216
+ `run claude mcp list to see whether ${worst.server} is connected, then node ${join(HERE, "note-mcp-failure.mjs")} summary for the failing tools`,
1217
+ repeated.map((r) => ({
1218
+ server: r.server,
1219
+ failures: r.failures,
1220
+ tools: r.tools,
1221
+ classes: r.classes,
1222
+ last: r.last,
1223
+ })),
1224
+ );
1225
+ }
1226
+
980
1227
  // usage-report.mjs runs detached with its output discarded, so the record it
981
1228
  // writes after every send attempt is the one place a broken reporting path
982
1229
  // becomes visible.
@@ -1205,27 +1452,23 @@ function checkXcodeSkills() {
1205
1452
  ok("xcode-skills");
1206
1453
  }
1207
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.
1208
1459
  function checkDiskSpace() {
1209
- let freeGb = null;
1210
- try {
1211
- const out = execFileSync("df", ["-k", HOME], { encoding: "utf8" });
1212
- const line = out.trim().split("\n").pop();
1213
- const cols = line.split(/\s+/);
1214
- const availKb = Number(cols[3]);
1215
- if (Number.isFinite(availKb)) freeGb = availKb / 1024 / 1024;
1216
- } catch {
1217
- /* df is not everywhere */
1218
- }
1219
- if (freeGb === null) {
1220
- 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");
1221
1463
  return;
1222
1464
  }
1223
- if (freeGb < 2) {
1465
+ if (r.low) {
1466
+ const pct = r.totalBytes ? ((r.freeBytes / r.totalBytes) * 100).toFixed(1) : "?";
1224
1467
  report(
1225
1468
  "disk-space",
1226
1469
  "WARN",
1227
- `${freeGb.toFixed(1)} GB free on the volume holding $HOME; a worktree plus a build needs more`,
1228
- "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",
1229
1472
  );
1230
1473
  return;
1231
1474
  }
@@ -1431,6 +1674,13 @@ function checkServerProfile(resolved) {
1431
1674
  }
1432
1675
  }
1433
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
+
1434
1684
  function main() {
1435
1685
  if (LIST) {
1436
1686
  // Lists what THIS invocation would run, which is what the name promises
@@ -1444,15 +1694,30 @@ function main() {
1444
1694
  }
1445
1695
  const unknown = argv.filter(
1446
1696
  (a) =>
1447
- 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),
1448
1699
  );
1449
1700
  if (unknown.length) {
1701
+ const flag = unknown[0].slice(2).split("=")[0];
1702
+ const hint = didYouMean(flag, KNOWN_FLAGS, { prefix: "--" });
1450
1703
  process.stderr.write(
1451
- `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`,
1452
1705
  );
1453
1706
  process.exitCode = 3;
1454
1707
  return;
1455
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
+ }
1456
1721
  if (PROFILE && PROFILE !== "server") {
1457
1722
  process.stderr.write(`usage: --profile takes "server" (got "${PROFILE}")\n`);
1458
1723
  process.exitCode = 3;
@@ -1473,7 +1738,7 @@ function main() {
1473
1738
  // that never ran.
1474
1739
  const line = results[results.length - 1];
1475
1740
  if (JSON_OUT) {
1476
- process.stdout.write(`${JSON.stringify({ exit: 4, checks: results }, null, 2)}\n`);
1741
+ process.stdout.write(`${JSON.stringify(jsonReport(4, results), null, 2)}\n`);
1477
1742
  } else {
1478
1743
  process.stdout.write(`${line.severity} ${line.id} - ${line.problem} - ${line.step}\n`);
1479
1744
  process.stdout.write(
@@ -1484,28 +1749,44 @@ function main() {
1484
1749
  return;
1485
1750
  }
1486
1751
 
1487
- checkInstallVersion();
1488
- checkUpdatePolicy();
1489
- checkScriptSurface();
1490
- checkSkillSiblings();
1491
- checkStateWritable();
1492
- checkPrefsValid();
1493
- checkIdentity();
1494
- checkHookCoverage();
1495
- checkHookReachability();
1496
- checkCredentials(credentialInventory());
1497
- checkStoreReference();
1498
- checkEmbeddedCredentials();
1499
- checkTaskTools();
1500
- checkMcpRegistration();
1501
- checkMcpSurface();
1502
- checkDiskSpace();
1503
- checkWorktreeResidue();
1504
- checkUsageReport();
1505
- checkUsageRegister();
1506
- checkFreeModels();
1507
- checkXcodeSkills();
1508
- 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
+ }
1509
1790
 
1510
1791
  const blocked = results.filter((r) => r.severity === "BLOCK");
1511
1792
  const warned = results.filter((r) => r.severity === "WARN");
@@ -1513,7 +1794,7 @@ function main() {
1513
1794
  const code = blocked.length ? 2 : warned.length ? 1 : 0;
1514
1795
 
1515
1796
  if (JSON_OUT) {
1516
- process.stdout.write(`${JSON.stringify({ exit: code, checks: results }, null, 2)}\n`);
1797
+ process.stdout.write(`${JSON.stringify(jsonReport(code, results), null, 2)}\n`);
1517
1798
  process.exitCode = code;
1518
1799
  return;
1519
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");