projectstore-claude 0.30.4 → 0.30.6

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 (50) hide show
  1. package/node_modules/projectstore/.claude-plugin/marketplace.json +2 -2
  2. package/node_modules/projectstore/.claude-plugin/plugin.json +6 -2
  3. package/node_modules/projectstore/.mcp.json +1 -2
  4. package/node_modules/projectstore/README.md +65 -16
  5. package/node_modules/projectstore/agents/archaeologist.md +1 -1
  6. package/node_modules/projectstore/agents/librarian.md +1 -1
  7. package/node_modules/projectstore/agents/planner.md +1 -1
  8. package/node_modules/projectstore/commands/doctor.md +14 -11
  9. package/node_modules/projectstore/commands/reconcile.md +1 -1
  10. package/node_modules/projectstore/commands/review.md +2 -2
  11. package/node_modules/projectstore/commands/story.md +1 -1
  12. package/node_modules/projectstore/docs/getting-started.md +3 -4
  13. package/node_modules/projectstore/docs/harnesses.md +1 -1
  14. package/node_modules/projectstore/docs/how-it-works.md +7 -0
  15. package/node_modules/projectstore/docs/images/icon.png +0 -0
  16. package/node_modules/projectstore/harnesses/claude-code.json +61 -11
  17. package/node_modules/projectstore/harnesses/codex.json +45 -15
  18. package/node_modules/projectstore/hooks/band.tsx +19 -8
  19. package/node_modules/projectstore/hooks/hooks.json +6 -6
  20. package/node_modules/projectstore/hooks/session-start.mjs +55 -24
  21. package/node_modules/projectstore/hooks/session-stop.mjs +43 -20
  22. package/node_modules/projectstore/package.json +11 -12
  23. package/node_modules/projectstore/scripts/band-shared.mjs +17 -2
  24. package/node_modules/projectstore/scripts/band.mjs +20 -2
  25. package/node_modules/projectstore/scripts/binding.mjs +1 -1
  26. package/node_modules/projectstore/scripts/build-adapters.mjs +45 -4
  27. package/node_modules/projectstore/scripts/cli.mjs +74 -1373
  28. package/node_modules/projectstore/scripts/convergence.mjs +59 -16
  29. package/node_modules/projectstore/scripts/doctor.mjs +199 -36
  30. package/node_modules/projectstore/scripts/harness.mjs +88 -6
  31. package/node_modules/projectstore/scripts/install-handlers.mjs +925 -0
  32. package/node_modules/projectstore/scripts/install-harness.mjs +129 -2081
  33. package/node_modules/projectstore/scripts/install-layout.mjs +453 -0
  34. package/node_modules/projectstore/scripts/install-preview.mjs +747 -0
  35. package/node_modules/projectstore/scripts/lib.mjs +387 -107
  36. package/node_modules/projectstore/scripts/mcp-server.mjs +33 -0
  37. package/node_modules/projectstore/scripts/mcp.mjs +60 -60
  38. package/node_modules/projectstore/scripts/model-spec.mjs +24 -0
  39. package/node_modules/projectstore/scripts/models.mjs +6 -10
  40. package/node_modules/projectstore/scripts/query.mjs +7 -6
  41. package/node_modules/projectstore/scripts/read-verbs.mjs +277 -0
  42. package/node_modules/projectstore/scripts/setup.mjs +62 -12
  43. package/node_modules/projectstore/scripts/statusline-launcher.mjs +36 -3
  44. package/node_modules/projectstore/scripts/surfaces.mjs +18 -5
  45. package/node_modules/projectstore/scripts/touch-session.mjs +30 -15
  46. package/node_modules/projectstore/scripts/verbs.mjs +1202 -0
  47. package/node_modules/projectstore/scripts/version-guard.mjs +57 -7
  48. package/package.json +3 -3
  49. package/node_modules/projectstore/docs/images/loop-light.svg +0 -94
  50. package/node_modules/projectstore/docs/images/team-light.svg +0 -79
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
2
+ // projectstore — mcp-server.mjs
3
+ //
4
+ // The MCP server's entry: what the plugin's .mcp.json runs, as `node
5
+ // <plugin root>/scripts/mcp-server.mjs --project <the host's project>`. It
6
+ // parses --project and starts the server through mcp.mjs's serveSupplied,
7
+ // the path the CLI's `mcp` verb takes too, so the two entries serve alike.
8
+ // It lives under scripts/, never bin/: a file in the plugin's top-level bin/
9
+ // is on the host's Bash PATH, and it imports nothing from cli.mjs, so its
10
+ // imports reach no install verb (the PS-DIRECTORY story "The MCP server's
11
+ // entry reaches no install verb through a read-verb runner that shares the
12
+ // CLI's verb table…", decision 3; the MCP ADR's decision 1 as amended).
13
+ //
14
+ // process.exitCode, never process.exit(): stdout is the protocol channel,
15
+ // and exit() can truncate a pending write on a pipe. A bad argument is exit
16
+ // 2 with its reason on stderr, and nothing on stdout.
17
+
18
+ import { parseArgs } from "node:util";
19
+ import { serveSupplied } from "./mcp.mjs";
20
+
21
+ let values;
22
+ try {
23
+ ({ values } = parseArgs({
24
+ args: process.argv.slice(2),
25
+ options: { project: { type: "string" } },
26
+ strict: true,
27
+ allowPositionals: false,
28
+ }));
29
+ } catch (e) {
30
+ process.stderr.write(`mcp-server: ${e.message} — it takes --project <dir> alone\n`);
31
+ process.exitCode = 2;
32
+ }
33
+ if (values) process.exitCode = await serveSupplied({ project: values.project ?? null });
@@ -2,13 +2,19 @@
2
2
  //
3
3
  // The MCP read surface: a hand-rolled JSON-RPC server over stdio, one tool
4
4
  // per CLI verb (MCP ADR decisions 2, 3, 4, 6). A front-end over the
5
- // front-end: every tool call runs the CLI's own `run()` in-process with
6
- // captured streams and returns the envelope it wrote, so a tool result equals
7
- // `projectstore <verb> --json` by construction, `doctor` stays spawned, and
8
- // the exit code maps onto `isError`. Nothing here reads an artifact's
9
- // frontmatter, walks the vault or names a branded environment variable —
10
- // cli.mjs, query.mjs and harness.mjs do, once each; the resources read the
11
- // three derived views and one artifact file whole, which is what a resource is.
5
+ // front-end: every tool call runs the read-verb runner (read-verbs.mjs's
6
+ // runRead, the CLI's own parse over the one verb table in verbs.mjs, with
7
+ // the read verbs' handlers alone) in-process with captured streams and
8
+ // returns the envelope it wrote, so a tool result equals `projectstore <verb>
9
+ // --json` by construction; `doctor` stays spawned, and the exit code maps
10
+ // onto `isError`. This module imports nothing from cli.mjs, whose write
11
+ // handlers reach the installer: the PS-DIRECTORY story "The MCP server's
12
+ // entry reaches no install verb through a read-verb runner that shares the
13
+ // CLI's verb table…", and the fence in tests/portability.test.mjs. Nothing
14
+ // here reads an artifact's frontmatter, walks the vault or names a branded
15
+ // environment variable — verbs.mjs, query.mjs and harness.mjs do, once each;
16
+ // the resources read the three derived views and one artifact file whole,
17
+ // which is what a resource is.
12
18
  //
13
19
  // stdout is the protocol channel. This module writes to it only through
14
20
  // serve()'s frame writer; importing it prints nothing (a test asserts it),
@@ -30,66 +36,31 @@
30
36
  // exits non-zero naming what it needed. An UNBOUND project is different: the
31
37
  // server starts, `status` says bound:false, and every other tool answers
32
38
  // isError naming /projectstore:bind — refusing to start would put a red
33
- // entry in the host's plugin errors for every new user.
39
+ // entry in the host's plugin errors for every new user. Two entries start
40
+ // it, through one function (serveSupplied): scripts/mcp-server.mjs, which
41
+ // the plugin's .mcp.json runs, and the CLI's `mcp` verb.
34
42
  //
35
43
  // Normative: the MCP ADR (accepted 2026-09-04, amended 2026-09-05); the
36
44
  // PS-CORE story "MCP read surface: hand-rolled stdio, one tool per CLI verb".
37
45
 
38
46
  import { existsSync, readFileSync, statSync, realpathSync } from "node:fs";
39
- import { join, resolve, dirname } from "node:path";
40
- import { fileURLToPath } from "node:url";
47
+ import { join, resolve } from "node:path";
41
48
  import { createInterface } from "node:readline";
42
- import { spawn } from "node:child_process";
43
- import { run, envelope, packageVersion, VERBS } from "./cli.mjs";
44
-
45
- const BIN = join(dirname(fileURLToPath(import.meta.url)), "..", "bin", "projectstore.mjs");
49
+ import { envelope, packageVersion, resolveProject, VERBS } from "./verbs.mjs";
50
+ import { runRead, doctorAsync, DOCTOR_TIMEOUT_MS } from "./read-verbs.mjs";
51
+ import { projectRootDeclared } from "./harness.mjs";
52
+ import { readConfigAt, isInsideVault, commandForm } from "./lib.mjs";
46
53
 
47
54
  // Exit codes → isError. 0 is ok; 1 is "findings or a refusal" — a doctor that
48
55
  // found issues has SUCCEEDED, and the envelope carries ok:false already; 2
49
56
  // (usage) and 3 (not bound) are the tool failing to answer at all.
50
57
  export const isErrorExit = (code) => code !== 0 && code !== 1;
51
58
 
52
- // doctor is the one verb the CLI spawns synchronously, which would hold this
53
- // server's loop for up to a minute — no ping answered, no other call served.
54
- // It runs as an asynchronous spawn of this same bin instead; stdout is still
55
- // the CLI's envelope, so parity holds.
56
- function spawnBin(argv, { env, cwd, timeoutMs = DOCTOR_TIMEOUT_MS, onChild = null }) {
57
- return new Promise((done) => {
58
- const child = spawn(process.execPath, [BIN, ...argv], {
59
- env,
60
- cwd: existsSync(cwd) ? cwd : undefined,
61
- stdio: ["ignore", "pipe", "pipe"],
62
- });
63
- if (onChild) onChild(child);
64
- let out = "",
65
- err = "";
66
- child.stdout.on("data", (d) => {
67
- out += d;
68
- });
69
- child.stderr.on("data", (d) => {
70
- err += d;
71
- });
72
- const timer = setTimeout(() => {
73
- child.kill("SIGKILL");
74
- err += `timed out after ${timeoutMs} ms`;
75
- }, timeoutMs);
76
- child.on("error", (e) => {
77
- clearTimeout(timer);
78
- done({ code: 2, out, err: err + e.message });
79
- });
80
- child.on("close", (code) => {
81
- clearTimeout(timer);
82
- done({ code: code === null ? 2 : code, out, err });
83
- });
84
- });
85
- }
86
- import { readConfigAt, isInsideVault, commandForm } from "./lib.mjs";
87
-
88
59
  // Two revisions, not four: 2025-03-26 has JSON-RPC batching (removed again in
89
60
  // 2025-06-18), which this server answers with -32600 — advertising that
90
61
  // revision would be a lie the conformance test could not see.
91
62
  export const PROTOCOL_VERSIONS = Object.freeze(["2025-11-25", "2025-06-18"]);
92
- export const DOCTOR_TIMEOUT_MS = 60000;
63
+ export { DOCTOR_TIMEOUT_MS };
93
64
  export const SERVER_NAME = "projectstore";
94
65
  export const TOOL_CEILING = 8;
95
66
  export const TOOL_LIST_TOKEN_CEILING = 3000; // ADR decision 7, chars/4
@@ -105,7 +76,7 @@ export const E_INTERNAL = -32603;
105
76
  // ─── The tool table ────────────────────────────────────────────────────
106
77
  //
107
78
  // One row per MCP tool: the verb it is the JSON form of, how its arguments
108
- // become argv, and the input schema a client sees. cli.mjs's VERBS rows name
79
+ // become argv, and the input schema a client sees. verbs.mjs's VERBS rows name
109
80
  // these tools in their `mcp` field; a drift test pins the two tables to each
110
81
  // other in both directions.
111
82
 
@@ -322,7 +293,7 @@ export function createServer({
322
293
  env = process.env,
323
294
  cwd = project,
324
295
  version = packageVersion(),
325
- runVerb = run,
296
+ runVerb = runRead,
326
297
  } = {}) {
327
298
  let initialized = false;
328
299
  const cfgOf = () => readConfigAt(project);
@@ -394,18 +365,21 @@ export function createServer({
394
365
  ];
395
366
  let code, outText, errText;
396
367
  if (t.verb === "doctor") {
397
- ({
398
- code,
399
- out: outText,
400
- err: errText,
401
- } = await spawnBin(argv, {
368
+ // doctor is the one verb the CLI spawns synchronously, which would hold
369
+ // this server's loop for up to a minute — no ping answered, no other
370
+ // call served. Its child runs asynchronously here instead, read and
371
+ // wrapped by the read runner's own doctor code, so parity holds.
372
+ const answer = await doctorAsync(a, {
373
+ project,
402
374
  env,
403
- cwd,
404
375
  onChild: (child) => {
405
376
  if (requestId !== null) inFlight.set(requestId, child);
406
377
  },
407
- }));
378
+ });
408
379
  if (requestId !== null) inFlight.delete(requestId);
380
+ code = answer.code;
381
+ outText = JSON.stringify(answer.envelope, null, 2);
382
+ errText = "";
409
383
  } else {
410
384
  const out = new Sink(),
411
385
  err = new Sink();
@@ -670,3 +644,29 @@ export function serve({
670
644
  }
671
645
  });
672
646
  }
647
+
648
+ // The one path both entries start the server through: scripts/mcp-server.mjs
649
+ // (what the plugin's .mcp.json runs) and the CLI's `mcp` verb. A project must
650
+ // have been SUPPLIED — `project` (their --project), the neutral variable or
651
+ // the harness's declared directory; resolveProject's cwd fallback is exactly
652
+ // what the MCP ADR's decision 6 forbids here, so without one the project is
653
+ // null and serve() refuses to start.
654
+ export function serveSupplied({
655
+ project = null,
656
+ env = process.env,
657
+ cwd = process.cwd(),
658
+ stdin = process.stdin,
659
+ stdout = process.stdout,
660
+ stderr = process.stderr,
661
+ signals = process,
662
+ } = {}) {
663
+ const supplied = Boolean(project || env.PROJECTSTORE_PROJECT_DIR || projectRootDeclared(env));
664
+ return serve({
665
+ project: supplied ? resolveProject({ project, env, cwd }) : null,
666
+ env,
667
+ stdin,
668
+ stdout,
669
+ stderr,
670
+ signals,
671
+ });
672
+ }
@@ -0,0 +1,24 @@
1
+ // projectstore — model-spec.mjs: a harness manifest's model and effort blocks,
2
+ // read as they are.
3
+ //
4
+ // modelSpec(manifest) → agent_translation.models, or null
5
+ // effortSpec(manifest) → agent_translation.effort, or null
6
+ //
7
+ // Pure readers, split from models.mjs (which re-exports them) so a hook can
8
+ // read the manifest without loading the module that reads a live catalog.
9
+ // models.mjs holds a `fetch` that sends a key from the environment; doctor,
10
+ // which the SessionStart hook imports, needs only effortSpec. The portability
11
+ // suite fences every hook's imports off any module with a fetch call: the
12
+ // story "The MCP server's entry reaches no install verb…", PS-DIRECTORY,
13
+ // decision 4.
14
+ // This file imports nothing: keep it that way.
15
+
16
+ export function modelSpec(manifest) {
17
+ const m = manifest?.agent_translation?.models;
18
+ return m && typeof m === "object" ? m : null;
19
+ }
20
+
21
+ export function effortSpec(manifest) {
22
+ const e = manifest?.agent_translation?.effort;
23
+ return e && typeof e === "object" ? e : null;
24
+ }
@@ -41,6 +41,12 @@ import { homedir } from "node:os";
41
41
  import { dirname, join } from "node:path";
42
42
  import { cachePaths, harnessHome, whichOnPath } from "./harness.mjs";
43
43
  import { writeFileAtomic } from "./lib.mjs";
44
+ import { modelSpec, effortSpec } from "./model-spec.mjs";
45
+
46
+ // The two block readers live in model-spec.mjs, which imports nothing, so a
47
+ // hook's imports reach them without reaching this file's fetch. Re-exported:
48
+ // every caller that reads the catalog too keeps one import.
49
+ export { modelSpec, effortSpec };
44
50
 
45
51
  // A known list is fresh for a day (decision 3); a live read is bounded by 3 s.
46
52
  export const FRESH_MS = 24 * 60 * 60 * 1000;
@@ -48,16 +54,6 @@ export const LIVE_TIMEOUT_MS = 3000;
48
54
  // A catalog's output beyond this is not a catalog: the read stops there.
49
55
  const MAX_BYTES = 16 * 1024 * 1024;
50
56
 
51
- export function modelSpec(manifest) {
52
- const m = manifest?.agent_translation?.models;
53
- return m && typeof m === "object" ? m : null;
54
- }
55
-
56
- export function effortSpec(manifest) {
57
- const e = manifest?.agent_translation?.effort;
58
- return e && typeof e === "object" ? e : null;
59
- }
60
-
61
57
  // A level is a lowercase token: the shape --set accepts and a catalog's
62
58
  // level must have to be kept.
63
59
  export const LEVEL = /^[a-z][a-z0-9-]*$/;
@@ -3,9 +3,10 @@
3
3
  // The read operations behind the CLI's read verbs and the MCP surface's
4
4
  // tools — one exported function per MCP tool (MCP ADR decision 2): status,
5
5
  // orientation, search, show (get_artifact), neighbors, lineage, codeRefs.
6
- // Read-only, no stdout side effects, no writes: imported by scripts/cli.mjs;
7
- // the MCP server reaches these only through cli.run(), so the envelope is
8
- // built in one place — but it shares the module graph, where stdout is the
6
+ // Read-only, no stdout side effects, no writes: imported by the read-verb
7
+ // runner (scripts/read-verbs.mjs), whose handlers both the CLI's run() and
8
+ // the MCP server dispatch through, so the envelope is built in one place —
9
+ // and this module shares the server's module graph, where stdout is the
9
10
  // protocol channel.
10
11
  //
11
12
  // Every result is small on purpose — a model reads it. Artifact paths in
@@ -24,8 +25,8 @@
24
25
  // return the same facts), stories from the kanban generator's finder, the
25
26
  // vault walk from doctor's (a static import is safe: doctor's main() is
26
27
  // guarded, and this module takes one pure function from it — the MCP ADR's
27
- // "spawn, never import" is about running doctor, which stays cli.mjs's
28
- // spawn), the orientation from the SessionStart gather. Bad input is a
28
+ // "spawn, never import" is about running doctor, which stays the read
29
+ // runner's spawn), the orientation from the SessionStart gather. Bad input is a
29
30
  // usage error (`code: "USAGE"`), which the front-ends turn into exit 2.
30
31
  //
31
32
  // Normative: MCP ADR decisions 2 and 4; the link-graph ADR's decision 4
@@ -56,7 +57,7 @@ import { buildGraph } from "./graph.mjs";
56
57
  import { findStories, statusToColumn } from "./kanban.mjs";
57
58
  // status's text screen is drawn with the presentation primitives; term.mjs
58
59
  // has no side effect at import, so the MCP server's graph gains nothing it
59
- // could trip on (cli.mjs imports it already).
60
+ // could trip on (verbs.mjs imports it already).
60
61
  import { PLAIN, painter, icon, heading, kv, rows, wrap, commandBlock } from "./term.mjs";
61
62
  import { packageCommand } from "./harness.mjs";
62
63
 
@@ -0,0 +1,277 @@
1
+ // projectstore — read-verbs.mjs
2
+ //
3
+ // The read-verb runner: the handlers of the verbs that write nothing (status,
4
+ // orientation, search, show, graph, codemap, doctor and version), and
5
+ // runRead(), which dispatches through the one verb table (scripts/verbs.mjs)
6
+ // with these handlers alone. The CLI's run() hands dispatch() these and its
7
+ // write handlers; the MCP server (scripts/mcp.mjs) runs runRead() and imports
8
+ // nothing from cli.mjs. So every MCP tool is a call into the same code its CLI
9
+ // verb runs, with the same envelope (MCP ADR decisions 1 and 2), and no module
10
+ // this one reaches is the installer or what it spawns — the story "The MCP
11
+ // server's entry reaches no install verb through a read-verb runner that
12
+ // shares the CLI's verb table…" (PS-DIRECTORY), whose fence
13
+ // (tests/portability.test.mjs) walks this module's imports.
14
+ //
15
+ // The one import() here is doctor's text renderer, doctor-report.mjs, which
16
+ // imports term.mjs and lib.mjs only.
17
+
18
+ import { spawnSync, spawn } from "node:child_process";
19
+ import { existsSync } from "node:fs";
20
+ import { resolve, dirname } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import * as term from "./term.mjs";
23
+ import { doctorFallbackText } from "./lib.mjs";
24
+ import { READ_OPERATIONS, LINEAGE_KINDS } from "./query.mjs";
25
+ import { dispatch, envelope, packageVersion, usageFail, ownEnv, runVersion } from "./verbs.mjs";
26
+
27
+ const HERE = dirname(fileURLToPath(import.meta.url));
28
+ export const DOCTOR_SCRIPT = resolve(HERE, "doctor.mjs");
29
+ export const DOCTOR_TIMEOUT_MS = 60000;
30
+
31
+ // The read verbs: one call into query.mjs, the result in the envelope or
32
+ // rendered. A usage error from the operation (a bad path, a missing query)
33
+ // is exit 2 with the message, never a stack trace. A renderer gets the
34
+ // stream's caps — painted at a terminal, plain on a pipe — and the env its
35
+ // command forms are named for; one that takes neither ignores them.
36
+ function emitRead({ verb, values, project, stdout, env }, op, result, ok = true) {
37
+ if (values.json) stdout.write(JSON.stringify(envelope(verb, project, ok, result), null, 2) + "\n");
38
+ else stdout.write(op.render(result, { caps: term.caps(stdout, env), env }));
39
+ return ok ? 0 : 1;
40
+ }
41
+
42
+ function readVerb(name) {
43
+ return async (ctx) => {
44
+ const { row, values, positionals, cfg, project } = ctx;
45
+ const op = READ_OPERATIONS[name];
46
+ try {
47
+ let result;
48
+ if (name === "status") result = op.fn(cfg, { project });
49
+ else if (name === "orientation") result = await op.fn(cfg);
50
+ else if (name === "search")
51
+ result = op.fn(cfg, positionals.join(" "), {
52
+ kinds: values.kind || null,
53
+ status: values.status ?? null,
54
+ limit: values.limit,
55
+ includeDerived: Boolean(values["include-derived"]),
56
+ caseSensitive: Boolean(values["case-sensitive"]),
57
+ });
58
+ else if (name === "show")
59
+ result = op.fn(cfg, positionals[0], { body: Boolean(values.body), section: values.section ?? null });
60
+ return emitRead({ verb: row.verb, ...ctx }, op, result);
61
+ } catch (e) {
62
+ if (e && e.code === "USAGE") return usageFail(e, { verb: row.verb, ...ctx });
63
+ throw e;
64
+ }
65
+ };
66
+ }
67
+
68
+ async function runGraph(ctx) {
69
+ const { row, values, positionals, cfg } = ctx;
70
+ const sub = positionals[0];
71
+ const path = positionals[1];
72
+ if (!["neighbors", "lineage"].includes(sub))
73
+ return usageFail(Object.assign(new Error("graph takes neighbors <path> or lineage <path>"), { code: "USAGE" }), {
74
+ verb: row.verb,
75
+ ...ctx,
76
+ });
77
+ const op = READ_OPERATIONS[sub];
78
+ try {
79
+ // The row declares the union; each mode takes its own — an option the
80
+ // mode would ignore is a usage error, not a silent no-op.
81
+ const notFor = sub === "neighbors" ? ["depth"] : ["direction", "limit"];
82
+ for (const o of notFor)
83
+ if (values[o] !== undefined)
84
+ throw Object.assign(new Error(`--${o} is not an option of graph ${sub}`), { code: "USAGE" });
85
+ const result =
86
+ sub === "neighbors"
87
+ ? op.fn(cfg, path, { kinds: values.kind || null, direction: values.direction, limit: values.limit })
88
+ : op.fn(cfg, path, {
89
+ depth: values.depth,
90
+ kinds: values.kind && values.kind.length ? values.kind : LINEAGE_KINDS,
91
+ });
92
+ return emitRead({ verb: `graph ${sub}`, ...ctx }, op, result);
93
+ } catch (e) {
94
+ if (e && e.code === "USAGE") return usageFail(e, { verb: row.verb, ...ctx });
95
+ throw e;
96
+ }
97
+ }
98
+
99
+ async function runCodemap(ctx) {
100
+ const { row, values, cfg } = ctx;
101
+ const op = READ_OPERATIONS.codeRefs;
102
+ try {
103
+ if (!values.for)
104
+ throw Object.assign(new Error("codemap takes --for <selector>; regeneration is reconcile --only codemap"), {
105
+ code: "USAGE",
106
+ });
107
+ return emitRead({ verb: row.verb, ...ctx }, op, op.fn(cfg, values.for, { reverse: Boolean(values.reverse) }));
108
+ } catch (e) {
109
+ if (e && e.code === "USAGE") return usageFail(e, { verb: row.verb, ...ctx });
110
+ throw e;
111
+ }
112
+ }
113
+
114
+ // ─── doctor ────────────────────────────────────────────────────────────
115
+ //
116
+ // Spawned, never imported (MCP ADR decision 2): doctor's main writes to
117
+ // stdout and is not exported, and importing its checks would be a second
118
+ // doctor. One spawn of scripts/doctor.mjs, always --json: its findings decide
119
+ // the exit code (doctor.mjs sets none of its own). The CLI spawns it
120
+ // synchronously; the MCP server, whose loop must keep answering, spawns it
121
+ // asynchronously (doctorAsync). Both read the child through doctorOutcome
122
+ // and answer doctorEnvelope, so the tool's result is the verb's by
123
+ // construction.
124
+
125
+ // The child's argv: --json, and the sections the flags name.
126
+ export const doctorArgs = (values) => [
127
+ DOCTOR_SCRIPT,
128
+ "--json",
129
+ ...[values.install && "--install", values.vault && "--vault"].filter(Boolean),
130
+ ];
131
+
132
+ // Where the child runs: in the project when it exists — a project that does
133
+ // not exist is still one doctor can report on ("not bound") — in the
134
+ // environment every child of this package gets (ownEnv).
135
+ const doctorSpawnOptions = (project, env) => ({
136
+ cwd: existsSync(project) ? project : undefined,
137
+ env: ownEnv(env, project),
138
+ });
139
+
140
+ // The child's result → { ok, findings } or { error }.
141
+ export function doctorOutcome({ error = null, status, stdout = "", stderr = "" }) {
142
+ if (error) return { error: error.message || String(error) };
143
+ if (status !== 0 && !stdout) return { error: (stderr || "").trim() || `exit ${status}` };
144
+ let findings;
145
+ try {
146
+ findings = JSON.parse(stdout);
147
+ } catch {
148
+ return { error: "unparseable output" };
149
+ }
150
+ return { ok: !findings.some((f) => f.level === "issue"), findings };
151
+ }
152
+
153
+ // The verb's envelope and exit code for an outcome: 0 clean, 1 findings, 2
154
+ // when doctor could not answer.
155
+ export function doctorEnvelope(project, outcome) {
156
+ if (outcome.error) return { code: 2, envelope: envelope("doctor", project, false, { error: outcome.error }) };
157
+ return { code: outcome.ok ? 0 : 1, envelope: envelope("doctor", project, outcome.ok, outcome.findings) };
158
+ }
159
+
160
+ // The MCP server's doctor: the same child, asynchronous, killed after
161
+ // `timeoutMs` or when the caller kills it (onChild hands it over, for
162
+ // notifications/cancelled). Resolves with doctorEnvelope's answer.
163
+ export function doctorAsync(values, { project, env, timeoutMs = DOCTOR_TIMEOUT_MS, onChild = null }) {
164
+ return new Promise((done) => {
165
+ const child = spawn(process.execPath, doctorArgs(values), {
166
+ ...doctorSpawnOptions(project, env),
167
+ stdio: ["ignore", "pipe", "pipe"],
168
+ });
169
+ if (onChild) onChild(child);
170
+ let out = "",
171
+ err = "",
172
+ timedOut = false;
173
+ child.stdout.on("data", (d) => {
174
+ out += d;
175
+ });
176
+ child.stderr.on("data", (d) => {
177
+ err += d;
178
+ });
179
+ const timer = setTimeout(() => {
180
+ timedOut = true;
181
+ child.kill("SIGKILL");
182
+ }, timeoutMs);
183
+ const finish = (r) => {
184
+ clearTimeout(timer);
185
+ done(doctorEnvelope(project, doctorOutcome(r)));
186
+ };
187
+ child.on("error", (e) => finish({ error: e }));
188
+ child.on("close", (status, signal) =>
189
+ finish(
190
+ status === null
191
+ ? { error: new Error(timedOut ? `timed out after ${timeoutMs} ms` : `ended by ${signal}`) }
192
+ : { status, stdout: out, stderr: err },
193
+ ),
194
+ );
195
+ });
196
+ }
197
+
198
+ // The CLI's doctor: the text a person reads is drawn from the findings here,
199
+ // in this process, by doctor-report.mjs — a renderer that imports no check
200
+ // (the presentation spec, contract 11). So a terminal gets colour, which a
201
+ // piped child could not tell it had, and the report and the exit code can
202
+ // never come from two different runs.
203
+ async function runDoctor({ values, project, env, stdout, stderr }) {
204
+ const r = spawnSync(process.execPath, doctorArgs(values), {
205
+ ...doctorSpawnOptions(project, env),
206
+ encoding: "utf8",
207
+ timeout: DOCTOR_TIMEOUT_MS,
208
+ maxBuffer: 1 << 24,
209
+ });
210
+ const outcome = doctorOutcome(r);
211
+ const answer = doctorEnvelope(project, outcome);
212
+ if (values.json) stdout.write(JSON.stringify(answer.envelope, null, 2) + "\n");
213
+ if (outcome.error) {
214
+ stderr.write(`doctor failed: ${outcome.error}\n`);
215
+ return answer.code;
216
+ }
217
+ if (!values.json) {
218
+ // The sections as doctor.mjs derives them: no flag is both.
219
+ const named = [values.install && "install", values.vault && "vault"].filter(Boolean);
220
+ stdout.write(
221
+ await doctorText(outcome.findings, named.length ? named : ["install", "vault"], {
222
+ caps: term.caps(stdout, env),
223
+ verbose: Boolean(values.verbose),
224
+ project,
225
+ env: ownEnv(env, project),
226
+ stderr,
227
+ }),
228
+ );
229
+ }
230
+ return answer.code;
231
+ }
232
+
233
+ // doctor's text from its findings. `env` is the child's environment
234
+ // (ownEnv), so every command form the report names is the one doctor itself
235
+ // would name. A renderer that cannot load, or throws, must not cost the
236
+ // reader the findings: they are printed one per line, `level check message
237
+ // — file`, and the Summary line still ends them (lib.mjs). `load` stands in
238
+ // for the import in a test.
239
+ export async function doctorText(
240
+ findings,
241
+ groups,
242
+ { caps, verbose = false, project = null, env = process.env, stderr = null } = {},
243
+ { load = () => import("./doctor-report.mjs") } = {},
244
+ ) {
245
+ try {
246
+ const { report } = await load();
247
+ return report(findings, groups, { caps, verbose, version: packageVersion(), project, env });
248
+ } catch (e) {
249
+ if (stderr)
250
+ stderr.write(
251
+ `doctor: the report could not be drawn (${e && e.message ? e.message : e}); its findings follow, one per line.\n`,
252
+ );
253
+ return doctorFallbackText(findings, { env });
254
+ }
255
+ }
256
+
257
+ // ─── The runner ────────────────────────────────────────────────────────
258
+
259
+ // The read verbs' handlers, keyed by verb: what the read runner serves, and
260
+ // the half of cli.mjs's HANDLERS that writes nothing.
261
+ export const READ_HANDLERS = Object.freeze({
262
+ status: readVerb("status"),
263
+ orientation: readVerb("orientation"),
264
+ search: readVerb("search"),
265
+ show: readVerb("show"),
266
+ graph: runGraph,
267
+ codemap: runCodemap,
268
+ doctor: runDoctor,
269
+ version: runVersion,
270
+ });
271
+
272
+ // runRead(argv, opts) — the CLI's parse over the one table, serving the read
273
+ // verbs only: any other verb of the table is refused, exit 2. `opts` as
274
+ // dispatch()'s (verbs.mjs).
275
+ export function runRead(argv, opts = {}) {
276
+ return dispatch(argv, READ_HANDLERS, opts);
277
+ }