@nifrajs/cli 5.6.0 → 5.7.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 (122) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/dist/check-diagnostics.d.ts.map +1 -1
  3. package/dist/check-diagnostics.js +4 -0
  4. package/dist/check-diagnostics.js.map +1 -1
  5. package/dist/check-scan.d.ts +6 -0
  6. package/dist/check-scan.d.ts.map +1 -1
  7. package/dist/check-scan.js +1 -30
  8. package/dist/check-scan.js.map +1 -1
  9. package/dist/check.d.ts.map +1 -1
  10. package/dist/check.js +35 -12
  11. package/dist/check.js.map +1 -1
  12. package/dist/cli.d.ts +4 -0
  13. package/dist/cli.d.ts.map +1 -1
  14. package/dist/cli.js +53 -5
  15. package/dist/cli.js.map +1 -1
  16. package/dist/command-catalog.d.ts +5 -0
  17. package/dist/command-catalog.d.ts.map +1 -1
  18. package/dist/command-catalog.js +18 -6
  19. package/dist/command-catalog.js.map +1 -1
  20. package/dist/contracts.d.ts +42 -4
  21. package/dist/contracts.d.ts.map +1 -1
  22. package/dist/contracts.js +288 -9
  23. package/dist/contracts.js.map +1 -1
  24. package/dist/doctor.d.ts +6 -4
  25. package/dist/doctor.d.ts.map +1 -1
  26. package/dist/doctor.js +20 -6
  27. package/dist/doctor.js.map +1 -1
  28. package/dist/internal/git-ignored.d.ts +12 -0
  29. package/dist/internal/git-ignored.d.ts.map +1 -0
  30. package/dist/internal/git-ignored.js +49 -0
  31. package/dist/internal/git-ignored.js.map +1 -0
  32. package/dist/internal/source-facts.d.ts +29 -0
  33. package/dist/internal/source-facts.d.ts.map +1 -1
  34. package/dist/internal/source-facts.js +160 -0
  35. package/dist/internal/source-facts.js.map +1 -1
  36. package/dist/load.d.ts +4 -1
  37. package/dist/load.d.ts.map +1 -1
  38. package/dist/load.js +10 -0
  39. package/dist/load.js.map +1 -1
  40. package/dist/local-cli.d.ts +15 -0
  41. package/dist/local-cli.d.ts.map +1 -0
  42. package/dist/local-cli.js +74 -0
  43. package/dist/local-cli.js.map +1 -0
  44. package/dist/lock-links.d.ts +0 -7
  45. package/dist/lock-links.d.ts.map +1 -1
  46. package/dist/lock-links.js +5 -44
  47. package/dist/lock-links.js.map +1 -1
  48. package/dist/mcp-delegate.d.ts +13 -5
  49. package/dist/mcp-delegate.d.ts.map +1 -1
  50. package/dist/mcp-delegate.js +24 -8
  51. package/dist/mcp-delegate.js.map +1 -1
  52. package/dist/mcp-http.js +1 -1
  53. package/dist/openapi-types.d.ts.map +1 -1
  54. package/dist/openapi-types.js +45 -2
  55. package/dist/openapi-types.js.map +1 -1
  56. package/dist/recipes/5.7.0.d.ts +12 -0
  57. package/dist/recipes/5.7.0.d.ts.map +1 -0
  58. package/dist/recipes/5.7.0.js +70 -0
  59. package/dist/recipes/5.7.0.js.map +1 -0
  60. package/dist/recipes/index.d.ts +13 -0
  61. package/dist/recipes/index.d.ts.map +1 -1
  62. package/dist/recipes/index.js +2 -0
  63. package/dist/recipes/index.js.map +1 -1
  64. package/dist/review.d.ts.map +1 -1
  65. package/dist/review.js +2 -0
  66. package/dist/review.js.map +1 -1
  67. package/dist/rules/codes.d.ts +2 -0
  68. package/dist/rules/codes.d.ts.map +1 -1
  69. package/dist/rules/codes.js +2 -0
  70. package/dist/rules/codes.js.map +1 -1
  71. package/dist/rules/explanations.d.ts.map +1 -1
  72. package/dist/rules/explanations.js +13 -3
  73. package/dist/rules/explanations.js.map +1 -1
  74. package/dist/rules/legacy.js +1 -1
  75. package/dist/rules/legacy.js.map +1 -1
  76. package/dist/rules/text-slot-boolean.d.ts +8 -0
  77. package/dist/rules/text-slot-boolean.d.ts.map +1 -0
  78. package/dist/rules/text-slot-boolean.js +57 -0
  79. package/dist/rules/text-slot-boolean.js.map +1 -0
  80. package/dist/rules/undeclared-response.d.ts +9 -0
  81. package/dist/rules/undeclared-response.d.ts.map +1 -0
  82. package/dist/rules/undeclared-response.js +93 -0
  83. package/dist/rules/undeclared-response.js.map +1 -0
  84. package/dist/upgrade.d.ts +34 -8
  85. package/dist/upgrade.d.ts.map +1 -1
  86. package/dist/upgrade.js +197 -25
  87. package/dist/upgrade.js.map +1 -1
  88. package/dist/version-drift.js +1 -1
  89. package/dist/version-drift.js.map +1 -1
  90. package/dist/web-app-options.d.ts +1 -1
  91. package/dist/web-app-options.d.ts.map +1 -1
  92. package/dist/web-app-options.js.map +1 -1
  93. package/docs/examples.json +7 -1
  94. package/docs/llms-full.txt +441 -105
  95. package/docs/types.json +164 -43
  96. package/package.json +11 -11
  97. package/src/check-diagnostics.ts +4 -0
  98. package/src/check-scan.ts +1 -29
  99. package/src/check.ts +32 -10
  100. package/src/cli.ts +58 -5
  101. package/src/command-catalog.ts +23 -6
  102. package/src/contracts.ts +348 -14
  103. package/src/doctor.ts +28 -12
  104. package/src/internal/git-ignored.ts +47 -0
  105. package/src/internal/source-facts.ts +198 -0
  106. package/src/load.ts +16 -0
  107. package/src/local-cli.ts +83 -0
  108. package/src/lock-links.ts +5 -43
  109. package/src/mcp-delegate.ts +30 -9
  110. package/src/mcp-http.ts +1 -1
  111. package/src/openapi-types.ts +43 -2
  112. package/src/recipes/5.7.0.ts +72 -0
  113. package/src/recipes/index.ts +16 -0
  114. package/src/review.ts +2 -0
  115. package/src/rules/codes.ts +2 -0
  116. package/src/rules/explanations.ts +13 -3
  117. package/src/rules/legacy.ts +1 -1
  118. package/src/rules/text-slot-boolean.ts +56 -0
  119. package/src/rules/undeclared-response.ts +92 -0
  120. package/src/upgrade.ts +229 -33
  121. package/src/version-drift.ts +1 -1
  122. package/src/web-app-options.ts +1 -0
package/src/contracts.ts CHANGED
@@ -6,13 +6,25 @@ import {
6
6
  reflectedRoutesFromEvidence,
7
7
  snapshotProjectEvidence,
8
8
  } from "@nifrajs/core/evidence"
9
- import type { ReflectedRoute } from "@nifrajs/core/reflection"
9
+ import type { ReflectedRoute, SchemaReflection } from "@nifrajs/core/reflection"
10
10
  import { BACKEND_APP_FILE } from "./app-files.ts"
11
11
  import { codeUnitOrder } from "./internal/code-unit-order.ts"
12
12
 
13
+ /** One declared part of a route's contract: `body`, `query`, `params`, `headers`, `cookies`,
14
+ * `response`, `sse` or `errors.<status>`. */
15
+ export interface ContractPart {
16
+ /** Hash of the part's schema, or `null` where it is declared in a form nifra cannot read. */
17
+ readonly digest: string | null
18
+ /** The type of each top-level field, `name?` for an optional one, when the schema is an object. */
19
+ readonly fields?: Readonly<Record<string, string>>
20
+ }
21
+
13
22
  export interface ContractDigest {
14
23
  readonly request: string
15
24
  readonly response: string
25
+ /** Each part the route declares. Absent in a lock written before parts were recorded: such a lock
26
+ * compares by side, and never covered headers or cookies. */
27
+ readonly parts?: Readonly<Record<string, ContractPart>>
16
28
  }
17
29
 
18
30
  export interface ContractsLock {
@@ -133,6 +145,115 @@ export async function emptySchemaDigest(): Promise<string> {
133
145
  return sha256(JSON.stringify(canonical(schemaValue(undefined, "request"))))
134
146
  }
135
147
 
148
+ const PART_ORDER = ["body", "query", "params", "headers", "cookies", "response", "sse"] as const
149
+ const REQUEST_PARTS: ReadonlySet<string> = new Set([
150
+ "body",
151
+ "query",
152
+ "params",
153
+ "headers",
154
+ "cookies",
155
+ ])
156
+ const sideOf = (part: string): "request" | "response" =>
157
+ REQUEST_PARTS.has(part) ? "request" : "response"
158
+
159
+ function partRank(part: string): number {
160
+ const at = PART_ORDER.findIndex((name) => name === part)
161
+ return at === -1 ? PART_ORDER.length : at
162
+ }
163
+
164
+ const partOrder = (a: string, b: string): number => partRank(a) - partRank(b) || codeUnitOrder(a, b)
165
+
166
+ function declaredParts(schema: ReflectedRoute["schema"]): Array<[string, SchemaReflection]> {
167
+ if (schema === undefined) return []
168
+ const parts: Array<[string, SchemaReflection]> = []
169
+ for (const part of PART_ORDER) {
170
+ const value = schema[part]
171
+ if (value !== undefined) parts.push([part, value])
172
+ }
173
+ for (const [status, value] of Object.entries(schema.errors ?? {}))
174
+ parts.push([`errors.${status}`, value])
175
+ return parts.sort(([a], [b]) => partOrder(a, b))
176
+ }
177
+
178
+ const MAX_ENUM_LABEL = 6
179
+
180
+ /** A short type name for one field schema, for the lock and a check message to show. */
181
+ function typeLabel(schema: unknown): string {
182
+ if (schema === true) return "unknown"
183
+ if (schema === false) return "never"
184
+ const record = recordOf(schema)
185
+ if (record === undefined) return "unknown"
186
+ if (Object.hasOwn(record, "const")) return JSON.stringify(record.const) ?? "unknown"
187
+ const values = record.enum
188
+ if (Array.isArray(values))
189
+ return values.length > MAX_ENUM_LABEL
190
+ ? `enum(${values.length})`
191
+ : values.map((value) => JSON.stringify(value)).join(" | ")
192
+ const union = record.anyOf ?? record.oneOf
193
+ if (Array.isArray(union)) return union.map((item) => typeLabel(item)).join(" | ")
194
+ const ref = record.$ref
195
+ if (typeof ref === "string") return ref.slice(ref.lastIndexOf("/") + 1)
196
+ const type = record.type
197
+ const types = Array.isArray(type) ? type : [type]
198
+ const labels: string[] = []
199
+ for (const name of types) {
200
+ if (typeof name !== "string") continue
201
+ if (name !== "array") labels.push(name)
202
+ else {
203
+ const item = typeLabel(record.items)
204
+ labels.push(item.includes(" | ") ? `(${item})[]` : `${item}[]`)
205
+ }
206
+ }
207
+ return labels.length === 0 ? "unknown" : labels.join(" | ")
208
+ }
209
+
210
+ /** Each part `route` declares, hashed alone, with its top-level fields. */
211
+ export async function contractParts(route: ReflectedRoute): Promise<Record<string, ContractPart>> {
212
+ const entries = await Promise.all(
213
+ declaredParts(route.schema).map(async ([part, value]): Promise<[string, ContractPart]> => {
214
+ const schema = value.jsonSchema ?? value.fields
215
+ if (schema === undefined) return [part, { digest: null }]
216
+ const digest = await sha256(JSON.stringify(canonical(schema)))
217
+ if (value.fields === undefined) return [part, { digest }]
218
+ const fields = value.fields
219
+ .map((field): [string, string] => [
220
+ field.required ? field.name : `${field.name}?`,
221
+ typeLabel(field.schema),
222
+ ])
223
+ .sort(([a], [b]) => codeUnitOrder(a, b))
224
+ return [part, { digest, fields: Object.fromEntries(fields) }]
225
+ }),
226
+ )
227
+ return Object.fromEntries(entries)
228
+ }
229
+
230
+ /** Per side, the digests of a route whose schema says nothing on that side: none declared, or every
231
+ * part declared in a form reflection cannot read (hashed as `null`). A lock entry holding one never
232
+ * guarded that side. */
233
+ async function blindDigests(): Promise<Record<"request" | "response", ReadonlySet<string>>> {
234
+ const of = async (side: "request" | "response") =>
235
+ new Set([
236
+ await sha256(JSON.stringify(canonical(schemaValue(undefined, side)))),
237
+ await sha256(JSON.stringify(canonical(schemaValue({}, side)))),
238
+ ])
239
+ return { request: await of("request"), response: await of("response") }
240
+ }
241
+
242
+ const unread = (value: SchemaReflection | undefined): boolean =>
243
+ value !== undefined && value.jsonSchema === undefined && value.fields === undefined
244
+
245
+ /** The parts of `route` that declare a schema reflection cannot read: hashed as `null`, as if absent,
246
+ * so the lock never notices a change to them. */
247
+ export function unreflectedParts(route: ReflectedRoute): string[] {
248
+ const schema = route.schema
249
+ if (schema === undefined) return []
250
+ const parts: string[] = []
251
+ for (const part of PART_ORDER) if (unread(schema[part])) parts.push(part)
252
+ for (const [status, value] of Object.entries(schema.errors ?? {}))
253
+ if (unread(value)) parts.push(`errors.${status}`)
254
+ return parts
255
+ }
256
+
136
257
  /** Whether every route in `lock` hashes to the empty-schema digest (so no route declares a schema). An
137
258
  * empty `routes` map is NOT vacuous in this sense - there is no route whose contract went unguarded. */
138
259
  export async function isVacuousLock(lock: ContractsLock): Promise<boolean> {
@@ -150,7 +271,11 @@ export async function buildContractsLock(
150
271
  const routes = Object.fromEntries(
151
272
  await Promise.all(
152
273
  reflected.map(
153
- async (route) => [`${route.method} ${route.path}`, await digestRoute(route)] as const,
274
+ async (route) =>
275
+ [
276
+ `${route.method} ${route.path}`,
277
+ { ...(await digestRoute(route)), parts: await contractParts(route) },
278
+ ] as const,
154
279
  ),
155
280
  ),
156
281
  )
@@ -192,13 +317,73 @@ export function validatesBeforeAuthentication(route: ReflectedRoute): boolean {
192
317
  return auth.length > 0 && auth.every((evidence) => evidence.source !== "nifra.authenticate")
193
318
  }
194
319
 
320
+ /** A route whose declared schema the lock records as `null` in `parts`. */
321
+ export interface UnreflectedRoute {
322
+ readonly route: string
323
+ readonly parts: readonly string[]
324
+ }
325
+
195
326
  export async function snapshotContracts(
196
327
  cwd: string,
197
328
  out = DEFAULT_CONTRACTS_LOCK,
198
329
  ): Promise<ContractsLock> {
199
- const lock = await buildContractsLock(await loadBackend(cwd))
330
+ return (await snapshotContractsReport(cwd, out)).lock
331
+ }
332
+
333
+ /** {@link snapshotContracts}, plus each route whose declared schema the lock records as `null`. */
334
+ export async function snapshotContractsReport(
335
+ cwd: string,
336
+ out = DEFAULT_CONTRACTS_LOCK,
337
+ ): Promise<{ lock: ContractsLock; unreflected: UnreflectedRoute[] }> {
338
+ const evidence = snapshotProjectEvidence(await loadBackend(cwd))
339
+ const lock = await buildContractsLock(undefined, evidence)
200
340
  await Bun.write(resolve(cwd, out), `${JSON.stringify(lock, null, 2)}\n`)
201
- return lock
341
+ const unreflected = reflectedRoutesFromEvidence(evidence)
342
+ .map((route) => ({ route: `${route.method} ${route.path}`, parts: unreflectedParts(route) }))
343
+ .filter((entry) => entry.parts.length > 0)
344
+ .sort((a, b) => codeUnitOrder(a.route, b.route))
345
+ return { lock, unreflected }
346
+ }
347
+
348
+ /** The lock entries of `lock` whose request or response digest says that side was never guarded. */
349
+ export async function blindLockEntries(
350
+ lock: ContractsLock,
351
+ ): Promise<Array<{ route: string; sides: Array<"request" | "response"> }>> {
352
+ const blind = await blindDigests()
353
+ const entries: Array<{ route: string; sides: Array<"request" | "response"> }> = []
354
+ for (const [route, digest] of Object.entries(lock.routes)) {
355
+ const sides = (["request", "response"] as const).filter((side) => blind[side].has(digest[side]))
356
+ if (sides.length > 0) entries.push({ route, sides })
357
+ }
358
+ return entries
359
+ }
360
+
361
+ function parseFields(value: unknown): Record<string, string> | undefined {
362
+ const record = recordOf(value)
363
+ if (record === undefined) return undefined
364
+ const fields: Array<[string, string]> = []
365
+ for (const [name, label] of Object.entries(record)) {
366
+ if (typeof label !== "string") return undefined
367
+ fields.push([name, label])
368
+ }
369
+ return Object.fromEntries(fields)
370
+ }
371
+
372
+ function parseParts(route: string, value: unknown): Record<string, ContractPart> {
373
+ const record = recordOf(value)
374
+ if (record === undefined) throw new TypeError(`invalid contract parts for ${route}`)
375
+ const parts: Array<[string, ContractPart]> = []
376
+ for (const [name, raw] of Object.entries(record)) {
377
+ const part = recordOf(raw)
378
+ const digest = part?.digest
379
+ if (digest !== null && !(typeof digest === "string" && DIGEST.test(digest)))
380
+ throw new TypeError(`invalid contract part ${name} for ${route}`)
381
+ const fields = part?.fields === undefined ? undefined : parseFields(part.fields)
382
+ if (part?.fields !== undefined && fields === undefined)
383
+ throw new TypeError(`invalid contract part ${name} fields for ${route}`)
384
+ parts.push([name, fields === undefined ? { digest } : { digest, fields }])
385
+ }
386
+ return Object.fromEntries(parts)
202
387
  }
203
388
 
204
389
  export function parseContractsLock(value: unknown): ContractsLock {
@@ -225,18 +410,109 @@ export function parseContractsLock(value: unknown): ContractsLock {
225
410
  !DIGEST.test(response)
226
411
  )
227
412
  throw new TypeError(`invalid contract ${key}`)
228
- routes[key] = { request, response }
413
+ const parts = item?.parts === undefined ? undefined : parseParts(key, item.parts)
414
+ routes[key] = parts === undefined ? { request, response } : { request, response, parts }
229
415
  }
230
416
  return typeof digest === "number" ? { version: 1, digest, routes } : { version: 1, routes }
231
417
  }
232
418
 
419
+ /** One lock mismatch. `sides` names what differs for a `changed` or `newly-covered` route, and
420
+ * `parts` which declared parts, when the lock records them (empty when only an edited side digest
421
+ * moved). */
422
+ export interface ContractDiagnostic {
423
+ readonly route?: string
424
+ readonly kind?: "added" | "removed" | "changed" | "newly-covered"
425
+ readonly sides?: readonly ("request" | "response")[]
426
+ readonly parts?: readonly string[]
427
+ readonly message: string
428
+ }
429
+
430
+ const own = (record: Readonly<Record<string, string>>, key: string): string | undefined =>
431
+ Object.hasOwn(record, key) ? record[key] : undefined
432
+
433
+ /** `+ added: type, - removed: type, kept: was -> now` between two field summaries. */
434
+ function fieldChanges(
435
+ before: Readonly<Record<string, string>>,
436
+ after: Readonly<Record<string, string>>,
437
+ ): string[] {
438
+ const names = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort(codeUnitOrder)
439
+ const changes: string[] = []
440
+ for (const name of names) {
441
+ const was = own(before, name)
442
+ const now = own(after, name)
443
+ if (was === now) continue
444
+ if (was === undefined) changes.push(`+ ${name}: ${now}`)
445
+ else if (now === undefined) changes.push(`- ${name}: ${was}`)
446
+ else changes.push(`${name}: ${was} -> ${now}`)
447
+ }
448
+ return changes
449
+ }
450
+
451
+ interface PartDrift {
452
+ readonly part: string
453
+ /** Locked as `null` and read now: the lock never guarded it. */
454
+ readonly uncovered: boolean
455
+ readonly detail: string
456
+ }
457
+
458
+ function partDrift(
459
+ before: Readonly<Record<string, ContractPart>>,
460
+ after: Readonly<Record<string, ContractPart>>,
461
+ ): PartDrift[] {
462
+ const names = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort(partOrder)
463
+ const drift: PartDrift[] = []
464
+ for (const part of names) {
465
+ const was = Object.hasOwn(before, part) ? before[part] : undefined
466
+ const now = Object.hasOwn(after, part) ? after[part] : undefined
467
+ if (was?.digest === now?.digest) continue
468
+ if (was === undefined || now === undefined) {
469
+ const added = now === undefined ? [] : fieldChanges({}, now.fields ?? {})
470
+ drift.push({
471
+ part,
472
+ uncovered: false,
473
+ detail:
474
+ was !== undefined
475
+ ? `${part} no longer declared`
476
+ : now?.digest === null
477
+ ? `${part} declared, in a form nifra cannot read`
478
+ : `${part} ${["declared", ...added].join(", ")}`,
479
+ })
480
+ continue
481
+ }
482
+ if (was.digest === null) {
483
+ drift.push({ part, uncovered: true, detail: part })
484
+ continue
485
+ }
486
+ const fields =
487
+ now.digest === null || was.fields === undefined || now.fields === undefined
488
+ ? []
489
+ : fieldChanges(was.fields, now.fields)
490
+ drift.push({
491
+ part,
492
+ uncovered: false,
493
+ detail:
494
+ now.digest === null
495
+ ? `${part} now in a form nifra cannot read`
496
+ : fields.length > 0
497
+ ? `${part} ${fields.join(", ")}`
498
+ : was.fields !== undefined && now.fields !== undefined
499
+ ? `${part} changed below its top-level fields`
500
+ : `${part} changed`,
501
+ })
502
+ }
503
+ return drift
504
+ }
505
+
506
+ const sidesOf = (parts: readonly string[]): Array<"request" | "response"> =>
507
+ (["request", "response"] as const).filter((side) => parts.some((part) => sideOf(part) === side))
508
+
233
509
  export async function checkContractsLock(
234
510
  cwd: string,
235
511
  file = DEFAULT_CONTRACTS_LOCK,
236
512
  ): Promise<{
237
513
  present: boolean
238
514
  vacuous: boolean
239
- diagnostics: Array<{ route?: string; message: string }>
515
+ diagnostics: Array<ContractDiagnostic>
240
516
  /** `METHOD /path` of every route the backend serves, read when the lock made the check load it. */
241
517
  served?: readonly string[]
242
518
  /** `METHOD /path` of each route {@link validatesBeforeAuthentication} names, read alongside `served`. */
@@ -252,7 +528,7 @@ export async function checkContractsLock(
252
528
  const inputBeforeAuth = reflectedRoutesFromEvidence(evidence)
253
529
  .filter(validatesBeforeAuthentication)
254
530
  .map((route) => `${route.method} ${route.path}`)
255
- const diagnostics: Array<{ route?: string; message: string }> = []
531
+ const diagnostics: ContractDiagnostic[] = []
256
532
  // Digests of two formats never compare, so this still fails; it just names the real cause.
257
533
  if (parsed.digest !== undefined && parsed.digest !== CONTRACT_DIGEST_FORMAT) {
258
534
  const newer = parsed.digest > CONTRACT_DIGEST_FORMAT
@@ -261,21 +537,79 @@ export async function checkContractsLock(
261
537
  })
262
538
  return { present: true, vacuous, diagnostics, served, inputBeforeAuth }
263
539
  }
540
+ const blind = await blindDigests()
264
541
  const keys = new Set([...Object.keys(parsed.routes), ...Object.keys(current.routes)])
265
542
  for (const key of [...keys].sort()) {
266
543
  const before = parsed.routes[key]
267
544
  const after = current.routes[key]
268
- if (
269
- before === undefined ||
270
- after === undefined ||
271
- before.request !== after.request ||
272
- before.response !== after.response
273
- ) {
545
+ if (before === undefined || after === undefined) {
274
546
  diagnostics.push({
275
547
  route: key,
276
- message: `contract changed for ${key}; if intentional run \`nifra contracts snapshot\` and include the lock update in the same change.`,
548
+ kind: before === undefined ? "added" : "removed",
549
+ message:
550
+ before === undefined
551
+ ? `${key} is served but not in ${file}; if intentional run \`nifra contracts snapshot\` and include the lock update in the same change.`
552
+ : `${key} is in ${file} but no longer served; if intentional run \`nifra contracts snapshot\` and include the lock update in the same change.`,
277
553
  })
554
+ continue
278
555
  }
556
+ // Between two digests that guard nothing there is nothing to compare.
557
+ const sides = (["request", "response"] as const).filter(
558
+ (side) =>
559
+ before[side] !== after[side] &&
560
+ !(blind[side].has(before[side]) && blind[side].has(after[side])),
561
+ )
562
+ if (before.parts !== undefined && after.parts !== undefined) {
563
+ const drift = partDrift(before.parts, after.parts)
564
+ const changed = drift.filter((item) => !item.uncovered)
565
+ // A side digest that moved with no part to show for it (an edited lock) still fails.
566
+ const unexplained = sides.filter((side) => !drift.some((item) => sideOf(item.part) === side))
567
+ if (changed.length > 0 || unexplained.length > 0) {
568
+ const parts = changed.map((item) => item.part)
569
+ const changedSides = sidesOf(parts)
570
+ const all = (["request", "response"] as const).filter(
571
+ (side) => changedSides.includes(side) || unexplained.includes(side),
572
+ )
573
+ const detail =
574
+ changed.length > 0 ? `: ${changed.map((item) => item.detail).join("; ")}` : ""
575
+ diagnostics.push({
576
+ route: key,
577
+ kind: "changed",
578
+ sides: all,
579
+ parts,
580
+ message: `contract changed for ${key} (${all.join(" and ")})${detail}; if intentional run \`nifra contracts snapshot\` and include the lock update in the same change.`,
581
+ })
582
+ }
583
+ const uncovered = drift.filter((item) => item.uncovered).map((item) => item.part)
584
+ if (uncovered.length > 0)
585
+ diagnostics.push({
586
+ route: key,
587
+ kind: "newly-covered",
588
+ sides: sidesOf(uncovered),
589
+ parts: uncovered,
590
+ message: `${key} ${uncovered.join(", ")}: ${file} locked the schema declared there as null (nifra could not read it), and this nifra reads it, so the lock never guarded it. Review the schema, then run \`nifra contracts snapshot\` to start guarding it.`,
591
+ })
592
+ continue
593
+ }
594
+ if (sides.length === 0) continue
595
+ // The lock cannot tell an older nifra that could not read a schema from a route that declared
596
+ // none, so this still fails: passing it would leave the side unguarded until someone snapshots.
597
+ const uncovered = sides.filter((side) => blind[side].has(before[side]))
598
+ const changed = sides.filter((side) => !blind[side].has(before[side]))
599
+ if (changed.length > 0)
600
+ diagnostics.push({
601
+ route: key,
602
+ kind: "changed",
603
+ sides: changed,
604
+ message: `contract changed for ${key} (${changed.join(" and ")}); if intentional run \`nifra contracts snapshot\` and include the lock update in the same change.`,
605
+ })
606
+ if (uncovered.length > 0)
607
+ diagnostics.push({
608
+ route: key,
609
+ kind: "newly-covered",
610
+ sides: uncovered,
611
+ message: `${key} ${uncovered.join(" and ")}: ${file} records no schema there (the route declared none, or an older nifra could not read it), and the route now has one, so the lock never guarded it. Review the schema, then run \`nifra contracts snapshot\` to start guarding it.`,
612
+ })
279
613
  }
280
614
  if (diagnostics.length > 0 && parsed.digest === undefined) {
281
615
  diagnostics.push({
package/src/doctor.ts CHANGED
@@ -219,17 +219,18 @@ export interface DoctorResult {
219
219
  }
220
220
  /**
221
221
  * `file:` entries of the project's bun.lock whose recorded dependencies the linked package.json no
222
- * longer declares: Bun never refreshes them, so it installs a second copy under the linked package.
222
+ * longer declares: Bun 1.4.2 never refreshes them, so it installs a second copy under the linked package.
223
223
  * Advisory (never folded into `ok`). `lock` is the lockfile, relative to the project.
224
224
  */
225
225
  readonly staleLinkLocks?: { readonly lock: string; readonly entries: readonly StaleLinkLock[] }
226
226
  /**
227
227
  * Route files that export `keepAlive` in an app where nothing names its sign-in cookie: no
228
- * `@nifrajs/auth`, Better Auth or Auth.js dependency, no `identityCookies`, `rotateIdentityEpoch()`
229
- * or `identityChanged()`. A sign-out there may leave the previous visitor's kept pages. Advisory
230
- * (never folded into `ok`).
228
+ * `identityCookies`, `rotateIdentityEpoch()` or `identityChanged()`, and either no `@nifrajs/auth`,
229
+ * Better Auth or Auth.js dependency or a source file (`renamedIn`) that gives the session cookie a
230
+ * name of its own. A sign-out there may leave the previous visitor's kept pages. Advisory (never
231
+ * folded into `ok`).
231
232
  */
232
- readonly keepAliveIdentity?: { readonly routes: readonly string[] }
233
+ readonly keepAliveIdentity?: { readonly routes: readonly string[]; readonly renamedIn?: string }
233
234
  /** Static production-readiness evidence for the selected deploy target. */
234
235
  readonly readiness?: DoctorReadiness
235
236
  /** The explicit source boundary used by the dependency scan. */
@@ -781,7 +782,7 @@ async function collectDoctorReadiness(
781
782
  : configured(
782
783
  "graceful-lifecycle",
783
784
  "graceful lifecycle",
784
- /\bgracefulSignals\s*:\s*(?:true\b|\{)|\bonStop\s*\(/,
785
+ /\bgracefulSignals\s*:\s*(?:true\b|\{)|\bonStop(?:ping)?\s*\(/,
785
786
  ),
786
787
  ]
787
788
  return {
@@ -872,6 +873,11 @@ const KNOWN_AUTH_PACKAGES = [
872
873
  "next-auth",
873
874
  ]
874
875
  const IDENTITY_SIGNAL = /\b(?:identityCookies\s*:|rotateIdentityEpoch\s*\(|identityChanged\s*\()/
876
+ // A session cookie renamed outright: Better Auth's `advanced.cookies.session_token.name`, Auth.js's
877
+ // `cookies.sessionToken.name`, `@nifrajs/auth`'s `cookieName`. A Better Auth `cookiePrefix` keeps the
878
+ // suffix the identity epoch matches, so it is not one.
879
+ const RENAMED_SESSION =
880
+ /\b(?:session_token|sessionToken)\s*:\s*\{[^}]*\bname\s*:|\bcookieName\s*:\s*["'`]/
875
881
 
876
882
  function keepAliveRoutes(cwd: string): readonly string[] {
877
883
  const routesDir = join(cwd, "routes")
@@ -898,6 +904,7 @@ export async function collectDoctorResult(
898
904
  const findings: DoctorFinding[] = []
899
905
  const manifestLists: ManifestList[] = []
900
906
  let identitySignal = false
907
+ let renamedIn: string | undefined
901
908
  // A standalone app owns its tests, so they remain in the declaration check. A workspace root owns
902
909
  // the published package source while its root devDependencies intentionally own shared tests,
903
910
  // benchmarks, and scaffold copy-surfaces. Keep that boundary explicit instead of reporting a
@@ -930,6 +937,7 @@ export async function collectDoctorResult(
930
937
  }
931
938
  manifestLists.push(...manifestListsIn(rel, content))
932
939
  if (!identitySignal && IDENTITY_SIGNAL.test(content)) identitySignal = true
940
+ if (renamedIn === undefined && RENAMED_SESSION.test(content)) renamedIn = rel
933
941
  },
934
942
  { includeTests: scanScope.includeTests, ignore: workspaceSurface },
935
943
  )
@@ -950,10 +958,15 @@ export async function collectDoctorResult(
950
958
  const lockDir = bunLockDir(cwd)
951
959
  const linkLocks = lockDir === undefined ? [] : staleLinkLocks(lockDir)
952
960
  const handBuilt = handBuiltManifests(cwd, manifestLists)
961
+ const knownAuth = KNOWN_AUTH_PACKAGES.some((name) => dependencySpec(pkg, name) !== undefined)
953
962
  const unnamedIdentity =
954
- identitySignal || KNOWN_AUTH_PACKAGES.some((name) => dependencySpec(pkg, name) !== undefined)
955
- ? []
956
- : keepAliveRoutes(cwd)
963
+ identitySignal || (knownAuth && renamedIn === undefined) ? [] : keepAliveRoutes(cwd)
964
+ const keepAliveIdentity =
965
+ unnamedIdentity.length === 0
966
+ ? undefined
967
+ : knownAuth && renamedIn !== undefined
968
+ ? { routes: unnamedIdentity, renamedIn }
969
+ : { routes: unnamedIdentity }
957
970
  // `staleDists`, `toolingDrift` and `staleMcpPins` are advisory (see DoctorResult): they never fail `ok`.
958
971
  return {
959
972
  ok:
@@ -973,7 +986,7 @@ export async function collectDoctorResult(
973
986
  ...(toolingDrift !== undefined ? { toolingDrift } : {}),
974
987
  ...(versionDrift !== undefined ? { versionDrift } : {}),
975
988
  ...(handBuilt.length > 0 ? { handBuiltManifests: handBuilt } : {}),
976
- ...(unnamedIdentity.length > 0 ? { keepAliveIdentity: { routes: unnamedIdentity } } : {}),
989
+ ...(keepAliveIdentity !== undefined ? { keepAliveIdentity } : {}),
977
990
  ...(staleMcpPins !== undefined && staleMcpPins.files.length > 0 ? { staleMcpPins } : {}),
978
991
  ...(lockDir !== undefined && linkLocks.length > 0
979
992
  ? {
@@ -1182,9 +1195,12 @@ export function doctorReport(result: DoctorResult, cliVersion?: string): string[
1182
1195
  lines.push(`⚠ ${handBuiltManifestMessage(finding)}\n`)
1183
1196
  }
1184
1197
  if (result.keepAliveIdentity !== undefined) {
1198
+ const { routes, renamedIn } = result.keepAliveIdentity
1185
1199
  lines.push(
1186
- `⚠ ${result.keepAliveIdentity.routes.join(", ")} keep pages alive, and nothing names this app's sign-in cookie (no @nifrajs/auth, Better Auth or Auth.js, no identityCookies): a sign-out may leave the previous visitor's pages one back away`,
1187
- " fix: name the session cookie in createWebApp({ keepAlive: { identityCookies } }), or call identityChanged() from @nifrajs/web/client for token auth - /docs/keep-alive#sign-in\n",
1200
+ renamedIn === undefined
1201
+ ? `⚠ ${routes.join(", ")} keep pages alive, and nothing names this app's sign-in cookie (no @nifrajs/auth, Better Auth or Auth.js, no identityCookies): a sign-out may leave the previous visitor's pages one back away`
1202
+ : `⚠ ${routes.join(", ")} keep pages alive, and ${renamedIn} renames the session cookie, which nifra knows only by its default name (no identityCookies): a sign-out may leave the previous visitor's pages one back away`,
1203
+ " fix: name the session cookie in keepAlive.identityCookies - exported from backend/framework.ts, or passed to createWebApp in a server you write - or call identityChanged() from @nifrajs/web/client for token auth - /docs/keep-alive#sign-in\n",
1188
1204
  )
1189
1205
  }
1190
1206
  // Advisory: the agent's MCP server is launched from these pins, so a stale one answers for an old
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Paths git considers ignored under `cwd`, in ONE batched `git check-ignore` call - so `.gitignore`
3
+ * (root + nested + the global excludesfile) is honoured, not just a built-in list. This keeps a scan out
4
+ * of generated trees and other copies that live under a repo but aren't the project: a
5
+ * monorepo that gitignores `builder/projects/` (238 generated apps) would otherwise be walked in full.
6
+ * Tracked files are never reported, whatever a pattern says. Returns an EMPTY set when there's no git /
7
+ * not a repo / git errors, so the caller degrades to its own list - never throws, never blocks.
8
+ */
9
+ export async function gitIgnored(cwd: string, rels: readonly string[]): Promise<Set<string>> {
10
+ if (rels.length === 0) return new Set()
11
+ try {
12
+ const proc = Bun.spawn(["git", "check-ignore", "--stdin", "-z"], {
13
+ cwd,
14
+ stdin: "pipe",
15
+ stdout: "pipe",
16
+ stderr: "ignore",
17
+ })
18
+ proc.stdin.write(`${rels.join("\0")}\0`)
19
+ await proc.stdin.end()
20
+ // -z keeps both directions literal: Git otherwise C-quotes Unicode/escapes on output and
21
+ // interprets quoted input. Only matching paths are emitted; exit 1 means none matched.
22
+ const out = await new Response(proc.stdout).text()
23
+ await proc.exited
24
+ return ignoredOf(out)
25
+ } catch {
26
+ return new Set()
27
+ }
28
+ }
29
+
30
+ /** {@link gitIgnored} for a caller that cannot await. */
31
+ export function gitIgnoredSync(cwd: string, rels: readonly string[]): Set<string> {
32
+ if (rels.length === 0) return new Set()
33
+ try {
34
+ const result = Bun.spawnSync(["git", "check-ignore", "--stdin", "-z"], {
35
+ cwd,
36
+ stdin: new TextEncoder().encode(`${rels.join("\0")}\0`),
37
+ stdout: "pipe",
38
+ stderr: "ignore",
39
+ })
40
+ return ignoredOf(result.stdout.toString())
41
+ } catch {
42
+ return new Set()
43
+ }
44
+ }
45
+
46
+ const ignoredOf = (out: string): Set<string> =>
47
+ new Set(out.split("\0").filter((path) => path !== ""))