@ultimat3/cli 30.9.0 → 31.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 (197) hide show
  1. package/CLAUDE.md +75 -64
  2. package/README.md +4 -1
  3. package/package.json +30 -29
  4. package/src/admin-registration.ts +1 -1
  5. package/src/affected.ts +5 -1
  6. package/src/app-boundaries.ts +88 -9
  7. package/src/app-load-async.ts +133 -0
  8. package/src/app-load-batch.ts +203 -0
  9. package/src/app-load-prebuilt.ts +147 -0
  10. package/src/app-load-register.ts +175 -0
  11. package/src/app-load.ts +143 -175
  12. package/src/app-loader-imports.ts +31 -0
  13. package/src/app-root.ts +13 -0
  14. package/src/app-runtime.ts +5 -1
  15. package/src/boundary-findings.ts +12 -0
  16. package/src/browser-launcher-port.ts +3 -7
  17. package/src/browser-launcher.ts +1 -1
  18. package/src/budgets-scan.ts +8 -0
  19. package/src/budgets.ts +10 -1
  20. package/src/build-registry-background.ts +59 -0
  21. package/src/build-registry.ts +207 -0
  22. package/src/cdp-shot-clock.ts +3 -11
  23. package/src/cdp-shot-driver.ts +3 -2
  24. package/src/cdp-shot-element.ts +3 -2
  25. package/src/cdp-shot-page.ts +2 -2
  26. package/src/cdp-shot-watch.ts +4 -3
  27. package/src/cmd-auth.ts +3 -3
  28. package/src/cmd-db-recount.ts +15 -0
  29. package/src/cmd-drill.ts +10 -6
  30. package/src/cmd-exercise.ts +2 -1
  31. package/src/cmd-generate-spec.ts +6 -0
  32. package/src/cmd-generate.ts +22 -4
  33. package/src/cmd-mail.ts +1 -1
  34. package/src/cmd-routes.ts +2 -2
  35. package/src/cmd-secrets-spec.ts +4 -1
  36. package/src/cmd-shot.ts +14 -4
  37. package/src/cmd-verify-spec.ts +21 -1
  38. package/src/cmd-verify.ts +16 -4
  39. package/src/coverage-source.ts +4 -1
  40. package/src/db-diagnostics.ts +8 -1
  41. package/src/dev-boot.ts +29 -15
  42. package/src/dev-dashboard-invalidations.ts +43 -0
  43. package/src/dev-dashboard.ts +13 -16
  44. package/src/dev-n-plus-one.ts +7 -3
  45. package/src/dev-rebuild.ts +2 -1
  46. package/src/dev-route-table.ts +1 -1
  47. package/src/dev-traces.ts +16 -15
  48. package/src/document-options.ts +12 -1
  49. package/src/drift-store.ts +55 -0
  50. package/src/error-catalog.ts +8 -3
  51. package/src/error-codes-boundary.ts +32 -0
  52. package/src/error-codes.ts +23 -19
  53. package/src/errors.ts +17 -7
  54. package/src/exercise-database.ts +13 -1
  55. package/src/exercise-findings.ts +36 -18
  56. package/src/exercise-services.ts +84 -0
  57. package/src/exercise-subject.ts +38 -13
  58. package/src/failure-capture-boot.ts +9 -5
  59. package/src/framework-schema.ts +5 -5
  60. package/src/generate-exercise.ts +1 -1
  61. package/src/generate-files.ts +27 -7
  62. package/src/generate-kinds.ts +5 -0
  63. package/src/generate-refresh.ts +53 -0
  64. package/src/generate-workspace.ts +169 -0
  65. package/src/generate-write.ts +8 -2
  66. package/src/hold.ts +19 -8
  67. package/src/image-prepare.ts +6 -2
  68. package/src/index.ts +5 -20
  69. package/src/island-bundle.ts +7 -3
  70. package/src/island-capture.ts +2 -2
  71. package/src/island-harness.ts +1 -1
  72. package/src/job-registration.ts +43 -6
  73. package/src/jobs-driver.ts +4 -5
  74. package/src/mcp-errors.ts +18 -4
  75. package/src/mcp-host.ts +5 -1
  76. package/src/mcp-ui-interact.ts +3 -0
  77. package/src/messages-gate.ts +4 -0
  78. package/src/new-shapes-generate.ts +1 -1
  79. package/src/otlp-export.ts +94 -29
  80. package/src/output.ts +3 -7
  81. package/src/page-sync.ts +3 -1
  82. package/src/role-load.ts +17 -11
  83. package/src/role-start.ts +5 -4
  84. package/src/role-sync.ts +7 -8
  85. package/src/route-islands-preload.ts +46 -0
  86. package/src/route-islands.ts +6 -2
  87. package/src/runtime-admin.ts +5 -1
  88. package/src/runtime-bindings.ts +25 -19
  89. package/src/runtime-boot-ports.ts +66 -0
  90. package/src/runtime-bus.ts +29 -5
  91. package/src/runtime-cache-bus.ts +53 -0
  92. package/src/runtime-cache.ts +43 -13
  93. package/src/runtime-isr-outcome.ts +5 -4
  94. package/src/runtime-jobs.ts +2 -2
  95. package/src/runtime-keys.ts +37 -0
  96. package/src/runtime-overrides.ts +148 -42
  97. package/src/runtime-port-bindings-queue.ts +36 -0
  98. package/src/runtime-port-bindings.ts +117 -0
  99. package/src/runtime-ports.ts +164 -0
  100. package/src/runtime-purge.ts +41 -28
  101. package/src/runtime-push.ts +7 -3
  102. package/src/runtime-queue.ts +70 -55
  103. package/src/runtime-realtime.ts +5 -5
  104. package/src/runtime-render-document.ts +4 -1
  105. package/src/runtime-services.ts +110 -158
  106. package/src/runtime-storage-boot.ts +111 -0
  107. package/src/runtime-storage-upload.ts +9 -7
  108. package/src/runtime-storage.ts +7 -1
  109. package/src/serve-boot.ts +8 -4
  110. package/src/serve-entry.ts +3 -0
  111. package/src/serve-env.ts +47 -14
  112. package/src/serve-prebuilt-paths.ts +3 -0
  113. package/src/serve-prebuilt.ts +15 -4
  114. package/src/serve.ts +2 -2
  115. package/src/static-cards.ts +3 -2
  116. package/src/static-report.ts +2 -2
  117. package/src/style-bundle.ts +1 -1
  118. package/src/sync-authenticator.ts +17 -18
  119. package/src/templates/action-tests.ts +4 -4
  120. package/src/templates/backfill.ts +5 -8
  121. package/src/templates/entity.ts +3 -0
  122. package/src/templates/github/ci.yml.ts +3 -1
  123. package/src/templates/github/dependabot.yml.ts +73 -0
  124. package/src/templates/job.ts +13 -22
  125. package/src/templates/naming.ts +20 -1
  126. package/src/templates/pinned/docker-compose.yml +1 -1
  127. package/src/templates/query.ts +7 -8
  128. package/src/templates/route.ts +5 -3
  129. package/src/templates/scaffold-api.ts +1 -1
  130. package/src/templates/scaffold-auth.ts +5 -3
  131. package/src/templates/scaffold-claude-commands.ts +6 -3
  132. package/src/templates/scaffold-claude.ts +4 -4
  133. package/src/templates/scaffold-container-compose.ts +2 -4
  134. package/src/templates/scaffold-domain-package.ts +1 -1
  135. package/src/templates/scaffold-entries.ts +6 -1
  136. package/src/templates/scaffold-helm-fences.ts +3 -2
  137. package/src/templates/scaffold-helm.ts +35 -6
  138. package/src/templates/scaffold-repo.ts +47 -135
  139. package/src/templates/scaffold-runtime-ports.ts +62 -0
  140. package/src/templates/scaffold-verify-floor.ts +97 -0
  141. package/src/templates/shapes/overlay.ts +1 -1
  142. package/src/templates/sign-in-oidc.ts +5 -3
  143. package/src/templates/sign-in-shared.ts +28 -10
  144. package/src/templates/workspace.ts +75 -0
  145. package/src/test-ignores.ts +5 -2
  146. package/src/test-select.ts +4 -1
  147. package/src/upgrade-gate.ts +30 -5
  148. package/src/upgrade-report.ts +7 -1
  149. package/src/verify-changed-facts.ts +53 -0
  150. package/src/verify-changed-scope.ts +161 -0
  151. package/src/verify-changed.ts +174 -0
  152. package/src/verify-checks.ts +31 -19
  153. package/src/verify-drift-owner.ts +30 -0
  154. package/src/verify-e2e.ts +2 -1
  155. package/src/verify-factories.ts +86 -0
  156. package/src/verify-run.ts +13 -11
  157. package/src/verify-step.ts +13 -0
  158. package/src/verify-tests.ts +58 -6
  159. package/src/write-line.ts +21 -6
  160. package/wiki/Actions.md +2 -2
  161. package/wiki/Adapters.md +400 -0
  162. package/wiki/Admin-Dashboard.md +1 -1
  163. package/wiki/Agents.md +9 -9
  164. package/wiki/Auth.md +78 -2
  165. package/wiki/Building-Your-Own-Base.md +1 -1
  166. package/wiki/CLI-Reference.md +34 -7
  167. package/wiki/Caching-And-Invalidation.md +17 -5
  168. package/wiki/Compared.md +8 -2
  169. package/wiki/Configuration.md +14 -14
  170. package/wiki/Deployment.md +28 -1
  171. package/wiki/Entities-And-Migrations.md +47 -1
  172. package/wiki/FAQ.md +8 -2
  173. package/wiki/Feature-Flags.md +1 -1
  174. package/wiki/Home.md +3 -2
  175. package/wiki/Jobs-And-Workflows.md +107 -6
  176. package/wiki/Known-Gaps.md +4 -3
  177. package/wiki/MCP-And-AI.md +18 -4
  178. package/wiki/Mail.md +14 -5
  179. package/wiki/Migrations-And-Backfills.md +29 -4
  180. package/wiki/Money.md +2 -0
  181. package/wiki/N-Plus-One-Detection.md +24 -22
  182. package/wiki/Notify.md +28 -4
  183. package/wiki/Observability.md +121 -15
  184. package/wiki/Queries-And-Live-Queries.md +2 -2
  185. package/wiki/Realtime.md +9 -4
  186. package/wiki/Routes-And-Render-Modes.md +5 -0
  187. package/wiki/Scraping.md +57 -11
  188. package/wiki/Shapes.md +2 -2
  189. package/wiki/Stability.md +7 -5
  190. package/wiki/Storage-And-Uploads.md +56 -4
  191. package/wiki/Testing.md +65 -52
  192. package/wiki/Troubleshooting.md +1 -1
  193. package/wiki/Tutorial-01-First-App.md +1 -1
  194. package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
  195. package/wiki/Tutorial-05-Deploy-Free.md +1 -1
  196. package/wiki/Tutorial-06-Growing-Up.md +8 -8
  197. package/wiki/Upgrading.md +129 -4
@@ -0,0 +1,174 @@
1
+ // `x verify --changed`, the pure half: each changed file (app-root-relative) to the rule it falls
2
+ // under, each rule to the gate steps whose inputs it can move. Fail-open by construction: a path
3
+ // no rule speaks for — a root config, an unknown directory, a deleted module, a file outside the
4
+ // app — selects the whole step list, so a narrowing can only ever skip a step it can prove idle.
5
+
6
+ import { isTest } from './source-files';
7
+ import type { VerifyStepName } from './verify-step';
8
+ import { VERIFY_STEP_NAMES } from './verify-step';
9
+ import { ownerOf } from './verify-tests';
10
+
11
+ export type ChangeRule =
12
+ | 'outside'
13
+ | 'root-config'
14
+ | 'unknown'
15
+ | 'deleted'
16
+ | 'doc'
17
+ | 'test'
18
+ | 'drift-input'
19
+ | 'generated'
20
+ | 'source';
21
+
22
+ /** What the disk says, read once by `verify-changed-facts.ts`, so this file needs no disk. */
23
+ export interface ChangedFacts {
24
+ /**
25
+ * Every app file an entity declaration or `packages/db` reaches by import — what `drift` hashes
26
+ * and compares — or `'everything'` when one of them computes an import nobody can follow.
27
+ */
28
+ readonly driftReach: ReadonlySet<string> | 'everything';
29
+ /** Every TypeScript file the app holds now: a changed one missing here was deleted or moved. */
30
+ readonly known: ReadonlySet<string>;
31
+ }
32
+
33
+ /** Directories whose files are app source: imported, so read by the steps that load the app. */
34
+ const SOURCE_DIRS = new Set(['apps', 'packages', 'guards', 'scripts', 'types', 'bin']);
35
+
36
+ /** Prose: no step compiles it; the steps that read it are `DOC_STEPS`. */
37
+ const isDoc = (path: string): boolean =>
38
+ path.endsWith('.md') || path.startsWith('docs/') || path.startsWith('wiki/');
39
+
40
+ /**
41
+ * What the `drift` step reads beyond the entity closure: the migrations and the db package, a
42
+ * generated client (`apps/<app>/clients/`) and the document it is stamped from (`openapi.json`).
43
+ */
44
+ const isDriftFile = (path: string): boolean =>
45
+ path.startsWith('packages/db/') ||
46
+ /^apps\/[^/]+\/clients\//.test(path) ||
47
+ path === 'openapi.json';
48
+
49
+ const isTypeScript = (path: string): boolean => /\.[cm]?tsx?$/.test(path);
50
+
51
+ /** The one rule a changed file falls under, most specific first. */
52
+ export function classifyChange(path: string, facts: ChangedFacts): ChangeRule {
53
+ if (path.startsWith('../')) return 'outside';
54
+ if (isDoc(path)) return 'doc';
55
+ if (isTest(path) || /(^|\/)e2e\//.test(path)) return 'test';
56
+ if (isDriftFile(path)) return 'drift-input';
57
+ if (path === 'x.manifest.json') return 'generated';
58
+ const top = path.split('/')[0] ?? '';
59
+ // Root-level files are read, not imported: `app.config.ts`, `bun.lock`, `x.verify.json` (the
60
+ // floor every step answers to), `tsconfig.json`, `biome.json`.
61
+ // `app.config.ts` anywhere: below the root it is a second app root (`X_APP_ROOT_NESTED`).
62
+ if (!path.includes('/') || path.endsWith('/app.config.ts')) return 'root-config';
63
+ if (!SOURCE_DIRS.has(top)) return 'unknown';
64
+ // A module gone from disk took its importers' facts with it, entity declarations included.
65
+ if (isTypeScript(path) && !facts.known.has(path)) return 'deleted';
66
+ if (facts.driftReach === 'everything' || facts.driftReach.has(path)) return 'drift-input';
67
+ return 'source';
68
+ }
69
+
70
+ const DOC_STEPS: readonly VerifyStepName[] = [
71
+ 'package-shape',
72
+ 'errors',
73
+ 'unit',
74
+ 'manifest',
75
+ 'roadmap',
76
+ ];
77
+ const TEST_STEPS: readonly VerifyStepName[] = [
78
+ 'typecheck',
79
+ 'lint',
80
+ 'filesize',
81
+ 'package-shape',
82
+ 'errors',
83
+ ];
84
+ const GENERATED_STEPS: readonly VerifyStepName[] = ['lint', 'contract-diff', 'manifest'];
85
+ const NOT_DRIFT = VERIFY_STEP_NAMES.filter((name) => name !== 'drift');
86
+
87
+ /** The steps one file selects under its rule. */
88
+ export function stepsOfChange(path: string, rule: ChangeRule): readonly VerifyStepName[] {
89
+ switch (rule) {
90
+ case 'doc':
91
+ return DOC_STEPS;
92
+ case 'test':
93
+ return [...TEST_STEPS, ownerOf(path)];
94
+ case 'generated':
95
+ return GENERATED_STEPS;
96
+ case 'source':
97
+ return NOT_DRIFT;
98
+ default:
99
+ return VERIFY_STEP_NAMES;
100
+ }
101
+ }
102
+
103
+ export interface ChangedStep {
104
+ readonly name: VerifyStepName;
105
+ /** The changed files that selected it, in diff order. */
106
+ readonly files: readonly string[];
107
+ }
108
+
109
+ export interface ChangedStepPlan {
110
+ readonly files: readonly { readonly path: string; readonly rule: ChangeRule }[];
111
+ /** In gate order — what `--only` would have run. Empty when nothing changed. */
112
+ readonly steps: readonly ChangedStep[];
113
+ }
114
+
115
+ export function planChangedSteps(paths: readonly string[], facts: ChangedFacts): ChangedStepPlan {
116
+ const files = paths.map((path) => ({ path, rule: classifyChange(path, facts) }));
117
+ const selected = new Map<VerifyStepName, string[]>();
118
+ for (const file of files) {
119
+ for (const step of stepsOfChange(file.path, file.rule)) {
120
+ const known = selected.get(step);
121
+ if (known === undefined) selected.set(step, [file.path]);
122
+ else if (!known.includes(file.path)) known.push(file.path);
123
+ }
124
+ }
125
+ const steps = VERIFY_STEP_NAMES.flatMap((name) => {
126
+ const named = selected.get(name);
127
+ return named === undefined ? [] : [{ name, files: named }];
128
+ });
129
+ return { files, steps };
130
+ }
131
+
132
+ /** The suites `--changed` narrows to selected test files (`ctx.tests`); `eval` keeps its own rules. */
133
+ const NARROWED_SUITES: ReadonlySet<VerifyStepName> = new Set([
134
+ 'unit',
135
+ 'contract',
136
+ 'live',
137
+ 'job',
138
+ 'e2e',
139
+ ]);
140
+
141
+ /** The rules whose files the import closure speaks for; any other rule's suites run whole. */
142
+ const CLOSURE_RULES: ReadonlySet<ChangeRule> = new Set(['source', 'test', 'drift-input']);
143
+
144
+ export interface NarrowedPlan {
145
+ readonly plan: ChangedStepPlan;
146
+ /** Suites a file outside the closure's reach selected (a doc): they run every test. */
147
+ readonly whole: readonly VerifyStepName[];
148
+ }
149
+
150
+ /**
151
+ * The plan without the suites no kept test belongs to — a suite with nothing to run would read as
152
+ * a vanished one (`X_VERIFY_SUITE_VANISHED`). `kept` is what `x test --affected` would run: the
153
+ * closure's tests AND every test the module graph never read. A suite a doc (or any rule the
154
+ * closure cannot speak for) selected is kept and run whole: a test reads a doc by no import.
155
+ * `kept` undefined: a changed file forced every test, and every suite stays as planned.
156
+ */
157
+ export function narrowSuites(
158
+ plan: ChangedStepPlan,
159
+ kept: readonly string[] | undefined,
160
+ ): NarrowedPlan {
161
+ if (kept === undefined) return { plan, whole: [] };
162
+ const owned = new Set<VerifyStepName>(kept.map((path) => ownerOf(path)));
163
+ const rules = new Map(plan.files.map((file) => [file.path, file.rule]));
164
+ const whole: VerifyStepName[] = [];
165
+ const steps = plan.steps.filter((step) => {
166
+ if (!NARROWED_SUITES.has(step.name)) return true;
167
+ if (step.files.some((path) => !CLOSURE_RULES.has(rules.get(path) ?? 'unknown'))) {
168
+ whole.push(step.name);
169
+ return true;
170
+ }
171
+ return owned.has(step.name);
172
+ });
173
+ return { plan: { ...plan, steps }, whole };
174
+ }
@@ -12,6 +12,7 @@ import { llmsDescriptionIssues, validateMeta } from '@ultimat3/seo';
12
12
  import { checkAgentsMd } from './app-agents-md';
13
13
  import { readAppSources } from './app-boundaries';
14
14
  import { envExampleFindings } from './app-env';
15
+ import { loadApp } from './app-load';
15
16
  import { appManifest, readAppManifest } from './app-manifest';
16
17
  import { policyFindings } from './app-permissions';
17
18
  import { asyncPageFindings } from './async-pages';
@@ -22,6 +23,7 @@ import { checkDestructiveMigrations } from './db-destructive';
22
23
  import { checkRollingMigrations } from './db-rolling';
23
24
  import { checkUngeneratableMigrations } from './db-ungeneratable';
24
25
  import { checkDocumentStyles, documentSurfaces } from './document-styles';
26
+ import { driftOutcome } from './drift-store';
25
27
  import { checkErrorCodeResolution, checkErrorFixReport } from './error-contract';
26
28
  import { guardFindings } from './guards';
27
29
  import { catalogFindings } from './i18n-registration';
@@ -50,6 +52,7 @@ import { loadSiteSettings } from './site-config';
50
52
  import { readStaticReport } from './static-report';
51
53
  import { unknownToolGateFindings } from './tool-gate-names';
52
54
  import { measureIfStale } from './verify-budgets-build';
55
+ import { nestedAppRootFindings } from './verify-drift-owner';
53
56
  import { exerciseStep } from './verify-exercise';
54
57
  import { floorProblemFindings, readVerifyFloor } from './verify-floor';
55
58
  import { mcpMountFindings } from './verify-mcp-mount';
@@ -201,26 +204,35 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
201
204
  // step's own question — do the committed migrations still describe what the app is doing to its
202
205
  // schema? — off the same directory, in the same pass, with no database either.
203
206
  applies: async (ctx) => existsSync(join(ctx.root, APP_CONFIG_FILE)),
204
- run: async (ctx) =>
205
- fromFindings([
206
- ...(await checkMigrationDrift(ctx.root)),
207
- ...(await checkDestructiveMigrations(ctx.root)),
208
- // The third rail, and the one the other two cannot see: a hand-written statement is
209
- // recorded by no snapshot and hashed by no source, so both halves above are green over SQL
210
- // a squash silently drops. Same directory, same reader, no database — this step's own
211
- // question, which is why it is not a step of its own.
212
- ...(await checkUngeneratableMigrations(ctx.root)),
213
- // The fourth, and the only one that opens a database — a scratch embedded one it boots
214
- // itself, so CI still needs nothing listening: the committed `packages/db/schema/` against
215
- // what replaying the migrations produces, and that dump loaded back (`X_SCHEMA_DUMP_DRIFT`).
216
- ...(await checkSchemaDump(ctx.root, ctx.env ?? Bun.env)),
217
- // The fifth: what the previous release would trip over during a roll. Off until the app
218
- // sets `rollingSince` in `x.verify.json`, since an applied migration cannot gain a marker.
219
- ...(await checkRollingMigrations(ctx.root)),
220
- // The sixth: a generated client (`x client`) against its own stamp — a source document that
207
+ run: async (ctx) => {
208
+ // Loaded first: the drivers the app's modules construct are what decide (`drift-store.ts`).
209
+ await loadApp(ctx.root);
210
+ // A store owning its own schema skips the five migration rails, never the client one.
211
+ return driftOutcome(ctx.root, {
212
+ schema: async () => [
213
+ ...(await checkMigrationDrift(ctx.root)),
214
+ ...(await checkDestructiveMigrations(ctx.root)),
215
+ // The third rail, and the one the other two cannot see: a hand-written statement is
216
+ // recorded by no snapshot and hashed by no source, so both halves above are green over SQL
217
+ // a squash silently drops. Same directory, same reader, no database — this step's own
218
+ // question, which is why it is not a step of its own.
219
+ ...(await checkUngeneratableMigrations(ctx.root)),
220
+ // The fourth, and the only one that opens a database — a scratch embedded one it boots
221
+ // itself, so CI still needs nothing listening: the committed `packages/db/schema/` against
222
+ // what replaying the migrations produces, and that dump loaded back (`X_SCHEMA_DUMP_DRIFT`).
223
+ ...(await checkSchemaDump(ctx.root, ctx.env ?? Bun.env)),
224
+ // The fifth: what the previous release would trip over during a roll. Off until the app
225
+ // sets `rollingSince` in `x.verify.json`, since an applied migration cannot gain a marker.
226
+ ...(await checkRollingMigrations(ctx.root)),
227
+ // The sixth: one migration owner. A nested `app.config.ts` is a second app root — its own
228
+ // registry, migrations and image (`X_APP_ROOT_NESTED`, `verify-drift-owner.ts`).
229
+ ...(await nestedAppRootFindings(ctx.root)),
230
+ ],
231
+ // The seventh: a generated client (`x client`) against its own stamp — a source document that
221
232
  // moved (`X_CLIENT_STALE`) or a body edited by hand (`X_CLIENT_EDITED`). No database.
222
- ...(await checkClientDrift(ctx.root)),
223
- ]),
233
+ client: () => checkClientDrift(ctx.root),
234
+ });
235
+ },
224
236
  },
225
237
  {
226
238
  name: 'contract-diff',
@@ -0,0 +1,30 @@
1
+ // The `drift` step's ownership rail: one repository is ONE app — one `app.config.ts` at the root,
2
+ // one registry every `apps/*` workspace boots into, one image whose `ROLE` picks the process, one
3
+ // `packages/db/migrations`. A second `app.config.ts` inside a workspace makes `x` treat that
4
+ // directory as its own root (its own migrations, its own image), so it is refused here by code.
5
+
6
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
7
+ import { commentSafe } from './comment-safe';
8
+ import type { Finding } from './output';
9
+ import { hasPathSegment } from './path-segments';
10
+ import { toPosix } from './posix-path';
11
+
12
+ const NESTED_CONFIG = '{apps,packages}/**/app.config.ts';
13
+
14
+ /** Every `app.config.ts` below `apps/` or `packages/`, sorted, never a dependency's. */
15
+ export async function nestedAppRootFindings(root: string): Promise<readonly Finding[]> {
16
+ const found: string[] = [];
17
+ for await (const path of new Bun.Glob(NESTED_CONFIG).scan({ cwd: root, absolute: false })) {
18
+ if (!hasPathSegment(path, 'node_modules')) found.push(toPosix(path));
19
+ }
20
+ return found.sort().map((path) => {
21
+ const workspace = path.slice(0, -'/app.config.ts'.length);
22
+ return {
23
+ code: 'X_APP_ROOT_NESTED',
24
+ cause: `${path} makes ${workspace} a second app root — its own registry, migrations and image. One repository is one app: every apps/* workspace boots in the one image (ROLE picks the process) and packages/db/migrations is the one migration owner`,
25
+ fix: `x verify --only drift --json # after deleting ${commentSafe(path)} and moving what it configured into the root app.config.ts`,
26
+ docs: ERROR_DOCS_URL,
27
+ at: path,
28
+ };
29
+ });
30
+ }
package/src/verify-e2e.ts CHANGED
@@ -4,7 +4,8 @@
4
4
  // app: the suite runs as before and its browser-backed cases skip — or refuse under
5
5
  // `E2E_BROWSER_REQUIRED=1`.
6
6
 
7
- import { E2E_ROOT_ENV, findChrome } from '@ultimat3/testing';
7
+ import { findChrome } from '@ultimat3/scraping/cdp';
8
+ import { E2E_ROOT_ENV } from '@ultimat3/testing';
8
9
  import type { ExecResult } from './exec';
9
10
 
10
11
  /**
@@ -0,0 +1,86 @@
1
+ // The factory lint on the `unit` step: an app's `packages/db/factories.ts` exports `factories`, and
2
+ // every factory — bare and with each trait — must build a row its entity accepts and create one it
3
+ // stores (`@ultimat3/testing`'s `lintFactories`). No file is no factories: the step says nothing.
4
+
5
+ // why: a synchronous exists check decides whether the child is spawned at all.
6
+ import { existsSync } from 'node:fs';
7
+ // why: Bun exposes no path-join primitive.
8
+ import { join } from 'node:path';
9
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
10
+ import type { Infer } from '@ultimat3/schema';
11
+ import { parse, t } from '@ultimat3/schema';
12
+ import type { Runner } from './exec';
13
+ import type { Finding } from './output';
14
+
15
+ /** The one place an app's factories live. One convention, so the gate can find them. */
16
+ export const FACTORIES_FILE = 'packages/db/factories.ts';
17
+ /** The export that file makes: a `FactorySet` (`Record<name, factory>`). */
18
+ export const FACTORIES_EXPORT = 'factories';
19
+
20
+ const CODE = 'X_TEST_FACTORY_INVALID';
21
+
22
+ const findingSchema = t.object({
23
+ factory: t.string,
24
+ trait: t.nullable(t.string),
25
+ strategy: t.string,
26
+ code: t.string,
27
+ cause: t.string,
28
+ });
29
+ const reportSchema = t.array(findingSchema);
30
+ type LintFinding = Infer<typeof findingSchema>;
31
+
32
+ /**
33
+ * Run in a CHILD, from the app's root: the factories and `lintFactories` must share the app's own
34
+ * copy of `@ultimat3/testing` (the persister slot is module state), and the app's entities must not
35
+ * register into this process's registries. The last stdout line is the report.
36
+ */
37
+ const SCRIPT = `const mod = await import(\`\${process.cwd()}/${FACTORIES_FILE}\`);
38
+ const set = mod[${JSON.stringify(FACTORIES_EXPORT)}];
39
+ if (typeof set !== 'object' || set === null) {
40
+ console.log(JSON.stringify([{ factory: '*', trait: null, strategy: 'build', code: '${CODE}', cause: '${FACTORIES_FILE} exports no ${FACTORIES_EXPORT} object' }]));
41
+ } else {
42
+ const { lintFactories } = await import('@ultimat3/testing');
43
+ console.log(JSON.stringify(await lintFactories(set)));
44
+ }`;
45
+
46
+ const label = (finding: LintFinding): string =>
47
+ `${finding.factory}${finding.trait === null ? '' : `.with('${finding.trait}')`}.${finding.strategy}()`;
48
+
49
+ /** One finding per factory × trait × strategy, each naming what to edit. */
50
+ export const factoryFinding = (finding: LintFinding): Finding => ({
51
+ code: CODE,
52
+ cause: `${label(finding)} is refused: ${finding.code} — ${finding.cause}`,
53
+ // A code shape to paste into the file, opened by what to change — never a sentence (`fix-prose`).
54
+ fix:
55
+ finding.trait === null
56
+ ? `defaults: (n, ids) => ({ /* every column ${finding.factory}'s entity requires, valid */ }) // factory "${finding.factory}" in ${FACTORIES_FILE}`
57
+ : `traits: { ${JSON.stringify(finding.trait)}: { /* only columns the entity declares, valid */ } } // factory "${finding.factory}" in ${FACTORIES_FILE}`,
58
+ docs: ERROR_DOCS_URL,
59
+ at: FACTORIES_FILE,
60
+ });
61
+
62
+ /** The child's last stdout line, parsed — or one finding saying the file would not load. */
63
+ function readReport(stdout: string, stderr: string): readonly LintFinding[] {
64
+ const last = stdout.trim().split('\n').at(-1) ?? '';
65
+ try {
66
+ return parse(reportSchema, JSON.parse(last));
67
+ } catch {
68
+ const reason = stderr.trim().split('\n').slice(-3).join(' ') || 'no report was printed';
69
+ return [
70
+ {
71
+ factory: '*',
72
+ trait: null,
73
+ strategy: 'build',
74
+ code: CODE,
75
+ cause: `${FACTORIES_FILE} did not load: ${reason}`,
76
+ },
77
+ ];
78
+ }
79
+ }
80
+
81
+ /** The lint's findings for the app at `root`; none when it keeps no factories file. */
82
+ export async function factoryFindings(root: string, runner: Runner): Promise<readonly Finding[]> {
83
+ if (!existsSync(join(root, FACTORIES_FILE))) return [];
84
+ const result = await runner(['bun', '--eval', SCRIPT], { cwd: root });
85
+ return readReport(result.stdout, result.stderr).map(factoryFinding);
86
+ }
package/src/verify-run.ts CHANGED
@@ -79,17 +79,19 @@ export async function runVerify(
79
79
  }
80
80
  };
81
81
  const began = performance.now();
82
- // The static steps wait for the serial suites and then run BESIDE them — only when `live` is in
83
- // the list, so a one-step run (`--only`) and a list with no serial suite keep today's order.
84
- const overlapping = selected.some((step) => step.name === SERIAL_SUITES[0]);
82
+ // The static steps wait for the serial suites and then run BESIDE the first one listed: `live`
83
+ // in a whole gate, `eval` in CI's static part (the `live` shards may name no other step). A list
84
+ // with no serial suite — a one-step `--only` among them — keeps declared order.
85
85
  // The second serial lane (`verify-e2e-lane.ts`): `e2e` beside `live`, its children stripped of
86
- // every service URL, in a package monorepo only.
87
- const e2eLane = overlapping && e2eBesideLive(ctx);
88
- const beside = overlapping
89
- ? selected.filter(
90
- (step) => BESIDE_SERIAL_SUITES.has(step.name) || (e2eLane && step.name === 'e2e'),
91
- )
92
- : [];
86
+ // every service URL, in a package monorepo only — so only when `live` is listed.
87
+ const e2eLane = selected.some((step) => step.name === SERIAL_SUITES[0]) && e2eBesideLive(ctx);
88
+ const grouped = selected.filter(
89
+ (step) => BESIDE_SERIAL_SUITES.has(step.name) || (e2eLane && step.name === 'e2e'),
90
+ );
91
+ const anchor = selected.find(
92
+ (step) => SERIAL_SUITES.includes(step.name) && !grouped.includes(step),
93
+ );
94
+ const beside = anchor === undefined ? [] : grouped;
93
95
  let pending: Promise<void> | undefined;
94
96
  const join = async (): Promise<void> => {
95
97
  await pending;
@@ -105,7 +107,7 @@ export async function runVerify(
105
107
  const shared: VerifyContext = base;
106
108
  for (const step of selected) {
107
109
  if (beside.includes(step)) continue;
108
- if (step.name === SERIAL_SUITES[0]) {
110
+ if (step === anchor) {
109
111
  pending = Promise.all(
110
112
  beside.map((other) => run(other, other.name === 'e2e' ? besideLive(base) : base)),
111
113
  ).then(() => undefined);
@@ -3,6 +3,7 @@
3
3
  // implementation can live beside the code it checks without importing the list.
4
4
 
5
5
  import { ERROR_DOCS_URL } from '@ultimat3/core';
6
+ import type { AppTestScope } from './affected-tests';
6
7
  import type { CoverageMap } from './coverage-lcov';
7
8
  import type { ExecResult, Runner } from './exec';
8
9
  import { execOutput } from './exec';
@@ -70,6 +71,12 @@ export type VerifyStepName = (typeof VERIFY_STEP_NAMES)[number];
70
71
  */
71
72
  export type HostCheck = (root: string) => Promise<readonly Finding[]>;
72
73
 
74
+ /** `VerifyContext.tests`: `x test --affected`'s selection, and the suites that run whole anyway. */
75
+ export interface ChangedTestSelection {
76
+ readonly scope: AppTestScope;
77
+ readonly whole: readonly VerifyStepName[];
78
+ }
79
+
73
80
  export interface VerifyContext {
74
81
  readonly root: string;
75
82
  readonly runner: Runner;
@@ -114,6 +121,12 @@ export interface VerifyContext {
114
121
  * name is accepted for the callers that narrow to one (`scripts/verify.ts`).
115
122
  */
116
123
  readonly only?: VerifyStepName | readonly VerifyStepName[];
124
+ /**
125
+ * `x verify --changed`: each suite but `eval` and those in `whole` runs what `x test --affected`
126
+ * would (`narrowToApp` over `scope`: the closure's tests and every test the graph never read); a
127
+ * suite left nothing spawns nothing; the unit floor is not judged on a subset. Absent: every test.
128
+ */
129
+ readonly tests?: ChangedTestSelection;
117
130
  /**
118
131
  * Per-step deadlines in milliseconds that beat `x.verify.json`'s `stepTimeoutMs`, which beat the
119
132
  * step class's declared number (`verify-deadline.ts`). A step past its deadline fails by name
@@ -13,6 +13,7 @@ import { join } from 'node:path';
13
13
  import { APP_CONFIG_FILE } from '@ultimat3/core';
14
14
  import type { TestType } from '@ultimat3/testing';
15
15
  import { TEST_TYPES } from '@ultimat3/testing';
16
+ import { narrowToApp } from './affected-tests';
16
17
  import { checkEvalBaselines, checkEvalCoverage, checkEvalRecording } from './app-evals';
17
18
  import { judgeCoverage } from './coverage-floor';
18
19
  import { msg } from './messages';
@@ -27,11 +28,12 @@ import type { WorkerPlan } from './test-workers';
27
28
  import { availableCpus, SERIAL_TYPES, totalMemory, workerPlan } from './test-workers';
28
29
  import { runCovered } from './verify-coverage-run';
29
30
  import { withE2eApp } from './verify-e2e';
31
+ import { factoryFindings } from './verify-factories';
30
32
  import { readVerifyFloor } from './verify-floor';
31
33
  import type { MachinePace } from './verify-pace';
32
34
  import { DECLARED_PACE, defaultTimeoutArgs, pacedMs, paceEnv } from './verify-pace';
33
35
  import { shardFiles } from './verify-shard';
34
- import type { StepOutcome, VerifyContext, VerifyStep } from './verify-step';
36
+ import type { ChangedTestSelection, StepOutcome, VerifyContext, VerifyStep } from './verify-step';
35
37
  import { fromExec, fromFindings } from './verify-step';
36
38
  import { runParallel } from './verify-test-run';
37
39
 
@@ -150,6 +152,17 @@ const ignoreFlags = (patterns: readonly string[]): readonly string[] =>
150
152
  export const typeFiltersOf = (type: Exclude<TestType, 'unit'>): readonly string[] =>
151
153
  OWNERSHIP.filter(([owner]) => owner === type).map(([, filter]) => filter);
152
154
 
155
+ /**
156
+ * What an e2e test's path is, as globs: the e2e step's own substrings (`typeFiltersOf('e2e')`),
157
+ * each spelt as the glob matching the same paths. One definition, read three ways — the e2e step
158
+ * selects by the substrings, the unit step ignores these globs, and `scripts/coverage-gate.ts`
159
+ * leaves them out of a package's coverage: an e2e suite drives a built app through a browser and
160
+ * child processes no in-process lcov sees, and it already runs in its own gate step.
161
+ */
162
+ export const E2E_PATH_GLOBS: readonly string[] = typeFiltersOf('e2e').map((filter) =>
163
+ filter.endsWith('/') ? `**/*${filter}**` : `**/*${filter}*`,
164
+ );
165
+
153
166
  /**
154
167
  * An e2e test's own budget: a first navigation waits on `x dev` compiling the route and its island,
155
168
  * which bun's default 5 s does not cover — a timeout there reads as an app bug that is not one.
@@ -166,7 +179,7 @@ export const testStepCommand = (type: TestType, pace?: MachinePace): readonly st
166
179
  'bun',
167
180
  'test',
168
181
  ...defaultTimeoutArgs(pace),
169
- ...ignoreFlags([...NEVER_A_TEST, '**/e2e/**', `**/*.${TYPED_SUFFIXES}.test.*`]),
182
+ ...ignoreFlags([...NEVER_A_TEST, ...E2E_PATH_GLOBS, `**/*.${TYPED_SUFFIXES}.test.*`]),
170
183
  ]
171
184
  : [
172
185
  'bun',
@@ -245,9 +258,34 @@ const runSerial = async (
245
258
  };
246
259
  };
247
260
 
261
+ /**
262
+ * `--changed`'s selection, through `x test --affected`'s own rule (`narrowToApp`: a test the module
263
+ * graph never read is KEPT). Never for `eval` (its rules reach past its files) or a suite a doc
264
+ * selected (`whole`): those run every test.
265
+ */
266
+ const selectionFor = (ctx: VerifyContext, type: TestType): ChangedTestSelection | undefined =>
267
+ ctx.tests === undefined || type === 'eval' || ctx.tests.whole.includes(type)
268
+ ? undefined
269
+ : ctx.tests;
270
+
248
271
  const runType = async (ctx: VerifyContext, type: TestType): Promise<StepOutcome> => {
249
- if (isSerial(type) && ctx.shard === undefined) return runSerial(ctx, type);
250
- const discoveredFiles = await filesFor(ctx.root, type);
272
+ const selected = selectionFor(ctx, type);
273
+ if (isSerial(type) && ctx.shard === undefined && selected === undefined) {
274
+ return runSerial(ctx, type);
275
+ }
276
+ const all = await filesFor(ctx.root, type);
277
+ const discoveredFiles =
278
+ selected === undefined ? all : narrowToApp(all, ctx.root, selected.scope).kept;
279
+ if (selected !== undefined) {
280
+ // No `tests` on the outcome: nothing was spawned, which is not a suite that ran zero tests.
281
+ if (discoveredFiles.length === 0) return { ok: true, findings: [], workers: 0 };
282
+ if (isSerial(type))
283
+ return runSerial(
284
+ ctx,
285
+ type,
286
+ discoveredFiles.map((file) => file.path),
287
+ );
288
+ }
251
289
  // Under `--shard`, this job runs its slice and says which — `x verify merge` checks the slices.
252
290
  // An EMPTY slice is a pass with zero tests, never the serial fallback below (which would run
253
291
  // the whole type): the zero-tests floor is `merge`'s to apply, on the summed counts.
@@ -281,7 +319,8 @@ const runType = async (ctx: VerifyContext, type: TestType): Promise<StepOutcome>
281
319
  : files.length < plan.workers
282
320
  ? `${String(files.length)} of ${plan.reason}`
283
321
  : plan.reason;
284
- if (type === 'unit' && isApp(ctx.root)) {
322
+ // A subset cannot hold the whole tree's coverage floor: only a full unit run is judged.
323
+ if (type === 'unit' && isApp(ctx.root) && selected === undefined) {
285
324
  return coveredUnit(ctx, {
286
325
  files: files.map((file) => file.path),
287
326
  workers,
@@ -409,12 +448,25 @@ const evalStep: VerifyStep = {
409
448
  const summaryOf = (type: TypedTest): string =>
410
449
  Object.hasOwn(SUMMARIES, type) ? SUMMARIES[type] : `${type} tests`;
411
450
 
451
+ /**
452
+ * The unit suite, and an app's factory lint beside it (`verify-factories.ts`): a factory that
453
+ * builds a row its entity refuses is a failing test in every file that uses it, found here once.
454
+ * Under `--shard` only slice 1 lints, so `x verify merge` reports each finding once.
455
+ */
456
+ const unitStep = async (ctx: VerifyContext): Promise<StepOutcome> => {
457
+ const suite = await runType(ctx, 'unit');
458
+ if (!isApp(ctx.root) || (ctx.shard !== undefined && ctx.shard.index !== 1)) return suite;
459
+ const factories = await factoryFindings(ctx.root, ctx.runner);
460
+ if (factories.length === 0) return suite;
461
+ return { ...suite, ok: false, findings: [...factories, ...suite.findings] };
462
+ };
463
+
412
464
  const stepFor = (type: TestType): VerifyStep => {
413
465
  if (type === 'unit') {
414
466
  return {
415
467
  name: 'unit',
416
468
  summary: 'pure logic — no database, no network',
417
- run: (ctx) => runType(ctx, 'unit'),
469
+ run: unitStep,
418
470
  };
419
471
  }
420
472
  if (type === 'eval') return evalStep;
package/src/write-line.ts CHANGED
@@ -51,14 +51,21 @@ let dropped = 0;
51
51
  /**
52
52
  * Per fd, because fd 1 and fd 2 are two readers. `degraded`: the last line was dropped, so the next
53
53
  * gets one attempt. `torn`: it was dropped HALF-written, so the next line that arrives opens with
54
- * the newline the torn one never got — otherwise the two glue into one unparseable line.
54
+ * the newline the torn one never got — otherwise the two glue into one unparseable line. `gone`:
55
+ * the reader closed its end (`EPIPE`, `| head -c 10`) and nothing written to it can arrive again.
55
56
  */
56
- const pipes = new Map<number, { degraded: boolean; torn: boolean }>();
57
+ interface PipeState {
58
+ degraded: boolean;
59
+ torn: boolean;
60
+ gone: boolean;
61
+ }
62
+
63
+ const pipes = new Map<number, PipeState>();
57
64
 
58
- const pipeOf = (fd: number): { degraded: boolean; torn: boolean } => {
65
+ const pipeOf = (fd: number): PipeState => {
59
66
  let pipe = pipes.get(fd);
60
67
  if (pipe === undefined) {
61
- pipe = { degraded: false, torn: false };
68
+ pipe = { degraded: false, torn: false, gone: false };
62
69
  pipes.set(fd, pipe);
63
70
  }
64
71
  return pipe;
@@ -71,7 +78,7 @@ export const droppedLineCount = (): number => dropped;
71
78
 
72
79
  /**
73
80
  * Write every byte of `buffer` to `fd`, or drop it after `EAGAIN_ATTEMPTS` stalls in a row — one
74
- * stall while the fd is degraded. Returns whether it all arrived. A write of zero bytes is a stall
81
+ * stall while the fd is degraded — or abandon it, and every later line, once the reader is gone. Returns whether it all arrived. A write of zero bytes is a stall
75
82
  * too, so no path spins.
76
83
  */
77
84
  export function writeAll(
@@ -81,6 +88,7 @@ export function writeAll(
81
88
  sleep: (ms: number) => void = Bun.sleepSync,
82
89
  ): boolean {
83
90
  const pipe = pipeOf(fd);
91
+ if (pipe.gone) return false;
84
92
  const prefix = pipe.torn ? 1 : 0;
85
93
  const bytes = prefix === 0 ? buffer : Buffer.concat([Uint8Array.of(NEWLINE), buffer]);
86
94
  let written = 0;
@@ -93,7 +101,14 @@ export function writeAll(
93
101
  // `stringField`, never a cast plus a property read — the rule `metrics-endpoint.ts` states
94
102
  // and `caught-value-reads.test.ts` enforces. Here it is also the difference between
95
103
  // rethrowing and retrying: a `code` that cannot be read must not read as `EAGAIN`.
96
- if (stringField(cause, 'code') !== 'EAGAIN') throw cause;
104
+ const code = stringField(cause, 'code');
105
+ // The reader closed its end: its choice, not the command's failure. Stop writing to it and
106
+ // let the command exit with the code it decided — never a stack trace and exit 1.
107
+ if (code === 'EPIPE') {
108
+ pipe.gone = true;
109
+ return false;
110
+ }
111
+ if (code !== 'EAGAIN') throw cause;
97
112
  }
98
113
  if (progress > 0) {
99
114
  written += progress;