@ultimat3/cli 1.2.0 → 3.0.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 (141) hide show
  1. package/CLAUDE.md +761 -0
  2. package/README.md +42 -9
  3. package/package.json +25 -23
  4. package/src/api-routes.ts +16 -0
  5. package/src/app-auth.ts +32 -0
  6. package/src/app-entities.ts +18 -0
  7. package/src/app-env.ts +103 -0
  8. package/src/app-load.ts +20 -3
  9. package/src/bin.ts +4 -3
  10. package/src/budgets.ts +134 -9
  11. package/src/cmd-build.ts +69 -21
  12. package/src/cmd-db-branch.ts +219 -0
  13. package/src/cmd-db.ts +458 -153
  14. package/src/cmd-deploy.ts +59 -6
  15. package/src/cmd-dev.ts +92 -18
  16. package/src/cmd-docs.ts +167 -0
  17. package/src/cmd-doctor.ts +74 -10
  18. package/src/cmd-env.ts +95 -0
  19. package/src/cmd-errors.ts +33 -13
  20. package/src/cmd-fix.ts +5 -1
  21. package/src/cmd-generate.ts +146 -111
  22. package/src/cmd-help.ts +16 -5
  23. package/src/cmd-i18n.ts +2 -0
  24. package/src/cmd-jobs.ts +47 -33
  25. package/src/cmd-mcp.ts +11 -2
  26. package/src/cmd-new.ts +14 -8
  27. package/src/cmd-planned.ts +55 -10
  28. package/src/cmd-policy.ts +1 -0
  29. package/src/cmd-registries.ts +3 -0
  30. package/src/cmd-secrets.ts +368 -0
  31. package/src/cmd-tasks.ts +1 -0
  32. package/src/cmd-test.ts +29 -24
  33. package/src/cmd-verify.ts +197 -25
  34. package/src/db-backfill.ts +401 -0
  35. package/src/db-branch.ts +269 -0
  36. package/src/db-destructive.ts +29 -0
  37. package/src/db-finding.ts +28 -0
  38. package/src/db-generate.ts +144 -0
  39. package/src/db-seed.ts +294 -0
  40. package/src/db-snapshot.ts +24 -0
  41. package/src/dev-assets.ts +108 -23
  42. package/src/dev-cache.ts +122 -0
  43. package/src/dev-dashboard.ts +19 -4
  44. package/src/dev-hooks.ts +27 -2
  45. package/src/dev-n-plus-one.ts +191 -0
  46. package/src/dev-queue.ts +105 -19
  47. package/src/dev-render.ts +158 -26
  48. package/src/dev-roles-fixture.ts +67 -0
  49. package/src/dev-roles.ts +167 -78
  50. package/src/dev-runtime.ts +117 -40
  51. package/src/dev-services.ts +15 -0
  52. package/src/dev-storage.ts +247 -0
  53. package/src/dev-sync.ts +107 -0
  54. package/src/dev-traces.ts +37 -7
  55. package/src/dispatch.ts +4 -2
  56. package/src/document-styles.ts +54 -0
  57. package/src/drift.ts +78 -10
  58. package/src/error-catalog.ts +8 -18
  59. package/src/error-codes.ts +192 -0
  60. package/src/error-contract.ts +29 -7
  61. package/src/error-fixes.ts +114 -0
  62. package/src/errors.ts +201 -138
  63. package/src/exec.ts +42 -8
  64. package/src/fix-command.ts +268 -0
  65. package/src/flag-number.ts +67 -0
  66. package/src/framework-scope.ts +49 -0
  67. package/src/generate-kinds.ts +97 -0
  68. package/src/guards.ts +186 -0
  69. package/src/index.ts +92 -15
  70. package/src/island-bundle.ts +166 -0
  71. package/src/island-routes.ts +50 -0
  72. package/src/jobs-driver.ts +33 -0
  73. package/src/jobs-json.ts +24 -0
  74. package/src/jobs-report.ts +17 -4
  75. package/src/mcp-db-target.ts +52 -27
  76. package/src/mcp-errors.ts +128 -19
  77. package/src/mcp-host.ts +44 -25
  78. package/src/messages.ts +93 -2
  79. package/src/metrics-endpoint.ts +64 -16
  80. package/src/migrations.ts +37 -4
  81. package/src/otlp-export.ts +64 -0
  82. package/src/output.ts +46 -16
  83. package/src/parse.ts +41 -3
  84. package/src/policy-facts.ts +38 -6
  85. package/src/policy-fixture.ts +14 -7
  86. package/src/prerender.ts +111 -2
  87. package/src/registry.ts +21 -3
  88. package/src/runtime-overrides.ts +66 -0
  89. package/src/safe-url-label.ts +24 -0
  90. package/src/scaffold-fixture.ts +10 -0
  91. package/src/scaffold-typecheck.ts +16 -38
  92. package/src/serve.ts +185 -13
  93. package/src/shell-quote.ts +15 -0
  94. package/src/source-files.ts +4 -0
  95. package/src/statement-loop.ts +74 -0
  96. package/src/style-csp.ts +18 -0
  97. package/src/sync-authenticator.ts +59 -0
  98. package/src/templates/action.ts +15 -30
  99. package/src/templates/admin-page.ts +103 -0
  100. package/src/templates/admin.ts +11 -7
  101. package/src/templates/backfill.ts +212 -0
  102. package/src/templates/entity.ts +72 -31
  103. package/src/templates/guard.ts +143 -0
  104. package/src/templates/index.ts +12 -1
  105. package/src/templates/island.ts +67 -0
  106. package/src/templates/job.ts +53 -13
  107. package/src/templates/naming.ts +17 -1
  108. package/src/templates/policy.ts +35 -28
  109. package/src/templates/query.ts +24 -5
  110. package/src/templates/resource.ts +19 -11
  111. package/src/templates/route.ts +90 -15
  112. package/src/templates/scaffold-app.ts +142 -45
  113. package/src/templates/scaffold-claude-agents.ts +149 -0
  114. package/src/templates/scaffold-claude-commands.ts +221 -0
  115. package/src/templates/scaffold-claude.ts +134 -0
  116. package/src/templates/scaffold-container.ts +46 -2
  117. package/src/templates/scaffold-db-package.ts +91 -0
  118. package/src/templates/scaffold-docs.ts +24 -5
  119. package/src/templates/scaffold-domain-package.ts +90 -0
  120. package/src/templates/scaffold-env.ts +87 -0
  121. package/src/templates/scaffold-i18n.ts +4 -1
  122. package/src/templates/scaffold-mcp-package.ts +49 -0
  123. package/src/templates/scaffold-package-shape.ts +25 -4
  124. package/src/templates/scaffold-repo.ts +116 -257
  125. package/src/templates/scaffold-roles.ts +68 -0
  126. package/src/templates/scaffold-ui-package.ts +56 -0
  127. package/src/templates/slice-foundation.ts +88 -0
  128. package/src/templates/wrap.ts +95 -0
  129. package/src/test-counts.ts +35 -0
  130. package/src/test-select.ts +30 -15
  131. package/src/test-shards.ts +20 -11
  132. package/src/test-workers.ts +50 -0
  133. package/src/ts-scan.ts +284 -15
  134. package/src/tsconfig-references.ts +103 -0
  135. package/src/verify-floor.ts +133 -0
  136. package/src/verify-step.ts +19 -0
  137. package/src/verify-test-run.ts +72 -0
  138. package/src/verify-tests.ts +160 -71
  139. package/src/version-loader.ts +20 -3
  140. package/src/workspace-checks.ts +87 -16
  141. package/src/write-line.ts +34 -0
package/src/ts-scan.ts CHANGED
@@ -28,14 +28,23 @@ const REGEX_AFTER_WORDS = new Set(
28
28
  'await case delete do else in instanceof new of return throw typeof void yield'.split(' '),
29
29
  );
30
30
 
31
- /** Index just past the closing quote of the literal opening at `from`, or the end of the text. */
31
+ /**
32
+ * Index just past the closing quote of the literal opening at `from`, or `from + 1` when a `'`/`"`
33
+ * does not close on its own line — which makes it text, not a literal. Only a template literal may
34
+ * span a newline, so the apostrophe in `<p>Don't panic</p>` is JSX text; read as an opener it ran
35
+ * forward to the next `'` in the FILE (the next `fix:` line) and blanked every declaration between,
36
+ * silently emptying the `errors` gate for the whole file. Same rule `endOfRegex` applies to a `/`.
37
+ * An escaped newline is still a continuation: the escape is consumed before the line test.
38
+ */
32
39
  function endOfLiteral(text: string, from: number): number {
33
40
  const quote = text[from] as string;
41
+ const spansLines = quote === '`';
34
42
  for (let i = from + 1; i < text.length; i += 1) {
35
43
  if (text[i] === '\\') i += 1;
36
44
  else if (text[i] === quote) return i + 1;
45
+ else if (!spansLines && text[i] === '\n') return from + 1;
37
46
  }
38
- return text.length;
47
+ return spansLines ? text.length : from + 1;
39
48
  }
40
49
 
41
50
  /**
@@ -118,11 +127,25 @@ export const stripComments = (text: string): string => blankRegions(text, false)
118
127
  /** Comments and string contents gone, delimiters kept — what a scan for code structure reads. */
119
128
  export const maskLiterals = (text: string): string => blankRegions(text, true);
120
129
 
121
- const lineOf = (text: string, index: number): number => {
122
- let line = 1;
123
- for (let i = 0; i < index; i += 1) if (text[i] === '\n') line += 1;
124
- return line;
125
- };
130
+ /**
131
+ * Line numbers for one text, in one pass. Counting newlines per lookup is O(index), which a scan
132
+ * asking for a line per literal pays once per literal — measured at ~15s over the framework's own
133
+ * package tree, against ~1s for the same walk with this. One offset table, then a binary search.
134
+ */
135
+ function lineIndex(text: string): (index: number) => number {
136
+ const newlines: number[] = [];
137
+ for (let i = 0; i < text.length; i += 1) if (text[i] === '\n') newlines.push(i);
138
+ return (index) => {
139
+ let low = 0;
140
+ let high = newlines.length;
141
+ while (low < high) {
142
+ const mid = (low + high) >> 1;
143
+ if ((newlines[mid] as number) < index) low = mid + 1;
144
+ else high = mid;
145
+ }
146
+ return low + 1;
147
+ };
148
+ }
126
149
 
127
150
  /**
128
151
  * Every string literal in the value expression starting at `from`, at the expression's own bracket
@@ -130,13 +153,20 @@ const lineOf = (text: string, index: number): number => {
130
153
  * instead of silently skipped; the depth rule is what keeps `command.join(' ')`'s separator and
131
154
  * `table['key']`'s key out — an argument is not a fix.
132
155
  */
133
- function valueLiterals(masked: string, source: string, from: number): readonly FixSite[] {
156
+ function valueLiterals(
157
+ masked: string,
158
+ source: string,
159
+ from: number,
160
+ lineAt: (index: number) => number,
161
+ ): readonly FixSite[] {
134
162
  const found: { value: string; index: number }[] = [];
135
163
  let depth = 0;
136
164
  for (let i = from; i < masked.length; i += 1) {
137
165
  const ch = masked[i] as string;
138
166
  if (QUOTES.has(ch)) {
139
167
  const end = endOfLiteral(masked, i);
168
+ // A quote that never closes is one character of code, not an empty literal to report.
169
+ if (end === i + 1) continue;
140
170
  if (depth === 0) found.push({ value: source.slice(i + 1, end - 1), index: i });
141
171
  i = end - 1;
142
172
  } else if (OPENERS.has(ch)) depth += 1;
@@ -147,7 +177,7 @@ function valueLiterals(masked: string, source: string, from: number): readonly F
147
177
  }
148
178
  return found.map((literal) => ({
149
179
  at: '',
150
- line: lineOf(masked, literal.index),
180
+ line: lineAt(literal.index),
151
181
  fix: literal.value,
152
182
  }));
153
183
  }
@@ -155,25 +185,180 @@ function valueLiterals(masked: string, source: string, from: number): readonly F
155
185
  /** The lookbehind rejects member access: `cond ? e.fix : ''` is a ternary, not a declaration. */
156
186
  const FIX_KEY = /(?<![.\w$])fix\s*:\s*/g;
157
187
 
188
+ /** Text between the bracket at `open` and its match, or `undefined` when it never closes. */
189
+ function bracketSpan(masked: string, open: number): string | undefined {
190
+ let depth = 0;
191
+ for (let i = open; i < masked.length; i += 1) {
192
+ const ch = masked[i] as string;
193
+ // Only `()[]{}`. An angle bracket is a generic in a parameter list and the tail of `=>` in the
194
+ // very same list, so counting it makes `(fn: () => void)` end the span in the wrong place.
195
+ if (OPENERS.has(ch)) depth += 1;
196
+ else if (CLOSERS.has(ch)) {
197
+ depth -= 1;
198
+ if (depth === 0) return masked.slice(open + 1, i);
199
+ }
200
+ }
201
+ return undefined;
202
+ }
203
+
204
+ /** Split at depth-0 commas. Safe on masked text, where a comma inside a literal is already gone. */
205
+ function topLevelParts(text: string): readonly string[] {
206
+ const parts: string[] = [];
207
+ let depth = 0;
208
+ let start = 0;
209
+ for (let i = 0; i < text.length; i += 1) {
210
+ const ch = text[i] as string;
211
+ if (OPENERS.has(ch)) depth += 1;
212
+ else if (CLOSERS.has(ch)) depth -= 1;
213
+ else if (ch === ',' && depth === 0) {
214
+ parts.push(text.slice(start, i));
215
+ start = i + 1;
216
+ }
217
+ }
218
+ parts.push(text.slice(start));
219
+ return parts;
220
+ }
221
+
222
+ /** A local function that builds an error and takes its fix positionally, and where in its list. */
223
+ interface FixHelper {
224
+ readonly name: string;
225
+ readonly index: number;
226
+ }
227
+
228
+ const HELPER_DECL =
229
+ /(?<![.\w$])(?:function\s+([A-Za-z_$][\w$]*)\s*\(|(?:const|let)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s+)?\()/g;
230
+
231
+ const FIX_PARAM = /^\s*fix\s*:\s*string\s*$/;
232
+
233
+ /**
234
+ * What separates a helper that BUILDS a fix from one that CONSUMES one. `citedCommandProblem(fix:
235
+ * string, …)` in `fix-command.ts` takes a fix in order to judge it, and reading its call sites as
236
+ * declarations would report findings about strings that are already findings. A builder names a
237
+ * `code` or constructs an `…Error`; a consumer does neither.
238
+ */
239
+ const BUILDS_ERROR = /(?<![.\w$])code\s*[:=]|new\s+[A-Za-z_$][\w$]*Error\s*\(/;
240
+
241
+ /**
242
+ * The body of the declaration whose parameter list ends at `after`, and never a `{` belonging to
243
+ * something below it. An unbounded `indexOf('{')` reads the next object literal in the FILE when
244
+ * the body is a concise expression, so `const label = (fix: string) => fix.trim();` followed
245
+ * anywhere by a `{ code: … }` was read as an error builder and every `label(…)` call handed the
246
+ * gate a string to judge as a fix — a false gate failure over innocent source.
247
+ *
248
+ * The scan therefore ends at the `;` that ends the declaration, or at a bracket closing a scope
249
+ * this declaration is inside. Both directions of that bound answer `''`, which classifies the
250
+ * helper as a non-builder: a missed fix line costs one unchecked citation, a wrongly claimed one
251
+ * costs a build. A `{` inside a return-type annotation (`(): { ok: boolean } => …`) is read as the
252
+ * body and answers `''` for the same reason.
253
+ */
254
+ function bodyOf(masked: string, after: number): string {
255
+ for (let i = after; i < masked.length; i += 1) {
256
+ const ch = masked[i] as string;
257
+ if (ch === '{') return bracketSpan(masked, i) ?? '';
258
+ if (ch === ';' || CLOSERS.has(ch)) break;
259
+ }
260
+ return '';
261
+ }
262
+
263
+ function fixHelpers(masked: string): readonly FixHelper[] {
264
+ const helpers: FixHelper[] = [];
265
+ for (const declaration of masked.matchAll(HELPER_DECL)) {
266
+ const name = declaration[1] ?? declaration[2];
267
+ const open = declaration.index + declaration[0].length - 1;
268
+ if (name === undefined || masked[open] !== '(') continue;
269
+ const params = bracketSpan(masked, open);
270
+ // A rest parameter makes the position of everything after it unknowable, and a destructured
271
+ // one has no position at all — its `fix:` key at the CALL site is already read by `FIX_KEY`.
272
+ if (params === undefined || params.includes('...')) continue;
273
+ const parts = topLevelParts(params);
274
+ if (parts.some((part) => /^\s*[[{]/.test(part))) continue;
275
+ const index = parts.findIndex((part) => FIX_PARAM.test(part));
276
+ if (index === -1) continue;
277
+ if (!BUILDS_ERROR.test(bodyOf(masked, open + params.length + 2))) continue;
278
+ helpers.push({ name, index });
279
+ }
280
+ return helpers;
281
+ }
282
+
283
+ /**
284
+ * The argument in that position at every call to that helper IN THIS FILE.
285
+ *
286
+ * Same file, deliberately: resolving `dbNotImplemented` imported from `@ultimat3/db` would mean a
287
+ * cross-file symbol table, and a scanner that guessed at which import a name came from would read
288
+ * an unrelated function's argument as a fix. The gap that leaves is named in `CLAUDE.md`.
289
+ */
290
+ function helperFixSites(
291
+ masked: string,
292
+ source: string,
293
+ at: string,
294
+ helper: FixHelper,
295
+ lineAt: (index: number) => number,
296
+ ): readonly FixSite[] {
297
+ const sites: FixSite[] = [];
298
+ // The lookbehind is `FIX_KEY`'s: `reporter.rejected(…)` is some other object's method.
299
+ const call = new RegExp(`(?<![.\\w$])${helper.name}\\s*\\(`, 'g');
300
+ for (const match of masked.matchAll(call)) {
301
+ const open = match.index + match[0].length - 1;
302
+ const args = bracketSpan(masked, open);
303
+ if (args === undefined) continue;
304
+ const parts = topLevelParts(args);
305
+ const argument = parts[helper.index];
306
+ if (argument === undefined) continue;
307
+ // Stricter than the `fix:` path, and deliberately: the whole argument must BE one literal.
308
+ // `valueLiterals` alone reads `prefix + 'x doctor'` as one literal, because the identifier
309
+ // half contributes none — and publishing half a fix as the whole one is the failure
310
+ // `soleLiteral` already names. A key at least declares that what follows is the value.
311
+ const quote = argument.trim()[0];
312
+ if (quote === undefined || !QUOTES.has(quote)) continue;
313
+ const literal = argument.indexOf(quote);
314
+ if (argument.slice(endOfLiteral(argument, literal)).trim() !== '') continue;
315
+ const from = parts.slice(0, helper.index).reduce((n, part) => n + part.length + 1, open + 1);
316
+ const literals = valueLiterals(masked, source, from, lineAt);
317
+ if (literals.length === 1) sites.push({ ...(literals[0] as FixSite), at });
318
+ }
319
+ return sites;
320
+ }
321
+
158
322
  /**
159
323
  * Every string a `fix:` can evaluate to. Searched over the masked source, so a `fix:` written
160
324
  * inside a doc comment or interpolated into a message is not mistaken for a declaration. A `fix`
161
325
  * computed at runtime — a bare identifier, a parameter, a table lookup with no literal fallback —
162
326
  * has nothing to read and is beyond a static scan; the gate says so rather than guessing.
327
+ *
328
+ * Two shapes, because a fix does not always arrive under a key. `@ultimat3/mcp`'s `readonly-sql.ts`
329
+ * hands every one of its fixes positionally to a local `rejected(cause, fix)` helper, so the key
330
+ * rule alone returned `[]` for the whole file — 20 non-test files in that package and the scanner
331
+ * saw fixes in three — and two stale `x db branch <name>` lines shipped through the hole.
163
332
  */
164
333
  export function scanFixes(source: string, at: string): readonly FixSite[] {
165
334
  const masked = maskLiterals(source);
335
+ const lineAt = lineIndex(masked);
166
336
  const sites: FixSite[] = [];
167
337
  for (const key of masked.matchAll(FIX_KEY)) {
168
338
  const start = key.index + key[0].length;
169
- for (const literal of valueLiterals(masked, source, start)) sites.push({ ...literal, at });
339
+ for (const literal of valueLiterals(masked, source, start, lineAt)) {
340
+ sites.push({ ...literal, at });
341
+ }
342
+ }
343
+ for (const helper of fixHelpers(masked)) {
344
+ sites.push(...helperFixSites(masked, source, at, helper, lineAt));
170
345
  }
171
346
  return sites;
172
347
  }
173
348
 
174
- /** `packages/<pkg>/src/errors.ts` and core's `error-codes.ts`: one file per package, by rule. */
175
- export const isCodeRegistry = (path: string): boolean =>
176
- /(?:^|\/)(?:errors|error-codes)\.ts$/.test(path);
349
+ const CODE_TABLE = /\bexport const [A-Z][A-Z0-9_]*_ERROR_(?:CODES|TITLES)\b/;
350
+
351
+ /**
352
+ * Whether a file IS a package's code registry — asked of its contents, not of its name.
353
+ *
354
+ * A filename test (`errors.ts` or `error-codes.ts`) held only while one file per package did both
355
+ * jobs. The moment `@ultimat3/cli`'s split under the 500-line ceiling — table into `error-codes.ts`,
356
+ * classes into `errors.ts` — the classes file was still *named* like a registry, so every code it
357
+ * throws outranked the package that actually owns it and `X_NOT_IMPLEMENTED` moved from `core` to
358
+ * `cli` in the manifest. The table is the thing; `export const <PKG>_ERROR_{CODES,TITLES}` is the
359
+ * one shape every package declares it in, and `x verify`'s `errors` step is what keeps that true.
360
+ */
361
+ export const isCodeRegistry = (source: string): boolean => CODE_TABLE.test(source);
177
362
 
178
363
  const CODE_AT_KEY = /\bcode\s*[:=]\s*(['"`])(X_[A-Z0-9_]+)\1/g;
179
364
  const CODE_LITERAL = /(['"`])(X_[A-Z0-9_]+)\1/g;
@@ -187,18 +372,102 @@ const CODE_KEY = /^[\t ]*(X_[A-Z0-9_]+)\s*:/gm;
187
372
  */
188
373
  export function scanCodes(source: string, at: string): readonly CodeSite[] {
189
374
  const text = stripComments(source);
375
+ const lineAt = lineIndex(text);
190
376
  const sites = new Map<string, CodeSite>();
191
377
  const add = (code: string, index: number): void => {
192
- if (!sites.has(code)) sites.set(code, { at, line: lineOf(text, index), code });
378
+ if (!sites.has(code)) sites.set(code, { at, line: lineAt(index), code });
193
379
  };
194
380
  for (const match of text.matchAll(CODE_AT_KEY)) add(match[2] as string, match.index);
195
- if (isCodeRegistry(at)) {
381
+ if (isCodeRegistry(text)) {
196
382
  for (const match of text.matchAll(CODE_LITERAL)) add(match[2] as string, match.index);
197
383
  for (const match of text.matchAll(CODE_KEY)) add(match[1] as string, match.index);
198
384
  }
199
385
  return [...sites.values()];
200
386
  }
201
387
 
388
+ export interface CodeFixSite extends CodeSite {
389
+ /**
390
+ * The fix literal exactly as written, `${…}` included. Absent when the throw site builds its
391
+ * fix out of something this cannot read — a helper call, a parameter, a ternary with two
392
+ * branches — because a fix the scan has to guess at is one it must not report.
393
+ */
394
+ readonly fix?: string;
395
+ }
396
+
397
+ /** `code:` / `code =`, or `fix:`. `fix =` is deliberately not a declaration — `scanFixes` agrees. */
398
+ const CODE_OR_FIX_KEY = /(?<![.\w$])(?:(code)\s*[:=]|(fix)\s*:)\s*/g;
399
+
400
+ /**
401
+ * The single literal a key's value evaluates to, or `undefined` when it evaluates to none or to
402
+ * more than one. Two is as unreadable as zero here: `cond ? 'a' : 'b'` and `'a' + 'b'` need a
403
+ * parser to tell apart, and picking a branch would publish half a fix as the whole one.
404
+ */
405
+ function soleLiteral(
406
+ masked: string,
407
+ source: string,
408
+ from: number,
409
+ lineAt: (index: number) => number,
410
+ ): FixSite | undefined {
411
+ const found = valueLiterals(masked, source, from, lineAt);
412
+ return found.length === 1 ? found[0] : undefined;
413
+ }
414
+
415
+ /**
416
+ * Every `X_*` code paired with the `fix:` written beside it — in the SAME object literal, which is
417
+ * the whole rule. `new UltimateError({ code, cause, fix })` is the one shape this framework raises
418
+ * an error in, so adjacency decides the pair without a parser and without asking which of a file's
419
+ * fixes belongs to which of its codes. `X_ERROR_FIX_INVALID` already proves every one of these is
420
+ * runnable, so a reader that projects them inherits that proof instead of restating it (axiom 2).
421
+ *
422
+ * A site is reported with no `fix` rather than dropped: "this code is raised here and the fix is
423
+ * computed" is a different, and more useful, answer than "this code does not exist".
424
+ */
425
+ export function scanCodeFixSites(source: string, at: string): readonly CodeFixSite[] {
426
+ const masked = maskLiterals(source);
427
+ const lineAt = lineIndex(masked);
428
+ const keys = new Map<number, { readonly kind: 'code' | 'fix'; readonly from: number }>();
429
+ for (const key of masked.matchAll(CODE_OR_FIX_KEY)) {
430
+ keys.set(key.index, {
431
+ kind: key[1] === undefined ? 'fix' : 'code',
432
+ from: key.index + key[0].length,
433
+ });
434
+ }
435
+ const codes = new Map<number, CodeSite>();
436
+ const fixes = new Map<number, string>();
437
+ const stack: number[] = [];
438
+ for (let i = 0; i < masked.length; i += 1) {
439
+ const ch = masked[i] as string;
440
+ if (QUOTES.has(ch)) {
441
+ i = endOfLiteral(masked, i) - 1;
442
+ continue;
443
+ }
444
+ if (OPENERS.has(ch)) {
445
+ stack.push(i);
446
+ continue;
447
+ }
448
+ if (CLOSERS.has(ch)) {
449
+ stack.pop();
450
+ continue;
451
+ }
452
+ const key = keys.get(i);
453
+ // Scope `-1` is the file body: a top-level `const code = 'X_A'` and an unrelated `fix:` far
454
+ // below it are not one declaration, and pairing them would invent an error nobody throws.
455
+ const scope = stack.at(-1);
456
+ if (key === undefined || scope === undefined) continue;
457
+ const literal = soleLiteral(masked, source, key.from, lineAt);
458
+ if (literal === undefined) continue;
459
+ if (key.kind === 'fix') {
460
+ if (!fixes.has(scope)) fixes.set(scope, literal.fix);
461
+ } else if (/^X_[A-Z0-9_]+$/.test(literal.fix) && !codes.has(scope)) {
462
+ codes.set(scope, { at, line: literal.line, code: literal.fix });
463
+ }
464
+ }
465
+ return [...codes].map(([scope, site]) => {
466
+ const fix = fixes.get(scope);
467
+ return fix === undefined ? site : { ...site, fix };
468
+ });
469
+ }
470
+
202
471
  const BORROWED_LIST = /BORROWED_ERROR_CODES[^=]*=[^[]*\[([^\]]*)\]/g;
203
472
 
204
473
  /**
@@ -0,0 +1,103 @@
1
+ // One rule: every published workspace is in the root build graph. `bun run typecheck` is `tsc -b`,
2
+ // which compiles referenced projects and nothing else — so a package no reference names is a
3
+ // package the gate's `typecheck` step reports green over without having read a line of it.
4
+
5
+ // Bun ships no equivalent: `join` builds the host-separator path from the scan root to the config.
6
+ // Nothing else here is `node:` — the read is `Bun.file`, and its rejection is also the answer for a
7
+ // root that has no `tsconfig.json` at all, so an `existsSync` ahead of it was a second question
8
+ // with one answer.
9
+ import { join } from 'node:path';
10
+ import { docsFor } from './error-codes';
11
+ import type { Finding } from './output';
12
+ import { maskLiterals, stripComments } from './ts-scan';
13
+
14
+ const ROOT_TSCONFIG = 'tsconfig.json';
15
+
16
+ /**
17
+ * `./packages/cli`, `packages/cli/` and `packages/cli` are one project; the JSON allows all three.
18
+ * Exported because "is this project already referenced?" is asked in three places — here,
19
+ * `scripts/new-package.ts` when it adds an entry, and `scripts/reference-app-gate.ts` when it
20
+ * checks an app — and a spelling one of them treats as a match and another does not is how the
21
+ * scaffolder appends a duplicate entry the check already considered present.
22
+ */
23
+ export const normalizeReferencePath = (path: string): string =>
24
+ path.replace(/^\.\//, '').replace(/\/+$/, '');
25
+
26
+ /**
27
+ * A tsconfig is JSONC and `JSON.parse` is not, so the comments and trailing commas `tsc` accepts —
28
+ * and `tsc --init` writes — are removed before the parse. `Bun.file().json()` rejects both, and
29
+ * the rejection was mapped to "this root does not use project references": the check went dark on
30
+ * exactly the roots most likely to have been written by hand, while `typecheck` stayed green over
31
+ * every package it then skipped. `stripComments` is `ts-scan.ts`'s, so a `//` inside a string is a
32
+ * URL and not a comment; the trailing-comma pass reads MASKED text for the same reason.
33
+ */
34
+ function parseJsonc(text: string): unknown {
35
+ const uncommented = stripComments(text);
36
+ const masked = maskLiterals(uncommented);
37
+ const chars = [...uncommented];
38
+ for (let i = 0; i < masked.length; i += 1) {
39
+ if (masked[i] !== ',') continue;
40
+ let next = i + 1;
41
+ while (next < masked.length && /\s/.test(masked[next] as string)) next += 1;
42
+ if (masked[next] === '}' || masked[next] === ']') chars[i] = ' ';
43
+ }
44
+ return JSON.parse(chars.join('')) as unknown;
45
+ }
46
+
47
+ /**
48
+ * `undefined` means "this root does not use project references" — a different repo shape, not an
49
+ * empty graph. A scaffolded app is that shape (`extends` + `include`, no references at all), and
50
+ * telling its author to add an entry to a list that does not exist is a fix that makes the build
51
+ * worse. A tsconfig that will not parse EVEN AS JSONC is `typecheck`'s to report, with tsc's own
52
+ * message — this check has no code that would mean "the file is broken" and must not borrow one
53
+ * that means something else.
54
+ */
55
+ async function referencedPaths(root: string): Promise<ReadonlySet<string> | undefined> {
56
+ const payload: unknown = await Bun.file(join(root, ROOT_TSCONFIG))
57
+ .text()
58
+ .then(parseJsonc)
59
+ .catch(() => undefined);
60
+ const references =
61
+ typeof payload === 'object' && payload !== null
62
+ ? (payload as { references?: unknown }).references
63
+ : undefined;
64
+ if (!Array.isArray(references)) return undefined;
65
+ return new Set(
66
+ references.flatMap((entry: unknown) => {
67
+ const value =
68
+ typeof entry === 'object' && entry !== null
69
+ ? (entry as { path?: unknown }).path
70
+ : undefined;
71
+ return typeof value === 'string' ? [normalizeReferencePath(value)] : [];
72
+ }),
73
+ );
74
+ }
75
+
76
+ /**
77
+ * The edit, spelled out: the array to add to, the entry to add, and the command that proves it
78
+ * took. `tsc -b` is the same one the gate's `typecheck` step runs, so a reader who runs the fix
79
+ * runs the check.
80
+ */
81
+ export const unreferencedFinding = (dir: string): Finding => ({
82
+ code: 'X_PACKAGE_UNREFERENCED',
83
+ cause: `packages/${dir} is a published workspace and ${ROOT_TSCONFIG} has no reference to it, so tsc -b never builds it`,
84
+ fix: `add { "path": "./packages/${dir}" } to "references" in ${ROOT_TSCONFIG}, then run bunx tsc -b --pretty false`,
85
+ docs: docsFor('X_PACKAGE_UNREFERENCED'),
86
+ at: ROOT_TSCONFIG,
87
+ });
88
+
89
+ /**
90
+ * Published workspaces only. A private package is not a shipped contract and a generated app's
91
+ * `packages/*` are all private, so this asks nothing of an app that never publishes — the same
92
+ * line `checkPublishShape` already draws.
93
+ */
94
+ export async function checkRootReferences(
95
+ root: string,
96
+ dirs: readonly string[],
97
+ ): Promise<readonly Finding[]> {
98
+ const referenced = await referencedPaths(root);
99
+ if (referenced === undefined) return [];
100
+ return dirs
101
+ .filter((dir) => !referenced.has(`packages/${dir}`))
102
+ .map((dir) => unreferencedFinding(dir));
103
+ }
@@ -0,0 +1,133 @@
1
+ // The suite ratchet: the steps this repo has already proved it can run, committed as a floor.
2
+ // `applies` answers "is there anything to check here?", and a deleted suite answers "no" — which
3
+ // reads as a skip and keeps the gate green. The floor turns that skip back into a failure. Read
4
+ // here and written by nothing: a gate that edits its own floor ratchets both ways, which is none.
5
+
6
+ // Bun ships no equivalent for either: `existsSync` answers whether this root committed a floor at
7
+ // all, and `join` builds the host-separator path to it.
8
+ import { existsSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { docsFor } from './error-codes';
11
+ import type { Finding } from './output';
12
+ import { VERIFY_STEP_NAMES } from './verify-step';
13
+
14
+ /** Hand-written and committed, beside the generated `x.manifest.json` the same gate reads. */
15
+ export const VERIFY_FLOOR_FILE = 'x.verify.json';
16
+
17
+ export interface VerifyFloor {
18
+ /** Declared step names this run may not report as skipped. */
19
+ readonly steps: readonly string[];
20
+ /** Why part of the file is not a floor. The `manifest` step reports these; nothing swallows them. */
21
+ readonly problems: readonly string[];
22
+ }
23
+
24
+ const asRecord = (value: unknown): Record<string, unknown> | undefined =>
25
+ typeof value === 'object' && value !== null && !Array.isArray(value)
26
+ ? (value as Record<string, unknown>)
27
+ : undefined;
28
+
29
+ /**
30
+ * The file's names, split into the ones the ratchet can enforce and the reasons the rest cannot be.
31
+ * A name no step declares is dropped rather than enforced — it can never apply, so enforcing it
32
+ * would pin the gate red forever — and it is returned as a problem, because a floor with a typo in
33
+ * it silently covers nothing, which is the same false green the floor exists to close.
34
+ *
35
+ * `declared` is a parameter rather than the imported constant at the call site, so a test can pin a
36
+ * closed world instead of asserting against every step this build happens to ship.
37
+ */
38
+ export function parseVerifyFloor(
39
+ text: string,
40
+ declared: readonly string[] = VERIFY_STEP_NAMES,
41
+ ): VerifyFloor {
42
+ let payload: unknown;
43
+ try {
44
+ payload = JSON.parse(text);
45
+ } catch (error) {
46
+ const reason = error instanceof Error ? error.message : String(error);
47
+ return { steps: [], problems: [`it does not parse as JSON (${reason})`] };
48
+ }
49
+ const steps = asRecord(payload)?.['steps'];
50
+ if (!Array.isArray(steps)) {
51
+ return { steps: [], problems: ['it has no "steps" array of step names'] };
52
+ }
53
+ const named = steps.filter((step): step is string => typeof step === 'string');
54
+ const unknown = named.filter((step) => !declared.includes(step));
55
+ return {
56
+ steps: named.filter((step) => declared.includes(step)),
57
+ problems: [
58
+ ...(named.length === steps.length ? [] : ['"steps" holds an entry that is not a string']),
59
+ ...(unknown.length === 0
60
+ ? []
61
+ : [`"steps" names ${unknown.join(', ')}, which x verify does not run`]),
62
+ ],
63
+ };
64
+ }
65
+
66
+ /** No file is no floor: a repo that never committed one is not ratcheted, and reports nothing. */
67
+ export async function readVerifyFloor(root: string): Promise<VerifyFloor | undefined> {
68
+ const path = join(root, VERIFY_FLOOR_FILE);
69
+ if (!existsSync(path)) return undefined;
70
+ const text = await Bun.file(path)
71
+ .text()
72
+ .catch(() => undefined);
73
+ if (text === undefined) return { steps: [], problems: ['it could not be read as a file'] };
74
+ return parseVerifyFloor(text);
75
+ }
76
+
77
+ /** Whether the floor already claims this step has something to check in this repo. */
78
+ export const floorRequires = (floor: VerifyFloor | undefined, step: string): boolean =>
79
+ floor?.steps.includes(step) === true;
80
+
81
+ /**
82
+ * A step the floor requires that found nothing to run. Named for what happened rather than for the
83
+ * file — the suite is what vanished — and the fix carries both edits that resolve it, because
84
+ * either can be right: the suite comes back, or the floor drops a line in a commit that says why.
85
+ *
86
+ * Command first, alternatives behind a `#`, so the line runs verbatim and the shell drops the rest
87
+ * (the shape `mcp-errors.ts` gives this same code). Neither edit is scripted here on purpose: a
88
+ * command that rewrites the floor is the gate editing its own ratchet, which is the false green the
89
+ * floor exists to close — so the run that proves the step is back is what this offers to repeat.
90
+ */
91
+ export const vanishedSuiteFinding = (step: string): Finding => ({
92
+ code: 'X_VERIFY_SUITE_VANISHED',
93
+ cause: `${VERIFY_FLOOR_FILE} requires the ${step} step and this run found nothing for it to check`,
94
+ fix: `x verify --json # restore the ${step} suite, or drop "${step}" from ${VERIFY_FLOOR_FILE} in the commit that says why`,
95
+ docs: docsFor('X_VERIFY_SUITE_VANISHED'),
96
+ at: VERIFY_FLOOR_FILE,
97
+ });
98
+
99
+ /**
100
+ * The second way a suite vanishes, and the reason this is the same code rather than a new one: a
101
+ * step whose files are all still there and whose every test skipped itself found exactly as much
102
+ * for the floor to stand on as a step with no files — nothing. `applies` cannot see it, because
103
+ * `describe.skipIf` is decided inside the run, so this is read back out of what bun reported.
104
+ *
105
+ * The fix names the suite's own command first: what an author has to change is the environment the
106
+ * tests skip without (`TEST_DATABASE_URL` for `live`), and running the type alone is how they find
107
+ * out which one. Dropping the step from the floor stays the alternative, behind the `#`, because
108
+ * either can be the right answer and neither may be performed by the gate on its own ratchet.
109
+ */
110
+ export const skippedSuiteFinding = (step: string, skipped: number): Finding => ({
111
+ code: 'X_VERIFY_SUITE_VANISHED',
112
+ cause: `${VERIFY_FLOOR_FILE} requires the ${step} step and all ${skipped} test(s) it found skipped themselves, so nothing ran`,
113
+ fix: `x test ${step} --json # then set what the suite skips without, or drop "${step}" from ${VERIFY_FLOOR_FILE} in the commit that says why`,
114
+ docs: docsFor('X_VERIFY_SUITE_VANISHED'),
115
+ at: VERIFY_FLOOR_FILE,
116
+ });
117
+
118
+ /**
119
+ * The floor file's own integrity, as findings. `X_CONFIG_INVALID` rather than a second code of this
120
+ * package's own: a committed file the framework reads and cannot use is exactly what core already
121
+ * named, and a floor that enforces nothing is not a vanished suite.
122
+ *
123
+ * The command runs first because it is what the edit needs: the step table it prints is the closed
124
+ * set of names the floor may hold, so an author fixing a typo reads the answer instead of guessing.
125
+ */
126
+ export const floorProblemFindings = (floor: VerifyFloor | undefined): readonly Finding[] =>
127
+ (floor?.problems ?? []).map((problem) => ({
128
+ code: 'X_CONFIG_INVALID',
129
+ cause: `${VERIFY_FLOOR_FILE} is not a suite floor: ${problem}`,
130
+ fix: `x verify --json # then write ${VERIFY_FLOOR_FILE} as {"steps":["unit","contract"]}, naming only steps it ran`,
131
+ docs: docsFor('X_CONFIG_INVALID'),
132
+ at: VERIFY_FLOOR_FILE,
133
+ }));
@@ -5,6 +5,7 @@
5
5
  import type { ExecResult, Runner } from './exec';
6
6
  import { execOutput } from './exec';
7
7
  import type { Finding } from './output';
8
+ import type { TestCounts } from './test-counts';
8
9
 
9
10
  /**
10
11
  * Every step of the gate, in cost order — cheapest and most informative first, and never a check
@@ -44,12 +45,30 @@ export interface VerifyContext {
44
45
  readonly root: string;
45
46
  readonly runner: Runner;
46
47
  readonly hostChecks?: Partial<Record<VerifyStepName, HostCheck>>;
48
+ /**
49
+ * How wide the parallel test steps go. Absent means `defaultWorkers()` — a knob, never a
50
+ * narrowing: no value of it changes which steps run or what "green" means, which is why this is
51
+ * the only flag `x verify` accepts beyond the global ones.
52
+ */
53
+ readonly workers?: number;
47
54
  }
48
55
 
49
56
  export interface StepOutcome {
50
57
  readonly ok: boolean;
51
58
  readonly findings: readonly Finding[];
52
59
  readonly output?: string;
60
+ /**
61
+ * Processes this step actually used. `1` is a step that ran serially, and a reader has to be
62
+ * able to tell "serial because nothing could isolate it" from "parallel and fast" without
63
+ * reading the step list's source.
64
+ */
65
+ readonly workers?: number;
66
+ /**
67
+ * What the suite executed, for the steps that run one. Absent means this step spawned no test
68
+ * process at all — a check step, or the `eval` step answering with declarations alone — and is
69
+ * NOT the same as a suite that ran nothing, which is a number the ratchet acts on.
70
+ */
71
+ readonly tests?: TestCounts;
53
72
  }
54
73
 
55
74
  export interface VerifyStep {