@nifrajs/cli 5.1.0 → 5.3.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 (230) hide show
  1. package/CHANGELOG.md +3313 -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 +7 -2
  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 +5 -0
  19. package/dist/check-diagnostics.js.map +1 -1
  20. package/dist/check-scan.d.ts +9 -3
  21. package/dist/check-scan.d.ts.map +1 -1
  22. package/dist/check-scan.js +61 -21
  23. package/dist/check-scan.js.map +1 -1
  24. package/dist/check.d.ts.map +1 -1
  25. package/dist/check.js +55 -15
  26. package/dist/check.js.map +1 -1
  27. package/dist/cli.d.ts.map +1 -1
  28. package/dist/cli.js +37 -18
  29. package/dist/cli.js.map +1 -1
  30. package/dist/command-catalog.d.ts.map +1 -1
  31. package/dist/command-catalog.js +9 -5
  32. package/dist/command-catalog.js.map +1 -1
  33. package/dist/db-tool.d.ts.map +1 -1
  34. package/dist/db-tool.js +2 -1
  35. package/dist/db-tool.js.map +1 -1
  36. package/dist/dev-bun-config.d.ts +6 -3
  37. package/dist/dev-bun-config.d.ts.map +1 -1
  38. package/dist/dev-bun-config.js +13 -10
  39. package/dist/dev-bun-config.js.map +1 -1
  40. package/dist/dev-feed-tool.d.ts +3 -2
  41. package/dist/dev-feed-tool.d.ts.map +1 -1
  42. package/dist/dev-feed-tool.js +26 -5
  43. package/dist/dev-feed-tool.js.map +1 -1
  44. package/dist/doctor.d.ts +15 -1
  45. package/dist/doctor.d.ts.map +1 -1
  46. package/dist/doctor.js +79 -61
  47. package/dist/doctor.js.map +1 -1
  48. package/dist/env-file.d.ts.map +1 -1
  49. package/dist/env-file.js +41 -8
  50. package/dist/env-file.js.map +1 -1
  51. package/dist/i18n-check.d.ts +11 -1
  52. package/dist/i18n-check.d.ts.map +1 -1
  53. package/dist/i18n-check.js +170 -17
  54. package/dist/i18n-check.js.map +1 -1
  55. package/dist/init-agents.d.ts +46 -6
  56. package/dist/init-agents.d.ts.map +1 -1
  57. package/dist/init-agents.js +193 -31
  58. package/dist/init-agents.js.map +1 -1
  59. package/dist/internal/project-specifiers.d.ts.map +1 -1
  60. package/dist/internal/project-specifiers.js +9 -1
  61. package/dist/internal/project-specifiers.js.map +1 -1
  62. package/dist/internal/source-facts.d.ts +22 -0
  63. package/dist/internal/source-facts.d.ts.map +1 -1
  64. package/dist/internal/source-facts.js +322 -0
  65. package/dist/internal/source-facts.js.map +1 -1
  66. package/dist/internal/workspace-packages.d.ts +22 -0
  67. package/dist/internal/workspace-packages.d.ts.map +1 -0
  68. package/dist/internal/workspace-packages.js +215 -0
  69. package/dist/internal/workspace-packages.js.map +1 -0
  70. package/dist/load.d.ts +7 -2
  71. package/dist/load.d.ts.map +1 -1
  72. package/dist/load.js +11 -2
  73. package/dist/load.js.map +1 -1
  74. package/dist/lock-links.d.ts +42 -0
  75. package/dist/lock-links.d.ts.map +1 -0
  76. package/dist/lock-links.js +144 -0
  77. package/dist/lock-links.js.map +1 -0
  78. package/dist/mcp-exec.d.ts +1 -0
  79. package/dist/mcp-exec.d.ts.map +1 -1
  80. package/dist/mcp-exec.js +16 -5
  81. package/dist/mcp-exec.js.map +1 -1
  82. package/dist/mcp-http.js +1 -1
  83. package/dist/mcp-io.d.ts +23 -3
  84. package/dist/mcp-io.d.ts.map +1 -1
  85. package/dist/mcp-io.js +59 -12
  86. package/dist/mcp-io.js.map +1 -1
  87. package/dist/mcp-isolate.d.ts.map +1 -1
  88. package/dist/mcp-isolate.js +2 -1
  89. package/dist/mcp-isolate.js.map +1 -1
  90. package/dist/mcp-root.d.ts +6 -4
  91. package/dist/mcp-root.d.ts.map +1 -1
  92. package/dist/mcp-root.js +12 -8
  93. package/dist/mcp-root.js.map +1 -1
  94. package/dist/migrate-layout.d.ts +2 -1
  95. package/dist/migrate-layout.d.ts.map +1 -1
  96. package/dist/migrate-layout.js +435 -29
  97. package/dist/migrate-layout.js.map +1 -1
  98. package/dist/project-site.d.ts +7 -0
  99. package/dist/project-site.d.ts.map +1 -0
  100. package/dist/project-site.js +19 -0
  101. package/dist/project-site.js.map +1 -0
  102. package/dist/recipes/4.0.0.d.ts.map +1 -1
  103. package/dist/recipes/4.0.0.js +2 -0
  104. package/dist/recipes/4.0.0.js.map +1 -1
  105. package/dist/recipes/5.1.0.d.ts +9 -0
  106. package/dist/recipes/5.1.0.d.ts.map +1 -0
  107. package/dist/recipes/5.1.0.js +22 -0
  108. package/dist/recipes/5.1.0.js.map +1 -0
  109. package/dist/recipes/5.2.0.d.ts +10 -0
  110. package/dist/recipes/5.2.0.d.ts.map +1 -0
  111. package/dist/recipes/5.2.0.js +32 -0
  112. package/dist/recipes/5.2.0.js.map +1 -0
  113. package/dist/recipes/5.3.0.d.ts +11 -0
  114. package/dist/recipes/5.3.0.d.ts.map +1 -0
  115. package/dist/recipes/5.3.0.js +35 -0
  116. package/dist/recipes/5.3.0.js.map +1 -0
  117. package/dist/recipes/index.d.ts +3 -0
  118. package/dist/recipes/index.d.ts.map +1 -1
  119. package/dist/recipes/index.js +9 -0
  120. package/dist/recipes/index.js.map +1 -1
  121. package/dist/review.d.ts.map +1 -1
  122. package/dist/review.js +4 -0
  123. package/dist/review.js.map +1 -1
  124. package/dist/rule-explain.d.ts +26 -0
  125. package/dist/rule-explain.d.ts.map +1 -0
  126. package/dist/rule-explain.js +49 -0
  127. package/dist/rule-explain.js.map +1 -0
  128. package/dist/rules/codes.d.ts +4 -0
  129. package/dist/rules/codes.d.ts.map +1 -1
  130. package/dist/rules/codes.js +4 -0
  131. package/dist/rules/codes.js.map +1 -1
  132. package/dist/rules/contract-visibility.d.ts.map +1 -1
  133. package/dist/rules/contract-visibility.js +93 -21
  134. package/dist/rules/contract-visibility.js.map +1 -1
  135. package/dist/rules/explanations.d.ts +14 -0
  136. package/dist/rules/explanations.d.ts.map +1 -0
  137. package/dist/rules/explanations.js +326 -0
  138. package/dist/rules/explanations.js.map +1 -0
  139. package/dist/rules/legacy.d.ts.map +1 -1
  140. package/dist/rules/legacy.js +24 -1
  141. package/dist/rules/legacy.js.map +1 -1
  142. package/dist/rules/merge-auth.d.ts +12 -0
  143. package/dist/rules/merge-auth.d.ts.map +1 -0
  144. package/dist/rules/merge-auth.js +52 -0
  145. package/dist/rules/merge-auth.js.map +1 -0
  146. package/dist/rules/pages.d.ts +51 -0
  147. package/dist/rules/pages.d.ts.map +1 -1
  148. package/dist/rules/pages.js +293 -2
  149. package/dist/rules/pages.js.map +1 -1
  150. package/dist/rules/route-statement.d.ts +10 -0
  151. package/dist/rules/route-statement.d.ts.map +1 -0
  152. package/dist/rules/route-statement.js +150 -0
  153. package/dist/rules/route-statement.js.map +1 -0
  154. package/dist/rules/routes.d.ts +3 -2
  155. package/dist/rules/routes.d.ts.map +1 -1
  156. package/dist/rules/routes.js +4 -3
  157. package/dist/rules/routes.js.map +1 -1
  158. package/dist/rules/zones.d.ts.map +1 -1
  159. package/dist/rules/zones.js +3 -2
  160. package/dist/rules/zones.js.map +1 -1
  161. package/dist/typecheck-coverage.d.ts +11 -0
  162. package/dist/typecheck-coverage.d.ts.map +1 -1
  163. package/dist/typecheck-coverage.js +50 -7
  164. package/dist/typecheck-coverage.js.map +1 -1
  165. package/dist/upgrade.d.ts +80 -11
  166. package/dist/upgrade.d.ts.map +1 -1
  167. package/dist/upgrade.js +332 -65
  168. package/dist/upgrade.js.map +1 -1
  169. package/dist/verification-plan.d.ts.map +1 -1
  170. package/dist/verification-plan.js +2 -0
  171. package/dist/verification-plan.js.map +1 -1
  172. package/dist/version-drift.d.ts.map +1 -1
  173. package/dist/version-drift.js +12 -1
  174. package/dist/version-drift.js.map +1 -1
  175. package/dist/web-app-options.d.ts +1 -1
  176. package/dist/web-app-options.d.ts.map +1 -1
  177. package/dist/web-app-options.js.map +1 -1
  178. package/docs/examples.json +19 -1
  179. package/docs/llms-full.txt +716 -138
  180. package/docs/types.json +516 -74
  181. package/package.json +13 -12
  182. package/src/agent-files.ts +27 -17
  183. package/src/assure-hydration.ts +8 -1
  184. package/src/assure.ts +11 -1
  185. package/src/capabilities-tool.ts +159 -50
  186. package/src/check-diagnostics.ts +10 -0
  187. package/src/check-scan.ts +64 -19
  188. package/src/check.ts +75 -15
  189. package/src/cli.ts +38 -17
  190. package/src/command-catalog.ts +16 -8
  191. package/src/db-tool.ts +2 -0
  192. package/src/dev-bun-config.ts +13 -9
  193. package/src/dev-feed-tool.ts +40 -6
  194. package/src/doctor.ts +102 -66
  195. package/src/env-file.ts +42 -7
  196. package/src/i18n-check.ts +254 -18
  197. package/src/init-agents.ts +221 -41
  198. package/src/internal/project-specifiers.ts +9 -1
  199. package/src/internal/source-facts.ts +397 -0
  200. package/src/internal/workspace-packages.ts +218 -0
  201. package/src/load.ts +19 -3
  202. package/src/lock-links.ts +173 -0
  203. package/src/mcp-exec.ts +18 -4
  204. package/src/mcp-http.ts +1 -1
  205. package/src/mcp-io.ts +72 -12
  206. package/src/mcp-isolate.ts +2 -0
  207. package/src/mcp-root.ts +14 -8
  208. package/src/migrate-layout.ts +496 -31
  209. package/src/project-site.ts +18 -0
  210. package/src/recipes/4.0.0.ts +2 -0
  211. package/src/recipes/5.1.0.ts +23 -0
  212. package/src/recipes/5.2.0.ts +33 -0
  213. package/src/recipes/5.3.0.ts +36 -0
  214. package/src/recipes/index.ts +9 -0
  215. package/src/review.ts +4 -0
  216. package/src/rule-explain.ts +75 -0
  217. package/src/rules/codes.ts +4 -0
  218. package/src/rules/contract-visibility.ts +118 -20
  219. package/src/rules/explanations.ts +339 -0
  220. package/src/rules/legacy.ts +24 -1
  221. package/src/rules/merge-auth.ts +55 -0
  222. package/src/rules/pages.ts +381 -2
  223. package/src/rules/route-statement.ts +170 -0
  224. package/src/rules/routes.ts +4 -3
  225. package/src/rules/zones.ts +3 -2
  226. package/src/typecheck-coverage.ts +51 -6
  227. package/src/upgrade.ts +430 -70
  228. package/src/verification-plan.ts +6 -0
  229. package/src/version-drift.ts +15 -0
  230. package/src/web-app-options.ts +9 -1
package/src/upgrade.ts CHANGED
@@ -12,7 +12,9 @@
12
12
  * 2. **dependency moves** - replace removed packages with their supported successor without
13
13
  * reserializing package.json or leaving duplicate dependency keys.
14
14
  * 3. **import moves** - rewrite exact import specifiers to their updated module paths.
15
- * 4. **verify** - reuse the existing `nifra check` gate; no new verification surface.
15
+ * 4. **verify** - reuse the existing `nifra check` gate; no new verification surface. It reads the
16
+ * installed packages, so while the edited pins are not installed yet it is skipped with the
17
+ * install command to run first: a check then would judge the release being left.
16
18
  *
17
19
  * Upgrading across several releases runs every recipe between the installed version (the lowest
18
20
  * fixed-group version the workspace declares) and the target, oldest first, then pins the target. A
@@ -36,7 +38,7 @@ import {
36
38
  statSync,
37
39
  writeFileSync,
38
40
  } from "node:fs"
39
- import { dirname, join, relative, sep } from "node:path"
41
+ import { dirname, join, relative, resolve, sep } from "node:path"
40
42
  import { fileURLToPath } from "node:url"
41
43
  import type { ReflectedHookReport } from "@nifrajs/core/reflection"
42
44
  import { Glob } from "bun"
@@ -48,7 +50,15 @@ import {
48
50
  parseHookReport,
49
51
  renderHookDiff,
50
52
  } from "./hooks-report.ts"
51
- import { PIN_SITES } from "./init-agents.ts"
53
+ import { type AncestorPinSite, ancestorPins, declaresCli, PIN_SITES } from "./init-agents.ts"
54
+ import {
55
+ BUN_LOCK,
56
+ describeChange,
57
+ linkLockUpdate,
58
+ pruneLinkLocks,
59
+ type StaleLinkLock,
60
+ staleLinkLocks,
61
+ } from "./lock-links.ts"
52
62
  import { getRecipe, listRecipeVersions, type UpgradeRecipe } from "./recipes/index.ts"
53
63
  import { markerTarget } from "./rules/comment-markers.ts"
54
64
 
@@ -61,7 +71,8 @@ export interface UpgradeOptions {
61
71
  readonly json?: boolean
62
72
  /** Print the available target versions and return. */
63
73
  readonly list?: boolean
64
- /** After `--write`, run `nifra check` and fail the command if it fails. Default true. */
74
+ /** After `--write`, run `nifra check` and fail the command if it fails, once the install matches
75
+ * the target; until then, print the install command to run first. Default true. */
65
76
  readonly verify?: boolean
66
77
  /** Permit a target BELOW the installed version (a rollback). Default false → fail-closed. */
67
78
  readonly allowDowngrade?: boolean
@@ -74,6 +85,8 @@ export interface UpgradeOptions {
74
85
  * change in which hooks run where is visible. Loads the backend. Default true; `--no-hooks` skips it.
75
86
  */
76
87
  readonly hooks?: boolean
88
+ /** Proceed although a linked repository loads its own nifra at another version. Default false. */
89
+ readonly allowLinkedSkew?: boolean
77
90
  }
78
91
 
79
92
  export interface PinChange {
@@ -106,6 +119,8 @@ export interface AgentPinChange {
106
119
  readonly file: string
107
120
  /** The versions it pinned, in order of appearance. */
108
121
  readonly from: readonly string[]
122
+ /** The target version, or `unpinned` when the project declares `@nifrajs/cli`: the launch then runs
123
+ * that install and never needs re-pinning. */
109
124
  readonly to: string
110
125
  }
111
126
 
@@ -131,8 +146,16 @@ export interface UpgradePlan {
131
146
  readonly retiredMarkers: readonly RetiredMarkerSite[]
132
147
  /** Installed group packages linked from outside the workspace root, at another version. Never edited. */
133
148
  readonly linkedOutside: readonly LinkedGroupInstall[]
149
+ /** Repositories a `link:`/`file:` dependency points outside the root, each loading its own nifra at
150
+ * another version. Never edited; the upgrade refuses while any is listed. */
151
+ readonly linkedSkew: readonly LinkedSkew[]
134
152
  /** Other versions pinned outside package.json. Never edited. */
135
153
  readonly strayPins: readonly StrayPin[]
154
+ /** `file:` entries of the project's bun.lock whose recorded dependencies the linked package.json
155
+ * (as this upgrade leaves it) no longer declares. Bun never refreshes them on its own. */
156
+ readonly linkLocks: readonly StaleLinkLock[]
157
+ /** Whether `--write` dropped {@link linkLocks} from bun.lock, so `bun install` re-reads them. */
158
+ readonly lockPruned: boolean
136
159
  readonly notes: readonly string[]
137
160
  }
138
161
 
@@ -142,21 +165,29 @@ const DEP_FIELDS = [
142
165
  "peerDependencies",
143
166
  "optionalDependencies",
144
167
  ] as const
168
+ const PEER_FIELD = "peerDependencies"
145
169
 
146
170
  // Only a bare semver spec is rewritten. Anything else - workspace:*, link:/file:, npm: aliases, git
147
171
  // urls, "*", "latest", or a multi-part range - is intentionally left untouched (skipped, not guessed).
148
172
  const SEMVER_SPEC =
149
173
  /^([\^~]|>=|<=|>|<|=)?\s*(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/
150
174
 
175
+ const UPPER_BOUND = /^\s*<=?/
176
+
177
+ // A strict bound kept on the target would exclude it: `>5.2.0` → `>5.3.0` refuses 5.3.0.
178
+ const INCLUSIVE_OPERATOR: Readonly<Record<string, string>> = { ">": ">=", "<": "<=" }
179
+
151
180
  /**
152
- * Rewrite a dependency version spec to `toVersion`, preserving the range operator (`^`, `~`, …), or
153
- * dropping it when `exact`. Returns null when the spec is not a plain semver spec (→ skip it) or
154
- * already equals the target.
181
+ * Rewrite a dependency version spec to `toVersion`, preserving the range operator (`^`, `~`, …;
182
+ * a strict `>` or `<` becomes `>=` or `<=`, so the result admits the target), or dropping it when
183
+ * `exact`. Returns null when the spec is not a plain semver spec (→ skip it) or already equals the
184
+ * target.
155
185
  */
156
186
  export function rewriteVersionSpec(spec: string, toVersion: string, exact = false): string | null {
157
187
  const match = SEMVER_SPEC.exec(spec.trim())
158
188
  if (!match) return null
159
- const operator = exact ? "" : (match[1] ?? "")
189
+ const written = match[1] ?? ""
190
+ const operator = exact ? "" : (INCLUSIVE_OPERATOR[written] ?? written)
160
191
  const next = `${operator}${toVersion}`
161
192
  return next === spec ? null : next
162
193
  }
@@ -232,6 +263,48 @@ export function compareSemverSpec(a: string, b: string): number {
232
263
  return 0
233
264
  }
234
265
 
266
+ /**
267
+ * Whether a plain semver spec's range admits `version`, as npm reads it: `^` and `~` stop before the
268
+ * next breaking release, and a prerelease satisfies only a spec naming a prerelease of its own core.
269
+ * False for any other spec.
270
+ */
271
+ export function specIncludes(spec: string, version: string): boolean {
272
+ const match = SEMVER_SPEC.exec(spec.trim())
273
+ const target = parseSpecVersion(version)
274
+ const floor = specVersion(spec)
275
+ if (match === null || target === null || floor === null) return false
276
+ const core: readonly [number, number, number] = [
277
+ Number(match[2]),
278
+ Number(match[3]),
279
+ Number(match[4]),
280
+ ]
281
+ if (
282
+ target.prerelease.length > 0 &&
283
+ (match[5] === undefined || compareSemverCore(core, target.core) !== 0)
284
+ )
285
+ return false
286
+ const order = compareSemverSpec(version, floor)
287
+ switch (match[1]) {
288
+ case ">=":
289
+ return order >= 0
290
+ case ">":
291
+ return order > 0
292
+ case "<=":
293
+ return order <= 0
294
+ case "<":
295
+ return order < 0
296
+ case "^": {
297
+ const below: readonly [number, number, number] =
298
+ core[0] > 0 ? [core[0] + 1, 0, 0] : core[1] > 0 ? [0, core[1] + 1, 0] : [0, 0, core[2] + 1]
299
+ return order >= 0 && compareSemverCore(target.core, below) < 0
300
+ }
301
+ case "~":
302
+ return order >= 0 && compareSemverCore(target.core, [core[0], core[1] + 1, 0]) < 0
303
+ default:
304
+ return order === 0
305
+ }
306
+ }
307
+
235
308
  const escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
236
309
 
237
310
  /**
@@ -258,13 +331,21 @@ export function pinSweepText(
258
331
  let out = text
259
332
  const changes: Array<Omit<PinChange, "file">> = []
260
333
  const downgrades: Array<Omit<PinChange, "file">> = []
261
- for (const { path, key, target: name, spec: rawSpec } of pinEntries(parsed)) {
334
+ for (const { path, holder, key, target: name, spec: rawSpec } of pinEntries(parsed)) {
262
335
  const field = path.join(".")
263
336
  const rule = rules.find(
264
337
  (r) => name === r.match || (r.match.endsWith("/") && name.startsWith(r.match)),
265
338
  )
266
339
  if (!rule) continue
267
- const next = rewriteVersionSpec(rawSpec, rule.to, exact)
340
+ // A peer range states what a library accepts, not what installs: widening a floor that already
341
+ // admits the target would drop every consumer still on an older release, and an exact peer pin
342
+ // would admit one release only.
343
+ const peer = field === PEER_FIELD
344
+ if (peer && specIncludes(rawSpec, rule.to)) continue
345
+ // An upper bound has no floor to raise: one that admits the target (`<6.0.0`) stays as written,
346
+ // in every field, and is never read as a rollback.
347
+ if (UPPER_BOUND.test(rawSpec) && specIncludes(rawSpec, rule.to)) continue
348
+ const next = rewriteVersionSpec(rawSpec, rule.to, exact && !peer)
268
349
  if (next === null) continue
269
350
  // Refuse a rollback: `upgrade <version>` pins an exact target, so an OLD target on a newer install
270
351
  // walks dependencies backward (e.g. ^2.3.0 → ^2.0.0) and can break a shared-package peer range.
@@ -279,17 +360,14 @@ export function pinSweepText(
279
360
  downgrades.push({ field, name: key, from: rawSpec, to: next })
280
361
  continue
281
362
  }
282
- // Replace exactly `"key"<ws>:<ws>"spec"` inside this field's object, preserving the whitespace. A
283
- // nested `overrides` entry repeated with the same spec maps the same way, so every one is replaced.
284
- const range = objectRangeAt(out, path)
285
- if (range === undefined) continue
286
- const pattern = new RegExp(`("${escapeRegExp(key)}"\\s*:\\s*")${escapeRegExp(rawSpec)}(")`, "g")
287
- const body = out.slice(range.start, range.end)
288
- const replaced = body.replace(pattern, `$1${next}$2`)
289
- if (replaced !== body) {
290
- out = out.slice(0, range.start) + replaced + out.slice(range.end)
291
- changes.push({ field, name: key, from: rawSpec, to: next })
292
- }
363
+ // Replace exactly `"key"<ws>:<ws>"spec"` inside the object holding this pin, preserving the
364
+ // whitespace: npm's nested `{ ".": "5.2.0" }` under another package names that package.
365
+ const range = objectRangeAt(out, holder)
366
+ const at = range === undefined ? undefined : memberValueAt(out, range, key)
367
+ const written = JSON.stringify(rawSpec)
368
+ if (at === undefined || out.slice(at, at + written.length) !== written) continue
369
+ out = out.slice(0, at) + JSON.stringify(next) + out.slice(at + written.length)
370
+ changes.push({ field, name: key, from: rawSpec, to: next })
293
371
  }
294
372
  return { text: out, changes, downgrades }
295
373
  }
@@ -312,31 +390,41 @@ function overrideTarget(key: string): string {
312
390
  }
313
391
 
314
392
  /** Every string version spec a package.json declares for a package, with the field path it sits in. */
315
- function pinEntries(
316
- parsed: Record<string, unknown>,
317
- ): Array<{ path: readonly string[]; key: string; target: string; spec: string }> {
318
- const entries: Array<{ path: readonly string[]; key: string; target: string; spec: string }> = []
393
+ interface PinEntry {
394
+ /** The field the pin is reported under: a dependency field, or the override field it sits in. */
395
+ readonly path: readonly string[]
396
+ /** The object holding the pin, nested override parents included. */
397
+ readonly holder: readonly string[]
398
+ readonly key: string
399
+ readonly target: string
400
+ readonly spec: string
401
+ }
402
+
403
+ function pinEntries(parsed: Record<string, unknown>): PinEntry[] {
404
+ const entries: PinEntry[] = []
319
405
  for (const field of DEP_FIELDS) {
320
406
  const deps = parsed[field]
321
407
  if (typeof deps !== "object" || deps === null) continue
322
408
  for (const [name, spec] of Object.entries(deps))
323
- if (typeof spec === "string") entries.push({ path: [field], key: name, target: name, spec })
409
+ if (typeof spec === "string")
410
+ entries.push({ path: [field], holder: [field], key: name, target: name, spec })
324
411
  }
325
412
  for (const path of OVERRIDE_FIELDS) {
326
413
  let value: unknown = parsed
327
414
  for (const key of path)
328
415
  value = typeof value === "object" && value !== null ? Reflect.get(value, key) : undefined
329
416
  // npm nests an override under the package whose dependency it pins; `.` pins that package itself.
330
- const walk = (object: object, parent: string | undefined): void => {
417
+ const walk = (object: object, parent: string | undefined, holder: readonly string[]): void => {
331
418
  for (const [key, spec] of Object.entries(object)) {
332
419
  const target = key === "." ? parent : overrideTarget(key)
333
420
  if (typeof spec === "string" && target !== undefined)
334
- entries.push({ path, key, target, spec })
421
+ entries.push({ path, holder, key, target, spec })
335
422
  else if (typeof spec === "object" && spec !== null && !Array.isArray(spec))
336
- walk(spec, target)
423
+ walk(spec, target, [...holder, key])
337
424
  }
338
425
  }
339
- if (typeof value === "object" && value !== null && !Array.isArray(value)) walk(value, undefined)
426
+ if (typeof value === "object" && value !== null && !Array.isArray(value))
427
+ walk(value, undefined, path)
340
428
  }
341
429
  return entries
342
430
  }
@@ -387,6 +475,18 @@ function memberObjectRange(
387
475
  within: { start: number; end: number },
388
476
  key: string,
389
477
  ): { start: number; end: number } | undefined {
478
+ const at = memberValueAt(text, within, key)
479
+ return at !== undefined && text[at] === "{"
480
+ ? { start: at + 1, end: closingBrace(text, at) }
481
+ : undefined
482
+ }
483
+
484
+ /** Where `key`'s value starts among the direct members of the object body `within`. */
485
+ function memberValueAt(
486
+ text: string,
487
+ within: { start: number; end: number },
488
+ key: string,
489
+ ): number | undefined {
390
490
  let depth = 0
391
491
  for (let index = within.start; index < within.end; index++) {
392
492
  const char = text[index]
@@ -399,9 +499,7 @@ function memberObjectRange(
399
499
  if (depth === 0 && text[after] === ":" && text.slice(index + 1, close) === key) {
400
500
  after++
401
501
  while (/\s/.test(text[after] ?? "")) after++
402
- return text[after] === "{"
403
- ? { start: after + 1, end: closingBrace(text, after) }
404
- : undefined
502
+ return after
405
503
  }
406
504
  index = close
407
505
  }
@@ -578,10 +676,15 @@ export function groupDeclaredNames(cwd: string): ReadonlySet<string> {
578
676
 
579
677
  /**
580
678
  * Every fixed-group version the package.json files under `cwd` declare with a plain semver spec, each
581
- * with the files that declare it. An override counts: it decides what installs. `workspace:`, `link:`
582
- * and other non-semver specs are not versions.
679
+ * with the files that declare it. An override counts: it decides what installs. A peer range does
680
+ * not (`>=3.1.0` names a floor a library accepts, not a version anything loads), and `workspace:`,
681
+ * `link:` and other non-semver specs are not versions.
583
682
  */
584
683
  export function groupPinVersions(cwd: string): ReadonlyMap<string, readonly string[]> {
684
+ return groupSpecVersions(cwd, false)
685
+ }
686
+
687
+ function groupSpecVersions(cwd: string, peers: boolean): Map<string, string[]> {
585
688
  const versions = new Map<string, string[]>()
586
689
  for (const rel of scan(cwd, "**/package.json")) {
587
690
  let parsed: Record<string, unknown>
@@ -590,8 +693,8 @@ export function groupPinVersions(cwd: string): ReadonlyMap<string, readonly stri
590
693
  } catch {
591
694
  continue
592
695
  }
593
- for (const { target, spec } of pinEntries(parsed)) {
594
- if (!isFixedGroup(target)) continue
696
+ for (const { path, target, spec } of pinEntries(parsed)) {
697
+ if (!isFixedGroup(target) || (path[0] === PEER_FIELD) !== peers) continue
595
698
  const version = specVersion(spec)
596
699
  if (version === null) continue
597
700
  const files = versions.get(version) ?? []
@@ -688,20 +791,34 @@ function plainFileAt(cwd: string, rel: string): boolean {
688
791
  }
689
792
 
690
793
  /**
691
- * The MCP launch pin in each agent file at `cwd`, moved to `version`: the files and the edit of
692
- * `nifra init-agents --sync-mcp`, so an agent launches the nifra the project installs once it does.
794
+ * The MCP launch pin in each agent file at `cwd`, and in each file above it whose launches all serve
795
+ * it ({@link ancestorPins}), moved to `version`: the files and the edit of `nifra init-agents
796
+ * --sync-mcp`, so an agent launches the nifra the project installs once it does.
693
797
  */
694
798
  function agentPinEdits(
695
799
  cwd: string,
696
800
  version: string,
697
- ): Array<{ readonly change: AgentPinChange; readonly text: string }> {
698
- const edits: Array<{ change: AgentPinChange; text: string }> = []
699
- for (const site of PIN_SITES) {
700
- if (!plainFileAt(cwd, site.path)) continue
801
+ above: readonly AncestorPinSite[],
802
+ ): Array<{ readonly change: AgentPinChange; readonly text: string; readonly abs: string }> {
803
+ const target = declaresCli(cwd) ? null : version
804
+ const edits: Array<{ change: AgentPinChange; text: string; abs: string }> = []
805
+ const sites = [
806
+ ...PIN_SITES.map((site) => ({ dir: cwd, file: site.path, path: site.path, site })),
807
+ ...above.map((entry) => ({ ...entry, file: entry.site.path })),
808
+ ]
809
+ for (const { dir, file, path, site } of sites) {
810
+ if (!plainFileAt(dir, file)) continue
811
+ const abs = join(dir, file)
812
+ // A launch above the project runs from that directory, which need not see the install: it stays pinned.
813
+ const to = dir === cwd ? target : version
701
814
  // latin1 is one char per byte, so every byte outside a pin is written back as it was.
702
- const scan = site.repin(readFileSync(join(cwd, site.path), "latin1"), version)
815
+ const scan = site.repin(readFileSync(abs, "latin1"), to)
703
816
  if (scan.stale.length === 0) continue
704
- edits.push({ change: { file: site.path, from: scan.stale, to: version }, text: scan.text })
817
+ edits.push({
818
+ change: { file: path, from: scan.stale, to: to ?? "unpinned" },
819
+ text: scan.text,
820
+ abs,
821
+ })
705
822
  }
706
823
  return edits
707
824
  }
@@ -723,6 +840,68 @@ const packageVersionAt = (dir: string): string | undefined => {
723
840
  }
724
841
  }
725
842
 
843
+ /** A repository linked into the project that resolves nifra from its own `node_modules`. */
844
+ export interface LinkedSkew {
845
+ /** The dependency's name, as the manifest declares it. */
846
+ readonly package: string
847
+ /** The project-relative manifest that declares it. */
848
+ readonly declaredIn: string
849
+ /** The linked repository's real path. */
850
+ readonly path: string
851
+ /** Each fixed-group package it installs itself, at a version other than the target. */
852
+ readonly installs: readonly { readonly package: string; readonly version: string }[]
853
+ }
854
+
855
+ /**
856
+ * Every `link:` or `file:` dependency whose installed folder resolves outside `cwd` and installs a
857
+ * fixed-group package of its own at a version other than `target`. Its imports resolve from its real
858
+ * path, so it keeps loading that copy after this project upgrades: a `server()` it builds can no longer
859
+ * be merged here, and single-copy never redirects across versions. A copy that resolves back inside
860
+ * `cwd` follows this project's install and is not counted.
861
+ */
862
+ export function linkedSkew(cwd: string, target: string): readonly LinkedSkew[] {
863
+ let root: string
864
+ try {
865
+ root = realpathSync(cwd)
866
+ } catch {
867
+ root = cwd
868
+ }
869
+ const inside = (path: string): boolean => path === root || path.startsWith(root + sep)
870
+ const seen = new Set<string>()
871
+ const found: LinkedSkew[] = []
872
+ for (const rel of scan(cwd, "**/package.json")) {
873
+ let manifest: unknown
874
+ try {
875
+ manifest = JSON.parse(readFileSync(join(cwd, rel), "utf8"))
876
+ } catch {
877
+ continue
878
+ }
879
+ for (const field of DEP_FIELDS) {
880
+ const block: unknown = Reflect.get(Object(manifest), field)
881
+ if (typeof block !== "object" || block === null) continue
882
+ for (const [name, spec] of Object.entries(block)) {
883
+ if (typeof spec !== "string" || !/^(?:link|file):/.test(spec)) continue
884
+ let path: string | undefined
885
+ for (const base of [join(cwd, dirname(rel)), cwd]) {
886
+ try {
887
+ path = realpathSync(join(base, "node_modules", name))
888
+ break
889
+ } catch {
890
+ // Not installed beside this manifest: try the root's node_modules.
891
+ }
892
+ }
893
+ if (path === undefined || inside(path) || seen.has(path)) continue
894
+ seen.add(path)
895
+ const installs = installedGroupPackages(path)
896
+ .filter((entry) => !inside(entry.path) && entry.version !== target)
897
+ .map((entry) => ({ package: entry.package, version: entry.version }))
898
+ if (installs.length > 0) found.push({ package: name, declaredIn: rel, path, installs })
899
+ }
900
+ }
901
+ }
902
+ return found
903
+ }
904
+
726
905
  /**
727
906
  * Every fixed-group package installed in `cwd/node_modules`, realpath-resolved so a linked repository
728
907
  * reports its own version. `inside` is false for one that resolves outside the workspace root.
@@ -764,15 +943,27 @@ export function installedGroupPackages(
764
943
  }
765
944
 
766
945
  /**
767
- * The lowest fixed-group version any package.json under `cwd` declares with a plain semver spec, or
768
- * null when none does. Recipes newer than it still have edits to make somewhere in the workspace.
946
+ * The version the workspace upgrades from: the lowest fixed-group version any package.json under
947
+ * `cwd` pins ({@link groupPinVersions}), since recipes newer than it still have edits to make
948
+ * somewhere. Without a pin, the lowest one installed inside the root, then the lowest peer floor;
949
+ * null when none names one.
769
950
  */
770
951
  export function installedGroupVersion(cwd: string): string | null {
771
- let lowest: string | null = null
772
- for (const version of groupPinVersions(cwd).keys()) {
773
- if (lowest === null || compareSemverSpec(version, lowest) < 0) lowest = version
952
+ const lowest = (versions: Iterable<string>): string | null => {
953
+ let found: string | null = null
954
+ for (const version of versions)
955
+ if (found === null || compareSemverSpec(version, found) < 0) found = version
956
+ return found
774
957
  }
775
- return lowest
958
+ return (
959
+ lowest(groupPinVersions(cwd).keys()) ??
960
+ lowest(
961
+ installedGroupPackages(cwd)
962
+ .filter((entry) => entry.inside)
963
+ .map((entry) => entry.version),
964
+ ) ??
965
+ lowest(groupSpecVersions(cwd, true).keys())
966
+ )
776
967
  }
777
968
 
778
969
  /** One recipe that applies every release recipe after `installed` up to `target`, oldest first. */
@@ -821,6 +1012,7 @@ export function computeUpgrade(
821
1012
  write: boolean,
822
1013
  allowDowngrade = false,
823
1014
  exact = false,
1015
+ above: readonly AncestorPinSite[] = [],
824
1016
  ): UpgradePlan {
825
1017
  const pins: PinChange[] = []
826
1018
  const agentPins: AgentPinChange[] = []
@@ -833,6 +1025,7 @@ export function computeUpgrade(
833
1025
  .filter((entry) => !entry.inside && entry.version !== recipe.version)
834
1026
  .map(({ package: name, path, version }) => ({ package: name, path, version }))
835
1027
 
1028
+ const manifests = new Map<string, string>()
836
1029
  if ((recipe.dependencyMoves?.length ?? 0) > 0 || recipe.pins.length > 0) {
837
1030
  for (const rel of scan(cwd, "**/package.json")) {
838
1031
  const abs = join(cwd, rel)
@@ -842,14 +1035,30 @@ export function computeUpgrade(
842
1035
  const pinned = pinSweepText(moved.text, recipe.pins, allowDowngrade, exact)
843
1036
  for (const change of pinned.changes) pins.push({ file: rel, ...change })
844
1037
  for (const d of pinned.downgrades) downgrades.push({ file: rel, ...d })
1038
+ if (pinned.text !== original) manifests.set(resolve(abs), pinned.text)
845
1039
  if (write && pinned.text !== original) writeFileSync(abs, pinned.text)
846
1040
  }
847
1041
  }
848
1042
 
849
- for (const { change, text } of agentPinEdits(cwd, recipe.version)) {
1043
+ // Read against the manifests as this upgrade leaves them, so a dry run lists what --write drops.
1044
+ const linkLocks = plainFileAt(cwd, BUN_LOCK) ? staleLinkLocks(resolve(cwd), manifests) : []
1045
+ let lockPruned = false
1046
+ if (write && linkLocks.length > 0) {
1047
+ const lockPath = join(cwd, BUN_LOCK)
1048
+ const pruned = pruneLinkLocks(
1049
+ readFileSync(lockPath, "utf8"),
1050
+ linkLocks.map((entry) => entry.package),
1051
+ )
1052
+ if (pruned !== undefined) {
1053
+ writeFileSync(lockPath, pruned)
1054
+ lockPruned = true
1055
+ }
1056
+ }
1057
+
1058
+ for (const { change, text, abs } of agentPinEdits(cwd, recipe.version, above)) {
850
1059
  agentPins.push(change)
851
1060
  planned.set(change.file, text)
852
- if (write) writeFileSync(join(cwd, change.file), Buffer.from(text, "latin1"))
1061
+ if (write) writeFileSync(abs, Buffer.from(text, "latin1"))
853
1062
  }
854
1063
 
855
1064
  if (recipe.importMoves.length > 0) {
@@ -893,7 +1102,10 @@ export function computeUpgrade(
893
1102
  downgrades,
894
1103
  retiredMarkers,
895
1104
  linkedOutside,
1105
+ linkedSkew: linkedSkew(cwd, recipe.version),
896
1106
  strayPins: strayPins(cwd, recipe.version, planned),
1107
+ linkLocks,
1108
+ lockPruned,
897
1109
  notes: recipe.notes ?? [],
898
1110
  }
899
1111
  }
@@ -922,7 +1134,9 @@ function renderPlan(
922
1134
  plan.importMoves.length === 0 &&
923
1135
  plan.retiredMarkers.length === 0 &&
924
1136
  plan.linkedOutside.length === 0 &&
925
- plan.strayPins.length === 0
1137
+ plan.linkedSkew.length === 0 &&
1138
+ plan.strayPins.length === 0 &&
1139
+ plan.linkLocks.length === 0
926
1140
  ) {
927
1141
  lines.push("Already up to date - no changes.")
928
1142
  return lines.join("\n")
@@ -995,12 +1209,54 @@ function renderPlan(
995
1209
  }
996
1210
  lines.push("")
997
1211
  }
1212
+ if (plan.linkLocks.length > 0) {
1213
+ lines.push(
1214
+ plan.lockPruned
1215
+ ? `Dropped ${plan.linkLocks.length} file: package(s) from bun.lock, whose recorded dependencies Bun never refreshes; \`bun install\` reads each linked package.json again:`
1216
+ : write
1217
+ ? `bun.lock records stale dependencies for ${plan.linkLocks.length} file: package(s), which Bun never refreshes; run \`${linkLockUpdate(plan.linkLocks)}\`:`
1218
+ : `bun.lock records stale dependencies for ${plan.linkLocks.length} file: package(s), which Bun never refreshes; --write drops them so \`bun install\` reads each linked package.json again:`,
1219
+ )
1220
+ for (const entry of plan.linkLocks)
1221
+ lines.push(
1222
+ ` ${entry.package} (file:${entry.path}) ${entry.changes.map(describeChange).join(", ")}`,
1223
+ )
1224
+ if (plan.lockPruned)
1225
+ lines.push(
1226
+ " Run `bun install` before committing bun.lock: until it records these packages again, `bun install --frozen-lockfile` fails.",
1227
+ )
1228
+ lines.push("")
1229
+ }
998
1230
  for (const note of plan.notes) lines.push(`note: ${note}`)
999
- if (!write) lines.push("\nRe-run with --write to apply, then nifra check verifies.")
1231
+ if (!write) lines.push("\nRe-run with --write to apply, then install and run nifra check.")
1000
1232
  return lines.join("\n").trimEnd()
1001
1233
  }
1002
1234
 
1003
1235
  /** Explain a refused rollback: which pins would roll back, why it's blocked, and the escape hatch. */
1236
+ /** The linked repositories to upgrade first, each with the commands that move it to `version`. */
1237
+ function renderLinkedSkew(
1238
+ version: string,
1239
+ skew: readonly LinkedSkew[],
1240
+ cwd: string,
1241
+ allowed: boolean,
1242
+ ): string {
1243
+ const lines = [
1244
+ `${allowed ? "Allowed by --allow-linked-skew" : "Blocked"}: ${skew.length} linked repositor${skew.length === 1 ? "y loads" : "ies load"} its own nifra at another version. Its imports resolve from its own node_modules, so after this upgrade a server() it builds cannot be merge()d here ("merge() requires a server() from this copy of @nifrajs/core").`,
1245
+ ]
1246
+ for (const entry of skew) {
1247
+ const at = relative(cwd, entry.path).split(sep).join("/") || "."
1248
+ lines.push(
1249
+ ` ${entry.package} (${entry.declaredIn}) at ${at}: ${entry.installs.map((install) => `${install.package} ${install.version}`).join(", ")}`,
1250
+ ` cd ${at} && nifra upgrade ${version} --write && bun install`,
1251
+ )
1252
+ }
1253
+ if (!allowed)
1254
+ lines.push(
1255
+ "Upgrade each one first, then run this again. --allow-linked-skew upgrades this project anyway.",
1256
+ )
1257
+ return lines.join("\n")
1258
+ }
1259
+
1004
1260
  function renderDowngradeRefusal(version: string, downgrades: readonly PinChange[]): string {
1005
1261
  return [
1006
1262
  `nifra upgrade → ${version}: refusing to DOWNGRADE ${downgrades.length} pin(s) below what's installed.`,
@@ -1013,11 +1269,61 @@ function renderDowngradeRefusal(version: string, downgrades: readonly PinChange[
1013
1269
  ].join("\n")
1014
1270
  }
1015
1271
 
1016
- /** The hook report around `--write`: the diff and where the pre-upgrade report was saved, or why not. */
1272
+ /** The hook report around `--write`: the diff and where the pre-upgrade report was saved, or why not.
1273
+ * `install` means the edits are not installed yet, so only the pre-upgrade report was taken. */
1017
1274
  export type UpgradeHookScope =
1018
1275
  | { readonly saved: string; readonly changes: readonly HookReportChange[] }
1276
+ | { readonly saved: string; readonly pending: "install" }
1019
1277
  | { readonly error: string; readonly saved?: string }
1020
1278
 
1279
+ /** The edits `--write` made that the installed packages do not reflect yet. */
1280
+ export interface PendingInstall {
1281
+ /** The command that installs them, by the lockfile the project keeps. */
1282
+ readonly command: string
1283
+ /** Fixed-group packages installed inside the root at a version other than the target. */
1284
+ readonly installed: readonly { readonly package: string; readonly version: string }[]
1285
+ }
1286
+
1287
+ const INSTALL_COMMANDS: readonly (readonly [lockfile: string, command: string])[] = [
1288
+ ["pnpm-lock.yaml", "pnpm install"],
1289
+ ["yarn.lock", "yarn install"],
1290
+ ["package-lock.json", "npm install"],
1291
+ ]
1292
+
1293
+ /**
1294
+ * Whether the project needs an install before a check can judge the target: `--write` changed what
1295
+ * package.json declares or what bun.lock records, or node_modules holds a group package at another
1296
+ * version. A link from outside the root is left out; installing here does not move it.
1297
+ */
1298
+ export function pendingInstall(cwd: string, plan: UpgradePlan): PendingInstall | undefined {
1299
+ const installed = installedGroupPackages(cwd)
1300
+ .filter((entry) => entry.inside && entry.version !== plan.version)
1301
+ .map(({ package: name, version }) => ({ package: name, version }))
1302
+ const edited = plan.pins.length > 0 || plan.dependencyMoves.length > 0 || plan.lockPruned
1303
+ if (!edited && installed.length === 0) return undefined
1304
+ const command =
1305
+ INSTALL_COMMANDS.find(([lockfile]) => existsSync(join(cwd, lockfile)))?.[1] ?? "bun install"
1306
+ return { command, installed }
1307
+ }
1308
+
1309
+ const SHOWN_INSTALLS = 3
1310
+
1311
+ function renderPendingInstall(pending: PendingInstall, version: string): string {
1312
+ const shown = pending.installed
1313
+ .slice(0, SHOWN_INSTALLS)
1314
+ .map((entry) => `${entry.package} ${entry.version}`)
1315
+ const more = pending.installed.length - shown.length
1316
+ const holds =
1317
+ shown.length === 0
1318
+ ? "the edited pins are not installed yet"
1319
+ : `node_modules still holds ${shown.join(", ")}${more > 0 ? ` and ${more} more` : ""}`
1320
+ return [
1321
+ `Not checked yet: \`nifra check\` reads the installed packages, and ${holds}, so it would judge the release this upgrade leaves rather than ${version}. Install, then check:`,
1322
+ ` ${pending.command}`,
1323
+ " nifra check",
1324
+ ].join("\n")
1325
+ }
1326
+
1021
1327
  async function hookReportBefore(cwd: string): Promise<ReflectedHookReport | { error: string }> {
1022
1328
  try {
1023
1329
  const { loadBackendApp } = await import("./load.ts")
@@ -1029,15 +1335,18 @@ async function hookReportBefore(cwd: string): Promise<ReflectedHookReport | { er
1029
1335
  }
1030
1336
 
1031
1337
  /** The report after the edits, from a fresh process: the edited sources must not come from this one's
1032
- * module cache. Saves the pre-upgrade report for `nifra routes --hooks --since` after an install. */
1338
+ * module cache. Saves the pre-upgrade report for `nifra routes --hooks --since` after an install.
1339
+ * While the edits are not installed, the old release would load in its place, so none is taken. */
1033
1340
  async function hookScopeAcross(
1034
1341
  cwd: string,
1035
1342
  before: ReflectedHookReport | { error: string },
1343
+ installed: boolean,
1036
1344
  ): Promise<UpgradeHookScope> {
1037
1345
  if ("error" in before) return { error: before.error }
1038
1346
  const saved = join(cwd, HOOKS_BEFORE_UPGRADE_FILE)
1039
1347
  mkdirSync(dirname(saved), { recursive: true })
1040
1348
  writeFileSync(saved, `${JSON.stringify(before, null, 2)}\n`)
1349
+ if (!installed) return { saved: HOOKS_BEFORE_UPGRADE_FILE, pending: "install" }
1041
1350
  const entry = fileURLToPath(
1042
1351
  new URL(import.meta.url.endsWith(".ts") ? "./cli.ts" : "./cli.js", import.meta.url),
1043
1352
  )
@@ -1071,6 +1380,7 @@ function renderHookScope(scope: UpgradeHookScope): string {
1071
1380
  const head = `Hook scope: not captured (${scope.error}).`
1072
1381
  return scope.saved === undefined ? head : [head, ...since(scope.saved)].join("\n")
1073
1382
  }
1383
+ if ("pending" in scope) return since(scope.saved).join("\n")
1074
1384
  return [
1075
1385
  "Hook scope across the edits (nifra routes --hooks):",
1076
1386
  renderHookDiff(scope.changes)
@@ -1090,6 +1400,33 @@ export function upgradeTargets(cliVersion: string): string[] {
1090
1400
  return versions.sort(compareSemverSpec)
1091
1401
  }
1092
1402
 
1403
+ /** Each target with the notes of every release after the installed one: what an app can observe
1404
+ * changing on the way up. Older releases are listed by version only. */
1405
+ function renderUpgradeList(
1406
+ targets: readonly string[],
1407
+ installed: string | null,
1408
+ notes: Readonly<Record<string, readonly string[]>>,
1409
+ ): string {
1410
+ const lines = [
1411
+ installed === null
1412
+ ? "available upgrade targets:"
1413
+ : `available upgrade targets (this project declares ${installed}):`,
1414
+ ]
1415
+ for (const version of targets) {
1416
+ const ahead = installed === null || compareSemverSpec(version, installed) > 0
1417
+ lines.push(` ${version}${version === installed ? " (declared)" : ""}`)
1418
+ if (!ahead) continue
1419
+ const list = notes[version] ?? []
1420
+ if (list.length === 0) lines.push(" no change an app can observe")
1421
+ for (const note of list) lines.push(` - ${note}`)
1422
+ }
1423
+ lines.push(
1424
+ "",
1425
+ "A newer release upgrades with its own CLI: bunx @nifrajs/cli@<version> upgrade <version>",
1426
+ )
1427
+ return lines.join("\n")
1428
+ }
1429
+
1093
1430
  /** The command that runs `version`'s own CLI with the same flags. `version` is a validated release. */
1094
1431
  function newerCliCommand(version: string, options: UpgradeOptions): string {
1095
1432
  const flags = [
@@ -1108,13 +1445,11 @@ export async function runUpgrade(cwd: string, options: UpgradeOptions): Promise<
1108
1445
  const cliVersion = options.cliVersion ?? listRecipeVersions().at(-1) ?? "0.0.0"
1109
1446
  const targets = upgradeTargets(cliVersion)
1110
1447
  if (options.list) {
1111
- if (options.json) console.log(JSON.stringify({ versions: targets, cliVersion }, null, 2))
1112
- else {
1113
- console.log(
1114
- `available upgrade targets:\n${targets.map((v) => ` ${v}`).join("\n")}\n\n` +
1115
- `A newer release upgrades with its own CLI: bunx @nifrajs/cli@<version> upgrade <version>`,
1116
- )
1117
- }
1448
+ const installed = installedGroupVersion(cwd)
1449
+ const notes = Object.fromEntries(targets.map((v) => [v, getRecipe(v)?.notes ?? []]))
1450
+ if (options.json)
1451
+ console.log(JSON.stringify({ versions: targets, cliVersion, installed, notes }, null, 2))
1452
+ else console.log(renderUpgradeList(targets, installed, notes))
1118
1453
  return true
1119
1454
  }
1120
1455
 
@@ -1170,7 +1505,8 @@ export async function runUpgrade(cwd: string, options: UpgradeOptions): Promise<
1170
1505
  const recipe = chainRecipes(version, from)
1171
1506
 
1172
1507
  // Fail-closed on rollback: a dry pass writes nothing, so we can refuse before any package.json is touched.
1173
- const preview = computeUpgrade(cwd, recipe, false, allowDowngrade, exact)
1508
+ const above = (await ancestorPins(cwd)).owned
1509
+ const preview = computeUpgrade(cwd, recipe, false, allowDowngrade, exact, above)
1174
1510
  if (preview.downgrades.length > 0) {
1175
1511
  if (options.json) {
1176
1512
  console.log(
@@ -1185,18 +1521,38 @@ export async function runUpgrade(cwd: string, options: UpgradeOptions): Promise<
1185
1521
  }
1186
1522
  return false
1187
1523
  }
1524
+ // Refused before anything is written: the linked repository fails at the first merge(), not here.
1525
+ if (preview.linkedSkew.length > 0 && options.allowLinkedSkew !== true) {
1526
+ if (options.json) {
1527
+ console.log(
1528
+ JSON.stringify(
1529
+ { ...preview, from, steps: recipe.steps, write: false, refused: "linked-skew" },
1530
+ null,
1531
+ 2,
1532
+ ),
1533
+ )
1534
+ } else {
1535
+ if (!write) console.log(renderPlan(preview, false, from, recipe.steps))
1536
+ console.error(renderLinkedSkew(recipe.version, preview.linkedSkew, cwd, false))
1537
+ }
1538
+ return false
1539
+ }
1188
1540
 
1189
1541
  const captureHooks = write && options.hooks !== false
1190
1542
  const before = captureHooks ? await hookReportBefore(cwd) : undefined
1191
- const plan = write ? computeUpgrade(cwd, recipe, true, allowDowngrade, exact) : preview
1192
- const hooks = before === undefined ? undefined : await hookScopeAcross(cwd, before)
1193
-
1194
- // Verify only makes sense once edits are on disk. Default on after --write; opt out with --no-verify.
1195
- const verify = write && options.verify !== false
1543
+ const plan = write ? computeUpgrade(cwd, recipe, true, allowDowngrade, exact, above) : preview
1544
+ const pending = write ? pendingInstall(cwd, plan) : undefined
1545
+ const hooks =
1546
+ before === undefined ? undefined : await hookScopeAcross(cwd, before, pending === undefined)
1547
+
1548
+ // Verify only makes sense once edits are on disk and installed. Default on after --write; opt out
1549
+ // with --no-verify. An uninstalled upgrade passes, so `upgrade --write && bun install` chains.
1550
+ const verify = write && options.verify !== false && pending === undefined
1196
1551
  if (options.json) {
1197
1552
  // The check result rides inside the one JSON document; its human report would break the stream.
1198
1553
  const report: Record<string, unknown> = { ...plan, from, steps: recipe.steps, write }
1199
1554
  if (hooks !== undefined) report.hooks = hooks
1555
+ if (pending !== undefined) report.install = pending
1200
1556
  let ok = true
1201
1557
  if (verify) {
1202
1558
  const { collectProjectVerification } = await import("./verification.ts")
@@ -1209,7 +1565,11 @@ export async function runUpgrade(cwd: string, options: UpgradeOptions): Promise<
1209
1565
  return ok
1210
1566
  }
1211
1567
  console.log(renderPlan(plan, write, from, recipe.steps))
1568
+ if (plan.linkedSkew.length > 0)
1569
+ console.warn(`\n${renderLinkedSkew(recipe.version, plan.linkedSkew, cwd, true)}`)
1212
1570
  if (hooks !== undefined) console.log(`\n${renderHookScope(hooks)}`)
1571
+ if (pending !== undefined && options.verify !== false)
1572
+ console.log(`\n${renderPendingInstall(pending, recipe.version)}`)
1213
1573
 
1214
1574
  if (verify) {
1215
1575
  const { runCheck } = await import("./check.ts")