@nifrajs/cli 2.13.0 → 3.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 (114) hide show
  1. package/dist/capabilities-tool.d.ts +54 -1
  2. package/dist/capabilities-tool.d.ts.map +1 -1
  3. package/dist/capabilities-tool.js +146 -18
  4. package/dist/capabilities-tool.js.map +1 -1
  5. package/dist/check.d.ts +11 -11
  6. package/dist/check.d.ts.map +1 -1
  7. package/dist/check.js +260 -49
  8. package/dist/check.js.map +1 -1
  9. package/dist/cli.d.ts +11 -0
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/cli.js +130 -414
  12. package/dist/cli.js.map +1 -1
  13. package/dist/command-catalog.d.ts +250 -0
  14. package/dist/command-catalog.d.ts.map +1 -0
  15. package/dist/command-catalog.js +1032 -0
  16. package/dist/command-catalog.js.map +1 -0
  17. package/dist/contracts.d.ts +9 -0
  18. package/dist/contracts.d.ts.map +1 -1
  19. package/dist/contracts.js +22 -6
  20. package/dist/contracts.js.map +1 -1
  21. package/dist/doctor.d.ts +55 -0
  22. package/dist/doctor.d.ts.map +1 -1
  23. package/dist/doctor.js +82 -9
  24. package/dist/doctor.js.map +1 -1
  25. package/dist/env-file.d.ts +17 -0
  26. package/dist/env-file.d.ts.map +1 -0
  27. package/dist/env-file.js +113 -0
  28. package/dist/env-file.js.map +1 -0
  29. package/dist/fix-recipes.d.ts.map +1 -1
  30. package/dist/fix-recipes.js +91 -15
  31. package/dist/fix-recipes.js.map +1 -1
  32. package/dist/internal/reserved-segment-codemod.d.ts +36 -0
  33. package/dist/internal/reserved-segment-codemod.d.ts.map +1 -0
  34. package/dist/internal/reserved-segment-codemod.js +134 -0
  35. package/dist/internal/reserved-segment-codemod.js.map +1 -0
  36. package/dist/internal/typescript-import.d.ts +1 -1
  37. package/dist/internal/typescript-import.d.ts.map +1 -1
  38. package/dist/internal/typescript-import.js +62 -11
  39. package/dist/internal/typescript-import.js.map +1 -1
  40. package/dist/introspect.d.ts +26 -1
  41. package/dist/introspect.d.ts.map +1 -1
  42. package/dist/introspect.js +74 -24
  43. package/dist/introspect.js.map +1 -1
  44. package/dist/load.d.ts.map +1 -1
  45. package/dist/load.js +22 -5
  46. package/dist/load.js.map +1 -1
  47. package/dist/manifest-tool.d.ts +15 -1
  48. package/dist/manifest-tool.d.ts.map +1 -1
  49. package/dist/manifest-tool.js +23 -9
  50. package/dist/manifest-tool.js.map +1 -1
  51. package/dist/mcp-http.js +1 -1
  52. package/dist/mcp-http.js.map +1 -1
  53. package/dist/mcp.d.ts +16 -0
  54. package/dist/mcp.d.ts.map +1 -1
  55. package/dist/mcp.js +127 -355
  56. package/dist/mcp.js.map +1 -1
  57. package/dist/project-facts.d.ts +40 -0
  58. package/dist/project-facts.d.ts.map +1 -0
  59. package/dist/project-facts.js +36 -0
  60. package/dist/project-facts.js.map +1 -0
  61. package/dist/recipes/3.0.0.d.ts +10 -0
  62. package/dist/recipes/3.0.0.d.ts.map +1 -0
  63. package/dist/recipes/3.0.0.js +23 -0
  64. package/dist/recipes/3.0.0.js.map +1 -0
  65. package/dist/recipes/index.d.ts.map +1 -1
  66. package/dist/recipes/index.js +2 -0
  67. package/dist/recipes/index.js.map +1 -1
  68. package/dist/release-verification.d.ts.map +1 -1
  69. package/dist/release-verification.js +15 -0
  70. package/dist/release-verification.js.map +1 -1
  71. package/dist/rules/comment-markers.d.ts +8 -0
  72. package/dist/rules/comment-markers.d.ts.map +1 -1
  73. package/dist/rules/comment-markers.js +36 -0
  74. package/dist/rules/comment-markers.js.map +1 -1
  75. package/dist/rules/index.d.ts +2 -3
  76. package/dist/rules/index.d.ts.map +1 -1
  77. package/dist/rules/index.js.map +1 -1
  78. package/dist/rules/routes.d.ts.map +1 -1
  79. package/dist/rules/routes.js +29 -44
  80. package/dist/rules/routes.js.map +1 -1
  81. package/dist/rules/security.js +14 -14
  82. package/dist/rules/security.js.map +1 -1
  83. package/dist/workspace-link.d.ts +37 -0
  84. package/dist/workspace-link.d.ts.map +1 -0
  85. package/dist/workspace-link.js +72 -0
  86. package/dist/workspace-link.js.map +1 -0
  87. package/docs/examples.json +1 -1
  88. package/docs/llms-full.txt +362 -20
  89. package/docs/types.json +956 -56
  90. package/package.json +9 -9
  91. package/src/capabilities-tool.ts +229 -21
  92. package/src/check.ts +312 -65
  93. package/src/cli.ts +140 -405
  94. package/src/command-catalog.ts +1435 -0
  95. package/src/contracts.ts +28 -7
  96. package/src/doctor.ts +134 -12
  97. package/src/env-file.ts +121 -0
  98. package/src/fix-recipes.ts +101 -15
  99. package/src/internal/reserved-segment-codemod.ts +150 -0
  100. package/src/internal/typescript-import.ts +61 -11
  101. package/src/introspect.ts +82 -21
  102. package/src/load.ts +25 -6
  103. package/src/manifest-tool.ts +43 -12
  104. package/src/mcp-http.ts +1 -1
  105. package/src/mcp.ts +163 -420
  106. package/src/project-facts.ts +86 -0
  107. package/src/recipes/3.0.0.ts +24 -0
  108. package/src/recipes/index.ts +2 -0
  109. package/src/release-verification.ts +17 -0
  110. package/src/rules/comment-markers.ts +36 -0
  111. package/src/rules/index.ts +3 -4
  112. package/src/rules/routes.ts +30 -44
  113. package/src/rules/security.ts +14 -14
  114. package/src/workspace-link.ts +80 -0
package/dist/mcp.js CHANGED
@@ -40,16 +40,15 @@ import { basename, isAbsolute, relative, resolve, sep } from "node:path";
40
40
  import { fileURLToPath } from "node:url";
41
41
  import { reflectRoutes } from "@nifrajs/core/reflection";
42
42
  import { Glob } from "bun";
43
+ import { commandCatalog, commandMcpName, findCommandSpec, } from "./command-catalog.js";
43
44
  import { collectContractProof } from "./contract-proof.js";
44
45
  import { loadDocsCorpus } from "./docs-search.js";
45
46
  import { loadExamplesCorpus } from "./examples.js";
46
- import { describeProject } from "./introspect.js";
47
47
  import { detectMonorepo, loadMonorepoApps } from "./load.js";
48
48
  import { docsTools } from "./mcp-docs-tools.js";
49
49
  import { createMcpProtocolState, handleRpc, rpcError, } from "./mcp-protocol.js";
50
50
  import { applyClientRoots, detectToolingDrift, driftNote, pathsFromRootsResult, resolveRootState, rootInstructions, rootVerdict, } from "./mcp-root.js";
51
51
  import { loadTypesCorpus } from "./types-search.js";
52
- import { collectProjectWorkGraph } from "./work-graph.js";
53
52
  /** Path to a sibling child entry (`mcp-run` / `mcp-render` / `mcp-ws`), resolved next to this module (`.ts` in
54
53
  * dev, `.js` once built). Each runs in a FRESH subprocess per call so the project's current code loads. */
55
54
  function childPath(name) {
@@ -69,6 +68,8 @@ function childPath(name) {
69
68
  * within one attention span rather than after minutes of polling.
70
69
  */
71
70
  const CHILD_TIMEOUT_MS = 30_000;
71
+ /** Maximum stdout or stderr retained from a project subprocess. The process is killed at the limit. */
72
+ export const CHILD_OUTPUT_MAX_BYTES = 1_048_576;
72
73
  /** Local dev-tool reads are intentionally bounded: MCP runs in an agent process and must not hang on or
73
74
  * buffer an unrelated loopback service just because a caller supplied its port. */
74
75
  export const LOCAL_TOOL_FETCH_TIMEOUT_MS = 2_000;
@@ -126,6 +127,39 @@ const timeoutMessage = (label, ms) => `${label} timed out after ${ms / 1000}s an
126
127
  `The app was loaded but the process did not finish. Most often this is a module-level side effect ` +
127
128
  `that keeps the event loop alive (a database pool, a Redis client, an interval) opened during import ` +
128
129
  `rather than lazily. Check for top-level connections in the app entry or anything it imports.`;
130
+ /** Read child output incrementally and cancel as soon as the byte budget is crossed. */
131
+ export async function readBoundedStream(stream, maxBytes = CHILD_OUTPUT_MAX_BYTES, onLimit) {
132
+ const reader = stream.getReader();
133
+ const decoder = new TextDecoder();
134
+ const chunks = [];
135
+ let totalBytes = 0;
136
+ try {
137
+ for (;;) {
138
+ const { done, value } = await reader.read();
139
+ if (done) {
140
+ chunks.push(decoder.decode());
141
+ return { text: chunks.join(""), truncated: false };
142
+ }
143
+ if (value === undefined)
144
+ continue;
145
+ const remaining = maxBytes - totalBytes;
146
+ if (remaining <= 0 || value.byteLength > remaining) {
147
+ if (remaining > 0) {
148
+ chunks.push(decoder.decode(value.subarray(0, remaining), { stream: true }));
149
+ chunks.push(decoder.decode());
150
+ }
151
+ await reader.cancel();
152
+ onLimit?.();
153
+ return { text: chunks.join(""), truncated: true };
154
+ }
155
+ totalBytes += value.byteLength;
156
+ chunks.push(decoder.decode(value, { stream: true }));
157
+ }
158
+ }
159
+ finally {
160
+ reader.releaseLock();
161
+ }
162
+ }
129
163
  async function spawnChild(child, cwd, input, label, signal) {
130
164
  if (signal?.aborted)
131
165
  return `${label} cancelled before it started.`;
@@ -134,31 +168,48 @@ async function spawnChild(child, cwd, input, label, signal) {
134
168
  stdout: "pipe",
135
169
  stderr: "pipe",
136
170
  });
137
- const abort = () => proc.kill();
171
+ let killed = false;
172
+ const kill = () => {
173
+ if (killed)
174
+ return;
175
+ killed = true;
176
+ proc.kill();
177
+ };
178
+ const abort = () => kill();
138
179
  signal?.addEventListener("abort", abort, { once: true });
139
180
  let timedOut = false;
140
181
  const timer = setTimeout(() => {
141
182
  timedOut = true;
142
- proc.kill();
183
+ kill();
143
184
  }, CHILD_TIMEOUT_MS);
185
+ let outputExceeded = false;
144
186
  try {
145
187
  proc.stdin.write(JSON.stringify(input));
146
188
  await proc.stdin.end();
147
189
  const [out, err] = await Promise.all([
148
- new Response(proc.stdout).text(),
149
- new Response(proc.stderr).text(),
190
+ readBoundedStream(proc.stdout, CHILD_OUTPUT_MAX_BYTES, () => {
191
+ outputExceeded = true;
192
+ kill();
193
+ }),
194
+ readBoundedStream(proc.stderr, CHILD_OUTPUT_MAX_BYTES, () => {
195
+ outputExceeded = true;
196
+ kill();
197
+ }),
150
198
  ]);
151
199
  await proc.exited;
152
200
  if (signal?.aborted) {
153
201
  const reason = typeof signal.reason === "string" ? `: ${signal.reason}` : "";
154
202
  return `${label} cancelled${reason}.`;
155
203
  }
204
+ if (outputExceeded) {
205
+ return `${label} output exceeded ${CHILD_OUTPUT_MAX_BYTES} bytes and was terminated.`;
206
+ }
156
207
  // A killed child may still have flushed a complete result before the timer fired; prefer real
157
208
  // output over the timeout message so a slow-but-successful render is not reported as a failure.
158
- const text = out.trim();
209
+ const text = out.text.trim();
159
210
  if (timedOut && text === "")
160
211
  return timeoutMessage(label, CHILD_TIMEOUT_MS);
161
- return text || `${label} failed:\n${err.trim() || "(no output)"}`;
212
+ return text || `${label} failed:\n${err.text.trim() || "(no output)"}`;
162
213
  }
163
214
  finally {
164
215
  clearTimeout(timer);
@@ -280,7 +331,17 @@ export class WarmWorker {
280
331
  const { done, value } = await reader.read();
281
332
  if (done)
282
333
  break;
334
+ if (value !== undefined && value.byteLength > CHILD_OUTPUT_MAX_BYTES) {
335
+ this.stderrBuffer = boundedAppend(this.stderrBuffer, `warm ${this.label} worker stdout exceeded ${CHILD_OUTPUT_MAX_BYTES} bytes\n`);
336
+ this.stop();
337
+ return;
338
+ }
283
339
  this.stdoutBuffer += decoder.decode(value, { stream: true });
340
+ if (this.stdoutBuffer.length > CHILD_OUTPUT_MAX_BYTES) {
341
+ this.stderrBuffer = boundedAppend(this.stderrBuffer, `warm ${this.label} worker stdout exceeded ${CHILD_OUTPUT_MAX_BYTES} bytes\n`);
342
+ this.stop();
343
+ return;
344
+ }
284
345
  let nl = this.stdoutBuffer.indexOf("\n");
285
346
  while (nl !== -1) {
286
347
  const line = this.stdoutBuffer.slice(0, nl).trim();
@@ -593,11 +654,66 @@ export function resolveProjectDir(root, dir) {
593
654
  function dirError(dir) {
594
655
  return JSON.stringify({ ok: false, error: `dir must be a subdirectory of the project root - "${dir}" escapes it.` }, null, 2);
595
656
  }
596
- /** Build the project-scoped tools for `cwd`. */
657
+ /** Adapt one executable catalog spec to its MCP descriptor and project-scoped handler. */
658
+ export function toMcpTool(source, options) {
659
+ const spec = "run" in source ? source : findCommandSpec(source.name);
660
+ if (spec === undefined)
661
+ throw new Error(`missing command spec for ${source.name}`);
662
+ const entry = "run" in source ? undefined : source;
663
+ const { cwd } = options;
664
+ const loadAppCached = options.loadAppCached ?? createCachedAppLoader(cwd);
665
+ return {
666
+ name: commandMcpName(entry?.name ?? spec.name),
667
+ description: entry?.summary ?? spec.summary,
668
+ inputSchema: entry?.inputSchema ?? spec.input.jsonSchema,
669
+ handler: async (args, context) => {
670
+ const raw = { ...args };
671
+ const dir = raw.dir;
672
+ if (dir !== undefined && typeof dir !== "string")
673
+ return dirError(undefined);
674
+ const target = resolveProjectDir(cwd, dir);
675
+ if (target === null)
676
+ return dirError(dir);
677
+ if (typeof raw.config === "string") {
678
+ const config = resolve(target, raw.config);
679
+ if (config !== target && !config.startsWith(`${target}${sep}`))
680
+ return JSON.stringify({ ok: false, error: "config must stay inside the selected project directory" }, null, 2);
681
+ }
682
+ delete raw.dir;
683
+ let input;
684
+ try {
685
+ input = spec.input.parse(raw);
686
+ }
687
+ catch (error) {
688
+ return JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) }, null, 2);
689
+ }
690
+ const commandContext = {
691
+ cwd: target,
692
+ signal: context.signal,
693
+ progress: () => context.reportProgress?.(0.5, 1),
694
+ ...(target === cwd ? { loadApp: loadAppCached } : {}),
695
+ };
696
+ const output = await spec.run(input, commandContext);
697
+ const value = spec.json?.(output, input) ?? output;
698
+ return typeof value === "string" ? value : JSON.stringify(value, null, 2);
699
+ },
700
+ };
701
+ }
702
+ export function catalogProjectTools(cwd, loadAppCached = createCachedAppLoader(cwd)) {
703
+ return commandCatalog
704
+ .filter((entry) => entry.transports.includes("mcp"))
705
+ .map((entry) => {
706
+ const spec = findCommandSpec(entry.name);
707
+ if (spec === undefined)
708
+ throw new Error(`missing command spec for ${entry.name}`);
709
+ return toMcpTool(spec, { cwd, loadAppCached });
710
+ });
711
+ }
597
712
  export function projectTools(cwd, loadAppCached = createCachedAppLoader(cwd)) {
598
713
  const warmRun = createWarmHandler("mcp-run", cwd, "run");
599
714
  const warmRender = createWarmHandler("mcp-render", cwd, "render");
600
- return [
715
+ const catalogTools = catalogProjectTools(cwd, () => loadAppCached());
716
+ const legacyTools = [
601
717
  {
602
718
  name: "nifra_contract_proof",
603
719
  description: "Compare the current route contract with its snapshot and join each changed route to its route-assurance and capability evidence. Returns hasBreaking as the gate. The typed-contract check is lazy and runs only when check is true.",
@@ -646,75 +762,6 @@ export function projectTools(cwd, loadAppCached = createCachedAppLoader(cwd)) {
646
762
  }
647
763
  },
648
764
  },
649
- {
650
- name: "nifra_prove",
651
- description: "Build the static verification work graph for this project. Pass changed files to get only impacted routes and the cheapest proof plan. The result includes a serializable evidence bundle and a machine-checkable stop condition. Requires a fresh build and never probes a running application.",
652
- inputSchema: {
653
- type: "object",
654
- properties: {
655
- files: {
656
- type: "array",
657
- items: { type: "string" },
658
- description: "Project-relative changed files. Omit for a graph overview.",
659
- },
660
- minLevel: {
661
- type: "integer",
662
- minimum: 0,
663
- maximum: 4,
664
- description: "Required proof level for the stop condition. Defaults to 1.",
665
- },
666
- },
667
- additionalProperties: false,
668
- },
669
- handler: async (args) => {
670
- const files = args.files;
671
- const minLevel = args.minLevel;
672
- if ((files !== undefined &&
673
- (!Array.isArray(files) || files.some((file) => typeof file !== "string"))) ||
674
- (minLevel !== undefined &&
675
- (typeof minLevel !== "number" ||
676
- !Number.isInteger(minLevel) ||
677
- minLevel < 0 ||
678
- minLevel > 4))) {
679
- return JSON.stringify({
680
- ok: false,
681
- error: "files must be strings and minLevel must be an integer from 0 to 4",
682
- }, null, 2);
683
- }
684
- try {
685
- return JSON.stringify(await collectProjectWorkGraph(cwd, {
686
- ...(files === undefined ? {} : { changedFiles: files }),
687
- ...(minLevel === undefined ? {} : { minLevel }),
688
- }), null, 2);
689
- }
690
- catch (error) {
691
- return JSON.stringify({ ok: false, error: error instanceof Error ? error.message : "work graph failed" }, null, 2);
692
- }
693
- },
694
- },
695
- {
696
- name: "nifra_context",
697
- description: "Get this nifra project's surface. Call it once UNFILTERED for a tight INDEX: the route list (API routes as `METHOD path`, page routes as `pattern → file`) + framework conventions + a pointer - cheap even on a big app, no per-route schema dump. Then pass `path` (a route prefix like /api/orders) and/or `kind` (api|pages) to fetch the FULL contract for that slice (body/query/response TS shapes + the exact typed-client call form).",
698
- inputSchema: {
699
- type: "object",
700
- properties: {
701
- path: {
702
- type: "string",
703
- description: "Only routes whose path/pattern starts with this prefix.",
704
- },
705
- kind: {
706
- type: "string",
707
- enum: ["api", "pages"],
708
- description: "Limit to API routes or page routes.",
709
- },
710
- },
711
- additionalProperties: false,
712
- },
713
- handler: async (args) => {
714
- const filter = args;
715
- return describeProject(await loadAppCached(), filter);
716
- },
717
- },
718
765
  {
719
766
  name: "nifra_explain",
720
767
  description: "Turn a nifra error into a STRUCTURED diagnostic instead of eyeballing a stack trace: a stable `code`, the top frame in YOUR source, a codeframe around the offending line, and - when nifra recognises the failure - the plain-language `cause` + `fix` + docs anchor. Pass `error` (and `stack` if you have it, e.g. from nifra_run/nifra_test output or a failing build) to explain a specific failure; or pass `port` to fetch the running dev server's most recent SSR failure from `/__nifra/last-error`. Returns the same JSON the dev overlay renders.",
@@ -844,25 +891,6 @@ export function projectTools(cwd, loadAppCached = createCachedAppLoader(cwd)) {
844
891
  }
845
892
  },
846
893
  },
847
- {
848
- name: "nifra_routes",
849
- description: "List this project's API routes as STRUCTURED JSON - each `{ method, path, call, body?, query?, response? }`, where `call` is the exact typed-client call form and the shapes are compact TS-typed contracts. For programmatic use (list_routes / get_route_schema) instead of parsing the nifra_context Markdown. No args = every route; pass `path` (a path or prefix like /api/orders) to narrow to those routes.",
850
- inputSchema: {
851
- type: "object",
852
- properties: {
853
- path: {
854
- type: "string",
855
- description: "Only routes whose path starts with this prefix (omit for all routes).",
856
- },
857
- },
858
- additionalProperties: false,
859
- },
860
- handler: async (args) => {
861
- const { routesToJson } = await import("./introspect.js");
862
- const { path } = args;
863
- return JSON.stringify(routesToJson(await loadAppCached(), path), null, 2);
864
- },
865
- },
866
894
  {
867
895
  name: "nifra_openapi",
868
896
  description: 'Return this project\'s backend OpenAPI 3.1 document generated from backend.ts route schemas via @nifrajs/schema. Use `format:"json"` for machine edits (default) or `format:"yaml"` for humans. Pass `path` (a route prefix like /api/orders, mirroring nifra_routes) to narrow a large backend to operations under that prefix instead of the whole document. Frontend-only apps return a valid empty paths object.',
@@ -1043,180 +1071,6 @@ export function projectTools(cwd, loadAppCached = createCachedAppLoader(cwd)) {
1043
1071
  return `${status}\n\n${renderScaffold(path, framework)}`;
1044
1072
  },
1045
1073
  },
1046
- {
1047
- name: "nifra_check",
1048
- description: 'Run the project\'s drift gate and return a structured result { ok, typecheck, diagnostics[], pipeline? }: typecheck (the frontend↔backend contract), plus lints for hand-rolled fetch() to your own API, untyped client("…") calls missing <typeof app>, and server-only imports in routes/. `pipeline` answers "which bundler does this app run on" (bun|vite, for dev AND build alike) without starting a server, and its `pipeline` diagnostics catch the hazards of having two: a plugin in the slot the other bundler reads (accepted, then never called), a dev toolchain imported by the file `nifra build` bundles into the production server, and `conditions` that cannot reach Bun\'s dev client bundle. Read it before adding a plugin or a compiler. Pass lintsOnly:true for a near-instant lint pass while iterating; run the full gate (default) to confirm the work is done - fix every diagnostic before finishing.',
1049
- inputSchema: {
1050
- type: "object",
1051
- properties: {
1052
- lintsOnly: {
1053
- type: "boolean",
1054
- description: "Skip tsc; run only the near-instant source lints (inner-loop mode).",
1055
- },
1056
- dir: {
1057
- type: "string",
1058
- description: 'Run the check in this subdirectory (relative to the project root), e.g. "app" or "packages/api". Use it when the MCP server\'s root is a monorepo but you want to check just one app. Default: the project root.',
1059
- },
1060
- },
1061
- additionalProperties: false,
1062
- },
1063
- handler: async (args, context) => {
1064
- const { collectCheckResult } = await import("./check.js");
1065
- const opts = args;
1066
- const target = resolveProjectDir(cwd, opts.dir);
1067
- if (target === null)
1068
- return dirError(opts.dir);
1069
- const result = await collectCheckResult(target, {
1070
- lintsOnly: opts.lintsOnly ?? false,
1071
- signal: context.signal,
1072
- // Bound the result so a large project can't emit an MCP message big enough to break the stdio
1073
- // transport (`-32000: Connection closed`). If `truncated` comes back, fix the shown diagnostics
1074
- // and re-run. The scan already skips gitignored trees (walkSource), so this is the safety net.
1075
- maxDiagnostics: 100,
1076
- });
1077
- return JSON.stringify(result.structuredDiagnostics === undefined
1078
- ? result
1079
- : { ...result, diagnostics: result.structuredDiagnostics }, null, 2);
1080
- },
1081
- },
1082
- {
1083
- name: "nifra_fix",
1084
- description: "Automatically fix diagnostic lints (such as rewriting hand-rolled fetch() calls to the typed nifra client, adding generic types to client factory calls, and resolving dependency drift in package.json). Runs diagnostics, applies all mechanical edit suggestions, applies doctor dependency fixes, and returns the remaining unresolved diagnostics.",
1085
- inputSchema: {
1086
- type: "object",
1087
- properties: {
1088
- code: {
1089
- type: "string",
1090
- description: "Apply the registered recipe for one stable diagnostic code when available.",
1091
- },
1092
- },
1093
- additionalProperties: false,
1094
- },
1095
- handler: async (args, context) => {
1096
- const { collectCheckResult } = await import("./check.js");
1097
- const { applyDiagnosticRecipe } = await import("./fix-recipes.js");
1098
- const { applyDoctorAutoFix } = await import("./doctor.js");
1099
- const { resolveInsideProject } = await import("./project-path.js");
1100
- const { writeFile, readFile } = await import("node:fs/promises");
1101
- let doctorResult = null;
1102
- try {
1103
- doctorResult = await applyDoctorAutoFix(cwd);
1104
- }
1105
- catch {
1106
- // ignore doctor errors
1107
- }
1108
- const checkResult = await collectCheckResult(cwd, {
1109
- lintsOnly: true,
1110
- signal: context.signal,
1111
- maxDiagnostics: 100,
1112
- });
1113
- const requestedCode = args.code;
1114
- const recipeFixed = [];
1115
- if (typeof requestedCode === "string") {
1116
- for (const diagnostic of checkResult.structuredDiagnostics ?? []) {
1117
- if (diagnostic.code !== requestedCode)
1118
- continue;
1119
- recipeFixed.push(...(await applyDiagnosticRecipe(cwd, diagnostic)));
1120
- }
1121
- }
1122
- const fixed = [];
1123
- for (const diag of checkResult.diagnostics) {
1124
- if (diag.file && diag.line && diag.suggestion?.kind === "edit" && diag.suggestion.diff) {
1125
- try {
1126
- const diffLines = diag.suggestion.diff.split("\n");
1127
- const beforeLine = diffLines.find((l) => l.startsWith("-"))?.slice(1);
1128
- const afterLine = diffLines.find((l) => l.startsWith("+"))?.slice(1);
1129
- if (beforeLine !== undefined && afterLine !== undefined) {
1130
- const filePath = await resolveInsideProject(cwd, diag.file);
1131
- if (filePath === undefined)
1132
- continue;
1133
- const content = await readFile(filePath, "utf-8");
1134
- const lines = content.split("\n");
1135
- const idx = diag.line - 1;
1136
- if (lines[idx] === beforeLine) {
1137
- lines[idx] = afterLine;
1138
- await writeFile(filePath, lines.join("\n"), "utf-8");
1139
- fixed.push({
1140
- file: diag.file,
1141
- line: diag.line,
1142
- title: diag.suggestion.title,
1143
- });
1144
- }
1145
- }
1146
- }
1147
- catch {
1148
- // ignore edit errors
1149
- }
1150
- }
1151
- }
1152
- const finalResult = await collectCheckResult(cwd, {
1153
- lintsOnly: false,
1154
- signal: context.signal,
1155
- maxDiagnostics: 100,
1156
- });
1157
- return JSON.stringify({
1158
- ok: finalResult.ok,
1159
- fixed,
1160
- recipeFixed,
1161
- doctorFixed: doctorResult?.fixed ?? [],
1162
- remainingDiagnostics: finalResult.diagnostics,
1163
- }, null, 2);
1164
- },
1165
- },
1166
- {
1167
- name: "nifra_assure",
1168
- description: "Evaluate nifra.assurance.ts and return the complete route-assurance report: every reflected route's first matching policy rule, enforcement evidence, missing/forbidden evidence, and the fail-closed ok bit. Use after adding or changing routes/security middleware; fix every finding before finishing.",
1169
- inputSchema: {
1170
- type: "object",
1171
- properties: {
1172
- config: {
1173
- type: "string",
1174
- description: "Config path relative to the selected project directory. Default: nifra.assurance.ts.",
1175
- },
1176
- bundle: {
1177
- type: "boolean",
1178
- description: "Return the single gate bundle with verdict and explicit skipped gates.",
1179
- },
1180
- strict: {
1181
- type: "boolean",
1182
- description: "Treat warning diagnostics as failures in the bundle.",
1183
- },
1184
- hydration: {
1185
- type: "boolean",
1186
- description: "Run the hydration assurance gate.",
1187
- },
1188
- interact: {
1189
- type: "boolean",
1190
- description: "Run declared hydration probes after the client mounts.",
1191
- },
1192
- dir: {
1193
- type: "string",
1194
- description: 'Evaluate this project subdirectory (relative to the MCP root), e.g. "apps/api". Default: the project root.',
1195
- },
1196
- },
1197
- additionalProperties: false,
1198
- },
1199
- handler: async (args) => {
1200
- const opts = args;
1201
- const target = resolveProjectDir(cwd, opts.dir);
1202
- if (target === null)
1203
- return dirError(opts.dir);
1204
- const config = opts.config === undefined ? undefined : resolve(target, opts.config);
1205
- if (config !== undefined && config !== target && !config.startsWith(target + sep)) {
1206
- return JSON.stringify({ ok: false, error: "config must stay inside the selected project directory" }, null, 2);
1207
- }
1208
- const { collectAssuranceReport, collectAssureBundle } = await import("./assure.js");
1209
- if (opts.bundle === true || opts.strict === true || opts.hydration === true) {
1210
- return JSON.stringify(await collectAssureBundle(target, {
1211
- ...(config === undefined ? {} : { config }),
1212
- ...(opts.strict === undefined ? {} : { strict: opts.strict }),
1213
- ...(opts.hydration === undefined ? {} : { hydration: opts.hydration }),
1214
- ...(opts.interact === undefined ? {} : { interact: opts.interact }),
1215
- }), null, 2);
1216
- }
1217
- return JSON.stringify(await collectAssuranceReport(target, config), null, 2);
1218
- },
1219
- },
1220
1074
  {
1221
1075
  name: "nifra_hydrate",
1222
1076
  description: "Run the hydration assurance gate and return stable NF-H diagnostics.",
@@ -1237,90 +1091,8 @@ export function projectTools(cwd, loadAppCached = createCachedAppLoader(cwd)) {
1237
1091
  return JSON.stringify(await runHydrationAssurance(target, { interact: opts.interact === true }), null, 2);
1238
1092
  },
1239
1093
  },
1240
- {
1241
- name: "nifra_replay",
1242
- description: "Validate and dispatch a token-only replay metadata file.",
1243
- inputSchema: {
1244
- type: "object",
1245
- properties: {
1246
- file: { type: "string", description: "Replay file relative to the project root." },
1247
- },
1248
- required: ["file"],
1249
- additionalProperties: false,
1250
- },
1251
- handler: async (args) => {
1252
- const file = args.file;
1253
- if (typeof file !== "string" || file.trim() === "")
1254
- return JSON.stringify({ ok: false, error: "file is required" });
1255
- const { runReplay } = await import("./replay.js");
1256
- try {
1257
- return JSON.stringify(await runReplay(cwd, file), null, 2);
1258
- }
1259
- catch (error) {
1260
- return JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) }, null, 2);
1261
- }
1262
- },
1263
- },
1264
- {
1265
- name: "nifra_levels",
1266
- description: "Compute this project's verification ladder and return { achieved, levels[] }, where each level carries { level, name, ok, reasons[] }. The ladder is cumulative: L0 typed contract (nifra check), L1 route assurance, L2 reviewed capability lockfile, L3 route trust manifest in sync, L4 contract invariants, so a level only holds when every level below it holds, and `achieved` is -1 when even L0 fails. This is the single gate that reports what a change actually proves: run it after finishing work, and treat any `reasons` on a level the project already claimed as a regression to fix.",
1267
- inputSchema: {
1268
- type: "object",
1269
- properties: {
1270
- config: {
1271
- type: "string",
1272
- description: "Assurance config path relative to the selected project directory. Default: nifra.assurance.ts.",
1273
- },
1274
- seed: {
1275
- type: "number",
1276
- description: "Deterministic seed for the L4 invariant run. Default 1.",
1277
- },
1278
- dir: {
1279
- type: "string",
1280
- description: 'Evaluate this project subdirectory (relative to the MCP root), e.g. "apps/api". Default: the project root.',
1281
- },
1282
- },
1283
- additionalProperties: false,
1284
- },
1285
- handler: async (args) => {
1286
- const opts = args;
1287
- const target = resolveProjectDir(cwd, opts.dir);
1288
- if (target === null)
1289
- return dirError(opts.dir);
1290
- if (opts.seed !== undefined && !Number.isSafeInteger(opts.seed)) {
1291
- return JSON.stringify({ ok: false, error: "seed must be a safe integer" }, null, 2);
1292
- }
1293
- const config = opts.config === undefined ? undefined : resolve(target, opts.config);
1294
- if (config !== undefined && config !== target && !config.startsWith(target + sep)) {
1295
- return JSON.stringify({ ok: false, error: "config must stay inside the selected project directory" }, null, 2);
1296
- }
1297
- const { collectVerificationLevels } = await import("./levels-tool.js");
1298
- return JSON.stringify(await collectVerificationLevels(target, {
1299
- ...(opts.config === undefined ? {} : { config: opts.config }),
1300
- ...(opts.seed === undefined ? {} : { seed: opts.seed }),
1301
- }), null, 2);
1302
- },
1303
- },
1304
- {
1305
- name: "nifra_doctor",
1306
- description: "Check this project for packages imported in source but NOT declared in package.json - the Bun-workspace trap where an import resolves at runtime (hoisting/workspace) so tests pass and `bun install` says no changes, yet tsc fails and a fresh/standalone install can't resolve it. Also reports `pipeline`: which bundler (bun|vite) this app's dev AND build phases run on and why, plus config hazards that only exist because there are two - a plugin sitting in the slot the other bundler reads (accepted, then never called), a dev toolchain imported by the file `nifra build` bundles into the production server (builds clean, dies at startup), and `conditions` that cannot reach the client bundle Bun's dev server serves. Returns { ok, ran, findings[], pipeline?, fixed?, skippedFixes? }. Pass autoFix:true to update package.json only when the dependency version can be inferred locally from an ancestor package.json or installed package metadata; otherwise the tool returns the exact bun add command to run.",
1307
- inputSchema: {
1308
- type: "object",
1309
- properties: {
1310
- autoFix: {
1311
- type: "boolean",
1312
- description: "When true, write safe package.json fixes using only locally inferred versions. Does not run install or use the network.",
1313
- },
1314
- },
1315
- additionalProperties: false,
1316
- },
1317
- handler: async (args) => {
1318
- const opts = args;
1319
- const { applyDoctorAutoFix, collectDoctorResult } = await import("./doctor.js");
1320
- return JSON.stringify(opts.autoFix === true ? await applyDoctorAutoFix(cwd) : await collectDoctorResult(cwd), null, 2);
1321
- },
1322
- },
1323
1094
  ];
1095
+ return [...catalogTools, ...legacyTools];
1324
1096
  }
1325
1097
  /** Extract tools registered via .tool() routes on the Nifra backend. Exported for the test that proves a
1326
1098
  * `server().tool()` route surfaces in `tools/list` and executes through `tools/call`. */