@nifrajs/cli 3.1.0 → 3.2.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 (158) hide show
  1. package/README.md +10 -0
  2. package/dist/assure-hydration.d.ts.map +1 -1
  3. package/dist/assure-hydration.js +6 -1
  4. package/dist/assure-hydration.js.map +1 -1
  5. package/dist/assure.d.ts.map +1 -1
  6. package/dist/assure.js +3 -2
  7. package/dist/assure.js.map +1 -1
  8. package/dist/check-diagnostics.d.ts +165 -0
  9. package/dist/check-diagnostics.d.ts.map +1 -0
  10. package/dist/check-diagnostics.js +1009 -0
  11. package/dist/check-diagnostics.js.map +1 -0
  12. package/dist/check-scan.d.ts +245 -0
  13. package/dist/check-scan.d.ts.map +1 -0
  14. package/dist/check-scan.js +1599 -0
  15. package/dist/check-scan.js.map +1 -0
  16. package/dist/check.d.ts +4 -324
  17. package/dist/check.d.ts.map +1 -1
  18. package/dist/check.js +8 -2366
  19. package/dist/check.js.map +1 -1
  20. package/dist/cli.d.ts.map +1 -1
  21. package/dist/cli.js +247 -10
  22. package/dist/cli.js.map +1 -1
  23. package/dist/command-catalog.d.ts +21 -1
  24. package/dist/command-catalog.d.ts.map +1 -1
  25. package/dist/command-catalog.js +122 -0
  26. package/dist/command-catalog.js.map +1 -1
  27. package/dist/env-file.js +5 -5
  28. package/dist/env-file.js.map +1 -1
  29. package/dist/frontend-guidance.d.ts +57 -0
  30. package/dist/frontend-guidance.d.ts.map +1 -0
  31. package/dist/frontend-guidance.js +195 -0
  32. package/dist/frontend-guidance.js.map +1 -0
  33. package/dist/levels-tool.d.ts.map +1 -1
  34. package/dist/levels-tool.js +6 -0
  35. package/dist/levels-tool.js.map +1 -1
  36. package/dist/load.d.ts.map +1 -1
  37. package/dist/load.js +4 -1
  38. package/dist/load.js.map +1 -1
  39. package/dist/mcp-context.d.ts +48 -0
  40. package/dist/mcp-context.d.ts.map +1 -0
  41. package/dist/mcp-context.js +215 -0
  42. package/dist/mcp-context.js.map +1 -0
  43. package/dist/mcp-docs-tools.d.ts.map +1 -1
  44. package/dist/mcp-docs-tools.js +31 -0
  45. package/dist/mcp-docs-tools.js.map +1 -1
  46. package/dist/mcp-exec.d.ts +74 -0
  47. package/dist/mcp-exec.d.ts.map +1 -0
  48. package/dist/mcp-exec.js +844 -0
  49. package/dist/mcp-exec.js.map +1 -0
  50. package/dist/mcp-http.js +1 -1
  51. package/dist/mcp-io.d.ts +26 -0
  52. package/dist/mcp-io.d.ts.map +1 -0
  53. package/dist/mcp-io.js +100 -0
  54. package/dist/mcp-io.js.map +1 -0
  55. package/dist/mcp-reflect.d.ts +16 -0
  56. package/dist/mcp-reflect.d.ts.map +1 -0
  57. package/dist/mcp-reflect.js +101 -0
  58. package/dist/mcp-reflect.js.map +1 -0
  59. package/dist/mcp-root.d.ts +7 -0
  60. package/dist/mcp-root.d.ts.map +1 -1
  61. package/dist/mcp-root.js +51 -3
  62. package/dist/mcp-root.js.map +1 -1
  63. package/dist/mcp.d.ts +10 -92
  64. package/dist/mcp.d.ts.map +1 -1
  65. package/dist/mcp.js +13 -1232
  66. package/dist/mcp.js.map +1 -1
  67. package/dist/openapi-tool.d.ts +5 -10
  68. package/dist/openapi-tool.d.ts.map +1 -1
  69. package/dist/openapi-tool.js +21 -2
  70. package/dist/openapi-tool.js.map +1 -1
  71. package/dist/openapi-types.d.ts +21 -0
  72. package/dist/openapi-types.d.ts.map +1 -0
  73. package/dist/openapi-types.js +214 -0
  74. package/dist/openapi-types.js.map +1 -0
  75. package/dist/port.d.ts.map +1 -1
  76. package/dist/port.js +2 -1
  77. package/dist/port.js.map +1 -1
  78. package/dist/project-facts.d.ts +2 -1
  79. package/dist/project-facts.d.ts.map +1 -1
  80. package/dist/project-facts.js.map +1 -1
  81. package/dist/release-verification.d.ts +4 -1
  82. package/dist/release-verification.d.ts.map +1 -1
  83. package/dist/release-verification.js +6 -138
  84. package/dist/release-verification.js.map +1 -1
  85. package/dist/rules/codes.d.ts +4 -0
  86. package/dist/rules/codes.d.ts.map +1 -1
  87. package/dist/rules/codes.js +4 -0
  88. package/dist/rules/codes.js.map +1 -1
  89. package/dist/rules/islands.d.ts +4 -0
  90. package/dist/rules/islands.d.ts.map +1 -0
  91. package/dist/rules/islands.js +155 -0
  92. package/dist/rules/islands.js.map +1 -0
  93. package/dist/rules/nano.d.ts +6 -0
  94. package/dist/rules/nano.d.ts.map +1 -0
  95. package/dist/rules/nano.js +264 -0
  96. package/dist/rules/nano.js.map +1 -0
  97. package/dist/rules/security.d.ts.map +1 -1
  98. package/dist/rules/security.js +38 -4
  99. package/dist/rules/security.js.map +1 -1
  100. package/dist/scaffold.d.ts +12 -6
  101. package/dist/scaffold.d.ts.map +1 -1
  102. package/dist/scaffold.js +149 -10
  103. package/dist/scaffold.js.map +1 -1
  104. package/dist/search-terms.d.ts.map +1 -1
  105. package/dist/search-terms.js +5 -3
  106. package/dist/search-terms.js.map +1 -1
  107. package/dist/stylex-migrate.d.ts +38 -0
  108. package/dist/stylex-migrate.d.ts.map +1 -0
  109. package/dist/stylex-migrate.js +1052 -0
  110. package/dist/stylex-migrate.js.map +1 -0
  111. package/dist/sync-manifest.d.ts.map +1 -1
  112. package/dist/sync-manifest.js +2 -1
  113. package/dist/sync-manifest.js.map +1 -1
  114. package/dist/verification-plan.d.ts +24 -0
  115. package/dist/verification-plan.d.ts.map +1 -0
  116. package/dist/verification-plan.js +116 -0
  117. package/dist/verification-plan.js.map +1 -0
  118. package/dist/work-graph.d.ts.map +1 -1
  119. package/dist/work-graph.js +6 -3
  120. package/dist/work-graph.js.map +1 -1
  121. package/docs/examples.json +36 -0
  122. package/docs/llms-full.txt +1226 -14
  123. package/docs/types.json +4185 -87
  124. package/package.json +9 -9
  125. package/src/assure-hydration.ts +6 -1
  126. package/src/assure.ts +4 -2
  127. package/src/check-diagnostics.ts +1219 -0
  128. package/src/check-scan.ts +1825 -0
  129. package/src/check.ts +47 -2752
  130. package/src/cli.ts +252 -10
  131. package/src/command-catalog.ts +155 -0
  132. package/src/env-file.ts +5 -5
  133. package/src/frontend-guidance.ts +259 -0
  134. package/src/levels-tool.ts +6 -0
  135. package/src/load.ts +4 -1
  136. package/src/mcp-context.ts +266 -0
  137. package/src/mcp-docs-tools.ts +37 -0
  138. package/src/mcp-exec.ts +1040 -0
  139. package/src/mcp-http.ts +1 -1
  140. package/src/mcp-io.ts +118 -0
  141. package/src/mcp-reflect.ts +140 -0
  142. package/src/mcp-root.ts +62 -4
  143. package/src/mcp.ts +61 -1511
  144. package/src/openapi-tool.ts +32 -2
  145. package/src/openapi-types.ts +261 -0
  146. package/src/port.ts +2 -1
  147. package/src/project-facts.ts +2 -4
  148. package/src/release-verification.ts +22 -164
  149. package/src/rules/codes.ts +4 -0
  150. package/src/rules/islands.ts +171 -0
  151. package/src/rules/nano.ts +295 -0
  152. package/src/rules/security.ts +40 -4
  153. package/src/scaffold.ts +169 -9
  154. package/src/search-terms.ts +7 -3
  155. package/src/stylex-migrate.ts +1139 -0
  156. package/src/sync-manifest.ts +2 -1
  157. package/src/verification-plan.ts +242 -0
  158. package/src/work-graph.ts +6 -3
@@ -0,0 +1,1009 @@
1
+ /**
2
+ * Diagnostic model and projections for the nifra verification pipeline.
3
+ *
4
+ * Scanners publish frozen facts; this module turns those facts plus policy into the stable legacy and
5
+ * structured diagnostic views. The CLI, JSON output, and MCP all consume the resulting CheckResult.
6
+ */
7
+ import { existsSync } from "node:fs";
8
+ import { join, resolve } from "node:path";
9
+ import { snapshotProjectEvidence } from "@nifrajs/core/evidence";
10
+ import { SINGLE_COPY_REGISTER_SPECIFIER } from "@nifrajs/core/single-copy";
11
+ import { IDENT, parseSimpleFetchCall, REMOVED_IMPORTS, SIMPLE_REWRITE_METHODS, } from "./check-scan.js";
12
+ import { diagnostic } from "./diagnostics.js";
13
+ import { freezeProjectFacts } from "./project-facts.js";
14
+ import { parseRulePacks, runRuleRegistry } from "./rules/index.js";
15
+ import { islandRules } from "./rules/islands.js";
16
+ import { LEGACY_RULE_CODES, legacyRules } from "./rules/legacy.js";
17
+ import { nanoRules } from "./rules/nano.js";
18
+ import { routeRules } from "./rules/routes.js";
19
+ import { securityRules } from "./rules/security.js";
20
+ const TSC_LINE = /^(.+?)\((\d+),\d+\):\s*(?:error|warning)\s+TS\d+:\s*(.+)$/;
21
+ const MAX_IGNORE_GLOB_LENGTH = 4096;
22
+ const MAX_IGNORE_GLOB_ALTERNATIVES = 64;
23
+ /**
24
+ * Match the small file-glob language used by check overrides without compiling user input into a
25
+ * regular expression. `nifra.check.json` is commonly supplied by a project or CI wrapper, so an
26
+ * attacker who can influence it must not be able to turn a diagnostic filter into a ReDoS input.
27
+ * The matcher supports the portable glob forms users expect here: `*`, `?`, `**`, character
28
+ * classes, and brace alternatives.
29
+ */
30
+ function safeIgnoreGlobMatch(pattern, file) {
31
+ if (pattern.length === 0 || pattern.length > MAX_IGNORE_GLOB_LENGTH)
32
+ return false;
33
+ for (const alternative of expandIgnoreGlobBraces(pattern)) {
34
+ if (matchIgnoreGlobPath(alternative, file))
35
+ return true;
36
+ }
37
+ return false;
38
+ }
39
+ function expandIgnoreGlobBraces(pattern) {
40
+ const open = firstUnescaped(pattern, "{");
41
+ if (open === -1)
42
+ return [pattern];
43
+ const close = matchingBrace(pattern, open);
44
+ if (close === -1)
45
+ return [pattern];
46
+ const choices = splitBraceChoices(pattern.slice(open + 1, close));
47
+ if (choices.length < 2)
48
+ return [pattern];
49
+ const expanded = [];
50
+ for (const choice of choices) {
51
+ const prefix = pattern.slice(0, open) + choice + pattern.slice(close + 1);
52
+ for (const nested of expandIgnoreGlobBraces(prefix)) {
53
+ expanded.push(nested);
54
+ if (expanded.length >= MAX_IGNORE_GLOB_ALTERNATIVES)
55
+ return expanded;
56
+ }
57
+ }
58
+ return expanded;
59
+ }
60
+ function firstUnescaped(value, needle) {
61
+ let escaped = false;
62
+ for (let index = 0; index < value.length; index++) {
63
+ const char = value[index];
64
+ if (escaped) {
65
+ escaped = false;
66
+ continue;
67
+ }
68
+ if (char === "\\") {
69
+ escaped = true;
70
+ continue;
71
+ }
72
+ if (char === needle)
73
+ return index;
74
+ }
75
+ return -1;
76
+ }
77
+ function matchingBrace(value, open) {
78
+ let depth = 0;
79
+ let escaped = false;
80
+ for (let index = open; index < value.length; index++) {
81
+ const char = value[index];
82
+ if (escaped) {
83
+ escaped = false;
84
+ continue;
85
+ }
86
+ if (char === "\\") {
87
+ escaped = true;
88
+ continue;
89
+ }
90
+ if (char === "{")
91
+ depth++;
92
+ else if (char === "}" && --depth === 0)
93
+ return index;
94
+ }
95
+ return -1;
96
+ }
97
+ function splitBraceChoices(value) {
98
+ const choices = [];
99
+ let start = 0;
100
+ let depth = 0;
101
+ let escaped = false;
102
+ for (let index = 0; index < value.length; index++) {
103
+ const char = value[index];
104
+ if (escaped) {
105
+ escaped = false;
106
+ continue;
107
+ }
108
+ if (char === "\\") {
109
+ escaped = true;
110
+ continue;
111
+ }
112
+ if (char === "{")
113
+ depth++;
114
+ else if (char === "}")
115
+ depth--;
116
+ else if (char === "," && depth === 0) {
117
+ choices.push(value.slice(start, index));
118
+ start = index + 1;
119
+ }
120
+ }
121
+ choices.push(value.slice(start));
122
+ return choices;
123
+ }
124
+ function matchIgnoreGlobPath(pattern, file) {
125
+ const patternParts = pattern.split("/");
126
+ const fileParts = file.split("/");
127
+ let reachable = new Array(fileParts.length + 1).fill(false);
128
+ reachable[0] = true;
129
+ for (const part of patternParts) {
130
+ const next = new Array(fileParts.length + 1).fill(false);
131
+ if (part === "**") {
132
+ let canReach = false;
133
+ for (let index = 0; index <= fileParts.length; index++) {
134
+ canReach ||= reachable[index] === true;
135
+ next[index] = canReach;
136
+ }
137
+ }
138
+ else {
139
+ for (let index = 0; index < fileParts.length; index++) {
140
+ if (reachable[index] && matchIgnoreGlobPart(part, fileParts[index]))
141
+ next[index + 1] = true;
142
+ }
143
+ }
144
+ reachable = next;
145
+ }
146
+ return reachable[fileParts.length] === true;
147
+ }
148
+ function matchIgnoreGlobPart(pattern, value) {
149
+ let previous = new Array(value.length + 1).fill(false);
150
+ previous[0] = true;
151
+ for (let patternIndex = 0; patternIndex < pattern.length; patternIndex++) {
152
+ const char = pattern[patternIndex];
153
+ const next = new Array(value.length + 1).fill(false);
154
+ if (char === "*") {
155
+ next[0] = previous[0] === true;
156
+ for (let valueIndex = 1; valueIndex <= value.length; valueIndex++)
157
+ next[valueIndex] = previous[valueIndex] === true || next[valueIndex - 1] === true;
158
+ }
159
+ else if (char === "?") {
160
+ for (let valueIndex = 1; valueIndex <= value.length; valueIndex++)
161
+ next[valueIndex] = previous[valueIndex - 1] === true;
162
+ }
163
+ else if (char === "\\" && patternIndex + 1 < pattern.length) {
164
+ const literal = pattern[++patternIndex];
165
+ for (let valueIndex = 1; valueIndex <= value.length; valueIndex++)
166
+ next[valueIndex] = previous[valueIndex - 1] === true && value[valueIndex - 1] === literal;
167
+ }
168
+ else if (char === "[") {
169
+ const classEnd = ignoreGlobClassEnd(pattern, patternIndex + 1);
170
+ if (classEnd === -1)
171
+ return matchIgnoreGlobPart(`\\[${pattern.slice(patternIndex + 1)}`, value);
172
+ for (let valueIndex = 1; valueIndex <= value.length; valueIndex++)
173
+ next[valueIndex] =
174
+ previous[valueIndex - 1] === true &&
175
+ matchIgnoreGlobClass(pattern.slice(patternIndex + 1, classEnd), value[valueIndex - 1]);
176
+ patternIndex = classEnd;
177
+ }
178
+ else {
179
+ for (let valueIndex = 1; valueIndex <= value.length; valueIndex++)
180
+ next[valueIndex] = previous[valueIndex - 1] === true && value[valueIndex - 1] === char;
181
+ }
182
+ previous = next;
183
+ }
184
+ return previous[value.length] === true;
185
+ }
186
+ function ignoreGlobClassEnd(pattern, start) {
187
+ for (let index = start; index < pattern.length; index++) {
188
+ if (pattern[index] === "]" && index > start)
189
+ return index;
190
+ }
191
+ return -1;
192
+ }
193
+ function matchIgnoreGlobClass(spec, value) {
194
+ let index = 0;
195
+ let negated = false;
196
+ if (spec[0] === "!" || spec[0] === "^") {
197
+ negated = true;
198
+ index++;
199
+ }
200
+ let matched = false;
201
+ while (index < spec.length) {
202
+ const first = spec[index] === "\\" ? spec[++index] : spec[index];
203
+ if (first === undefined)
204
+ break;
205
+ index++;
206
+ if (spec[index] === "-" && index + 1 < spec.length) {
207
+ index++;
208
+ const last = spec[index] === "\\" ? spec[++index] : spec[index];
209
+ if (last !== undefined && first <= value && value <= last)
210
+ matched = true;
211
+ index++;
212
+ }
213
+ else if (value === first) {
214
+ matched = true;
215
+ }
216
+ }
217
+ return negated ? !matched : matched;
218
+ }
219
+ const UNTYPED_CLIENT_HINT = 'client("…") without a type argument - write client<typeof app>("…") (or client(contract, url)) so the compiler can catch drift';
220
+ const FETCH_HINT = "hand-rolled fetch() to your own API - call it through client<typeof app> (from @nifrajs/client) so the compiler catches drift";
221
+ const SERVER_IMPORT_HINT = "server-only import in a route module (bundled for the browser) - reach it via c.db / ctx.api inside a loader, never a top-level import";
222
+ const RESPONSE_ROUTE_HINT = "route handler returns a raw Response - the typed client infers `data: never`, so drift detection is lost for this route. Return a plain object (it's serialized for you); for a stream use a typed SSE route (`app.sse(...)`), which keeps typed events; or, if a raw Response is intended (file/redirect), add `{ response: t.… }` or a `// nifra-expect raw-response` comment to mark it and silence this";
223
+ const PIPELINE_DOC_HINT = "nifra runs one bundler per phase - `vitePlugins` feed Vite, `clientPlugins`/`serverPlugins` feed Bun, and the file `nifra build` imports the adapter from is bundled into the server. See the Gotchas section of the Dev & HMR guide.";
224
+ const UNDECLARED_DEP_HINT = "imported package is not declared in package.json dependencies - run bun add to declare it";
225
+ const SQL_COMPILER_MISSING_HINT = "the interpolated-SQL rule did NOT run - it parses source with the TypeScript compiler, which is an optional peer and is not installed here. This report says nothing about SQL injection either way. Install it with `bun add -d typescript`";
226
+ const SQL_INTERPOLATION_EXAMPLE = "$" + "{value}";
227
+ const INTERPOLATED_SQL_HINT = `SQL built by interpolating a value into the statement text - the value becomes statement, not a parameter, so anything the caller controls can end the literal and continue as SQL. Pass it as a bound parameter (\`?\` / \`$1\` and an argument), or use your driver's tagged template (sql\`… ${SQL_INTERPOLATION_EXAMPLE} …\`), which binds the substitutions for you`;
228
+ const MANIFEST_DRIFT_HINT = "server-manifest.ts is out of sync with routes/ - re-run the build to regenerate it (a disk-less worker bakes this route table, so the drift is a silent edge break), then commit it";
229
+ const TRUST_MANIFEST_DRIFT_HINT = "nifra.manifest.json is missing, invalid, or out of sync - run `nifra manifest emit`, review it, and commit the regenerated trust artifact";
230
+ const CAPABILITY_HINT = "effect/capability assurance failed - align the route declaration with approved adapter provenance; never bypass an owned effect seam";
231
+ const bySite = (a, b) => a.file.localeCompare(b.file) || a.line - b.line;
232
+ function oneLineDiff(file, line, before, after) {
233
+ return `--- ${file}:${line}\n+++ ${file}:${line}\n@@\n-${before}\n+${after}`;
234
+ }
235
+ function untypedClientSuggestion(f) {
236
+ const replacement = f.snippet.replace(/(?<![.\w])client\s*\(/, "client<typeof app>(");
237
+ return replacement === f.snippet
238
+ ? {
239
+ kind: "manual",
240
+ title: "Add the app type argument to the client factory",
241
+ steps: [
242
+ 'Change `client("...")` to `client<typeof app>("...")`.',
243
+ "Make sure the backend app type is imported or otherwise in scope.",
244
+ ],
245
+ }
246
+ : {
247
+ kind: "edit",
248
+ title: "Insert `<typeof app>` into the client factory call",
249
+ diff: oneLineDiff(f.file, f.line, f.snippet, replacement),
250
+ steps: ["Make sure the backend app type is imported or otherwise in scope."],
251
+ };
252
+ }
253
+ function routeKey(method, path) {
254
+ return `${method.toUpperCase()} ${path}`;
255
+ }
256
+ function typedClientCall(method, path) {
257
+ const segs = path.split("/").filter((seg) => seg !== "");
258
+ let chain = "api";
259
+ if (segs.length === 0)
260
+ chain += ".index";
261
+ else {
262
+ for (const seg of segs) {
263
+ chain += IDENT.test(seg) ? `.${seg}` : `[${JSON.stringify(seg)}]`;
264
+ }
265
+ }
266
+ return `${chain}.${method.toLowerCase()}()`;
267
+ }
268
+ function staticRouteMap(routes) {
269
+ const out = new Map();
270
+ for (const route of routes) {
271
+ if (route.path.includes(":") || route.path.includes("*"))
272
+ continue;
273
+ const key = routeKey(route.method, route.path);
274
+ const bucket = out.get(key);
275
+ if (bucket === undefined)
276
+ out.set(key, [route]);
277
+ else
278
+ bucket.push(route);
279
+ }
280
+ return out;
281
+ }
282
+ function ownFetchEditSuggestion(f, routes) {
283
+ const call = parseSimpleFetchCall(f.snippet);
284
+ if (call === undefined || !SIMPLE_REWRITE_METHODS.has(call.method))
285
+ return undefined;
286
+ const matches = routes.get(routeKey(call.method, call.path));
287
+ if (matches === undefined || matches.length !== 1)
288
+ return undefined;
289
+ const replacementCall = typedClientCall(call.method, call.path);
290
+ const replacement = `${f.snippet.slice(0, call.start)}${replacementCall}${f.snippet.slice(call.end)}`;
291
+ if (replacement === f.snippet)
292
+ return undefined;
293
+ const route = matches[0];
294
+ if (route === undefined)
295
+ return undefined;
296
+ return {
297
+ kind: "edit",
298
+ title: "Rewrite simple own-API fetch to the typed nifra client",
299
+ diff: oneLineDiff(f.file, f.line, f.snippet, replacement),
300
+ steps: [
301
+ `Matched ${route.method} ${route.path} at ${route.file}:${route.line}.`,
302
+ "Use an in-scope typed client named `api` (`client<typeof app>(baseUrl)` or the route loader/action `api`).",
303
+ "Update downstream `Response` handling to branch on `{ ok, data, error }` if this variable is used later.",
304
+ ],
305
+ };
306
+ }
307
+ function ownFetchSuggestion(f, routes) {
308
+ const exact = ownFetchEditSuggestion(f, routes);
309
+ if (exact !== undefined)
310
+ return exact;
311
+ return {
312
+ kind: "manual",
313
+ title: "Replace own-API fetch with the typed nifra client",
314
+ steps: [
315
+ "Call `nifra_routes` or read `nifra://routes` for the exact typed-client call form.",
316
+ "Create `const api = client<typeof app>(baseUrl)` from `@nifrajs/client`.",
317
+ "Replace the relative `fetch()` call with the generated `api...get/post/...` call and branch on `{ ok, data, error }`.",
318
+ ],
319
+ };
320
+ }
321
+ function serverImportSuggestion(specifier, chain, fallback) {
322
+ const sink = chain[chain.length - 1] ?? specifier;
323
+ // Surface the resolved chain in the fix steps so the agent sees the full path (`route → ../data →
324
+ // ../db → node:crypto`) and which module to cut - not just the route's own top-level import.
325
+ const chainStep = chain.length > 2
326
+ ? fallback
327
+ ? `Server-only code reaches this route through \`${chain.join(" → ")}\` (the deeper chain couldn't be resolved precisely - trace it from \`${specifier}\`).`
328
+ : `Server-only code reaches this route transitively: \`${chain.join(" → ")}\`. The sink is \`${sink}\`; break the chain at the first hop (\`${specifier}\`) or move the sink behind the server boundary.`
329
+ : undefined;
330
+ return {
331
+ kind: "manual",
332
+ title: "Move server-only code behind the route server boundary",
333
+ steps: [
334
+ ...(chainStep !== undefined ? [chainStep] : []),
335
+ `Remove the top-level \`import … from "${specifier}"\` from this route module (it's bundled for the browser).`,
336
+ "Access backend/data work through the route `loader`/`action` context (`api`, `env`, or project server context).",
337
+ `If a direct module import is unavoidable, lazy-load it (\`await import("${specifier}")\`) inside the server-only loader/action path.`,
338
+ ],
339
+ };
340
+ }
341
+ function responseRouteSuggestion() {
342
+ return {
343
+ kind: "manual",
344
+ title: "Preserve typed-client response inference",
345
+ steps: [
346
+ "Prefer returning a plain object from JSON routes; nifra serializes it for you.",
347
+ "For a stream, use a typed SSE route - `app.sse(...)` (or `sse(c, run)` from `@nifrajs/core/server`) - which keeps typed events instead of collapsing the client to `data: never`.",
348
+ "If this route must return a raw Response (redirect, file), declare an explicit response schema, or add a `// nifra-expect raw-response` comment above the return to mark it intentional and silence this advisory.",
349
+ ],
350
+ };
351
+ }
352
+ export async function collectCheckDiagnostics(cwd, scan, opts = {}) {
353
+ const factsSeed = scan.facts;
354
+ const { fetches, untypedClients, removedImports, responseRoutes, interpolatedSql } = factsSeed.sourceFindings;
355
+ const staticRoutes = factsSeed.routes;
356
+ const serverImports = factsSeed.importGraph;
357
+ const { doctor: dr, manifestDrift } = factsSeed.packages;
358
+ const { checkConfig } = factsSeed.policies;
359
+ const tc = scan.typecheck;
360
+ const sqlCompiler = scan.sqlCompiler;
361
+ const checkConfigError = scan.checkConfigError;
362
+ const checkConfigWarnings = scan.checkConfigWarnings;
363
+ const diagnostics = [];
364
+ const structuredExtras = [];
365
+ if (checkConfigError !== undefined) {
366
+ diagnostics.push({
367
+ rule: "check-config",
368
+ severity: "warning",
369
+ file: "nifra.check.json",
370
+ message: `nifra.check.json could not be parsed (${checkConfigError}) - its external-mount allowlist was ignored`,
371
+ fix: "Fix the JSON syntax in nifra.check.json",
372
+ });
373
+ }
374
+ for (const warning of checkConfigWarnings) {
375
+ diagnostics.push({
376
+ rule: "check-config",
377
+ severity: "warning",
378
+ file: "nifra.check.json",
379
+ message: `nifra.check.json: ${warning}`,
380
+ fix: "Fix the entry in nifra.check.json",
381
+ });
382
+ }
383
+ if (tc.missingTypeScript === true) {
384
+ // A tsconfig with no reachable `typescript` install is a broken gate, not a benign skip: the
385
+ // contract check the project asked for (by having a tsconfig) silently didn't run. Fail closed.
386
+ diagnostics.push({
387
+ rule: "typecheck",
388
+ severity: "error",
389
+ file: "tsconfig.json",
390
+ message: "tsconfig.json is present but no `typescript` install was found from this directory upward - the typecheck gate did NOT run",
391
+ fix: "bun add -d typescript",
392
+ suggestion: {
393
+ kind: "command",
394
+ title: "Install TypeScript so the contract gate can run",
395
+ command: ["bun", "add", "-d", "typescript"],
396
+ },
397
+ });
398
+ }
399
+ if (tc.ran && !tc.ok) {
400
+ const lines = (tc.output ?? "").split("\n");
401
+ let matched = false;
402
+ for (const l of lines) {
403
+ const m = TSC_LINE.exec(l.trim());
404
+ if (m) {
405
+ matched = true;
406
+ diagnostics.push({
407
+ rule: "typecheck",
408
+ severity: "error",
409
+ file: m[1],
410
+ line: Number(m[2]),
411
+ message: m[3],
412
+ suggestion: {
413
+ kind: "manual",
414
+ title: "Fix the TypeScript contract error",
415
+ steps: [
416
+ "Open the reported file and line.",
417
+ "Align the handler, route schema, or typed-client call with the compiler error.",
418
+ "Run `nifra_check` again after the edit.",
419
+ ],
420
+ },
421
+ });
422
+ }
423
+ }
424
+ if (!matched)
425
+ diagnostics.push({
426
+ rule: "typecheck",
427
+ severity: "error",
428
+ message: tc.output || "typecheck failed",
429
+ suggestion: {
430
+ kind: "manual",
431
+ title: "Fix the TypeScript contract error",
432
+ steps: ["Run `tsc --noEmit` locally for the full compiler output."],
433
+ },
434
+ });
435
+ }
436
+ const routes = staticRouteMap(staticRoutes);
437
+ for (const f of [...fetches].sort(bySite)) {
438
+ diagnostics.push({
439
+ rule: "typed-client",
440
+ severity: "error",
441
+ file: f.file,
442
+ line: f.line,
443
+ message: `${f.snippet} - ${FETCH_HINT}`,
444
+ fix: FETCH_HINT,
445
+ suggestion: ownFetchSuggestion(f, routes),
446
+ });
447
+ }
448
+ for (const f of [...removedImports].sort(bySite)) {
449
+ const entry = REMOVED_IMPORTS.find((candidate) => f.snippet.includes(`"${candidate.specifier}`) ||
450
+ f.snippet.includes(`'${candidate.specifier}`));
451
+ diagnostics.push({
452
+ rule: "removed-import",
453
+ severity: "error",
454
+ file: f.file,
455
+ line: f.line,
456
+ message: `${f.snippet} - removed in nifra ${entry?.since ?? "2.0"}: ${entry?.replacement ?? "see the changelog"}`,
457
+ fix: entry?.replacement ?? "see the changelog",
458
+ });
459
+ }
460
+ for (const f of [...untypedClients].sort(bySite)) {
461
+ diagnostics.push({
462
+ rule: "untyped-client",
463
+ severity: "error",
464
+ file: f.file,
465
+ line: f.line,
466
+ message: `${f.snippet} - ${UNTYPED_CLIENT_HINT}`,
467
+ fix: UNTYPED_CLIENT_HINT,
468
+ suggestion: untypedClientSuggestion(f),
469
+ });
470
+ }
471
+ for (const f of [...serverImports].sort(bySite)) {
472
+ // #4.4: the FULL transitive chain the import-resolution walk found - `route → ../data → ../db →
473
+ // node:crypto`, matching the build leak-guard's depth - instead of just the direct edge. The chain's
474
+ // tail is the actual server-only sink; the head is the route. When a precise resolve wasn't possible
475
+ // (a bare pkg / path alias), `fallback` is set and the chain degrades to the honest direct edge.
476
+ const chain = f.chain;
477
+ const sink = chain[chain.length - 1] ?? f.specifier;
478
+ diagnostics.push({
479
+ rule: "server-only-import",
480
+ severity: "error",
481
+ file: f.file,
482
+ line: f.line,
483
+ message: `${f.snippet} - server-only "${sink}" reaches the browser bundle via ${chain.join(" → ")}${f.fallback ? " (direct edge - couldn't resolve the transitive chain precisely)" : ""}; ${SERVER_IMPORT_HINT}`,
484
+ fix: SERVER_IMPORT_HINT,
485
+ chain,
486
+ suggestion: serverImportSuggestion(f.specifier, chain, f.fallback),
487
+ });
488
+ }
489
+ if (sqlCompiler === undefined) {
490
+ // A security rule that could not run must say so. Silence here is indistinguishable from a clean
491
+ // result, and this is the one rule whose clean result means "no SQL injection was found".
492
+ diagnostics.push({
493
+ rule: "interpolated-sql",
494
+ severity: "warning",
495
+ message: SQL_COMPILER_MISSING_HINT,
496
+ fix: SQL_COMPILER_MISSING_HINT,
497
+ suggestion: {
498
+ kind: "command",
499
+ title: "Install TypeScript so the SQL rule can run",
500
+ command: ["bun add -d typescript"],
501
+ },
502
+ });
503
+ }
504
+ for (const f of [...interpolatedSql].sort(bySite)) {
505
+ diagnostics.push({
506
+ rule: "interpolated-sql",
507
+ severity: "error",
508
+ file: f.file,
509
+ line: f.line,
510
+ message: `${f.snippet} - ${INTERPOLATED_SQL_HINT}`,
511
+ fix: "bind the value as a parameter instead of interpolating it into the statement",
512
+ suggestion: {
513
+ kind: "manual",
514
+ title: "Bind the value instead of interpolating it",
515
+ steps: [
516
+ "Replace the interpolation with a placeholder your driver understands (`?` for SQLite/MySQL, `$1` for Postgres).",
517
+ "Pass the value as an argument alongside the statement, so the driver binds it.",
518
+ `Or switch to the driver's tagged template (sql\`… ${SQL_INTERPOLATION_EXAMPLE} …\`): the tag receives substitutions separately and binds them.`,
519
+ "An identifier that genuinely cannot be bound (a table or column name) must be checked against an allowlist you control, never taken from the request.",
520
+ "If the statement is dynamic but every value is already bound (generating `($1),($2),…` for a batch insert), mark it with a `// nifra-expect sql-dynamic: <reason>` comment on the line above - the reason is required.",
521
+ ],
522
+ },
523
+ });
524
+ }
525
+ // Advisory - surfaced but NOT folded into `ok`, so it never fails the gate (a raw Response is valid).
526
+ for (const f of [...responseRoutes].sort(bySite)) {
527
+ diagnostics.push({
528
+ rule: "response-route",
529
+ severity: "warning",
530
+ file: f.file,
531
+ line: f.line,
532
+ message: `${f.snippet} - ${RESPONSE_ROUTE_HINT}`,
533
+ fix: RESPONSE_ROUTE_HINT,
534
+ suggestion: responseRouteSuggestion(),
535
+ });
536
+ }
537
+ if (dr.ran) {
538
+ for (const f of dr.findings) {
539
+ diagnostics.push({
540
+ rule: "undeclared-dependency",
541
+ severity: "error",
542
+ file: f.file,
543
+ line: f.line,
544
+ message: `imports ${f.package} which is not declared in package.json - ${UNDECLARED_DEP_HINT}`,
545
+ fix: `add ${f.package} to package.json dependencies`,
546
+ suggestion: {
547
+ kind: "command",
548
+ title: `Declare ${f.package} in package.json`,
549
+ command: ["bun", "add", f.package],
550
+ },
551
+ });
552
+ }
553
+ for (const finding of dr.duplicateInstalls) {
554
+ // One line per physical copy: version, resolved absolute path, and who pulled it in. The
555
+ // absolute path is what a reader pastes into an editor or `rm -rf`; the importer list is what
556
+ // tells them WHICH package.json to fix - a relative path alone answers neither.
557
+ const copyLines = finding.copies.map((copy) => `${finding.package}@${copy.version} at ${copy.absolutePath ?? copy.path} - pulled in by ${copy.importers.join(", ")}`);
558
+ diagnostics.push({
559
+ rule: "duplicate-install",
560
+ severity: "error",
561
+ message: `${finding.package} identity preflight found ${finding.cause} - ${finding.explanation}${finding.topology === undefined ? "" : `. Topology: ${finding.topology}`}${finding.scope === undefined ? "" : `. Scope: ${finding.scope}`}`,
562
+ fix: finding.remediation,
563
+ evidence: copyLines,
564
+ suggestion: {
565
+ kind: "manual",
566
+ title: `Resolve ${finding.package} to one loaded copy`,
567
+ // The renderer prints this block verbatim before the steps: the exact config for fix 2, so
568
+ // the reader pastes instead of transcribing prose into JSON and TOML.
569
+ diff: [
570
+ "package.json:",
571
+ ` "nifra": { "singleCopy": ["${finding.package}"] }`,
572
+ "bunfig.toml:",
573
+ ` preload = ["${SINGLE_COPY_REGISTER_SPECIFIER}"]`,
574
+ " [test]",
575
+ ` preload = ["${SINGLE_COPY_REGISTER_SPECIFIER}"]`,
576
+ ].join("\n"),
577
+ steps: [
578
+ ...copyLines.map((line) => `Copy: ${line}`),
579
+ "Fix 1 - deduplicate: align workspace dependency and peer ranges on one compatible version, remove stale nested installs, and reinstall from the workspace root so every importer resolves one physical copy.",
580
+ `Fix 2 - declare single-copy: apply the package.json and bunfig.toml config printed above; nifra then rewrites every duplicate to this app's copy.${finding.cause === "version-skew" ? " A declaration only covers same-version duplicates, so fix 1's range alignment must land first." : ""}`,
581
+ "Re-run `nifra check`; the gate stays failing until one fix lands.",
582
+ ],
583
+ },
584
+ });
585
+ }
586
+ // Declared single-copy: the resolver collapses these before anything loads, so the build is sound
587
+ // and the gate stays green. It is still worth a line - the guarantee lives in a declaration now,
588
+ // and a reader who deletes it gets a null hook dispatcher with no obvious cause.
589
+ for (const finding of dr.deduplicatedInstalls ?? []) {
590
+ const copies = finding.copies.map((copy) => copy.path).join("; ");
591
+ diagnostics.push({
592
+ rule: "duplicate-install",
593
+ severity: "warning",
594
+ message: `${finding.package} is installed at ${finding.copies.length} paths (${copies}) and is declared single-copy - nifra resolves every duplicate to this app's copy`,
595
+ fix: finding.remediation,
596
+ });
597
+ }
598
+ // Advisory (never fails the gate): while actively editing a linked package its dist is always
599
+ // momentarily behind. The finding earns its keep when a dev server is about to start against it -
600
+ // Bun reads live `src` while Vite's SSR runner reads the artifact, so a stale one 500s inside
601
+ // framework/shared-package code and reads exactly like an upstream regression.
602
+ for (const f of dr.staleDists) {
603
+ // The rebuild is only actionable with the LOCATION: a workspace link routinely points into a
604
+ // sibling repo, so "rebuild @nifrajs/core" left the developer to go find the checkout and guess
605
+ // the script. Name the directory and the package's own script, or say plainly that it declares
606
+ // none - never suggest a command that would fail.
607
+ const rebuild = f.buildScript === undefined
608
+ ? `${f.packageDir} declares no build script - build it the way that package expects`
609
+ : `cd ${f.packageDir} && bun run ${f.buildScript} (or \`nifra fix --code NF-C010\`)`;
610
+ diagnostics.push({
611
+ rule: "stale-workspace-dist",
612
+ severity: "warning",
613
+ message: f.missing
614
+ ? `${f.package} was never built - ${f.distFile} is missing, but its export map serves it to Vite SSR/node consumers while Bun reads src - ${rebuild}`
615
+ : `${f.package} has a stale build artifact - ${f.distFile} is ${f.behindSeconds}s older than ${f.sourceFile}, and Vite SSR/node consumers read the artifact while Bun reads src - ${rebuild}`,
616
+ fix: rebuild,
617
+ evidence: [f.package, f.distFile, f.sourceFile, f.packageDir],
618
+ suggestion: {
619
+ kind: "manual",
620
+ title: `Rebuild ${f.package}`,
621
+ steps: [
622
+ rebuild,
623
+ "Only workspace-linked installs drift; npm tarballs are immutable and never flagged.",
624
+ ],
625
+ },
626
+ });
627
+ }
628
+ }
629
+ // The two-pipeline rule, read from the config as TEXT (doctor collects it - see ./pipeline-report.ts).
630
+ // `loadApp` already refuses a misplaced plugin, but only when something loads the app; a check that
631
+ // never executes project code, and CI that never starts a dev server, would otherwise meet these for
632
+ // the first time as a production server that built cleanly and died at startup.
633
+ for (const f of dr.pipeline?.findings ?? []) {
634
+ diagnostics.push({
635
+ rule: "pipeline",
636
+ severity: f.severity,
637
+ file: f.file,
638
+ ...(f.line !== undefined ? { line: f.line } : {}),
639
+ message: f.message,
640
+ fix: f.fix,
641
+ suggestion: { kind: "manual", title: f.fix, steps: [PIPELINE_DOC_HINT] },
642
+ });
643
+ }
644
+ // #7: a committed server-manifest.ts that drifted from routes/ - name the exact missing/extra routes.
645
+ for (const f of manifestDrift) {
646
+ const parts = [];
647
+ if (f.missing.length > 0)
648
+ parts.push(`missing from manifest: ${f.missing.join(", ")}`);
649
+ if (f.extra.length > 0)
650
+ parts.push(`stale in manifest: ${f.extra.join(", ")}`);
651
+ diagnostics.push({
652
+ rule: "server-manifest-drift",
653
+ severity: "error",
654
+ file: f.file,
655
+ message: `${f.file} drifted from routes/ (${parts.join("; ")}) - ${MANIFEST_DRIFT_HINT}`,
656
+ fix: MANIFEST_DRIFT_HINT,
657
+ evidence: [...f.missing, ...f.extra],
658
+ suggestion: {
659
+ kind: "manual",
660
+ title: "Regenerate the committed server manifest",
661
+ steps: [
662
+ "Re-run your build (`nifra build --target <t>` or your build script) - it regenerates server-manifest.ts from the current routes/.",
663
+ "Commit the updated server-manifest.ts.",
664
+ ],
665
+ },
666
+ });
667
+ }
668
+ // G+B+D+F: when the project opts into capability assurance, `nifra check` becomes the static
669
+ // provenance firewall as well as the typed-contract gate. Loading is explicit/config-owned; projects
670
+ // without nifra.assurance.ts retain the historical scan and hot path unchanged.
671
+ const provided = opts.assurance;
672
+ let applicationRulePacks = [];
673
+ let loadedPolicy = provided;
674
+ let loadedCapability = provided?.capability;
675
+ const assuranceConfigPath = join(cwd, "nifra.assurance.ts");
676
+ if (provided !== undefined ? provided.present : existsSync(assuranceConfigPath)) {
677
+ try {
678
+ // Either the shared reflection from `collectProjectVerification` (no second pass) or, on the
679
+ // standalone path, loaded + reflected here. Both branches yield the same config + evidence.
680
+ let config;
681
+ let project;
682
+ let routeAssurance;
683
+ let evidence;
684
+ if (provided !== undefined) {
685
+ // A load/evaluate failure travels as `provided.error`; re-throwing lands it in the same
686
+ // capability-config diagnostic the standalone catch produces.
687
+ if (provided.error !== undefined)
688
+ throw provided.error;
689
+ config = provided.config;
690
+ project = provided.capability;
691
+ routeAssurance = provided.routeAssurance;
692
+ evidence = provided.evidence;
693
+ }
694
+ else {
695
+ const { loadAssuranceConfig } = await import("./assure.js");
696
+ config = await loadAssuranceConfig(cwd);
697
+ if (config.capabilities !== undefined) {
698
+ const { collectCapabilityProjectReport } = await import("./capabilities-tool.js");
699
+ project = await collectCapabilityProjectReport(cwd, config.source, config.capabilities);
700
+ }
701
+ loadedPolicy = {
702
+ present: true,
703
+ config,
704
+ ...(routeAssurance === undefined ? {} : { routeAssurance }),
705
+ ...(project === undefined ? {} : { capability: project }),
706
+ ...(evidence === undefined ? {} : { evidence }),
707
+ };
708
+ loadedCapability = project;
709
+ }
710
+ applicationRulePacks = parseRulePacks(config.rulePacks);
711
+ const capabilityReport = project?.report;
712
+ if (config.capabilities !== undefined && project !== undefined) {
713
+ for (const finding of project.report.findings) {
714
+ const violation = finding.code === "forbidden-effect-import"
715
+ ? project.violations.find((candidate) => candidate.method === finding.method && candidate.path === finding.path)
716
+ : undefined;
717
+ const truncation = finding.code === "provenance-truncated"
718
+ ? project.truncations.find((candidate) => candidate.method === finding.method && candidate.path === finding.path)
719
+ : undefined;
720
+ // An unmatched seam is a policy defect, not a route defect: the fix is in the policy file,
721
+ // so it gets its own steps instead of the route-side provenance guidance.
722
+ const seamFix = finding.code === "unmatched-provenance-seam"
723
+ ? "Write the seam exactly as the code imports it, or delete the rule."
724
+ : undefined;
725
+ diagnostics.push({
726
+ rule: "capability-assurance",
727
+ severity: "error",
728
+ ...(violation !== undefined
729
+ ? { file: violation.module, chain: violation.chain }
730
+ : truncation !== undefined
731
+ ? { chain: truncation.chain }
732
+ : {}),
733
+ message: `${finding.message}${seamFix === undefined ? ` - ${CAPABILITY_HINT}` : ""}`,
734
+ fix: seamFix ?? CAPABILITY_HINT,
735
+ suggestion: seamFix === undefined
736
+ ? {
737
+ kind: "manual",
738
+ title: "Restore declared effect provenance",
739
+ steps: [
740
+ "Route effectful work through an import listed in capabilities.provenance.imports.",
741
+ "Declare the exact capability token on the route; do not widen unrelated routes in the same file.",
742
+ "For domain writes, add the adapter the capability definition requires: `schema.idempotency` for the `request` tier, `.use(durableCommand({ journal }))` from @nifrajs/middleware for the `durable` tier.",
743
+ "Run `nifra capabilities snapshot` only after assurance passes, then review the lockfile diff.",
744
+ ],
745
+ }
746
+ : {
747
+ kind: "manual",
748
+ title: "Point the provenance rule at a module that exists",
749
+ steps: [
750
+ "Copy the specifier from the import statement itself - it is matched as written, with no extension or index resolution.",
751
+ "Use a trailing `/*` when the seam is a directory of modules (`@myorg/db/*`).",
752
+ "For a routeModules entry, give the project-relative path of the file that implements the route.",
753
+ "Delete the rule if the seam it governed is gone; leaving it in place proves nothing.",
754
+ ],
755
+ },
756
+ });
757
+ }
758
+ }
759
+ if (config.manifest !== undefined) {
760
+ const { buildNifraManifest, parseNifraManifest, serializeNifraManifest } = await import("@nifrajs/core/manifest");
761
+ const assurance = routeAssurance ??
762
+ (await import("@nifrajs/core/assurance")).evaluateRouteAssurance(config.source, config.policy, {
763
+ ...(config.capabilities !== undefined
764
+ ? { definitions: config.capabilities.definitions }
765
+ : {}),
766
+ });
767
+ evidence ??= snapshotProjectEvidence(config.source, {
768
+ assurance,
769
+ ...(capabilityReport !== undefined ? { capabilities: capabilityReport } : {}),
770
+ });
771
+ const path = resolve(cwd, config.manifest.path ?? "nifra.manifest.json");
772
+ let message;
773
+ if (!assurance.ok || (capabilityReport !== undefined && !capabilityReport.ok)) {
774
+ message =
775
+ "the configured assurance policy is failing, so a trusted manifest cannot be built";
776
+ }
777
+ else if (!existsSync(path)) {
778
+ message = "the configured trust manifest is missing";
779
+ }
780
+ else {
781
+ try {
782
+ const current = await buildNifraManifest({
783
+ evidence,
784
+ assurance,
785
+ ...(capabilityReport !== undefined ? { capabilities: capabilityReport } : {}),
786
+ });
787
+ const storedText = await Bun.file(path).text();
788
+ const stored = await parseNifraManifest(storedText, path);
789
+ const expectedText = `${serializeNifraManifest(current)}\n`;
790
+ if (storedText !== expectedText || stored.contentHash !== current.contentHash) {
791
+ message = "the configured trust manifest does not match live route reflection";
792
+ }
793
+ }
794
+ catch (error) {
795
+ message = `the configured trust manifest is invalid: ${error instanceof Error ? error.message : String(error)}`;
796
+ }
797
+ }
798
+ if (message !== undefined) {
799
+ diagnostics.push({
800
+ rule: "manifest-drift",
801
+ severity: "error",
802
+ file: path,
803
+ message: `${message} - ${TRUST_MANIFEST_DRIFT_HINT}`,
804
+ fix: TRUST_MANIFEST_DRIFT_HINT,
805
+ suggestion: {
806
+ kind: "command",
807
+ title: "Regenerate the signed-manifest input artifact",
808
+ command: ["nifra", "manifest", "emit"],
809
+ steps: [
810
+ "Review the route, assurance, capability, and classification delta before committing it.",
811
+ ],
812
+ },
813
+ });
814
+ }
815
+ }
816
+ }
817
+ catch (err) {
818
+ loadedPolicy = { present: true, error: err };
819
+ diagnostics.push({
820
+ rule: "capability-config",
821
+ severity: "error",
822
+ file: "nifra.assurance.ts",
823
+ message: `capability assurance config could not be evaluated: ${err instanceof Error ? err.message : String(err)}`,
824
+ suggestion: {
825
+ kind: "manual",
826
+ title: "Repair the assurance config",
827
+ steps: [
828
+ "Ensure nifra.assurance.ts default-exports defineAssuranceConfig({ source, policy, capabilities }).",
829
+ "Fix configuration/import errors; the provenance firewall fails closed when its policy cannot load.",
830
+ ],
831
+ },
832
+ });
833
+ }
834
+ }
835
+ try {
836
+ const { checkContractsLock } = await import("./contracts.js");
837
+ if (!existsSync(join(cwd, "backend.ts")) && !existsSync(join(cwd, "contracts.lock.json"))) {
838
+ throw new Error("contract source not configured");
839
+ }
840
+ const contract = await checkContractsLock(cwd);
841
+ if (!contract.present) {
842
+ structuredExtras.push(diagnostic({
843
+ code: "NF-K001",
844
+ severity: "info",
845
+ message: "no contract lock; run `nifra contracts snapshot` to enable drift detection",
846
+ verify: "nifra contracts snapshot",
847
+ }));
848
+ }
849
+ else {
850
+ if (contract.vacuous) {
851
+ // Every route hashes to the empty-schema digest, so the lock exists but the drift rule guards
852
+ // nothing: it can only ever compare "no schema" to "no schema". Say so, or a green contract check
853
+ // reads as proof of a stable contract when there is no contract to be stable.
854
+ structuredExtras.push(diagnostic({
855
+ code: "NF-K001",
856
+ severity: "info",
857
+ message: "no route schemas declared - the trust manifest is vacuous: every contract hash is the empty-schema digest, so drift detection guards nothing. Declare route schemas (body/query/params/response) so the lock has a contract to protect.",
858
+ verify: "nifra check --lints-only",
859
+ }));
860
+ }
861
+ for (const finding of contract.diagnostics) {
862
+ diagnostics.push({
863
+ rule: "contract-drift",
864
+ severity: "error",
865
+ code: "NF-K001",
866
+ ...(finding.route !== undefined ? { evidence: [finding.route] } : {}),
867
+ message: finding.message,
868
+ fix: "run `nifra contracts snapshot` after reviewing the contract change",
869
+ verify: "nifra check --lints-only",
870
+ });
871
+ }
872
+ }
873
+ }
874
+ catch (error) {
875
+ if (error instanceof Error && error.message === "contract source not configured") {
876
+ // API-only source scans have no contract surface to snapshot.
877
+ }
878
+ else {
879
+ diagnostics.push({
880
+ rule: "contract-drift",
881
+ severity: "error",
882
+ code: "NF-K001",
883
+ message: `contract lock could not be checked: ${error instanceof Error ? error.message : String(error)}`,
884
+ verify: "nifra contracts snapshot",
885
+ });
886
+ }
887
+ }
888
+ const projectFacts = freezeProjectFacts({
889
+ ...factsSeed,
890
+ policies: {
891
+ ...factsSeed.policies,
892
+ ...(loadedPolicy === undefined ? {} : { assurance: loadedPolicy }),
893
+ ...(loadedCapability === undefined ? {} : { capability: loadedCapability }),
894
+ rulePacks: applicationRulePacks,
895
+ },
896
+ }, diagnostics);
897
+ const ruleContext = {
898
+ root: cwd,
899
+ sources: projectFacts.source,
900
+ project: projectFacts,
901
+ };
902
+ const structuredDiagnostics = [...structuredExtras];
903
+ let registryDiagnostics = [];
904
+ try {
905
+ registryDiagnostics = await runRuleRegistry(ruleContext, [...legacyRules, ...securityRules, ...routeRules, ...islandRules, ...nanoRules], projectFacts.policies.rulePacks);
906
+ structuredDiagnostics.push(...registryDiagnostics);
907
+ }
908
+ catch (error) {
909
+ registryDiagnostics = [
910
+ diagnostic({
911
+ code: "NF-C017",
912
+ severity: "error",
913
+ message: `rule registry failed closed: ${error instanceof Error ? error.message : String(error)}`,
914
+ fix: { recipe: "rule-pack.repair", command: "nifra check --lints-only" },
915
+ verify: "nifra check --lints-only",
916
+ }),
917
+ ];
918
+ structuredDiagnostics.push(...registryDiagnostics);
919
+ }
920
+ for (const item of registryDiagnostics) {
921
+ // The legacy adapters publish stable structured findings; the human compatibility view already
922
+ // contains their original rule names. Security rules and application packs still need a legacy-view
923
+ // row because they have no pre-registry diagnostic.
924
+ if (legacyRules.some((rule) => rule.code === item.code))
925
+ continue;
926
+ diagnostics.push({
927
+ rule: item.code,
928
+ severity: item.severity === "error" ? "error" : "warning",
929
+ code: item.code,
930
+ ...(item.file !== undefined ? { file: item.file } : {}),
931
+ ...(item.line !== undefined ? { line: item.line } : {}),
932
+ message: item.message,
933
+ ...(item.evidence !== undefined ? { evidence: item.evidence } : {}),
934
+ ...(item.verify !== undefined ? { verify: item.verify } : {}),
935
+ });
936
+ }
937
+ // Per-rule overrides from `nifra.check.json` `rules`, applied centrally to BOTH diagnostic views
938
+ // before `ok` is computed - never inside individual rules, so no rule can dodge (or double-apply)
939
+ // them. A key matches the legacy rule name or the stable NF- code.
940
+ const overrideFor = (...keys) => {
941
+ for (const key of keys) {
942
+ if (key !== undefined && checkConfig.rules[key] !== undefined)
943
+ return checkConfig.rules[key];
944
+ }
945
+ return undefined;
946
+ };
947
+ const dropped = (override, file) => {
948
+ if (override.severity === "off")
949
+ return true;
950
+ if (override.ignore === undefined || file === undefined)
951
+ return false;
952
+ return override.ignore.some((pattern) => safeIgnoreGlobMatch(pattern, file));
953
+ };
954
+ const codeToLegacy = new Map(Object.entries(LEGACY_RULE_CODES).map(([name, code]) => [code, name]));
955
+ const finalDiagnostics = diagnostics.flatMap((d) => {
956
+ const override = overrideFor(d.rule, d.code, LEGACY_RULE_CODES[d.rule]);
957
+ if (override === undefined)
958
+ return [d];
959
+ if (dropped(override, d.file))
960
+ return [];
961
+ // "off" is fully handled by `dropped` above - only real severities reach the retag.
962
+ if (override.severity === undefined || override.severity === "off")
963
+ return [d];
964
+ return [{ ...d, severity: override.severity === "warn" ? "warning" : override.severity }];
965
+ });
966
+ const finalStructured = structuredDiagnostics.flatMap((d) => {
967
+ const override = overrideFor(d.code, codeToLegacy.get(d.code));
968
+ if (override === undefined)
969
+ return [d];
970
+ if (dropped(override, d.file))
971
+ return [];
972
+ if (override.severity === undefined || override.severity === "off")
973
+ return [d];
974
+ return [Object.freeze({ ...d, severity: override.severity })];
975
+ });
976
+ // Cap the diagnostics when asked (the MCP path), so a project with thousands of findings can't return a
977
+ // message that breaks the stdio transport. `ok` reflects the FULL set - truncation never flips it.
978
+ const total = finalDiagnostics.length;
979
+ const max = opts.maxDiagnostics;
980
+ const shown = max !== undefined && total > max ? finalDiagnostics.slice(0, max) : finalDiagnostics;
981
+ const result = {
982
+ ok: !finalDiagnostics.some((diagnostic) => diagnostic.severity === "error"),
983
+ typecheck: tc.ran ? (tc.ok ? "pass" : "fail") : "skipped",
984
+ ...(!tc.ran && tc.note !== undefined ? { typecheckNote: tc.note } : {}),
985
+ diagnostics: shown,
986
+ ...(dr.pipeline !== undefined ? { pipeline: dr.pipeline } : {}),
987
+ ...(dr.ran
988
+ ? {
989
+ identityPreflight: {
990
+ ...(dr.identityBasis !== undefined ? { basis: dr.identityBasis } : {}),
991
+ ...(dr.identityScanTruncated === true ? { truncated: true } : {}),
992
+ duplicates: dr.duplicateInstalls,
993
+ deduplicated: dr.deduplicatedInstalls ?? [],
994
+ },
995
+ }
996
+ : {}),
997
+ ...(checkConfig.externalMounts.length > 0
998
+ ? { externalMounts: checkConfig.externalMounts }
999
+ : {}),
1000
+ ...(Object.keys(checkConfig.rules).length > 0 ? { ruleOverrides: checkConfig.rules } : {}),
1001
+ ...(shown.length < total ? { truncated: { shown: shown.length, total } } : {}),
1002
+ };
1003
+ Object.defineProperty(result, "structuredDiagnostics", {
1004
+ value: finalStructured.slice(0, shown.length + structuredExtras.length),
1005
+ enumerable: false,
1006
+ });
1007
+ return result;
1008
+ }
1009
+ //# sourceMappingURL=check-diagnostics.js.map