@mmerterden/multi-agent-pipeline 24.0.0 → 24.1.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 (41) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +2 -0
  3. package/README.tr.md +2 -0
  4. package/docs/facts.json +2 -2
  5. package/docs/features.md +8 -0
  6. package/install/_dev-only-files.mjs +1 -0
  7. package/manifest.json +43 -42
  8. package/package.json +4 -2
  9. package/pipeline/commands/multi-agent/SKILL.md +1 -1
  10. package/pipeline/commands/multi-agent/analysis/SKILL.md +1 -1
  11. package/pipeline/contract/CHANGELOG.md +15 -0
  12. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  13. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  14. package/pipeline/contract/fixtures/runs-awaiting-question.json +6 -1
  15. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  16. package/pipeline/contract/fixtures/runs-failed.json +21 -1
  17. package/pipeline/contract/fixtures/runs-old-schema.json +18 -3
  18. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +31 -1
  19. package/pipeline/contract/fixtures/runs-pr-opened.json +31 -1
  20. package/pipeline/contract/fixtures/runs-running.json +16 -1
  21. package/pipeline/contract/manifest.json +13 -13
  22. package/pipeline/contract/types/index.d.ts +19 -1
  23. package/pipeline/multi-agent-refs/analysis/render.md +12 -1
  24. package/pipeline/multi-agent-refs/help/en.md +10 -2
  25. package/pipeline/multi-agent-refs/help/tr.md +8 -2
  26. package/pipeline/multi-agent-refs/phases/phase-0-init.md +1 -0
  27. package/pipeline/multi-agent-refs/phases/phase-4-commit.md +1 -0
  28. package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
  29. package/pipeline/multi-agent-refs/tracker-contract.md +36 -10
  30. package/pipeline/office/index.html +75 -2
  31. package/pipeline/schemas/activity.schema.json +63 -4
  32. package/pipeline/schemas/now-lines.json +103 -0
  33. package/pipeline/schemas/now-lines.schema.json +42 -0
  34. package/pipeline/schemas/runs-index.schema.json +22 -1
  35. package/pipeline/scripts/_contract-core.mjs +1 -1
  36. package/pipeline/scripts/activity-snapshot.mjs +27 -1
  37. package/pipeline/scripts/phase-tracker.sh +80 -12
  38. package/pipeline/scripts/render-work-summary.sh +51 -1
  39. package/pipeline/scripts/runs-index.mjs +2 -1
  40. package/pipeline/skills/.skill-manifest.json +1 -1
  41. package/pipeline/scripts/.doctor-mut.47076.mjs +0 -2253
@@ -1,2253 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * @file doctor.mjs - what is wrong with this install, and the one step that fixes it.
4
- *
5
- * WHY THIS EXISTS
6
- *
7
- * Every failure this reports has already reached a user, and each one arrived
8
- * the same way: late, mid-run, after the pickers had been answered. A missing
9
- * script fails at the call. Malformed preferences fail after Phase 0 has already
10
- * asked five questions. A token in a remote URL does not fail at all - it leaks.
11
- * None of it is visible beforehand, so the pipeline's own answer to "is this
12
- * machine set up correctly" was to start a run and find out.
13
- *
14
- * So this is a gate, not a report. The exit code is the product:
15
- *
16
- * 0 healthy nothing above INFO
17
- * 1 degraded at least one WARN
18
- * 2 blocked at least one BLOCK
19
- * 3 usage error
20
- * 4 indeterminate the layout did not resolve, so nothing was checked
21
- *
22
- * 4 is the one people forget. Without it "I could not look" borrows the exit
23
- * code of "I looked and it is fine", and every consumer downstream believes a
24
- * broken resolver is a clean bill.
25
- *
26
- * BLOCK IS A CLOSED DEFINITION: a state where a run will fail or leak, never one
27
- * where it will merely be worse. Five checks can produce it and the rest top out
28
- * at WARN however bad they look. Without that rule "blocked" grows until nobody
29
- * respects exit 2.
30
- *
31
- * IT RECOMMENDS, IT NEVER FIXES. A remote whose URL carries a token may be the
32
- * only credential that repo has; the remote may be a mirror a script depends on
33
- * verbatim; and this can run inside a checkout the user does not own. Silent
34
- * repair breaks all three.
35
- *
36
- * Contract, every check by id, and the severity rules: multi-agent-refs/features/doctor.md
37
- *
38
- * Usage:
39
- * doctor.mjs [--probe] [--json] [--explain] [--task-tools=yes|no]
40
- * [--only <id,...>]
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.
48
- */
49
-
50
- import {
51
- existsSync,
52
- readFileSync,
53
- readdirSync,
54
- mkdirSync,
55
- writeFileSync,
56
- rmSync,
57
- realpathSync,
58
- } from "node:fs";
59
- import { basename, join, dirname } from "node:path";
60
- import { homedir } from "node:os";
61
- import { execFileSync, spawnSync } from "node:child_process";
62
- import { fileURLToPath, pathToFileURL } from "node:url";
63
- import { runMain } from "../lib/fatal.mjs";
64
- import { hostCommand } from "../lib/user-facing.mjs";
65
- import {
66
- UNATTENDED_PROFILE_INSTALL,
67
- UNATTENDED_SETTINGS_FILE,
68
- } from "../lib/unattended-settings-location.mjs";
69
- import { prefsHosts, profileGaps } from "../lib/unattended-profile-check.mjs";
70
- import { xcodeSkillsStatus } from "../lib/xcode-plugin.mjs";
71
- import { hookReport, registrationGaps } from "../lib/hook-registration.mjs";
72
- import { PREFS_ENV, globalPref, prefsFileIn } from "../lib/prefs-value.mjs";
73
- import { itemNames } from "../lib/service-account.mjs";
74
- import { check as lowDiskCheck } from "../lib/low-disk.mjs";
75
- import { exitOnHelp } from "../lib/cli-help.mjs";
76
- import { LEGACY_SERVER_ID, MCP_SERVER_ID, projectLegacyEntries } from "../lib/mcp-rename.mjs";
77
- import { didYouMean } from "../lib/args.mjs";
78
- import { HOST_IDS, STATE_ROOT, currentHostId, host } from "../lib/host.mjs";
79
- import { localModelProblem } from "../lib/local-model.mjs";
80
- import { reportingState } from "./usage-register.mjs";
81
- import { accessDoctorLine, readAccessState } from "./usage-access.mjs";
82
- import { familyLine, loadFromManifest, schemaLoadByFamily } from "../lib/mcp-schema-load.mjs";
83
-
84
- exitOnHelp(import.meta.url);
85
-
86
- const HERE = dirname(fileURLToPath(import.meta.url));
87
- const HOME = homedir();
88
- // Shared state: logs, preferences, knowledge and the Claude Code settings file
89
- // live here whichever hosts are installed.
90
- const CLAUDE = join(HOME, STATE_ROOT);
91
- // The install this doctor is part of. Running from a checkout there is no
92
- // install to read, so the checks that need one answer about the first host.
93
- // Reading `.claude` on a Copilot-only machine reported "no install" on a
94
- // machine with a complete one.
95
- const HOST_ID = currentHostId(HERE) ?? HOST_IDS[0];
96
- const HOST = host(HOST_ID);
97
- const HOST_TREE = currentHostId(HERE) ? dirname(HERE) : join(HOME, HOST.install.root);
98
- const PREFS = prefsFileIn(HOME);
99
-
100
- const argv = process.argv.slice(2);
101
- const JSON_OUT = argv.includes("--json");
102
- const PROBE = argv.includes("--probe");
103
- const EXPLAIN = argv.includes("--explain");
104
- const LIST = argv.includes("--list-checks");
105
- // `--profile server` adds checks that only matter when nobody is at the
106
- // keyboard. They are ADDITIVE: the default run is byte-for-byte what it was,
107
- // because a laptop being told it fails a server check would teach people to
108
- // ignore doctor.
109
- const profileFlag = argv.find((a) => a.startsWith("--profile="));
110
- const PROFILE = profileFlag ? profileFlag.slice("--profile=".length) : "";
111
- const taskFlag = argv.find((a) => a.startsWith("--task-tools="));
112
- const TASK_TOOLS = taskFlag ? taskFlag.split("=")[1] : null;
113
- const onlyAt = argv.findIndex((a) => a === "--only" || a.startsWith("--only="));
114
- const ONLY_RAW =
115
- onlyAt === -1
116
- ? null
117
- : argv[onlyAt].startsWith("--only=")
118
- ? argv[onlyAt].slice("--only=".length)
119
- : (argv[onlyAt + 1] ?? "");
120
- const SELECTION =
121
- ONLY_RAW === null
122
- ? null
123
- : ONLY_RAW.split(",")
124
- .map((s) => s.trim())
125
- .filter(Boolean);
126
-
127
- // The report shape `--json` prints; schemas/doctor-report.schema.json.
128
- const SCHEMA_VERSION = 1;
129
-
130
- // The id set. Kept here and in features/doctor.md, and smoke-doctor.sh asserts
131
- // the two are equal in BOTH directions: a check cannot ship without its entry,
132
- // and an entry cannot outlive its check.
133
- const CHECK_IDS = [
134
- "host-platform",
135
- "install-present",
136
- "install-version",
137
- "update-policy",
138
- "script-surface",
139
- "skill-siblings",
140
- "state-writable",
141
- "prefs-valid",
142
- "identity",
143
- "hook-coverage",
144
- "hook-reachability",
145
- "guard-rules",
146
- "credential-mapping",
147
- "credential-liveness",
148
- "store-reference",
149
- "embedded-credentials",
150
- "task-tools",
151
- "mcp-registration",
152
- "mcp-surface",
153
- "mcp-schema-load",
154
- "mcp-failures",
155
- "disk-space",
156
- "worktree-residue",
157
- "usage-report",
158
- "usage-register",
159
- "access",
160
- "free-models",
161
- "local-model",
162
- "xcode-skills",
163
- "routine-commands",
164
- "mcp-legacy-names",
165
- ];
166
-
167
- // Only under `--profile server`. Kept in their own list so `--list-checks`
168
- // can say which ones a default run does not include.
169
- const SERVER_CHECK_IDS = [
170
- "unattended-contract",
171
- "unattended-permissions",
172
- "scheduler",
173
- "keychain-unlock",
174
- ];
175
-
176
- // Only these six may return BLOCK. Enforced below, not merely documented: a
177
- // check that returns BLOCK without being listed here is downgraded and the
178
- // downgrade is reported, because an unenforced rule is a comment.
179
- const MAY_BLOCK = new Set([
180
- "host-platform",
181
- "install-present",
182
- "script-surface",
183
- "state-writable",
184
- "prefs-valid",
185
- "embedded-credentials",
186
- ]);
187
-
188
- // The step's first word. A closed list is what stops "consider reviewing your
189
- // configuration" from being an acceptable answer.
190
- const STEP_VERBS = [
191
- "run",
192
- "set",
193
- "map",
194
- "revoke",
195
- "install",
196
- "remove",
197
- "free",
198
- "export",
199
- "merge",
200
- "record",
201
- "re-run",
202
- ];
203
-
204
- const results = [];
205
- const STEP_RE = new RegExp(`^(${STEP_VERBS.join("|")})\\b`);
206
-
207
- function report(id, severity, problem, step, detail) {
208
- let sev = severity;
209
- if (sev === "BLOCK" && !MAY_BLOCK.has(id)) {
210
- sev = "WARN";
211
- problem = `${problem} (downgraded: ${id} is not a blocking check)`;
212
- }
213
- // The writing contract is enforced where a step is written, not only in the
214
- // gate. A rule that lives solely in a test is a rule the next author will not
215
- // see, and "consider reviewing your configuration" is the shape it decays to.
216
- if (step && !STEP_RE.test(step)) {
217
- throw new Error(
218
- `doctor: the step for "${id}" must start with one of ${STEP_VERBS.join(", ")} - got "${step}"`,
219
- );
220
- }
221
- results.push({ id, severity: sev, problem, step: step || null, detail: detail || null });
222
- }
223
- const ok = (id) => report(id, "OK", null, null);
224
- const skip = (id, why) => report(id, "SKIP", why, null);
225
-
226
- function readJson(path) {
227
- try {
228
- return JSON.parse(readFileSync(path, "utf8"));
229
- } catch {
230
- return null;
231
- }
232
- }
233
-
234
- /* ---------------------------------------------------------------- checks -- */
235
-
236
- // The scope is pinned in the reinstall step on purpose. A `@mmerterden:registry=`
237
- // line in the user's own .npmrc outranks `--registry`, so an unpinned npx
238
- // resolves against whatever that file names - which on a machine configured for
239
- // GitHub Packages is a 404 and a process that never starts. A health check whose
240
- // one step silently fails is worse than no step. Rule: smoke-npm-scope-pinning.sh.
241
- const SUBTREES = HOST.install.subtrees;
242
-
243
- // Runs before everything else so a non-darwin host gets one honest line instead
244
- // of a cascade of failures whose common cause is never stated. This blocks
245
- // rather than warns because a run there does not degrade, it fails: every
246
- // credential read shells `security`, every iOS build `xcodebuild`, every piece
247
- // of visual evidence `simctl`.
248
- function checkHostPlatform() {
249
- if (process.platform === "darwin") {
250
- ok("host-platform");
251
- return true;
252
- }
253
- report(
254
- "host-platform",
255
- "BLOCK",
256
- `this host reports "${process.platform}"; the pipeline supports macOS only`,
257
- "install on macOS, or set MULTI_AGENT_ALLOW_NON_DARWIN=1 to proceed untested",
258
- );
259
- return false;
260
- }
261
-
262
- function checkInstallPresent() {
263
- if (!existsSync(HOST_TREE)) {
264
- report(
265
- "install-present",
266
- "BLOCK",
267
- `no install at ${HOST_TREE}`,
268
- "consider reinstalling",
269
- );
270
- return false;
271
- }
272
- const missing = SUBTREES.filter((d) => !existsSync(join(HOST_TREE, d)));
273
- if (missing.length) {
274
- report(
275
- "install-present",
276
- "BLOCK",
277
- `the install is missing ${missing.join(", ")}`,
278
- "run npx --@mmerterden:registry=https://registry.npmjs.org @mmerterden/multi-agent-pipeline install",
279
- );
280
- return false;
281
- }
282
- ok("install-present");
283
- return true;
284
- }
285
-
286
- function checkInstallVersion() {
287
- const stamp = join(HOST_TREE, ".pipeline-version");
288
- if (!existsSync(stamp)) {
289
- skip("install-version", "no .pipeline-version stamp in the installed tree");
290
- return;
291
- }
292
- const installed = readFileSync(stamp, "utf8").trim();
293
- const pkgPath = join(HERE, "..", "..", "package.json");
294
- const pkg = existsSync(pkgPath) ? readJson(pkgPath) : null;
295
- if (!pkg?.version) {
296
- skip("install-version", "no checkout resolved from here to compare against");
297
- return;
298
- }
299
- if (installed !== pkg.version) {
300
- report(
301
- "install-version",
302
- "WARN",
303
- `installed ${installed}, this checkout is ${pkg.version}`,
304
- `run ${hostCommand("update", HERE)}`,
305
- );
306
- return;
307
- }
308
- ok("install-version");
309
- }
310
-
311
- // Whether a run updates itself before it starts, read the way the run reads it.
312
- //
313
- // The schema defaults `enabled`, `ttlHours` and `autoUpdate`, so a preferences
314
- // file with no `updateCheck` block behaves exactly like one that sets all three
315
- // - and that is the problem this reports. The setting that decides whether a
316
- // run silently updates itself is then invisible in the file somebody opens to
317
- // change it, and the only way to learn the answer is to read the schema.
318
- //
319
- // Reported, never written. A preferences file is the user's, and a diagnostic
320
- // that edits one is not a diagnostic.
321
- function checkUpdatePolicy() {
322
- const prefs = readJson(PREFS);
323
- if (!prefs) {
324
- skip("update-policy", "no preferences file to read");
325
- return;
326
- }
327
- const uc = prefs.global?.updateCheck;
328
- const effective = {
329
- enabled: uc?.enabled ?? true,
330
- ttlHours: uc?.ttlHours ?? 24,
331
- autoUpdate: uc?.autoUpdate ?? true,
332
- };
333
- const spelled = uc && typeof uc === "object" ? Object.keys(uc) : [];
334
- const missing = ["enabled", "ttlHours", "autoUpdate"].filter((k) => !spelled.includes(k));
335
- const summary = `enabled=${effective.enabled}, autoUpdate=${effective.autoUpdate}, ttlHours=${effective.ttlHours}`;
336
- if (missing.length === 0) {
337
- ok("update-policy");
338
- return;
339
- }
340
- report(
341
- "update-policy",
342
- "INFO",
343
- `${summary} - ${missing.join(", ")} come from the schema, not from your preferences file`,
344
- "set global.updateCheck in ~/.claude/multi-agent-preferences.json to make the policy explicit",
345
- );
346
- }
347
-
348
- function checkScriptSurface() {
349
- const cmdDir = join(HOST_TREE, HOST.install.commandSpecs);
350
- if (!existsSync(cmdDir)) {
351
- skip("script-surface", "no installed command tree to read");
352
- return;
353
- }
354
- const wanted = new Set();
355
- for (const d of readdirSync(cmdDir)) {
356
- const f = join(cmdDir, d, "SKILL.md");
357
- if (!existsSync(f)) continue;
358
- const text = readFileSync(f, "utf8");
359
- // The path segment has to allow `/`. Without it a reference to
360
- // `scripts/nested/bar.mjs` was truncated to the directory, so as long as the
361
- // directory existed a missing file one level inside it passed - the check
362
- // reported OK for exactly the case it exists to catch.
363
- // The install rewrites `$HOME/.claude/...` into the host's own root as the
364
- // files land, so the text to match is this host's spelling, not the one the
365
- // repo is written in.
366
- for (const m of text.matchAll(
367
- new RegExp(
368
- `\\$HOME/\\${HOST.install.root}/(scripts|lib)/([A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*)`,
369
- "g",
370
- ),
371
- )) {
372
- wanted.add(join(m[1], m[2]));
373
- }
374
- }
375
- const missing = [...wanted].filter((rel) => !existsSync(join(HOST_TREE, rel))).sort();
376
- if (missing.length) {
377
- report(
378
- "script-surface",
379
- "BLOCK",
380
- `${missing.length} script(s) a command calls are not installed: ${missing.slice(0, 3).join(", ")}`,
381
- `run ${hostCommand("update", HERE)}`,
382
- missing,
383
- );
384
- return;
385
- }
386
- ok("script-surface");
387
- }
388
-
389
- function checkSkillSiblings() {
390
- const sib = join(HOST_TREE, "scripts", "skill-siblings.mjs");
391
- if (!existsSync(sib)) {
392
- skip("skill-siblings", "skill-siblings.mjs is not installed");
393
- return;
394
- }
395
- let out;
396
- try {
397
- out = execFileSync("node", [sib, "--audit", "--json"], {
398
- encoding: "utf8",
399
- stdio: ["ignore", "pipe", "pipe"],
400
- });
401
- } catch (e) {
402
- report(
403
- "skill-siblings",
404
- "WARN",
405
- `the sibling audit did not complete: ${String(e.message).split("\n")[0]}`,
406
- `run ${hostCommand("sync", HERE)}`,
407
- );
408
- return;
409
- }
410
- const j = (() => {
411
- try {
412
- return JSON.parse(out);
413
- } catch {
414
- return null;
415
- }
416
- })();
417
- if (!j) {
418
- report(
419
- "skill-siblings",
420
- "WARN",
421
- "the sibling audit returned no JSON",
422
- `run ${hostCommand("sync", HERE)}`,
423
- );
424
- return;
425
- }
426
- // A local-only wrapper is authored for this machine and deliberately excluded
427
- // from the sync, so it is absent from Copilot and Codex by design. Counting it
428
- // as unsynced told the user to run a sync that would change nothing - a health
429
- // check whose one step is a no-op teaches people to ignore it.
430
- const localOnly = new Set();
431
- const cmdRoot = join(HOST_TREE, HOST.install.commandSpecs);
432
- if (existsSync(cmdRoot)) {
433
- for (const d of readdirSync(cmdRoot)) {
434
- const f = join(cmdRoot, d, "SKILL.md");
435
- if (existsSync(f) && /^local-only:\s*true/m.test(readFileSync(f, "utf8"))) localOnly.add(d);
436
- }
437
- }
438
- const unsynced = (j.rows || []).filter(
439
- (r) => !localOnly.has(r.name) && (r.missingInstalled || []).length > 0,
440
- ).length;
441
- if (unsynced > 0) {
442
- report(
443
- "skill-siblings",
444
- "WARN",
445
- `${unsynced} of ${j.commands - localOnly.size} synced command(s) are missing from at least one installed host`,
446
- `run ${hostCommand("sync", HERE)}`,
447
- );
448
- return;
449
- }
450
- ok("skill-siblings");
451
- }
452
-
453
- function checkStateWritable() {
454
- const dir = join(CLAUDE, "logs", "multi-agent");
455
- try {
456
- mkdirSync(dir, { recursive: true });
457
- const probe = join(dir, `.doctor-${process.pid}`);
458
- writeFileSync(probe, "x");
459
- rmSync(probe);
460
- } catch (e) {
461
- report(
462
- "state-writable",
463
- "BLOCK",
464
- `cannot write run state under ${dir}: ${e.code || e.message}`,
465
- `run chmod u+w ${dir}`,
466
- );
467
- return;
468
- }
469
- ok("state-writable");
470
- }
471
-
472
- function checkPrefsValid() {
473
- const prefs = PREFS;
474
- if (!existsSync(prefs)) {
475
- report("prefs-valid", "WARN", "no preferences file yet", `run ${hostCommand("setup", HERE)}`);
476
- return;
477
- }
478
- const j = readJson(prefs);
479
- if (!j) {
480
- report(
481
- "prefs-valid",
482
- "BLOCK",
483
- "multi-agent-preferences.json does not parse",
484
- `run ${hostCommand("setup", HERE)}`,
485
- );
486
- return;
487
- }
488
- if (typeof j.global !== "object" || j.global === null) {
489
- report(
490
- "prefs-valid",
491
- "BLOCK",
492
- "preferences carry no global block",
493
- `run ${hostCommand("setup", HERE)}`,
494
- );
495
- return;
496
- }
497
- ok("prefs-valid");
498
- }
499
-
500
- function checkIdentity() {
501
- // The key is `identities[]` - a list, because a machine with a work and a
502
- // personal account needs both, and `platformIdentityRouting` picks per remote.
503
- // Looking for a singular `identity` reported "none recorded" on a machine with
504
- // two, which is the shape of wrongness a health check must not have.
505
- const prefs = readJson(PREFS);
506
- const list = prefs?.global?.identities;
507
- const usable = Array.isArray(list) ? list.filter((i) => i?.name && i?.email) : [];
508
- if (usable.length) {
509
- ok("identity");
510
- return;
511
- }
512
- report(
513
- "identity",
514
- "WARN",
515
- "no git identity recorded, so a run stops at the commit phase",
516
- `run ${hostCommand("setup", HERE)}`,
517
- );
518
- }
519
-
520
- function checkHookCoverage() {
521
- // These hooks are entries in Claude Code's own settings file, which only that
522
- // host reads, so the template and the file it merges into are both under the
523
- // state root rather than under this host's tree.
524
- if (HOST_ID !== "claude") {
525
- skip("hook-coverage", `${HOST.label} does not read Claude Code's hooks file`);
526
- return;
527
- }
528
- const tpl = join(CLAUDE, "templates", "claude-hooks.json");
529
- if (!existsSync(tpl)) {
530
- skip("hook-coverage", "no hooks template installed to compare against");
531
- return;
532
- }
533
- const want = readJson(tpl);
534
- const have = readJson(join(CLAUDE, "settings.json"));
535
- if (!want) {
536
- skip("hook-coverage", "the hooks template does not parse");
537
- return;
538
- }
539
- const wantedCmds = new Set();
540
- for (const group of Object.values(want.hooks || {})) {
541
- for (const entry of group || []) {
542
- for (const h of entry.hooks || []) if (h.command) wantedCmds.add(h.command);
543
- }
544
- }
545
- const haveCmds = new Set();
546
- for (const group of Object.values(have?.hooks || {})) {
547
- for (const entry of Array.isArray(group) ? group : []) {
548
- for (const h of entry?.hooks || [])
549
- if (typeof h?.command === "string") haveCmds.add(h.command);
550
- }
551
- }
552
- const absent = [...wantedCmds].filter((c) => !haveCmds.has(c));
553
- if (absent.length) {
554
- report(
555
- "hook-coverage",
556
- "WARN",
557
- `${absent.length} of ${wantedCmds.size} template hook(s) are not in settings.json`,
558
- `merge ${tpl} into ${join(CLAUDE, "settings.json")}`,
559
- );
560
- return;
561
- }
562
- const seen = new Set();
563
- const twice = new Set();
564
- for (const [event, groups] of Object.entries(have?.hooks || {})) {
565
- for (const group of Array.isArray(groups) ? groups : []) {
566
- for (const h of group?.hooks || []) {
567
- if (typeof h?.command !== "string") continue;
568
- const key = `${event} ${group.matcher || ""} ${h.command}`;
569
- if (seen.has(key)) twice.add(`${h.command.split("/").pop()} on ${group.matcher || event}`);
570
- seen.add(key);
571
- }
572
- }
573
- }
574
- if (twice.size) {
575
- report(
576
- "hook-coverage",
577
- "WARN",
578
- `registered twice, so it runs twice per call: ${[...twice].join(", ")}`,
579
- `run ${hostCommand("update", HERE)}`,
580
- );
581
- return;
582
- }
583
- ok("hook-coverage");
584
- }
585
-
586
- // hook-coverage asks whether each template command appears in settings.json
587
- // at all. This asks what Claude Code will actually run: per event, a matcher
588
- // that covers the template's tool names, the script present under
589
- // ~/.claude/scripts, no disableAllHooks; and which preferences do nothing
590
- // because their hook is missing (lib/hook-registration.mjs).
591
- function checkHookReachability() {
592
- // These hooks are entries in Claude Code's own settings file, which only that
593
- // host reads, so the template and the file it merges into are both under the
594
- // state root rather than under this host's tree.
595
- if (HOST_ID !== "claude") {
596
- skip("hook-reachability", `${HOST.label} does not read Claude Code's hooks file`);
597
- return;
598
- }
599
- const tpl = join(CLAUDE, "templates", "claude-hooks.json");
600
- if (!existsSync(tpl)) {
601
- skip("hook-reachability", "no hooks template installed to compare against");
602
- return;
603
- }
604
- const r = hookReport({ templatePath: tpl, home: HOME });
605
- if (r.error) {
606
- skip("hook-reachability", r.error);
607
- return;
608
- }
609
- if (r.ok) {
610
- ok("hook-reachability");
611
- return;
612
- }
613
- const parts = [];
614
- if (r.disabled) parts.push(r.disabled);
615
- else if (r.missing.length) {
616
- const names = [
617
- ...new Set(
618
- r.missing.map(
619
- (m) => `${m.script || m.command} on ${m.event}${m.matcher ? ` ${m.matcher}` : ""}`,
620
- ),
621
- ),
622
- ];
623
- parts.push(
624
- `${r.missing.length} template hook(s) Claude Code will not run: ${names.slice(0, 4).join(", ")}${names.length > 4 ? ` and ${names.length - 4} more` : ""}`,
625
- );
626
- }
627
- if (r.inert.length) {
628
- parts.push(
629
- `inert preference(s): ${r.inert.map((i) => `${i.pref} (needs ${i.script})`).join(", ")}`,
630
- );
631
- }
632
- report(
633
- "hook-reachability",
634
- "WARN",
635
- parts.join("; "),
636
- `merge ${tpl} into ${join(CLAUDE, "settings.json")} (or run ${hostCommand("setup", HERE)})`,
637
- [
638
- ...r.missing.map((m) => `${m.event} ${m.matcher || "-"} ${m.command}: ${m.why}`),
639
- ...r.inert.map((i) => `prefs.global.${i.pref} -> ${i.script}`),
640
- ],
641
- );
642
- }
643
-
644
- // prefs.global.guardRules as the guard reads them (_user_guard_rules.py
645
- // --report, same file lookup), so doctor and the guard cannot disagree on
646
- // which rule is valid. Reports rule labels and problems, never a pattern.
647
- // A rule whose tool agent-guard.sh is not registered on does nothing; Read is
648
- // the usual case, since the default hooks do not register the guard there.
649
- const GUARD_COMMAND = 'bash "$HOME/.claude/scripts/agent-guard.sh"';
650
- // The host tools a rule's tool name governs. MultiEdit is left out: the
651
- // current host has no such tool, so requiring a registration for it would
652
- // warn on every default install.
653
- const GUARD_RULE_TOOLS = { Edit: ["Edit", "NotebookEdit"] };
654
-
655
- function guardRulesReport() {
656
- const script = join(HERE, "_user_guard_rules.py");
657
- if (!existsSync(script)) return { skip: "_user_guard_rules.py is not installed" };
658
- try {
659
- const out = execFileSync("python3", [script, "--report"], {
660
- encoding: "utf8",
661
- timeout: 10000,
662
- stdio: ["ignore", "pipe", "ignore"],
663
- });
664
- return JSON.parse(out);
665
- } catch {
666
- return { skip: "python3 could not read the guard rules" };
667
- }
668
- }
669
-
670
- function checkGuardRules() {
671
- const r = guardRulesReport();
672
- if (r.skip) {
673
- skip("guard-rules", r.skip);
674
- return;
675
- }
676
- if (r.error) {
677
- report(
678
- "guard-rules",
679
- "WARN",
680
- `${r.error}: no guard rule applies; attended each call a rule could govern carries a note, and ` +
681
- (r.holdsRules === false
682
- ? "unattended nothing is refused, since the file does not name guardRules"
683
- : "every such call is refused unattended"),
684
- `set ${r.source} to valid JSON with prefs.global.guardRules as a list`,
685
- null,
686
- );
687
- return;
688
- }
689
- if (!r.rules) {
690
- ok("guard-rules");
691
- return;
692
- }
693
- const parts = [];
694
- const detail = [];
695
- const step = [];
696
- if (r.invalid.length) {
697
- const blocks = r.invalid.filter((i) => i.action === "block" && i.tool).length;
698
- parts.push(
699
- `${r.invalid.length} of ${r.rules} guard rule(s) are invalid and ignored` +
700
- (blocks ? `, and ${blocks} invalid block rule(s) refuse their tool unattended` : ""),
701
- );
702
- for (const i of r.invalid) detail.push(`${i.label}: ${i.problem}`);
703
- step.push("set prefs.global.guardRules so every rule validates (--explain names each)");
704
- }
705
- const uncovered = r.tools.flatMap((tool) => {
706
- const names = GUARD_RULE_TOOLS[tool] || [tool.replace(/[*?]/g, "x")];
707
- const missing = names.filter((name) => {
708
- const template = {
709
- hooks: {
710
- PreToolUse: [{ matcher: name, hooks: [{ type: "command", command: GUARD_COMMAND }] }],
711
- },
712
- };
713
- return registrationGaps({ template, home: HOME }).missing.length > 0;
714
- });
715
- if (!missing.length) return [];
716
- return [missing.length === names.length ? tool : `${tool} (${missing.join(", ")})`];
717
- });
718
- if (uncovered.length) {
719
- parts.push(
720
- `guard rules for ${uncovered.join(", ")} do nothing: agent-guard.sh is not registered there`,
721
- );
722
- for (const t of uncovered) detail.push(`PreToolUse ${t}: agent-guard.sh not registered`);
723
- step.push(
724
- `merge a PreToolUse entry running agent-guard.sh for ${uncovered.join(", ")} into ${join(CLAUDE, "settings.json")}`,
725
- );
726
- }
727
- const slow = Array.isArray(r.slow) ? r.slow : [];
728
- const slowNote =
729
- `${slow.length} guard rule(s) have a slow shape and run under the 1-second matching budget, ` +
730
- "where a block or ask rule that runs out of time refuses unattended and asks attended";
731
- for (const i of slow) detail.push(`${i.label}: ${i.shape}`);
732
- if (!parts.length && slow.length) {
733
- report(
734
- "guard-rules",
735
- "INFO",
736
- slowNote,
737
- "set each named rule's match to a tighter pattern: bound the inner quantifier or make its neighbours disjoint",
738
- detail,
739
- );
740
- return;
741
- }
742
- if (slow.length) parts.push(slowNote);
743
- if (!parts.length) {
744
- ok("guard-rules");
745
- return;
746
- }
747
- report("guard-rules", "WARN", parts.join("; "), step.join("; then "), detail);
748
- }
749
-
750
- function credentialInventory() {
751
- const inv = join(HOST_TREE, "lib", "credential-inventory.sh");
752
- if (!existsSync(inv)) return null;
753
- try {
754
- const args = PROBE ? [inv, "--json", "--probe"] : [inv, "--json"];
755
- return JSON.parse(
756
- execFileSync("bash", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }),
757
- );
758
- } catch {
759
- return null;
760
- }
761
- }
762
-
763
- function checkCredentials(inv) {
764
- if (!inv) {
765
- skip("credential-mapping", "credential-inventory.sh did not produce an inventory");
766
- skip("credential-liveness", "credential-inventory.sh did not produce an inventory");
767
- return;
768
- }
769
- // The INFO / WARN boundary is decided in credential-inventory.sh; this only
770
- // renders it. Unmapped is a capability the user chose not to enable, which is
771
- // information. A mapped credential the service refused is a warning, because
772
- // the configuration made a claim.
773
- const malformed = (inv.credentials || []).filter((c) => c.state === "malformed");
774
- const unmapped = (inv.credentials || []).filter((c) => c.state === "unmapped");
775
- if (malformed.length) {
776
- report(
777
- "credential-mapping",
778
- "WARN",
779
- `${malformed.length} mapped credential(s) are malformed: ${malformed.map((c) => c.logical).join(", ")}`,
780
- `run ${hostCommand("setup", HERE)}`,
781
- );
782
- } else if (unmapped.length) {
783
- // A generated credential is created by its own command, never pasted, so
784
- // setup cannot map it and the step names that command instead.
785
- const pasted = unmapped.filter((c) => !c.generated);
786
- const generated = unmapped.filter((c) => c.generated);
787
- const steps = [
788
- ...(pasted.length
789
- ? [`map ${pasted.map((c) => c.logical).join(", ")} with ${hostCommand("setup", HERE)}`]
790
- : []),
791
- ...generated.map((c) => c.remedy),
792
- ];
793
- report(
794
- "credential-mapping",
795
- "INFO",
796
- `${unmapped.length} optional capabilit${unmapped.length === 1 ? "y is" : "ies are"} not enabled: ${unmapped.map((c) => c.logical).join(", ")}`,
797
- steps.join("; "),
798
- );
799
- } else {
800
- ok("credential-mapping");
801
- }
802
-
803
- if (!PROBE) {
804
- skip("credential-liveness", "no --probe: a network check is the caller's decision to spend");
805
- return;
806
- }
807
- // A rejected credential and an unreachable host need different actions, and
808
- // credential-inventory.sh already separates them: "unreachable - no response
809
- // at all - on a corporate host, almost always the VPN". Telling someone to
810
- // re-onboard a token that was never the problem is the failure mode the
811
- // registry's own keychain rule warns about, one layer up.
812
- const rejected = [
813
- ...(inv.authRejected || []).map((k) => [k, "rejected"]),
814
- ...(inv.needsGrant || []).map((k) => [k, "no grant"]),
815
- ];
816
- const unreachable = (inv.unreachable || []).slice();
817
- if (rejected.length) {
818
- report(
819
- "credential-liveness",
820
- "WARN",
821
- `${rejected.length} credential(s) were refused: ${rejected.map(([k, w]) => `${k} (${w})`).join(", ")}`,
822
- `run ${hostCommand("setup", HERE)}`,
823
- );
824
- return;
825
- }
826
- if (unreachable.length) {
827
- report(
828
- "credential-liveness",
829
- "WARN",
830
- `${unreachable.length} host(s) did not answer at all: ${unreachable.join(", ")}`,
831
- "run the probe again on the network those hosts are on",
832
- );
833
- return;
834
- }
835
- ok("credential-liveness");
836
- }
837
-
838
- // The toolkit's store_* tools find the App Store Connect and Google Play keys
839
- // through a reference file naming Keychain services, written by
840
- // write-store-config.mjs from the items this machine's accounts name. A file
841
- // that does not reflect them means the keys sit in the Keychain and every
842
- // store call still says "not onboarded". No account is nothing claimed, so
843
- // that case is OK.
844
- const STORE_OF_SERVICE = {
845
- appstore_connect: "appStoreConnect",
846
- google_play: "googlePlay",
847
- };
848
- const STORE_SLOTS = {
849
- appstore_connect: ["key_id", "issuer_id", "private_key"],
850
- google_play: ["service_account_json"],
851
- };
852
- const STORE_LABELS = { appStoreConnect: "App Store Connect", googlePlay: "Google Play" };
853
-
854
- /** The stores whose keys this machine's accounts name at all. */
855
- function storesNamed(prefs) {
856
- const named = itemNames(prefs).filter((x) => STORE_SLOTS[x.service]?.includes(x.slot));
857
- return [...new Set(named.map((x) => STORE_OF_SERVICE[x.service]))];
858
- }
859
-
860
- function checkStoreReference() {
861
- const prefsFile = PREFS;
862
- const mapped = storesNamed(readJson(prefsFile));
863
- if (!mapped.length) {
864
- ok("store-reference");
865
- return;
866
- }
867
- const writer = join(HOST_TREE, "scripts", "write-store-config.mjs");
868
- if (!existsSync(writer)) {
869
- skip("store-reference", "write-store-config.mjs is not installed");
870
- return;
871
- }
872
- let res;
873
- try {
874
- const out = execFileSync(process.execPath, [writer, "--check"], {
875
- encoding: "utf8",
876
- stdio: ["ignore", "pipe", "ignore"],
877
- env: {
878
- ...process.env,
879
- [PREFS_ENV]: prefsFile,
880
- CRED_STORE: join(HOST_TREE, "lib", "credential-store.sh"),
881
- },
882
- });
883
- res = JSON.parse(out);
884
- } catch (e) {
885
- try {
886
- res = JSON.parse(String(e.stdout || ""));
887
- } catch {
888
- res = null;
889
- }
890
- }
891
- if (!res || res.error) {
892
- skip("store-reference", res?.error || "write-store-config.mjs --check produced no verdict");
893
- return;
894
- }
895
- const fix = `run node "$HOME/${basename(HOST_TREE)}/scripts/write-store-config.mjs"`;
896
- if (res.state !== "current") {
897
- const ready = Object.entries(res.stores || {})
898
- .filter(([, v]) => v.included)
899
- .map(([k]) => STORE_LABELS[k] || k);
900
- report(
901
- "store-reference",
902
- "WARN",
903
- `store keys are in the Keychain but the store reference file ${res.state === "missing" ? "is missing" : "is stale"} (${res.path}), so store_* tools cannot find ${ready.join(" and ") || "them"}`,
904
- fix,
905
- );
906
- return;
907
- }
908
- const partial = Object.entries(res.stores || {}).filter(
909
- ([store, v]) => !v.included && mapped.includes(store),
910
- );
911
- if (partial.length) {
912
- report(
913
- "store-reference",
914
- "INFO",
915
- partial
916
- .map(
917
- ([store, v]) =>
918
- `${STORE_LABELS[store] || store} is partly onboarded, missing ${v.missing.join(", ")}`,
919
- )
920
- .join("; "),
921
- `run ${hostCommand("setup", HERE)}`,
922
- );
923
- return;
924
- }
925
- ok("store-reference");
926
- }
927
-
928
- function checkEmbeddedCredentials() {
929
- // The value never enters a shell variable or this process's output. What is
930
- // reported is the repo, the config key, the host, a shape label and a length
931
- // bucket - because `ghp_` plus a length is already a fingerprint, and this
932
- // line goes to a terminal that is often shared, which is why the check exists.
933
- const roots = [process.cwd()];
934
- const found = [];
935
- for (const root of roots) {
936
- const cfg = join(root, ".git", "config");
937
- if (!existsSync(cfg)) continue;
938
- let text;
939
- try {
940
- text = readFileSync(cfg, "utf8");
941
- } catch {
942
- continue;
943
- }
944
- for (const line of text.split("\n")) {
945
- const m = line.match(/^\s*(url)\s*=\s*(\S+)\s*$/);
946
- if (!m) continue;
947
- const cred = m[2].match(/^https?:\/\/([^@/]+)@([^/]+)/);
948
- if (!cred) continue;
949
- const secret = cred[1].includes(":") ? cred[1].split(":")[1] : cred[1];
950
- if (!secret || secret.length < 8) continue;
951
- const bucket = secret.length < 40 ? "<40" : secret.length < 100 ? "40-99" : ">=100";
952
- found.push({
953
- repo: root,
954
- key: m[1],
955
- host: cred[2],
956
- shape: "userinfo-in-url",
957
- length: bucket,
958
- });
959
- }
960
- }
961
- if (found.length) {
962
- const f = found[0];
963
- report(
964
- "embedded-credentials",
965
- "BLOCK",
966
- `a credential is embedded in a git remote (${f.repo}, ${f.key}, host ${f.host}, ${f.shape}, length ${f.length})`,
967
- `revoke that credential at ${f.host}`,
968
- found,
969
- );
970
- return;
971
- }
972
- ok("embedded-credentials");
973
- }
974
-
975
- function checkTaskTools() {
976
- if (TASK_TOOLS !== "yes" && TASK_TOOLS !== "no") {
977
- // A script cannot see the model's tool list. Answering "absent" from here
978
- // would be the same defect this check is about.
979
- skip("task-tools", "the caller did not report its tool list (--task-tools=yes|no)");
980
- return;
981
- }
982
- if (TASK_TOOLS === "yes") {
983
- ok("task-tools");
984
- return;
985
- }
986
- report(
987
- "task-tools",
988
- "INFO",
989
- "this session's model does not carry TaskCreate/TaskUpdate, so the phase widget cannot render",
990
- "export CLAUDE_CODE_ENABLE_TODO_TOOLS=1 before starting Claude Code",
991
- );
992
- }
993
-
994
- // What checkMcpRegistration found, for checkMcpSchemaLoad: the registered
995
- // toolkit entry and, under --probe, the tools/list it served.
996
- let toolkitEntry = null;
997
- let probedTools = null;
998
-
999
- function checkMcpRegistration() {
1000
- // Registered is not the same as working, and the difference is what the user
1001
- // actually hits: a half-extracted package in the npx cache left the server
1002
- // dying on `Cannot find module` at startup, which the client reports only as
1003
- // CONNECTION_CLOSED. A check that reads the registration and stops would have
1004
- // called that healthy. So without --probe this reports what is CONFIGURED and
1005
- // says so; with --probe it starts the server and counts the tools it serves.
1006
- let entry = null;
1007
- for (const p of [join(HOME, ".claude.json"), join(CLAUDE, "settings.json")]) {
1008
- const j = readJson(p);
1009
- const key = j?.mcpServers && Object.keys(j.mcpServers).find((k) => k === MCP_SERVER_ID);
1010
- if (key) {
1011
- entry = j.mcpServers[key];
1012
- break;
1013
- }
1014
- }
1015
- if (!entry) {
1016
- report(
1017
- "mcp-registration",
1018
- "INFO",
1019
- "multi-agent is not registered as an MCP server, so its tools are unavailable",
1020
- `install it with ${[HOST.cli.candidates[0], "mcp", "add", ...HOST.cli.scopeArgs, "multi-agent"].join(" ")}`,
1021
- );
1022
- return;
1023
- }
1024
- if (!PROBE) {
1025
- ok("mcp-registration");
1026
- return;
1027
- }
1028
- const handshake = [
1029
- JSON.stringify({
1030
- jsonrpc: "2.0",
1031
- id: 1,
1032
- method: "initialize",
1033
- params: {
1034
- protocolVersion: "2024-11-05",
1035
- capabilities: {},
1036
- clientInfo: { name: "doctor", version: "1" },
1037
- },
1038
- }),
1039
- JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
1040
- JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" }),
1041
- ].join("\n");
1042
- toolkitEntry = entry;
1043
- let served = 0;
1044
- let servedVersion = null;
1045
- let why = "";
1046
- try {
1047
- const out = execFileSync(entry.command, entry.args || [], {
1048
- input: `${handshake}\n`,
1049
- encoding: "utf8",
1050
- timeout: 240000,
1051
- stdio: ["pipe", "pipe", "pipe"],
1052
- env: { ...process.env, ...(entry.env || {}) },
1053
- });
1054
- for (const line of out.split("\n")) {
1055
- if (!line.trim()) continue;
1056
- try {
1057
- const m = JSON.parse(line);
1058
- if (m.id === 1 && typeof m.result?.serverInfo?.version === "string")
1059
- servedVersion = m.result.serverInfo.version;
1060
- if (m.id === 2 && Array.isArray(m.result?.tools)) {
1061
- served = m.result.tools.length;
1062
- probedTools = m.result.tools;
1063
- }
1064
- } catch {
1065
- /* the server may print non-JSON lines */
1066
- }
1067
- }
1068
- } catch (e) {
1069
- why =
1070
- String(e.stderr || e.message || "")
1071
- .split("\n")
1072
- .find((l) => /Error|error/.test(l)) || "the server did not start";
1073
- }
1074
- if (served > 0) {
1075
- // The unattended guard confines exactly the parameters the vendored
1076
- // declaration names, so a toolkit of another version can carry a path
1077
- // parameter the guard only judges by its name.
1078
- const declared = readJson(
1079
- join(HERE, "..", "schemas", "toolkit-path-params.json"),
1080
- )?.toolkitVersion;
1081
- if (servedVersion && typeof declared === "string" && servedVersion !== declared) {
1082
- report(
1083
- "mcp-registration",
1084
- "WARN",
1085
- `the toolkit serves version ${servedVersion} but the unattended guard's toolkit-path-params.json was generated from ${declared}`,
1086
- "run /multi-agent:update so the pipeline and the toolkit come from the same release",
1087
- );
1088
- return;
1089
- }
1090
- ok("mcp-registration");
1091
- return;
1092
- }
1093
- report(
1094
- "mcp-registration",
1095
- "WARN",
1096
- `multi-agent is registered but served no tools${why ? ` (${why.trim().slice(0, 90)})` : ""}`,
1097
- "remove the stale npx cache entry under ~/.npm/_npx and let it re-download",
1098
- why,
1099
- );
1100
- }
1101
-
1102
- // How many MCP servers is this host paying for on every turn?
1103
- //
1104
- // checkMcpRegistration answers "is OURS registered". This answers the question the
1105
- // user never gets asked: every registered server's tool list is sent with every
1106
- // turn, they are added one at a time, and nobody sees the running total - our own
1107
- // toolkit is 115 tools by itself. This check only ever REPORTS. It never disables
1108
- // anything, and it never blocks or warns, because how many servers are worth their
1109
- // context is the user's call and not a health failure.
1110
- //
1111
- // The threshold is judgement and is therefore a pref, not a constant hidden here:
1112
- // `prefs.global.mcpSurface.infoAbove` (default 8). 0 reports the count always.
1113
- function checkMcpSurface() {
1114
- // Three places a server can be declared, and all three are charged in the
1115
- // project the caller is standing in: the global config, the per-project block
1116
- // inside ~/.claude.json, and a .mcp.json committed to the repo. Counting only
1117
- // the global block understates exactly where it matters - a project-scoped
1118
- // server is invisible to the user for the same reason a global one is.
1119
- //
1120
- // Not counted, and said so in features/doctor.md: servers a marketplace plugin
1121
- // registers. Nothing in the config names them, and guessing a number is worse
1122
- // than reporting the one that is countable.
1123
- const cwd = process.cwd();
1124
- // The per-project key is matched by resolved path, not by string. On macOS /tmp
1125
- // and /var are symlinks, so the same directory has two spellings: the one the
1126
- // host wrote into its config and the one node reports. A string compare finds
1127
- // nothing on whichever side lost the race, and reports a smaller number with no
1128
- // sign that anything was missed.
1129
- const real = (p) => {
1130
- try {
1131
- return realpathSync(p);
1132
- } catch {
1133
- return p;
1134
- }
1135
- };
1136
- const hereReal = real(cwd);
1137
- const names = new Set();
1138
- const add = (obj, scope) => {
1139
- for (const k of Object.keys(obj || {})) names.add(`${k} (${scope})`);
1140
- };
1141
- const home = readJson(join(HOME, ".claude.json"));
1142
- add(home?.mcpServers, "global");
1143
- add(readJson(join(CLAUDE, "settings.json"))?.mcpServers, "global");
1144
- for (const [dir, entry] of Object.entries(home?.projects || {})) {
1145
- if (real(dir) === hereReal) add(entry?.mcpServers, "this project");
1146
- }
1147
- add(readJson(join(cwd, ".mcp.json"))?.mcpServers, ".mcp.json");
1148
- const prefs = readJson(PREFS);
1149
- const raw = prefs?.global?.mcpSurface?.infoAbove;
1150
- const threshold = Number.isInteger(raw) && raw >= 0 ? raw : 8;
1151
- const sorted = [...names].sort();
1152
- if (sorted.length <= threshold) {
1153
- ok("mcp-surface");
1154
- return;
1155
- }
1156
- report(
1157
- "mcp-surface",
1158
- "INFO",
1159
- `${sorted.length} MCP servers are registered, and every one of them sends its tool list on every turn`,
1160
- "remove the servers this machine does not use (--explain lists them)",
1161
- sorted,
1162
- );
1163
- }
1164
-
1165
- // How much context the toolkit's tool list takes, per family, and what each
1166
- // MCP_TOOLKIT_CAPS family would save. Measured from the tools/list --probe
1167
- // served, or read from a `families` field in the tool-manifest.json beside a
1168
- // toolkit registered by path. Tokens are bytes / 4, an estimate, and said to
1169
- // be one. INFO above prefs.global.mcpSurface.schemaInfoAboveTokens (8000):
1170
- // which families a repo needs is the user's call, not a health failure.
1171
- function checkMcpSchemaLoad() {
1172
- let load = probedTools ? schemaLoadByFamily(probedTools) : null;
1173
- let from = "the served tools/list";
1174
- if (!load && toolkitEntry) {
1175
- const script = (toolkitEntry.args || []).find((a) => /index\.m?js$/.test(String(a)));
1176
- if (script) {
1177
- load = loadFromManifest(readJson(join(dirname(String(script)), "tool-manifest.json")));
1178
- from = "the toolkit's tool-manifest.json";
1179
- }
1180
- }
1181
- if (!load) {
1182
- skip(
1183
- "mcp-schema-load",
1184
- toolkitEntry || PROBE
1185
- ? "the toolkit served no tool list to measure"
1186
- : "the tool-list size is measured with --probe",
1187
- );
1188
- return;
1189
- }
1190
- const raw = readJson(PREFS)?.global?.mcpSurface?.schemaInfoAboveTokens;
1191
- const threshold = Number.isInteger(raw) && raw >= 0 ? raw : 8000;
1192
- if (load.totalTokens < threshold) {
1193
- ok("mcp-schema-load");
1194
- return;
1195
- }
1196
- const caps = toolkitEntry?.env?.MCP_TOOLKIT_CAPS;
1197
- const top = load.families
1198
- .slice(0, 3)
1199
- .map((f) => `${f.family} ~${f.tokens}`)
1200
- .join(", ");
1201
- report(
1202
- "mcp-schema-load",
1203
- "INFO",
1204
- `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}` : ""}`,
1205
- "set MCP_TOOLKIT_CAPS in the toolkit's MCP entry to the families this repo uses (--explain lists each family's estimate)",
1206
- load.families.map(familyLine),
1207
- );
1208
- }
1209
-
1210
- // The local MCP failure log note-mcp-failure.sh writes. A missing sibling
1211
- // leaves the check to SKIP rather than taking doctor down with it: doctor is
1212
- // what a half-installed machine runs.
1213
- let mcpFailureLog = null;
1214
- try {
1215
- mcpFailureLog = await import("./note-mcp-failure.mjs");
1216
- } catch {
1217
- mcpFailureLog = null;
1218
- }
1219
-
1220
- // A server whose calls keep failing, read from the failures this machine
1221
- // already recorded. Nothing is probed. INFO, never WARN: a flaky third-party
1222
- // server degrades a session but is not this install's health, and the step
1223
- // names the server so the user can decide.
1224
- function checkMcpFailures() {
1225
- if (!mcpFailureLog) {
1226
- skip("mcp-failures", "note-mcp-failure.mjs is not installed");
1227
- return;
1228
- }
1229
- if (!mcpFailureLog.captureEnabled()) {
1230
- skip("mcp-failures", "MCP failure counting is off (mcpFailures.enabled or usageLog.optOut)");
1231
- return;
1232
- }
1233
- const summary = mcpFailureLog.failureSummary(mcpFailureLog.readFailures());
1234
- const diskFull = summary.servers.filter((s) => s.classes["disk-full"]);
1235
- if (diskFull.length) {
1236
- const n = diskFull.reduce((sum, s) => sum + s.classes["disk-full"], 0);
1237
- report(
1238
- "mcp-failures",
1239
- "INFO",
1240
- `${n} MCP call(s) failed with disk-full in the last ${summary.hours} hours (${diskFull.map((s) => s.server).join(", ")})`,
1241
- `run ${hostCommand("clean-disk", HERE)}: it measures every category first and deletes only the ones you choose`,
1242
- diskFull.map((s) => ({ server: s.server, diskFull: s.classes["disk-full"] })),
1243
- );
1244
- return;
1245
- }
1246
- const repeated = summary.servers.filter((s) => summary.repeated.includes(s.server));
1247
- if (!repeated.length) {
1248
- ok("mcp-failures");
1249
- return;
1250
- }
1251
- const worst = repeated[0];
1252
- const others = repeated.length > 1 ? ` (and ${repeated.length - 1} more server(s))` : "";
1253
- report(
1254
- "mcp-failures",
1255
- "INFO",
1256
- `${worst.server} failed ${worst.failures} times in the last ${summary.hours} hours${others}`,
1257
- `run claude mcp list to see whether ${worst.server} is connected, then node ${join(HERE, "note-mcp-failure.mjs")} summary for the failing tools`,
1258
- repeated.map((r) => ({
1259
- server: r.server,
1260
- failures: r.failures,
1261
- tools: r.tools,
1262
- classes: r.classes,
1263
- last: r.last,
1264
- })),
1265
- );
1266
- }
1267
-
1268
- // usage-report.mjs runs detached with its output discarded, so the record it
1269
- // writes after every send attempt is the one place a broken reporting path
1270
- // becomes visible.
1271
- const USAGE_STEPS = {
1272
- "no-login": () => `run node ${join(HERE, "usage-identity.mjs")} --refresh`,
1273
- "no-token": () => `run node ${join(HERE, "usage-register.mjs")}`,
1274
- "endpoint-not-allowed": () => "set usageLog.endpoint to an https address",
1275
- rejected: () => `run node ${join(HERE, "usage-register.mjs")}`,
1276
- "not-accepted": () => `run node ${join(HERE, "usage-identity.mjs")} --refresh`,
1277
- redirected: (r) =>
1278
- r.location
1279
- ? `set usageLog.endpoint to the address on ${r.location} it redirects to`
1280
- : `run node ${join(HERE, "migrate-prefs.mjs")}`,
1281
- failed: () => "re-run a phase once the reporting endpoint is reachable",
1282
- };
1283
-
1284
- // One line for the reporting state, from the last send and the last
1285
- // registration attempt together (usage-register.mjs reportingState): the
1286
- // states that need the person are reported even while reporting is still
1287
- // off, because a machine that never registered is exactly that case.
1288
- function checkUsageReport() {
1289
- const prefs = readJson(PREFS);
1290
- const usage = prefs?.global?.usageLog;
1291
- const logs = join(CLAUDE, "logs", "multi-agent");
1292
- const last = readJson(join(logs, "usage-last-send.json"));
1293
- const state = reportingState({
1294
- send: last && typeof last.outcome === "string" ? last : null,
1295
- register: readJson(join(logs, "usage-last-register.json")),
1296
- usageLog: usage || {},
1297
- lang: prefs?.global?.outputLanguage === "tr" ? "tr" : "en",
1298
- });
1299
- if (usage?.optOut !== true) {
1300
- if (state.state === "no-identity") {
1301
- report("usage-report", "WARN", state.line, `run ${hostCommand("setup", HERE)}`);
1302
- return;
1303
- }
1304
- if (state.state === "pending-approval") {
1305
- report(
1306
- "usage-report",
1307
- "INFO",
1308
- state.line,
1309
- `run node ${join(HERE, "usage-register.mjs")} after the site owner approves it`,
1310
- );
1311
- return;
1312
- }
1313
- if (state.state === "deferred") {
1314
- report(
1315
- "usage-report",
1316
- "INFO",
1317
- state.line,
1318
- `run node ${join(HERE, "usage-register.mjs")} in a normal terminal`,
1319
- );
1320
- return;
1321
- }
1322
- }
1323
- if (usage?.enabled !== true || usage?.optOut === true) {
1324
- skip("usage-report", "usage reporting is off");
1325
- return;
1326
- }
1327
- if (!last || typeof last.outcome !== "string") {
1328
- skip("usage-report", "no report has been sent from this machine yet");
1329
- return;
1330
- }
1331
- if (last.outcome === "accepted") {
1332
- report("usage-report", "OK", null, null, { summary: state.line });
1333
- return;
1334
- }
1335
- if (state.state === "rejected") {
1336
- report("usage-report", "WARN", state.line, `run node ${join(HERE, "usage-register.mjs")}`);
1337
- return;
1338
- }
1339
- const key = last.outcome === "skipped" ? last.reason : last.outcome;
1340
- const stepFor = USAGE_STEPS[key] ?? USAGE_STEPS.failed;
1341
- const detail = [last.status, last.reason, last.location && `to ${last.location}`]
1342
- .filter(Boolean)
1343
- .join(", ");
1344
- const when = last.t ? ` at ${last.t}` : "";
1345
- report(
1346
- "usage-report",
1347
- "WARN",
1348
- `the last usage report${last.id ? ` for ${last.id}` : ""} was ${last.outcome}${detail ? ` (${detail})` : ""}${when}, so runs are missing from the usage panel`,
1349
- stepFor(last),
1350
- );
1351
- }
1352
-
1353
- // usage-register.mjs runs quietly from setup, update and Phase 0, so the record
1354
- // of its last attempt, and of the failure report it may have sent, is where a
1355
- // machine that never registers shows why.
1356
- const REGISTER_FINE = new Set(["registered", "registered-feedback-only", "enabled"]);
1357
- const REGISTER_QUIET = new Set([
1358
- "token in environment",
1359
- "token in prefs",
1360
- "token already onboarded",
1361
- ]);
1362
-
1363
- function beaconSummary(beacon) {
1364
- const last = beacon?.last;
1365
- if (!last || typeof last.outcome !== "string") return "no failure report was sent";
1366
- const when = last.t ? ` at ${last.t}` : "";
1367
- return last.outcome === "sent"
1368
- ? `the failure report (${last.reason}) reached the site${when}`
1369
- : `the failure report (${last.reason}) could not be delivered${when}`;
1370
- }
1371
-
1372
- function checkUsageRegister() {
1373
- const prefs = readJson(PREFS);
1374
- if (prefs?.global?.usageLog?.optOut === true) {
1375
- skip("usage-register", "usage reporting is opted out");
1376
- return;
1377
- }
1378
- const logs = join(CLAUDE, "logs", "multi-agent");
1379
- const last = readJson(join(logs, "usage-last-register.json"));
1380
- if (!last || typeof last.status !== "string") {
1381
- skip("usage-register", "no registration has been attempted on this machine yet");
1382
- return;
1383
- }
1384
- if (
1385
- REGISTER_FINE.has(last.status) ||
1386
- (last.status === "skipped" && REGISTER_QUIET.has(last.detail))
1387
- ) {
1388
- ok("usage-register");
1389
- return;
1390
- }
1391
- if (last.status === "pending-approval") {
1392
- report(
1393
- "usage-register",
1394
- "INFO",
1395
- "the reporting site holds this machine's registration until its owner approves it",
1396
- `run node ${join(HERE, "usage-register.mjs")} after the site owner approves it`,
1397
- );
1398
- return;
1399
- }
1400
- if (last.status === "deferred") {
1401
- report(
1402
- "usage-register",
1403
- "INFO",
1404
- `the last usage registration${last.t ? ` at ${last.t}` : ""} was deferred: ${last.detail || "identity not visible in this context"}`,
1405
- `run node ${join(HERE, "usage-register.mjs")} in a normal terminal`,
1406
- );
1407
- return;
1408
- }
1409
- const beacon = beaconSummary(readJson(join(logs, "usage-register-beacon.json")));
1410
- const fix = `run node ${join(HERE, "usage-register.mjs")} --refresh`;
1411
- if (typeof last.failingSince === "string" && ["unavailable", "declined"].includes(last.status)) {
1412
- const why = last.detail || last.status;
1413
- const tries = last.t && last.t !== last.failingSince ? `, last tried ${last.t}` : "";
1414
- report(
1415
- "usage-register",
1416
- "WARN",
1417
- `usage registration failing since ${last.failingSince}: ${why}${tries}; ${beacon}`,
1418
- fix,
1419
- );
1420
- return;
1421
- }
1422
- const when = last.t ? ` at ${last.t}` : "";
1423
- const detail = last.detail ? ` (${last.detail})` : "";
1424
- report(
1425
- "usage-register",
1426
- "WARN",
1427
- `the last usage registration${when} was ${last.status}${detail}; ${beacon}`,
1428
- fix,
1429
- );
1430
- }
1431
-
1432
- // The last answer of the run-time access check (usage-access.mjs), read from
1433
- // its state file: doctor asks the site nothing itself.
1434
- function checkAccessState() {
1435
- const prefs = readJson(PREFS);
1436
- const lang = prefs?.global?.outputLanguage === "tr" ? "tr" : "en";
1437
- const state = readAccessState(HOME);
1438
- const { closed, line } = accessDoctorLine(state, lang);
1439
- const last = state?.last?.result;
1440
- if (!last || last === "unreachable" || last === "skipped") {
1441
- skip("access", line);
1442
- return;
1443
- }
1444
- if (!closed) {
1445
- report("access", "OK", null, null, { summary: line });
1446
- return;
1447
- }
1448
- const step =
1449
- last === "blocked"
1450
- ? "re-run the task once the site owner reopens access"
1451
- : `re-run the task after ${last === "invite-pending" ? "accepting the invitation" : "access is granted"}${state.last.url ? ` (${state.last.url})` : ""}`;
1452
- report("access", "WARN", line, step);
1453
- }
1454
-
1455
- // A saved routine is a local-only command the installer carries across
1456
- // updates as written, so a body that names a removed command keeps typing it.
1457
- // Each pattern is assembled from parts so this file does not itself name the
1458
- // commands smoke-removed-modes-absent.sh holds absent.
1459
- const REMOVED_COMMANDS = [
1460
- {
1461
- name: "autopilot",
1462
- re: new RegExp("/multi-agent[:-]" + "autopilot(?![-\\w])"),
1463
- replacement: '/multi-agent "<task>" autopilot',
1464
- },
1465
- {
1466
- name: "model",
1467
- re: new RegExp("/multi-agent[:-]" + "model(?![-\\w])"),
1468
- replacement: "/multi-agent:fable-on, /multi-agent:fable-off or /multi-agent:fable-status",
1469
- },
1470
- {
1471
- name: "routines <action>",
1472
- re: new RegExp(
1473
- "(?:/multi-agent[:-]|(?<![\\w-])multi-agent )routines" +
1474
- "[[ ]+(share|browse|import|update|delete)(?![-\\w])",
1475
- ),
1476
- replacement: "/multi-agent:routines-<action>",
1477
- },
1478
- ];
1479
-
1480
- function checkRoutineCommands() {
1481
- const root = join(HOST_TREE, HOST.install.commandSpecs);
1482
- const routines = [];
1483
- try {
1484
- for (const name of readdirSync(root)) {
1485
- const f = join(root, name, "SKILL.md");
1486
- if (!existsSync(f)) continue;
1487
- const text = readFileSync(f, "utf8");
1488
- if (/^local-only:\s*true\s*$/m.test(text)) routines.push({ name, text });
1489
- }
1490
- } catch {
1491
- // No command tree: nothing saved to check.
1492
- }
1493
- if (!routines.length) {
1494
- skip("routine-commands", "no saved routine on this machine");
1495
- return;
1496
- }
1497
- const stale = routines
1498
- .map((r) => ({ name: r.name, gone: REMOVED_COMMANDS.filter((c) => c.re.test(r.text)) }))
1499
- .filter((r) => r.gone.length);
1500
- if (!stale.length) {
1501
- ok("routine-commands");
1502
- return;
1503
- }
1504
- const found = REMOVED_COMMANDS.filter((c) => stale.some((r) => r.gone.includes(c)));
1505
- const listed = stale.map((r) => `${r.name} (${r.gone.map((c) => c.name).join(", ")})`);
1506
- report(
1507
- "routine-commands",
1508
- "WARN",
1509
- `${stale.length} saved routine(s) name a removed command: ${listed.join(", ")}`,
1510
- found.map((c) => `set ${c.replacement} in place of the ${c.name} command`).join("; ") +
1511
- ` in ${join(root, "<name>", "SKILL.md")} for each`,
1512
- );
1513
- }
1514
-
1515
- // The installer carries the user's own settings to the MCP server's current id;
1516
- // a project's .claude/settings*.json and .mcp.json, read at the root of the
1517
- // repository the current directory is in, are the repository's, so rules
1518
- // there still naming the old id are reported, with the edit to make. The
1519
- // user's own ~/.claude is never read here: during the transition the
1520
- // installer keeps old entries there on purpose.
1521
- function checkMcpLegacyNames() {
1522
- const found = projectLegacyEntries(process.cwd(), { home: HOME });
1523
- if (!found.length) {
1524
- ok("mcp-legacy-names");
1525
- return;
1526
- }
1527
- const files = found.map((f) => f.file);
1528
- const count = found.reduce((n, f) => n + f.entries.length, 0);
1529
- report(
1530
- "mcp-legacy-names",
1531
- "WARN",
1532
- `${count} entr(ies) in this project still name the MCP server's old id ${LEGACY_SERVER_ID}: ${found
1533
- .map((f) => `${f.file} (${f.entries.slice(0, 3).join("; ")})`)
1534
- .join(", ")}`,
1535
- `set mcp__${MCP_SERVER_ID}__ in place of mcp__${LEGACY_SERVER_ID}__ in permission rules and hook matchers, and ${MCP_SERVER_ID} in place of ${LEGACY_SERVER_ID} as a server id or .mcp.json key, in ${files.join(", ")}`,
1536
- );
1537
- }
1538
-
1539
- // route-on --free promises that simple tasks leave Claude. With no usable
1540
- // provider every one of them silently escalates back, which costs nothing but
1541
- // saves nothing either - the user believes a control is working that is not.
1542
- // --probe sends each configured provider one tiny request, so a dead key or an
1543
- // exhausted quota shows up here instead of as a week of escalations.
1544
- function checkFreeModels() {
1545
- const prefs = readJson(PREFS);
1546
- const routing = prefs?.global?.modelRouting;
1547
- if (routing?.enabled !== true || routing?.free?.enabled !== true) {
1548
- skip("free-models", "free-model routing is off");
1549
- return;
1550
- }
1551
- const lib = [
1552
- join(HERE, "..", "lib", "toolkit-llm.sh"),
1553
- join(HOST_TREE, "lib", "toolkit-llm.sh"),
1554
- ].find((p) => existsSync(p));
1555
- if (!lib) {
1556
- report(
1557
- "free-models",
1558
- "WARN",
1559
- "route-on --free is on but lib/toolkit-llm.sh is not installed, so every free task escalates to Claude",
1560
- `run ${hostCommand("update", HERE)}`,
1561
- );
1562
- return;
1563
- }
1564
- const train = routing.free.allowTraining === true ? ["--allow-training"] : [];
1565
- const run = (args) =>
1566
- JSON.parse(
1567
- execFileSync("bash", ["-c", '. "$1"; shift; ma_toolkit_llm "$@"', "_", lib, ...args], {
1568
- encoding: "utf8",
1569
- timeout: PROBE ? 180000 : 60000,
1570
- stdio: ["ignore", "pipe", "ignore"],
1571
- }),
1572
- );
1573
- let listing;
1574
- try {
1575
- listing = run(["providers", ...train]);
1576
- } catch {
1577
- report(
1578
- "free-models",
1579
- "WARN",
1580
- "route-on --free is on but the multi-agent-mcp CLI could not be run (node and npx are needed), so every free task escalates to Claude",
1581
- "run npx -y --@mmerterden:registry=https://registry.npmjs.org -p @mmerterden/multi-agent-mcp@latest multi-agent-mcp-llm providers",
1582
- );
1583
- return;
1584
- }
1585
- const usable = (listing.providers || []).filter((p) => p.configured && p.allowed_by_policy);
1586
- const detail = (listing.providers || []).map(
1587
- (p) =>
1588
- `${p.id}: ${p.configured ? (p.allowed_by_policy ? `ready (${p.key_source})` : `configured, outside the ${listing.data_policy} policy`) : `missing - ${p.setup}`}`,
1589
- );
1590
- if (!usable.length) {
1591
- report(
1592
- "free-models",
1593
- "WARN",
1594
- `route-on --free is on but no free provider is usable under the ${listing.data_policy} data policy, so every free task escalates to Claude`,
1595
- 'run bash "$HOME/.claude/lib/credential-store.sh" set llm-groq - and paste a free key from https://console.groq.com/keys',
1596
- detail,
1597
- );
1598
- return;
1599
- }
1600
- if (!PROBE) {
1601
- report("free-models", "OK", null, null, detail);
1602
- return;
1603
- }
1604
- let probed;
1605
- try {
1606
- probed = run(["probe"]);
1607
- } catch {
1608
- report(
1609
- "free-models",
1610
- "WARN",
1611
- "the free-provider probe could not run",
1612
- "re-run with --probe once the network is reachable",
1613
- detail,
1614
- );
1615
- return;
1616
- }
1617
- const dead = probed.filter((r) => usable.some((u) => u.id === r.provider) && r.outcome !== "ok");
1618
- if (dead.length === usable.length) {
1619
- report(
1620
- "free-models",
1621
- "WARN",
1622
- `every usable free provider failed a probe (${dead.map((r) => `${r.provider}: ${r.outcome}`).join(", ")}), so free tasks escalate to Claude until one recovers`,
1623
- "set a fresh key for the failing provider with the credential store, or add a second provider",
1624
- probed.map((r) => `${r.provider}: ${r.outcome}${r.reason ? ` (${r.reason})` : ""}`),
1625
- );
1626
- return;
1627
- }
1628
- report(
1629
- "free-models",
1630
- "OK",
1631
- null,
1632
- null,
1633
- probed.map((r) => `${r.provider}: ${r.outcome}${r.reason ? ` (${r.reason})` : ""}`),
1634
- );
1635
- }
1636
-
1637
- // Apple's Xcode skills are the reference for iPhone Duo and window resizing,
1638
- // SwiftUI, App Intents and the accessibility audits, and Claude Code reads them
1639
- // from a copy the installer keeps at the installed Xcode build. A newer Xcode
1640
- // leaves that copy older than what the Mac offers, which degrades the answer
1641
- // rather than breaking a run, so it tops out at WARN.
1642
- // The local-model host runs a model served from this machine, so two things
1643
- // have to be true that no other host needs: a model and address are recorded,
1644
- // and the server answers. Both are checked where they are used rather than at
1645
- // the first dispatch, because a run that reaches a phase and then cannot ask a
1646
- // model has already spent the setup.
1647
- function checkLocalModel() {
1648
- if (HOST_ID !== "local") {
1649
- skip("local-model", `${HOST.label} does not run a model served from this machine`);
1650
- return;
1651
- }
1652
- const cfg = readJson(PREFS)?.global?.localModel ?? null;
1653
- const problem = localModelProblem(cfg);
1654
- if (problem) {
1655
- report("local-model", "BLOCK", problem, `set global.localModel in ${PREFS}`);
1656
- return;
1657
- }
1658
- if (!PROBE) {
1659
- ok("local-model");
1660
- return;
1661
- }
1662
- // --probe only: a reachability check costs a request, and a doctor run that
1663
- // wakes a model loader every time would be its own problem.
1664
- const url = new URL("models", cfg.baseUrl.endsWith("/") ? cfg.baseUrl : `${cfg.baseUrl}/`);
1665
- try {
1666
- execFileSync("curl", ["-sS", "-m", "5", "-o", "/dev/null", "-w", "%{http_code}", url.href], {
1667
- encoding: "utf8",
1668
- stdio: ["ignore", "pipe", "pipe"],
1669
- });
1670
- } catch {
1671
- report(
1672
- "local-model",
1673
- "BLOCK",
1674
- `nothing answered at ${url.origin}, so no phase can reach a model`,
1675
- "start the local model server, then re-run this check",
1676
- );
1677
- return;
1678
- }
1679
- ok("local-model");
1680
- }
1681
-
1682
- function checkXcodeSkills() {
1683
- const s = xcodeSkillsStatus(HOME);
1684
- // Apple's set reaches Claude Code as a linked plugin and every other host as
1685
- // copied skill directories, which this status cannot see. Reporting the
1686
- // Claude linkage on another host told the user to fix something that is not
1687
- // how their host receives them.
1688
- if (HOST_ID !== "claude") {
1689
- skip(
1690
- "xcode-skills",
1691
- `${HOST.label} receives Apple's Xcode skills as copies, not as a linked plugin`,
1692
- );
1693
- return;
1694
- }
1695
- if (!s.available) {
1696
- skip(
1697
- "xcode-skills",
1698
- "no Xcode 27.1+ agent plugin on this Mac; the pipeline's own iOS skills apply",
1699
- );
1700
- return;
1701
- }
1702
- if (!s.claude || !s.claude.installed) {
1703
- report(
1704
- "xcode-skills",
1705
- "INFO",
1706
- `Apple's Xcode skills (${s.skills}, Xcode ${s.build}) are not linked into ${HOST.label}`,
1707
- `run ${hostCommand("update", HERE)}, or node install.js ${HOST.install.flag} from the pipeline checkout`,
1708
- );
1709
- return;
1710
- }
1711
- if (!s.claude.current) {
1712
- report(
1713
- "xcode-skills",
1714
- "WARN",
1715
- `Apple's Xcode skills are linked from Xcode ${s.claude.build}, but this Mac now has ${s.build}`,
1716
- "run /multi-agent:update to refresh them from the installed Xcode",
1717
- );
1718
- return;
1719
- }
1720
- ok("xcode-skills");
1721
- }
1722
-
1723
- // One statfs call against the volume holding $HOME. Low means below
1724
- // prefs.global.diskCleaner.lowDiskGb or lowDiskPercent (lib/low-disk.mjs owns
1725
- // both defaults). What could be freed comes from the newest disk-cleaner dry
1726
- // run under ~/.claude/logs/disk-cleaner, never from a fresh measurement: a
1727
- // full measurement walks every cache and would make doctor slow. --probe runs
1728
- // one under a time cap; a timeout is reported, never a failure. Nothing here
1729
- // deletes anything.
1730
- const DISK_REPORT_MAX_AGE_MS = 24 * 3_600_000;
1731
- const DISK_PROBE_TIMEOUT_MS = 60_000;
1732
- const DISK_TOP = 3;
1733
- const GB = 1e9;
1734
- const gb = (bytes) => `${(bytes / GB).toFixed(1)} GB`;
1735
-
1736
- function newestDiskReport(dir) {
1737
- let names;
1738
- try {
1739
- names = readdirSync(dir)
1740
- .filter((n) => /^report-.*\.json$/.test(n))
1741
- .sort()
1742
- .reverse();
1743
- } catch {
1744
- return null;
1745
- }
1746
- for (const n of names) {
1747
- const data = readJson(join(dir, n));
1748
- if (data && data.mode === "dry-run" && Array.isArray(data.categories)) {
1749
- return { file: join(dir, n), data };
1750
- }
1751
- }
1752
- return null;
1753
- }
1754
-
1755
- function probeDiskReport() {
1756
- const timeout = Number(process.env.DOCTOR_DISK_PROBE_TIMEOUT_MS) || DISK_PROBE_TIMEOUT_MS;
1757
- const r = spawnSync(
1758
- process.execPath,
1759
- [join(HERE, "disk-cleaner.mjs"), "--dry-run", "--json", `--top=${DISK_TOP}`],
1760
- { encoding: "utf8", timeout, maxBuffer: 256 * 1024 * 1024 },
1761
- );
1762
- if (r.error?.code === "ETIMEDOUT" || r.signal) {
1763
- return { timedOut: true, seconds: Math.round(timeout / 1000) };
1764
- }
1765
- try {
1766
- return { data: JSON.parse(r.stdout) };
1767
- } catch {
1768
- return { error: (r.stderr || "no JSON on stdout").trim().split("\n")[0] };
1769
- }
1770
- }
1771
-
1772
- function reclaimSummary(data, source, file) {
1773
- const measuredAt = Date.parse(data.startedAt);
1774
- const ageMs = Number.isFinite(measuredAt) ? Date.now() - measuredAt : null;
1775
- const top = [...data.categories]
1776
- .filter((c) => c.bytes > 0)
1777
- .sort((a, b) => b.bytes - a.bytes)
1778
- .slice(0, DISK_TOP)
1779
- .map((c) => ({ id: c.id, bytes: c.bytes }));
1780
- return {
1781
- source,
1782
- file,
1783
- measuredAt: data.startedAt || null,
1784
- ageHours: ageMs == null ? null : Math.round((ageMs / 3_600_000) * 10) / 10,
1785
- stale: ageMs == null || ageMs > DISK_REPORT_MAX_AGE_MS,
1786
- totalBytes: data.reclaimableBytes ?? data.totalBytes ?? 0,
1787
- top,
1788
- };
1789
- }
1790
-
1791
- function ageText(hours) {
1792
- if (hours == null) return "at an unknown time";
1793
- if (hours < 1) return `${Math.max(1, Math.round(hours * 60))} min ago`;
1794
- if (hours < 48) return `${Math.round(hours)} h ago`;
1795
- return `${Math.round(hours / 24)} days ago`;
1796
- }
1797
-
1798
- function checkDiskSpace() {
1799
- const r = lowDiskCheck({ path: HOME });
1800
- if (r.freeBytes == null) {
1801
- skip("disk-space", "statfs did not report a usable figure on this host");
1802
- return;
1803
- }
1804
- const cmd = hostCommand("clean-disk", HERE);
1805
- const pct = r.totalBytes ? (r.freeBytes / r.totalBytes) * 100 : null;
1806
- const freeText = `${gb(r.freeBytes)} (${pct == null ? "?" : pct.toFixed(1)}%) free on the volume holding $HOME`;
1807
- const threshold = Number(globalPref("diskCleaner.reclaimableGb", 10));
1808
- const reclaimGb = Number.isFinite(threshold) && threshold >= 0 ? threshold : 10;
1809
-
1810
- let reclaim = null;
1811
- let probe = null;
1812
- if (PROBE) {
1813
- const p = probeDiskReport();
1814
- probe = p.data
1815
- ? { ok: true }
1816
- : p.timedOut
1817
- ? { timedOut: true, seconds: p.seconds }
1818
- : { error: p.error };
1819
- if (p.data) reclaim = reclaimSummary(p.data, "probe", null);
1820
- }
1821
- if (!reclaim) {
1822
- const found = newestDiskReport(join(CLAUDE, "logs", "disk-cleaner"));
1823
- if (found) reclaim = reclaimSummary(found.data, "report", found.file);
1824
- }
1825
-
1826
- let measured;
1827
- if (probe?.timedOut) {
1828
- measured = `the measurement timed out after ${probe.seconds} s`;
1829
- if (reclaim && !reclaim.stale) measured += `; the last one, ${ageText(reclaim.ageHours)}`;
1830
- } else if (probe?.error) {
1831
- measured = `the measurement failed (${probe.error})`;
1832
- } else if (!reclaim) {
1833
- measured = `nothing measured yet; ${cmd} measures what can be freed`;
1834
- } else if (reclaim.stale) {
1835
- measured = `the last measurement is ${ageText(reclaim.ageHours).replace(/ ago$/, " old")}; ${cmd} measures again`;
1836
- } else {
1837
- measured = `measured ${ageText(reclaim.ageHours)}`;
1838
- }
1839
- const fresh = reclaim && !reclaim.stale;
1840
- const reclaimText = fresh
1841
- ? `${gb(reclaim.totalBytes)} can be freed${reclaim.top.length ? ` (${reclaim.top.map((c) => `${c.id} ${gb(c.bytes)}`).join(", ")})` : ""}, ${measured}`
1842
- : measured;
1843
- const detail = {
1844
- freeBytes: r.freeBytes,
1845
- totalBytes: r.totalBytes,
1846
- freePercent: pct == null ? null : Math.round(pct * 10) / 10,
1847
- lowGb: r.lowGb,
1848
- lowPercent: r.lowPercent,
1849
- reclaimableGb: reclaimGb,
1850
- reclaimable: reclaim,
1851
- probe,
1852
- summary: `${freeText}; ${reclaimText}`,
1853
- };
1854
- const freeStep = fresh
1855
- ? `run ${cmd}: ${gb(reclaim.totalBytes)} can be freed`
1856
- : `run ${cmd} to measure what can be freed; it deletes only what you choose`;
1857
-
1858
- if (r.low) {
1859
- report(
1860
- "disk-space",
1861
- "WARN",
1862
- `${freeText}, under the ${r.lowGb} GB / ${r.lowPercent}% floor; a worktree plus a build needs more; ${reclaimText}`,
1863
- freeStep,
1864
- detail,
1865
- );
1866
- return;
1867
- }
1868
- if (fresh && reclaim.totalBytes >= reclaimGb * GB) {
1869
- report("disk-space", "INFO", `${freeText}; ${reclaimText}`, freeStep, detail);
1870
- return;
1871
- }
1872
- report("disk-space", "OK", null, null, detail);
1873
- }
1874
-
1875
- // A finished task removes its own worktree at PR time, but a run that dies
1876
- // before Phase 4 never reaches that step and nothing else collects it: the
1877
- // finalizer only runs on success and gc-worktrees only sweeps entries git no
1878
- // longer knows about. So worktrees accumulate silently, and each one is a full
1879
- // second checkout. Measured on one real iOS repo: 15 left behind, 11 GB.
1880
- //
1881
- // Only the repo the caller is standing in is examined. A project name in prefs
1882
- // is a name, not a path, and guessing checkout locations to report a number is
1883
- // how a diagnostic starts lying.
1884
- function checkWorktreeResidue() {
1885
- let repo;
1886
- try {
1887
- repo = execFileSync("git", ["rev-parse", "--show-toplevel"], {
1888
- encoding: "utf8",
1889
- stdio: ["ignore", "pipe", "ignore"],
1890
- }).trim();
1891
- } catch {
1892
- skip("worktree-residue", "not inside a git repository, so there is no checkout to measure");
1893
- return;
1894
- }
1895
- const wt = join(repo, ".worktrees");
1896
- let entries;
1897
- try {
1898
- entries = readdirSync(wt).filter((n) => n !== ".DS_Store" && n !== ".archive");
1899
- } catch {
1900
- ok("worktree-residue");
1901
- return;
1902
- }
1903
- if (entries.length === 0) {
1904
- ok("worktree-residue");
1905
- return;
1906
- }
1907
- let gb = null;
1908
- try {
1909
- const out = execFileSync("du", ["-sk", wt], { encoding: "utf8" });
1910
- const kb = Number(out.trim().split(/\s+/)[0]);
1911
- if (Number.isFinite(kb)) gb = kb / 1024 / 1024;
1912
- } catch {
1913
- /* du is not everywhere; the count alone is still worth reporting */
1914
- }
1915
- const size = gb === null ? "" : `, ${gb.toFixed(1)} GB`;
1916
- if (entries.length >= 5 || (gb !== null && gb >= 2)) {
1917
- report(
1918
- "worktree-residue",
1919
- "WARN",
1920
- `${entries.length} worktree(s) left under ${wt}${size}; runs that stopped before Phase 4 are never collected`,
1921
- `run ${hostCommand("garbage-collect", HERE)}, or ${hostCommand("kill", HERE)} for a task you know is dead`,
1922
- );
1923
- return;
1924
- }
1925
- ok("worktree-residue");
1926
- }
1927
-
1928
- /* ------------------------------------------------------------------ main -- */
1929
-
1930
- /**
1931
- * Checks that only matter when nobody is at the keyboard.
1932
- *
1933
- * Every one of them is a way a server run stops WITHOUT SAYING SO - the
1934
- * failure mode this whole profile exists for. A laptop hits none of them
1935
- * because a human is there to answer, unlock and restart, which is exactly why
1936
- * they are not in the default run.
1937
- *
1938
- * None may BLOCK: `MAY_BLOCK` is a closed set and these are readiness, not
1939
- * correctness. A machine that fails all four still runs the pipeline fine with
1940
- * someone watching it.
1941
- *
1942
- * @param {{root: string}|any} resolved the install layout from checkInstallPresent
1943
- */
1944
- function checkServerProfile(resolved) {
1945
- const root = resolved?.root || join(homedir(), ".claude");
1946
-
1947
- // 1. The contract exists on this machine. Without it nothing tells the
1948
- // operator which entry points honour MULTI_AGENT_UNATTENDED.
1949
- const contract = join(root, "multi-agent-refs", "unattended-contract.md");
1950
- if (existsSync(contract)) {
1951
- ok("unattended-contract");
1952
- } else {
1953
- report(
1954
- "unattended-contract",
1955
- "WARN",
1956
- "unattended-contract.md is not installed, so nothing here documents what an unattended run resolves",
1957
- `run ${hostCommand("update", HERE)} to refresh the reference tree`,
1958
- );
1959
- }
1960
-
1961
- // 2. The permission posture. autopilot spawns `claude --permission-prompts
1962
- // none`, but the tools it then calls still have to be allowed somewhere,
1963
- // and on a fresh machine they are not - the run stops at the first
1964
- // prompt with nobody to answer it. The rule is schemas/unattended-profile.json,
1965
- // the same file `install --unattended` writes from, and the posture lives
1966
- // in multi-agent-unattended.settings.json, the file the runner passes with
1967
- // `claude --settings`: dontAsk, Edit and Write allowed, every deny rule
1968
- // present. Permission lists merge across settings files, so a whole-Bash
1969
- // allow in settings.json undoes the narrow list and is a gap too.
1970
- const settings = join(root, UNATTENDED_SETTINGS_FILE);
1971
- const readDoc = (f) => {
1972
- try {
1973
- return JSON.parse(readFileSync(f, "utf-8")) ?? {};
1974
- } catch {
1975
- return {};
1976
- }
1977
- };
1978
- const doc = readDoc(settings);
1979
- const perms = doc.permissions ?? {};
1980
- const attendedAllow = (() => {
1981
- const a = readDoc(join(root, "settings.json")).permissions?.allow;
1982
- return (Array.isArray(a) ? a : []).map(String);
1983
- })();
1984
- const allow = (Array.isArray(perms.allow) ? perms.allow : []).map(String);
1985
- const deny = (Array.isArray(perms.deny) ? perms.deny : []).map(String);
1986
- let profile = null;
1987
- for (const p of [
1988
- join(root, "schemas", "unattended-profile.json"),
1989
- join(HERE, "..", "schemas", "unattended-profile.json"),
1990
- ]) {
1991
- try {
1992
- profile = JSON.parse(readFileSync(p, "utf-8"));
1993
- break;
1994
- } catch {
1995
- /* next candidate */
1996
- }
1997
- }
1998
- const gaps = [];
1999
- for (const t of ["Edit", "Write"]) if (!allow.includes(t)) gaps.push(`${t} is not allowed`);
2000
- if (!allow.some((a) => a.startsWith("Bash("))) gaps.push("no Bash rule is allowed");
2001
- if (profile) {
2002
- for (const { rule } of profile.wideAllows)
2003
- if (attendedAllow.includes(rule))
2004
- gaps.push(`a bare ${rule} allow in settings.json makes the narrow list meaningless`);
2005
- const found = profileGaps(doc, profile, {
2006
- extraHosts: prefsHosts(dirname(root)),
2007
- home: dirname(root),
2008
- });
2009
- gaps.push(...found.permissions, ...found.sandbox);
2010
- } else {
2011
- gaps.push("schemas/unattended-profile.json is not installed, so the posture cannot be checked");
2012
- }
2013
- if (!gaps.length) {
2014
- ok("unattended-permissions");
2015
- } else {
2016
- report(
2017
- "unattended-permissions",
2018
- "WARN",
2019
- `the unattended permission posture is incomplete: ${gaps.join("; ")}`,
2020
- `run \`${UNATTENDED_PROFILE_INSTALL}\` (it prints the profile before writing it)`,
2021
- { settings, allow, deny },
2022
- );
2023
- }
2024
-
2025
- // 3. Something has to start the work. launchd is the only scheduler this
2026
- // ships a template for; a server with no agent loaded runs nothing and
2027
- // looks idle rather than broken.
2028
- let loaded = false;
2029
- try {
2030
- loaded = execFileSync("launchctl", ["list"], { encoding: "utf-8", timeout: 5000 }).includes(
2031
- "multi-agent",
2032
- );
2033
- } catch {
2034
- // launchctl absent or refusing: treat as "nothing is loaded", which is the
2035
- // conservative read - claiming a scheduler we could not see would be worse.
2036
- }
2037
- if (loaded) {
2038
- ok("scheduler");
2039
- } else {
2040
- report(
2041
- "scheduler",
2042
- "WARN",
2043
- "no multi-agent launchd agent is loaded, so nothing starts a queued run on its own",
2044
- `run ${hostCommand("autopilot-on", HERE)} to install the agent, or schedule the runner yourself`,
2045
- );
2046
- }
2047
-
2048
- // 4. The keychain. Every credential this pipeline reads lives there, and a
2049
- // LaunchDaemon started before login gets a LOCKED keychain: each fetch
2050
- // fails, and the failures surface far away as 401s that blame the token.
2051
- // Reading a real credential here would be a network call and a side
2052
- // effect; the presence of a login-keychain path is the cheap proxy.
2053
- let keychain = "";
2054
- try {
2055
- keychain = execFileSync("security", ["default-keychain"], {
2056
- encoding: "utf-8",
2057
- timeout: 5000,
2058
- }).trim();
2059
- } catch {
2060
- // Same shape: unreachable reads as absent.
2061
- }
2062
- if (keychain) {
2063
- ok("keychain-unlock");
2064
- } else {
2065
- report(
2066
- "keychain-unlock",
2067
- "WARN",
2068
- "no default keychain is reachable from this session; a boot-time daemon sees a locked one and every credential read fails as a 401",
2069
- "run the LaunchAgent at login rather than a LaunchDaemon at boot (docs/server-readiness.md)",
2070
- );
2071
- }
2072
- }
2073
-
2074
- const KNOWN_FLAGS = ["probe", "json", "explain", "list-checks", "task-tools", "profile", "only"];
2075
-
2076
- /** The --json document: schemas/doctor-report.schema.json. */
2077
- function jsonReport(exit, checks) {
2078
- return { schemaVersion: SCHEMA_VERSION, exit, selection: SELECTION, checks };
2079
- }
2080
-
2081
- function main() {
2082
- if (LIST) {
2083
- // Lists what THIS invocation would run, which is what the name promises
2084
- // and what the registry gate compares against the output of a real run.
2085
- // Listing the server checks unconditionally made `--list-checks` disagree
2086
- // with a default run by four, and the gate that counts printed lines
2087
- // against listed checks caught it immediately.
2088
- for (const id of CHECK_IDS) process.stdout.write(`${id}\n`);
2089
- if (PROFILE === "server") for (const id of SERVER_CHECK_IDS) process.stdout.write(`${id}\n`);
2090
- return;
2091
- }
2092
- const unknown = argv.filter(
2093
- (a) =>
2094
- a.startsWith("--") &&
2095
- !/^--(probe|json|explain|list-checks|task-tools=|profile=|only(=|$))/.test(a),
2096
- );
2097
- if (unknown.length) {
2098
- const flag = unknown[0].slice(2).split("=")[0];
2099
- const hint = didYouMean(flag, KNOWN_FLAGS, { prefix: "--" });
2100
- process.stderr.write(
2101
- `${hint ? `unknown option ${unknown[0]}${hint}\n` : ""}usage: doctor.mjs [--probe] [--json] [--explain] [--task-tools=yes|no] [--profile=server] [--only <id,...>] | --list-checks\n`,
2102
- );
2103
- process.exitCode = 3;
2104
- return;
2105
- }
2106
- if (SELECTION !== null) {
2107
- const known = [...CHECK_IDS, ...SERVER_CHECK_IDS];
2108
- const bad = SELECTION.filter((id) => !known.includes(id));
2109
- if (!SELECTION.length || bad.length) {
2110
- const hint = bad.length ? didYouMean(bad[0], known) : "";
2111
- process.stderr.write(
2112
- `usage: --only takes check ids from --list-checks${bad.length ? ` (unknown: ${bad.join(", ")}${hint})` : ""}\n`,
2113
- );
2114
- process.exitCode = 3;
2115
- return;
2116
- }
2117
- }
2118
- if (PROFILE && PROFILE !== "server") {
2119
- process.stderr.write(`usage: --profile takes "server" (got "${PROFILE}")\n`);
2120
- process.exitCode = 3;
2121
- return;
2122
- }
2123
- if (taskFlag && TASK_TOOLS !== "yes" && TASK_TOOLS !== "no") {
2124
- process.stderr.write("usage: --task-tools takes yes or no\n");
2125
- process.exitCode = 3;
2126
- return;
2127
- }
2128
-
2129
- checkHostPlatform();
2130
-
2131
- const resolved = checkInstallPresent();
2132
- if (!resolved) {
2133
- // Indeterminate, not healthy and not merely degraded: nothing after this
2134
- // could be checked, and saying "blocked" would claim a verdict on checks
2135
- // that never ran.
2136
- const line = results[results.length - 1];
2137
- if (JSON_OUT) {
2138
- process.stdout.write(`${JSON.stringify(jsonReport(4, results), null, 2)}\n`);
2139
- } else {
2140
- process.stdout.write(`${line.severity} ${line.id} - ${line.problem} - ${line.step}\n`);
2141
- process.stdout.write(
2142
- `\n-> indeterminate: the layout did not resolve, so ${CHECK_IDS.length - results.length} checks did not run\n`,
2143
- );
2144
- }
2145
- process.exitCode = 4;
2146
- return;
2147
- }
2148
-
2149
- // Each step names the ids it reports, so --only can leave out the work of
2150
- // a check nobody asked for. A step that feeds another (the registration
2151
- // probe feeds the schema load) lists both.
2152
- const steps = [
2153
- [["install-version"], checkInstallVersion],
2154
- [["update-policy"], checkUpdatePolicy],
2155
- [["script-surface"], checkScriptSurface],
2156
- [["skill-siblings"], checkSkillSiblings],
2157
- [["state-writable"], checkStateWritable],
2158
- [["prefs-valid"], checkPrefsValid],
2159
- [["identity"], checkIdentity],
2160
- [["hook-coverage"], checkHookCoverage],
2161
- [["hook-reachability"], checkHookReachability],
2162
- [["guard-rules"], checkGuardRules],
2163
- [["credential-mapping", "credential-liveness"], () => checkCredentials(credentialInventory())],
2164
- [["store-reference"], checkStoreReference],
2165
- [["embedded-credentials"], checkEmbeddedCredentials],
2166
- [["task-tools"], checkTaskTools],
2167
- [["mcp-registration", "mcp-schema-load"], checkMcpRegistration],
2168
- [["mcp-surface"], checkMcpSurface],
2169
- [["mcp-schema-load"], checkMcpSchemaLoad],
2170
- [["mcp-failures"], checkMcpFailures],
2171
- [["disk-space"], checkDiskSpace],
2172
- [["worktree-residue"], checkWorktreeResidue],
2173
- [["usage-report"], checkUsageReport],
2174
- [["usage-register"], checkUsageRegister],
2175
- [["access"], checkAccessState],
2176
- [["free-models"], checkFreeModels],
2177
- [["local-model"], checkLocalModel],
2178
- [["xcode-skills"], checkXcodeSkills],
2179
- [["routine-commands"], checkRoutineCommands],
2180
- [["mcp-legacy-names"], checkMcpLegacyNames],
2181
- ];
2182
- if (PROFILE === "server") steps.push([SERVER_CHECK_IDS, () => checkServerProfile(resolved)]);
2183
- for (const [ids, run] of steps) {
2184
- if (SELECTION === null || ids.some((id) => SELECTION.includes(id))) run();
2185
- }
2186
- if (SELECTION !== null) {
2187
- const keep = results.filter((r) => SELECTION.includes(r.id));
2188
- results.length = 0;
2189
- results.push(...keep);
2190
- }
2191
-
2192
- const blocked = results.filter((r) => r.severity === "BLOCK");
2193
- const warned = results.filter((r) => r.severity === "WARN");
2194
- const skipped = results.filter((r) => r.severity === "SKIP");
2195
- const code = blocked.length ? 2 : warned.length ? 1 : 0;
2196
-
2197
- if (JSON_OUT) {
2198
- process.stdout.write(`${JSON.stringify(jsonReport(code, results), null, 2)}\n`);
2199
- process.exitCode = code;
2200
- return;
2201
- }
2202
-
2203
- // Every check prints, in registry order, including the ones that found
2204
- // nothing and the ones that were not run. A list that shows only problems
2205
- // cannot be told apart from a list that was never produced.
2206
- for (const id of [...CHECK_IDS, ...SERVER_CHECK_IDS]) {
2207
- const r = results.find((x) => x.id === id);
2208
- if (!r) continue;
2209
- if (r.severity === "OK") {
2210
- const note = typeof r.detail?.summary === "string" ? ` - ${r.detail.summary}` : "";
2211
- process.stdout.write(`OK ${id}${note}\n`);
2212
- } else if (r.severity === "SKIP") {
2213
- process.stdout.write(`SKIP ${id} - ${r.problem}\n`);
2214
- } else {
2215
- process.stdout.write(`${r.severity.padEnd(5)} ${id} - ${r.problem} - ${r.step}\n`);
2216
- }
2217
- }
2218
- const verdict = code === 0 ? "healthy" : code === 1 ? "degraded" : "blocked";
2219
- process.stdout.write(
2220
- `\n-> ${verdict}: ${blocked.length} blocking, ${warned.length} warning(s), ${skipped.length} not checked, ${results.length} checks\n`,
2221
- );
2222
- if (EXPLAIN) {
2223
- for (const r of results.filter((x) => x.detail)) {
2224
- process.stdout.write(`\n${r.id}:\n`);
2225
- for (const d of Array.isArray(r.detail) ? r.detail : [r.detail]) {
2226
- process.stdout.write(` ${typeof d === "string" ? d : JSON.stringify(d)}\n`);
2227
- }
2228
- }
2229
- }
2230
- process.exitCode = code;
2231
- }
2232
-
2233
- // Exported so the gate can DRIVE the engine instead of reading it. Asserting the
2234
- // BLOCK downgrade with a regex over this file's own source proves nothing: a
2235
- // comment carrying the same two substrings satisfies it as well as the code does,
2236
- // so the enforcement could be deleted outright and the gate would stay green.
2237
- export { report, results as __results, MAY_BLOCK as __mayBlock };
2238
-
2239
- // realpath on both sides: `import.meta.url` is already resolved, while argv[1]
2240
- // is whatever the caller typed. On macOS a run out of /tmp (a symlink to
2241
- // /private/tmp) would otherwise never match, and the script would do nothing.
2242
- function invokedDirectly() {
2243
- if (!process.argv[1]) return false;
2244
- try {
2245
- return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
2246
- } catch {
2247
- return false;
2248
- }
2249
- }
2250
-
2251
- if (invokedDirectly()) {
2252
- runMain("doctor", main);
2253
- }