@ultimat3/cli 31.20.0 → 31.22.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 (39) hide show
  1. package/CLAUDE.md +1 -1
  2. package/README.md +11 -6
  3. package/package.json +29 -29
  4. package/src/cmd-db.ts +5 -18
  5. package/src/cmd-doctor.ts +8 -3
  6. package/src/cmd-mcp.ts +6 -1
  7. package/src/cmd-verify.ts +19 -15
  8. package/src/db-schema-dump.ts +20 -0
  9. package/src/dev-lock.ts +26 -5
  10. package/src/doctor-guards.ts +27 -12
  11. package/src/drift-store.ts +28 -2
  12. package/src/error-codes-doctor.ts +9 -5
  13. package/src/guards.ts +66 -28
  14. package/src/lint-findings.ts +34 -10
  15. package/src/mcp-agent-host.ts +107 -0
  16. package/src/mcp-errors.ts +4 -0
  17. package/src/mcp-host.ts +23 -1
  18. package/src/mcp-request-statements.ts +129 -0
  19. package/src/mcp-ui.ts +1 -2
  20. package/src/messages.ts +0 -2
  21. package/src/runtime-cache.ts +12 -3
  22. package/src/schema-dump-drift.ts +78 -4
  23. package/src/templates/guard-repo-await-in-loop-test.ts +89 -0
  24. package/src/templates/guard-repo-await-in-loop.ts +214 -0
  25. package/src/templates/guard-repo-unbounded-test.ts +56 -0
  26. package/src/templates/guard-repo-unbounded.ts +197 -0
  27. package/src/templates/scaffold-claude-agents.ts +4 -4
  28. package/src/templates/scaffold-claude-hook.ts +40 -0
  29. package/src/templates/scaffold-claude.ts +22 -6
  30. package/src/templates/scaffold-docs.ts +2 -7
  31. package/src/templates/scaffold-guards.ts +6 -0
  32. package/src/verify-changed.ts +32 -5
  33. package/src/verify-checks.ts +26 -7
  34. package/src/verify-progress.ts +32 -1
  35. package/wiki/CLI-Reference.md +19 -8
  36. package/wiki/MCP-And-AI.md +7 -3
  37. package/wiki/Tutorial-02-First-Feature.md +1 -1
  38. package/wiki/Upgrading.md +7 -0
  39. package/src/retry-memo.ts +0 -37
package/src/guards.ts CHANGED
@@ -31,6 +31,13 @@ export interface Guard {
31
31
  * may, from `root`.
32
32
  */
33
33
  check(root: string, sources: GuardSources): Promise<readonly Finding[]> | readonly Finding[];
34
+ /**
35
+ * `'warning'`: REPORT ONLY. The findings it returns ride the step as warnings — listed in
36
+ * `--json` and on the step line, never a failure — so a rule can ship to every app before the
37
+ * apps are clean of it. Absent: every finding fails the gate. A finding that breaks the contract
38
+ * is a failure either way, because a guard that fails open is the defect this seam refuses.
39
+ */
40
+ readonly severity?: 'warning';
34
41
  }
35
42
 
36
43
  const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -40,7 +47,8 @@ const isGuard = (value: unknown): value is Guard =>
40
47
  isRecord(value) &&
41
48
  typeof value['summary'] === 'string' &&
42
49
  value['summary'].trim() !== '' &&
43
- typeof value['check'] === 'function';
50
+ typeof value['check'] === 'function' &&
51
+ (value['severity'] === undefined || value['severity'] === 'warning');
44
52
 
45
53
  const CODE = /^X_[A-Z0-9_]+$/;
46
54
 
@@ -122,6 +130,22 @@ const invalid = (path: string, cause: string): Finding => ({
122
130
  at: path,
123
131
  });
124
132
 
133
+ const notAGuard = (path: string, exported: unknown): Finding => {
134
+ if (exported === undefined) {
135
+ return invalid(
136
+ path,
137
+ `${path} exports no \`guard\`, so a file in ${GUARD_DIR}/ enforces nothing`,
138
+ );
139
+ }
140
+ const severity = isRecord(exported) ? exported['severity'] : undefined;
141
+ return invalid(
142
+ path,
143
+ severity !== undefined && severity !== 'warning'
144
+ ? `${path} exports a \`guard\` whose severity is ${shown(severity)} — 'warning' (report only) is the one, or none to fail the gate`
145
+ : `${path} exports a \`guard\` with no summary and no check()`,
146
+ );
147
+ };
148
+
125
149
  const findingInvalid = (path: string, cause: string): Finding => ({
126
150
  code: 'X_GUARD_FINDING_INVALID',
127
151
  cause: `${path} returned a finding that is not one: ${cause}`,
@@ -133,52 +157,53 @@ const findingInvalid = (path: string, cause: string): Finding => ({
133
157
  /** Same reason as `shown`: an app's guard may throw a value that fights every way of reading it. */
134
158
  const messageOf = (error: unknown): string => renderThrowable(error);
135
159
 
160
+ /** What the gate does with a guard's findings: fail on `findings`, list `warnings`. */
161
+ export interface GuardReport {
162
+ readonly findings: readonly Finding[];
163
+ /** A report-only guard's findings, each held to the same contract. Never a failure. */
164
+ readonly warnings: readonly Finding[];
165
+ }
166
+
167
+ const refused = (finding: Finding): GuardReport => ({ findings: [finding], warnings: [] });
168
+
136
169
  /** One guard: import it, run it, and hold what it returns to the contract. Never throws. */
137
- async function runGuard(
138
- root: string,
139
- path: string,
140
- sources: GuardSources,
141
- ): Promise<readonly Finding[]> {
170
+ async function runGuard(root: string, path: string, sources: GuardSources): Promise<GuardReport> {
142
171
  let loaded: unknown;
143
172
  try {
144
173
  loaded = await import(pathToFileURL(join(root, path)).href);
145
174
  } catch (error) {
146
- return [failed(path, `${path} could not be imported: ${messageOf(error)}`)];
175
+ return refused(failed(path, `${path} could not be imported: ${messageOf(error)}`));
147
176
  }
148
177
  const exported = isRecord(loaded) ? loaded['guard'] : undefined;
149
- if (!isGuard(exported)) {
150
- return [
151
- invalid(
152
- path,
153
- exported === undefined
154
- ? `${path} exports no \`guard\`, so a file in ${GUARD_DIR}/ enforces nothing`
155
- : `${path} exports a \`guard\` with no summary and no check()`,
156
- ),
157
- ];
158
- }
178
+ if (!isGuard(exported)) return refused(notAGuard(path, exported));
159
179
  let returned: unknown;
160
180
  try {
161
181
  returned = await exported.check(root, sources);
162
182
  } catch (error) {
163
- return [failed(path, `${path} ("${exported.summary}") threw: ${messageOf(error)}`)];
183
+ return refused(failed(path, `${path} ("${exported.summary}") threw: ${messageOf(error)}`));
164
184
  }
165
185
  if (!Array.isArray(returned)) {
166
- return [findingInvalid(path, `check() answered ${typeof returned}, not a list of findings`)];
186
+ return refused(
187
+ findingInvalid(path, `check() answered ${typeof returned}, not a list of findings`),
188
+ );
167
189
  }
168
- const findings: Finding[] = [];
190
+ const broken: Finding[] = [];
191
+ const held: Finding[] = [];
169
192
  for (const candidate of returned as readonly unknown[]) {
170
193
  // Reading a candidate can throw on its own — a getter that raises, a proxy that refuses — and
171
194
  // `findingProblem` is total only for values it can read. Per candidate, so one unreadable
172
195
  // entry costs its own line and not the readable findings beside it.
173
196
  try {
174
197
  const problem = findingProblem(candidate);
175
- if (problem !== undefined) findings.push(findingInvalid(path, problem));
176
- else findings.push(findingOf(candidate as Record<string, unknown>, path));
198
+ if (problem !== undefined) broken.push(findingInvalid(path, problem));
199
+ else held.push(findingOf(candidate as Record<string, unknown>, path));
177
200
  } catch (error) {
178
- findings.push(findingInvalid(path, `it could not be read: ${messageOf(error)}`));
201
+ broken.push(findingInvalid(path, `it could not be read: ${messageOf(error)}`));
179
202
  }
180
203
  }
181
- return findings;
204
+ return exported.severity === 'warning'
205
+ ? { findings: broken, warnings: held }
206
+ : { findings: [...broken, ...held], warnings: [] };
182
207
  }
183
208
 
184
209
  /**
@@ -188,15 +213,28 @@ async function runGuard(
188
213
  * step, which is what keeps "green" meaning one thing (axiom 5) while the app still gets to make
189
214
  * its own convention a build error.
190
215
  */
191
- export const guardFindings = async (
216
+ export const guardReport = async (
192
217
  root: string,
193
218
  /** Files the step already read (`guardSources`' seed), so no guard reads one a second time. */
194
219
  seed: readonly { readonly path: string; readonly source: string }[] = [],
195
- ): Promise<readonly Finding[]> => {
220
+ ): Promise<GuardReport> => {
196
221
  const findings: Finding[] = [];
222
+ const warnings: Finding[] = [];
197
223
  const sources = guardSources(root, seed);
198
224
  for (const path of await guardPaths(root)) {
199
- findings.push(...(await runGuard(root, path, sources)));
225
+ const report = await runGuard(root, path, sources);
226
+ findings.push(...report.findings);
227
+ warnings.push(...report.warnings);
200
228
  }
201
- return findings;
229
+ return { findings, warnings };
202
230
  };
231
+
232
+ /** The findings that fail the gate; a report-only guard's are `guardReport`'s `warnings`. */
233
+ export const guardFindings = async (
234
+ root: string,
235
+ seed: readonly { readonly path: string; readonly source: string }[] = [],
236
+ ): Promise<readonly Finding[]> => (await guardReport(root, seed)).findings;
237
+
238
+ /** A report-only finding as the one line the step lists it on. */
239
+ export const guardWarningLine = (finding: Finding): string =>
240
+ `${finding.at === undefined ? '' : `${finding.at}: `}${finding.code} ${finding.cause} — fix: ${finding.fix}`;
@@ -1,6 +1,7 @@
1
- // `biome check --reporter=json` read as findings, one per diagnostic. `X_LINT_FAILED` alone said
2
- // `bunx biome check --write .`, and that exits "Skipped 1 suggested fixes", still red, with what was
3
- // wrong in the step's `output` where a reader of `findings` never looks.
1
+ // `biome check --reporter=json` read as findings: one per diagnostic an edit fixes, and ONE for every
2
+ // diagnostic `--write` repairs, naming all their files in a single command. `X_LINT_FAILED` alone
3
+ // said `bunx biome check --write .`, which exits "Skipped 1 suggested fixes", still red; a finding
4
+ // per formatted file was twenty commands for one keystroke's worth of work (plan 101 19b, Y1).
4
5
 
5
6
  import { ERROR_DOCS_URL } from '@ultimat3/core';
6
7
  import { commentSafe } from './comment-safe';
@@ -53,19 +54,36 @@ const diagnosticFrom = (value: unknown): Diagnostic | undefined => {
53
54
  const REPAIRED_BY_WRITE = (category: string): boolean =>
54
55
  category === 'format' || category.startsWith('assist/');
55
56
 
56
- const findingOf = ({ category, message, path, line }: Diagnostic): Finding => {
57
- const place = line > 0 ? `${path}:${String(line)}` : path;
57
+ const placeOf = ({ path, line }: Diagnostic): string =>
58
+ line > 0 ? `${path}:${String(line)}` : path;
59
+
60
+ /** A diagnostic only an edit fixes: the file, the rule and the message, one finding each. */
61
+ const editFinding = (diagnostic: Diagnostic): Finding => {
62
+ const { category, message, path } = diagnostic;
63
+ const place = placeOf(diagnostic);
58
64
  return {
59
65
  code: 'X_LINT_FAILED',
60
66
  cause: `${place} ${category}: ${message}`,
61
- fix: REPAIRED_BY_WRITE(category)
62
- ? `bunx biome check --write ${quoteArg(path)}`
63
- : `bunx biome check ${quoteArg(path)} # ${category}: edit ${commentSafe(place)}, ${commentSafe(message)}`,
67
+ fix: `bunx biome check ${quoteArg(path)} # ${category}: edit ${commentSafe(place)}, ${commentSafe(message)}`,
64
68
  docs: ERROR_DOCS_URL,
65
69
  at: path,
66
70
  };
67
71
  };
68
72
 
73
+ /** Every diagnostic `--write` repairs, as one finding whose one command names each file once. */
74
+ const writeFinding = (diagnostics: readonly Diagnostic[]): Finding => {
75
+ const paths = [...new Set(diagnostics.map((diagnostic) => diagnostic.path))];
76
+ const places = diagnostics.map((d) => `${placeOf(d)} ${d.category}: ${d.message}`);
77
+ return {
78
+ code: 'X_LINT_FAILED',
79
+ cause: places.join('; '),
80
+ // Each path through `quoteArg`, joined after: one command, every file one argument.
81
+ fix: ['bunx biome check --write', ...paths.map(quoteArg)].join(' '),
82
+ docs: ERROR_DOCS_URL,
83
+ ...(paths.length === 1 ? { at: paths[0] } : {}),
84
+ };
85
+ };
86
+
69
87
  /** Every failing diagnostic, or `undefined` when the output is not the report it should be. */
70
88
  export function lintFindings(stdout: string): readonly Finding[] | undefined {
71
89
  let report: unknown;
@@ -75,10 +93,16 @@ export function lintFindings(stdout: string): readonly Finding[] | undefined {
75
93
  return undefined;
76
94
  }
77
95
  if (!isRecord(report) || !Array.isArray(report['diagnostics'])) return undefined;
78
- return report['diagnostics'].flatMap((value) => {
96
+ const diagnostics = report['diagnostics'].flatMap((value) => {
79
97
  const diagnostic = diagnosticFrom(value);
80
- return diagnostic === undefined ? [] : [findingOf(diagnostic)];
98
+ return diagnostic === undefined ? [] : [diagnostic];
81
99
  });
100
+ const written = diagnostics.filter((d) => REPAIRED_BY_WRITE(d.category));
101
+ // The command first: it clears its share in one run, and the edits are what is left after it.
102
+ return [
103
+ ...(written.length === 0 ? [] : [writeFinding(written)]),
104
+ ...diagnostics.filter((d) => !REPAIRED_BY_WRITE(d.category)).map(editFinding),
105
+ ];
82
106
  }
83
107
 
84
108
  /**
@@ -0,0 +1,107 @@
1
+ // The CLI's answers to `@ultimat3/mcp`'s `DevAgentHost`, each from the command that already owns
2
+ // the question: `docs.search` is `x docs`, `db.explain`'s production refusal is `x explain`'s,
3
+ // `requests.statements` is `x dev`'s ledger read off its own `/_x/timeline`, and `verify.narrow` is
4
+ // `x verify --changed`'s planner asked about one file. Nothing here is a second implementation.
5
+
6
+ // why: Bun has no path API; an MCP `file` argument may be absolute or `./`-led, the planner reads
7
+ // app-relative POSIX paths.
8
+ import { relative, resolve } from 'node:path';
9
+ import { NotImplementedError, renderFixShellArg, UltimateError } from '@ultimat3/core';
10
+ import { docsCommand } from './cmd-docs';
11
+ import type { Runner } from './exec';
12
+ import { readsAsProduction } from './mcp-db-target';
13
+ import type { ParsedArgs } from './parse';
14
+ import type { DevServices, Env } from './runtime-bindings';
15
+ import { planChangedSteps } from './verify-changed';
16
+ import { readChangedFacts } from './verify-changed-facts';
17
+ import { VERIFY_STEP_NAMES } from './verify-step';
18
+
19
+ /**
20
+ * `x explain`'s own rule (`cmd-explain.ts`): an embedded database is always a dev one, an external
21
+ * one is planned only where the environment does not read as production. `db.explain` with
22
+ * `analyze: true` executes the statement, so it inherits the refusal whole — and its code.
23
+ */
24
+ export function assertExplainTarget(services: DevServices, env: Env): void {
25
+ if (services.db.mode !== 'external' || !readsAsProduction(env)) return;
26
+ throw new UltimateError({
27
+ code: 'X_EXPLAIN_PRODUCTION_DATABASE',
28
+ cause:
29
+ 'DATABASE_URL names an external database and this environment reads as production, where db.explain would plan — and with analyze, run — the statement for real',
30
+ fix: 'env -u DATABASE_URL x mcp serve --transport stdio # db.explain then plans on the embedded dev database; for production data, a staging restore with ULTIMATE_ENV=staging',
31
+ });
32
+ }
33
+
34
+ /**
35
+ * `x docs <query> --limit <n> --json`, run in this process. The args are built, never parsed:
36
+ * a question that starts with `-` is a question, and `parseArgs` would read it as a flag.
37
+ */
38
+ export async function searchDocs(
39
+ ctx: { readonly root: string; readonly env: Env; readonly runner: Runner },
40
+ query: string,
41
+ limit: number,
42
+ ): Promise<unknown> {
43
+ const args: ParsedArgs = {
44
+ command: 'docs',
45
+ subcommand: undefined,
46
+ positionals: [query],
47
+ flags: new Map([['limit', String(limit)]]),
48
+ json: true,
49
+ help: false,
50
+ passthrough: [],
51
+ };
52
+ const result = await docsCommand.run({
53
+ args,
54
+ cwd: ctx.root,
55
+ env: ctx.env,
56
+ runner: ctx.runner,
57
+ bunVersion: Bun.version,
58
+ });
59
+ return {
60
+ ok: result.ok,
61
+ summary: result.summary,
62
+ data: result.data ?? null,
63
+ findings: result.findings ?? [],
64
+ };
65
+ }
66
+
67
+ const toPosix = (path: string): string => path.split('\\').join('/');
68
+
69
+ /**
70
+ * What to run after editing `file`: the steps `x verify --changed` would select for it alone, and
71
+ * the narrowest commands that run them. A path outside the app, or one no rule speaks for,
72
+ * selects every step — the planner fails open, and so does this answer.
73
+ */
74
+ export async function narrowVerify(root: string, file: string): Promise<unknown> {
75
+ const path = toPosix(relative(resolve(root), resolve(root, file)));
76
+ const plan = planChangedSteps([path], await readChangedFacts(root));
77
+ const rule = plan.files[0]?.rule ?? 'unknown';
78
+ const steps = plan.steps.map((step) => step.name);
79
+ const shown = renderFixShellArg(path, '<file>');
80
+ const whole = steps.length === VERIFY_STEP_NAMES.length;
81
+ const verify = whole ? 'x verify --json' : `x verify --only ${steps.join(',')} --json`;
82
+ // Read off the steps, never off the rule's name: the planner gains rules (`page`), and a test
83
+ // suite among the steps is what says the file's tests are worth running first.
84
+ const tests =
85
+ rule === 'test'
86
+ ? [`x test --filter ${shown} --json`]
87
+ : !whole && steps.includes('unit')
88
+ ? ['x test --affected --dirty --json']
89
+ : [];
90
+ return {
91
+ file: path,
92
+ rule,
93
+ steps,
94
+ // Tests first: they are the fastest red, and the verify line re-runs them inside the gate.
95
+ commands: steps.length === 0 ? [] : [...tests, verify],
96
+ whole: 'x verify --changed --dirty --json',
97
+ };
98
+ }
99
+
100
+ /** `requests.statements` against no running `x dev` — the ledger lives in that process alone. */
101
+ export function devNotRunning(): NotImplementedError {
102
+ return new NotImplementedError({
103
+ cause:
104
+ 'requests.statements without a running x dev is not implemented in this build: the statement ledger lives in that process',
105
+ fix: 'x dev # then make the request, and call requests.statements again',
106
+ });
107
+ }
package/src/mcp-errors.ts CHANGED
@@ -398,6 +398,10 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
398
398
  'x db migrate --json # the fresh database has no tables yet; then x db seed --json if the app declares a seed. The moved directory (meta.aside) is kept: delete it once its rows are not needed',
399
399
  X_EXPLAIN_PRODUCTION_DATABASE:
400
400
  'env -u DATABASE_URL x queries list --json # then the same prefix on x explain <query> --json: it plans on the embedded dev database; for a copy of production data, point DATABASE_URL at a staging restore with ULTIMATE_ENV=staging',
401
+ X_DB_INDEX_UNDECLARED:
402
+ 'x verify --only drift --json # each X_DB_INDEX_UNDECLARED warning names the index: its DROP INDEX CONCURRENTLY IF EXISTS "<name>"; goes in a new hand-written migration (-- transaction: false), or declare it in the entity\'s indexes: [...] and x db gen "<change>"',
403
+ X_SHIPPED_GUARD_MISSING:
404
+ "x doctor --json # each X_SHIPPED_GUARD_MISSING warning's fix is the command that writes its guard, then x verify --only boundaries --json",
401
405
  };
402
406
 
403
407
  const isCliCode = (code: string): code is CliErrorCode =>
package/src/mcp-host.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  ROLES,
16
16
  renderFixShellArg,
17
17
  renderThrowable,
18
+ retryMemo,
18
19
  UltimateError,
19
20
  } from '@ultimat3/core';
20
21
  import type { DbClient } from '@ultimat3/db';
@@ -43,15 +44,17 @@ import { appManifest, policyFacts } from './app-manifest';
43
44
  import { loadAppRuntime } from './app-runtime';
44
45
  import { loadAppGraph, resolveNode } from './cmd-graph-load';
45
46
  import { declareDevEnvironment, needsDevEnvironmentDeclaration } from './dev-environment';
47
+ import { liveDevLock } from './dev-lock';
46
48
  import { loadCodeFixes } from './error-fixes';
47
49
  import { BadFlagError } from './errors';
48
50
  import type { Runner } from './exec';
51
+ import { assertExplainTarget, devNotRunning, narrowVerify, searchDocs } from './mcp-agent-host';
49
52
  import { databaseTarget } from './mcp-db-target';
50
53
  import { explainErrorCode } from './mcp-errors';
51
54
  import { type ShellRunInput, shellRunner, shellTests, shellVerify } from './mcp-host-shell';
55
+ import { requestStatements } from './mcp-request-statements';
52
56
  import { type UiCapabilities, uiCapabilities } from './mcp-ui';
53
57
  import { readMigrations } from './migrations';
54
- import { retryMemo } from './retry-memo';
55
58
  import { plainAppRoutes, routeRows } from './route-table';
56
59
  import type { DevServices, Env } from './runtime-bindings';
57
60
  import { resolveServices } from './runtime-bindings';
@@ -285,6 +288,25 @@ function capabilities(
285
288
  return readOnlyRows(db, sql, limits, await readOnlyRole.get());
286
289
  },
287
290
 
291
+ // `db.query`'s layers 1–2 again, behind `x explain`'s production refusal: with `analyze` the
292
+ // plan is executed, so a production database is refused before any connection is opened.
293
+ async explainQuery(statement: string, limits: QueryLimits): Promise<QueryRows> {
294
+ assertExplainTarget(lazy.services, input.env);
295
+ const { db } = await lazy.running();
296
+ return readOnlyRows(db, statement, limits, await readOnlyRole.get());
297
+ },
298
+
299
+ searchDocs: (query: string, limit: number) => searchDocs(input, query, limit),
300
+
301
+ async requestStatements(ask) {
302
+ // The lock `x dev` writes names its URL; a missing or stale one is no server to ask.
303
+ const lock = liveDevLock(lazy.services.stateDir);
304
+ if (lock === undefined) throw devNotRunning();
305
+ return requestStatements({ devUrl: lock.url, ...ask });
306
+ },
307
+
308
+ narrowVerify: (file: string) => narrowVerify(root, file),
309
+
288
310
  async runMigrations(branch: string, dryRun: boolean) {
289
311
  const before = await pendingIds(root, lazy);
290
312
  if (dryRun) return { branch, applied: [], pending: before };
@@ -0,0 +1,129 @@
1
+ // `requests.statements`: the running `x dev`'s per-request statement counts and N+1 verdicts, read
2
+ // off its own `/_x/timeline` JSON — the panel that already projects the recorder and the ledger
3
+ // (`dev-n-plus-one.ts`). The ledger lives in that process, so this asks it; it never keeps a copy.
4
+
5
+ import { renderThrowable, UltimateError } from '@ultimat3/core';
6
+ import { t } from '@ultimat3/schema';
7
+
8
+ /** What one timeline answer is parsed into: only the fields this tool reports. */
9
+ const SPAN = t.object({ kind: t.string });
10
+ const TRACE = t.object({
11
+ requestId: t.string,
12
+ method: t.string,
13
+ path: t.string,
14
+ status: t.number,
15
+ spans: t.array(SPAN),
16
+ });
17
+ const TIMELINE = t.object({
18
+ requests: t.array(t.object({ requestId: t.string, path: t.string, totalMs: t.number })),
19
+ selected: t.nullable(TRACE),
20
+ repeatedSql: t.array(t.object({ sql: t.string, count: t.number })),
21
+ nPlusOne: t.nullable(t.array(t.json())),
22
+ });
23
+ const PAYLOAD = t.object({
24
+ ok: t.boolean,
25
+ data: t.optional(t.json()),
26
+ error: t.optional(t.object({ code: t.string, cause: t.string, fix: t.string })),
27
+ });
28
+
29
+ /** One GET of the dev server, answered as parsed JSON. A seam so a test needs no server. */
30
+ export type FetchJson = (url: string) => Promise<unknown>;
31
+
32
+ const restart = 'x stop --json && x dev # the running x dev did not answer as this CLI expects';
33
+
34
+ export const fetchJson: FetchJson = async (url) => {
35
+ try {
36
+ return (await (
37
+ await fetch(url, {
38
+ headers: { accept: 'application/json' },
39
+ // A local dev server answers in milliseconds; a wedged one must not hold the tool.
40
+ signal: AbortSignal.timeout(5_000),
41
+ })
42
+ ).json()) as unknown;
43
+ } catch (error) {
44
+ throw new UltimateError({
45
+ code: 'X_CLI_UNEXPECTED',
46
+ cause: `requests.statements could not read ${url}: ${renderThrowable(error)}`,
47
+ fix: restart,
48
+ });
49
+ }
50
+ };
51
+
52
+ interface Timeline {
53
+ readonly requests: readonly { readonly requestId: string }[];
54
+ readonly selected: {
55
+ readonly requestId: string;
56
+ readonly method: string;
57
+ readonly path: string;
58
+ readonly status: number;
59
+ readonly spans: readonly { readonly kind: string }[];
60
+ } | null;
61
+ readonly repeatedSql: readonly { readonly sql: string; readonly count: number }[];
62
+ readonly nPlusOne: readonly unknown[] | null;
63
+ }
64
+
65
+ /** One panel read: the panel's own refusal passes through with its code, cause and fix. */
66
+ async function timeline(get: FetchJson, base: string, requestId?: string): Promise<Timeline> {
67
+ const query = requestId === undefined ? '' : `&requestId=${encodeURIComponent(requestId)}`;
68
+ const url = `${base}/_x/timeline?json=1${query}`;
69
+ const payload = PAYLOAD.safeParse(await get(url));
70
+ if (payload.issues !== undefined) {
71
+ throw new UltimateError({
72
+ code: 'X_CLI_UNEXPECTED',
73
+ cause: `requests.statements read ${url} and it is not a /_x panel answer`,
74
+ fix: restart,
75
+ });
76
+ }
77
+ const { ok, data, error } = payload.value;
78
+ if (!ok && error !== undefined) throw new UltimateError(error);
79
+ const parsed = TIMELINE.safeParse(data);
80
+ if (parsed.issues !== undefined) {
81
+ throw new UltimateError({
82
+ code: 'X_CLI_UNEXPECTED',
83
+ cause: `requests.statements read ${url} and its timeline is not the shape this CLI reads`,
84
+ fix: restart,
85
+ });
86
+ }
87
+ return parsed.value;
88
+ }
89
+
90
+ /** The selected request, as the tool reports it — `null` verdicts mean no ledger, not no loops. */
91
+ function requestFacts(view: Timeline): unknown {
92
+ const selected = view.selected;
93
+ if (selected === null) return null;
94
+ return {
95
+ requestId: selected.requestId,
96
+ method: selected.method,
97
+ path: selected.path,
98
+ status: selected.status,
99
+ statements: selected.spans.filter((span) => span.kind === 'sql').length,
100
+ repeated: view.repeatedSql,
101
+ nPlusOne: view.nPlusOne,
102
+ };
103
+ }
104
+
105
+ /**
106
+ * `requestId` given: that request. Absent: the newest `limit`, newest first — one panel read per
107
+ * request, because the panel counts statements for the request it is asked about and no other.
108
+ */
109
+ export async function requestStatements(
110
+ input: {
111
+ readonly devUrl: string;
112
+ readonly requestId: string | undefined;
113
+ readonly limit: number;
114
+ },
115
+ get: FetchJson = fetchJson,
116
+ ): Promise<unknown> {
117
+ const first = await timeline(get, input.devUrl, input.requestId);
118
+ if (input.requestId !== undefined) {
119
+ const found = first.selected?.requestId === input.requestId ? [requestFacts(first)] : [];
120
+ // A request the recorder no longer holds answers the ones it does, never a bare empty list.
121
+ return found.length > 0
122
+ ? { devUrl: input.devUrl, requests: found }
123
+ : { devUrl: input.devUrl, requests: [], known: first.requests.map((r) => r.requestId) };
124
+ }
125
+ const rest = first.requests.slice(1, input.limit).map((request) => request.requestId);
126
+ const others = await Promise.all(rest.map((id) => timeline(get, input.devUrl, id)));
127
+ const requests = [first, ...others].map(requestFacts).filter((request) => request !== null);
128
+ return { devUrl: input.devUrl, requests };
129
+ }
package/src/mcp-ui.ts CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
  // why: Bun exposes no path-join primitive, and the picture's directory is a path an agent opens.
12
12
  import { join } from 'node:path';
13
- import { finiteCount, UltimateError } from '@ultimat3/core';
13
+ import { finiteCount, retryMemo, UltimateError } from '@ultimat3/core';
14
14
  import type {
15
15
  UiDiffInput,
16
16
  UiDiffResult,
@@ -33,7 +33,6 @@ import { islandVerdictJson } from './island-verdict';
33
33
  import { diffShots } from './mcp-ui-diff';
34
34
  import { inspectRoute } from './mcp-ui-inspect';
35
35
  import { interactRoute } from './mcp-ui-interact';
36
- import { retryMemo } from './retry-memo';
37
36
  import type { Env } from './runtime-bindings';
38
37
  import { shotBrowserChoice } from './shot-browser';
39
38
  import { devServerFor, type ShotServer } from './shot-server';
package/src/messages.ts CHANGED
@@ -94,8 +94,6 @@ const CATALOG = {
94
94
  'cli.doctor.poolerWakeOff':
95
95
  'wake off, pickup within idlePollMaxMs ({ms} ms by default): a transaction pooler delivers no notification. For the wake, give this role a direct or session-pooled DATABASE_URL and unset DATABASE_POOLER',
96
96
  'cli.doctor.findings': '{count} finding(s)',
97
- 'cli.doctor.guards':
98
- '{count} shipped guard(s) this app does not hold — each line adds one, then x verify reports what it finds:',
99
97
  'cli.doctor.guardsDiffer':
100
98
  '{count} shipped guard(s) differ from the current template — an older copy or your own edit; each line rewrites one and its test, review the diff before keeping it:',
101
99
  // `x doctor`'s other listing: what the coverage floor in x.verify.json does not see, and why.
@@ -78,11 +78,18 @@ export interface CacheTiersOptions {
78
78
  readonly supplied?: readonly CacheTier[] | undefined;
79
79
  /** The wait before re-subscribing after `attempt` failures (1-based). Injected by a test. */
80
80
  readonly subscribeRetryMs?: ((attempt: number) => number) | undefined;
81
+ /**
82
+ * How that wait is slept. Default `Bun.sleep`; a test hands one that resolves when it turns the
83
+ * loop, so a retry is counted rather than timed.
84
+ */
85
+ readonly subscribeRetryWait?: ((ms: number) => Promise<unknown>) | undefined;
81
86
  /**
82
87
  * How long the boot subscribe may be refused before a refusal is worth a warning. Default
83
88
  * `FIRST_DIAL_GRACE_MS`; a test of an OUTAGE passes 0.
84
89
  */
85
90
  readonly firstDialGraceMs?: number | undefined;
91
+ /** The monotonic clock that window is read on. Default `performance.now`; a test injects one. */
92
+ readonly monotonicNow?: (() => number) | undefined;
86
93
  /** The client a `redis` rung reads, for the URL `env` names. Default core's `redisClient`. */
87
94
  readonly redisClient?: ((url: string) => RedisLike) | undefined;
88
95
  /**
@@ -335,12 +342,14 @@ export function startCacheTiers(options: CacheTiersOptions): () => Promise<void>
335
342
  /** Cuts the retry's wait short: the bus coming up is a better signal than a backoff. */
336
343
  let wake: () => void = () => undefined;
337
344
  const retryMs = options.subscribeRetryMs ?? defaultSubscribeRetryMs;
345
+ const retryWait = options.subscribeRetryWait ?? ((ms: number) => Bun.sleep(ms));
338
346
  // This process heard no peer for a window nobody measured — since boot, or since the connection
339
347
  // dropped — so nothing it holds in its own heap is known fresh. One cold cache, never a stale one.
340
348
  const flushDeaf = (source: string): void => {
341
349
  void flushProcessTiers(source);
342
350
  };
343
- const bootedAt = performance.now();
351
+ const now = options.monotonicNow ?? (() => performance.now());
352
+ const bootedAt = now();
344
353
  /** Whether an operator has been told of this outage — what makes `recovered` worth a line. */
345
354
  let warned = false;
346
355
  const subscribing = (async (): Promise<InvalidationSubscription | undefined> => {
@@ -364,7 +373,7 @@ export function startCacheTiers(options: CacheTiersOptions): () => Promise<void>
364
373
  // one line per retry per pod for as long as it lasts.
365
374
  // Silent inside the first dial's window. Past it, the FIRST refusal warns whatever its
366
375
  // attempt number, then the milestones thin the rest.
367
- const inGrace = performance.now() - bootedAt < graceMs;
376
+ const inGrace = now() - bootedAt < graceMs;
368
377
  if (!inGrace && (!warned || isOutageMilestone(attempt))) {
369
378
  warned = true;
370
379
  logger.warn('cache.broadcast.subscribe-failed', {
@@ -374,7 +383,7 @@ export function startCacheTiers(options: CacheTiersOptions): () => Promise<void>
374
383
  }
375
384
  const woken = Promise.withResolvers<undefined>();
376
385
  wake = (): void => woken.resolve(undefined);
377
- await Promise.race([Bun.sleep(retryMs(attempt)), released.promise, woken.promise]);
386
+ await Promise.race([retryWait(retryMs(attempt)), released.promise, woken.promise]);
378
387
  }
379
388
  }
380
389
  return undefined;