@ultimat3/cli 31.4.2 → 31.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CLAUDE.md +15 -7
  2. package/package.json +29 -29
  3. package/src/admin-catalog-keys.ts +17 -1
  4. package/src/app-boundaries.ts +3 -2
  5. package/src/app-transport.ts +7 -3
  6. package/src/asset-route-meta.ts +29 -0
  7. package/src/browser-barrel-cut.ts +109 -0
  8. package/src/browser-import-chain.ts +119 -0
  9. package/src/browser-transport.ts +85 -13
  10. package/src/cmd-dev.ts +15 -2
  11. package/src/cmd-drill.ts +39 -9
  12. package/src/cmd-fix.ts +14 -4
  13. package/src/cmd-i18n.ts +52 -10
  14. package/src/dev-boot.ts +6 -4
  15. package/src/dev-log.ts +95 -0
  16. package/src/dev-rebuild-remount.ts +152 -0
  17. package/src/dev-rebuild-schema.ts +30 -0
  18. package/src/dev-rebuild.ts +51 -14
  19. package/src/dev-supervisor.ts +5 -4
  20. package/src/error-codes.ts +2 -0
  21. package/src/error-contract.ts +29 -2
  22. package/src/favicon.ts +2 -1
  23. package/src/fix-sequence.ts +97 -0
  24. package/src/generate-grant-findings.ts +2 -2
  25. package/src/generate-grants.ts +50 -1
  26. package/src/generate-write.ts +16 -0
  27. package/src/i18n-registration.ts +8 -5
  28. package/src/island-routes.ts +2 -1
  29. package/src/load-findings.ts +29 -22
  30. package/src/mcp-errors.ts +11 -3
  31. package/src/mcp-host-shell.ts +128 -0
  32. package/src/mcp-host.ts +81 -55
  33. package/src/mcp-test-output.ts +5 -2
  34. package/src/messages-gate.ts +12 -0
  35. package/src/messages.ts +16 -0
  36. package/src/policy-append.ts +88 -0
  37. package/src/pwa-artifacts.ts +3 -3
  38. package/src/runtime-assets.ts +4 -1
  39. package/src/site-asset-routes.ts +2 -1
  40. package/src/style-routes.ts +2 -1
  41. package/src/templates/entity.ts +18 -3
  42. package/src/templates/guard-repo-raw-sql.ts +6 -3
  43. package/src/templates/policy.ts +5 -1
  44. package/src/templates/query.ts +4 -2
  45. package/src/templates/resource-service.ts +5 -2
  46. package/src/templates/scaffold-repo.ts +8 -2
  47. package/src/ts-scan.ts +86 -1
  48. package/src/verify-checks.ts +23 -51
  49. package/src/verify-contract-diff.ts +143 -0
  50. package/src/verify-seeds.ts +132 -0
  51. package/src/verify-tests.ts +12 -6
  52. package/src/worker-bundle.ts +2 -1
  53. package/wiki/CLI-Reference.md +2 -2
  54. package/wiki/Entities-And-Migrations.md +3 -3
  55. package/wiki/Interface-Rules.md +2 -2
  56. package/wiki/Project-Layout.md +3 -3
  57. package/wiki/Upgrading.md +7 -0
@@ -13,6 +13,7 @@ import { commentSafe } from './comment-safe';
13
13
  import { GenerateJsonInvalidError, ScaffoldPathEscapeError } from './errors';
14
14
  import { mergeJsonDeep, mergeJsonInPlace, sortJsonDeep } from './json-merge';
15
15
  import type { Finding } from './output';
16
+ import { appendPolicy } from './policy-append';
16
17
  import { quoteArg } from './shell-quote';
17
18
  import type { GeneratedFile } from './templates';
18
19
 
@@ -188,6 +189,12 @@ const conflictFix = (
188
189
  return `${invocation} --force # overwrites ${path}, or pass a different name`;
189
190
  const into = `--feature ${quoteArg(slice)}`;
190
191
  const named = quoteArg(name);
192
+ // `x g policy` on a slice that already declares this very set: an action is the wrong kind and
193
+ // `--force` deletes every other rule in the file. A second set under its own name APPENDS.
194
+ const head = /^(?<head>.*? g) policy /.exec(invocation)?.groups?.['head'];
195
+ if (module === 'policy.ts' && head !== undefined) {
196
+ return `${head} policy ${quoteArg(`${name}-admin`)} ${into} # appends a second permission set: ${commentSafe(path)} already exports ${commentSafe(name)}'s`;
197
+ }
191
198
  // A read needs the slice's table (X_FEATURE_REQUIRED), so it is offered only beside one.
192
199
  const read = existsSync(join(dirname(absolute), 'entity.ts'))
193
200
  ? `or x g query ${named} ${into}`
@@ -212,6 +219,15 @@ function planFile(
212
219
  ? { kind: 'skip' }
213
220
  : { kind: 'write', file, absolute, contents: file.contents };
214
221
  }
222
+ // A slice's `policy.ts` holds every primitive's rules: a second permission set is appended to it,
223
+ // `--force` included — overwriting it would delete the rules already there. The same set again
224
+ // does not merge (`appendPolicy` answers undefined) and is the conflict below.
225
+ if (file.merge === undefined && typeof file.contents === 'string' && existsSync(absolute)) {
226
+ const merged = file.path.endsWith('/policy.ts')
227
+ ? appendPolicy(readFileSync(absolute, 'utf8'), file.contents)
228
+ : undefined;
229
+ if (merged !== undefined) return { kind: 'write', file, absolute, contents: merged };
230
+ }
215
231
  // The scaffold's own copy, untouched, is replaced without asking; an edited one is the author's.
216
232
  if (file.merge === 'replaces-pristine' && existsSync(absolute)) {
217
233
  if (readFileSync(absolute, 'utf8') === file.pristine) {
@@ -156,14 +156,18 @@ export async function checkRegistration(input: RegistrationInput): Promise<Regis
156
156
  };
157
157
  }
158
158
 
159
- /** Keys the catalog does not define, or defines with a placeholder. Labels are never plurals. */
160
- const unanswered = (catalog: Catalog, keys: readonly string[]): readonly string[] =>
159
+ /**
160
+ * Keys the catalog does not define, or defines with a placeholder. Labels are never plurals.
161
+ * Exported because `x i18n sync` writes exactly this set and `x i18n check` counts it: one rule.
162
+ */
163
+ export const unanswered = (catalog: Catalog, keys: readonly string[]): readonly string[] =>
161
164
  keys.filter((key) => !Object.hasOwn(catalog, key) || isLoudMiss(catalog[key]));
162
165
 
163
166
  /**
164
167
  * `X_CATALOG_MISSING_KEYS` — the same fact, a catalog without keys it is asked for — with the
165
- * cause naming who asks and a fix that is an EDIT: `x i18n sync`, the code's own fix, seeds the
166
- * keys SOURCE uses and cannot know these.
168
+ * cause naming who asks. The fix stays the code's own, `x i18n sync <locale>`: it writes these keys
169
+ * too (`cmd-i18n.ts`), nested. The hand edit this used to name was a dotted key, which
170
+ * `loadCatalog` refuses as `X_CATALOG_INVALID`.
167
171
  */
168
172
  function adminKeysFinding(locale: Locale, missing: readonly string[]): Finding {
169
173
  const path = catalogPath(locale);
@@ -172,7 +176,6 @@ function adminKeysFinding(locale: Locale, missing: readonly string[]): Finding {
172
176
  return {
173
177
  ...findingFrom(catalogMissingKeys(locale, missing)),
174
178
  cause: `${path} is missing ${missing.length} key(s) the mounted admin renders (defineAdmin derives them, so no source file names one): ${shown.join(', ')}${more}`,
175
- fix: `add to ${path}, each with its real label: ${shown.join(', ')}${more} — then x i18n check --json`,
176
179
  at: path,
177
180
  };
178
181
  }
@@ -4,6 +4,7 @@
4
4
 
5
5
  import type { Route, UltimateRequest } from '@ultimat3/http';
6
6
  import { applyCacheHeaders, jsonResponse, NO_STORE, textResponse } from '@ultimat3/http';
7
+ import { assetRouteMeta } from './asset-route-meta';
7
8
  import type { IslandBundle } from './island-bundle';
8
9
  import { ISLAND_BASE_PATH } from './island-bundle';
9
10
 
@@ -24,7 +25,7 @@ export function islandRoutes(source: IslandSource): readonly Route[] {
24
25
  {
25
26
  method: 'GET',
26
27
  path: `${ISLAND_BASE_PATH}/*file`,
27
- meta: { name: 'assets.island', auth: 'public', tags: ['assets'] },
28
+ meta: assetRouteMeta({ name: 'assets.island', auth: 'public' }),
28
29
  handler: (request: UltimateRequest): Response => {
29
30
  // An entry or a shared chunk: an entry's bytes import its chunks by a relative name, so both
30
31
  // have to answer at the one base path, under the one cache rule.
@@ -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
+ }
package/src/mcp-host.ts CHANGED
@@ -9,8 +9,10 @@
9
9
  import { join } from 'node:path';
10
10
  import {
11
11
  agentActor,
12
+ isRole,
12
13
  isUltimateError,
13
14
  NotImplementedError,
15
+ ROLES,
14
16
  renderFixShellArg,
15
17
  renderThrowable,
16
18
  UltimateError,
@@ -34,21 +36,19 @@ import type {
34
36
  QueryLimits,
35
37
  QueryRows,
36
38
  VerifyResult,
37
- VerifyStep,
38
39
  } from '@ultimat3/mcp';
39
40
  import { DEV_SCOPES, devHost, devMcpServer, frameworkIntrospection } from '@ultimat3/mcp';
40
41
  import { loadApp } from './app-load';
41
42
  import { appManifest, policyFacts } from './app-manifest';
42
43
  import { loadAppRuntime } from './app-runtime';
43
44
  import { loadAppGraph, resolveNode } from './cmd-graph-load';
44
- import { runVerify, VERIFY_STEPS } from './cmd-verify';
45
- import { declareDevEnvironment } from './dev-environment';
45
+ import { declareDevEnvironment, needsDevEnvironmentDeclaration } from './dev-environment';
46
46
  import { loadCodeFixes } from './error-fixes';
47
47
  import { BadFlagError } from './errors';
48
48
  import type { Runner } from './exec';
49
49
  import { databaseTarget } from './mcp-db-target';
50
50
  import { explainErrorCode } from './mcp-errors';
51
- import { testRunOf } from './mcp-test-run';
51
+ import { type ShellRunInput, shellRunner, shellTests, shellVerify } from './mcp-host-shell';
52
52
  import { type UiCapabilities, uiCapabilities } from './mcp-ui';
53
53
  import { readMigrations } from './migrations';
54
54
  import { retryMemo } from './retry-memo';
@@ -57,8 +57,6 @@ import type { DevServices, Env } from './runtime-bindings';
57
57
  import { resolveServices } from './runtime-bindings';
58
58
  import type { RunningServices } from './runtime-services';
59
59
  import { startServices } from './runtime-services';
60
- import { testEnvOverrides } from './test-dotenv';
61
- import { measurePace } from './verify-pace';
62
60
 
63
61
  export interface DevHostInput {
64
62
  readonly root: string;
@@ -196,29 +194,78 @@ export async function readOnlyRows(
196
194
  }
197
195
 
198
196
  /**
199
- * `bun test`'s argv for a `test.run` filter. A filter is a PATH, and one starting with `-` is a
200
- * `bun test` flag — `--preload ./x.ts` loads a module into the child — so it is refused rather
201
- * than forwarded: a filter is a path, and no path this suite has starts with `-`.
197
+ * `db.migrate`'s answer to a foreign throw. The fix is the REGISTERED one (`mcp-errors.ts`), never
198
+ * a literal here: this said `x db reset`, and an agent that followed it wiped the database the
199
+ * migration had failed against.
202
200
  */
203
- export function testRunArgv(filter: string | undefined): readonly string[] {
204
- if (filter === undefined) return ['bun', 'test'];
205
- if (filter.trimStart().startsWith('-')) {
201
+ export function migrateFailed(error: unknown): UltimateError {
202
+ return new UltimateError({
203
+ code: 'X_DB_MIGRATE_FAILED',
204
+ // The blessed total renderer: `String(error)` runs the value's own `toString`, and this is
205
+ // the last hop before an agent is handed the three-line result.
206
+ cause: renderThrowable(error),
207
+ fix:
208
+ explainErrorCode('X_DB_MIGRATE_FAILED')?.fix ?? 'x errors explain X_DB_MIGRATE_FAILED --json',
209
+ });
210
+ }
211
+
212
+ /**
213
+ * The log `logs.tail` reads. `role` is joined into a path, so it must BE a role: `'../x'` named a
214
+ * file outside the state directory. The tool's schema lists the roles, but a schema is advice to a
215
+ * client and this is the line that opens the file.
216
+ */
217
+ export function logTailPath(dir: string, role: string | undefined): string {
218
+ if (role === undefined) return join(dir, 'dev.log');
219
+ if (!isRole(role)) {
206
220
  throw new BadFlagError({
207
- flag: 'filter',
221
+ flag: 'role',
208
222
  command: 'mcp serve',
209
- reason: `test.run's filter "${filter}" starts with "-", which bun test would read as its own flag`,
210
- fix: 'call test.run with a path filter such as packages/cli/src, or with no filter',
223
+ reason: `logs.tail's role "${role}" is not a runtime role`,
224
+ fix: `logs.tail({ role: 'web' }) # role is one of ${ROLES.join(', ')}; none reads dev.log`,
211
225
  });
212
226
  }
213
- return ['bun', 'test', filter];
227
+ return join(dir, 'logs', `${role}.log`);
228
+ }
229
+
230
+ /** The first window read from a log's end; each further one is four times wider. */
231
+ const TAIL_WINDOW_BYTES = 64 * 1024;
232
+ /** The most a tail ever reads: past this, lines that long are cut rather than the log loaded. */
233
+ const TAIL_MAX_BYTES = 1024 * 1024;
234
+
235
+ /** What `tailLines` reads of a file: its size and a byte range — `Bun.file`'s own shape. */
236
+ export interface TailSource {
237
+ readonly size: number;
238
+ slice(start: number, end: number): { text(): Promise<string> };
239
+ }
240
+
241
+ /**
242
+ * The last `lines` lines, read from the END in widening windows. `file.text()` loaded the whole
243
+ * `dev.log` per call, and an agent calls this in a loop against a log `x dev` never rotates. A
244
+ * window that does not start at byte 0 drops its first line: it may be partial, and may begin
245
+ * mid-character.
246
+ */
247
+ export async function tailLines(file: TailSource, lines: number): Promise<readonly string[]> {
248
+ let window = TAIL_WINDOW_BYTES;
249
+ for (;;) {
250
+ const start = Math.max(0, file.size - Math.min(window, TAIL_MAX_BYTES));
251
+ const all = (await file.slice(start, file.size).text()).trimEnd().split('\n');
252
+ const whole = start === 0 ? all : all.slice(1);
253
+ if (whole.length >= lines || start === 0) return whole.slice(-lines);
254
+ // At the cap with no newline inside it, the one line there is longer than the cap: answered
255
+ // cut, never as `[]` — an empty tail reads as an empty log.
256
+ if (window >= TAIL_MAX_BYTES) return (whole.length === 0 ? all : whole).slice(-lines);
257
+ window *= 4;
258
+ }
214
259
  }
215
260
 
216
261
  function capabilities(
217
262
  input: DevHostInput,
218
263
  lazy: LazyServices,
219
264
  ui: UiCapabilities,
265
+ declared: boolean,
220
266
  ): DevCapabilities {
221
- const { root, runner, env } = input;
267
+ const { root } = input;
268
+ const shell: ShellRunInput = { ...input, declared };
222
269
  // Layer 1 is seven idempotent DDL statements, and `db.query` is a tool an agent calls in a
223
270
  // loop — resolve the role once per process and reuse the answer, `null` included. A FAILED
224
271
  // resolution is not an answer: `??=` kept the rejection, so a statement timeout on the DDL
@@ -249,13 +296,7 @@ function capabilities(
249
296
  // code/cause/fix result, which is what an agent needs to act without a round trip. The
250
297
  // engine's own errors already carry that shape and pass through untouched.
251
298
  if (isUltimateError(error)) throw error;
252
- throw new UltimateError({
253
- code: 'X_DB_MIGRATE_FAILED',
254
- // The blessed total renderer: `String(error)` runs the value's own `toString`, and
255
- // this is the last hop before an agent is handed the three-line result.
256
- cause: renderThrowable(error),
257
- fix: 'x db reset',
258
- });
299
+ throw migrateFailed(error);
259
300
  }
260
301
  // The ledger is the evidence for "applied" — never the migrator's own return value.
261
302
  const pending = await pendingIds(root, lazy);
@@ -277,35 +318,25 @@ function capabilities(
277
318
  }));
278
319
  },
279
320
 
280
- // `bun test <filter>` matches on the test path, the same rule `x test`'s `discoverTests` uses.
281
- async runTests(filter: string | undefined) {
282
- // Same leak the CLI's own `x test`/`x verify` had: `.env.development` auto-loaded into
283
- // THIS process must not ride along into the `bun test` child the dev MCP server spawns.
284
- const envOverrides = testEnvOverrides(root, env);
285
- const result = await runner(testRunArgv(filter), {
286
- cwd: root,
287
- ...(Object.keys(envOverrides).length === 0 ? {} : { env: envOverrides }),
288
- });
289
- // The whole result, exit code included: `0 fail` beside `1 error` is a red run.
290
- return testRunOf(result);
291
- },
321
+ // `x test` itself, never a second test path: the files, batches and env the shell gets.
322
+ runTests: (filter: string | undefined) => shellTests(shell, filter),
292
323
 
293
324
  async tailLogs(lines: number, role: string | undefined) {
294
325
  const dir = lazy.services.stateDir;
295
- const path = role === undefined ? join(dir, 'dev.log') : join(dir, 'logs', `${role}.log`);
326
+ const path = logTailPath(dir, role);
296
327
  const file = Bun.file(path);
297
328
  if (!(await file.exists())) {
298
- // `@ultimat3/core`'s `logger` is a module const with no sink seam, so there is nothing to
299
- // intercept in-process — a log on disk is the only honest source, and the fix creates one.
329
+ // A log on disk is the only honest source: `x dev` tees every line of its own to
330
+ // `dev.log` (`dev-log.ts`), so starting it is the fix. No role writes a log of its own.
300
331
  throw new NotImplementedError({
301
332
  cause: `logs.tail without ${path} is not implemented in this build`,
302
333
  fix:
303
334
  role === undefined
304
- ? `x dev > ${path} 2>&1`
335
+ ? 'x dev'
305
336
  : `mkdir -p ${renderFixShellArg(join(dir, 'logs'), '<the logs dir of the path the cause names>')} && x dev --role ${role} > ${path} 2>&1`,
306
337
  });
307
338
  }
308
- return (await file.text()).trimEnd().split('\n').slice(-lines);
339
+ return tailLines(file, lines);
309
340
  },
310
341
 
311
342
  async readManifest() {
@@ -328,21 +359,11 @@ function capabilities(
328
359
 
329
360
  ...ui,
330
361
 
331
- async verify(fix: boolean): Promise<VerifyResult> {
362
+ async verify(fix: boolean, only?: readonly string[]): Promise<VerifyResult> {
332
363
  // The one safe autofix this repo actually has. Anything more would be the gate rewriting
333
364
  // code it was asked to judge.
334
- if (fix) await runner(['bunx', 'biome', 'check', '--write', '.'], { cwd: root });
335
- const result = await runVerify(VERIFY_STEPS, { root, runner, pace: measurePace() });
336
- return {
337
- ok: result.ok,
338
- steps: (result.steps ?? []).map((step): VerifyStep => {
339
- const detail = step.findings[0]?.cause;
340
- // exactOptionalPropertyTypes: omit `detail`, never hand over an explicit undefined.
341
- return detail === undefined
342
- ? { name: step.name, ok: step.ok }
343
- : { name: step.name, ok: step.ok, detail };
344
- }),
345
- };
365
+ if (fix) await shellRunner(shell)(['bunx', 'biome', 'check', '--write', '.'], { cwd: root });
366
+ return shellVerify(shell, only);
346
367
  },
347
368
  };
348
369
  }
@@ -360,6 +381,9 @@ export async function createDevMcpServer(input: DevHostInput): Promise<CliMcpSer
360
381
  // into a process that has not said it is development. Measured on 20.1.5: the first `ui.shot`
361
382
  // in a session photographed a 401 (`actorKind: anonymous`), and only the second call — whose
362
383
  // scratch boot re-imported the app after declaring — rendered. Idempotent; a set key stays.
384
+ // Asked before declaring: whether the key is this process's own is what `tests.run` and
385
+ // `verify.run` strip from their children, so they run as the shell runs them.
386
+ const declared = needsDevEnvironmentDeclaration(input.env);
363
387
  declareDevEnvironment(input.env);
364
388
  await Promise.all([loadApp(input.root), loadCodeFixes()]);
365
389
  // The plain `runtime.ts` routes, read once: `routes.list` answers the table `x routes` prints.
@@ -370,7 +394,9 @@ export async function createDevMcpServer(input: DevHostInput): Promise<CliMcpSer
370
394
  routes: () => routeRows(plain).map((row) => row.json),
371
395
  policies: () => policyFacts(),
372
396
  });
373
- const server = devMcpServer({ host: devHost(introspection, capabilities(input, lazy, ui)) });
397
+ const server = devMcpServer({
398
+ host: devHost(introspection, capabilities(input, lazy, ui, declared)),
399
+ });
374
400
  const caller = localCaller();
375
401
  return {
376
402
  server,
@@ -6,7 +6,10 @@ import type { TestRun } from '@ultimat3/mcp';
6
6
 
7
7
  const TAIL_LINES = 20;
8
8
  const FAIL_LINE = /^\(fail\)\s+(.*?)(?:\s+\[[\d.]+\s*m?s\])?$/;
9
- const ERROR_LINE = /^\s*error:\s*(.+)$/;
9
+ // Bun's own assertion line, or an uncaught `UltimateError` subclass, which bun prints as
10
+ // `DbError: X_CODE: cause` and never as `error: …`. Anchored on the code, so a source excerpt that
11
+ // only names an Error type is not read as a message.
12
+ const ERROR_LINE = /^\s*(?:error:\s*(.+)|[A-Z]\w*Error:\s*(X_[A-Z0-9_]+\b.*))$/;
10
13
 
11
14
  const lastCount = (output: string, label: string): number | undefined => {
12
15
  const last = [...output.matchAll(new RegExp(`^\\s*(\\d+)\\s+${label}\\b`, 'gm'))].at(-1);
@@ -35,7 +38,7 @@ export function parseBunTest(output: string, durationMs: number): TestRun {
35
38
  for (const line of output.split('\n')) {
36
39
  const error = ERROR_LINE.exec(line);
37
40
  if (error !== null) {
38
- message = error[1] ?? '';
41
+ message = error[1] ?? error[2] ?? '';
39
42
  continue;
40
43
  }
41
44
  const fail = FAIL_LINE.exec(line.trimEnd());
@@ -85,6 +85,18 @@ export const GATE_MESSAGES = {
85
85
  'cli.verify.failSkipped': '{failed} of {count} steps failed — {skipped} skipped: {names}',
86
86
  // The `errors` step's own coverage, in `output`: a scan without a parser reads most fix lines
87
87
  // and not all of them, and a step that reports findings alone claims a completeness it lacks.
88
+ // `contract-diff`'s baseline whenever it is not HEAD's file (`verify-contract-diff.ts`).
89
+ 'cli.verify.contract.mergeBase': 'baseline: {file} at the merge base with {ref}',
90
+ 'cli.verify.contract.baseTip':
91
+ 'baseline: {file} at {ref} — a shallow checkout reaches no merge base with it',
92
+ 'cli.verify.contract.baseUnfetched':
93
+ '{ref} is not fetched, so {file} at HEAD is the baseline — run `{fix}` for the merge base',
94
+ 'cli.verify.contract.noCheckout': 'not a git checkout: {file} on disk is the baseline',
95
+ 'cli.verify.contract.noCommit': 'no commit yet: no published {file} to break',
96
+ 'cli.verify.contract.uncommitted': '{file} is not committed at {rev}: nothing published to break',
97
+ 'cli.verify.contract.notManifest': '{file} at {rev} is not a manifest: no baseline',
98
+ // A step standing down while the app's load is red (`load-findings.ts`).
99
+ 'cli.verify.loadBlocked': 'skipped: load failed (see {owner})',
88
100
  'cli.verify.fixCoverage': 'checked {checked} fix line(s), could not read {unreadable}',
89
101
  // The `drift` step on an app whose only store is a `defineDriver` one: migrations describe
90
102
  // Postgres, and that store owns its schema — said in `output`, so the step is not a silent green.
package/src/messages.ts CHANGED
@@ -47,6 +47,22 @@ const CATALOG = {
47
47
  'cli.dev.mail.refused': 'mail=refused({detail})',
48
48
  'cli.dev.hmr': 'reloaded {file} in {ms}ms',
49
49
  'cli.dev.restart': 'restarting: {reason} — a module that defines a primitive holds the old code',
50
+ // The two other restarts (`dev-rebuild-remount.ts`), each saying its own cause: the route table is
51
+ // mounted once at boot, and a module that failed to import is served only by a new process.
52
+ 'cli.dev.restartSurface':
53
+ 'restarting: {file} changed what x dev mounts ({changes}) — the route table is built once, at boot',
54
+ 'cli.dev.restartFindings':
55
+ 'restarting: {file} changed which modules load ({changes}) — the new process prints the verdict',
56
+ 'cli.dev.change.added': '{what} added',
57
+ 'cli.dev.change.removed': '{what} removed',
58
+ 'cli.dev.change.failing': '{file} fails to load',
59
+ 'cli.dev.change.loads': '{file} loads again',
60
+ 'cli.dev.mounted.route': 'route {name}',
61
+ 'cli.dev.mounted.action': 'action {name}',
62
+ 'cli.dev.mounted.query': 'query {name}',
63
+ 'cli.dev.mounted.channel': 'channel {name}',
64
+ 'cli.dev.mounted.admin': 'admin {name}',
65
+ 'cli.dev.mounted.mount': 'mount {name}',
50
66
  // The restart's wait, said while it waits: a save never cancels a running job (issue #677).
51
67
  'cli.dev.restartWaiting':
52
68
  'restart waits for {count} running job(s) to finish — no new job is claimed; Ctrl-C stops now (a job still running is cut off at the drain deadline and requeued)',