@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
@@ -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
@@ -112,25 +112,52 @@ export interface ErrorFixReport {
112
112
  * relative specifiers only, and that gap is 3 call sites across this repo, measured 2026-08.
113
113
  */
114
114
  readonly unreadable: number;
115
+ /** File → fix lines `fix-sequence.ts` refused there, allowed or not: what the baseline must equal. */
116
+ readonly sequenceRefused: ReadonlyMap<string, number>;
117
+ }
118
+
119
+ /**
120
+ * `fix-sequence.ts`'s rule, ratcheted per file: a file at or under its recorded count passes, and
121
+ * past it every refused line is reported — a text scan cannot tell which of them is the new one.
122
+ */
123
+ function sequenceRefusals(
124
+ sites: readonly FixSite[],
125
+ fixSequenceProblem: (fix: string) => string | undefined,
126
+ ): readonly Finding[] {
127
+ return sites.flatMap((site) => {
128
+ const problem = fixSequenceProblem(staticFix(site.fix));
129
+ return problem === undefined ? [] : [fixFinding(site, problem)];
130
+ });
115
131
  }
116
132
 
117
133
  export async function checkErrorFixReport(root: string): Promise<ErrorFixReport> {
118
134
  const findings: Finding[] = [];
119
135
  const catalog = await loadCommandCatalog();
136
+ // At its point of use, like the catalog: `app-load.ts` imports this module for
137
+ // `collectDeclaredCodes`, and a gate-only rule must not ride into every serving role's graph
138
+ // (`serve-graph.test.ts`'s `SERVING_ROLE_CEILING`).
139
+ const { FIX_SEQUENCE_BASELINE, fixSequenceProblem, generatorForceProblem } = await import(
140
+ './fix-sequence'
141
+ );
120
142
  const imports = createHelperResolver(root);
121
143
  let checked = 0;
122
144
  let unreadable = 0;
145
+ const sequenceRefused = new Map<string, number>();
123
146
  for await (const path of eachSourceFile(root)) {
124
147
  if (isTest(path) || isGenerated(path)) continue;
125
148
  const source = await Bun.file(join(root, path)).text();
126
149
  const scan = scanFixSites(source, path, await imports(path, source));
127
150
  checked += scan.sites.length;
128
151
  unreadable += scan.unreadable;
152
+ const refused = sequenceRefusals(scan.sites, fixSequenceProblem);
153
+ if (refused.length > 0) sequenceRefused.set(path, refused.length);
154
+ if (refused.length > (FIX_SEQUENCE_BASELINE.get(path) ?? 0)) findings.push(...refused);
129
155
  for (const site of scan.sites) {
130
156
  // The interpolation-blanked form for both rules: `x ${name}` names no command this can
131
157
  // resolve, and reading `<value>` as one would be a finding nobody can act on.
132
158
  const fix = staticFix(site.fix);
133
- const problem = fixProblem(site.fix) ?? citedCommandProblem(fix, catalog);
159
+ const problem =
160
+ fixProblem(site.fix) ?? generatorForceProblem(fix) ?? citedCommandProblem(fix, catalog);
134
161
  if (problem !== undefined) {
135
162
  findings.push(fixFinding(site, problem));
136
163
  continue;
@@ -141,7 +168,7 @@ export async function checkErrorFixReport(root: string): Promise<ErrorFixReport>
141
168
  if (missing !== undefined) findings.push(pathFinding(site, missing));
142
169
  }
143
170
  }
144
- return { findings, checked, unreadable };
171
+ return { findings, checked, unreadable, sequenceRefused };
145
172
  }
146
173
 
147
174
  /** The findings alone, for every caller that reports no coverage line. */
package/src/favicon.ts CHANGED
@@ -10,6 +10,7 @@ import { join } from 'node:path';
10
10
  import { blankRaster, encodeImage } from '@ultimat3/core';
11
11
  import type { CacheHint, Route, UltimateRequest } from '@ultimat3/http';
12
12
  import { applyCacheHeaders } from '@ultimat3/http';
13
+ import { assetRouteMeta } from './asset-route-meta';
13
14
 
14
15
  /** What a browser asks for with no `<link rel="icon">` to tell it otherwise. */
15
16
  export const FAVICON_PATH = '/favicon.ico';
@@ -108,6 +109,6 @@ export async function faviconResponse(root: string): Promise<Response> {
108
109
  export const faviconRoute = (root: string): Route => ({
109
110
  method: 'GET',
110
111
  path: FAVICON_PATH,
111
- meta: { name: 'assets.favicon', auth: 'public', cache: FAVICON_CACHE, tags: ['assets'] },
112
+ meta: assetRouteMeta({ name: 'assets.favicon', auth: 'public', cache: FAVICON_CACHE }),
112
113
  handler: async (_request: UltimateRequest): Promise<Response> => faviconResponse(root),
113
114
  });
@@ -0,0 +1,97 @@
1
+ // The order rule on a `fix:` line, for the `errors` step: the edit leads, the re-run follows —
2
+ // `x verify # after deleting .sensitive()` is pasted before it is read, and re-runs unchanged.
3
+ // Shipped lines are ratcheted per file in `FIX_SEQUENCE_BASELINE`; a new one is
4
+ // `X_ERROR_FIX_INVALID`. A generator offered with `--force` is never a fix (none shipped 2026-11).
5
+
6
+ /**
7
+ * A comment opening with the precondition, in its deferred-edit form only: `<command> # after
8
+ * editing …` (a gerund, a call, or an interpolated edit) or `# once … is repaired` (a past
9
+ * participle). A `#` glued to a word is a URL fragment (`…/Upgrading#after-31`), and `# once per
10
+ * environment` / `# once, at boot` is a frequency — neither is refused.
11
+ */
12
+ const DEFERRED_EDIT =
13
+ /(?:^|\s)#\s+(?:(after)\s+(?:\w+ing\b|[\w.$]+\(|<value>)|(once)\s+(?!(?:per|only|a|an|each|every|more)\b)[^#,]*?\b\w+ed\b)/i;
14
+
15
+ /**
16
+ * A line whose whole instruction is to run the failing command again: an optional "fix the
17
+ * failure / cause / error, then", the re-run, and nothing it names to change.
18
+ */
19
+ const RERUN_ONLY =
20
+ /^\s*(?:(?:fix|resolve|address|correct|repair)\b[^,.;#]*\b(?:cause|failure|error|problem)\b[^,.;#]*[,;]?\s*(?:then|and)\s+)?(?:re-?run|retry|run (?:it |this )?again)(?:\s+(?:it|this|the command|this command))?\s*\.?\s*$/i;
21
+
22
+ /**
23
+ * The rule, on one fix line — already `staticFix`ed by the caller, as every rule of the step reads
24
+ * it. `undefined` means the line leads with what to change.
25
+ */
26
+ export function fixSequenceProblem(fix: string): string | undefined {
27
+ const deferred = DEFERRED_EDIT.exec(fix);
28
+ if (deferred !== null) {
29
+ return `fix "${fix}" opens with the command and defers the edit to "# ${deferred[1] ?? deferred[2]} …", so the line pasted first re-runs the failure unchanged — lead with the edit, then the command`;
30
+ }
31
+ if (RERUN_ONLY.test(fix)) {
32
+ return `fix "${fix}" only says to re-run, and names no edit, call or file that would make the re-run pass`;
33
+ }
34
+ return undefined;
35
+ }
36
+
37
+ /** `x g …` / `x generate …` carrying `--force`, before any `#` comment: the part that is pasted. */
38
+ const FORCED_GENERATOR = /(?:^|[\s;|&(])x\s+(?:g|generate)\b[^#]*?\s--force(?![\w-])/;
39
+
40
+ /**
41
+ * A printed fix is pasted with no diff in front of it, and a generator's file can be shared — a
42
+ * slice's `policy.ts` holds every permission its generators wrote, and `x g policy … --force`
43
+ * replaced the first with the second (FX2). Prose behind the `#` is not pasted, so it is not read.
44
+ */
45
+ export function generatorForceProblem(fix: string): string | undefined {
46
+ const runnable = fix.split(/\s#\s/)[0] ?? '';
47
+ if (!FORCED_GENERATOR.test(runnable)) return undefined;
48
+ return `fix "${fix}" runs a generator with --force, which overwrites a file other slices or generators may share, and a pasted fix shows no diff first — name the edit to the existing file instead`;
49
+ }
50
+
51
+ /**
52
+ * Root-relative file → how many fix lines in it the rule above refuses: 53 lines in 38 files across
53
+ * this repo and its three tracked apps, measured 2026-11-11 (the docs site's
54
+ * `packages/docs-source/src/errors.ts` is the one app entry). A file at or under its count passes;
55
+ * one past it, or any file not listed — every app's — is a finding at each of its refused lines.
56
+ * Held EQUAL to the step's counts by `fix-sequence.test.ts`: rewrite a line, lower its entry.
57
+ */
58
+ export const FIX_SEQUENCE_BASELINE: ReadonlyMap<string, number> = new Map([
59
+ ['packages/cli/src/cmd-client-customer.ts', 1],
60
+ ['packages/cli/src/cmd-deploy-preflight.ts', 1],
61
+ ['packages/cli/src/cmd-env-init.ts', 1],
62
+ ['packages/cli/src/handle-registration.ts', 1],
63
+ ['packages/cli/src/job-registration.ts', 1],
64
+ ['packages/cli/src/package-boundaries.ts', 1],
65
+ ['packages/cli/src/upgrade-plan.ts', 1],
66
+ ['packages/cli/src/verify-drift-owner.ts', 1],
67
+ ['packages/core/src/define-error.ts', 1],
68
+ ['packages/core/src/errors.ts', 1],
69
+ ['packages/db/src/drift-triggers.ts', 1],
70
+ ['packages/db/src/generate-partition.ts', 2],
71
+ ['packages/db/src/lifecycle-errors.ts', 1],
72
+ ['packages/db/src/primary-key.ts', 1],
73
+ ['packages/docs-source/src/errors.ts', 4],
74
+ ['packages/entity/src/counter.ts', 1],
75
+ ['packages/entity/src/partition.ts', 1],
76
+ ['packages/entity/src/retain.ts', 1],
77
+ ['packages/jobs/src/subject-errors.ts', 1],
78
+ ['packages/mail/src/preview-check.ts', 1],
79
+ ['packages/mcp/src/meta-errors.ts', 1],
80
+ ['packages/mcp/src/remote-errors.ts', 1],
81
+ ['packages/schema/src/sensitive.ts', 1],
82
+ ['packages/seo/src/errors.ts', 1],
83
+ ['packages/testing/src/exercise-override-input.ts', 1],
84
+ ['packages/testing/src/plan-sweep-report.ts', 4],
85
+ ['scripts/adapter-ports.ts', 4],
86
+ ['scripts/bench-claims.ts', 1],
87
+ ['scripts/budget-raises.ts', 1],
88
+ ['scripts/declaration-readers-callers.ts', 2],
89
+ ['scripts/factory-names.ts', 2],
90
+ ['scripts/instrument-slots.ts', 1],
91
+ ['scripts/lib/export-all.ts', 1],
92
+ ['scripts/new-error-code.ts', 1],
93
+ ['scripts/plan-status.ts', 3],
94
+ ['scripts/posix-relative.ts', 1],
95
+ ['scripts/set-cookie-literals.ts', 2],
96
+ ['scripts/sql-export-readers.ts', 1],
97
+ ]);
@@ -8,9 +8,9 @@ import { appDisk } from './generate-disk';
8
8
  import type { RoleGrant } from './generate-grants';
9
9
  import {
10
10
  adminGrantsFor,
11
- grantsForWritten,
12
11
  insertGrants,
13
12
  insertPermissions,
13
+ policyGrantsFor,
14
14
  writtenTables,
15
15
  } from './generate-grants';
16
16
  import type { Finding } from './output';
@@ -49,7 +49,7 @@ export async function ungrantedByGenerator(
49
49
  disk: GenerateDisk = appDisk(root),
50
50
  ): Promise<readonly Finding[]> {
51
51
  const admin = (await writtenTables(root, written, disk)).flatMap(adminGrantsFor);
52
- const grants = [...grantsForWritten(written), ...admin];
52
+ const grants = [...(await policyGrantsFor(root, written, disk)), ...admin];
53
53
  if (grants.length === 0) return [];
54
54
  const source = await disk.read(ROLES_FILE);
55
55
  // The file whose declarations nobody granted: where a reader starts when the map is not ours.
@@ -39,6 +39,55 @@ export function grantsForWritten(written: readonly string[]): readonly RoleGrant
39
39
  });
40
40
  }
41
41
 
42
+ /** `member` reads, `admin` does everything else — `grantsForWritten`'s rule, per permission. */
43
+ const grantFor = (permission: string): RoleGrant => ({
44
+ role: permission.endsWith(':read') ? 'member' : 'admin',
45
+ permission,
46
+ });
47
+
48
+ /** The string literals of the `definePermissions([...])` list opening at `open`. */
49
+ const literalsAt = (source: string, masked: string, open: number): readonly string[] =>
50
+ (readList(source, masked, open)?.entries ?? []).flatMap((entry) => {
51
+ const literal = /^'([^']+)'$/.exec(entry.text.trim())?.[1];
52
+ return literal === undefined ? [] : [literal];
53
+ });
54
+
55
+ /** Every permission a policy's `definePermissions([...])` calls declare, comments masked. */
56
+ export function declaredPermissions(source: string): readonly string[] {
57
+ const masked = maskOf(source);
58
+ return declarationLists(masked).flatMap((open) => literalsAt(source, masked, open));
59
+ }
60
+
61
+ /**
62
+ * The set a generator run WROTE into a policy: its LAST `definePermissions([...])` call. A fresh
63
+ * file holds one call, the template's; an append (`policy-append.ts`) puts its set after
64
+ * everything the author had. Never every declared permission: a hand-placed admin-only
65
+ * `payroll:read` earlier in the file would be granted to `member` by the next `x g policy`.
66
+ */
67
+ export function introducedPermissions(source: string): readonly string[] {
68
+ const masked = maskOf(source);
69
+ const last = declarationLists(masked).at(-1);
70
+ return last === undefined ? [] : literalsAt(source, masked, last);
71
+ }
72
+
73
+ /**
74
+ * The grants the written policies imply: the set each run introduced, read off the file as it now
75
+ * stands — or, a file this cannot read a declaration from, the slice-path rule of
76
+ * `grantsForWritten`.
77
+ */
78
+ export async function policyGrantsFor(
79
+ root: string,
80
+ written: readonly string[],
81
+ disk: GenerateDisk = appDisk(root),
82
+ ): Promise<readonly RoleGrant[]> {
83
+ const grants: RoleGrant[] = [];
84
+ for (const path of written.filter((each) => POLICY_PATH.test(each))) {
85
+ const introduced = introducedPermissions((await disk.read(path)) ?? '');
86
+ grants.push(...(introduced.length > 0 ? introduced.map(grantFor) : grantsForWritten([path])));
87
+ }
88
+ return grants;
89
+ }
90
+
42
91
  /** `entity('widgets', {` — the name the admin's permissions are spelled with. */
43
92
  const ENTITY_NAME = /\bentity\(\s*'([^']+)'/;
44
93
 
@@ -166,7 +215,7 @@ export async function grantGeneratedPermissions(
166
215
  disk: GenerateDisk = appDisk(root),
167
216
  ): Promise<readonly string[]> {
168
217
  const admin = (await writtenTables(root, written, disk)).flatMap(adminGrantsFor);
169
- const grants = [...grantsForWritten(written), ...admin];
218
+ const grants = [...(await policyGrantsFor(root, written, disk)), ...admin];
170
219
  const before = grants.length === 0 ? undefined : await disk.read(ROLES_FILE);
171
220
  if (before === undefined) return [];
172
221
  const unplaced = insertGrants(before, grants).skipped;