@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/mcp-host.ts CHANGED
@@ -36,21 +36,19 @@ import type {
36
36
  QueryLimits,
37
37
  QueryRows,
38
38
  VerifyResult,
39
- VerifyStep,
40
39
  } from '@ultimat3/mcp';
41
40
  import { DEV_SCOPES, devHost, devMcpServer, frameworkIntrospection } from '@ultimat3/mcp';
42
41
  import { loadApp } from './app-load';
43
42
  import { appManifest, policyFacts } from './app-manifest';
44
43
  import { loadAppRuntime } from './app-runtime';
45
44
  import { loadAppGraph, resolveNode } from './cmd-graph-load';
46
- import { runVerify, VERIFY_STEPS } from './cmd-verify';
47
- import { declareDevEnvironment } from './dev-environment';
45
+ import { declareDevEnvironment, needsDevEnvironmentDeclaration } from './dev-environment';
48
46
  import { loadCodeFixes } from './error-fixes';
49
47
  import { BadFlagError } from './errors';
50
48
  import type { Runner } from './exec';
51
49
  import { databaseTarget } from './mcp-db-target';
52
50
  import { explainErrorCode } from './mcp-errors';
53
- import { testRunOf } from './mcp-test-run';
51
+ import { type ShellRunInput, shellRunner, shellTests, shellVerify } from './mcp-host-shell';
54
52
  import { type UiCapabilities, uiCapabilities } from './mcp-ui';
55
53
  import { readMigrations } from './migrations';
56
54
  import { retryMemo } from './retry-memo';
@@ -59,8 +57,6 @@ import type { DevServices, Env } from './runtime-bindings';
59
57
  import { resolveServices } from './runtime-bindings';
60
58
  import type { RunningServices } from './runtime-services';
61
59
  import { startServices } from './runtime-services';
62
- import { testEnvOverrides } from './test-dotenv';
63
- import { measurePace } from './verify-pace';
64
60
 
65
61
  export interface DevHostInput {
66
62
  readonly root: string;
@@ -197,24 +193,6 @@ export async function readOnlyRows(
197
193
  return { columns, rows: kept.map((row) => columns.map((column) => row[column])), guards };
198
194
  }
199
195
 
200
- /**
201
- * `bun test`'s argv for a `test.run` filter. A filter is a PATH, and one starting with `-` is a
202
- * `bun test` flag — `--preload ./x.ts` loads a module into the child — so it is refused rather
203
- * than forwarded: a filter is a path, and no path this suite has starts with `-`.
204
- */
205
- export function testRunArgv(filter: string | undefined): readonly string[] {
206
- if (filter === undefined) return ['bun', 'test'];
207
- if (filter.trimStart().startsWith('-')) {
208
- throw new BadFlagError({
209
- flag: 'filter',
210
- command: 'mcp serve',
211
- reason: `test.run's filter "${filter}" starts with "-", which bun test would read as its own flag`,
212
- fix: 'call test.run with a path filter such as packages/cli/src, or with no filter',
213
- });
214
- }
215
- return ['bun', 'test', filter];
216
- }
217
-
218
196
  /**
219
197
  * `db.migrate`'s answer to a foreign throw. The fix is the REGISTERED one (`mcp-errors.ts`), never
220
198
  * a literal here: this said `x db reset`, and an agent that followed it wiped the database the
@@ -284,8 +262,10 @@ function capabilities(
284
262
  input: DevHostInput,
285
263
  lazy: LazyServices,
286
264
  ui: UiCapabilities,
265
+ declared: boolean,
287
266
  ): DevCapabilities {
288
- const { root, runner, env } = input;
267
+ const { root } = input;
268
+ const shell: ShellRunInput = { ...input, declared };
289
269
  // Layer 1 is seven idempotent DDL statements, and `db.query` is a tool an agent calls in a
290
270
  // loop — resolve the role once per process and reuse the answer, `null` included. A FAILED
291
271
  // resolution is not an answer: `??=` kept the rejection, so a statement timeout on the DDL
@@ -338,31 +318,21 @@ function capabilities(
338
318
  }));
339
319
  },
340
320
 
341
- // `bun test <filter>` matches on the test path, the same rule `x test`'s `discoverTests` uses.
342
- async runTests(filter: string | undefined) {
343
- // Same leak the CLI's own `x test`/`x verify` had: `.env.development` auto-loaded into
344
- // THIS process must not ride along into the `bun test` child the dev MCP server spawns.
345
- const envOverrides = testEnvOverrides(root, env);
346
- const result = await runner(testRunArgv(filter), {
347
- cwd: root,
348
- ...(Object.keys(envOverrides).length === 0 ? {} : { env: envOverrides }),
349
- });
350
- // The whole result, exit code included: `0 fail` beside `1 error` is a red run.
351
- return testRunOf(result);
352
- },
321
+ // `x test` itself, never a second test path: the files, batches and env the shell gets.
322
+ runTests: (filter: string | undefined) => shellTests(shell, filter),
353
323
 
354
324
  async tailLogs(lines: number, role: string | undefined) {
355
325
  const dir = lazy.services.stateDir;
356
326
  const path = logTailPath(dir, role);
357
327
  const file = Bun.file(path);
358
328
  if (!(await file.exists())) {
359
- // `@ultimat3/core`'s `logger` is a module const with no sink seam, so there is nothing to
360
- // intercept in-process — a log on disk is the only honest source, and the fix creates one.
329
+ // A log on disk is the only honest source: `x dev` tees every line of its own to
330
+ // `dev.log` (`dev-log.ts`), so starting it is the fix. No role writes a log of its own.
361
331
  throw new NotImplementedError({
362
332
  cause: `logs.tail without ${path} is not implemented in this build`,
363
333
  fix:
364
334
  role === undefined
365
- ? `x dev > ${path} 2>&1`
335
+ ? 'x dev'
366
336
  : `mkdir -p ${renderFixShellArg(join(dir, 'logs'), '<the logs dir of the path the cause names>')} && x dev --role ${role} > ${path} 2>&1`,
367
337
  });
368
338
  }
@@ -389,21 +359,11 @@ function capabilities(
389
359
 
390
360
  ...ui,
391
361
 
392
- async verify(fix: boolean): Promise<VerifyResult> {
362
+ async verify(fix: boolean, only?: readonly string[]): Promise<VerifyResult> {
393
363
  // The one safe autofix this repo actually has. Anything more would be the gate rewriting
394
364
  // code it was asked to judge.
395
- if (fix) await runner(['bunx', 'biome', 'check', '--write', '.'], { cwd: root });
396
- const result = await runVerify(VERIFY_STEPS, { root, runner, pace: measurePace() });
397
- return {
398
- ok: result.ok,
399
- steps: (result.steps ?? []).map((step): VerifyStep => {
400
- const detail = step.findings[0]?.cause;
401
- // exactOptionalPropertyTypes: omit `detail`, never hand over an explicit undefined.
402
- return detail === undefined
403
- ? { name: step.name, ok: step.ok }
404
- : { name: step.name, ok: step.ok, detail };
405
- }),
406
- };
365
+ if (fix) await shellRunner(shell)(['bunx', 'biome', 'check', '--write', '.'], { cwd: root });
366
+ return shellVerify(shell, only);
407
367
  },
408
368
  };
409
369
  }
@@ -421,6 +381,9 @@ export async function createDevMcpServer(input: DevHostInput): Promise<CliMcpSer
421
381
  // into a process that has not said it is development. Measured on 20.1.5: the first `ui.shot`
422
382
  // in a session photographed a 401 (`actorKind: anonymous`), and only the second call — whose
423
383
  // scratch boot re-imported the app after declaring — rendered. Idempotent; a set key stays.
384
+ // Asked before declaring: whether the key is this process's own is what `tests.run` and
385
+ // `verify.run` strip from their children, so they run as the shell runs them.
386
+ const declared = needsDevEnvironmentDeclaration(input.env);
424
387
  declareDevEnvironment(input.env);
425
388
  await Promise.all([loadApp(input.root), loadCodeFixes()]);
426
389
  // The plain `runtime.ts` routes, read once: `routes.list` answers the table `x routes` prints.
@@ -431,7 +394,9 @@ export async function createDevMcpServer(input: DevHostInput): Promise<CliMcpSer
431
394
  routes: () => routeRows(plain).map((row) => row.json),
432
395
  policies: () => policyFacts(),
433
396
  });
434
- const server = devMcpServer({ host: devHost(introspection, capabilities(input, lazy, ui)) });
397
+ const server = devMcpServer({
398
+ host: devHost(introspection, capabilities(input, lazy, ui, declared)),
399
+ });
435
400
  const caller = localCaller();
436
401
  return {
437
402
  server,
@@ -6,7 +6,10 @@ import type { TestRun } from '@ultimat3/mcp';
6
6
 
7
7
  const TAIL_LINES = 20;
8
8
  const FAIL_LINE = /^\(fail\)\s+(.*?)(?:\s+\[[\d.]+\s*m?s\])?$/;
9
- const ERROR_LINE = /^\s*error:\s*(.+)$/;
9
+ // Bun's own assertion line, or an uncaught `UltimateError` subclass, which bun prints as
10
+ // `DbError: X_CODE: cause` and never as `error: …`. Anchored on the code, so a source excerpt that
11
+ // only names an Error type is not read as a message.
12
+ const ERROR_LINE = /^\s*(?:error:\s*(.+)|[A-Z]\w*Error:\s*(X_[A-Z0-9_]+\b.*))$/;
10
13
 
11
14
  const lastCount = (output: string, label: string): number | undefined => {
12
15
  const last = [...output.matchAll(new RegExp(`^\\s*(\\d+)\\s+${label}\\b`, 'gm'))].at(-1);
@@ -35,7 +38,7 @@ export function parseBunTest(output: string, durationMs: number): TestRun {
35
38
  for (const line of output.split('\n')) {
36
39
  const error = ERROR_LINE.exec(line);
37
40
  if (error !== null) {
38
- message = error[1] ?? '';
41
+ message = error[1] ?? error[2] ?? '';
39
42
  continue;
40
43
  }
41
44
  const fail = FAIL_LINE.exec(line.trimEnd());
@@ -85,6 +85,18 @@ export const GATE_MESSAGES = {
85
85
  'cli.verify.failSkipped': '{failed} of {count} steps failed — {skipped} skipped: {names}',
86
86
  // The `errors` step's own coverage, in `output`: a scan without a parser reads most fix lines
87
87
  // and not all of them, and a step that reports findings alone claims a completeness it lacks.
88
+ // `contract-diff`'s baseline whenever it is not HEAD's file (`verify-contract-diff.ts`).
89
+ 'cli.verify.contract.mergeBase': 'baseline: {file} at the merge base with {ref}',
90
+ 'cli.verify.contract.baseTip':
91
+ 'baseline: {file} at {ref} — a shallow checkout reaches no merge base with it',
92
+ 'cli.verify.contract.baseUnfetched':
93
+ '{ref} is not fetched, so {file} at HEAD is the baseline — run `{fix}` for the merge base',
94
+ 'cli.verify.contract.noCheckout': 'not a git checkout: {file} on disk is the baseline',
95
+ 'cli.verify.contract.noCommit': 'no commit yet: no published {file} to break',
96
+ 'cli.verify.contract.uncommitted': '{file} is not committed at {rev}: nothing published to break',
97
+ 'cli.verify.contract.notManifest': '{file} at {rev} is not a manifest: no baseline',
98
+ // A step standing down while the app's load is red (`load-findings.ts`).
99
+ 'cli.verify.loadBlocked': 'skipped: load failed (see {owner})',
88
100
  'cli.verify.fixCoverage': 'checked {checked} fix line(s), could not read {unreadable}',
89
101
  // The `drift` step on an app whose only store is a `defineDriver` one: migrations describe
90
102
  // Postgres, and that store owns its schema — said in `output`, so the step is not a silent green.
package/src/messages.ts CHANGED
@@ -47,6 +47,22 @@ const CATALOG = {
47
47
  'cli.dev.mail.refused': 'mail=refused({detail})',
48
48
  'cli.dev.hmr': 'reloaded {file} in {ms}ms',
49
49
  'cli.dev.restart': 'restarting: {reason} — a module that defines a primitive holds the old code',
50
+ // The two other restarts (`dev-rebuild-remount.ts`), each saying its own cause: the route table is
51
+ // mounted once at boot, and a module that failed to import is served only by a new process.
52
+ 'cli.dev.restartSurface':
53
+ 'restarting: {file} changed what x dev mounts ({changes}) — the route table is built once, at boot',
54
+ 'cli.dev.restartFindings':
55
+ 'restarting: {file} changed which modules load ({changes}) — the new process prints the verdict',
56
+ 'cli.dev.change.added': '{what} added',
57
+ 'cli.dev.change.removed': '{what} removed',
58
+ 'cli.dev.change.failing': '{file} fails to load',
59
+ 'cli.dev.change.loads': '{file} loads again',
60
+ 'cli.dev.mounted.route': 'route {name}',
61
+ 'cli.dev.mounted.action': 'action {name}',
62
+ 'cli.dev.mounted.query': 'query {name}',
63
+ 'cli.dev.mounted.channel': 'channel {name}',
64
+ 'cli.dev.mounted.admin': 'admin {name}',
65
+ 'cli.dev.mounted.mount': 'mount {name}',
50
66
  // The restart's wait, said while it waits: a save never cancels a running job (issue #677).
51
67
  'cli.dev.restartWaiting':
52
68
  'restart waits for {count} running job(s) to finish — no new job is claimed; Ctrl-C stops now (a job still running is cut off at the drain deadline and requeued)',
@@ -0,0 +1,88 @@
1
+ // A second permission set into a slice's existing `policy.ts`: the generated module's body
2
+ // appended, its imports folded into the ones already there. A pure merge edit over two sources —
3
+ // `x g policy <name> --feature <slice>` used to overwrite the author's rules or refuse outright.
4
+
5
+ /** `import { a, b } from 'm';` on one line: the shape every policy template emits. */
6
+ const NAMED_IMPORT = /^import \{ (?<names>[^}]+) \} from '(?<from>[^']+)';$/;
7
+
8
+ /** Every top-level binding a module exports by declaration. */
9
+ const exportedNames = (source: string): ReadonlySet<string> =>
10
+ new Set(
11
+ [...source.matchAll(/^export (?:const|let|function|class|interface|type|enum) (\w+)/gm)].map(
12
+ (match) => match[1] ?? '',
13
+ ),
14
+ );
15
+
16
+ /** Biome's order for named specifiers, case-folded and by code unit: never `Intl`, whose order
17
+ * moves with the machine's ICU. */
18
+ const sortNames = (names: readonly string[]): readonly string[] =>
19
+ [...names].sort((a, b) => {
20
+ const [x, y] = [a.toLowerCase(), b.toLowerCase()];
21
+ return x < y ? -1 : x > y ? 1 : 0;
22
+ });
23
+
24
+ /** A named import over one line or several, as Biome wraps one past the line width. */
25
+ const importOf = (from: string): RegExp =>
26
+ new RegExp(
27
+ `^import \\{(?<names>[^}]*)\\} from '${from.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')}';$`,
28
+ 'm',
29
+ );
30
+
31
+ const namesIn = (list: string): readonly string[] =>
32
+ list
33
+ .split(',')
34
+ .map((name) => name.trim())
35
+ .filter((name) => name !== '');
36
+
37
+ /** Where a new import line goes: before the first import whose specifier sorts after it. */
38
+ function insertImport(source: string, line: string, from: string): string {
39
+ const statements = [...source.matchAll(/^import [^;]*? from '(?<from>[^']+)';$/gm)];
40
+ const next = statements.find((each) => {
41
+ const specifier = each.groups?.['from'] ?? '';
42
+ return !specifier.startsWith('.') && specifier > from;
43
+ });
44
+ const last = statements.at(-1);
45
+ const at = next?.index ?? (last === undefined ? 0 : (last.index ?? 0) + last[0].length + 1);
46
+ return `${source.slice(0, at)}${line}\n${source.slice(at)}`;
47
+ }
48
+
49
+ /** `existing` with each named import of `wanted` present, merged into one from the same module. */
50
+ function foldImports(existing: string, wanted: readonly string[]): string {
51
+ let source = existing;
52
+ for (const line of wanted) {
53
+ const groups = NAMED_IMPORT.exec(line)?.groups;
54
+ if (groups === undefined) continue;
55
+ const from = groups['from'] ?? '';
56
+ const names = namesIn(groups['names'] ?? '');
57
+ const held = importOf(from).exec(source);
58
+ if (held === null) {
59
+ source = insertImport(source, line, from);
60
+ continue;
61
+ }
62
+ const merged = sortNames([...new Set([...namesIn(held.groups?.['names'] ?? ''), ...names])]);
63
+ source = source.replace(importOf(from), `import { ${merged.join(', ')} } from '${from}';`);
64
+ }
65
+ return source;
66
+ }
67
+
68
+ /**
69
+ * `existing` with `generated`'s permission set appended, or `undefined` when the two cannot be
70
+ * merged: `generated` exports a name `existing` already does (the same set, generated again), or
71
+ * an import is in a shape this does not read. Nothing the author wrote is moved or rewritten
72
+ * except an import line gaining a specifier.
73
+ */
74
+ export function appendPolicy(existing: string, generated: string): string | undefined {
75
+ const held = exportedNames(existing);
76
+ const adding = exportedNames(generated);
77
+ if (adding.size === 0 || [...adding].some((name) => held.has(name))) return undefined;
78
+ const lines = generated.split('\n');
79
+ const lastImport = lines.findLastIndex((line) => line.startsWith('import '));
80
+ if (lastImport === -1) return undefined;
81
+ const imports = lines.slice(0, lastImport + 1).filter((line) => line.startsWith('import '));
82
+ if (imports.some((line) => !NAMED_IMPORT.test(line))) return undefined;
83
+ const body = lines
84
+ .slice(lastImport + 1)
85
+ .join('\n')
86
+ .trim();
87
+ return `${foldImports(existing, imports).trimEnd()}\n\n${body}\n`;
88
+ }
@@ -91,6 +91,14 @@ const chain = (indent: string, head: string, calls: readonly string[]): string =
91
91
  return `${indent}${head}\n${calls.map((call) => `${indent} ${call}`).join('\n')};`;
92
92
  };
93
93
 
94
+ /** The insert shape's alias, broken inside \`Insertable<…>\` the way Biome breaks one that is long. */
95
+ const newRowType = (row: string, camel: string): string => {
96
+ const flat = `export type New${row} = Insertable<typeof ${camel}.$columns>;`;
97
+ return flat.length <= LINE_WIDTH
98
+ ? flat
99
+ : `export type New${row} = Insertable<\n typeof ${camel}.$columns\n>;`;
100
+ };
101
+
94
102
  const repoSource = (name: NameSet, dbModule: string, stems: EntityStems): string => {
95
103
  const row = name.pascal;
96
104
  const table = `db.${name.plural}`;
@@ -110,7 +118,7 @@ const repoSource = (name: NameSet, dbModule: string, stems: EntityStems): string
110
118
  const insertSignature = wrapList(
111
119
  '',
112
120
  'export async function insert(',
113
- [`row: Omit<${row}, 'id' | 'createdAt'>`],
121
+ [`row: New${row}`],
114
122
  `): Promise<${row}> {`,
115
123
  );
116
124
  const listChain = chain(' ', `return ${table}`, [
@@ -130,8 +138,15 @@ const repoSource = (name: NameSet, dbModule: string, stems: EntityStems): string
130
138
  // Raw SQL has two homes and neither is this file: a \`query\`'s source and a migration. Reach for
131
139
  // it here only for a statement the handle cannot express — a join, a window, a CTE.
132
140
 
133
- import { db } from '${dbModule}';
134
- import type { ${row} } from './${stems.entity}';
141
+ ${sortedImports(["import type { Insertable } from '@ultimat3/entity';", `import { db } from '${dbModule}';`])}
142
+ ${wrapImport([row, name.camel], `./${stems.entity}`).replace(/^import \{/, 'import type {')}
143
+
144
+ /**
145
+ * What an insert supplies: the declaration's own write shape. A column with a default or a
146
+ * nullable one is optional here, so a counter or an optional relation added to the entity never
147
+ * breaks a caller that omits it; a required column is still a compile error at every insert.
148
+ */
149
+ ${newRowType(row, name.camel)}
135
150
 
136
151
  ${byIdSignature}
137
152
  ${byIdBody}
@@ -222,13 +222,17 @@ export function policyFiles(
222
222
  ): readonly GeneratedFile[] {
223
223
  const feature = names(rawName.length > 0 ? rawName : target.feature);
224
224
  const dir = `${target.surfaceDir}/${target.feature}`;
225
+ // A set named apart from its slice is a SECOND one there (`policy-append.ts` appends its rules
226
+ // to `policy.ts`), and its test lands beside the slice's own rather than over it.
227
+ const test =
228
+ feature.kebab === target.feature ? 'policy.test.ts' : `policy-${feature.kebab}.test.ts`;
225
229
  return [
226
230
  {
227
231
  path: `${dir}/policy.ts`,
228
232
  contents: shape.singleTenant ? singleTenantPolicySource(feature) : policySource(feature),
229
233
  },
230
234
  {
231
- path: `${dir}/policy.test.ts`,
235
+ path: `${dir}/${test}`,
232
236
  contents: shape.singleTenant ? singleTenantPolicyTest(feature) : policyTest(feature),
233
237
  },
234
238
  ];
@@ -39,8 +39,10 @@ export const ${name.camel}Sorts = ['createdAt', 'title'] as const;
39
39
  // tenant. One source of tenancy — a parameter would be a second one a caller could set.
40
40
  export const ${name.camel} = query({
41
41
  input: t.object({
42
- limit: t.number.default(50),
43
- // A closed set, so a sort is a column this read has an order for, never a caller's string.
42
+ limit: t.number.int().min(1).max(500).default(50),
43
+ // Bounded above, so no request reads the whole table — at the scaffold dashboard's ROW_LIMIT,
44
+ // its one caller past the default; a closed set, so a sort is a column this read has an order
45
+ // for, never a caller's string.
44
46
  sort: t.enum(${name.camel}Sorts).default('createdAt'),
45
47
  dir: t.enum(['asc', 'desc']).default('desc'),
46
48
  }),
@@ -14,8 +14,11 @@ import type { ${feature.pascal} } from './entity';
14
14
  import { ${feature.pascal}NotFoundError } from './errors';
15
15
  import * as repo from './repo';
16
16
 
17
- /** Derived from the row, never restated: a new column reaches this input without an edit here. */
18
- export type Create${feature.pascal}Input = Omit<${feature.pascal}, 'id' | 'createdAt'>;
17
+ /**
18
+ * The repo's insert shape, never restated: a new column reaches this input without an edit here,
19
+ * and one with a default or a nullable one stays optional (\`Insertable\`, not \`Omit<Row, …>\`).
20
+ */
21
+ export type Create${feature.pascal}Input = repo.New${feature.pascal};
19
22
 
20
23
  /** The row, aliased once, so every signature below reads at one width whatever the feature is
21
24
  * called — a generated file the app's own formatter rewrites is a red \`lint\` over code nobody
@@ -269,7 +269,9 @@ defineMeasurementActor(async () => {
269
269
  // Go-templated manifests are a parse ERROR, not a format miss. `css.quoteStyle` is `single` and SCSS
270
270
  // turns `noUnknownUnit` off: 2.6 begins PARSING SCSS too, its default is double, and a token call
271
271
  // reads as a dimension (`tokens.text('lg')` → unit `lg`), so both misfire on the framework's own
272
- // idiom.
272
+ // idiom. `noDefaultExport`: a default-exported action registered under the name "default" — the
273
+ // export is the name the API, the manifest and the MCP tool carry. `types/scss.d.ts`'s ambient class
274
+ // map is the one default export, and the override names that file alone.
273
275
  const biome = (): string => `{
274
276
  "$schema": "https://biomejs.dev/schemas/${BIOME_VERSION}/schema.json",
275
277
  "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
@@ -292,7 +294,7 @@ const biome = (): string => `{
292
294
  "preset": "recommended",
293
295
  "suspicious": { "noExplicitAny": "error" },
294
296
  "correctness": { "noUnusedVariables": "error", "noUnusedImports": "error" },
295
- "style": { "useNodejsImportProtocol": "error" }
297
+ "style": { "useNodejsImportProtocol": "error", "noDefaultExport": "error" }
296
298
  }
297
299
  },
298
300
  "javascript": {
@@ -301,6 +303,10 @@ const biome = (): string => `{
301
303
  "markdown": { "formatter": { "enabled": false } },
302
304
  "yaml": { "formatter": { "enabled": false } },
303
305
  "overrides": [
306
+ {
307
+ "includes": ["**/scss.d.ts"],
308
+ "linter": { "rules": { "style": { "noDefaultExport": "off" } } }
309
+ },
304
310
  {
305
311
  "includes": ["**/*.scss"],
306
312
  "linter": { "rules": { "correctness": { "noUnknownUnit": "off" } } }
package/src/ts-scan.ts CHANGED
@@ -253,6 +253,8 @@ export interface CodeFixSite extends CodeSite {
253
253
  * branches — because a fix the scan has to guess at is one it must not report.
254
254
  */
255
255
  readonly fix?: string;
256
+ /** Read off a `*FIXES` table key: a fix lookup by code, which constructs nothing. */
257
+ readonly fromTable?: true;
256
258
  }
257
259
 
258
260
  /** `code:` / `code =`, or `fix:`. `fix =` is deliberately not a declaration — `scanFixes` agrees. */
@@ -339,10 +341,93 @@ export function scanCodeFixSites(source: string, at: string): readonly CodeFixSi
339
341
  codes.set(scope, { at, line: literal?.line ?? lineAt(key.from), code });
340
342
  }
341
343
  }
342
- return [...codes].map(([scope, site]) => {
344
+ const paired = [...codes].map(([scope, site]) => {
343
345
  const fix = fixes.get(scope);
344
346
  return fix === undefined ? site : { ...site, fix };
345
347
  });
348
+ return [...paired, ...fixTableSites(masked, source, at, lineAt)];
349
+ }
350
+
351
+ /**
352
+ * A module-scope `const <NAME>FIXES = {…}` or `Object.freeze(…)({…})` — the table a factory reads
353
+ * as `fix: SQLSTATE_FIXES[code]`. No `code:` literal anywhere, so the adjacency rule above never
354
+ * saw one of its codes, and `x errors explain X_DB_SCHEMA_STALE` answered "nothing raises it".
355
+ * The NAME is the rule: a titles table is keyed by the same codes and holds no fix.
356
+ */
357
+ const FIX_TABLE =
358
+ /(?<![.\w$])const\s+[A-Z][A-Z0-9_]*FIXES\s*(?::[^=;]*)?=\s*(?:Object\.freeze\s*(?:<[^(]*>)?\(\s*)?\{/g;
359
+
360
+ /** A table key: an `X_*` code right after the `{` or a `,` of its own object. */
361
+ const TABLE_KEY = /(?<=[{,]\s*)(X_[A-Z0-9_]+)\s*:\s*/g;
362
+
363
+ /** A value that is literals joined by `+` and nothing else — one fix line, written over lines. */
364
+ const ONLY_JOINS = /^[\s+]*$/;
365
+
366
+ function fixTableSites(
367
+ masked: string,
368
+ source: string,
369
+ at: string,
370
+ lineAt: (index: number) => number,
371
+ ): readonly CodeFixSite[] {
372
+ const sites: CodeFixSite[] = [];
373
+ for (const table of masked.matchAll(FIX_TABLE)) {
374
+ const open = table.index + table[0].length - 1;
375
+ let depth = 0;
376
+ let close = masked.length;
377
+ for (let i = open; i < masked.length; i += 1) {
378
+ const ch = masked[i] as string;
379
+ if (QUOTES.has(ch)) i = Math.max(i, endOfLiteral(masked, i) - 1);
380
+ else if (OPENERS.has(ch)) depth += 1;
381
+ else if (CLOSERS.has(ch) && --depth === 0) {
382
+ close = i;
383
+ break;
384
+ }
385
+ }
386
+ const body = masked.slice(open, close);
387
+ for (const key of body.matchAll(TABLE_KEY)) {
388
+ if (depthAt(body, key.index) !== 1) continue;
389
+ const from = open + key.index + key[0].length;
390
+ const site: CodeFixSite = {
391
+ at,
392
+ line: lineAt(open + key.index),
393
+ code: key[1] as string,
394
+ fromTable: true,
395
+ };
396
+ const fix = joinedLiterals(masked, source, from);
397
+ sites.push(fix === undefined ? site : { ...site, fix });
398
+ }
399
+ }
400
+ return sites;
401
+ }
402
+
403
+ /** Bracket depth at `index` of a masked span that opens with its own `{`. */
404
+ function depthAt(body: string, index: number): number {
405
+ let depth = 0;
406
+ for (let i = 0; i < index; i += 1) {
407
+ const ch = body[i] as string;
408
+ if (QUOTES.has(ch)) i = Math.max(i, endOfLiteral(body, i) - 1);
409
+ else if (OPENERS.has(ch)) depth += 1;
410
+ else if (CLOSERS.has(ch)) depth -= 1;
411
+ }
412
+ return depth;
413
+ }
414
+
415
+ /**
416
+ * The fix the value at `from` evaluates to when it is one literal or literals joined by `+`;
417
+ * `undefined` for anything else between them (a call, a ternary, an identifier) — never half a fix.
418
+ */
419
+ function joinedLiterals(masked: string, source: string, from: number): string | undefined {
420
+ const parts: string[] = [];
421
+ for (let i = from; i < masked.length; i += 1) {
422
+ const ch = masked[i] as string;
423
+ if (QUOTES.has(ch)) {
424
+ const end = endOfLiteral(masked, i);
425
+ parts.push(source.slice(i + 1, end - 1));
426
+ i = end - 1;
427
+ } else if (ch === ',' || ch === '}') break;
428
+ else if (!ONLY_JOINS.test(ch)) return undefined;
429
+ }
430
+ return parts.length === 0 ? undefined : parts.join('');
346
431
  }
347
432
 
348
433
  const BORROWED_LIST = /BORROWED_ERROR_CODES[^=]*=[^[]*\[([^\]]*)\]/g;