@ultimat3/cli 31.5.0 → 31.6.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 (43) hide show
  1. package/CLAUDE.md +14 -7
  2. package/package.json +29 -29
  3. package/src/admin-catalog-keys.ts +17 -1
  4. package/src/app-transport.ts +7 -3
  5. package/src/browser-barrel-cut.ts +109 -0
  6. package/src/browser-import-chain.ts +119 -0
  7. package/src/browser-transport.ts +85 -13
  8. package/src/cmd-dev.ts +15 -2
  9. package/src/cmd-fix.ts +14 -4
  10. package/src/cmd-i18n.ts +52 -10
  11. package/src/dev-boot.ts +6 -4
  12. package/src/dev-log.ts +95 -0
  13. package/src/dev-rebuild-remount.ts +152 -0
  14. package/src/dev-rebuild-schema.ts +30 -0
  15. package/src/dev-rebuild.ts +51 -14
  16. package/src/dev-supervisor.ts +5 -4
  17. package/src/error-codes.ts +2 -0
  18. package/src/error-contract.ts +29 -2
  19. package/src/fix-sequence.ts +97 -0
  20. package/src/generate-grant-findings.ts +2 -2
  21. package/src/generate-grants.ts +50 -1
  22. package/src/generate-write.ts +16 -0
  23. package/src/i18n-registration.ts +8 -5
  24. package/src/load-findings.ts +29 -22
  25. package/src/mcp-errors.ts +11 -3
  26. package/src/mcp-host-shell.ts +128 -0
  27. package/src/mcp-host.ts +19 -54
  28. package/src/mcp-test-output.ts +5 -2
  29. package/src/messages-gate.ts +12 -0
  30. package/src/messages.ts +16 -0
  31. package/src/policy-append.ts +88 -0
  32. package/src/templates/entity.ts +18 -3
  33. package/src/templates/policy.ts +5 -1
  34. package/src/templates/query.ts +4 -2
  35. package/src/templates/resource-service.ts +5 -2
  36. package/src/templates/scaffold-repo.ts +8 -2
  37. package/src/ts-scan.ts +86 -1
  38. package/src/verify-checks.ts +23 -51
  39. package/src/verify-contract-diff.ts +143 -0
  40. package/src/verify-seeds.ts +132 -0
  41. package/src/verify-tests.ts +12 -6
  42. package/wiki/CLI-Reference.md +2 -2
  43. package/wiki/Upgrading.md +3 -0
package/src/cmd-fix.ts CHANGED
@@ -6,8 +6,10 @@
6
6
  import { ERROR_DOCS_URL, nearestName } from '@ultimat3/core';
7
7
  import { appImportGraph, readAppSources } from './app-boundaries';
8
8
  import { requireAppRoot } from './app-root';
9
+ import { appTransportFindings } from './app-transport';
9
10
  import type { BoundaryCut } from './boundary-cuts';
10
11
  import { planBoundaryCuts } from './boundary-cuts';
12
+ import { browserCutJson, involvesTarget } from './browser-barrel-cut';
11
13
  import { fixSpec } from './cmd-fix-spec';
12
14
  import type { CliCommand, CommandContext } from './command';
13
15
  import { BadFlagError, FixTargetUnknownError, MissingPositionalError } from './errors';
@@ -110,8 +112,12 @@ export const fixCommand: CliCommand = {
110
112
  files.map((source) => source.path),
111
113
  );
112
114
  const cuts = planBoundaryCuts(target, appImportGraph(files));
115
+ // The browser graph too: an island's server barrel is a boundary its author has to cut.
116
+ const browser = (await appTransportFindings(root, files)).filter((finding) =>
117
+ involvesTarget(finding, target),
118
+ );
113
119
 
114
- if (cuts.length === 0) {
120
+ if (cuts.length === 0 && browser.length === 0) {
115
121
  return {
116
122
  ok: true,
117
123
  command: 'fix',
@@ -123,9 +129,13 @@ export const fixCommand: CliCommand = {
123
129
  return {
124
130
  ok: false,
125
131
  command: 'fix',
126
- summary: msg('cli.fix.plan', { count: cuts.length, file: target, edits: editCount(cuts) }),
127
- findings: cuts.map(findingForCut),
128
- data: { file: target, cuts: cuts.map(cutJson) },
132
+ summary: msg('cli.fix.plan', {
133
+ count: cuts.length + browser.length,
134
+ file: target,
135
+ edits: editCount(cuts) + new Set(browser.map((one) => one.fix)).size,
136
+ }),
137
+ findings: [...cuts.map(findingForCut), ...browser],
138
+ data: { file: target, cuts: [...cuts.map(cutJson), ...browser.map(browserCutJson)] },
129
139
  };
130
140
  },
131
141
  };
package/src/cmd-i18n.ts CHANGED
@@ -10,7 +10,8 @@ import { type FileHandle, mkdir, open } from 'node:fs/promises';
10
10
  import { dirname, join } from 'node:path';
11
11
  import { DEFAULT_LOCALE, stringField } from '@ultimat3/core';
12
12
  import type { Catalog } from '@ultimat3/i18n';
13
- import { auditCatalogs, catalogKeys } from '@ultimat3/i18n';
13
+ import { auditCatalogs, catalogFor, catalogKeys } from '@ultimat3/i18n';
14
+ import { adminKeyLabel, mountedAdminKeys } from './admin-catalog-keys';
14
15
  import { loadApp } from './app-load';
15
16
  import { requireAppRoot } from './app-root';
16
17
  import { i18nSpec } from './cmd-i18n-spec';
@@ -29,8 +30,10 @@ import { syncI18nIndex } from './i18n-index';
29
30
  import { localeParityFindings } from './i18n-locale-parity';
30
31
  import {
31
32
  checkRegistration,
33
+ isLoudMiss,
32
34
  loudMiss,
33
35
  missingKeyFindings,
36
+ unanswered,
34
37
  withPlaceholdersMissing,
35
38
  } from './i18n-registration';
36
39
  import { msg } from './messages';
@@ -118,6 +121,14 @@ function resolveOneLocale(ctx: CommandContext, sub: string): string {
118
121
  return locale;
119
122
  }
120
123
 
124
+ /**
125
+ * The admin-derived keys `locale`'s REGISTRY does not answer with a real string — the question
126
+ * `checkRegistration` asks of the same keys, so `sync` writes and `check` counts exactly what the
127
+ * `i18n` step refuses. Asked after `loadApp`: the registry holds the app's catalogs only then.
128
+ */
129
+ const unansweredAdminKeys = (locale: string, keys: readonly string[]): readonly string[] =>
130
+ unanswered(catalogFor(locale), keys);
131
+
121
132
  async function runCheck(root: string): Promise<CommandResult> {
122
133
  const { report: audited, catalogs, extraction, ignoreUnused } = await auditApp(root);
123
134
  // Corrected once, before anything reads it: the table's `missing` column, the summary count, the
@@ -165,11 +176,22 @@ async function runCheck(root: string): Promise<CommandResult> {
165
176
  }
166
177
 
167
178
  // A key that renders a loud miss counts once, whichever half of the check found it: a missing
168
- // catalog entry and an entry no registry holds are the same `⟦key⟧` on the same page.
179
+ // catalog entry and an entry no registry holds are the same `⟦key⟧` on the same page. The keys a
180
+ // mounted admin derives are counted too — they fail `ok`, and a summary of "0 missing key(s)"
181
+ // over `ok: false` sent the reader looking for a finding the count said was not there.
182
+ const adminKeys = await mountedAdminKeys();
183
+ const adminGaps = Object.keys(catalogs)
184
+ .filter((locale) => !unregistered.has(locale))
185
+ .map((locale) => ({ locale, missing: unansweredAdminKeys(locale, adminKeys).length }))
186
+ .filter((gap) => gap.missing > 0);
169
187
  const gapLocales =
170
- report.locales.filter((audit) => audit.missing.length > 0).length + registration.locales;
188
+ new Set([
189
+ ...report.locales.filter((audit) => audit.missing.length > 0).map((audit) => audit.locale),
190
+ ...adminGaps.map((gap) => gap.locale),
191
+ ]).size + registration.locales;
171
192
  const missingTotal =
172
193
  report.locales.reduce((sum, audit) => sum + audit.missing.length, 0) +
194
+ adminGaps.reduce((sum, gap) => sum + gap.missing, 0) +
173
195
  registration.unregistered;
174
196
  const ok = report.ok && registration.ok && parity.length === 0;
175
197
  // The summary names the parity findings when there are any: `cli.i18n.gaps` counts MISSING KEYS,
@@ -270,6 +292,20 @@ async function untranslatedKeys(
270
292
  const placeholderCatalog = (keys: readonly string[]): Catalog =>
271
293
  Object.fromEntries(keys.map((key) => [key, loudMiss(key)]));
272
294
 
295
+ /**
296
+ * The keys a mounted admin derives that `locale` does not answer — spelled in no source file, so
297
+ * the source scan above can never seed one, and `X_CATALOG_MISSING_KEYS` names this command as the
298
+ * fix for them all the same. The default locale gets the label `x g resource --admin` writes
299
+ * (`adminKeyLabel`), a real string the gate accepts; any other locale gets it MARKED, a translation
300
+ * a human still owes, exactly as a merged key is.
301
+ */
302
+ async function adminCatalog(locale: string, seeded: boolean): Promise<Catalog> {
303
+ const keys = unansweredAdminKeys(locale, await mountedAdminKeys());
304
+ const label = (key: string): string =>
305
+ seeded ? adminKeyLabel(key) : loudMiss(adminKeyLabel(key));
306
+ return Object.fromEntries(keys.map((key) => [key, label(key)]));
307
+ }
308
+
273
309
  async function runSync(root: string, ctx: CommandContext): Promise<CommandResult> {
274
310
  const locale = resolveOneLocale(ctx, 'sync');
275
311
  const catalogs = await loadCatalogs(root);
@@ -290,9 +326,14 @@ async function runSync(root: string, ctx: CommandContext): Promise<CommandResult
290
326
  // A real merge copies the default locale's strings MARKED (`seedCatalog`, as `x i18n add` does):
291
327
  // copied bare they rendered English to every `fr` reader under a green gate.
292
328
  const seeded = from === undefined || from === locale;
293
- const source = seeded
294
- ? placeholderCatalog(await untranslatedKeys(root, catalogs, locale))
295
- : seedCatalog(catalogs[from] ?? {});
329
+ // The admin's keys first, so a value the default locale already carries for one (copied, marked)
330
+ // wins over a label read off the key.
331
+ const source = {
332
+ ...(await adminCatalog(locale, seeded)),
333
+ ...(seeded
334
+ ? placeholderCatalog(await untranslatedKeys(root, catalogs, locale))
335
+ : seedCatalog(catalogs[from] ?? {})),
336
+ };
296
337
  const { merged, added } = syncCatalog(target, source);
297
338
  if (added.length > 0) await Bun.write(join(root, catalogPath(locale)), serializeCatalog(merged));
298
339
  // Unconditional, and not only when keys moved: a catalog that reached disk some other way — a
@@ -319,10 +360,11 @@ async function runSync(root: string, ctx: CommandContext): Promise<CommandResult
319
360
  total,
320
361
  path: catalogPath(locale),
321
362
  registered,
322
- // Which of `added` still need a human: all of them. `⟦key⟧` where there was no catalog to
323
- // copy from, `⟦<default string>⟧` on a real merge — both are what `x i18n check` counts as
324
- // missing until replaced, so `--json` never reports a copy as a translation.
325
- placeholders: added,
363
+ // Which of `added` still need a human: every one but an admin label in the default locale.
364
+ // `⟦key⟧` where there was no catalog to copy from, `⟦<default string>⟧` on a real merge —
365
+ // both are what `x i18n check` counts as missing until replaced, so `--json` never reports a
366
+ // copy as a translation.
367
+ placeholders: added.filter((key) => isLoudMiss(merged[key])),
326
368
  },
327
369
  };
328
370
  }
package/src/dev-boot.ts CHANGED
@@ -73,11 +73,13 @@ export interface StartDevOptions {
73
73
  readonly roles?: readonly Role[];
74
74
  readonly onReload?: (file: string, durationMs: number) => void;
75
75
  /**
76
- * A save reached a module that defines a primitive, so this process cannot serve it
77
- * (`takeStalePins`). Given, it is called INSTEAD of `onReload` — `x dev`'s child drains and exits
78
- * for its supervisor to boot a fresh one. Absent, the save is `X_DEV_RESTART_REQUIRED` on `/_x`.
76
+ * A save this process cannot serve: it reached a module that defines a primitive
77
+ * (`takeStalePins`), or changed what the boot mounted (`dev-rebuild-remount.ts`). Given, it is
78
+ * called INSTEAD of `onReload` — `x dev`'s child prints `line`, the restart's own reason, then
79
+ * drains and exits for its supervisor to boot a fresh one. Absent, the save is
80
+ * `X_DEV_RESTART_REQUIRED` on `/_x`.
79
81
  */
80
- readonly onRestart?: (pins: readonly StalePin[]) => void;
82
+ readonly onRestart?: (pins: readonly StalePin[], line: string) => void;
81
83
  }
82
84
 
83
85
  /**
package/src/dev-log.ts ADDED
@@ -0,0 +1,95 @@
1
+ // `x dev`'s log on disk: every line the process logger writes, teed into `<stateDir>/dev.log`
2
+ // beside the terminal, so the dev MCP server's `logs.tail` has a file to read. Rotated once at
3
+ // 16 MiB (`dev.log.1`): a dev server left up for a week must not fill the disk.
4
+
5
+ // why: Bun has no synchronous append, rename or mkdir. A log line is written synchronously so the
6
+ // last line before a crash is on disk, and rotation is one rename.
7
+ import {
8
+ closeSync,
9
+ existsSync,
10
+ mkdirSync,
11
+ openSync,
12
+ renameSync,
13
+ statSync,
14
+ writeSync,
15
+ } from 'node:fs';
16
+ // why: Bun exposes no path-join primitive.
17
+ import { join } from 'node:path';
18
+ import type { LogLevel } from '@ultimat3/core';
19
+ import { installLogSink } from '@ultimat3/core';
20
+ import { writeErrorLine, writeLine } from './write-line';
21
+
22
+ export const DEV_LOG_FILENAME = 'dev.log';
23
+ /** The size at which `dev.log` becomes `dev.log.1` and starts over. */
24
+ export const DEV_LOG_MAX_BYTES = 16 * 1024 * 1024;
25
+
26
+ export const devLogPath = (stateDir: string): string => join(stateDir, DEV_LOG_FILENAME);
27
+
28
+ export interface DevLog {
29
+ /** One line; the newline is added here. */
30
+ write(line: string): void;
31
+ close(): void;
32
+ }
33
+
34
+ const sizeOf = (path: string): number => (existsSync(path) ? statSync(path).size : 0);
35
+
36
+ /**
37
+ * The file, appended to: a restarted `x dev` child (`dev-supervisor.ts`) continues the log the
38
+ * last one wrote, and what it already held counts toward the cap.
39
+ */
40
+ export function openDevLog(stateDir: string, maxBytes: number = DEV_LOG_MAX_BYTES): DevLog {
41
+ const path = devLogPath(stateDir);
42
+ // External database and storage leave the state directory uncreated (`runtime-bindings.ts`).
43
+ mkdirSync(stateDir, { recursive: true });
44
+ let size = sizeOf(path);
45
+ let fd = openSync(path, 'a');
46
+ const encoder = new TextEncoder();
47
+ return {
48
+ write(line: string): void {
49
+ const bytes = encoder.encode(`${line}\n`);
50
+ if (size > 0 && size + bytes.length > maxBytes) {
51
+ closeSync(fd);
52
+ renameSync(path, `${path}.1`);
53
+ fd = openSync(path, 'a');
54
+ size = 0;
55
+ }
56
+ writeSync(fd, bytes);
57
+ size += bytes.length;
58
+ },
59
+ close(): void {
60
+ closeSync(fd);
61
+ },
62
+ };
63
+ }
64
+
65
+ /** Where a terminal line goes: the CLI's own synchronous fd writers, by default. */
66
+ export type TerminalWrite = (line: string, stream: 'stdout' | 'stderr') => void;
67
+
68
+ const toTerminal: TerminalWrite = (line, stream) =>
69
+ stream === 'stderr' ? writeErrorLine(line) : writeLine(line);
70
+
71
+ const ERROR_LEVELS: ReadonlySet<LogLevel> = new Set(['error', 'fatal']);
72
+
73
+ /**
74
+ * Tee the process logger into `dev.log` until the returned release runs. The terminal keeps the
75
+ * lanes core's own writer uses: `--json` (`dispatch.ts`'s `setLogStream('stderr')`) and every
76
+ * `error`/`fatal` line on stderr, the rest on stdout — stdout under `--json` is the document.
77
+ */
78
+ export function teeDevLog(
79
+ stateDir: string,
80
+ options: { readonly json: boolean; readonly write?: TerminalWrite },
81
+ ): () => void {
82
+ const log = openDevLog(stateDir);
83
+ const terminal = options.write ?? toTerminal;
84
+ const release = installLogSink((line, level) => {
85
+ log.write(line);
86
+ terminal(line, options.json || ERROR_LEVELS.has(level) ? 'stderr' : 'stdout');
87
+ });
88
+ let released = false;
89
+ return () => {
90
+ if (released) return;
91
+ released = true;
92
+ release();
93
+ log.close();
94
+ };
95
+ }
@@ -0,0 +1,152 @@
1
+ // Whether a rebuilt generation can be served by the process that built it. `x dev` mounts its route
2
+ // table ONCE, at boot (`dev-route-table.ts`): a page, action, query, channel, admin or mount that
3
+ // appeared or vanished in a save is a 404 (or a dead handler) until a new process mounts it. A load
4
+ // finding that appeared or cleared is the same question, asked of the modules that did not import.
5
+
6
+ import type { Manifest } from '@ultimat3/manifest';
7
+ import type { MessageKey } from './messages';
8
+ import { msg } from './messages';
9
+ import type { Finding } from './output';
10
+
11
+ /** One thing the boot mounted: `key` says whether it is the same thing, `label` names it. */
12
+ interface Mounted {
13
+ readonly kind: 'route' | 'action' | 'query' | 'channel' | 'admin' | 'mount';
14
+ readonly key: string;
15
+ readonly label: string;
16
+ }
17
+
18
+ /** Why a generation needs a new process — and exactly what moved, for the restart line. */
19
+ export type Remount =
20
+ | {
21
+ readonly kind: 'surface';
22
+ readonly added: readonly string[];
23
+ readonly removed: readonly string[];
24
+ }
25
+ | {
26
+ readonly kind: 'findings';
27
+ readonly failing: readonly string[];
28
+ readonly loads: readonly string[];
29
+ };
30
+
31
+ /** What the boot mounted from `manifest`. Never the handlers' bodies: an edited body reloads. */
32
+ function mountedOf(manifest: Manifest): readonly Mounted[] {
33
+ const named = (kind: Mounted['kind'], name: string): Mounted => ({
34
+ kind,
35
+ key: name,
36
+ label: name,
37
+ });
38
+ return [
39
+ ...manifest.routes.map((route): Mounted => {
40
+ const key = `${route.url} (${route.render}${route.surface === undefined ? '' : `, ${route.surface}`})`;
41
+ return { kind: 'route', key, label: key };
42
+ }),
43
+ ...manifest.actions.map((action) => named('action', action.name)),
44
+ ...manifest.queries.map((query) => named('query', query.name)),
45
+ ...(manifest.channels ?? []).map((channel) => named('channel', channel.name)),
46
+ ...(manifest.admin ?? []).map(
47
+ (admin): Mounted => ({ kind: 'admin', key: JSON.stringify(admin), label: admin.basePath }),
48
+ ),
49
+ ...(manifest.mounts ?? []).map(
50
+ (mount): Mounted => ({ kind: 'mount', key: JSON.stringify(mount), label: mount.prefix }),
51
+ ),
52
+ ];
53
+ }
54
+
55
+ /**
56
+ * Each kind's catalog word, spelled out so every key is a literal the catalog is checked against.
57
+ * A switch, not a table: `item.kind` is read off a mount, and a computed table read can answer an
58
+ * `Object.prototype` member (`bun run proto-index`); the switch is exhaustive by its return type.
59
+ */
60
+ function kindWord(kind: Mounted['kind']): MessageKey {
61
+ switch (kind) {
62
+ case 'route':
63
+ return 'cli.dev.mounted.route';
64
+ case 'action':
65
+ return 'cli.dev.mounted.action';
66
+ case 'query':
67
+ return 'cli.dev.mounted.query';
68
+ case 'channel':
69
+ return 'cli.dev.mounted.channel';
70
+ case 'admin':
71
+ return 'cli.dev.mounted.admin';
72
+ case 'mount':
73
+ return 'cli.dev.mounted.mount';
74
+ }
75
+ }
76
+
77
+ const mountedId = (item: Mounted): string => `${item.kind}\u0000${item.key}`;
78
+
79
+ /** `before` less `after`, as the catalog's words: `route /fresh (ssr, app)`. */
80
+ const missingFrom = (before: readonly Mounted[], after: readonly Mounted[]): string[] => {
81
+ const kept = new Set(after.map(mountedId));
82
+ return before
83
+ .filter((item) => !kept.has(mountedId(item)))
84
+ .map((item) => msg(kindWord(item.kind), { name: item.label }));
85
+ };
86
+
87
+ const findingKey = (finding: Finding): string =>
88
+ [finding.code, finding.at ?? '', finding.cause].join('\u0000');
89
+
90
+ /** Where each finding of `before` that `after` no longer holds was raised, deduplicated. */
91
+ const clearedAt = (before: readonly Finding[], after: readonly Finding[]): string[] => {
92
+ const kept = new Set(after.map(findingKey));
93
+ const gone = before.filter((finding) => !kept.has(findingKey(finding)));
94
+ return [...new Set(gone.map((finding) => finding.at ?? finding.code))];
95
+ };
96
+
97
+ export interface Generation {
98
+ readonly manifest: Manifest;
99
+ readonly findings: readonly Finding[];
100
+ }
101
+
102
+ /**
103
+ * `surface` first: it is the cause of the 404 a fixed load failure left behind. A finding that
104
+ * appeared or cleared restarts too, so the ready line a fresh child prints is the generation's own
105
+ * verdict — red while a module will not import, green the save after it does. Order-insensitive:
106
+ * a reordered scan is not a different answer.
107
+ */
108
+ export function remountReason(before: Generation, after: Generation): Remount | undefined {
109
+ const was = mountedOf(before.manifest);
110
+ const now = mountedOf(after.manifest);
111
+ const added = missingFrom(now, was);
112
+ const removed = missingFrom(was, now);
113
+ if (added.length > 0 || removed.length > 0) return { kind: 'surface', added, removed };
114
+ const failing = clearedAt(after.findings, before.findings);
115
+ const loads = clearedAt(before.findings, after.findings);
116
+ if (failing.length > 0 || loads.length > 0) return { kind: 'findings', failing, loads };
117
+ return undefined;
118
+ }
119
+
120
+ /** What moved, one comma-separated list: `route /fresh (ssr, app) added, query feed removed`. */
121
+ function changes(remount: Remount): string {
122
+ const words =
123
+ remount.kind === 'surface'
124
+ ? [
125
+ ...remount.added.map((what) => msg('cli.dev.change.added', { what })),
126
+ ...remount.removed.map((what) => msg('cli.dev.change.removed', { what })),
127
+ ]
128
+ : [
129
+ ...remount.failing.map((file) => msg('cli.dev.change.failing', { file })),
130
+ ...remount.loads.map((file) => msg('cli.dev.change.loads', { file })),
131
+ ];
132
+ return words.join(', ');
133
+ }
134
+
135
+ /** The restart line `x dev` prints for a generation it cannot mount — true to why. */
136
+ export function remountLine(remount: Remount, file: string): string {
137
+ const key = remount.kind === 'surface' ? 'cli.dev.restartSurface' : 'cli.dev.restartFindings';
138
+ return msg(key, { file, changes: changes(remount) });
139
+ }
140
+
141
+ /** `/_x`'s finding when nothing supervises the process (an embedded `startDev()`, no `onRestart`). */
142
+ export function remountFinding(remount: Remount, file: string): Finding {
143
+ return {
144
+ code: 'X_DEV_RESTART_REQUIRED',
145
+ cause:
146
+ remount.kind === 'surface'
147
+ ? `the save to ${file} changed what x dev mounts (${changes(remount)}) — the route table is built once, at boot, so this process answers 404 for what was added`
148
+ : `the save to ${file} changed which modules load (${changes(remount)}) — a module that failed to import is served only by a new process`,
149
+ fix: 'x stop && x dev',
150
+ at: file,
151
+ };
152
+ }
@@ -0,0 +1,30 @@
1
+ // The schema half of an `x dev` generation: entities ahead of the migrations, said when the
2
+ // generation is built — at the boot a restart makes, and at a save — instead of first as
3
+ // `X_DB_SCHEMA_STALE` on the page that queries the new column.
4
+
5
+ import { checkSourceDrift } from './drift';
6
+ import type { Finding } from './output';
7
+ import { findingFrom } from './output';
8
+
9
+ /** The migrate half too: `x dev` applies no migration, so `x db gen` alone leaves the page red. */
10
+ export const SCHEMA_AHEAD_FIX = 'x db gen "describe the change" && x db migrate';
11
+
12
+ /**
13
+ * `checkSourceDrift`'s answer with the whole instruction. Asked only of a generation that loaded
14
+ * clean: a module that would not import leaves the registry short, which hashes as drift that is not
15
+ * there. Never rejects — a failed check is a finding, never a dev server that will not boot.
16
+ */
17
+ export async function schemaAheadFindings(
18
+ root: string,
19
+ check: (root: string) => Promise<readonly Finding[]> = checkSourceDrift,
20
+ ): Promise<readonly Finding[]> {
21
+ try {
22
+ return (await check(root)).map((finding) => ({
23
+ ...finding,
24
+ cause: `entities are ahead of the migrations: ${finding.cause}`,
25
+ fix: SCHEMA_AHEAD_FIX,
26
+ }));
27
+ } catch (error) {
28
+ return [findingFrom(error)];
29
+ }
30
+ }
@@ -2,6 +2,9 @@
2
2
  // one generation, the ISR store emptied, and a save this process cannot serve handed to the
3
3
  // supervisor as a restart. Coalesced, so a tick arriving mid-build is one trailing rebuild.
4
4
 
5
+ // why: Bun ships no path API; a restart's pins are absolute, the watcher's file is root-relative.
6
+ import { resolve } from 'node:path';
7
+
5
8
  import type { Manifest } from '@ultimat3/manifest';
6
9
  import { beginDeviceSocketGeneration } from '@ultimat3/realtime/server';
7
10
  import type { IsrController } from '@ultimat3/render/server';
@@ -9,12 +12,15 @@ import type { AppManifest } from './app-manifest';
9
12
  import { appManifest } from './app-manifest';
10
13
  import type { StalePin } from './app-reload-graph';
11
14
  import { takeStalePins } from './app-reload-graph';
15
+ import { remountFinding, remountLine, remountReason } from './dev-rebuild-remount';
16
+ import { schemaAheadFindings } from './dev-rebuild-schema';
12
17
  import type { ReloadTrigger } from './dev-reload';
13
18
  import { coalesceReloads } from './dev-reload';
14
- import { restartFinding } from './dev-supervisor';
19
+ import { restartFinding, restartReason } from './dev-supervisor';
15
20
  import type { BuildIslandsOptions, IslandBundle } from './island-bundle';
16
21
  import { buildIslands } from './island-bundle';
17
22
  import { appPersistsRecords } from './island-realtime-state';
23
+ import { msg } from './messages';
18
24
  import type { Finding } from './output';
19
25
  import { findingFrom } from './output';
20
26
 
@@ -38,13 +44,19 @@ export interface DevState {
38
44
  islands: IslandBundle;
39
45
  }
40
46
 
41
- /** The two builders of one generation — the seam a test times them through. */
47
+ /** The builders of one generation — the seam a test times them through. */
42
48
  export interface GenerationBuilders {
43
49
  readonly manifest: (root: string) => Promise<AppManifest>;
44
50
  readonly islands: (root: string, options: BuildIslandsOptions) => Promise<IslandBundle>;
51
+ /** Entities ahead of the migrations (`dev-rebuild-schema.ts`); asked once the load is clean. */
52
+ readonly schema: (root: string) => Promise<readonly Finding[]>;
45
53
  }
46
54
 
47
- const BUILDERS: GenerationBuilders = { manifest: appManifest, islands: buildIslands };
55
+ const BUILDERS: GenerationBuilders = {
56
+ manifest: appManifest,
57
+ islands: buildIslands,
58
+ schema: schemaAheadFindings,
59
+ };
48
60
 
49
61
  /**
50
62
  * One generation — the app's manifest and its island bundle — both builders started at once, at
@@ -65,18 +77,26 @@ export async function buildGeneration(
65
77
  () => appPersistsRecords(),
66
78
  () => undefined,
67
79
  );
68
- const [{ manifest, findings }, islands] = await Promise.all([
80
+ // After the load, beside the island build: the hash reads the registry the load filled, and a
81
+ // load with findings left it short — drift that is not there, so it is not asked.
82
+ const schema = loaded.then(({ findings }) => (findings.length > 0 ? [] : build.schema(root)));
83
+ const [{ manifest, findings }, islands, ahead] = await Promise.all([
69
84
  loaded,
70
85
  build.islands(root, { persists }),
86
+ schema,
71
87
  ]);
72
- return { manifest, findings, islands };
88
+ return { manifest, findings: [...findings, ...ahead], islands };
73
89
  }
74
90
 
75
91
  /** What a rebuild reports to, read off `StartDevOptions`. */
76
92
  export interface DevRebuildOptions {
77
93
  readonly root: string;
78
94
  readonly onReload?: (file: string, durationMs: number) => void;
79
- readonly onRestart?: (pins: readonly StalePin[]) => void;
95
+ /**
96
+ * `line` is the restart's own reason, rendered — a pinned module, a changed surface or a load
97
+ * finding that appeared or cleared — so the log never states one cause for another.
98
+ */
99
+ readonly onRestart?: (pins: readonly StalePin[], line: string) => void;
80
100
  }
81
101
 
82
102
  /**
@@ -103,6 +123,9 @@ export function devRebuilder(
103
123
  isr: IsrController,
104
124
  refreshDevices: () => Promise<readonly string[]>,
105
125
  ): ReloadTrigger {
126
+ // What the route table was built from: the boot's generation, for the life of this process. Each
127
+ // save is compared with IT, not with the save before — a route added two saves ago is still a 404.
128
+ const mounted = { manifest: state.manifest, findings: state.appFindings };
106
129
  // One rebuild at a time, and the last save wins: a tick arriving mid-build coalesces into ONE
107
130
  // trailing rebuild instead of racing the one in flight for `state.manifest` and `state.islands`.
108
131
  return coalesceReloads(
@@ -110,6 +133,7 @@ export function devRebuilder(
110
133
  const started = performance.now();
111
134
  beginDeviceSocketGeneration();
112
135
  const { manifest, findings, islands } = await buildGeneration(options.root);
136
+ const remount = remountReason(mounted, { manifest, findings });
113
137
  state.manifest = manifest;
114
138
  state.appFindings = findings;
115
139
  state.islands = islands;
@@ -118,16 +142,29 @@ export function devRebuilder(
118
142
  for (const path of await isr.store().paths()) await isr.store().delete(path);
119
143
  state.reloads += 1;
120
144
  // Read on EVERY rebuild, so a pin one save reached is never reported against the next save.
121
- const pins = takeStalePins();
145
+ const stale = takeStalePins();
146
+ // A generation this process cannot mount is a restart named after the saved file — never
147
+ // "reloaded" over a route table built for the generation before it.
148
+ const saved = resolve(options.root, file);
149
+ const pins =
150
+ stale.length > 0 || remount === undefined ? stale : [{ changed: saved, pinned: saved }];
122
151
  const [device] = unserved;
123
152
  state.reloadFinding =
124
- pins.length > 0 && options.onRestart === undefined
125
- ? restartFinding(options.root, pins)
126
- : device === undefined
127
- ? undefined
128
- : unservedDeviceFinding(device, file);
129
- if (pins.length > 0 && options.onRestart !== undefined) options.onRestart(pins);
130
- else options.onReload?.(file, Math.round(performance.now() - started));
153
+ stale.length > 0 && options.onRestart === undefined
154
+ ? restartFinding(options.root, stale)
155
+ : device !== undefined
156
+ ? unservedDeviceFinding(device, file)
157
+ : remount !== undefined && options.onRestart === undefined
158
+ ? remountFinding(remount, file)
159
+ : undefined;
160
+ if (pins.length > 0 && options.onRestart !== undefined) {
161
+ options.onRestart(
162
+ pins,
163
+ stale.length > 0 || remount === undefined
164
+ ? msg('cli.dev.restart', { reason: restartReason(options.root, stale) })
165
+ : remountLine(remount, file),
166
+ );
167
+ } else options.onReload?.(file, Math.round(performance.now() - started));
131
168
  },
132
169
  // Same rule as a module that will not import: a save the manifest cannot be rebuilt from is
133
170
  // a finding on `/_x`, never an unhandled rejection that takes the dev server down.
@@ -17,7 +17,6 @@ import {
17
17
  import { devPortFor } from './dev-port';
18
18
  import { type RetiringWorker, retireThenDrain } from './dev-restart-retire';
19
19
  import { PORT_RANGE } from './flag-number';
20
- import { msg } from './messages';
21
20
  import type { Finding } from './output';
22
21
  import { parseArgs } from './parse';
23
22
  import { posixRelative } from './posix-path';
@@ -237,7 +236,7 @@ export function restartFinding(root: string, pins: readonly StalePin[]): Finding
237
236
 
238
237
  /** The child's half: what `startDev` is handed, and what the hold calls once released. */
239
238
  export interface ChildRestart {
240
- readonly options: { readonly onRestart?: (pins: readonly StalePin[]) => void };
239
+ readonly options: { readonly onRestart?: (pins: readonly StalePin[], line: string) => void };
241
240
  readonly exit: (code: number) => void;
242
241
  /**
243
242
  * The worker this child booted, handed over once `startDev` returns: a restart retires it before
@@ -278,11 +277,13 @@ export function childRestart(
278
277
  });
279
278
  return {
280
279
  options: {
281
- onRestart: (pins) => {
280
+ // `line` is the rebuild's, rendered for the restart's own cause (`dev-rebuild.ts`): a pinned
281
+ // module, a changed route table or a load finding that appeared or cleared.
282
+ onRestart: (_pins, line) => {
282
283
  // Already stopping for a signal (`x stop`, Ctrl-C) or a gone supervisor or root: a save
283
284
  // landing during that drain must not respawn a child its operator asked to end.
284
285
  if (leaving !== undefined && leaving !== 'restart') return;
285
- writeErrorLine(msg('cli.dev.restart', { reason: restartReason(root, pins) }));
286
+ writeErrorLine(line);
286
287
  leaving ??= 'restart';
287
288
  watched?.stopping(DEV_RESTART_EXIT_CODE);
288
289
  if (restarting) return;
@@ -237,6 +237,7 @@ export const CLI_OWNED_ERROR_CODES = [
237
237
  'X_WORKSPACE_NAME_TAKEN',
238
238
  'X_PARTITIONS_UNMAINTAINED',
239
239
  'X_TYPESCRIPT_VERSION',
240
+ 'X_SEED_FAILED',
240
241
  ] as const;
241
242
 
242
243
  /**
@@ -460,6 +461,7 @@ export const CLI_ERROR_TITLES: Readonly<Record<CliListedErrorCode, string>> = {
460
461
  'x g app or x g package was given a name the other workspace kind already holds',
461
462
  X_PARTITIONS_UNMAINTAINED: 'a partitioned entity with no partitions() job',
462
463
  X_TYPESCRIPT_VERSION: 'The app declares a TypeScript older than the one x new scaffolds',
464
+ X_SEED_FAILED: 'a seed threw an uncoded error',
463
465
  };
464
466
 
465
467
  // One unconditional call, so a second package claiming one of the CLI's codes throws