@nifrajs/cli 5.1.0 → 5.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 (201) hide show
  1. package/CHANGELOG.md +3211 -0
  2. package/README.md +3 -0
  3. package/dist/agent-files.d.ts +19 -11
  4. package/dist/agent-files.d.ts.map +1 -1
  5. package/dist/agent-files.js +26 -18
  6. package/dist/agent-files.js.map +1 -1
  7. package/dist/assure-hydration.d.ts.map +1 -1
  8. package/dist/assure-hydration.js +1 -0
  9. package/dist/assure-hydration.js.map +1 -1
  10. package/dist/assure.d.ts.map +1 -1
  11. package/dist/assure.js +14 -1
  12. package/dist/assure.js.map +1 -1
  13. package/dist/capabilities-tool.d.ts.map +1 -1
  14. package/dist/capabilities-tool.js +131 -45
  15. package/dist/capabilities-tool.js.map +1 -1
  16. package/dist/check-diagnostics.d.ts +5 -0
  17. package/dist/check-diagnostics.d.ts.map +1 -1
  18. package/dist/check-diagnostics.js +3 -0
  19. package/dist/check-diagnostics.js.map +1 -1
  20. package/dist/check-scan.d.ts.map +1 -1
  21. package/dist/check-scan.js +6 -3
  22. package/dist/check-scan.js.map +1 -1
  23. package/dist/check.d.ts.map +1 -1
  24. package/dist/check.js +52 -12
  25. package/dist/check.js.map +1 -1
  26. package/dist/cli.d.ts.map +1 -1
  27. package/dist/cli.js +23 -12
  28. package/dist/cli.js.map +1 -1
  29. package/dist/command-catalog.d.ts.map +1 -1
  30. package/dist/command-catalog.js +9 -5
  31. package/dist/command-catalog.js.map +1 -1
  32. package/dist/dev-bun-config.d.ts +6 -3
  33. package/dist/dev-bun-config.d.ts.map +1 -1
  34. package/dist/dev-bun-config.js +13 -10
  35. package/dist/dev-bun-config.js.map +1 -1
  36. package/dist/dev-feed-tool.d.ts +3 -2
  37. package/dist/dev-feed-tool.d.ts.map +1 -1
  38. package/dist/dev-feed-tool.js +26 -5
  39. package/dist/dev-feed-tool.js.map +1 -1
  40. package/dist/doctor.d.ts +15 -1
  41. package/dist/doctor.d.ts.map +1 -1
  42. package/dist/doctor.js +79 -61
  43. package/dist/doctor.js.map +1 -1
  44. package/dist/i18n-check.d.ts +11 -1
  45. package/dist/i18n-check.d.ts.map +1 -1
  46. package/dist/i18n-check.js +170 -17
  47. package/dist/i18n-check.js.map +1 -1
  48. package/dist/init-agents.d.ts +46 -6
  49. package/dist/init-agents.d.ts.map +1 -1
  50. package/dist/init-agents.js +193 -31
  51. package/dist/init-agents.js.map +1 -1
  52. package/dist/internal/project-specifiers.d.ts.map +1 -1
  53. package/dist/internal/project-specifiers.js +9 -1
  54. package/dist/internal/project-specifiers.js.map +1 -1
  55. package/dist/internal/source-facts.d.ts +6 -0
  56. package/dist/internal/source-facts.d.ts.map +1 -1
  57. package/dist/internal/source-facts.js +106 -0
  58. package/dist/internal/source-facts.js.map +1 -1
  59. package/dist/internal/workspace-packages.d.ts +22 -0
  60. package/dist/internal/workspace-packages.d.ts.map +1 -0
  61. package/dist/internal/workspace-packages.js +215 -0
  62. package/dist/internal/workspace-packages.js.map +1 -0
  63. package/dist/load.d.ts +7 -2
  64. package/dist/load.d.ts.map +1 -1
  65. package/dist/load.js +11 -2
  66. package/dist/load.js.map +1 -1
  67. package/dist/lock-links.d.ts +42 -0
  68. package/dist/lock-links.d.ts.map +1 -0
  69. package/dist/lock-links.js +144 -0
  70. package/dist/lock-links.js.map +1 -0
  71. package/dist/mcp-exec.d.ts.map +1 -1
  72. package/dist/mcp-exec.js +5 -2
  73. package/dist/mcp-exec.js.map +1 -1
  74. package/dist/mcp-http.js +1 -1
  75. package/dist/mcp-root.d.ts +6 -4
  76. package/dist/mcp-root.d.ts.map +1 -1
  77. package/dist/mcp-root.js +12 -8
  78. package/dist/mcp-root.js.map +1 -1
  79. package/dist/migrate-layout.d.ts +2 -1
  80. package/dist/migrate-layout.d.ts.map +1 -1
  81. package/dist/migrate-layout.js +434 -29
  82. package/dist/migrate-layout.js.map +1 -1
  83. package/dist/project-site.d.ts +7 -0
  84. package/dist/project-site.d.ts.map +1 -0
  85. package/dist/project-site.js +19 -0
  86. package/dist/project-site.js.map +1 -0
  87. package/dist/recipes/4.0.0.d.ts.map +1 -1
  88. package/dist/recipes/4.0.0.js +2 -0
  89. package/dist/recipes/4.0.0.js.map +1 -1
  90. package/dist/recipes/5.1.0.d.ts +9 -0
  91. package/dist/recipes/5.1.0.d.ts.map +1 -0
  92. package/dist/recipes/5.1.0.js +22 -0
  93. package/dist/recipes/5.1.0.js.map +1 -0
  94. package/dist/recipes/5.2.0.d.ts +10 -0
  95. package/dist/recipes/5.2.0.d.ts.map +1 -0
  96. package/dist/recipes/5.2.0.js +32 -0
  97. package/dist/recipes/5.2.0.js.map +1 -0
  98. package/dist/recipes/index.d.ts +3 -0
  99. package/dist/recipes/index.d.ts.map +1 -1
  100. package/dist/recipes/index.js +7 -0
  101. package/dist/recipes/index.js.map +1 -1
  102. package/dist/review.d.ts.map +1 -1
  103. package/dist/review.js +2 -0
  104. package/dist/review.js.map +1 -1
  105. package/dist/rule-explain.d.ts +26 -0
  106. package/dist/rule-explain.d.ts.map +1 -0
  107. package/dist/rule-explain.js +49 -0
  108. package/dist/rule-explain.js.map +1 -0
  109. package/dist/rules/codes.d.ts +2 -0
  110. package/dist/rules/codes.d.ts.map +1 -1
  111. package/dist/rules/codes.js +2 -0
  112. package/dist/rules/codes.js.map +1 -1
  113. package/dist/rules/contract-visibility.d.ts.map +1 -1
  114. package/dist/rules/contract-visibility.js +93 -21
  115. package/dist/rules/contract-visibility.js.map +1 -1
  116. package/dist/rules/explanations.d.ts +14 -0
  117. package/dist/rules/explanations.d.ts.map +1 -0
  118. package/dist/rules/explanations.js +316 -0
  119. package/dist/rules/explanations.js.map +1 -0
  120. package/dist/rules/legacy.d.ts.map +1 -1
  121. package/dist/rules/legacy.js +24 -1
  122. package/dist/rules/legacy.js.map +1 -1
  123. package/dist/rules/merge-auth.d.ts +12 -0
  124. package/dist/rules/merge-auth.d.ts.map +1 -0
  125. package/dist/rules/merge-auth.js +52 -0
  126. package/dist/rules/merge-auth.js.map +1 -0
  127. package/dist/rules/pages.d.ts +27 -0
  128. package/dist/rules/pages.d.ts.map +1 -1
  129. package/dist/rules/pages.js +177 -2
  130. package/dist/rules/pages.js.map +1 -1
  131. package/dist/rules/routes.d.ts +3 -2
  132. package/dist/rules/routes.d.ts.map +1 -1
  133. package/dist/rules/routes.js +4 -3
  134. package/dist/rules/routes.js.map +1 -1
  135. package/dist/rules/zones.d.ts.map +1 -1
  136. package/dist/rules/zones.js +3 -2
  137. package/dist/rules/zones.js.map +1 -1
  138. package/dist/typecheck-coverage.d.ts +11 -0
  139. package/dist/typecheck-coverage.d.ts.map +1 -1
  140. package/dist/typecheck-coverage.js +50 -7
  141. package/dist/typecheck-coverage.js.map +1 -1
  142. package/dist/upgrade.d.ts +37 -1
  143. package/dist/upgrade.d.ts.map +1 -1
  144. package/dist/upgrade.js +171 -20
  145. package/dist/upgrade.js.map +1 -1
  146. package/dist/verification-plan.d.ts.map +1 -1
  147. package/dist/verification-plan.js +2 -0
  148. package/dist/verification-plan.js.map +1 -1
  149. package/dist/version-drift.d.ts.map +1 -1
  150. package/dist/version-drift.js +12 -1
  151. package/dist/version-drift.js.map +1 -1
  152. package/dist/web-app-options.d.ts +1 -1
  153. package/dist/web-app-options.d.ts.map +1 -1
  154. package/dist/web-app-options.js.map +1 -1
  155. package/docs/examples.json +19 -1
  156. package/docs/llms-full.txt +625 -130
  157. package/docs/types.json +396 -50
  158. package/package.json +13 -12
  159. package/src/agent-files.ts +27 -17
  160. package/src/assure-hydration.ts +1 -0
  161. package/src/assure.ts +11 -1
  162. package/src/capabilities-tool.ts +159 -50
  163. package/src/check-diagnostics.ts +8 -0
  164. package/src/check-scan.ts +9 -3
  165. package/src/check.ts +67 -12
  166. package/src/cli.ts +24 -11
  167. package/src/command-catalog.ts +16 -8
  168. package/src/dev-bun-config.ts +13 -9
  169. package/src/dev-feed-tool.ts +40 -6
  170. package/src/doctor.ts +102 -66
  171. package/src/i18n-check.ts +254 -18
  172. package/src/init-agents.ts +221 -41
  173. package/src/internal/project-specifiers.ts +9 -1
  174. package/src/internal/source-facts.ts +124 -0
  175. package/src/internal/workspace-packages.ts +218 -0
  176. package/src/load.ts +19 -3
  177. package/src/lock-links.ts +173 -0
  178. package/src/mcp-exec.ts +5 -2
  179. package/src/mcp-http.ts +1 -1
  180. package/src/mcp-root.ts +14 -8
  181. package/src/migrate-layout.ts +495 -31
  182. package/src/project-site.ts +18 -0
  183. package/src/recipes/4.0.0.ts +2 -0
  184. package/src/recipes/5.1.0.ts +23 -0
  185. package/src/recipes/5.2.0.ts +33 -0
  186. package/src/recipes/index.ts +7 -0
  187. package/src/review.ts +2 -0
  188. package/src/rule-explain.ts +75 -0
  189. package/src/rules/codes.ts +2 -0
  190. package/src/rules/contract-visibility.ts +118 -20
  191. package/src/rules/explanations.ts +329 -0
  192. package/src/rules/legacy.ts +24 -1
  193. package/src/rules/merge-auth.ts +55 -0
  194. package/src/rules/pages.ts +221 -2
  195. package/src/rules/routes.ts +4 -3
  196. package/src/rules/zones.ts +3 -2
  197. package/src/typecheck-coverage.ts +51 -6
  198. package/src/upgrade.ts +227 -22
  199. package/src/verification-plan.ts +6 -0
  200. package/src/version-drift.ts +15 -0
  201. package/src/web-app-options.ts +9 -1
@@ -29,9 +29,9 @@
29
29
  * a second nifra member arrives.
30
30
  */
31
31
 
32
- import type { Stats } from "node:fs"
33
- import { chmod, lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"
34
- import { isAbsolute, relative, resolve, sep } from "node:path"
32
+ import { readFileSync, type Stats } from "node:fs"
33
+ import { chmod, lstat, mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises"
34
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
35
35
  import {
36
36
  AGENT_POINTERS,
37
37
  AGENTS_MD_PATH,
@@ -63,10 +63,13 @@ export interface InitAgentsFileResult {
63
63
  export interface InitAgentsResult {
64
64
  readonly cwd: string
65
65
  readonly files: readonly InitAgentsFileResult[]
66
- /** Under --sync-mcp: the `@nifrajs/cli` version every pin was brought to. */
66
+ /** Under --sync-mcp: the `@nifrajs/cli` version every pin was brought to, or {@link UNPINNED}. */
67
67
  readonly syncedTo?: string
68
68
  }
69
69
 
70
+ /** `syncedTo` when every launch was unpinned to follow the project's installed CLI. */
71
+ export const UNPINNED = "installed"
72
+
70
73
  export interface InitAgentsOptions {
71
74
  /** Overwrite an existing `.mcp.json` / `CLAUDE.md` / `.cursor/mcp.json` instead of skipping it. */
72
75
  readonly force?: boolean
@@ -182,12 +185,12 @@ async function atomicWrite(
182
185
  * `--force` is irrelevant here - we never overwrite the user's existing guidance. The structure section
183
186
  * is for an app with `routes/`; an API-only app has no frontend to keep apart.
184
187
  */
185
- async function ensureAgentsMd(cwd: string): Promise<InitAgentsFileResult> {
188
+ async function ensureAgentsMd(cwd: string, pin?: string): Promise<InitAgentsFileResult> {
186
189
  const abs = safeJoin(cwd, AGENTS_MD_PATH)
187
190
  await assertSafeParents(cwd, abs)
188
191
  const irregular = await nonRegularTarget(abs, AGENTS_MD_PATH)
189
192
  if (irregular !== undefined) return irregular
190
- const sections = [{ heading: "## MCP server", text: agentsMcpSection() }]
193
+ const sections = [{ heading: "## MCP server", text: agentsMcpSection(pin) }]
191
194
  if (await isDirectory(safeJoin(cwd, "routes"))) {
192
195
  sections.push({ heading: STRUCTURE_HEADING, text: agentsStructureSection() })
193
196
  }
@@ -225,11 +228,12 @@ const isDirectory = (path: string): Promise<boolean> =>
225
228
  /** An exact version: the only pin --sync-mcp rewrites. A dist-tag or a range is a deliberate choice,
226
229
  * not a scaffold-time freeze. Prerelease and build suffixes are part of the version. */
227
230
  const PIN_VERSION = String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?`
228
- /** The pin as both MCP registries hold it: one JSON string in the server's `args`. */
229
- const JSON_PIN = new RegExp(`"@nifrajs/cli@(${PIN_VERSION})"`, "g")
230
- /** The pin as the markdown quotes it: the whole launch command, so prose that merely mentions a
231
- * version (an upgrade note, a changelog line) is never touched. */
232
- const LAUNCH_PIN = new RegExp(`${MCP_SERVER_COMMAND} @nifrajs/cli@(${PIN_VERSION}) mcp`, "g")
231
+ /** The launch as both MCP registries hold it: one JSON string in the server's `args`, pinned (group 1
232
+ * is the version) or unpinned, which follows the project's install. */
233
+ const JSON_PIN = new RegExp(`"@nifrajs/cli(?:@(${PIN_VERSION}))?"`, "g")
234
+ /** The launch as the markdown quotes it: the whole command, so prose that merely mentions a version
235
+ * (an upgrade note, a changelog line) is never touched. */
236
+ const LAUNCH_PIN = new RegExp(`${MCP_SERVER_COMMAND} @nifrajs/cli(?:@(${PIN_VERSION}))? mcp`, "g")
233
237
 
234
238
  /** The one nifra workspace member `cwd` resolves to, as a POSIX path relative to it, when `cwd` is a
235
239
  * workspace root and not itself a nifra project. */
@@ -238,9 +242,13 @@ async function workspaceMember(cwd: string): Promise<string | undefined> {
238
242
  return state.source === "workspace" ? relative(cwd, state.root).split(sep).join("/") : undefined
239
243
  }
240
244
 
241
- /** The registries' launch args when they name no directory: `["@nifrajs/cli@x.y.z", "mcp"]`. Group 2
242
- * is the whitespace between the two, reused before the member so the file keeps its own layout. */
243
- const JSON_BARE_LAUNCH = new RegExp(`("@nifrajs/cli@${PIN_VERSION}"\\s*,(\\s*)"mcp")(\\s*\\])`, "g")
245
+ /** The registries' launch args when they name no directory: `["@nifrajs/cli@x.y.z", "mcp"]`, pinned or
246
+ * not. Group 2 is the whitespace between the two, reused before the member so the file keeps its own
247
+ * layout. */
248
+ const JSON_BARE_LAUNCH = new RegExp(
249
+ `("@nifrajs/cli(?:@${PIN_VERSION})?"\\s*,(\\s*)"mcp")(\\s*\\])`,
250
+ "g",
251
+ )
244
252
 
245
253
  /** Add `member` after a bare `"mcp"` launch arg; a launch that already names a directory is left alone. */
246
254
  function nameMember(
@@ -261,7 +269,7 @@ function nameMember(
261
269
  export interface PinScan {
262
270
  /** The input with every stale pin rewritten - every other character untouched. */
263
271
  readonly text: string
264
- /** Pins found, current or stale. */
272
+ /** Launches found, pinned or not, current or stale. */
265
273
  readonly pins: number
266
274
  /** The distinct stale versions, in order of appearance. */
267
275
  readonly stale: readonly string[]
@@ -269,21 +277,26 @@ export interface PinScan {
269
277
  readonly named?: string
270
278
  }
271
279
 
272
- function repin(text: string, pattern: RegExp, target: string): PinScan {
280
+ /**
281
+ * Move every pinned launch to `target`, or unpin it when `target` is `null` (the project installs the
282
+ * CLI, so the launch follows that install). An unpinned launch is already current: it is never pinned
283
+ * again, since dropping the pin was a choice.
284
+ */
285
+ function repin(text: string, pattern: RegExp, target: string | null): PinScan {
273
286
  let pins = 0
274
287
  const stale: string[] = []
275
- const rewritten = text.replace(pattern, (match: string, version: string) => {
288
+ const rewritten = text.replace(pattern, (match: string, version: string | undefined) => {
276
289
  pins++
277
- if (version === target) return match
290
+ if (version === undefined || version === target) return match
278
291
  if (!stale.includes(version)) stale.push(version)
279
- return match.replace(`@${version}`, () => `@${target}`)
292
+ return match.replace(`@${version}`, () => (target === null ? "" : `@${target}`))
280
293
  })
281
294
  return { text: rewritten, pins, stale }
282
295
  }
283
296
 
284
297
  /** AGENTS.md is the user's file: only its `## MCP server` section - the heading up to the next `#` or
285
298
  * `##` heading, or the end of the file - is ours to re-pin. */
286
- function repinMcpSection(text: string, target: string): PinScan {
299
+ function repinMcpSection(text: string, target: string | null): PinScan {
287
300
  const heading = /^## MCP server\b.*$/m.exec(text)
288
301
  if (heading === null) return { text, pins: 0, stale: [] }
289
302
  const start = heading.index + heading[0].length
@@ -295,7 +308,7 @@ function repinMcpSection(text: string, target: string): PinScan {
295
308
 
296
309
  /** An MCP registry: its pin, and at a workspace root the member its launch names. Only the registries
297
310
  * launch the server, so the markdown launch commands keep their wording. */
298
- function repinRegistry(text: string, target: string, member?: string): PinScan {
311
+ function repinRegistry(text: string, target: string | null, member?: string): PinScan {
299
312
  const scan = repin(text, JSON_PIN, target)
300
313
  if (member === undefined || scan.pins === 0) return scan
301
314
  const { text: rewritten, named } = nameMember(scan.text, member)
@@ -306,7 +319,7 @@ function repinRegistry(text: string, target: string, member?: string): PinScan {
306
319
  * rewrite. */
307
320
  export const PIN_SITES: readonly {
308
321
  readonly path: string
309
- readonly repin: (text: string, target: string, member?: string) => PinScan
322
+ readonly repin: (text: string, target: string | null, member?: string) => PinScan
310
323
  }[] = [
311
324
  { path: MCP_JSON_PATH, repin: repinRegistry },
312
325
  { path: CURSOR_MCP_JSON_PATH, repin: repinRegistry },
@@ -329,7 +342,7 @@ type PinState =
329
342
  async function readPin(
330
343
  cwd: string,
331
344
  site: (typeof PIN_SITES)[number],
332
- target: string,
345
+ target: string | null,
333
346
  member?: string,
334
347
  ): Promise<PinState> {
335
348
  const abs = safeJoin(cwd, site.path)
@@ -348,13 +361,152 @@ async function readPin(
348
361
  // latin1 is one char per byte, so writing it back reproduces every byte outside a pin exactly,
349
362
  // whatever the file's encoding; the pin patterns are ASCII, so they match as they would in UTF-8.
350
363
  const scan = site.repin(await readFile(abs, "latin1"), target, member)
351
- if (scan.pins === 0) return { kind: "skip", note: "no pinned @nifrajs/cli launch command" }
364
+ if (scan.pins === 0) return { kind: "skip", note: "no @nifrajs/cli launch command" }
352
365
  if (scan.stale.length === 0 && scan.named === undefined) return { kind: "current" }
353
366
  return { kind: "stale", abs, mode: stat.mode & 0o777, scan }
354
367
  }
355
368
 
369
+ /** A pinned file above the project whose every nifra launch serves the project. */
370
+ export interface AncestorPinSite {
371
+ /** The directory that holds it. */
372
+ readonly dir: string
373
+ /** Where the file is, from the project directory, as reports name it (`../.mcp.json`). */
374
+ readonly path: string
375
+ /** The site it is, its `path` relative to `dir`. */
376
+ readonly site: (typeof PIN_SITES)[number]
377
+ /** The member a bare registry launch is given, as `init-agents` at that root would. */
378
+ readonly member: string
379
+ }
380
+
381
+ /** Pinned files above the project, split by whether a member's re-pin may rewrite them. */
382
+ export interface AncestorPins {
383
+ readonly owned: readonly AncestorPinSite[]
384
+ /** Pinned files that also launch something else, or that the scan could not attribute. */
385
+ readonly foreign: readonly { readonly path: string; readonly note: string }[]
386
+ }
387
+
388
+ const REGISTRY_PATHS: ReadonlySet<string> = new Set([MCP_JSON_PATH, CURSOR_MCP_JSON_PATH])
389
+ const LAUNCH_ARG = new RegExp(`^@nifrajs/cli(?:@${PIN_VERSION})?$`)
390
+
391
+ /** The directories above `dir`, nearest first, up to the repository root; none outside a repository. */
392
+ async function ancestorsToRepoRoot(dir: string): Promise<string[]> {
393
+ const out: string[] = []
394
+ for (let at = dir; (await lstatOrMissing(join(at, ".git"))) === undefined; ) {
395
+ const parent = dirname(at)
396
+ if (parent === at) return []
397
+ out.push(parent)
398
+ at = parent
399
+ }
400
+ return out
401
+ }
402
+
403
+ /** Whether a launch from `dir` that names no directory serves `project`, as `nifra mcp` resolves it. */
404
+ async function bareLaunchServes(dir: string, project: string): Promise<boolean> {
405
+ const state = await resolveRootState(dir, false)
406
+ return state.isProject && (await realpath(state.root).catch(() => state.root)) === project
407
+ }
408
+
409
+ /** Each pinned launch in an MCP registry: the directory it names, `null` for none, `undefined` for
410
+ * a pin not followed by `mcp`. The whole result is `undefined` when a pin sits outside any launch. */
411
+ function registryLaunches(text: string): (string | null | undefined)[] | undefined {
412
+ let parsed: unknown
413
+ try {
414
+ parsed = JSON.parse(text)
415
+ } catch {
416
+ return undefined
417
+ }
418
+ const servers: unknown = Reflect.get(Object(parsed), "mcpServers")
419
+ const launches: (string | null | undefined)[] = []
420
+ for (const entry of Object.values(Object(servers))) {
421
+ const args: unknown = Reflect.get(Object(entry), "args")
422
+ if (!Array.isArray(args)) continue
423
+ args.forEach((arg, i) => {
424
+ if (typeof arg !== "string" || !LAUNCH_ARG.test(arg)) return
425
+ const named: unknown = args[i + 2]
426
+ if (args[i + 1] !== "mcp") launches.push(undefined)
427
+ else launches.push(typeof named === "string" && !named.startsWith("-") ? named : null)
428
+ })
429
+ }
430
+ return [...text.matchAll(JSON_PIN)].length === launches.length ? launches : undefined
431
+ }
432
+
356
433
  /**
357
- * The version --sync-mcp pins to: the nifra the project installs, so the server an agent launches
434
+ * The pinned files above `cwd`, up to the repository root. A workspace root's registry launches
435
+ * `mcp <member>`, which is what `init-agents` writes there, so a member's re-pin has to reach it. A
436
+ * file is the member's to rewrite only when every nifra launch in it serves the member, resolved the
437
+ * way `nifra mcp` resolves it; a file that also serves another project is reported and left alone.
438
+ */
439
+ export async function ancestorPins(cwd: string): Promise<AncestorPins> {
440
+ const project = await realpath(cwd).catch(() => resolve(cwd))
441
+ const owned: AncestorPinSite[] = []
442
+ const foreign: { path: string; note: string }[] = []
443
+ for (const dir of await ancestorsToRepoRoot(project)) {
444
+ let bare: Promise<boolean> | undefined
445
+ const servesBare = () => (bare ??= bareLaunchServes(dir, project))
446
+ const launchServes = async (named: string | null | undefined): Promise<boolean> =>
447
+ named === undefined
448
+ ? false
449
+ : named === null
450
+ ? servesBare()
451
+ : (await realpath(resolve(dir, named)).catch(() => "")) === project
452
+ for (const site of PIN_SITES) {
453
+ const abs = join(dir, site.path)
454
+ const path = relative(project, abs).split(sep).join("/")
455
+ const stat = await lstatOrMissing(abs)
456
+ if (stat === undefined || stat.isDirectory()) continue
457
+ if (!stat.isFile()) {
458
+ foreign.push({ path, note: "not a regular file - left alone" })
459
+ continue
460
+ }
461
+ const text = await readFile(abs, "latin1")
462
+ let serves: boolean
463
+ if (REGISTRY_PATHS.has(site.path)) {
464
+ const launches = registryLaunches(text)
465
+ if (launches === undefined) {
466
+ foreign.push({ path, note: "holds a pin no launch accounts for - left alone" })
467
+ continue
468
+ }
469
+ if (launches.length === 0) continue
470
+ serves = true
471
+ for (const named of launches) if (!(await launchServes(named))) serves = false
472
+ } else {
473
+ if (site.repin(text, MCP_CLI_VERSION).pins === 0) continue
474
+ serves = await servesBare()
475
+ }
476
+ if (serves)
477
+ owned.push({ dir, path, site, member: relative(dir, project).split(sep).join("/") })
478
+ else foreign.push({ path, note: "its launch is not this project's alone - left alone" })
479
+ }
480
+ }
481
+ return { owned, foreign }
482
+ }
483
+
484
+ /** Whether the project at `dir` declares `@nifrajs/cli` in its own manifest, so `bunx` run there
485
+ * finds its install. */
486
+ export function declaresCli(dir: string): boolean {
487
+ try {
488
+ const manifest: unknown = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"))
489
+ return ["dependencies", "devDependencies", "optionalDependencies"].some((field) =>
490
+ Object.hasOwn(Object(Reflect.get(Object(manifest), field)), "@nifrajs/cli"),
491
+ )
492
+ } catch {
493
+ return false
494
+ }
495
+ }
496
+
497
+ /**
498
+ * What --sync-mcp and `nifra upgrade --write` move the project's own launches to: `null`, unpinned,
499
+ * when the project declares `@nifrajs/cli`, so the launch follows that install from then on; otherwise
500
+ * {@link mcpPinTarget}. Only the launch directory's own manifest counts: a workspace root whose member
501
+ * declares the CLI keeps the pin, since an isolated install puts no `nifra` bin at the root and bunx
502
+ * would fetch the latest release instead.
503
+ */
504
+ export async function mcpLaunchTarget(cwd: string): Promise<string | null> {
505
+ return declaresCli(cwd) ? null : mcpPinTarget(cwd)
506
+ }
507
+
508
+ /**
509
+ * The version a pinned launch moves to: the nifra the project installs, so the server an agent launches
358
510
  * describes the surface the code builds with. The running CLI's own version when nothing is
359
511
  * installed. Not simply the running CLI's version: the command that fixes a drifted server is run
360
512
  * by that drifted CLI, and it must not re-pin to itself.
@@ -369,7 +521,7 @@ export async function mcpPinTarget(cwd: string): Promise<string> {
369
521
  return memberInstalled?.version ?? MCP_CLI_VERSION
370
522
  }
371
523
 
372
- /** One file whose launch command pins a version other than {@link mcpPinTarget}. */
524
+ /** One file whose launch command pins a version other than {@link mcpLaunchTarget}. */
373
525
  export interface StaleMcpPin {
374
526
  readonly path: string
375
527
  readonly pinned: readonly string[]
@@ -378,38 +530,55 @@ export interface StaleMcpPin {
378
530
  /** Read-only: every agent file whose pinned `@nifrajs/cli` is not the one the project installs. */
379
531
  export async function collectStaleMcpPins(
380
532
  cwd: string,
381
- ): Promise<{ readonly target: string; readonly files: readonly StaleMcpPin[] }> {
382
- const target = await mcpPinTarget(cwd)
533
+ ): Promise<{ readonly target: string | null; readonly files: readonly StaleMcpPin[] }> {
534
+ const target = await mcpLaunchTarget(cwd)
383
535
  const files: StaleMcpPin[] = []
384
536
  for (const site of PIN_SITES) {
385
537
  const state = await readPin(cwd, site, target)
386
538
  if (state.kind === "stale") files.push({ path: site.path, pinned: state.scan.stale })
387
539
  }
540
+ // A launch above the project runs from that directory, so it stays pinned.
541
+ const pinned = target ?? (await mcpPinTarget(cwd))
542
+ for (const above of (await ancestorPins(cwd)).owned) {
543
+ const state = await readPin(above.dir, above.site, pinned)
544
+ if (state.kind === "stale") files.push({ path: above.path, pinned: state.scan.stale })
545
+ }
388
546
  return { target, files }
389
547
  }
390
548
 
391
549
  /** --sync-mcp: rewrite each stale pin to the project's version and touch nothing else. Creates no
392
550
  * file and appends no section - a file without a pin is reported, not repaired. */
393
551
  async function syncMcpPins(cwd: string): Promise<InitAgentsResult> {
394
- const target = await mcpPinTarget(cwd)
552
+ const target = await mcpLaunchTarget(cwd)
395
553
  const member = await workspaceMember(cwd)
396
554
  const files: InitAgentsFileResult[] = []
397
- for (const site of PIN_SITES) {
398
- const state = await readPin(cwd, site, target, member)
555
+ const sync = async (path: string, state: PinState, to: string | null): Promise<void> => {
399
556
  if (state.kind === "skip") {
400
- files.push({ path: site.path, action: "skipped", note: state.note })
557
+ files.push({ path, action: "skipped", note: state.note })
401
558
  } else if (state.kind === "current") {
402
- files.push({ path: site.path, action: "present", note: `already pinned to ${target}` })
559
+ files.push({
560
+ path,
561
+ action: "present",
562
+ note: to === null ? "already follows the installed CLI" : `already pinned to ${to}`,
563
+ })
403
564
  } else {
404
565
  await atomicWrite(state.abs, Buffer.from(state.scan.text, "latin1"), state.mode)
566
+ const moved = to ?? "the installed CLI (unpinned)"
405
567
  const notes = [
406
- ...(state.scan.stale.length > 0 ? [`${state.scan.stale.join(", ")} -> ${target}`] : []),
568
+ ...(state.scan.stale.length > 0 ? [`${state.scan.stale.join(", ")} -> ${moved}`] : []),
407
569
  ...(state.scan.named !== undefined ? [`launches \`mcp ${state.scan.named}\``] : []),
408
570
  ]
409
- files.push({ path: site.path, action: "synced", note: notes.join("; ") })
571
+ files.push({ path, action: "synced", note: notes.join("; ") })
410
572
  }
411
573
  }
412
- return { cwd, files, syncedTo: target }
574
+ for (const site of PIN_SITES)
575
+ await sync(site.path, await readPin(cwd, site, target, member), target)
576
+ const above = await ancestorPins(cwd)
577
+ const pinned = target ?? (await mcpPinTarget(cwd))
578
+ for (const site of above.owned)
579
+ await sync(site.path, await readPin(site.dir, site.site, pinned, site.member), pinned)
580
+ for (const { path, note } of above.foreign) files.push({ path, action: "skipped", note })
581
+ return { cwd, files, syncedTo: target ?? UNPINNED }
413
582
  }
414
583
 
415
584
  /**
@@ -429,26 +598,31 @@ export async function initAgents(
429
598
  }
430
599
  // Order: the two MCP registries and each agent's pointer (owned, no-clobber), then AGENTS.md (additive).
431
600
  const member = await workspaceMember(cwd)
432
- const registry = member === undefined ? mcpJson() : nameMember(mcpJson(), member).text
601
+ const pin = declaresCli(cwd) ? undefined : MCP_CLI_VERSION
602
+ const registry = member === undefined ? mcpJson(pin) : nameMember(mcpJson(pin), member).text
433
603
  const files: InitAgentsFileResult[] = []
434
604
  files.push(await writeOwned(cwd, MCP_JSON_PATH, registry, force))
435
605
  files.push(await writeOwned(cwd, CURSOR_MCP_JSON_PATH, registry, force))
436
606
  for (const pointer of AGENT_POINTERS) {
437
607
  files.push(await writeOwned(cwd, pointer.path, pointer.content(), force))
438
608
  }
439
- files.push(await ensureAgentsMd(cwd))
609
+ files.push(await ensureAgentsMd(cwd, pin))
440
610
  // A file the run left alone may still launch an old CLI. Say so where the file is reported, with
441
611
  // the command that fixes only that. Advisory: a file it cannot read costs the hint, not the run.
442
612
  const { target, files: stale } = await collectStaleMcpPins(cwd).catch(() => ({
443
613
  target: "",
444
614
  files: [] as readonly StaleMcpPin[],
445
615
  }))
616
+ const fix =
617
+ target === null
618
+ ? "`nifra init-agents --sync-mcp` unpins it to follow the installed CLI"
619
+ : `\`nifra init-agents --sync-mcp\` re-pins it to ${target}`
446
620
  return {
447
621
  cwd,
448
622
  files: files.map((file) => {
449
623
  const pin = stale.find((entry) => entry.path === file.path)
450
624
  if (pin === undefined || (file.action !== "skipped" && file.action !== "present")) return file
451
- const hint = `pinned to ${pin.pinned.join(", ")}; \`nifra init-agents --sync-mcp\` re-pins it to ${target}`
625
+ const hint = `pinned to ${pin.pinned.join(", ")}; ${fix}`
452
626
  return { ...file, note: file.note === undefined ? hint : `${file.note}; ${hint}` }
453
627
  }),
454
628
  }
@@ -469,9 +643,15 @@ export function renderInitAgents(result: InitAgentsResult): string {
469
643
  return ` ${ACTION_GLYPH[f.action]} ${f.path}${tail}`
470
644
  })
471
645
  if (result.syncedTo !== undefined) {
646
+ const launch =
647
+ result.syncedTo === UNPINNED
648
+ ? "runs the installed @nifrajs/cli (unpinned), so an upgrade needs no re-pin"
649
+ : `pins @nifrajs/cli@${result.syncedTo}`
472
650
  const footer = result.files.some((f) => f.action === "synced")
473
- ? `\nThe nifra MCP launch now pins @nifrajs/cli@${result.syncedTo}. Restart your agent so it respawns the server.`
474
- : `\nNothing to re-pin - no file pins a version other than @nifrajs/cli@${result.syncedTo}.`
651
+ ? `\nThe nifra MCP launch now ${launch}. Restart your agent so it respawns the server.`
652
+ : result.syncedTo === UNPINNED
653
+ ? "\nNothing to re-pin - every launch already follows the installed @nifrajs/cli."
654
+ : `\nNothing to re-pin - no file pins a version other than @nifrajs/cli@${result.syncedTo}.`
475
655
  return `nifra init-agents --sync-mcp\n\n${lines.join("\n")}\n${footer}`
476
656
  }
477
657
  const wroteAny = result.files.some((f) => f.action === "wrote" || f.action === "appended")
@@ -78,6 +78,14 @@ const IMPORT_EMIT_OPTIONS = [
78
78
  "preserveValueImports",
79
79
  ]
80
80
 
81
+ /** Whether the next character after whitespace closes an object or array: a scan, not a slice, so a
82
+ * large file with many commas stays linear. */
83
+ function closesNext(code: string, from: number): boolean {
84
+ let at = from
85
+ while (at < code.length && /\s/.test(code.charAt(at))) at += 1
86
+ return code[at] === "}" || code[at] === "]"
87
+ }
88
+
81
89
  /** JSON with comments and trailing commas, as tsconfig files are written. Throws on anything else. */
82
90
  export function parseJsonc(text: string): unknown {
83
91
  let code = ""
@@ -107,7 +115,7 @@ export function parseJsonc(text: string): unknown {
107
115
  while (end < code.length && code[end] !== '"') end += code[end] === "\\" ? 2 : 1
108
116
  json += code.slice(i, end + 1)
109
117
  i = end
110
- } else if (ch === "," && /^\s*[}\]]/.test(code.slice(i + 1))) {
118
+ } else if (ch === "," && closesNext(code, i + 1)) {
111
119
  } else json += ch
112
120
  }
113
121
  return JSON.parse(json.replace(/^\uFEFF/, ""))
@@ -36,6 +36,12 @@ export interface SourceFacts {
36
36
  path: string,
37
37
  ): boolean | undefined
38
38
  isResponseSyntaxAt(source: TSApi.SourceFile, position: number): boolean | undefined
39
+ /**
40
+ * Whether `position` lies in a route handler: a function passed to `.get("/path", …)` and the
41
+ * other method registrations, a function value of an `implement(contract, {...})` map, a local
42
+ * function either one names, or a local function a handler returns a call to (one hop).
43
+ */
44
+ isRouteHandlerAt(source: TSApi.SourceFile, position: number): boolean
39
45
  /** Whether the `import` keyword at `position` starts a runtime `import(specifier)` call (true) or a
40
46
  * type-position `import("…")` such as `typeof import("x")` (false); undefined when neither. */
41
47
  isDynamicImportAt(
@@ -82,6 +88,110 @@ function rawResponseExpression(ts: TypeScriptApi, node: TSApi.Expression): boole
82
88
  )
83
89
  }
84
90
 
91
+ const REGISTRATION_METHODS: ReadonlySet<string> = new Set([
92
+ "get",
93
+ "post",
94
+ "put",
95
+ "patch",
96
+ "delete",
97
+ "head",
98
+ "options",
99
+ "all",
100
+ ])
101
+
102
+ function unwrapExpression(ts: TypeScriptApi, node: TSApi.Expression): TSApi.Expression {
103
+ let current = node
104
+ while (
105
+ ts.isParenthesizedExpression(current) ||
106
+ ts.isAsExpression(current) ||
107
+ ts.isSatisfiesExpression(current) ||
108
+ ts.isAwaitExpression(current)
109
+ )
110
+ current = current.expression
111
+ return current
112
+ }
113
+
114
+ type FunctionNode =
115
+ | TSApi.ArrowFunction
116
+ | TSApi.FunctionExpression
117
+ | TSApi.FunctionDeclaration
118
+ | TSApi.MethodDeclaration
119
+
120
+ /** Every route handler of `source`, by the rules {@link SourceFacts.isRouteHandlerAt} states. */
121
+ function routeHandlers(ts: TypeScriptApi, source: TSApi.SourceFile): ReadonlySet<TSApi.Node> {
122
+ const isFunctionValue = (node: TSApi.Node): node is FunctionNode =>
123
+ ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isMethodDeclaration(node)
124
+ // Local functions by name; a name declared twice keeps both, which only ever adds findings.
125
+ const locals = new Map<string, FunctionNode[]>()
126
+ const declare = (name: string, fn: FunctionNode): void => {
127
+ locals.set(name, [...(locals.get(name) ?? []), fn])
128
+ }
129
+ const collect = (node: TSApi.Node): void => {
130
+ if (ts.isFunctionDeclaration(node) && node.name !== undefined) declare(node.name.text, node)
131
+ else if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {
132
+ const value = unwrapExpression(ts, node.initializer)
133
+ if (isFunctionValue(value)) declare(node.name.text, value)
134
+ }
135
+ ts.forEachChild(node, collect)
136
+ }
137
+ collect(source)
138
+
139
+ const handlers = new Set<TSApi.Node>()
140
+ const named = (expression: TSApi.Node): readonly FunctionNode[] => {
141
+ if (ts.isIdentifier(expression)) return locals.get(expression.text) ?? []
142
+ return isFunctionValue(expression) ? [expression] : []
143
+ }
144
+ const find = (node: TSApi.Node): void => {
145
+ if (ts.isCallExpression(node)) {
146
+ const callee = node.expression
147
+ const method = ts.isPropertyAccessExpression(callee) ? callee.name.text : undefined
148
+ const [first, ...rest] = node.arguments
149
+ if (
150
+ method !== undefined &&
151
+ REGISTRATION_METHODS.has(method) &&
152
+ first !== undefined &&
153
+ (ts.isStringLiteralLike(first) || ts.isTemplateExpression(first))
154
+ ) {
155
+ for (const argument of rest)
156
+ for (const fn of named(unwrapExpression(ts, argument))) handlers.add(fn)
157
+ }
158
+ const implement =
159
+ (ts.isIdentifier(callee) && callee.text === "implement") || method === "implement"
160
+ const map =
161
+ node.arguments[1] === undefined ? undefined : unwrapExpression(ts, node.arguments[1])
162
+ if (implement && map !== undefined && ts.isObjectLiteralExpression(map)) {
163
+ for (const property of map.properties) {
164
+ if (ts.isMethodDeclaration(property)) handlers.add(property)
165
+ else if (ts.isPropertyAssignment(property))
166
+ for (const fn of named(unwrapExpression(ts, property.initializer))) handlers.add(fn)
167
+ else if (ts.isShorthandPropertyAssignment(property))
168
+ for (const fn of locals.get(property.name.text) ?? []) handlers.add(fn)
169
+ }
170
+ }
171
+ }
172
+ ts.forEachChild(node, find)
173
+ }
174
+ find(source)
175
+
176
+ // One hop: a local function a handler returns a call to answers for that handler.
177
+ const returned = new Set<TSApi.Node>()
178
+ const follow = (node: TSApi.Node): void => {
179
+ const value =
180
+ ts.isReturnStatement(node) && node.expression !== undefined
181
+ ? node.expression
182
+ : ts.isArrowFunction(node) && !ts.isBlock(node.body)
183
+ ? node.body
184
+ : undefined
185
+ const call = value === undefined ? undefined : unwrapExpression(ts, value)
186
+ if (call !== undefined && ts.isCallExpression(call))
187
+ for (const fn of named(call.expression)) returned.add(fn)
188
+ ts.forEachChild(node, follow)
189
+ }
190
+ for (const handler of handlers) follow(handler)
191
+ for (const fn of returned) handlers.add(fn)
192
+ return handlers
193
+ }
194
+
85
195
  export interface SourceFactsOptions {
86
196
  /** Whether the compiler settings for a parsed file keep an import whose named specifiers are all
87
197
  * type-only (`verbatimModuleSyntax`). Without it such an import is erased. */
@@ -215,6 +325,19 @@ export function createSourceFacts(
215
325
  return false
216
326
  }
217
327
 
328
+ const handlersBySource = new WeakMap<TSApi.SourceFile, ReadonlySet<TSApi.Node>>()
329
+ const isRouteHandlerAt = (source: TSApi.SourceFile, position: number): boolean => {
330
+ let handlers = handlersBySource.get(source)
331
+ if (handlers === undefined) {
332
+ handlers = routeHandlers(ts, source)
333
+ handlersBySource.set(source, handlers)
334
+ }
335
+ return (
336
+ ancestorAt(ts, source, position, (node): node is TSApi.Node => handlers.has(node)) !==
337
+ undefined
338
+ )
339
+ }
340
+
218
341
  const isDynamicImportAt = (
219
342
  source: TSApi.SourceFile,
220
343
  position: number,
@@ -245,6 +368,7 @@ export function createSourceFacts(
245
368
  isRouteArgumentAt,
246
369
  isFunctionRouteCallAt,
247
370
  isResponseSyntaxAt,
371
+ isRouteHandlerAt,
248
372
  isDynamicImportAt,
249
373
  }
250
374
  }