@ultimat3/cli 31.4.2 → 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 (57) hide show
  1. package/CLAUDE.md +15 -7
  2. package/package.json +29 -29
  3. package/src/admin-catalog-keys.ts +17 -1
  4. package/src/app-boundaries.ts +3 -2
  5. package/src/app-transport.ts +7 -3
  6. package/src/asset-route-meta.ts +29 -0
  7. package/src/browser-barrel-cut.ts +109 -0
  8. package/src/browser-import-chain.ts +119 -0
  9. package/src/browser-transport.ts +85 -13
  10. package/src/cmd-dev.ts +15 -2
  11. package/src/cmd-drill.ts +39 -9
  12. package/src/cmd-fix.ts +14 -4
  13. package/src/cmd-i18n.ts +52 -10
  14. package/src/dev-boot.ts +6 -4
  15. package/src/dev-log.ts +95 -0
  16. package/src/dev-rebuild-remount.ts +152 -0
  17. package/src/dev-rebuild-schema.ts +30 -0
  18. package/src/dev-rebuild.ts +51 -14
  19. package/src/dev-supervisor.ts +5 -4
  20. package/src/error-codes.ts +2 -0
  21. package/src/error-contract.ts +29 -2
  22. package/src/favicon.ts +2 -1
  23. package/src/fix-sequence.ts +97 -0
  24. package/src/generate-grant-findings.ts +2 -2
  25. package/src/generate-grants.ts +50 -1
  26. package/src/generate-write.ts +16 -0
  27. package/src/i18n-registration.ts +8 -5
  28. package/src/island-routes.ts +2 -1
  29. package/src/load-findings.ts +29 -22
  30. package/src/mcp-errors.ts +11 -3
  31. package/src/mcp-host-shell.ts +128 -0
  32. package/src/mcp-host.ts +81 -55
  33. package/src/mcp-test-output.ts +5 -2
  34. package/src/messages-gate.ts +12 -0
  35. package/src/messages.ts +16 -0
  36. package/src/policy-append.ts +88 -0
  37. package/src/pwa-artifacts.ts +3 -3
  38. package/src/runtime-assets.ts +4 -1
  39. package/src/site-asset-routes.ts +2 -1
  40. package/src/style-routes.ts +2 -1
  41. package/src/templates/entity.ts +18 -3
  42. package/src/templates/guard-repo-raw-sql.ts +6 -3
  43. package/src/templates/policy.ts +5 -1
  44. package/src/templates/query.ts +4 -2
  45. package/src/templates/resource-service.ts +5 -2
  46. package/src/templates/scaffold-repo.ts +8 -2
  47. package/src/ts-scan.ts +86 -1
  48. package/src/verify-checks.ts +23 -51
  49. package/src/verify-contract-diff.ts +143 -0
  50. package/src/verify-seeds.ts +132 -0
  51. package/src/verify-tests.ts +12 -6
  52. package/src/worker-bundle.ts +2 -1
  53. package/wiki/CLI-Reference.md +2 -2
  54. package/wiki/Entities-And-Migrations.md +3 -3
  55. package/wiki/Interface-Rules.md +2 -2
  56. package/wiki/Project-Layout.md +3 -3
  57. package/wiki/Upgrading.md +7 -0
@@ -18,6 +18,7 @@
18
18
  // one module later (`transport-values.ts`), reported with a fix that removes the hand-off.
19
19
 
20
20
  import { ERROR_DOCS_URL, maskLiterals } from '@ultimat3/core';
21
+ import { importChain, namesFrom } from './browser-import-chain';
21
22
  import { commentSafe } from './comment-safe';
22
23
  import type { ClosureHost } from './import-closure';
23
24
  import { importClosure } from './import-closure';
@@ -37,6 +38,17 @@ export interface Bypass extends TransportCall {
37
38
 
38
39
  export interface ServerBarrel extends BarrelImport {
39
40
  readonly file: string;
41
+ /** The browser entry that reaches `file`, first, and `file` last: `[file]` when it IS the entry. */
42
+ readonly chain: readonly string[];
43
+ /** The import in `chain[0]` that starts the chain — the edge a cut deletes. */
44
+ readonly hop?: { readonly spec: string; readonly line: number };
45
+ /** What `file` takes from the barrel; `'*'` is the whole module. */
46
+ readonly names: readonly string[] | '*';
47
+ /**
48
+ * The edit is the swap to the browser entry, at `file` — else the cut of the entry's first hop.
49
+ * A swap only when the entry publishes every name taken; unread, only when `file` IS the entry.
50
+ */
51
+ readonly swaps: boolean;
40
52
  }
41
53
 
42
54
  export const isIsland = (path: string): boolean => path.endsWith('.island.tsx');
@@ -78,6 +90,11 @@ export interface TransportInput {
78
90
  readonly barrels: ReadonlyMap<string, string>;
79
91
  /** A package's own modules may import its own barrel; only a FOREIGN import pays for it. */
80
92
  readonly ownsBarrel?: (file: string, barrel: string) => boolean;
93
+ /**
94
+ * Browser entry → every name it exports, where the caller could read it. A swap promised without
95
+ * it compiles only by luck: `entity()` is in the barrel and not in `@ultimat3/entity/record`.
96
+ */
97
+ readonly published?: ReadonlyMap<string, ReadonlySet<string>>;
81
98
  }
82
99
 
83
100
  /** The whole rule over a tree, pure. */
@@ -88,7 +105,6 @@ export function checkBrowserTransport(input: TransportInput): {
88
105
  } {
89
106
  const reachable = importClosure(input.host, input.entries);
90
107
  const bypasses: Bypass[] = [];
91
- const barrels: ServerBarrel[] = [];
92
108
  for (const file of reachable) {
93
109
  if (input.exempt?.has(file) === true) continue;
94
110
  const source = input.host.read(file) ?? '';
@@ -100,12 +116,34 @@ export function checkBrowserTransport(input: TransportInput): {
100
116
  if (input.seams.get(value.shape) === file) continue;
101
117
  bypasses.push({ ...value, file, passed: true });
102
118
  }
103
- for (const found of barrelImports(source, input.barrels)) {
104
- if (input.ownsBarrel?.(file, found.barrel) === true) continue;
105
- barrels.push({ ...found, file });
119
+ }
120
+ return { reachable, bypasses, barrels: serverBarrelSites(input) };
121
+ }
122
+
123
+ /**
124
+ * Per ENTRY, never per tree: a barrel three hops below two islands is two mistakes, one in each
125
+ * island, and a finding that names only the module it landed in blames a file nobody edited.
126
+ */
127
+ function serverBarrelSites(input: TransportInput): readonly ServerBarrel[] {
128
+ const barrels: ServerBarrel[] = [];
129
+ for (const entry of input.entries) {
130
+ for (const file of importClosure(input.host, [entry])) {
131
+ if (input.exempt?.has(file) === true) continue;
132
+ const source = input.host.read(file) ?? '';
133
+ for (const found of barrelImports(source, input.barrels)) {
134
+ if (input.ownsBarrel?.(file, found.barrel) === true) continue;
135
+ const path = importChain(input.host, entry, file) ?? { chain: [entry, file] };
136
+ const names = namesFrom(source, found.barrel);
137
+ const published = input.published?.get(found.entry);
138
+ const swaps =
139
+ published === undefined
140
+ ? entry === file
141
+ : names !== '*' && names.every((name) => published.has(name));
142
+ barrels.push({ ...found, file, ...path, names, swaps });
143
+ }
106
144
  }
107
145
  }
108
- return { reachable, bypasses, barrels };
146
+ return barrels;
109
147
  }
110
148
 
111
149
  /**
@@ -143,8 +181,8 @@ const siteOf = (site: { readonly file: string; readonly line: number }): string
143
181
  `${commentSafe(site.file)}:${site.line}`;
144
182
 
145
183
  /**
146
- * One runnable line, the edit behind a `#` — the shape `app-boundaries.ts` gives every fix. The
147
- * command re-reads the tree; the comment is the edit, because only the finding knows the line.
184
+ * The edit first, the re-read after: a line pasted before it is read must not re-run the failure
185
+ * unchanged (`fix-sequence.ts`). Only the finding knows the line, so it names it.
148
186
  */
149
187
  export function bypassFinding(bypass: Bypass, context: FindingContext): Finding {
150
188
  if (bypass.passed === true) return passedFinding(bypass, context);
@@ -154,7 +192,7 @@ export function bypassFinding(bypass: Bypass, context: FindingContext): Finding
154
192
  code: 'X_BROWSER_TRANSPORT_BYPASS',
155
193
  at: `${bypass.file}:${bypass.line}`,
156
194
  cause: `${site} calls ${bypass.spelled} in browser-reachable code; ${holder === undefined ? 'no module may' : `only ${holder} may`}, so this request skips the page's record store, idempotency header and principal fence`,
157
- fix: `${context.rerun} # after replacing ${bypass.spelled} at ${site} with ${REPLACEMENT.get(bypass.shape) ?? ''}`,
195
+ fix: `edit ${commentSafe(bypass.file)}:${bypass.line} — replace ${bypass.spelled} with ${REPLACEMENT.get(bypass.shape) ?? ''}; then ${context.rerun}`,
158
196
  docs: ERROR_DOCS_URL,
159
197
  };
160
198
  }
@@ -171,18 +209,52 @@ function passedFinding(bypass: Bypass, context: FindingContext): Finding {
171
209
  code: 'X_BROWSER_TRANSPORT_BYPASS',
172
210
  at: `${bypass.file}:${bypass.line}`,
173
211
  cause: `${site} passes the global ${bypass.spelled} as a value in browser-reachable code; whatever receives it calls it directly, and ${holder === undefined ? 'no module may' : `only ${holder} may`}, so those requests skip the page's record store, idempotency header and principal fence`,
174
- fix: `${context.rerun} # after deleting ${bypass.spelled} at ${site} (rpc() and queryClient() send through clientTransport when given none) and making the module that took it use ${REPLACEMENT.get(bypass.shape) ?? ''}`,
212
+ fix: `edit ${commentSafe(bypass.file)}:${bypass.line} — delete ${bypass.spelled} (rpc() and queryClient() send through clientTransport when given none), and make the module that took it use ${REPLACEMENT.get(bypass.shape) ?? ''}; then ${context.rerun}`,
175
213
  docs: ERROR_DOCS_URL,
176
214
  };
177
215
  }
178
216
 
179
- export function barrelFinding(site: ServerBarrel, context: FindingContext): Finding {
217
+ /**
218
+ * Where the barrel is cut (`ServerBarrel.swaps`). A site that needs the server half is server code,
219
+ * so the mistake is the browser entry's first hop: that edge is the one to delete. `meta` carries
220
+ * the chain for a `--json` reader and for `x fix boundary`, which lists the cut for any file on it.
221
+ */
222
+ export function barrelFinding(site: ServerBarrel, _context: FindingContext): Finding {
223
+ const entry = site.chain[0] ?? site.file;
180
224
  const at = siteOf(site);
225
+ const meta = {
226
+ entry,
227
+ chain: [...site.chain],
228
+ sites: [`${site.file}:${site.line}`],
229
+ barrel: site.barrel,
230
+ browserEntry: site.entry,
231
+ names: site.names === '*' ? '*' : [...site.names],
232
+ cut: site.swaps ? 'swap' : 'entry',
233
+ ...(site.hop === undefined ? {} : { hop: { spec: site.hop.spec, line: site.hop.line } }),
234
+ };
235
+ const through = site.chain.length > 1 ? ` (${site.chain.map(commentSafe).join(' → ')})` : '';
236
+ if (site.swaps) {
237
+ return {
238
+ code: 'X_BROWSER_SERVER_BARREL',
239
+ at: `${site.file}:${site.line}`,
240
+ cause: `${at} imports ${site.barrel} in browser-reachable code${through}; that barrel is the package's server half, and ${site.entry} is the entry it publishes for a browser`,
241
+ fix: `edit ${commentSafe(site.file)}:${site.line} — change the import from '${site.barrel}' to '${site.entry}'`,
242
+ docs: ERROR_DOCS_URL,
243
+ meta,
244
+ };
245
+ }
246
+ const taken = site.names === '*' ? 'the whole module' : site.names.join(', ');
247
+ const cut =
248
+ site.hop === undefined
249
+ ? { line: site.line, spec: site.barrel }
250
+ : { line: site.hop.line, spec: site.hop.spec };
251
+ const where = siteOf({ file: entry, line: cut.line });
181
252
  return {
182
253
  code: 'X_BROWSER_SERVER_BARREL',
183
- at: `${site.file}:${site.line}`,
184
- cause: `${at} imports ${site.barrel} in browser-reachable code; that barrel is the package's server half, and ${site.entry} is the entry it publishes for a browser`,
185
- fix: `${context.rerun} # after changing the import at ${at} from '${site.barrel}' to '${site.entry}'`,
254
+ at: `${entry}:${cut.line}`,
255
+ cause: `${where} pulls server code into a browser bundle: ${at} takes ${taken} from ${site.barrel}, its server half, not ${site.entry}${through}`,
256
+ fix: `edit ${commentSafe(entry)}:${cut.line} — delete the import of '${cut.spec}' and every use of what it binds; in a browser, read rows through a query (useQuery(<QUERY_REF>, input) from '@ultimat3/realtime') and write through an action (await browserClient.<action>(input))`,
186
257
  docs: ERROR_DOCS_URL,
258
+ meta,
187
259
  };
188
260
  }
package/src/cmd-dev.ts CHANGED
@@ -11,6 +11,7 @@ import { devSpec } from './cmd-dev-spec';
11
11
  import type { CliCommand, CommandContext } from './command';
12
12
  import { startDev } from './dev-boot';
13
13
  import { clearLock, preflight, writeLock } from './dev-lock';
14
+ import { teeDevLog } from './dev-log';
14
15
  import { devPortFor } from './dev-port';
15
16
  import { childRestart } from './dev-supervisor';
16
17
  import { holdUntilShutdown } from './hold';
@@ -53,6 +54,9 @@ export const devCommand: CliCommand = {
53
54
  // The directory is CLAIMED from here down, so a boot that throws has to give it back — the
54
55
  // `releaseBoot` shape, with one acquisition. Without it the first failed `x dev` in a shell
55
56
  // refuses every later one with a pid that is no longer running.
57
+ // Before the boot, so its own lines are in it: `logs.tail` reads this file, and a dev server
58
+ // that never wrote it answered every agent with X_NOT_IMPLEMENTED.
59
+ const untee = teeDevLog(services.stateDir, { json: ctx.args.json });
56
60
  const restart = childRestart(root, ctx.env);
57
61
  const server = await startDev({
58
62
  root,
@@ -66,6 +70,7 @@ export const devCommand: CliCommand = {
66
70
  ...restart.options,
67
71
  }).catch((error: unknown) => {
68
72
  release();
73
+ untee();
69
74
  throw error;
70
75
  });
71
76
  // A restart retires this worker before it drains, so a save never cancels a running job.
@@ -136,7 +141,11 @@ export const devCommand: CliCommand = {
136
141
  });
137
142
  if (ctx.args.flags.get('once') === true) {
138
143
  clearLock(services.stateDir);
139
- await server.stop();
144
+ try {
145
+ await server.stop();
146
+ } finally {
147
+ untee();
148
+ }
140
149
  return result;
141
150
  }
142
151
  // Long-running: `dispatch` awaits this instead of exiting, so the watcher keeps reloading and
@@ -151,7 +160,11 @@ export const devCommand: CliCommand = {
151
160
  // The lock first: a stop() that throws must not leave a file claiming this pid still owns
152
161
  // the directory, because the next boot would then refuse for a process that is gone.
153
162
  clearLock(services.stateDir);
154
- await server.stop();
163
+ try {
164
+ await server.stop();
165
+ } finally {
166
+ untee();
167
+ }
155
168
  },
156
169
  // Released — the port, the lock and the embedded database are free for the next child.
157
170
  { exit: restart.exit },
package/src/cmd-drill.ts CHANGED
@@ -5,7 +5,13 @@
5
5
 
6
6
  import type { AppConfig } from '@ultimat3/core';
7
7
  import { DRAIN_DEADLINE_DEFAULT_MS, MAX_TIMER_MS } from '@ultimat3/core';
8
- import type { Drill, DrillConfig, DrillDeclarations, DrillReport } from '@ultimat3/testing';
8
+ import type {
9
+ Drill,
10
+ DrillConfig,
11
+ DrillDeclarations,
12
+ DrillFleet,
13
+ DrillReport,
14
+ } from '@ultimat3/testing';
9
15
  import {
10
16
  bunDrillSql,
11
17
  DRILL_NAMES,
@@ -90,6 +96,33 @@ const findingsOf = (report: DrillReport): readonly Finding[] =>
90
96
  return { code: error.code, cause: error.cause, fix: error.fix };
91
97
  });
92
98
 
99
+ /** The evidence connection: `bunDrillSql`'s shape, a seam so a test can make it throw. */
100
+ type DrillSqlConnection = ReturnType<typeof bunDrillSql>;
101
+
102
+ /**
103
+ * One drill's body over a started fleet, which is ALWAYS stopped. The fleet is spawned role
104
+ * processes: the connection was opened before the `try`, so a constructor that threw (a malformed
105
+ * URL is a synchronous `Invalid URL`) left every role running, and a `close()` that threw skipped
106
+ * `stop()` the same way.
107
+ */
108
+ export async function withDrillFleet<T>(
109
+ fleet: Pick<DrillFleet, 'databaseUrl' | 'stop'>,
110
+ open: (url: string) => DrillSqlConnection,
111
+ body: (sql: DrillSqlConnection) => Promise<T>,
112
+ ): Promise<T> {
113
+ let sql: DrillSqlConnection | undefined;
114
+ try {
115
+ sql = open(fleet.databaseUrl);
116
+ return await body(sql);
117
+ } finally {
118
+ try {
119
+ await sql?.close();
120
+ } finally {
121
+ await fleet.stop();
122
+ }
123
+ }
124
+ }
125
+
93
126
  export const drillCommand: CliCommand = {
94
127
  spec: drillSpec,
95
128
  async run(ctx: CommandContext): Promise<CommandResult> {
@@ -147,14 +180,11 @@ export const drillCommand: CliCommand = {
147
180
  roles: drillRoles(drill),
148
181
  readyTimeoutMs: READY_TIMEOUT_MS,
149
182
  });
150
- const sql = bunDrillSql(fleet.databaseUrl);
151
- try {
152
- const sync = drillSyncLane(fleet);
153
- reports.push(await runDrill({ drill, fleet, budgets, targets, sql, sync }));
154
- } finally {
155
- await sql.close();
156
- await fleet.stop();
157
- }
183
+ reports.push(
184
+ await withDrillFleet(fleet, bunDrillSql, (sql) =>
185
+ runDrill({ drill, fleet, budgets, targets, sql, sync: drillSyncLane(fleet) }),
186
+ ),
187
+ );
158
188
  }
159
189
  const held = reports.filter((report) => report.verdict.ok).length;
160
190
  const findings = reports.flatMap(findingsOf);
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
+ }