@ultimat3/cli 30.9.0 → 31.1.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 (215) hide show
  1. package/CLAUDE.md +80 -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-base.ts +51 -0
  6. package/src/affected.ts +34 -11
  7. package/src/app-boundaries.ts +88 -9
  8. package/src/app-load-async.ts +133 -0
  9. package/src/app-load-batch.ts +203 -0
  10. package/src/app-load-prebuilt.ts +147 -0
  11. package/src/app-load-register.ts +175 -0
  12. package/src/app-load.ts +143 -175
  13. package/src/app-loader-imports.ts +31 -0
  14. package/src/app-root.ts +13 -0
  15. package/src/app-runtime.ts +5 -1
  16. package/src/boundary-findings.ts +12 -0
  17. package/src/browser-launcher-port.ts +3 -7
  18. package/src/browser-launcher.ts +1 -1
  19. package/src/budgets-scan.ts +8 -0
  20. package/src/budgets.ts +10 -1
  21. package/src/build-registry-background.ts +59 -0
  22. package/src/build-registry.ts +207 -0
  23. package/src/cdp-shot-clock.ts +3 -11
  24. package/src/cdp-shot-driver.ts +3 -2
  25. package/src/cdp-shot-element.ts +3 -2
  26. package/src/cdp-shot-page.ts +2 -2
  27. package/src/cdp-shot-watch.ts +4 -3
  28. package/src/ci-log.ts +76 -13
  29. package/src/cmd-affected-spec.ts +7 -3
  30. package/src/cmd-affected.ts +91 -77
  31. package/src/cmd-auth.ts +3 -3
  32. package/src/cmd-ci.ts +6 -3
  33. package/src/cmd-db-recount.ts +15 -0
  34. package/src/cmd-drill.ts +10 -6
  35. package/src/cmd-exercise.ts +2 -1
  36. package/src/cmd-generate-spec.ts +6 -0
  37. package/src/cmd-generate.ts +22 -4
  38. package/src/cmd-mail.ts +1 -1
  39. package/src/cmd-pr-spec.ts +1 -1
  40. package/src/cmd-pr.ts +72 -1
  41. package/src/cmd-routes.ts +2 -2
  42. package/src/cmd-secrets-spec.ts +4 -1
  43. package/src/cmd-shot.ts +14 -262
  44. package/src/cmd-test-spec.ts +2 -2
  45. package/src/cmd-verify-spec.ts +21 -1
  46. package/src/cmd-verify.ts +16 -4
  47. package/src/coverage-source.ts +4 -1
  48. package/src/db-diagnostics.ts +8 -1
  49. package/src/dev-boot.ts +29 -15
  50. package/src/dev-dashboard-invalidations.ts +43 -0
  51. package/src/dev-dashboard.ts +13 -16
  52. package/src/dev-n-plus-one.ts +7 -3
  53. package/src/dev-rebuild.ts +2 -1
  54. package/src/dev-route-table.ts +1 -1
  55. package/src/dev-traces.ts +16 -15
  56. package/src/document-options.ts +12 -1
  57. package/src/drift-store.ts +55 -0
  58. package/src/error-catalog.ts +8 -3
  59. package/src/error-codes-boundary.ts +32 -0
  60. package/src/error-codes-package.ts +38 -0
  61. package/src/error-codes.ts +28 -40
  62. package/src/errors.ts +17 -7
  63. package/src/exercise-database.ts +13 -1
  64. package/src/exercise-findings.ts +36 -18
  65. package/src/exercise-services.ts +84 -0
  66. package/src/exercise-subject.ts +38 -13
  67. package/src/failure-capture-boot.ts +9 -5
  68. package/src/framework-schema.ts +5 -5
  69. package/src/generate-exercise.ts +1 -1
  70. package/src/generate-files.ts +27 -7
  71. package/src/generate-kinds.ts +5 -0
  72. package/src/generate-refresh.ts +53 -0
  73. package/src/generate-workspace.ts +169 -0
  74. package/src/generate-write.ts +8 -2
  75. package/src/hold.ts +19 -8
  76. package/src/image-prepare.ts +6 -2
  77. package/src/index.ts +5 -20
  78. package/src/island-bundle.ts +7 -3
  79. package/src/island-capture.ts +2 -2
  80. package/src/island-harness.ts +1 -1
  81. package/src/job-registration.ts +43 -6
  82. package/src/jobs-driver.ts +4 -5
  83. package/src/mcp-errors.ts +20 -4
  84. package/src/mcp-host.ts +5 -1
  85. package/src/mcp-ui-interact.ts +3 -0
  86. package/src/messages-gate.ts +10 -0
  87. package/src/new-shapes-generate.ts +1 -1
  88. package/src/otlp-export.ts +94 -29
  89. package/src/output.ts +24 -10
  90. package/src/page-sync.ts +3 -1
  91. package/src/pr-activity.ts +150 -0
  92. package/src/pr-bots.ts +109 -0
  93. package/src/pr-threads.ts +7 -2
  94. package/src/role-load.ts +17 -11
  95. package/src/role-start.ts +5 -4
  96. package/src/role-sync.ts +7 -8
  97. package/src/route-islands-preload.ts +46 -0
  98. package/src/route-islands.ts +6 -2
  99. package/src/runtime-admin.ts +5 -1
  100. package/src/runtime-bindings.ts +25 -19
  101. package/src/runtime-boot-ports.ts +66 -0
  102. package/src/runtime-bus.ts +29 -5
  103. package/src/runtime-cache-bus.ts +53 -0
  104. package/src/runtime-cache.ts +43 -13
  105. package/src/runtime-isr-outcome.ts +5 -4
  106. package/src/runtime-jobs.ts +2 -2
  107. package/src/runtime-keys.ts +37 -0
  108. package/src/runtime-overrides.ts +148 -42
  109. package/src/runtime-port-bindings-queue.ts +36 -0
  110. package/src/runtime-port-bindings.ts +117 -0
  111. package/src/runtime-ports.ts +164 -0
  112. package/src/runtime-purge.ts +41 -28
  113. package/src/runtime-push.ts +7 -3
  114. package/src/runtime-queue.ts +70 -55
  115. package/src/runtime-realtime.ts +5 -5
  116. package/src/runtime-render-document.ts +4 -1
  117. package/src/runtime-services.ts +110 -158
  118. package/src/runtime-storage-boot.ts +111 -0
  119. package/src/runtime-storage-upload.ts +9 -7
  120. package/src/runtime-storage.ts +7 -1
  121. package/src/serve-boot.ts +8 -4
  122. package/src/serve-entry.ts +3 -0
  123. package/src/serve-env.ts +47 -14
  124. package/src/serve-prebuilt-paths.ts +3 -0
  125. package/src/serve-prebuilt.ts +15 -4
  126. package/src/serve.ts +2 -2
  127. package/src/shot-gpu.ts +61 -0
  128. package/src/shot-route.ts +95 -0
  129. package/src/shot-run.ts +189 -0
  130. package/src/shot-verdict.ts +5 -0
  131. package/src/static-cards.ts +3 -2
  132. package/src/static-report.ts +2 -2
  133. package/src/style-bundle.ts +1 -1
  134. package/src/sync-authenticator.ts +17 -18
  135. package/src/templates/action-tests.ts +4 -4
  136. package/src/templates/backfill.ts +5 -8
  137. package/src/templates/entity.ts +3 -0
  138. package/src/templates/github/ci.yml.ts +3 -1
  139. package/src/templates/github/dependabot.yml.ts +73 -0
  140. package/src/templates/job.ts +13 -22
  141. package/src/templates/naming.ts +20 -1
  142. package/src/templates/pinned/docker-compose.yml +1 -1
  143. package/src/templates/query.ts +7 -8
  144. package/src/templates/route.ts +5 -3
  145. package/src/templates/scaffold-api.ts +1 -1
  146. package/src/templates/scaffold-auth.ts +5 -3
  147. package/src/templates/scaffold-claude-commands.ts +6 -3
  148. package/src/templates/scaffold-claude.ts +4 -4
  149. package/src/templates/scaffold-container-compose.ts +2 -4
  150. package/src/templates/scaffold-domain-package.ts +1 -1
  151. package/src/templates/scaffold-entries.ts +6 -1
  152. package/src/templates/scaffold-helm-fences.ts +3 -2
  153. package/src/templates/scaffold-helm.ts +35 -6
  154. package/src/templates/scaffold-repo.ts +47 -135
  155. package/src/templates/scaffold-runtime-ports.ts +62 -0
  156. package/src/templates/scaffold-verify-floor.ts +97 -0
  157. package/src/templates/shapes/overlay.ts +1 -1
  158. package/src/templates/sign-in-oidc.ts +5 -3
  159. package/src/templates/sign-in-shared.ts +28 -10
  160. package/src/templates/workspace.ts +75 -0
  161. package/src/test-ignores.ts +5 -2
  162. package/src/test-select.ts +4 -1
  163. package/src/tsconfig-aliases.ts +85 -0
  164. package/src/upgrade-gate.ts +30 -5
  165. package/src/upgrade-report.ts +7 -1
  166. package/src/verify-changed-facts.ts +53 -0
  167. package/src/verify-changed-scope.ts +162 -0
  168. package/src/verify-changed.ts +174 -0
  169. package/src/verify-checks.ts +33 -19
  170. package/src/verify-drift-owner.ts +30 -0
  171. package/src/verify-e2e.ts +2 -1
  172. package/src/verify-factories.ts +86 -0
  173. package/src/verify-run.ts +13 -11
  174. package/src/verify-step.ts +13 -0
  175. package/src/verify-tests.ts +58 -6
  176. package/src/workspace-external-deps.ts +164 -0
  177. package/src/write-line.ts +21 -6
  178. package/wiki/Actions.md +2 -2
  179. package/wiki/Adapters.md +400 -0
  180. package/wiki/Admin-Dashboard.md +1 -1
  181. package/wiki/Agents.md +9 -9
  182. package/wiki/Auth.md +78 -2
  183. package/wiki/Building-Your-Own-Base.md +1 -1
  184. package/wiki/CLI-Reference.md +45 -14
  185. package/wiki/Caching-And-Invalidation.md +17 -5
  186. package/wiki/Compared.md +8 -2
  187. package/wiki/Configuration.md +14 -14
  188. package/wiki/Deployment.md +28 -1
  189. package/wiki/Entities-And-Migrations.md +47 -1
  190. package/wiki/FAQ.md +8 -2
  191. package/wiki/Feature-Flags.md +1 -1
  192. package/wiki/Home.md +3 -2
  193. package/wiki/Jobs-And-Workflows.md +107 -6
  194. package/wiki/Known-Gaps.md +4 -3
  195. package/wiki/MCP-And-AI.md +18 -4
  196. package/wiki/Mail.md +14 -5
  197. package/wiki/Migrations-And-Backfills.md +29 -4
  198. package/wiki/Money.md +2 -0
  199. package/wiki/N-Plus-One-Detection.md +24 -22
  200. package/wiki/Notify.md +28 -4
  201. package/wiki/Observability.md +121 -15
  202. package/wiki/Queries-And-Live-Queries.md +2 -2
  203. package/wiki/Realtime.md +9 -4
  204. package/wiki/Routes-And-Render-Modes.md +5 -0
  205. package/wiki/Scraping.md +57 -11
  206. package/wiki/Shapes.md +2 -2
  207. package/wiki/Stability.md +7 -5
  208. package/wiki/Storage-And-Uploads.md +56 -4
  209. package/wiki/Testing.md +65 -52
  210. package/wiki/Troubleshooting.md +1 -1
  211. package/wiki/Tutorial-01-First-App.md +1 -1
  212. package/wiki/Tutorial-04-Jobs-And-Realtime.md +1 -1
  213. package/wiki/Tutorial-05-Deploy-Free.md +1 -1
  214. package/wiki/Tutorial-06-Growing-Up.md +8 -8
  215. package/wiki/Upgrading.md +136 -5
@@ -0,0 +1,85 @@
1
+ // The package names a tsconfig's `compilerOptions.paths` answers for, read through its `extends`
2
+ // chain. An alias resolves through the compiler and Bun's own tsconfig reading, never through
3
+ // `node_modules`, so a rule asking "is this import declared?" must not treat one as a package.
4
+
5
+ import { dirname, isAbsolute, join } from 'node:path'; // why: Bun exposes no path primitives.
6
+ import { packageOfSpecifier } from './workspace-graph';
7
+
8
+ type JsonObject = Readonly<Record<string, unknown>>;
9
+
10
+ const asRecord = (value: unknown): JsonObject | undefined =>
11
+ typeof value === 'object' && value !== null && !Array.isArray(value)
12
+ ? (value as JsonObject)
13
+ : undefined;
14
+
15
+ /** JSONC: a tsconfig may carry comments and trailing commas. Absent or unreadable says nothing. */
16
+ async function readTsconfig(path: string): Promise<JsonObject | undefined> {
17
+ const file = Bun.file(path);
18
+ if (!(await file.exists())) return undefined;
19
+ try {
20
+ return asRecord(Bun.JSONC.parse(await file.text()));
21
+ } catch {
22
+ return undefined;
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Where one `extends` entry points. Relative and absolute paths as TypeScript reads them (`.json`
28
+ * appended when absent); a package specifier through Bun's resolver, trying the package's own
29
+ * `tsconfig.json` first as TypeScript does. A specifier that does not resolve says nothing.
30
+ */
31
+ function extendedPath(entry: string, from: string): string | undefined {
32
+ if (entry.startsWith('.') || isAbsolute(entry)) {
33
+ const path = isAbsolute(entry) ? entry : join(from, entry);
34
+ return path.endsWith('.json') ? path : `${path}.json`;
35
+ }
36
+ const candidates = entry.endsWith('.json') ? [entry] : [`${entry}/tsconfig.json`, entry];
37
+ for (const candidate of candidates) {
38
+ try {
39
+ return Bun.resolveSync(candidate, from);
40
+ } catch {
41
+ // The next spelling, then nothing.
42
+ }
43
+ }
44
+ return undefined;
45
+ }
46
+
47
+ /**
48
+ * The effective `paths` of the tsconfig at `path`: its own when it declares any, else the last
49
+ * `extends` entry's that does — TypeScript replaces `paths` wholesale, never merges it. `seen`
50
+ * stops a cycle, which TypeScript refuses and this must not loop on.
51
+ */
52
+ async function effectivePaths(
53
+ path: string,
54
+ seen: Set<string> = new Set(),
55
+ ): Promise<JsonObject | undefined> {
56
+ if (seen.has(path)) return undefined;
57
+ seen.add(path);
58
+ const config = await readTsconfig(path);
59
+ if (config === undefined) return undefined;
60
+ const own = asRecord(asRecord(config['compilerOptions'])?.['paths']);
61
+ if (own !== undefined) return own;
62
+ const extended = config['extends'];
63
+ const entries =
64
+ typeof extended === 'string' ? [extended] : Array.isArray(extended) ? extended : [];
65
+ let inherited: JsonObject | undefined;
66
+ for (const entry of entries) {
67
+ if (typeof entry !== 'string') continue;
68
+ const target = extendedPath(entry, dirname(path));
69
+ const paths = target === undefined ? undefined : await effectivePaths(target, seen);
70
+ if (paths !== undefined) inherited = paths;
71
+ }
72
+ return inherited;
73
+ }
74
+
75
+ /** Every package name the `tsconfig.json` in each of `dirs` aliases, unioned. */
76
+ export async function tsconfigAliases(dirs: readonly string[]): Promise<ReadonlySet<string>> {
77
+ const aliases = new Set<string>();
78
+ for (const dir of dirs) {
79
+ for (const key of Object.keys((await effectivePaths(join(dir, 'tsconfig.json'))) ?? {})) {
80
+ const name = packageOfSpecifier(key.replace(/\/?\*.*$/, ''));
81
+ if (name !== undefined) aliases.add(name);
82
+ }
83
+ }
84
+ return aliases;
85
+ }
@@ -1,5 +1,5 @@
1
- // A hop's gate, run by the CLI the hop just installed: `x manifest`, `x doctor --json`, `x verify
2
- // --json`. Never in this process, because the installed CLI is the one that knows the installed
1
+ // A hop's gate, run by the CLI the hop just installed: `x manifest`, `x doctor --json`, `x exercise
2
+ // --json`, `x verify --json`. Never in this process, because the installed CLI is the one that knows the installed
3
3
  // framework (`local-cli.ts`), and it may be many majors older than this one: each answer is read as
4
4
  // a foreign document, and one that will not parse is a finding, never a green.
5
5
 
@@ -84,9 +84,21 @@ export interface HopGuards {
84
84
  readonly differs: readonly { readonly name: string; readonly refresh: string }[];
85
85
  }
86
86
 
87
+ /**
88
+ * `x exercise`'s findings, listed before the gate: an upgrade spent its commits feeding the
89
+ * exercise one red gate at a time, and each of these fixes pastes as written.
90
+ */
91
+ export interface HopExercise {
92
+ /** False when the hop's CLI answered no exercise document (none, or one predating it): unknown. */
93
+ readonly reported: boolean;
94
+ readonly ok: boolean;
95
+ readonly findings: readonly GateFinding[];
96
+ }
97
+
87
98
  export interface HopGate {
88
99
  readonly manifest: { readonly ok: boolean; readonly findings: readonly GateFinding[] };
89
100
  readonly guards: HopGuards;
101
+ readonly exercise: HopExercise;
90
102
  readonly verify: {
91
103
  readonly ok: boolean;
92
104
  readonly summary: string;
@@ -164,6 +176,17 @@ const readManifest = (result: ExecResult): HopGate['manifest'] => {
164
176
  return { ok: result.ok, findings: flatten(document) };
165
177
  };
166
178
 
179
+ /** Read like the manifest, except that no document is `reported: false`, never a finding. */
180
+ const readExercise = (result: ExecResult): HopExercise => {
181
+ const parsed = MANIFEST.safeParse(documentIn(result.stdout));
182
+ if (parsed.issues !== undefined) return { reported: false, ok: false, findings: [] };
183
+ const document = parsed.value as {
184
+ readonly ok: boolean;
185
+ readonly findings?: readonly RawFinding[];
186
+ };
187
+ return { reported: true, ok: result.ok && document.ok, findings: flatten(document) };
188
+ };
189
+
167
190
  /** A doctor that exits red is normal (a port, an env key); only its listing is read here. */
168
191
  const readGuards = (result: ExecResult): HopGuards => {
169
192
  const parsed = DOCTOR.safeParse(documentIn(result.stdout));
@@ -173,11 +196,11 @@ const readGuards = (result: ExecResult): HopGuards => {
173
196
  return { reported: true, missing: guards.missing ?? [], differs: guards.differs ?? [] };
174
197
  };
175
198
 
176
- /** The three, in order, each told apart by `onStage` so a long gate is not a long silence. */
199
+ /** The four, in order, each told apart by `onStage` so a long gate is not a long silence. */
177
200
  export async function runHopGate(input: {
178
201
  readonly runner: Runner;
179
202
  readonly root: string;
180
- readonly onStage: (stage: 'manifest' | 'doctor' | 'verify') => void;
203
+ readonly onStage: (stage: 'manifest' | 'doctor' | 'exercise' | 'verify') => void;
181
204
  }): Promise<HopGate> {
182
205
  const { runner, root, onStage } = input;
183
206
  const installed = (args: readonly string[]): Promise<ExecResult> =>
@@ -186,9 +209,11 @@ export async function runHopGate(input: {
186
209
  const manifest = readManifest(await installed(['manifest', '--json']));
187
210
  onStage('doctor');
188
211
  const guards = readGuards(await installed(['doctor', '--json']));
212
+ onStage('exercise');
213
+ const exercise = readExercise(await installed(['exercise', '--json']));
189
214
  onStage('verify');
190
215
  const verify = readVerify(await installed(['verify', '--json']));
191
- return { manifest, guards, verify };
216
+ return { manifest, guards, exercise, verify };
192
217
  }
193
218
 
194
219
  /** What a repository with no app can still be asked, in the order an author would run them. */
@@ -88,7 +88,12 @@ export const humanLines = (input: {
88
88
  ...(gate?.guards.differs ?? []).map((guard) =>
89
89
  msg('cli.upgrade.guard', { fix: guard.refresh }),
90
90
  ),
91
- ...findingLines([...(gate?.manifest.findings ?? []), ...(gate?.verify.findings ?? [])]),
91
+ // The exercise's own list first: every fix it has, before the gate's verdict on the same tree.
92
+ ...findingLines([
93
+ ...(gate?.exercise.findings ?? []),
94
+ ...(gate?.manifest.findings ?? []),
95
+ ...(gate?.verify.findings ?? []),
96
+ ]),
92
97
  ...scripts
93
98
  .filter((script) => script.ok === false)
94
99
  .map((script) => msg('cli.upgrade.scriptRed', { name: script.name })),
@@ -133,6 +138,7 @@ export const report = (input: {
133
138
  agentsMd: input.agentsMd ?? null,
134
139
  guards: gate?.guards ?? null,
135
140
  manifest: gate?.manifest ?? null,
141
+ exercise: gate?.exercise ?? null,
136
142
  verify: gate?.verify ?? null,
137
143
  scripts,
138
144
  then,
@@ -0,0 +1,53 @@
1
+ // `x verify --changed`, the disk half: which app files the `drift` step's inputs reach by import,
2
+ // and which TypeScript files exist now. Read once, handed to the pure planner (`verify-changed.ts`).
3
+ // Seeds are read off the import itself — a file importing `@ultimat3/entity` declares a table
4
+ // however it is named — never off a filename convention a hand-written entity can miss.
5
+
6
+ // why: Bun ships no path API; files are read from the app root with the host's separator.
7
+ import { join } from 'node:path';
8
+ import { appSourceFiles, fileImports } from './app-module-graph';
9
+ import { isTest } from './source-files';
10
+ import type { ChangedFacts } from './verify-changed';
11
+
12
+ /** A runtime OR type import of the entity package, in any of its subpaths. */
13
+ const ENTITY_IMPORT = /['"]@ultimat3\/entity(?:\/[^'"]*)?['"]/;
14
+
15
+ interface Scanned {
16
+ readonly path: string;
17
+ readonly imports: readonly string[];
18
+ readonly opaque: boolean;
19
+ readonly seed: boolean;
20
+ }
21
+
22
+ /** Pure: the closure over already-scanned files, so the rule is testable without a tree. */
23
+ export function driftReachOf(files: readonly Scanned[]): ReadonlySet<string> | 'everything' {
24
+ const byPath = new Map(files.map((file) => [file.path, file]));
25
+ const reached = new Set<string>();
26
+ const queue = files.filter((file) => file.seed).map((file) => file.path);
27
+ for (let at = queue.shift(); at !== undefined; at = queue.shift()) {
28
+ if (reached.has(at)) continue;
29
+ reached.add(at);
30
+ const file = byPath.get(at);
31
+ // A seed that computes an import can reach any file: nothing is provably outside drift.
32
+ if (file?.opaque === true) return 'everything';
33
+ for (const target of file?.imports ?? []) if (!reached.has(target)) queue.push(target);
34
+ }
35
+ return reached;
36
+ }
37
+
38
+ export async function readChangedFacts(root: string): Promise<ChangedFacts> {
39
+ const paths = await appSourceFiles(root);
40
+ const scanned: Scanned[] = [];
41
+ for (const path of paths) {
42
+ if (isTest(path)) continue;
43
+ const source = await Bun.file(join(root, path)).text();
44
+ const found = fileImports(root, path, source);
45
+ scanned.push({
46
+ path,
47
+ imports: found.imports,
48
+ opaque: found.opaque,
49
+ seed: path.startsWith('packages/db/') || ENTITY_IMPORT.test(source),
50
+ });
51
+ }
52
+ return { driftReach: driftReachOf(scanned), known: new Set(paths) };
53
+ }
@@ -0,0 +1,162 @@
1
+ // `x verify --changed`, resolved: the diff (`affected.ts`'s one reader of `--base`/`--dirty`, so
2
+ // `x affected` and this flag can never measure a change against two different bases), re-rooted
3
+ // onto the app, then planned. What `cmd-verify.ts` narrows the run with, and what `--json` reports.
4
+
5
+ // why: Bun ships no path API; git prints paths from the checkout root, the planner reads app-relative.
6
+ import { join, relative, resolve } from 'node:path';
7
+ import { renderFixShellArg } from '@ultimat3/core';
8
+ import type { AffectedSelection } from './affected';
9
+ import { changedFiles, gitRoot, readAffectedSelection, resolveSelection } from './affected';
10
+ import type { AppTestScope } from './affected-tests';
11
+ import { appTestScope, narrowToApp } from './affected-tests';
12
+ import { BadFlagError } from './errors';
13
+ import type { Runner } from './exec';
14
+ import type { CommandResult, JsonValue } from './output';
15
+ import type { ParsedArgs } from './parse';
16
+ import { flagBool, flagString } from './parse';
17
+ import { discoverTests } from './test-select';
18
+ import type { ChangedFacts, ChangedStepPlan } from './verify-changed';
19
+ import { narrowSuites, planChangedSteps } from './verify-changed';
20
+ import { readChangedFacts } from './verify-changed-facts';
21
+ import type { ChangedTestSelection, VerifyStepName } from './verify-step';
22
+
23
+ /** Every test file a suite would discover, app-root-relative. */
24
+ const discoverAll = async (root: string): Promise<readonly string[]> =>
25
+ (await discoverTests(root)).map((file) => file.path);
26
+
27
+ export interface ChangedScope {
28
+ readonly selection: AffectedSelection;
29
+ /** Suites already narrowed to `tests.kept`. */
30
+ readonly plan: ChangedStepPlan;
31
+ /**
32
+ * What each suite runs — `undefined` when a changed file forced every test (or no app). `kept`
33
+ * is `x test --affected`'s answer: the closure's tests and every test the graph never read.
34
+ */
35
+ readonly tests: ChangedTestRun | undefined;
36
+ /** The changed files that forced every test, when one did. */
37
+ readonly forcing: readonly string[];
38
+ }
39
+
40
+ /** `VerifyContext.tests`, plus the files it keeps, for `--json`. */
41
+ export interface ChangedTestRun extends ChangedTestSelection {
42
+ readonly kept: readonly string[];
43
+ }
44
+
45
+ const toPosix = (path: string): string => path.split('\\').join('/');
46
+
47
+ /** Checkout-relative paths onto the app root: a file outside the app comes back `../…`. */
48
+ export const reRoot = (checkout: string, app: string, paths: readonly string[]): string[] =>
49
+ paths.map((path) => toPosix(relative(resolve(app), join(resolve(checkout), path))));
50
+
51
+ export async function changedScope(options: {
52
+ readonly runner: Runner;
53
+ readonly root: string;
54
+ readonly args: ParsedArgs;
55
+ /** Injected by tests; the real read walks the app once. */
56
+ readonly facts?: (root: string) => Promise<ChangedFacts>;
57
+ /** Injected by tests; the real one is `x test --affected`'s selection. */
58
+ readonly tests?: (
59
+ root: string,
60
+ checkout: string,
61
+ changed: readonly string[],
62
+ ) => Promise<AppTestScope | undefined>;
63
+ /** Injected by tests; the real one is the suites' own discovery, every type. */
64
+ readonly discover?: (root: string) => Promise<readonly string[]>;
65
+ }): Promise<ChangedScope> {
66
+ const request = readAffectedSelection(options.args, 'verify');
67
+ const checkout = await gitRoot(options.runner, options.root, 'verify');
68
+ const selection = await resolveSelection(options.runner, checkout, request);
69
+ const files = await changedFiles(options.runner, {
70
+ cwd: checkout,
71
+ command: 'verify',
72
+ selection,
73
+ });
74
+ const facts = await (options.facts ?? readChangedFacts)(options.root);
75
+ const selected = await (options.tests ?? appTestScope)(options.root, checkout, files);
76
+ const plan = planChangedSteps(reRoot(checkout, options.root, files), facts);
77
+ if (selected === undefined || selected.all) {
78
+ return { selection, plan, tests: undefined, forcing: selected?.forcing ?? [] };
79
+ }
80
+ const discovered = await (options.discover ?? discoverAll)(options.root);
81
+ const kept = narrowToApp(
82
+ discovered.map((path) => ({ path })),
83
+ options.root,
84
+ selected,
85
+ ).kept.map((file) => file.path);
86
+ const narrowed = narrowSuites(plan, kept);
87
+ return {
88
+ selection,
89
+ plan: narrowed.plan,
90
+ tests: { scope: selected, whole: narrowed.whole, kept },
91
+ forcing: [],
92
+ };
93
+ }
94
+
95
+ /** `data.changed`: the base, every file with its rule, and every step with the files that chose it. */
96
+ export const changedScopeJson = (scope: ChangedScope): JsonValue => ({
97
+ base: scope.selection.base,
98
+ dirty: scope.selection.dirty,
99
+ files: scope.plan.files.map((file) => ({ path: file.path, rule: file.rule })),
100
+ steps: scope.plan.steps.map((step) => ({ name: step.name, files: [...step.files] })),
101
+ tests:
102
+ scope.tests === undefined
103
+ ? { all: true, forcing: [...scope.forcing] }
104
+ : { all: false, files: [...scope.tests.kept], whole: [...scope.tests.whole] },
105
+ });
106
+
107
+ /** How many files a human line names before it says `(+N)`. */
108
+ const SHOWN = 3;
109
+
110
+ /** One human line per selected step: `drift ← packages/db/migrations/1.sql (+2)`. */
111
+ export const changedScopeLines = (scope: ChangedScope): readonly string[] =>
112
+ scope.plan.steps.map((step) => {
113
+ const shown = step.files.slice(0, SHOWN).join(', ');
114
+ const more = step.files.length > SHOWN ? ` (+${step.files.length - SHOWN})` : '';
115
+ return ` ${step.name.padEnd(14)}← ${shown}${more}`;
116
+ });
117
+
118
+ /**
119
+ * Whether this run is `--changed`. Refused beside `--only` — two narrowings, and whichever won
120
+ * the other would be silently ignored — and `--base`/`--dirty` without it, which narrow nothing.
121
+ */
122
+ export function readChangedRun(
123
+ args: ParsedArgs,
124
+ only: readonly VerifyStepName[] | undefined,
125
+ ): boolean {
126
+ const changed = flagBool(args, 'changed');
127
+ if (changed && only !== undefined) {
128
+ throw new BadFlagError({
129
+ flag: 'changed',
130
+ command: 'verify',
131
+ reason: '--changed derives the step list from the diff and --only names one: pick one',
132
+ fix: 'x verify --changed --json',
133
+ });
134
+ }
135
+ if (!changed) {
136
+ const stray =
137
+ flagString(args, 'base') !== undefined
138
+ ? 'base'
139
+ : flagBool(args, 'dirty')
140
+ ? 'dirty'
141
+ : undefined;
142
+ if (stray !== undefined) {
143
+ throw new BadFlagError({
144
+ flag: stray,
145
+ command: 'verify',
146
+ reason: `--${stray} scopes the diff --changed reads, and does nothing without it`,
147
+ fix:
148
+ stray === 'base'
149
+ ? `x verify --changed --base ${renderFixShellArg(flagString(args, 'base'), '<ref>')} --json`
150
+ : 'x verify --changed --dirty --json',
151
+ });
152
+ }
153
+ }
154
+ return changed;
155
+ }
156
+
157
+ /** `data.changed` and one line per chosen step, after whatever the run already reported. */
158
+ export const withChangedData = (result: CommandResult, scope: ChangedScope): CommandResult => ({
159
+ ...result,
160
+ lines: [...changedScopeLines(scope), ...(result.lines ?? [])],
161
+ data: { ...((result.data ?? {}) as Record<string, JsonValue>), changed: changedScopeJson(scope) },
162
+ });
@@ -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';
@@ -59,6 +62,7 @@ import { fromExec, fromFindings, hostFindings } from './verify-step';
59
62
  import { TEST_STEPS } from './verify-tests';
60
63
  import { typecheckArgs } from './verify-typecheck';
61
64
  import { checkPackageShape, fileSizeReport, hasWorkspacePackages } from './workspace-checks';
65
+ import { checkExternalDependencies } from './workspace-external-deps';
62
66
  import { checkWorkspaceDependencies } from './workspace-graph';
63
67
 
64
68
  /** The one file that makes the `roadmap` step answerable, and therefore what `applies` reads. */
@@ -155,6 +159,7 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
155
159
  fromFindings([
156
160
  ...(await checkPackageShape(ctx.root)),
157
161
  ...(await checkWorkspaceDependencies(ctx.root)),
162
+ ...(await checkExternalDependencies(ctx.root)),
158
163
  ]),
159
164
  },
160
165
  {
@@ -201,26 +206,35 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
201
206
  // step's own question — do the committed migrations still describe what the app is doing to its
202
207
  // schema? — off the same directory, in the same pass, with no database either.
203
208
  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
209
+ run: async (ctx) => {
210
+ // Loaded first: the drivers the app's modules construct are what decide (`drift-store.ts`).
211
+ await loadApp(ctx.root);
212
+ // A store owning its own schema skips the five migration rails, never the client one.
213
+ return driftOutcome(ctx.root, {
214
+ schema: async () => [
215
+ ...(await checkMigrationDrift(ctx.root)),
216
+ ...(await checkDestructiveMigrations(ctx.root)),
217
+ // The third rail, and the one the other two cannot see: a hand-written statement is
218
+ // recorded by no snapshot and hashed by no source, so both halves above are green over SQL
219
+ // a squash silently drops. Same directory, same reader, no database — this step's own
220
+ // question, which is why it is not a step of its own.
221
+ ...(await checkUngeneratableMigrations(ctx.root)),
222
+ // The fourth, and the only one that opens a database — a scratch embedded one it boots
223
+ // itself, so CI still needs nothing listening: the committed `packages/db/schema/` against
224
+ // what replaying the migrations produces, and that dump loaded back (`X_SCHEMA_DUMP_DRIFT`).
225
+ ...(await checkSchemaDump(ctx.root, ctx.env ?? Bun.env)),
226
+ // The fifth: what the previous release would trip over during a roll. Off until the app
227
+ // sets `rollingSince` in `x.verify.json`, since an applied migration cannot gain a marker.
228
+ ...(await checkRollingMigrations(ctx.root)),
229
+ // The sixth: one migration owner. A nested `app.config.ts` is a second app root — its own
230
+ // registry, migrations and image (`X_APP_ROOT_NESTED`, `verify-drift-owner.ts`).
231
+ ...(await nestedAppRootFindings(ctx.root)),
232
+ ],
233
+ // The seventh: a generated client (`x client`) against its own stamp — a source document that
221
234
  // moved (`X_CLIENT_STALE`) or a body edited by hand (`X_CLIENT_EDITED`). No database.
222
- ...(await checkClientDrift(ctx.root)),
223
- ]),
235
+ client: () => checkClientDrift(ctx.root),
236
+ });
237
+ },
224
238
  },
225
239
  {
226
240
  name: 'contract-diff',