@ultimat3/cli 31.21.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.
- package/CLAUDE.md +1 -1
- package/README.md +11 -6
- package/package.json +29 -29
- package/src/cmd-db.ts +5 -18
- package/src/cmd-doctor.ts +8 -3
- package/src/cmd-mcp.ts +6 -1
- package/src/cmd-verify.ts +19 -15
- package/src/db-schema-dump.ts +20 -0
- package/src/dev-lock.ts +26 -5
- package/src/doctor-guards.ts +27 -12
- package/src/error-codes-doctor.ts +6 -4
- package/src/guards.ts +66 -28
- package/src/lint-findings.ts +34 -10
- package/src/mcp-agent-host.ts +107 -0
- package/src/mcp-errors.ts +2 -0
- package/src/mcp-host.ts +22 -0
- package/src/mcp-request-statements.ts +129 -0
- package/src/messages.ts +0 -2
- package/src/runtime-cache.ts +12 -3
- package/src/templates/guard-repo-await-in-loop-test.ts +89 -0
- package/src/templates/guard-repo-await-in-loop.ts +214 -0
- package/src/templates/guard-repo-unbounded-test.ts +56 -0
- package/src/templates/guard-repo-unbounded.ts +197 -0
- package/src/templates/scaffold-claude-agents.ts +4 -4
- package/src/templates/scaffold-claude-hook.ts +40 -0
- package/src/templates/scaffold-claude.ts +22 -6
- package/src/templates/scaffold-docs.ts +2 -7
- package/src/templates/scaffold-guards.ts +6 -0
- package/src/verify-changed.ts +32 -5
- package/src/verify-checks.ts +14 -6
- package/src/verify-progress.ts +32 -1
- package/wiki/CLI-Reference.md +19 -8
- package/wiki/MCP-And-AI.md +7 -3
- package/wiki/Tutorial-02-First-Feature.md +1 -1
- package/wiki/Upgrading.md +6 -0
package/src/lint-findings.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
// `biome check --reporter=json` read as findings
|
|
2
|
-
//
|
|
3
|
-
//
|
|
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
|
|
57
|
-
|
|
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:
|
|
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
|
-
|
|
96
|
+
const diagnostics = report['diagnostics'].flatMap((value) => {
|
|
79
97
|
const diagnostic = diagnosticFrom(value);
|
|
80
|
-
return diagnostic === undefined ? [] : [
|
|
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
|
@@ -400,6 +400,8 @@ const CLI_FIXES: Readonly<Record<CliErrorCode, string>> = {
|
|
|
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
401
|
X_DB_INDEX_UNDECLARED:
|
|
402
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",
|
|
403
405
|
};
|
|
404
406
|
|
|
405
407
|
const isCliCode = (code: string): code is CliErrorCode =>
|
package/src/mcp-host.ts
CHANGED
|
@@ -44,12 +44,15 @@ import { appManifest, policyFacts } from './app-manifest';
|
|
|
44
44
|
import { loadAppRuntime } from './app-runtime';
|
|
45
45
|
import { loadAppGraph, resolveNode } from './cmd-graph-load';
|
|
46
46
|
import { declareDevEnvironment, needsDevEnvironmentDeclaration } from './dev-environment';
|
|
47
|
+
import { liveDevLock } from './dev-lock';
|
|
47
48
|
import { loadCodeFixes } from './error-fixes';
|
|
48
49
|
import { BadFlagError } from './errors';
|
|
49
50
|
import type { Runner } from './exec';
|
|
51
|
+
import { assertExplainTarget, devNotRunning, narrowVerify, searchDocs } from './mcp-agent-host';
|
|
50
52
|
import { databaseTarget } from './mcp-db-target';
|
|
51
53
|
import { explainErrorCode } from './mcp-errors';
|
|
52
54
|
import { type ShellRunInput, shellRunner, shellTests, shellVerify } from './mcp-host-shell';
|
|
55
|
+
import { requestStatements } from './mcp-request-statements';
|
|
53
56
|
import { type UiCapabilities, uiCapabilities } from './mcp-ui';
|
|
54
57
|
import { readMigrations } from './migrations';
|
|
55
58
|
import { plainAppRoutes, routeRows } from './route-table';
|
|
@@ -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/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.
|
package/src/runtime-cache.ts
CHANGED
|
@@ -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
|
|
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 =
|
|
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([
|
|
386
|
+
await Promise.race([retryWait(retryMs(attempt)), released.promise, woken.promise]);
|
|
378
387
|
}
|
|
379
388
|
}
|
|
380
389
|
return undefined;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// The test `x new` writes beside the `repo-await-in-loop` guard: the rule's own cases, run in the
|
|
2
|
+
// app. Split from `guard-repo-await-in-loop.ts` at the file target; the code is handed in.
|
|
3
|
+
|
|
4
|
+
export const repoAwaitInLoopTest = (
|
|
5
|
+
code: string,
|
|
6
|
+
): string => `// The rule, driven directly. Failure case first: a guard whose rule silently stopped matching is
|
|
7
|
+
// a green gate over the convention it was written to enforce.
|
|
8
|
+
|
|
9
|
+
import { expect, unitTest } from '@ultimat3/testing';
|
|
10
|
+
import { awaitsInLoops } from './repo-await-in-loop';
|
|
11
|
+
|
|
12
|
+
const REPO = 'apps/web/app/posts/repo.ts';
|
|
13
|
+
const repo = (...lines: readonly string[]) => [{ path: REPO, source: lines.join('\\n') }];
|
|
14
|
+
|
|
15
|
+
unitTest('an await in a for body is refused at its line, naming the loop', () => {
|
|
16
|
+
const findings = awaitsInLoops(
|
|
17
|
+
repo(
|
|
18
|
+
'export const touch = async (ids: string[]) => {',
|
|
19
|
+
' for (const id of ids) {',
|
|
20
|
+
' await db.posts.update(id, { seen: true });',
|
|
21
|
+
' }',
|
|
22
|
+
'};',
|
|
23
|
+
),
|
|
24
|
+
);
|
|
25
|
+
expect(findings).toHaveLength(1);
|
|
26
|
+
expect(findings[0]?.code).toBe('${code}');
|
|
27
|
+
expect(findings[0]?.at).toBe(\`\${REPO}:3\`);
|
|
28
|
+
expect(findings[0]?.cause).toContain(\`the for at \${REPO}:2\`);
|
|
29
|
+
expect(findings[0]?.fix).toStartWith(
|
|
30
|
+
"db.<table>.andWhere('id', 'in', ids).limit(ids.length).all()",
|
|
31
|
+
);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
unitTest('a while condition, a do body, a brace-less for and a callback are the same rule', () => {
|
|
35
|
+
expect(awaitsInLoops(repo('while (await db.jobs.claim()) count += 1;'))).toHaveLength(1);
|
|
36
|
+
expect(
|
|
37
|
+
awaitsInLoops(repo('do {', ' row = await db.jobs.next();', '} while (row);')),
|
|
38
|
+
).toHaveLength(1);
|
|
39
|
+
expect(awaitsInLoops(repo('for (const id of ids) await db.posts.delete(id);'))).toHaveLength(1);
|
|
40
|
+
const each = repo('ids.forEach(async (id) => {', ' await db.posts.delete(id);', '});');
|
|
41
|
+
expect(awaitsInLoops(each)[0]?.cause).toContain('the .forEach at');
|
|
42
|
+
expect(
|
|
43
|
+
awaitsInLoops(repo('rows.map(async (row) => await db.tags.byId(row.tagId));')),
|
|
44
|
+
).toHaveLength(1);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
unitTest('one finding per loop, at the innermost loop holding the await', () => {
|
|
48
|
+
const nested = repo(
|
|
49
|
+
'for (const a of as) {',
|
|
50
|
+
' for (const b of bs) {',
|
|
51
|
+
' await db.x.insert({ a, b });',
|
|
52
|
+
' await db.y.insert({ a, b });',
|
|
53
|
+
' }',
|
|
54
|
+
'}',
|
|
55
|
+
);
|
|
56
|
+
const findings = awaitsInLoops(nested);
|
|
57
|
+
expect(findings).toHaveLength(1);
|
|
58
|
+
expect(findings[0]?.cause).toContain(\`the for at \${REPO}:2\`);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
unitTest(
|
|
62
|
+
'a loop under expectedQueryLoop, an await outside the loop and a for-await header are silent',
|
|
63
|
+
() => {
|
|
64
|
+
const declared = repo(
|
|
65
|
+
"expectedQueryLoop('one indexed lookup per field', async () => {",
|
|
66
|
+
' for (const f of fields) await db.posts.where({ [f]: term }).limit(5).all();',
|
|
67
|
+
'});',
|
|
68
|
+
);
|
|
69
|
+
expect(awaitsInLoops(declared)).toEqual([]);
|
|
70
|
+
expect(
|
|
71
|
+
awaitsInLoops(
|
|
72
|
+
repo(
|
|
73
|
+
'const rows = await db.posts.limit(10).all();',
|
|
74
|
+
'for (const row of rows) total += row.n;',
|
|
75
|
+
),
|
|
76
|
+
),
|
|
77
|
+
).toEqual([]);
|
|
78
|
+
expect(awaitsInLoops(repo('await Promise.all(ids.map((id) => id.trim()));'))).toEqual([]);
|
|
79
|
+
expect(awaitsInLoops(repo('for await (const row of stream) total += row.n;'))).toEqual([]);
|
|
80
|
+
},
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
unitTest('a comment and a string naming the shape are not code', () => {
|
|
84
|
+
expect(awaitsInLoops(repo('// for (const id of ids) await db.x.delete(id);'))).toEqual([]);
|
|
85
|
+
expect(awaitsInLoops(repo("const s = 'for (const id of ids) await db.x.delete(id)';"))).toEqual(
|
|
86
|
+
[],
|
|
87
|
+
);
|
|
88
|
+
});
|
|
89
|
+
`;
|