@ultimat3/cli 31.51.0 → 31.53.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 (169) hide show
  1. package/CLAUDE.md +1 -1
  2. package/README.md +9 -9
  3. package/package.json +29 -29
  4. package/src/app-kit-disk.ts +39 -0
  5. package/src/app-kit-forms.ts +27 -0
  6. package/src/app-kit.ts +146 -0
  7. package/src/budgets.ts +3 -1
  8. package/src/catalog-layout.ts +194 -0
  9. package/src/cdp-shot-driver-screen.ts +72 -0
  10. package/src/cdp-shot-driver.ts +17 -1
  11. package/src/cmd-design-capture.ts +210 -0
  12. package/src/cmd-design-errors.ts +50 -0
  13. package/src/cmd-design-paths.ts +47 -0
  14. package/src/cmd-design-publish.ts +64 -0
  15. package/src/cmd-design-run.ts +229 -0
  16. package/src/cmd-design-spec.ts +47 -0
  17. package/src/cmd-design-theme.ts +107 -0
  18. package/src/cmd-design-url.ts +201 -0
  19. package/src/cmd-design.ts +188 -0
  20. package/src/cmd-doctor.ts +3 -0
  21. package/src/cmd-generate-spec.ts +5 -0
  22. package/src/cmd-generate.ts +3 -1
  23. package/src/cmd-i18n-spec.ts +4 -4
  24. package/src/cmd-i18n-split.ts +133 -0
  25. package/src/cmd-i18n.ts +46 -66
  26. package/src/cmd-kit-spec.ts +13 -0
  27. package/src/cmd-kit.ts +133 -0
  28. package/src/cmd-shot-against.ts +275 -0
  29. package/src/cmd-shot-spec.ts +9 -1
  30. package/src/cmd-shot.ts +19 -0
  31. package/src/cmd-upgrade.ts +11 -0
  32. package/src/codemods/agent-kit.ts +130 -0
  33. package/src/codemods/agents-md-budget.ts +47 -0
  34. package/src/codemods/docs-visual-quality.ts +198 -0
  35. package/src/codemods/index.ts +8 -0
  36. package/src/codemods/settings-kit-allow.ts +49 -0
  37. package/src/config-redact.ts +20 -4
  38. package/src/db-rollback-pass.ts +4 -1
  39. package/src/design-extract-script.ts +187 -0
  40. package/src/design-extract.ts +311 -0
  41. package/src/design-map-colors.ts +180 -0
  42. package/src/design-map.ts +288 -0
  43. package/src/dev-child-watch.ts +16 -0
  44. package/src/dev-db-migrate.ts +27 -46
  45. package/src/dev-db-migrator-hold.ts +131 -0
  46. package/src/dev-db-rollback.ts +11 -2
  47. package/src/dev-rebuild-schema.ts +7 -24
  48. package/src/doctor-kit.ts +25 -0
  49. package/src/error-catalog.ts +4 -2
  50. package/src/error-codes-kit.ts +24 -0
  51. package/src/error-codes.ts +12 -10
  52. package/src/generate-catalog-locales.ts +25 -2
  53. package/src/generate-files.ts +31 -1
  54. package/src/generate-follow-ups.ts +8 -3
  55. package/src/guards-shipped-names.ts +5 -0
  56. package/src/i18n-audit.ts +17 -33
  57. package/src/i18n-index.ts +108 -31
  58. package/src/i18n-locale-parity.ts +14 -6
  59. package/src/i18n-new-locale.ts +75 -0
  60. package/src/i18n-registration.ts +52 -27
  61. package/src/island-capture.ts +36 -7
  62. package/src/kit/agent-audit.ts +49 -0
  63. package/src/kit/agent-data.ts +32 -0
  64. package/src/kit/agent-server.ts +34 -0
  65. package/src/kit/agent-shape.ts +61 -0
  66. package/src/kit/agent-web.ts +49 -0
  67. package/src/kit/design-map.ts +106 -0
  68. package/src/kit/managed.ts +12 -0
  69. package/src/kit/registry.ts +89 -0
  70. package/src/kit/skill-design-research.ts +119 -0
  71. package/src/kit/skill-feature.ts +159 -0
  72. package/src/kit/skill-planx.ts +139 -0
  73. package/src/kit/skill-upgrade.ts +94 -0
  74. package/src/kit/skill-verify.ts +80 -0
  75. package/src/mcp-errors.ts +5 -0
  76. package/src/mcp-ui-diff.ts +13 -38
  77. package/src/mcp-ui.ts +30 -1
  78. package/src/merge-state.ts +3 -2
  79. package/src/messages-design.ts +104 -0
  80. package/src/messages-floor.ts +2 -0
  81. package/src/messages-upgrade.ts +9 -0
  82. package/src/messages.ts +4 -0
  83. package/src/registry.ts +4 -0
  84. package/src/serve-boot-telemetry.ts +106 -0
  85. package/src/serve-boot.ts +23 -4
  86. package/src/shot-blank.ts +70 -0
  87. package/src/shot-diff.ts +96 -0
  88. package/src/shot-gpu.ts +17 -5
  89. package/src/templates/catalog-barrel.ts +84 -0
  90. package/src/templates/guard-animated-layout-script.ts +173 -0
  91. package/src/templates/guard-effect-without-fallback.ts +117 -0
  92. package/src/templates/guard-motion-adapter.ts +161 -0
  93. package/src/templates/guard-raw-frame-loop.ts +134 -0
  94. package/src/templates/guard-raw-motion-script.ts +132 -0
  95. package/src/templates/guard-raw-motion-ts-scan.ts +95 -0
  96. package/src/templates/guard-released-forms.ts +12 -1
  97. package/src/templates/guard-untranslated-string.ts +27 -6
  98. package/src/templates/index.ts +1 -2
  99. package/src/templates/island.ts +55 -8
  100. package/src/templates/kit-released-forms.ts +63 -0
  101. package/src/templates/locales.ts +6 -0
  102. package/src/templates/motion-scale.ts +115 -0
  103. package/src/templates/scaffold-claude.ts +39 -26
  104. package/src/templates/scaffold-design.ts +41 -0
  105. package/src/templates/scaffold-docs.ts +31 -7
  106. package/src/templates/scaffold-gitattributes.ts +9 -2
  107. package/src/templates/scaffold-guards.ts +31 -2
  108. package/src/templates/scaffold-i18n.ts +10 -6
  109. package/src/templates/scaffold-verify-floor.ts +3 -0
  110. package/src/templates/shapes/blog-site.ts +15 -0
  111. package/src/templates/shapes/blog.ts +2 -0
  112. package/src/templates/shapes/content-site.ts +13 -0
  113. package/src/templates/shapes/content.ts +2 -0
  114. package/src/templates/shapes/dashboard-detail.ts +2 -0
  115. package/src/templates/shapes/dashboard-motion.ts +284 -0
  116. package/src/templates/shapes/dashboard.ts +19 -1
  117. package/src/templates/shapes/landing-motion.ts +67 -0
  118. package/src/templates/shapes/offline.ts +5 -2
  119. package/src/templates/shapes/saas.ts +4 -0
  120. package/src/test-ignores.ts +3 -2
  121. package/src/upgrade-gate.ts +14 -2
  122. package/src/upgrade-kit.ts +65 -0
  123. package/src/upgrade-report-kit.ts +28 -0
  124. package/src/upgrade-report.ts +3 -0
  125. package/src/verify-checks.ts +9 -1
  126. package/src/verify-floor.ts +9 -1
  127. package/src/verify-local-only.ts +66 -0
  128. package/src/verify-run.ts +17 -2
  129. package/src/workspace-checks.ts +3 -3
  130. package/wiki/Actions.md +1 -1
  131. package/wiki/Agents.md +33 -1
  132. package/wiki/Auth.md +3 -3
  133. package/wiki/Batching-And-Preloading.md +1 -0
  134. package/wiki/CLI-Reference-Data.md +241 -0
  135. package/wiki/CLI-Reference-Gate.md +572 -0
  136. package/wiki/CLI-Reference-Project.md +414 -0
  137. package/wiki/CLI-Reference-Ship.md +348 -0
  138. package/wiki/CLI-Reference-Tools.md +687 -0
  139. package/wiki/CLI-Reference.md +18 -2227
  140. package/wiki/Compared.md +8 -8
  141. package/wiki/Configuration.md +26 -2
  142. package/wiki/Deployment.md +1 -1
  143. package/wiki/Design-Research.md +96 -0
  144. package/wiki/Effects.md +83 -0
  145. package/wiki/Entities-And-Migrations.md +3 -2
  146. package/wiki/FAQ.md +1 -1
  147. package/wiki/Getting-Started.md +1 -1
  148. package/wiki/Home.md +2 -2
  149. package/wiki/I18n.md +39 -5
  150. package/wiki/Installation.md +1 -1
  151. package/wiki/Jobs-And-Workflows.md +29 -1
  152. package/wiki/Known-Gaps.md +6 -2
  153. package/wiki/MCP-And-AI.md +4 -0
  154. package/wiki/Motion.md +85 -0
  155. package/wiki/Observability.md +15 -1
  156. package/wiki/Outbound-HTTP.md +62 -2
  157. package/wiki/PWA-And-Offline.md +1 -1
  158. package/wiki/Policies-And-Authz.md +10 -0
  159. package/wiki/Project-Layout.md +1 -1
  160. package/wiki/Realtime.md +29 -2
  161. package/wiki/Static-Assets.md +1 -1
  162. package/wiki/Testing.md +33 -0
  163. package/wiki/Theming.md +31 -8
  164. package/wiki/Troubleshooting.md +1 -1
  165. package/wiki/Tutorial-02-First-Feature.md +1 -1
  166. package/wiki/UI-Components.md +2 -0
  167. package/wiki/Upgrading.md +9 -3
  168. package/src/templates/scaffold-claude-agents.ts +0 -161
  169. package/src/templates/scaffold-claude-commands.ts +0 -239
@@ -0,0 +1,288 @@
1
+ // A reference's measurements as framework vocabulary: `tokens.proposal.json` (a `defineTheme`
2
+ // argument) and `motion-map.json` (each animation as a `@ultimat3/ui/motion` call or effects entry).
3
+ //
4
+ // Durations and easings snap through the motion scale the shipped guards use
5
+ // (`templates/motion-scale.ts`), so research and the gate agree on what "base" means. Pure.
6
+
7
+ import type { Extraction, ObservedMotion } from './design-extract';
8
+ import {
9
+ clusterPalette,
10
+ type PaletteCluster,
11
+ proposeColors,
12
+ type ThemeTables,
13
+ withNearestRoles,
14
+ } from './design-map-colors';
15
+ import type { DurationToken, EasingToken } from './templates/motion-scale';
16
+ import { snapDuration, snapEasing } from './templates/motion-scale';
17
+
18
+ export type { PaletteCluster, ThemeTables } from './design-map-colors';
19
+ export { clusterPalette } from './design-map-colors';
20
+
21
+ /**
22
+ * `@ultimat3/ui`'s radius rungs in px, the ones a measured corner can mean. Not imported: the CLI
23
+ * does not depend on `@ultimat3/ui`, and its barrel exports no radius table. `design-map.test.ts`
24
+ * holds these to the canonical `_radius.scss`.
25
+ */
26
+ export const RADIUS_RUNGS = { sm: 4, md: 8, lg: 12, xl: 16 } as const;
27
+ type RadiusRung = keyof typeof RADIUS_RUNGS;
28
+
29
+ /** The `defineTheme` argument `tokens.proposal.json` holds. */
30
+ export interface DesignProposal {
31
+ readonly colors?: {
32
+ readonly light?: Record<string, string>;
33
+ readonly dark?: Record<string, string>;
34
+ };
35
+ readonly radius?: Partial<Record<RadiusRung, string>>;
36
+ readonly motion?: MotionProposal;
37
+ }
38
+
39
+ export interface MotionProposal {
40
+ readonly duration?: Partial<Record<Exclude<DurationToken, 'instant'>, string>>;
41
+ readonly easing?: Partial<Record<EasingToken, string>>;
42
+ }
43
+
44
+ /** Corners past a rung's reach (a pill, a circle) are not a radius scale. */
45
+ const RADIUS_MAX = 64;
46
+
47
+ export function proposeRadius(
48
+ radii: readonly { readonly px: number; readonly count: number }[],
49
+ ): Partial<Record<RadiusRung, string>> {
50
+ const best = new Map<RadiusRung, { px: number; count: number }>();
51
+ for (const radius of radii) {
52
+ if (radius.px <= 0 || radius.px > RADIUS_MAX) continue;
53
+ let rung: RadiusRung = 'sm';
54
+ let gap = Number.POSITIVE_INFINITY;
55
+ for (const [name, px] of Object.entries(RADIUS_RUNGS) as [RadiusRung, number][]) {
56
+ if (Math.abs(px - radius.px) < gap) {
57
+ rung = name;
58
+ gap = Math.abs(px - radius.px);
59
+ }
60
+ }
61
+ const held = best.get(rung);
62
+ if (held === undefined || radius.count > held.count) best.set(rung, radius);
63
+ }
64
+ return Object.fromEntries([...best].map(([rung, radius]) => [rung, `${String(radius.px)}px`]));
65
+ }
66
+
67
+ /** CSS's easing keywords as the control points they are. */
68
+ /** A Map: the key is a page's easing string, and `'constructor'` must miss, not hit a prototype. */
69
+ const KEYWORD_CURVES: ReadonlyMap<string, readonly number[]> = new Map([
70
+ ['ease', [0.25, 0.1, 0.25, 1]],
71
+ ['ease-in', [0.42, 0, 1, 1]],
72
+ ['ease-out', [0, 0, 0.58, 1]],
73
+ ['ease-in-out', [0.42, 0, 0.58, 1]],
74
+ ]);
75
+
76
+ /** A curve's four control points, or `undefined` for `linear`, `steps()`, `linear()` and `other`. */
77
+ export function easingPoints(easing: string): readonly number[] | undefined {
78
+ const keyword = KEYWORD_CURVES.get(easing);
79
+ if (keyword !== undefined) return keyword;
80
+ const match = /^cubic-bezier\(([^)]*)\)$/.exec(easing);
81
+ if (match === null) return undefined;
82
+ const points = (match[1] ?? '').split(',').map((part) => Number(part.trim()));
83
+ return points.length === 4 && points.every(Number.isFinite) ? points : undefined;
84
+ }
85
+
86
+ /** A `linear()` with many stops is how a spring is written in CSS. */
87
+ const isSpring = (easing: string): boolean =>
88
+ easing.startsWith('linear(') && easing.split(',').length >= 4;
89
+
90
+ const curveText = (points: readonly number[]): string => `cubic-bezier(${points.join(', ')})`;
91
+
92
+ /** How far a curve may overshoot: past it a `y` is a page's typo or a probe, not a tempo. */
93
+ const CURVE_Y_LIMIT = 10;
94
+ const PLAIN_DECIMAL = /^-?\d+(?:\.\d+)?$/;
95
+
96
+ /**
97
+ * A curve `defineTheme` will take as written: x values in [0, 1], every point a plain decimal (a
98
+ * page's `1.23e+23` prints as exponent notation, which no CSS curve pattern accepts) and no `y`
99
+ * past `CURVE_Y_LIMIT`. Anything else is dropped from the proposal, never repaired.
100
+ */
101
+ const isProposableCurve = (points: readonly number[]): boolean => {
102
+ const [x1, y1, x2, y2] = points;
103
+ if (x1 === undefined || y1 === undefined || x2 === undefined || y2 === undefined) return false;
104
+ if (x1 < 0 || x1 > 1 || x2 < 0 || x2 > 1) return false;
105
+ if (Math.abs(y1) > CURVE_Y_LIMIT || Math.abs(y2) > CURVE_Y_LIMIT) return false;
106
+ return points.every((point) => PLAIN_DECIMAL.test(String(point)));
107
+ };
108
+
109
+ /** The weighted median: what most of the page actually waits. */
110
+ function median(values: readonly { readonly value: number; readonly weight: number }[]): number {
111
+ const sorted = [...values].sort((a, b) => a.value - b.value);
112
+ const half = sorted.reduce((sum, entry) => sum + entry.weight, 0) / 2;
113
+ let seen = 0;
114
+ for (const entry of sorted) {
115
+ seen += entry.weight;
116
+ if (seen >= half) return entry.value;
117
+ }
118
+ return sorted.at(-1)?.value ?? 0;
119
+ }
120
+
121
+ /**
122
+ * The tempo: each rung the page's durations snap to, set to their weighted median; each easing
123
+ * token, set to the curve the page used most for it. A loop's period is not a tempo, and a curve
124
+ * whose x values leave [0, 1] is one CSS — and `defineTheme` — refuses.
125
+ */
126
+ export function proposeMotion(motion: readonly ObservedMotion[]): MotionProposal {
127
+ const timed = motion.filter((m) => m.trigger !== 'loop' && m.durationMs > 0);
128
+ const durations = new Map<string, { value: number; weight: number }[]>();
129
+ const curves = new Map<string, Map<string, number>>();
130
+ for (const m of timed) {
131
+ const rung = snapDuration(m.durationMs);
132
+ durations.set(rung, [...(durations.get(rung) ?? []), { value: m.durationMs, weight: m.count }]);
133
+ const points = easingPoints(m.easing);
134
+ if (points === undefined) continue;
135
+ if (!isProposableCurve(points)) continue;
136
+ const token = snapEasing(points);
137
+ const text = curveText(points);
138
+ const counts = curves.get(token) ?? new Map<string, number>();
139
+ counts.set(text, (counts.get(text) ?? 0) + m.count);
140
+ curves.set(token, counts);
141
+ }
142
+ const duration = Object.fromEntries(
143
+ [...durations].map(([rung, values]) => [rung, `${String(Math.round(median(values)))}ms`]),
144
+ );
145
+ const easing = Object.fromEntries(
146
+ [...curves].map(([token, counts]) => [
147
+ token,
148
+ [...counts].sort((a, b) => b[1] - a[1])[0]?.[0] ?? '',
149
+ ]),
150
+ );
151
+ return {
152
+ ...(Object.keys(duration).length === 0 ? {} : { duration }),
153
+ ...(Object.keys(easing).length === 0 ? {} : { easing }),
154
+ };
155
+ }
156
+
157
+ export interface MotionMapEntry {
158
+ readonly module: '@ultimat3/ui/motion' | '@ultimat3/effects';
159
+ /** A name the module exports — `animate`, `inView`, `Marquee`, … */
160
+ readonly name: string;
161
+ readonly observed: (Omit<ObservedMotion, 'count'> & { readonly count: number }) | null;
162
+ readonly duration?: Exclude<DurationToken, 'instant'> | undefined;
163
+ readonly easing?: EasingToken | undefined;
164
+ readonly why: string;
165
+ }
166
+
167
+ const LAYOUT_PROPERTIES = new Set([
168
+ 'width',
169
+ 'height',
170
+ 'top',
171
+ 'left',
172
+ 'right',
173
+ 'bottom',
174
+ 'margin',
175
+ 'padding',
176
+ ]);
177
+
178
+ function entryFor(m: ObservedMotion): Omit<MotionMapEntry, 'observed' | 'duration' | 'easing'> {
179
+ if (isSpring(m.easing)) {
180
+ return {
181
+ module: '@ultimat3/ui/motion',
182
+ name: 'springLinear',
183
+ why: 'a linear() curve is a spring',
184
+ };
185
+ }
186
+ if (m.trigger === 'loop') {
187
+ const marquee = m.properties.some((p) => p === 'transform' || p.startsWith('translate'));
188
+ return marquee
189
+ ? { module: '@ultimat3/effects', name: 'Marquee', why: 'an endless transform is a marquee' }
190
+ : { module: '@ultimat3/effects', name: 'Shimmer', why: 'an endless paint loop is a shimmer' };
191
+ }
192
+ if (m.trigger === 'scroll') {
193
+ return m.durationMs === 0
194
+ ? { module: '@ultimat3/ui/motion', name: 'scrollLinked', why: 'driven by a scroll timeline' }
195
+ : { module: '@ultimat3/ui/motion', name: 'inView', why: 'started as it scrolled into view' };
196
+ }
197
+ if (m.properties.some((p) => LAYOUT_PROPERTIES.has(p))) {
198
+ return {
199
+ module: '@ultimat3/ui/motion',
200
+ name: 'layout',
201
+ why: 'animates a layout property: FLIP it with transforms instead',
202
+ };
203
+ }
204
+ if (m.trigger === 'hover' || m.trigger === 'state') {
205
+ return {
206
+ module: '@ultimat3/ui/motion',
207
+ name: 'motionTiming',
208
+ why: `a ${m.trigger} transition`,
209
+ };
210
+ }
211
+ return { module: '@ultimat3/ui/motion', name: 'animate', why: 'an entrance animation' };
212
+ }
213
+
214
+ /** Every distinct observed animation, then the effects the page's paint implies. */
215
+ export function motionMap(extraction: Extraction): MotionMapEntry[] {
216
+ const entries: MotionMapEntry[] = extraction.motion.map((m) => {
217
+ const points = easingPoints(m.easing);
218
+ return {
219
+ ...entryFor(m),
220
+ observed: m,
221
+ ...(m.durationMs > 0 && m.trigger !== 'loop' ? { duration: snapDuration(m.durationMs) } : {}),
222
+ ...(points === undefined ? {} : { easing: snapEasing(points) }),
223
+ };
224
+ });
225
+ if (extraction.backdrop.count > 0) {
226
+ entries.push({
227
+ module: '@ultimat3/effects',
228
+ name: 'GlassSurface',
229
+ observed: null,
230
+ why: `${String(extraction.backdrop.count)} element(s) use backdrop-filter`,
231
+ });
232
+ }
233
+ if (extraction.canvases > 0) {
234
+ entries.push({
235
+ module: '@ultimat3/effects',
236
+ name: 'EffectCanvas',
237
+ observed: null,
238
+ why: `${String(extraction.canvases)} visible canvas element(s) — a drawn background`,
239
+ });
240
+ }
241
+ return entries;
242
+ }
243
+
244
+ export interface DesignMapping {
245
+ readonly proposal: DesignProposal;
246
+ readonly palette: { readonly light: PaletteCluster[]; readonly dark: PaletteCluster[] };
247
+ readonly motionMap: MotionMapEntry[];
248
+ }
249
+
250
+ /**
251
+ * Both schemes' captures as one mapping. Colours need `tables` — without them (no `@ultimat3/ui`
252
+ * to resolve) the proposal carries no colours, because nothing could check their contrast.
253
+ */
254
+ export function mapDesign(
255
+ captures: { readonly light: Extraction; readonly dark: Extraction },
256
+ tables: ThemeTables | undefined,
257
+ ): DesignMapping {
258
+ const palette = {
259
+ light: clusterPalette(captures.light.colors),
260
+ dark: clusterPalette(captures.dark.colors),
261
+ };
262
+ const light = tables === undefined ? {} : proposeColors(palette.light, 'light', tables);
263
+ const dark = tables === undefined ? {} : proposeColors(palette.dark, 'dark', tables);
264
+ const colors = {
265
+ ...(Object.keys(light).length === 0 ? {} : { light }),
266
+ ...(Object.keys(dark).length === 0 ? {} : { dark }),
267
+ };
268
+ const radius = proposeRadius([...captures.light.radii, ...captures.dark.radii]);
269
+ const motion = proposeMotion(captures.light.motion);
270
+ return {
271
+ proposal: {
272
+ ...(Object.keys(colors).length === 0 ? {} : { colors }),
273
+ ...(Object.keys(radius).length === 0 ? {} : { radius }),
274
+ ...(Object.keys(motion).length === 0 ? {} : { motion }),
275
+ },
276
+ palette: {
277
+ light:
278
+ tables === undefined
279
+ ? palette.light.slice(0, 16)
280
+ : withNearestRoles(palette.light, 'light', tables),
281
+ dark:
282
+ tables === undefined
283
+ ? palette.dark.slice(0, 16)
284
+ : withNearestRoles(palette.dark, 'dark', tables),
285
+ },
286
+ motionMap: motionMap(captures.light),
287
+ };
288
+ }
@@ -153,6 +153,22 @@ export function hardExit(
153
153
  };
154
154
  }
155
155
 
156
+ /**
157
+ * A stop this process begins on its own because serving on is unsafe — the embedded session that
158
+ * could not be made `x_app` again after a migrate pass (`dev-db-migrator-hold.ts`). Its own hard
159
+ * exit, since an unsupervised `x dev` starts no watch: that drain meets a database whose turn is
160
+ * never given back, and a hook waiting on it must not keep the process. Exit 1 if it comes to that.
161
+ */
162
+ export function stopDevServing(
163
+ signal: string,
164
+ exit: (code: number) => void = (code) => process.exit(code),
165
+ begin: (signal: string) => Promise<void> = drain,
166
+ afterMs: () => number = devHardExitMs,
167
+ ): void {
168
+ hardExit(exit, afterMs)(1);
169
+ void begin(signal);
170
+ }
171
+
156
172
  /** What the supervisor sends for a stop: the signal it would have forwarded on POSIX. */
157
173
  export interface DevDrainMessage {
158
174
  readonly type: 'x-dev-drain';
@@ -3,26 +3,25 @@
3
3
  // so the command asks the holder instead of opening `.x/pgdata` a second time. Loopback Host and
4
4
  // peer, same-origin: the `/_x/db` doors.
5
5
 
6
- import { NotImplementedError, renderThrowable, UltimateError } from '@ultimat3/core';
6
+ import { renderThrowable, UltimateError } from '@ultimat3/core';
7
7
  import type { DriftDifference } from '@ultimat3/db';
8
- import { checkDrift, db, migrate } from '@ultimat3/db';
8
+ import { checkDrift, migrate } from '@ultimat3/db';
9
9
  import type { CatalogDescription } from '@ultimat3/db/schema-dump';
10
10
  import { introspectCatalog } from '@ultimat3/db/schema-dump';
11
11
  import type { Route, UltimateRequest } from '@ultimat3/http';
12
12
  import { jsonResponse } from '@ultimat3/http';
13
- import { loadAppConfig } from './app-config-load';
14
13
  import { acceptCreatedTables } from './db-accept-created';
15
14
  import { DEV_LEDGER_PATH, DEV_MIGRATE_PATH, DEV_ROLLBACK_PATH } from './db-dev-wire';
16
15
  import { frameworkStorageDrift } from './db-object-drift';
17
16
  import { assertSameOrigin, hostRefusal } from './dev-dashboard-guard';
17
+ import { devMigratorPass } from './dev-db-migrator-hold';
18
18
  import { ledgerInDev, rollbackInDev, stepsOf } from './dev-db-rollback';
19
19
  import { ledgerMoved } from './dev-db-settled';
20
20
  import { readMigrations } from './migrations';
21
- import { rowSecurityDeclared } from './row-security-boot';
22
21
  import { stopRunStartFix } from './stop-run-start';
23
22
 
24
23
  /** The command that works when this process cannot apply: the embedded database to itself. */
25
- export const MIGRATE_ALONE_FIX = stopRunStartFix(['db', 'migrate']);
24
+ const MIGRATE_ALONE_FIX = stopRunStartFix(['db', 'migrate']);
26
25
 
27
26
  /** One applied pass as it crosses the wire: `runMigrations`' report, and the live catalog. */
28
27
  export interface DevMigrateData {
@@ -38,50 +37,36 @@ export interface DevMigrateData {
38
37
 
39
38
  type Env = Readonly<Record<string, string | undefined>>;
40
39
 
41
- /**
42
- * With `database.rowSecurity`, this process serves as `x_app` and a migration must run as
43
- * `x_migrator` from the bootstrap session — one embedded session cannot be both while it serves.
44
- */
45
- export async function devCanMigrate(root: string): Promise<boolean> {
46
- return !rowSecurityDeclared(await loadAppConfig(root));
47
- }
48
-
49
- /** Refused where this process serves as `x_app`; `fix` is the command run alone, start to start. */
50
- async function assertDevCanMigrate(root: string, fix: string): Promise<void> {
51
- if (await devCanMigrate(root)) return;
52
- throw new NotImplementedError({
53
- cause:
54
- 'this x dev serves the embedded database as x_app (database.rowSecurity), and migrations run as x_migrator — one embedded session cannot hold both',
55
- fix,
56
- });
57
- }
58
-
59
40
  /**
60
41
  * `serve.ts`'s `runMigrations` over the client this process already holds: the same file list,
61
42
  * the same ledger, the same post-condition. No boot and no `stop()` — the database is `x dev`'s.
43
+ * Where it serves as `x_app`, the whole pass is one hold of the session (`devMigratorPass`).
62
44
  */
63
45
  export async function migrateInDev(root: string, env: Env): Promise<DevMigrateData> {
64
- await assertDevCanMigrate(root, MIGRATE_ALONE_FIX);
65
46
  const migrations = await readMigrations(root);
66
- const report = await migrate({
67
- migrations,
68
- ...(env['APP_VERSION'] === undefined ? {} : { appVersion: env['APP_VERSION'] }),
47
+ return devMigratorPass(root, env, async ({ client, lock, bootstrap }) => {
48
+ const report = await migrate({
49
+ migrations,
50
+ client,
51
+ lock,
52
+ ...(env['APP_VERSION'] === undefined ? {} : { appVersion: env['APP_VERSION'] }),
53
+ });
54
+ // As `runMigrations` reads them: after the migrate step, as the bootstrap user. One at a
55
+ // time — under the hold they share one session with no turn queue between them.
56
+ await bootstrap();
57
+ const drift = acceptCreatedTables(await checkDrift({ migrations, client }), migrations);
58
+ const catalog = await introspectCatalog({ client });
59
+ const storage = await frameworkStorageDrift(client);
60
+ return {
61
+ applied: report.applied.map((entry) => entry.id),
62
+ skipped: report.skipped.length,
63
+ appVersion: report.appVersion,
64
+ durationMs: report.durationMs,
65
+ drift: drift.differences,
66
+ catalog,
67
+ storage,
68
+ };
69
69
  });
70
- const drift = acceptCreatedTables(await checkDrift({ migrations }), migrations);
71
- const client = db();
72
- const [catalog, storage] = await Promise.all([
73
- introspectCatalog({ client }),
74
- frameworkStorageDrift(client),
75
- ]);
76
- return {
77
- applied: report.applied.map((entry) => entry.id),
78
- skipped: report.skipped.length,
79
- appVersion: report.appVersion,
80
- durationMs: report.durationMs,
81
- drift: drift.differences,
82
- catalog,
83
- storage,
84
- };
85
70
  }
86
71
 
87
72
  /** The refusal as the command re-throws it: the code, cause and fix of whatever stopped the pass. */
@@ -143,10 +128,6 @@ export function devMigrateRoutes(input: DevMigrateRouteInput): readonly Route[]
143
128
  ),
144
129
  door(input, DEV_ROLLBACK_PATH, 'dev._x.db.rollback', async (request) => {
145
130
  const steps = stepsOf(request.url.searchParams.get('steps'));
146
- await assertDevCanMigrate(
147
- root,
148
- stopRunStartFix(['db', 'rollback', '--steps', String(steps)]),
149
- );
150
131
  return rollbackInDev(root, env, steps).finally(ledgerMoved);
151
132
  }),
152
133
  // A read, behind the same doors and the same verb: nothing under `/_x/db` answers a GET.
@@ -0,0 +1,131 @@
1
+ // A migrate or rollback pass inside a live `x dev` whose embedded session serves as `x_app`
2
+ // (`database.rowSecurity`): the one PGlite session is taken exclusively, becomes `x_migrator` for
3
+ // the pass, and serves as `x_app` again before any other statement runs — or never serves again.
4
+
5
+ import { logger, renderThrowable } from '@ultimat3/core';
6
+ import type { DbClient } from '@ultimat3/db';
7
+ import {
8
+ assertRowSecurityBinds,
9
+ baseClient,
10
+ DbError,
11
+ db,
12
+ holdMigratorRole,
13
+ isReservable,
14
+ raw,
15
+ serveAsAppRole,
16
+ } from '@ultimat3/db';
17
+ import { loadAppConfig } from './app-config-load';
18
+ import { stopDevServing } from './dev-child-watch';
19
+ import { rowSecurityDeclared } from './row-security-boot';
20
+ import { resolveServices } from './runtime-bindings';
21
+ import { stopRunStartFix } from './stop-run-start';
22
+
23
+ type Env = Readonly<Record<string, string | undefined>>;
24
+
25
+ /** What a pass runs on. Every statement of the pass goes to `client`, never to the ambient one. */
26
+ export interface MigratorPass {
27
+ readonly client: DbClient;
28
+ /**
29
+ * `migrate()`/`rollback()`'s `lock`. `false` under the hold: the advisory lock would reserve the
30
+ * session a second time and wait for the turn this pass is holding, and the hold already is the
31
+ * exclusion — PGlite has one session and one opener.
32
+ */
33
+ readonly lock: boolean;
34
+ /** `reset role`: the reads `x db migrate` alone makes after its migrate step, as the bootstrap user. */
35
+ readonly bootstrap: () => Promise<void>;
36
+ }
37
+
38
+ export interface MigratorHoldSeams {
39
+ /** The client whose session is held. Defaults to the ambient one. */
40
+ readonly client?: DbClient | undefined;
41
+ /** Run once when the session could not be made `x_app` again. Defaults to `stopDevServing`. */
42
+ readonly stopServing?: (() => void) | undefined;
43
+ }
44
+
45
+ /** After the turn that will never be released: start again, and the boot arms the roles afresh. */
46
+ const RESTART_FIX = 'x stop --json && x dev';
47
+
48
+ const roleLost = (error: unknown): DbError =>
49
+ new DbError({
50
+ code: 'X_DB_ROW_SECURITY_BYPASSED',
51
+ cause: `x dev ran a migrate pass as x_migrator and could not serve as x_app again (${renderThrowable(error)}), so it stopped serving: no statement reaches the embedded session, whose role is no longer one row security binds`,
52
+ fix: RESTART_FIX,
53
+ sourceError: error,
54
+ });
55
+
56
+ /**
57
+ * Back to what the boot armed (`armRowSecurity`), judged again. `rollback` first: a pass that died
58
+ * inside a transaction would otherwise take the `set role` below with it at that transaction's end
59
+ * — and outside a transaction it is a warning, not an error.
60
+ */
61
+ async function serveAgain(session: DbClient): Promise<void> {
62
+ await session.execute(raw('rollback'));
63
+ await session.execute(raw('reset role'));
64
+ await serveAsAppRole(session);
65
+ await assertRowSecurityBinds(session);
66
+ }
67
+
68
+ /**
69
+ * `run` as `x_migrator` on the reserved session. PGlite's `reserve()` holds its turn queue, so a
70
+ * request's statement issued meanwhile waits and then runs as `x_app`: nothing but the pass ever
71
+ * sees the migrator or the bootstrap superuser. The turn is given back only once the session is
72
+ * `x_app` and bound by row security again; otherwise it is kept for the life of the process —
73
+ * every later statement waits rather than reading every tenant's rows — and `stopServing` runs.
74
+ */
75
+ export async function withMigratorHold<T>(
76
+ run: (pass: MigratorPass) => Promise<T>,
77
+ seams: MigratorHoldSeams = {},
78
+ ): Promise<T> {
79
+ const client = seams.client ?? baseClient();
80
+ if (!isReservable(client)) {
81
+ throw new DbError({
82
+ code: 'X_DB_ROW_SECURITY_BYPASSED',
83
+ cause:
84
+ 'x dev serves the embedded database as x_app and its client cannot reserve the session, so a pass as x_migrator would run beside the requests it serves',
85
+ fix: stopRunStartFix(['db', 'migrate']),
86
+ });
87
+ }
88
+ const session = await client.reserve();
89
+ let outcome: { readonly value: T } | { readonly error: unknown };
90
+ try {
91
+ await session.execute(raw('reset role'));
92
+ await holdMigratorRole(session);
93
+ const value = await run({
94
+ client: session,
95
+ lock: false,
96
+ bootstrap: async () => {
97
+ await session.execute(raw('reset role'));
98
+ },
99
+ });
100
+ outcome = { value };
101
+ } catch (error) {
102
+ outcome = { error };
103
+ }
104
+ try {
105
+ await serveAgain(session);
106
+ } catch (error) {
107
+ // No `session.release()`: the turn is the only thing between a request and a superuser.
108
+ const lost = roleLost(error);
109
+ logger.error(lost.code, { code: lost.code, cause: lost.cause, fix: lost.fix });
110
+ (seams.stopServing ?? (() => stopDevServing('row-security-lost')))();
111
+ throw lost;
112
+ }
113
+ session.release();
114
+ if ('error' in outcome) throw outcome.error;
115
+ return outcome.value;
116
+ }
117
+
118
+ /**
119
+ * A pass run by this `x dev`. Held only where the roles are ours and the session is one — the
120
+ * embedded database with `database.rowSecurity`. Anywhere else it is the ambient client under the
121
+ * migrate lock: an external database's migrator is whoever `DATABASE_URL` connects as.
122
+ */
123
+ export async function devMigratorPass<T>(
124
+ root: string,
125
+ env: Env,
126
+ run: (pass: MigratorPass) => Promise<T>,
127
+ ): Promise<T> {
128
+ const embedded = resolveServices(root, env).db.mode === 'embedded';
129
+ if (embedded && rowSecurityDeclared(await loadAppConfig(root))) return withMigratorHold(run);
130
+ return run({ client: db(), lock: true, bootstrap: async () => undefined });
131
+ }
@@ -5,6 +5,7 @@
5
5
  import { db, isLedgerMissing, readLedger } from '@ultimat3/db';
6
6
  import { ROLLBACK_STEPS } from './db-dev-wire';
7
7
  import { reverseApplied } from './db-rollback-pass';
8
+ import { devMigratorPass } from './dev-db-migrator-hold';
8
9
  import { parseIntFlag } from './flag-number';
9
10
 
10
11
  type Env = Readonly<Record<string, string | undefined>>;
@@ -12,13 +13,21 @@ type Env = Readonly<Record<string, string | undefined>>;
12
13
  /** `?steps=n`, through the command's own reader: the door refuses what the flag refuses. */
13
14
  export const stepsOf = (raw: string | null): number => parseIntFlag(raw ?? '', ROLLBACK_STEPS);
14
15
 
15
- /** `rollback()` over the client this process already holds, with the command's own two refusals. */
16
+ /**
17
+ * `rollback()` over the client this process already holds, with the command's own two refusals.
18
+ * Where it serves as `x_app`, the reversal runs as `x_migrator` under the same hold a migrate
19
+ * pass takes (`dev-db-migrator-hold.ts`).
20
+ */
16
21
  export async function rollbackInDev(
17
22
  root: string,
18
23
  env: Env,
19
24
  steps: number,
20
25
  ): Promise<{ readonly reverted: readonly string[] }> {
21
- return { reverted: await reverseApplied(root, env, steps) };
26
+ return {
27
+ reverted: await devMigratorPass(root, env, ({ client, lock }) =>
28
+ reverseApplied(root, env, steps, { client, lock }),
29
+ ),
30
+ };
22
31
  }
23
32
 
24
33
  /** Each applied migration's id and the checksum it was applied with; no ledger is no rows. */
@@ -6,27 +6,18 @@ import type { Migration } from '@ultimat3/db';
6
6
  import { db, dbClientInstalled, isLedgerMissing, readLedger } from '@ultimat3/db';
7
7
  import { AppMigrationsUnappliedError } from './app-migrations-verdict';
8
8
  import { type AppliedRow, refuseEdited } from './db-applied-edits';
9
- import { devCanMigrate, MIGRATE_ALONE_FIX } from './dev-db-migrate';
10
9
  import { checkSourceDrift } from './drift';
11
10
  import { readMigrations } from './migrations';
12
11
  import type { Finding } from './output';
13
12
  import { findingFrom } from './output';
14
- import { resolveServices } from './runtime-bindings';
15
13
 
16
14
  /**
17
15
  * The migrate half too: `x dev` applies no migration unasked, so `x db gen` alone leaves the page
18
- * red. Beside this process `x db migrate` is applied BY it (`dev-db-migrate.ts`), embedded or not.
16
+ * red. Beside this process `x db migrate` is applied BY it (`dev-db-migrate.ts`), embedded or not,
17
+ * and with `database.rowSecurity` as `x_migrator` under a hold (`dev-db-migrator-hold.ts`).
19
18
  */
20
19
  export const SCHEMA_AHEAD_FIX = 'x db gen "describe the change" && x db migrate';
21
20
 
22
- /** Where this process cannot apply the pass itself: the embedded database, to the command alone. */
23
- export const SCHEMA_AHEAD_FIX_ALONE = `x db gen "describe the change" && ${MIGRATE_ALONE_FIX}`;
24
-
25
- /** Whether `x db migrate` works while this `x dev` runs: any external database, or a pass it takes. */
26
- export async function migratesBesideDev(root: string): Promise<boolean> {
27
- return resolveServices(root, Bun.env).db.mode !== 'embedded' || (await devCanMigrate(root));
28
- }
29
-
30
21
  /** What `ledgerFindings` asks — the seam a test hands rows through. */
31
22
  export interface LedgerReads {
32
23
  readonly migrations: (root: string) => Promise<readonly Migration[]>;
@@ -62,7 +53,6 @@ const READS: LedgerReads = {
62
53
  */
63
54
  export async function ledgerFindings(
64
55
  root: string,
65
- beside: (root: string) => Promise<boolean> = migratesBesideDev,
66
56
  reads: LedgerReads = READS,
67
57
  ): Promise<readonly Finding[]> {
68
58
  const migrations = await reads.migrations(root);
@@ -72,10 +62,9 @@ export async function ledgerFindings(
72
62
  const missing = migrations.map((migration) => migration.id).filter((id) => !applied.has(id));
73
63
  const findings: Finding[] = [];
74
64
  if (missing.length > 0) {
75
- const behind = findingFrom(
76
- new AppMigrationsUnappliedError({ missing, ledger: ledger !== undefined }),
65
+ findings.push(
66
+ findingFrom(new AppMigrationsUnappliedError({ missing, ledger: ledger !== undefined })),
77
67
  );
78
- findings.push((await beside(root)) ? behind : { ...behind, fix: MIGRATE_ALONE_FIX });
79
68
  }
80
69
  try {
81
70
  refuseEdited(ledger ?? [], migrations);
@@ -109,23 +98,17 @@ function marked(findings: readonly Finding[]): readonly Finding[] {
109
98
  export async function schemaAheadFindings(
110
99
  root: string,
111
100
  check: (root: string) => Promise<readonly Finding[]> = checkSourceDrift,
112
- beside: (root: string) => Promise<boolean> = migratesBesideDev,
113
- ledger: (
114
- root: string,
115
- beside: (root: string) => Promise<boolean>,
116
- ) => Promise<readonly Finding[]> = ledgerFindings,
101
+ ledger: (root: string) => Promise<readonly Finding[]> = ledgerFindings,
117
102
  ): Promise<readonly Finding[]> {
118
103
  try {
119
104
  const drifted = await check(root);
120
- const fix =
121
- drifted.length === 0 || (await beside(root)) ? SCHEMA_AHEAD_FIX : SCHEMA_AHEAD_FIX_ALONE;
122
105
  return marked([
123
106
  ...drifted.map((finding) => ({
124
107
  ...finding,
125
108
  cause: `entities are ahead of the migrations: ${finding.cause}`,
126
- fix,
109
+ fix: SCHEMA_AHEAD_FIX,
127
110
  })),
128
- ...(await ledger(root, beside)),
111
+ ...(await ledger(root)),
129
112
  ]);
130
113
  } catch (error) {
131
114
  return marked([findingFrom(error)]);