@ultimat3/cli 31.5.0 → 31.6.1

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 (53) hide show
  1. package/CLAUDE.md +15 -8
  2. package/package.json +29 -29
  3. package/src/admin-catalog-keys.ts +17 -1
  4. package/src/app-transport.ts +7 -3
  5. package/src/browser-barrel-cut.ts +109 -0
  6. package/src/browser-import-chain.ts +119 -0
  7. package/src/browser-transport.ts +85 -13
  8. package/src/cmd-dev.ts +15 -2
  9. package/src/cmd-fix.ts +14 -4
  10. package/src/cmd-i18n.ts +52 -10
  11. package/src/dev-boot.ts +6 -4
  12. package/src/dev-log.ts +95 -0
  13. package/src/dev-rebuild-remount.ts +152 -0
  14. package/src/dev-rebuild-schema.ts +30 -0
  15. package/src/dev-rebuild.ts +51 -14
  16. package/src/dev-supervisor.ts +5 -4
  17. package/src/error-codes.ts +2 -0
  18. package/src/error-contract.ts +29 -2
  19. package/src/fix-sequence.ts +97 -0
  20. package/src/generate-grant-findings.ts +2 -2
  21. package/src/generate-grants.ts +50 -1
  22. package/src/generate-write.ts +16 -0
  23. package/src/i18n-registration.ts +8 -5
  24. package/src/island-bundle.ts +9 -9
  25. package/src/island-group-cache.ts +2 -1
  26. package/src/island-identity.ts +22 -51
  27. package/src/island-link.ts +32 -65
  28. package/src/island-outputs.ts +2 -6
  29. package/src/island-realtime.ts +1 -3
  30. package/src/island-runtime.ts +11 -8
  31. package/src/load-findings.ts +29 -22
  32. package/src/mcp-errors.ts +11 -3
  33. package/src/mcp-host-shell.ts +128 -0
  34. package/src/mcp-host.ts +19 -54
  35. package/src/mcp-test-output.ts +5 -2
  36. package/src/messages-gate.ts +12 -0
  37. package/src/messages.ts +16 -0
  38. package/src/page-sync.ts +1 -1
  39. package/src/policy-append.ts +88 -0
  40. package/src/sw-artifacts.ts +1 -1
  41. package/src/templates/entity.ts +18 -3
  42. package/src/templates/policy.ts +5 -1
  43. package/src/templates/query.ts +4 -2
  44. package/src/templates/resource-service.ts +5 -2
  45. package/src/templates/scaffold-repo.ts +8 -2
  46. package/src/ts-scan.ts +86 -1
  47. package/src/verify-checks.ts +23 -51
  48. package/src/verify-contract-diff.ts +143 -0
  49. package/src/verify-seeds.ts +132 -0
  50. package/src/verify-tests.ts +12 -6
  51. package/src/worker-bundle.ts +8 -9
  52. package/wiki/CLI-Reference.md +2 -2
  53. package/wiki/Upgrading.md +4 -0
@@ -1,14 +1,15 @@
1
1
  // One split `Bun.build` of every island, turned into the files a browser fetches: an entry per
2
- // island and a chunk per module two or more islands share, each named by its SOURCE identity and
3
- // importing the others by that name. `island-bundle.ts` runs the build; this file only links.
2
+ // island and a chunk per module two or more islands share, each named by a hash of its FINAL
3
+ // bytes and importing the others by that name. `island-bundle.ts` runs the build; this only links.
4
4
  //
5
- // Why the names are rewritten rather than taken from Bun's `chunk-[hash]`: that hash is of the
6
- // OUTPUT, and `Bun.build` under `minify` is not byte-deterministic (`graphHash` in
7
- // `island-bundle.ts` has the measurement). An output-addressed shared chunk flaps its URL, and
8
- // every entry importing it flaps with it — the precache-404 and cold-cache defect, back.
5
+ // Why the names are rewritten rather than taken from Bun's `chunk-[hash]`: every import of another
6
+ // output is rewritten here, so Bun's hash is of bytes no browser receives. And why the hash is of
7
+ // the OUTPUT, never the sources (#1075): the minifier names a shared chunk's exports by how often
8
+ // the WHOLE build uses them, so an edit to one entry swapped `var g=q(…),y=Fe(…)` for
9
+ // `var y=q(…),g=Fe(…)` in a chunk whose sources had not moved. Named by its sources, it kept its
10
+ // URL, and a CDN holding the old copy under `immutable` handed the new islands the wrong export.
9
11
 
10
12
  import { posix } from 'node:path'; // why: Bun ships no path API; `basename` of a specifier.
11
- import { frameworkVersion } from '@ultimat3/core';
12
13
  import { contentHash } from '@ultimat3/render/server';
13
14
  import { IslandBuildFailedError } from './errors';
14
15
 
@@ -20,15 +21,13 @@ export interface BuiltOutput {
20
21
  readonly file?: string;
21
22
  /** Emitted code, the debug-id comment already removed. */
22
23
  readonly code: string;
23
- /** Its source map's `sourcesContent` — empty for a chunk of bundler runtime helpers only. */
24
- readonly sources: readonly string[];
25
24
  }
26
25
 
27
26
  export interface LinkedFile {
28
27
  /** The output this came from, so the caller can pair it with its island. */
29
28
  readonly path: string;
30
29
  readonly file?: string;
31
- /** `chunk-<identity>` for a shared chunk; the caller prefixes an entry with its module id. */
30
+ /** `contentHash(code)`: `chunk-<identity>` shared, `<moduleId>-<identity>` an entry. */
32
31
  readonly identity: string;
33
32
  /** The code with every import of another output rewritten to that output's final name. */
34
33
  readonly code: string;
@@ -42,97 +41,65 @@ export const sharedChunkName = (identity: string): string => `chunk-${identity}.
42
41
  /** Static imports and `import()` both: a browser fetches either before the island is whole. */
43
42
  const LOADS = new Set(['import-statement', 'dynamic-import']);
44
43
 
45
- interface Scanned {
46
- readonly exports: readonly string[];
47
- /** Specifiers exactly as written, each naming another output of this build. */
48
- readonly specifiers: readonly string[];
49
- }
50
-
51
- function scan(code: string, byName: ReadonlyMap<string, BuiltOutput>): Scanned {
44
+ /** Specifiers exactly as written, each naming another output of this build. */
45
+ function specifiersOf(code: string, byName: ReadonlyMap<string, BuiltOutput>): readonly string[] {
52
46
  const scanned = new Bun.Transpiler({ loader: 'js' }).scan(code);
53
47
  const specifiers = scanned.imports
54
48
  .filter((one) => LOADS.has(one.kind) && byName.has(posix.basename(one.path)))
55
49
  .map((one) => one.path);
56
- return { exports: [...scanned.exports].sort(), specifiers: [...new Set(specifiers)] };
50
+ return [...new Set(specifiers)];
57
51
  }
58
52
 
59
53
  /**
60
- * Every output's identity, from what went in: its own sources (hashed and sorted, as `graphHash`
61
- * does), its EXPORT names, and the identities of every output it imports. The exports are in it
62
- * because they are the link between two files built together — an importer's `import{a as o}`
63
- * is only correct against a chunk exporting `a`, so a chunk whose interface moved must not keep a
64
- * URL an older importer is holding. The imports are in it because an entry's bytes NAME its
65
- * chunks: a moved chunk moves every entry that loads it.
54
+ * Every output linked, leaves first: an output's bytes NAME the chunks it imports, so its final
55
+ * code — and so its name — exists only once theirs do. The identity is `contentHash` of exactly the
56
+ * code returned, so one name is one byte string across every build that ever emits it.
66
57
  */
67
58
  export function linkOutputs(outputs: readonly BuiltOutput[]): readonly LinkedFile[] {
68
59
  const byName = new Map(outputs.map((one) => [posix.basename(one.path), one]));
69
- const scans = new Map(outputs.map((one) => [one.path, scan(one.code, byName)]));
70
- const identities = new Map<string, string>();
60
+ const linked = new Map<string, LinkedFile>();
71
61
  const visiting = new Set<string>();
72
62
 
73
- const identityOf = (output: BuiltOutput): string => {
74
- const known = identities.get(output.path);
63
+ const link = (output: BuiltOutput): LinkedFile => {
64
+ const known = linked.get(output.path);
75
65
  if (known !== undefined) return known;
76
66
  if (visiting.has(output.path)) throw cycle(output);
77
67
  visiting.add(output.path);
78
- const scanned = scans.get(output.path) ?? { exports: [], specifiers: [] };
79
- const deps = scanned.specifiers
80
- .map((spec) => byName.get(posix.basename(spec)))
81
- .filter((dep): dep is BuiltOutput => dep !== undefined)
82
- .map(identityOf)
83
- .sort();
84
- // A chunk of bundler runtime helpers has no source file behind it — its code IS its source.
85
- const own = output.sources.length === 0 ? [contentHash(output.code)] : output.sources;
86
- const identity = contentHash(
87
- [
88
- output.file ?? 'shared',
89
- frameworkVersion(),
90
- Bun.version,
91
- ...own.map((source) => contentHash(source)).sort(),
92
- 'exports',
93
- ...scanned.exports,
94
- 'imports',
95
- ...deps,
96
- ].join('\u0000'),
97
- );
98
- visiting.delete(output.path);
99
- identities.set(output.path, identity);
100
- return identity;
101
- };
102
-
103
- return outputs.map((output) => {
104
- const identity = identityOf(output);
105
- const scanned = scans.get(output.path) ?? { exports: [], specifiers: [] };
106
68
  let code = output.code;
107
69
  const imports: string[] = [];
108
- for (const spec of scanned.specifiers) {
70
+ for (const spec of specifiersOf(output.code, byName)) {
109
71
  const dep = byName.get(posix.basename(spec));
110
72
  if (dep === undefined) continue;
111
- const name = sharedChunkName(identityOf(dep));
73
+ const name = sharedChunkName(link(dep).identity);
112
74
  imports.push(name);
113
75
  // The quoted literal, whole: Bun writes every specifier double-quoted, and a chunk name is a
114
76
  // hash no program text contains by accident. Relative, so it resolves beside the importer
115
77
  // under any base path — `/islands/` served, a temp directory in `mountIsland`.
116
78
  code = code.split(JSON.stringify(spec)).join(JSON.stringify(`./${name}`));
117
79
  }
118
- return {
80
+ const done: LinkedFile = {
119
81
  path: output.path,
120
82
  ...(output.file === undefined ? {} : { file: output.file }),
121
- identity,
83
+ identity: contentHash(code),
122
84
  code,
123
85
  imports: [...new Set(imports)].sort(),
124
86
  };
125
- });
87
+ visiting.delete(output.path);
88
+ linked.set(output.path, done);
89
+ return done;
90
+ };
91
+
92
+ return outputs.map(link);
126
93
  }
127
94
 
128
95
  /**
129
- * Two outputs importing each other: esbuild-family splitting does not emit one, and an identity
130
- * built from its imports' identities has no answer for it. Refused by name rather than answered
131
- * with a hash that silently ignores an edge.
96
+ * Two outputs importing each other: esbuild-family splitting does not emit one between chunks, and
97
+ * a name that is a hash of bytes containing the other's name has no answer for it. Refused by
98
+ * name rather than answered with a name that ignores an edge.
132
99
  */
133
100
  function cycle(output: BuiltOutput): IslandBuildFailedError {
134
101
  return new IslandBuildFailedError({
135
102
  file: output.file ?? output.path,
136
- logs: `the island build emitted a chunk import cycle through ${output.path}, so its outputs have no source identity to be named by`,
103
+ logs: `the island build emitted a chunk import cycle through ${output.path}, so its outputs cannot each be named by their own bytes`,
137
104
  });
138
105
  }
@@ -59,14 +59,13 @@ export async function builtOutputs(
59
59
  if (sources === undefined || (artifact.kind === 'entry-point' && file === undefined)) {
60
60
  throw new IslandBuildFailedError({
61
61
  file: file ?? key,
62
- logs: `the bundler emitted ${key} with no source map or no island behind it, so the output has no stable identity`,
62
+ logs: `the bundler emitted ${key} with no source map or no island behind it, so the files it was built from are unknown`,
63
63
  });
64
64
  }
65
65
  outputs.push({
66
66
  path: key,
67
67
  ...(file === undefined ? {} : { file }),
68
68
  code: stripDebugId(await artifact.text()),
69
- sources,
70
69
  });
71
70
  }
72
71
  return outputs;
@@ -117,10 +116,7 @@ export function entryChunks(
117
116
  file,
118
117
  moduleId,
119
118
  url: `${ISLAND_BASE_PATH}/${moduleId}-${entry.identity}.js`,
120
- // The FIRST bytes this process emitted for these inputs, so a URL served `immutable` answers
121
- // one byte string for as long as the process lives. Without it `x dev` re-mints the chunk on
122
- // every watcher tick and a browser holding the previous one under `max-age=31536000` has two
123
- // different files at one address. `bytes` is measured on THAT code, never on this build's.
119
+ // The identity IS `contentHash(entry.code)` (`island-link.ts`), so the URL names these bytes.
124
120
  ...stableChunk(file, entry.identity, entry.code),
125
121
  imports: closure(entry.imports),
126
122
  sources: withOwnFile(file, sources.get(entry.path) ?? []),
@@ -82,9 +82,7 @@ const entrySource = (file: string, follows: boolean): string =>
82
82
  /**
83
83
  * The install names `@ultimat3/realtime` BARE, and `islandRealtimePlugin` resolves it from the
84
84
  * ISLAND's own directory — the resolution the island itself gets — so the bundle holds one copy
85
- * and the signal lands where the hooks read it. Never the resolved absolute path spliced in: this
86
- * source is part of the chunk's `sourcesContent`, which is what `graphHash` names the URL from, so
87
- * a path in it gave the same island a different URL in every checkout and every image build.
85
+ * and the signal lands where the hooks read it.
88
86
  * `solid-js` goes through `island-solid-dedupe.ts` like every other import in the graph.
89
87
  *
90
88
  * The await comes first: no hook may run before the page runtime is installed, and the module
@@ -1,16 +1,17 @@
1
1
  // The page runtime as ONE chunk beside the islands (#505): realtime's `page-runtime.ts` — the store,
2
- // the socket stack, the query client, core's transport — built once per build, addressed by its
3
- // source graph like any island, and loaded by a realtime island only on a document the page boot
2
+ // the socket stack, the query client, core's transport — built once per build, named by its
3
+ // bytes like any island, and loaded by a realtime island only on a document the page boot
4
4
  // is absent from. Islands carry thin hooks over it; none carries a copy of it.
5
5
 
6
6
  // why: Bun ships no path API; the runtime is resolved beside the realtime the islands bundle.
7
7
  import { dirname, join } from 'node:path';
8
+ import { contentHash } from '@ultimat3/render/server';
8
9
  import type { BunPlugin } from 'bun';
9
10
  import { IslandBuildFailedError } from './errors';
10
11
  import type { IslandChunk, SharedChunk } from './island-bundle';
11
12
  import { inputFiles } from './island-cache-inputs';
12
13
  import { realSpelling } from './island-duplicates';
13
- import { describeBuildError, graphHash, stableChunk, stripDebugId } from './island-identity';
14
+ import { describeBuildError, stableChunk, stripDebugId } from './island-identity';
14
15
  import { frameworkDedupePlugins } from './island-package-dedupe';
15
16
  import type { SourcePaths } from './island-sources';
16
17
  import { sourcesOnDisk } from './island-sources';
@@ -147,7 +148,7 @@ async function buildRuntime(
147
148
  minify: true,
148
149
  plugins: [runtimeEntryPlugin(file), ...frameworkDedupePlugins(root)],
149
150
  // `island-bundle.ts`'s reasons, verbatim: only ever built to be shipped, and the map's
150
- // `sourcesContent` is the one stable identity a minified bundle has.
151
+ // sources are what the island store re-checks a prebuilt chunk against.
151
152
  define: { 'process.env.NODE_ENV': '"production"' },
152
153
  sourcemap: 'external',
153
154
  metafile: true,
@@ -164,13 +165,15 @@ async function buildRuntime(
164
165
  });
165
166
  }
166
167
  const text = await map.text();
167
- const identity = graphHash(ENTRY, text);
168
+ // Named by its bytes (#1075), as every island output is: `immutable` is a promise about them.
169
+ const code = stripDebugId(await output.text());
170
+ const identity = contentHash(code);
168
171
  const url = `${basePath}/page-runtime.${identity}.js`;
169
172
  return {
170
173
  realtime,
171
174
  wait,
172
175
  url,
173
- ...stableChunk(url, identity, stripDebugId(await output.text())),
176
+ ...stableChunk(url, identity, code),
174
177
  sources: await sourcesOnDisk(root, JSON.parse(text)),
175
178
  inputs: await inputFiles(Object.keys(built.metafile?.inputs ?? {})),
176
179
  };
@@ -178,8 +181,8 @@ async function buildRuntime(
178
181
 
179
182
  /**
180
183
  * The entry installs the runtime as its whole body; the module is named BARE in that source and
181
- * resolved here, because the source is part of `sourcesContent` and a machine path in it would give
182
- * one runtime a different URL in every checkout (the reason `island-realtime.ts` names realtime).
184
+ * resolved here, the reason `island-realtime.ts` names realtime: resolved from where the islands
185
+ * resolve it, it is the one copy they bundle.
183
186
  */
184
187
  function runtimeEntryPlugin(file: string): BunPlugin {
185
188
  return {
@@ -1,41 +1,48 @@
1
- // One cause, one step. A module that will not import was reported by up to four steps at once —
2
- // `contract-diff`, `budgets`, `policy` and `manifest` all load the app, and each carried the load's
3
- // findings — so one syntax error read as four red steps and four copies of one line (plan 101
4
- // slice 11 i). The `manifest` step owns them: it runs in every repo, and "does the projection
5
- // describe the code?" is the question a module that will not import answers first.
1
+ // One cause, one finding. A module that will not import leaves every registry half-filled, and each
2
+ // step that loaded the app reported what half a registry looks like — a permission typo read as 9
3
+ // findings across 7 steps (plan 101 19a FX8). The `manifest` step owns the load's findings: it runs
4
+ // in every repo, and "does the projection describe the code?" is the question a broken module
5
+ // answers first. Every other step that loads the app stands down while the load is red.
6
6
 
7
7
  import { loadApp } from './app-load';
8
+ import { msg } from './messages';
8
9
  import type { Finding } from './output';
9
- import type { StepOutcome, VerifyStepName } from './verify-step';
10
+ import type { VerifyContext, VerifyStep, VerifyStepName } from './verify-step';
10
11
 
11
12
  /** The step that reports the app's load failures. Every other step points at it. */
12
13
  export const LOAD_OWNER: VerifyStepName = 'manifest';
13
14
 
15
+ /** What a dependent step says instead of running over a half-loaded registry. */
16
+ export const LOAD_BLOCKED = msg('cli.verify.loadBlocked', { owner: LOAD_OWNER });
17
+
14
18
  /** What the app load reports, as the step sees it. */
15
19
  export type LoadProbe = (root: string) => Promise<{ readonly findings: readonly Finding[] }>;
16
20
 
17
21
  const keyOf = (finding: Finding): string =>
18
22
  [finding.code, finding.at ?? '', finding.cause].join('\u0000');
19
23
 
24
+ /** Whether this run reports the owner step: the gate always does, `--only` when it names it. */
25
+ function ownerRuns(ctx: VerifyContext): boolean {
26
+ if (ctx.only === undefined) return true;
27
+ return typeof ctx.only === 'string' ? ctx.only === LOAD_OWNER : ctx.only.includes(LOAD_OWNER);
28
+ }
29
+
20
30
  /**
21
- * `findings` without the ones the app load raised, and an `output` line saying where they went.
22
- * The step's own verdict stands on what is left: a budget the broken module left unmeasured is
23
- * still this step's finding, only its cause moved.
31
+ * `step`, standing down while the app's load has findings. A run that includes the owner gets one
32
+ * line saying where the cause went and no findings — the gate is red on `manifest` already. A
33
+ * narrowed run without the owner (`x verify --only budgets`) carries the load's findings itself:
34
+ * skipping there would be a green over an app that does not load.
24
35
  */
25
- export async function withoutLoadFindings(
26
- root: string,
27
- findings: readonly Finding[],
28
- load: LoadProbe = loadApp,
29
- ): Promise<StepOutcome> {
30
- const loaded = new Set((await load(root)).findings.map(keyOf));
31
- const kept = findings.filter((finding) => !loaded.has(keyOf(finding)));
32
- const moved = findings.length - kept.length;
36
+ export function blockedByLoad(step: VerifyStep, load: LoadProbe = loadApp): VerifyStep {
33
37
  return {
34
- ok: kept.length === 0,
35
- findings: kept,
36
- ...(moved === 0
37
- ? {}
38
- : { output: `skipped: ${moved} module-load finding(s) — see ${LOAD_OWNER}` }),
38
+ ...step,
39
+ async run(ctx) {
40
+ const { findings } = await load(ctx.root);
41
+ if (findings.length === 0) return step.run(ctx);
42
+ return ownerRuns(ctx)
43
+ ? { ok: true, findings: [], output: LOAD_BLOCKED }
44
+ : { ok: false, findings, output: LOAD_BLOCKED };
45
+ },
39
46
  };
40
47
  }
41
48
 
package/src/mcp-errors.ts CHANGED
@@ -143,7 +143,10 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
143
143
  X_PORT_INVALID: 'docker run -e PORT=3000 my-app:latest',
144
144
  X_RUNTIME_DRIVER_SPLIT:
145
145
  'x dev --json # the boot names the driver; move it to `export const runtime = { jobs }` in apps/web/runtime.ts',
146
- X_GENERATE_CONFLICT: 'x g route posts --force --json',
146
+ // `generate-write.ts`'s `conflictFix` shape, without the run's own name: list what the run would
147
+ // write, then a free name or the slice to add into — never `--force` over a file a slice shares.
148
+ X_GENERATE_CONFLICT:
149
+ 'x g route posts --dry-run --json # lists each file the run would write; then the same command under a name no file holds, or x g query posts --feature posts to add into that slice',
147
150
  X_APP_NAME_EMPTY:
148
151
  'x new my-app --json # a name with letters or digits; it becomes the directory',
149
152
  X_APP_EMPTY:
@@ -210,8 +213,10 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
210
213
  // The finding's own `fix:` is this command plus the edit — the line, and what replaces the call.
211
214
  X_BROWSER_TRANSPORT_BYPASS:
212
215
  'x verify --only boundaries --json # each finding names the line and the transport to use instead',
216
+ // `x errors explain` holds no finding, so the runnable half is the step that prints one; that
217
+ // finding's own fix IS the edit, edit first (`fix-sequence.ts`): a swap, or a cut.
213
218
  X_BROWSER_SERVER_BARREL:
214
- 'x verify --only boundaries --json # each finding names the import and the browser entry to import instead',
219
+ 'x verify --only boundaries --json # each finding opens with its edit: the import swapped to the browser entry it names (@ultimat3/query/client for @ultimat3/query), or the cut where the island first reaches the barrel',
215
220
  // `EDITOR=` inline rather than `export`: the variable is only needed for the one invocation, and
216
221
  // an agent copying this line gets a working command instead of a shell it has to keep.
217
222
  X_SECRETS_EDITOR_MISSING: 'EDITOR=nano x secrets edit',
@@ -374,6 +379,7 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
374
379
  'x verify --only package-shape --json # each finding carries its own `bun add <package> --cwd <workspace>` line',
375
380
  X_TYPESCRIPT_VERSION:
376
381
  'x doctor --json # each X_TYPESCRIPT_VERSION finding names its manifest and the bun add that moves it',
382
+ X_SEED_FAILED: 'bun --eval \'await (await import("./packages/db/seeds/dev.ts")).dev.run()\'',
377
383
  };
378
384
 
379
385
  const isCliCode = (code: string): code is CliErrorCode =>
@@ -413,7 +419,9 @@ function projectedFix(code: string): string {
413
419
  // with the same line, because it is the same condition seen from a second command.
414
420
  return `bun install && x doctor --json # the installed @ultimat3 packages could not be read, so no throw site could be quoted for ${code}`;
415
421
  }
416
- return `x errors list --json # nothing in the installed framework raises ${code}, so the package that registered it owns its fix`;
422
+ // Not "nothing raises it": the scan reads literals and `*FIXES` table keys, and a code raised
423
+ // from a computed value is neither — that claim told the reader of a live error it was dead.
424
+ return `x errors list --json # no throw site in the installed framework spells ${code} as a literal or a *FIXES table key: it is raised from a computed value, and the raised error carries its own fix line`;
417
425
  }
418
426
  // Both notes name a thing this answer does NOT know, because an answer that hides either is one
419
427
  // an agent acts on without noticing: which of several throw sites it is quoting, and which words
@@ -0,0 +1,128 @@
1
+ // `tests.run` and `verify.run` as the shell runs them: `x test` and `x verify` themselves, through
2
+ // their own commands, with the environment the shell would have handed them. A second test path in
3
+ // the dev MCP server (a bare `bun test <filter>`) answered red for files `x test` ran green.
4
+
5
+ import { ENVIRONMENT_KEY } from '@ultimat3/core';
6
+ import type { TestRun, VerifyResult, VerifyStep } from '@ultimat3/mcp';
7
+ import { testCommand } from './cmd-test';
8
+ import { testSpec } from './cmd-test-spec';
9
+ import { verifyCommand } from './cmd-verify';
10
+ import { verifySpec } from './cmd-verify-spec';
11
+ import { BadFlagError } from './errors';
12
+ import type { ExecResult, Runner } from './exec';
13
+ import { testRunOf } from './mcp-test-run';
14
+ import { parseArgs } from './parse';
15
+
16
+ type Env = Readonly<Record<string, string | undefined>>;
17
+
18
+ export interface ShellRunInput {
19
+ readonly root: string;
20
+ /** The host's environment — after `declareDevEnvironment` may have written to it. */
21
+ readonly env: Env;
22
+ readonly runner: Runner;
23
+ /**
24
+ * Whether THIS process declared `ULTIMATE_ENV=development` (`declareDevEnvironment`). A shell
25
+ * never has it, so neither may a child: inherited, it overrode the `NODE_ENV=test` every
26
+ * `bun test` sets, and the app's tests seeded and connected as development.
27
+ */
28
+ readonly declared: boolean;
29
+ }
30
+
31
+ /** The env a shell would hand `x test`/`x verify`: the host's, less what the host declared. */
32
+ export const shellEnv = (input: ShellRunInput): Env =>
33
+ input.declared ? { ...input.env, [ENVIRONMENT_KEY]: undefined } : input.env;
34
+
35
+ /**
36
+ * Every child spawned with the declared key unset, unless the caller sets it itself. `exec.ts`
37
+ * overlays `options.env` onto `Bun.env`, the very object `declareDevEnvironment` wrote to, so
38
+ * handing the commands `shellEnv` alone would not reach their children.
39
+ */
40
+ export function shellRunner(input: ShellRunInput): Runner {
41
+ if (!input.declared) return input.runner;
42
+ return (command, options) =>
43
+ input.runner(command, { ...options, env: { [ENVIRONMENT_KEY]: undefined, ...options.env } });
44
+ }
45
+
46
+ /**
47
+ * `x test`'s argv for a `tests.run` filter. A filter is a path substring; one starting with `-`
48
+ * would be read as a flag of `x test`, so it is refused rather than forwarded.
49
+ */
50
+ export function testRunArgs(filter: string | undefined): readonly string[] {
51
+ if (filter === undefined) return ['test'];
52
+ if (filter.trimStart().startsWith('-')) {
53
+ throw new BadFlagError({
54
+ flag: 'filter',
55
+ command: 'mcp serve',
56
+ reason: `test.run's filter "${filter}" starts with "-", which x test would read as its own flag`,
57
+ fix: 'call test.run with a path filter such as packages/cli/src, or with no filter',
58
+ });
59
+ }
60
+ return ['test', '--filter', filter];
61
+ }
62
+
63
+ const isBunTest = (result: ExecResult): boolean =>
64
+ result.command[0] === 'bun' && result.command[1] === 'test';
65
+
66
+ /** Every `bun test` batch `x test` spawned, summed into the one answer the tool returns. */
67
+ export function sumRuns(results: readonly ExecResult[], durationMs: number): TestRun {
68
+ const runs = results.filter(isBunTest).map(testRunOf);
69
+ return {
70
+ passed: runs.reduce((sum, run) => sum + run.passed, 0),
71
+ failed: runs.reduce((sum, run) => sum + run.failed, 0),
72
+ skipped: runs.reduce((sum, run) => sum + run.skipped, 0),
73
+ durationMs,
74
+ failures: runs.flatMap((run) => run.failures),
75
+ };
76
+ }
77
+
78
+ /** `tests.run`: `x test --filter <filter>`, with each batch's output read back into counts. */
79
+ export async function shellTests(
80
+ input: ShellRunInput,
81
+ filter: string | undefined,
82
+ ): Promise<TestRun> {
83
+ const results: ExecResult[] = [];
84
+ const runner = shellRunner(input);
85
+ const started = performance.now();
86
+ const outcome = await testCommand.run({
87
+ args: parseArgs(testRunArgs(filter), [testSpec]),
88
+ cwd: input.root,
89
+ env: shellEnv(input),
90
+ bunVersion: Bun.version,
91
+ runner: async (command, options) => {
92
+ const result = await runner(command, options);
93
+ results.push(result);
94
+ return result;
95
+ },
96
+ });
97
+ const run = sumRuns(results, Math.round(performance.now() - started));
98
+ // A red command with no red batch read (a batch the parser could not see) is still red.
99
+ if (outcome.ok || run.failed > 0) return run;
100
+ const failure = { test: 'x test', message: outcome.summary };
101
+ return { ...run, failed: 1, failures: [failure] };
102
+ }
103
+
104
+ /** `verify.run`: `x verify [--only a,b]`, its steps projected onto the tool's shape. */
105
+ export async function shellVerify(
106
+ input: ShellRunInput,
107
+ only: readonly string[] | undefined,
108
+ ): Promise<VerifyResult> {
109
+ const argv = only === undefined ? ['verify'] : ['verify', '--only', only.join(',')];
110
+ // A refused `--only` throws the command's own coded error, which the tool renders as one.
111
+ const result = await verifyCommand.run({
112
+ args: parseArgs(argv, [verifySpec]),
113
+ cwd: input.root,
114
+ env: shellEnv(input),
115
+ bunVersion: Bun.version,
116
+ runner: shellRunner(input),
117
+ });
118
+ return {
119
+ ok: result.ok,
120
+ steps: (result.steps ?? []).map((step): VerifyStep => {
121
+ const detail = step.findings[0]?.cause;
122
+ // exactOptionalPropertyTypes: omit `detail`, never hand over an explicit undefined.
123
+ return detail === undefined
124
+ ? { name: step.name, ok: step.ok }
125
+ : { name: step.name, ok: step.ok, detail };
126
+ }),
127
+ };
128
+ }