@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,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
+ }
@@ -31,6 +31,7 @@ import {
31
31
  import type { AssetPath } from '@ultimat3/render';
32
32
  import { assetPathProblem } from '@ultimat3/render';
33
33
  import { loadAppConfig } from './app-config-load';
34
+ import { assetRouteMeta } from './asset-route-meta';
34
35
  import { hasSourceIcon, iconPlan, iconRenderer } from './icon-assets';
35
36
  import type { AppLocales } from './pwa-manifest-locales';
36
37
  import { appLocales, localeMembers, spellIn } from './pwa-manifest-locales';
@@ -253,13 +254,12 @@ export const pwaManifestRoute = (artifacts: PwaArtifacts): Route => ({
253
254
  path: WEB_MANIFEST_PATH,
254
255
  // `'path'`: `/en/manifest.webmanifest` reaches this route with its prefix split off and `en` as the
255
256
  // locale, and the bare path is the default locale's — never negotiated, so a CDN may cache both.
256
- meta: {
257
+ meta: assetRouteMeta({
257
258
  name: 'assets.manifest',
258
259
  auth: 'public',
259
260
  cache: MANIFEST_CACHE,
260
- tags: ['assets'],
261
261
  localeSource: 'path',
262
- },
262
+ }),
263
263
  handler: async (_request: UltimateRequest, ctx: RequestContext): Promise<Response> =>
264
264
  applyCacheHeaders(
265
265
  // `textResponse` for the length it declares: `compress` reads nothing undeclared.
@@ -19,6 +19,7 @@ import {
19
19
  variantKey,
20
20
  variantRevision,
21
21
  } from '@ultimat3/storage';
22
+ import { assetRouteMeta } from './asset-route-meta';
22
23
  import { faviconRoute } from './favicon';
23
24
  // The icon matrix's source, its base path and its renderer live in their own module so that
24
25
  // `pwa-artifacts.ts` — which this file imports for the manifest route — can reach them without
@@ -260,7 +261,7 @@ export function assetRoutes(options: AssetRoutesOptions): readonly Route[] {
260
261
  const routes: Route[] = plan.entries.map((entry) => ({
261
262
  method: 'GET',
262
263
  path: entry.outputPath,
263
- meta: { name: `assets.icon.${entry.spec.filename}`, auth: 'public', tags: ['assets'] },
264
+ meta: assetRouteMeta({ name: `assets.icon.${entry.spec.filename}`, auth: 'public' }),
264
265
  // Revalidated, never `immutable` (22.3.2): the file name is the icon's SIZE, so a new
265
266
  // `icon.png` shipped under the same URLs and every client that had seen the old one kept it for
266
267
  // a year. The manifest and the apple-touch links name these paths, so a hashed URL would move
@@ -277,6 +278,8 @@ export function assetRoutes(options: AssetRoutesOptions): readonly Route[] {
277
278
  routes.push({
278
279
  method: 'GET',
279
280
  path: `${MEDIA_BASE_PATH}/*key`,
281
+ // Tagged `assets` (the retained-build lookup reads the tag) but NOT on the `assets` bucket: an
282
+ // authenticated storage read per request is not a content-hashed chunk, so it stays `default`.
280
283
  meta: {
281
284
  name: 'assets.media',
282
285
  auth: 'required',
@@ -12,6 +12,7 @@ import {
12
12
  parseByteRange,
13
13
  RANGE_UNSATISFIABLE,
14
14
  } from '@ultimat3/http';
15
+ import { assetRouteMeta } from './asset-route-meta';
15
16
  import type { SiteAsset, SiteAssetTable } from './site-assets';
16
17
  import { parseHashedAssetUrl, SITE_ASSET_BASE_PATH } from './site-assets';
17
18
 
@@ -65,7 +66,7 @@ export function siteAssetRoutes(table: SiteAssetTable): readonly Route[] {
65
66
  {
66
67
  method: 'GET',
67
68
  path: `${SITE_ASSET_BASE_PATH}/*file`,
68
- meta: { name: 'assets.site', auth: 'public', tags: ['assets'] },
69
+ meta: assetRouteMeta({ name: 'assets.site', auth: 'public' }),
69
70
  handler: (request: UltimateRequest): Response => {
70
71
  const named = parseHashedAssetUrl(request.pathname);
71
72
  if (named === undefined) {
@@ -5,6 +5,7 @@
5
5
 
6
6
  import type { Route, UltimateRequest } from '@ultimat3/http';
7
7
  import { applyCacheHeaders, jsonResponse, NO_STORE, textResponse } from '@ultimat3/http';
8
+ import { assetRouteMeta } from './asset-route-meta';
8
9
  import type { StyleBundle } from './style-bundle';
9
10
  import { STYLE_BASE_PATH } from './style-bundle';
10
11
 
@@ -28,7 +29,7 @@ export function styleRoutes(source: StyleSource): readonly Route[] {
28
29
  {
29
30
  method: 'GET',
30
31
  path: `${STYLE_BASE_PATH}/*file`,
31
- meta: { name: 'assets.style', auth: 'public', tags: ['assets'] },
32
+ meta: assetRouteMeta({ name: 'assets.style', auth: 'public' }),
32
33
  handler: (request: UltimateRequest): Response => {
33
34
  const chunk = source().chunkAt(request.pathname);
34
35
  if (chunk === undefined) {
@@ -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}
@@ -277,9 +277,12 @@ export function rawRepoSql(files: readonly RepoFile[]): readonly Finding[] {
277
277
  export const guard: Guard = {
278
278
  summary: 'a repo.ts reads through the typed handle, never a sql literal the handle can express',
279
279
  async check(_root, sources) {
280
- // The run's ONE read of these files: every guard asking for this glob shares the walk.
281
- const repos = await sources.files('{apps,packages}/**/repo.ts');
282
- return rawRepoSql(repos.map((file) => ({ path: file.path, source: file.text })));
280
+ // The run's ONE read of these files: every guard asking for this glob shares the walk. A
281
+ // \`repo-<part>.ts\` is the same repo split at the file ceiling, so it is read too — but not a
282
+ // \`repo-<part>.test.ts\`, which the same glob reaches and whose fixture SQL is no repo's.
283
+ const repos = await sources.files('{apps,packages}/**/repo{,-*}.ts');
284
+ const read = repos.filter((file) => !file.path.endsWith('.test.ts'));
285
+ return rawRepoSql(read.map((file) => ({ path: file.path, source: file.text })));
283
286
  },
284
287
  };
285
288
  `;
@@ -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;
@@ -5,15 +5,14 @@
5
5
  import { existsSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { APP_CONFIG_FILE, ERROR_DOCS_URL } from '@ultimat3/core';
8
- import type { Manifest } from '@ultimat3/manifest';
9
- import { AGENTS_MD_FILENAME, MANIFEST_FILENAME, verifyContract } from '@ultimat3/manifest';
8
+ import { AGENTS_MD_FILENAME } from '@ultimat3/manifest';
10
9
  import type { MetaIssue } from '@ultimat3/seo';
11
10
  import { llmsDescriptionIssues, validateMeta } from '@ultimat3/seo';
12
11
  import { checkAgentsMd } from './app-agents-md';
13
12
  import { readAppSources } from './app-boundaries';
14
13
  import { envExampleFindings } from './app-env';
15
14
  import { loadApp } from './app-load';
16
- import { appManifest, readAppManifest } from './app-manifest';
15
+ import { appManifest } from './app-manifest';
17
16
  import { policyFindings } from './app-permissions';
18
17
  import { asyncPageFindings } from './async-pages';
19
18
  import { appBoundaryFindings } from './boundary-findings';
@@ -32,7 +31,7 @@ import { readJobBudgetFindings } from './job-budget';
32
31
  import { unregisteredJobFindings } from './job-registration';
33
32
  import { LINT_ARGV, lintOutcome } from './lint-findings';
34
33
  import { liveRouteFindings } from './live-routes';
35
- import { withLoadFindings, withoutLoadFindings } from './load-findings';
34
+ import { blockedByLoad, withLoadFindings } from './load-findings';
36
35
  import {
37
36
  hasCommittedContract,
38
37
  manifestMissingFindings,
@@ -41,7 +40,6 @@ import {
41
40
  import { mcpLockFindings } from './mcp-lock-findings';
42
41
  import { msg } from './messages';
43
42
  import type { Finding } from './output';
44
- import { findingFrom } from './output';
45
43
  import { retainUnsweptFindings } from './retain-sweep';
46
44
  import { checkMigrationDrift } from './schema-drift';
47
45
  import { checkSchemaDump } from './schema-dump-drift';
@@ -52,6 +50,7 @@ import { loadSiteSettings } from './site-config';
52
50
  import { readStaticReport } from './static-report';
53
51
  import { unknownToolGateFindings } from './tool-gate-names';
54
52
  import { measureIfStale } from './verify-budgets-build';
53
+ import { contractDiffStep } from './verify-contract-diff';
55
54
  import { nestedAppRootFindings } from './verify-drift-owner';
56
55
  import { exerciseStep } from './verify-exercise';
57
56
  import { floorProblemFindings, readVerifyFloor } from './verify-floor';
@@ -192,9 +191,11 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
192
191
  },
193
192
  },
194
193
  ...TEST_STEPS.slice(0, AFTER_JOB),
195
- exerciseStep,
194
+ // Every step that loads the app stands down while the load is red: the cause is `manifest`'s,
195
+ // and what a half-filled registry looks like is not a finding (`load-findings.ts`).
196
+ blockedByLoad(exerciseStep),
196
197
  ...TEST_STEPS.slice(AFTER_JOB),
197
- {
198
+ blockedByLoad({
198
199
  name: 'drift',
199
200
  summary:
200
201
  'entity declarations vs migrations, every destructive statement declared, every statement no declaration carries, and the committed schema dump',
@@ -235,26 +236,9 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
235
236
  client: () => checkClientDrift(ctx.root),
236
237
  });
237
238
  },
238
- },
239
- {
240
- name: 'contract-diff',
241
- summary: 'the published contract vs the committed manifest',
242
- // A BREAKING change against the committed manifest, and nothing else. Whether the committed
243
- // files are stale — `openapi.json` included — is the `manifest` step's, through the one check
244
- // `x manifest --check` runs (`manifest-staleness.ts`): reported here as well it was two
245
- // steps and one command answering one question, and the step named `manifest` saying green.
246
- applies: async (ctx) => existsSync(join(ctx.root, MANIFEST_FILENAME)),
247
- async run(ctx) {
248
- const committed = await readAppManifest(ctx.root);
249
- const { manifest, findings } = await appManifest(ctx.root);
250
- // A module that will not import is `manifest`'s to report (`load-findings.ts`).
251
- return withoutLoadFindings(ctx.root, [
252
- ...findings,
253
- ...(committed === undefined ? [] : contractFindings(committed, manifest)),
254
- ]);
255
- },
256
- },
257
- {
239
+ }),
240
+ blockedByLoad(contractDiffStep),
241
+ blockedByLoad({
258
242
  name: 'budgets',
259
243
  summary:
260
244
  'per-route JS bytes, the global style layer every document carries, and the routes that boot nothing to receive their live rows',
@@ -288,12 +272,10 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
288
272
  // reported under `X_ISLAND_PROPS_INVALID` — the build's own sentence, naming the prop and
289
273
  // its bytes — and not as an `X_BUDGET_UNMEASURED` whose fix is to go and read this file.
290
274
  const report = await readStaticReport(ctx.root);
291
- // The load's own findings are `manifest`'s, reported there once; this step's output says so.
292
- // A module that would not import registers no route, so every route it declared still reads
293
- // as `X_BUDGET_UNMEASURED` here — the symptom stays this step's, and the gate stays red.
294
- const { manifest, findings } = await appManifest(ctx.root);
295
- const outcome = await withoutLoadFindings(ctx.root, [
296
- ...findings,
275
+ // Reached only over a clean load (`blockedByLoad`): a route a broken module never registered
276
+ // is the load's finding on `manifest`, never one `X_BUDGET_UNMEASURED` per route here.
277
+ const { manifest } = await appManifest(ctx.root);
278
+ const outcome = fromFindings([
297
279
  ...checkDocumentStyles(documentSurfaces()),
298
280
  // The third rider, and the same question this step already asks one level down: what
299
281
  // JavaScript does this route's document boot? A live read with no island is a route
@@ -314,8 +296,8 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
314
296
  .join('\n');
315
297
  return output === '' ? outcome : { ...outcome, output };
316
298
  },
317
- },
318
- {
299
+ }),
300
+ blockedByLoad({
319
301
  name: 'seo',
320
302
  summary: 'every indexable site/ route has a title and a description a search result can render',
321
303
  // The SEO checkers shipped in `@ultimat3/seo` with no caller anywhere — `validateMeta` and its
@@ -349,8 +331,8 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
349
331
  ...(warnings.length === 0 ? {} : { warnings }),
350
332
  };
351
333
  },
352
- },
353
- {
334
+ }),
335
+ blockedByLoad({
354
336
  name: 'i18n',
355
337
  summary: 'every string this app renders resolves — in the catalogs AND in the registry',
356
338
  // Its own step rather than a rider on `boundaries`, by that step's own test: a rider must ask
@@ -370,16 +352,16 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
370
352
  // is the vacuous green this check exists to refuse.
371
353
  applies: async (ctx) => existsSync(join(ctx.root, APP_CONFIG_FILE)),
372
354
  run: async (ctx) => fromFindings(await catalogFindings(ctx.root)),
373
- },
374
- {
355
+ }),
356
+ blockedByLoad({
375
357
  name: 'policy',
376
358
  summary: 'every permission this app grants or requires is one it declares',
377
359
  // A repo with no `app.config.ts` is the framework monorepo, which declares no roles and
378
360
  // registers no routes — SKIPPED there, never passed, for the reason `i18n` gives: a step that
379
361
  // answers `ok` about nothing is the vacuous green these checks exist to refuse.
380
362
  applies: async (ctx) => existsSync(join(ctx.root, APP_CONFIG_FILE)),
381
- run: async (ctx) => withoutLoadFindings(ctx.root, await policyFindings(ctx.root)),
382
- },
363
+ run: async (ctx) => fromFindings(await policyFindings(ctx.root)),
364
+ }),
383
365
  {
384
366
  name: 'manifest',
385
367
  summary: 'the files an agent reads: generated facts, hand-written conventions, the env example',
@@ -466,16 +448,6 @@ async function driftFindings(root: string): Promise<readonly Finding[]> {
466
448
  return [...findings, ...(await manifestStaleness(root, manifest))];
467
449
  }
468
450
 
469
- /** A breaking change is allowed — with a major bump. `verifyContract` is the one that decides. */
470
- function contractFindings(before: Manifest, after: Manifest): readonly Finding[] {
471
- try {
472
- verifyContract({ before, after });
473
- return [];
474
- } catch (error) {
475
- return [{ ...findingFrom(error), at: MANIFEST_FILENAME }];
476
- }
477
- }
478
-
479
451
  /**
480
452
  * One `MetaIssue` as the gate reports it. `at` is the route FILE and never the URL: every seo error
481
453
  * already names the file in its cause, and `at` is what an agent opens.