@ultimat3/cli 31.15.0 → 31.16.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.
@@ -31,6 +31,19 @@ export const UPGRADE_MESSAGES = {
31
31
  'cli.upgrade.done': '{from} -> {to}: the gate is green',
32
32
  'cli.upgrade.dryRun': '{from} -> {to}: nothing written, no gate run',
33
33
  'cli.upgrade.guard': 'guard, yours to take or leave: {fix}',
34
+ 'cli.upgrade.guardInstalled':
35
+ 'guard installed: guards/{name}.ts, from this release (delete the file to drop the rule)',
36
+ 'cli.upgrade.guardWithheld':
37
+ 'guard not installed, the tree breaks it in {count} place(s) — yours to take: {fix}',
38
+ 'cli.upgrade.guardUnmeasured':
39
+ 'guard not installed, its findings could not be counted — yours to take: {fix}',
40
+ 'cli.upgrade.coverage':
41
+ 'coverage floor: {file} {fromLines} / {fromFuncs} -> {toLines} / {toFuncs}, measured {lines}% / {funcs}% after the Bun floor moved — review the why',
42
+ 'cli.upgrade.exerciseFloor':
43
+ 'exercise floor: {file} "exercise" {figures}, measured by this hop\'s x exercise — it may only fall',
44
+ 'cli.upgrade.coverage.unpinned': 'no engines.bun',
45
+ 'cli.upgrade.coverage.why':
46
+ 'Rebaselined {date} by x upgrade to {release}: Bun {bunFrom} -> {bunTo}, with no test or source changed, measured {lines}% of lines and {funcs}% of functions, so the floor moves from {fromLines} / {fromFuncs} to {toLines} / {toFuncs}.',
34
47
  'cli.upgrade.read': 'read: {title} — {url}',
35
48
  'cli.upgrade.red': '{from} -> {to}: not done, the gate says: {summary}',
36
49
  'cli.upgrade.stillRunning': 'x upgrade: still in {stage} ({elapsed})',
package/src/messages.ts CHANGED
@@ -104,6 +104,9 @@ const CATALOG = {
104
104
  // `x doctor`'s reminder: the rolling rail is off until this key is set (`doctor-rolling.ts`).
105
105
  'cli.doctor.rollingSince':
106
106
  'the rolling-deploy rail is off: set "rollingSince": "{newest}" in x.verify.json to judge every migration after your newest',
107
+ // `x doctor`'s warnings: beside the verdict on `main`, red on `next` (`doctor-warnings.ts`).
108
+ 'cli.doctor.warnings': '{count} warning(s) — not in the verdict until the next major:',
109
+ 'cli.doctor.warning': ' {code}: {cause} — fix: {fix}',
107
110
  'cli.docs.code': '{code} is an error code — x errors explain answers it',
108
111
  'cli.docs.exports': 'exports: {list}',
109
112
  'cli.docs.installed': 'installed: {list}',
@@ -1,6 +1,7 @@
1
1
  // `x new`'s `x.verify.json`: the suite floor and the coverage bar every scaffolded app starts on.
2
2
  // Split from `scaffold-repo.ts` (the repo's root files), which had reached the 500-line ceiling.
3
3
 
4
+ import { STATEMENTS_MAX } from '@ultimat3/testing';
4
5
  import type { CoverageExclude } from '../coverage-floor';
5
6
  import { COVERAGE_BAR } from '../coverage-floor';
6
7
  import type { VerifyStepName } from '../verify-step';
@@ -91,6 +92,9 @@ export const verifyFloor = (example: boolean): string =>
91
92
  },
92
93
  // The rolling rail judges from the first migration: a new app has nothing to grandfather.
93
94
  rollingSince: '0',
95
+ // Nor does the exercise pass: every proof must ask, and one call sends the default ceiling
96
+ // at most. An app scaffolded before this key reads warnings instead (`exercise-floor.ts`).
97
+ exercise: { unprovenMax: 0, statementsMax: STATEMENTS_MAX },
94
98
  },
95
99
  null,
96
100
  2,
@@ -27,6 +27,18 @@ import { readFileSync } from 'node:fs'; // why: Bun ships no synchronous file re
27
27
  // why: Bun exposes no path-join primitive.
28
28
  import { join } from 'node:path';
29
29
 
30
+ /**
31
+ * Keys that LOCATE something on this host and never change what the app does: a browser binary
32
+ * (`browser-launcher.ts`'s `BROWSER_PATH_VARS`, restated so this file does not load the CDP driver
33
+ * graph; `test-dotenv.test.ts` pins the two lists together) and the temp directory. Scrubbing one
34
+ * because `.env.development` happens to name it only breaks the child — e2e stops finding Chrome.
35
+ */
36
+ export const HOST_LOCATOR_KEYS: readonly string[] = [
37
+ 'PUPPETEER_EXECUTABLE_PATH',
38
+ 'CHROME_PATH',
39
+ 'TMPDIR',
40
+ ];
41
+
30
42
  /** Bun's own grammar, matched against `env-example.ts`'s `ENV_KEY_RE` (kept separate: see header). */
31
43
  const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
32
44
 
@@ -72,14 +84,15 @@ export interface DevOnlyLeakInput {
72
84
 
73
85
  /**
74
86
  * The pure decision, no filesystem: every key `.env.development`/`.env.development.local` would
75
- * set, where `env`'s CURRENT value for that key is exactly what the file would have set. See this
76
- * file's header for why a legitimate test file declaring the same key does not exempt it.
87
+ * set, where `env`'s CURRENT value for that key is exactly what the file would have set — a
88
+ * `HOST_LOCATOR_KEYS` member excepted. See this file's header for why a legitimate test file declaring the same key does not exempt it.
77
89
  */
78
90
  export function devOnlyLeakedKeys(input: DevOnlyLeakInput): readonly string[] {
79
91
  const merged = new Map(parseDotenvValues(input.devText));
80
92
  for (const [key, value] of parseDotenvValues(input.devLocalText)) merged.set(key, value);
81
93
  const leaked: string[] = [];
82
94
  for (const [key, devValue] of merged) {
95
+ if (HOST_LOCATOR_KEYS.includes(key)) continue;
83
96
  // `Object.hasOwn` FIRST: `key` is data (a name out of a dotenv file), and `env['constructor']`
84
97
  // on a plain object answers `Object.prototype`'s member, not `undefined` — the rule
85
98
  // `scripts/proto-index.ts` ratchets, with its own sanctioned repair.
@@ -0,0 +1,109 @@
1
+ // A Bun-floor hop's coverage rebaseline: Bun 1.4.4 counted functions differently with no test or
2
+ // source changed, so a hop that moves the Bun floor measures the unit suite once (the installed
3
+ // CLI's `verify --only unit`) and, only when that lands under the stated floor, moves the floor to
4
+ // what it measured with a dated `why`. Written into the hop's diff and reported, never silently.
5
+
6
+ // why: Bun exposes no path-join primitive; `x.verify.json` sits at the app root.
7
+ import { join } from 'node:path';
8
+ import { t } from '@ultimat3/schema';
9
+ import type { CoverageFloor } from './coverage-floor';
10
+ import { COVERAGE_FIELD, floorFor, readCoverageFloor, shown } from './coverage-floor';
11
+ import { msg } from './messages';
12
+ import { documentIn } from './upgrade-document';
13
+ import type { InstalledCli } from './upgrade-guards';
14
+ import { parseJson } from './upgrade-registry';
15
+ import { VERIFY_FLOOR_FILE } from './verify-floor';
16
+
17
+ const NUMBERS = t.object({ lines: t.number, funcs: t.number });
18
+ const UNIT = t.object({
19
+ steps: t.array(
20
+ t.object({
21
+ name: t.string,
22
+ findings: t.optional(t.array(t.object({ code: t.string }))),
23
+ }),
24
+ ),
25
+ data: t.object({ coverage: t.object({ unit: NUMBERS }) }),
26
+ });
27
+
28
+ interface Numbers {
29
+ readonly lines: number;
30
+ readonly funcs: number;
31
+ }
32
+
33
+ /** What the `why` says about the hop that moved the floor. */
34
+ export interface CoverageRebaseline {
35
+ readonly release: string;
36
+ readonly bunFrom: string | null;
37
+ readonly bunTo: string;
38
+ /** `YYYY-MM-DD`, UTC: the day the measurement was taken. */
39
+ readonly today: string;
40
+ }
41
+
42
+ /** What the report carries: the floor before, the one written, and the measurement behind it. */
43
+ export interface HopCoverage {
44
+ readonly file: string;
45
+ readonly measured: Numbers;
46
+ readonly from: Numbers;
47
+ readonly to: Numbers;
48
+ readonly why: string;
49
+ }
50
+
51
+ /** The app's floor file, as an object, with the coverage floor in it — or undefined: nothing to move. */
52
+ export async function statedCoverage(
53
+ root: string,
54
+ ): Promise<
55
+ { readonly payload: Record<string, unknown>; readonly floor: CoverageFloor } | undefined
56
+ > {
57
+ const file = Bun.file(join(root, VERIFY_FLOOR_FILE));
58
+ if (!(await file.exists())) return undefined;
59
+ const payload = parseJson(await file.text());
60
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return undefined;
61
+ const record = payload as Record<string, unknown>;
62
+ const floor = readCoverageFloor(record).coverage;
63
+ return floor === undefined ? undefined : { payload: record, floor };
64
+ }
65
+
66
+ /** Measures once; moves only the number that fell under its floor, and only to what was measured. */
67
+ export async function rebaselineCoverage(input: {
68
+ readonly cli: InstalledCli;
69
+ readonly root: string;
70
+ readonly stated: NonNullable<Awaited<ReturnType<typeof statedCoverage>>>;
71
+ readonly bun: CoverageRebaseline;
72
+ }): Promise<HopCoverage | null> {
73
+ const { cli, root, stated, bun } = input;
74
+ const parsed = UNIT.safeParse(
75
+ documentIn((await cli(['verify', '--only', 'unit', '--json'])).stdout),
76
+ );
77
+ if (parsed.issues !== undefined) return null;
78
+ const document = parsed.value as {
79
+ readonly steps: readonly { name: string; findings?: readonly { code: string }[] }[];
80
+ readonly data: { readonly coverage: { readonly unit: Numbers } };
81
+ };
82
+ const below = document.steps
83
+ .find((step) => step.name === 'unit')
84
+ ?.findings?.some((finding) => finding.code === 'X_COVERAGE_BELOW_FLOOR');
85
+ if (below !== true) return null;
86
+ const measured = document.data.coverage.unit;
87
+ const from = { lines: stated.floor.lines, funcs: stated.floor.funcs };
88
+ const to = {
89
+ lines: measured.lines < from.lines ? floorFor(measured.lines) : from.lines,
90
+ funcs: measured.funcs < from.funcs ? floorFor(measured.funcs) : from.funcs,
91
+ };
92
+ const said = msg('cli.upgrade.coverage.why', {
93
+ date: bun.today,
94
+ release: bun.release,
95
+ bunFrom: bun.bunFrom ?? msg('cli.upgrade.coverage.unpinned'),
96
+ bunTo: bun.bunTo,
97
+ lines: shown(measured.lines),
98
+ funcs: shown(measured.funcs),
99
+ fromLines: String(from.lines),
100
+ fromFuncs: String(from.funcs),
101
+ toLines: String(to.lines),
102
+ toFuncs: String(to.funcs),
103
+ });
104
+ const why = stated.floor.why === undefined ? said : `${said} ${stated.floor.why}`;
105
+ const raw = stated.payload[COVERAGE_FIELD] as Record<string, unknown>;
106
+ const next = { ...stated.payload, [COVERAGE_FIELD]: { ...raw, ...to, why } };
107
+ await Bun.write(join(root, VERIFY_FLOOR_FILE), `${JSON.stringify(next, null, 2)}\n`);
108
+ return { file: VERIFY_FLOOR_FILE, measured, from, to, why };
109
+ }
@@ -0,0 +1,18 @@
1
+ // The one JSON document on a child CLI's stdout, read as a foreign document: a hop's gate, the
2
+ // guards it installs and every caller that spawns an installed CLI share this one reading of it.
3
+
4
+ import { parseJson } from './upgrade-registry';
5
+
6
+ /**
7
+ * Whole first; then its last line that parses, because the CLI that keeps fd 1 to one document
8
+ * under `--json` is a recent one and a hop can install one that still logs a boot line ahead of it.
9
+ */
10
+ export function documentIn(stdout: string): unknown {
11
+ const whole = parseJson(stdout.trim());
12
+ if (whole !== undefined) return whole;
13
+ const lines = stdout.split('\n').filter((line) => line.trimStart().startsWith('{'));
14
+ return lines
15
+ .reverse()
16
+ .map(parseJson)
17
+ .find((parsed) => parsed !== undefined);
18
+ }
@@ -0,0 +1,53 @@
1
+ // A hop's exercise ratchet: after the hop's `x exercise` wrote `.x/exercise.json`, an app whose
2
+ // `x.verify.json` states no `exercise.unprovenMax` / `statementsMax` gets the figures that pass
3
+ // measured, so the floor starts where the app is and only falls. A key the app already wrote is
4
+ // never touched. Written into the hop's diff and reported, never silently.
5
+
6
+ // why: Bun exposes no path-join primitive; `x.verify.json` sits at the app root.
7
+ import { join } from 'node:path';
8
+ import type { ExerciseFloor } from './exercise-floor';
9
+ import { readExerciseFloor } from './exercise-floor';
10
+ import {
11
+ exerciseReportStamp,
12
+ measuredExerciseFloor,
13
+ withExerciseFloor,
14
+ } from './exercise-floor-report';
15
+ import { parseJson } from './upgrade-registry';
16
+ import { VERIFY_FLOOR_FILE } from './verify-floor';
17
+
18
+ /** What the report carries: the figures written, each one the hop's own pass measured. */
19
+ export interface HopExerciseFloor {
20
+ readonly file: string;
21
+ readonly written: ExerciseFloor;
22
+ }
23
+
24
+ /**
25
+ * Writes the measured figure for each exercise key the floor file lacks; null when none. `before`
26
+ * is the report's stamp ahead of the hop's `x exercise`: a report that pass did not rewrite (it
27
+ * died, or is a CLI with no report) holds another pass's figures and is never ratcheted.
28
+ */
29
+ export async function ratchetExerciseFloor(
30
+ root: string,
31
+ before: number | undefined,
32
+ ): Promise<HopExerciseFloor | null> {
33
+ const after = await exerciseReportStamp(root);
34
+ if (after === undefined || after === before) return null;
35
+ const file = Bun.file(join(root, VERIFY_FLOOR_FILE));
36
+ if (!(await file.exists())) return null;
37
+ const text = await file.text();
38
+ const payload = parseJson(text);
39
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return null;
40
+ const stated = readExerciseFloor(payload as Record<string, unknown>);
41
+ // A malformed key is the `manifest` step's finding; writing beside it would hide it.
42
+ if (stated.problems.length > 0) return null;
43
+ const measured = await measuredExerciseFloor(root);
44
+ if (measured === undefined) return null;
45
+ const written: { unprovenMax?: number; statementsMax?: number } = {};
46
+ if (stated.floor?.unprovenMax === undefined) written.unprovenMax = measured.unprovenMax;
47
+ if (stated.floor?.statementsMax === undefined) written.statementsMax = measured.statementsMax;
48
+ if (Object.keys(written).length === 0) return null;
49
+ const next = withExerciseFloor(text, written);
50
+ if (next === text) return null;
51
+ await Bun.write(join(root, VERIFY_FLOOR_FILE), next);
52
+ return { file: VERIFY_FLOOR_FILE, written };
53
+ }
@@ -1,16 +1,27 @@
1
- // A hop's gate, run by the CLI the hop just installed: `x manifest`, `x doctor --json`, `x exercise
2
- // --json`, `x verify --json`. Never in this process, because the installed CLI is the one that knows the installed
3
- // framework (`local-cli.ts`), and it may be many majors older than this one: each answer is read as
4
- // a foreign document, and one that will not parse is a finding, never a green.
1
+ // A hop's gate, run by the CLI the hop just installed: manifest, doctor, the missing guards and a
2
+ // Bun-floor hop's coverage (`upgrade-guards.ts`, `upgrade-coverage.ts`), exercise, verify. Never in
3
+ // this process: the installed CLI knows the installed framework (`local-cli.ts`) and may be majors
4
+ // older, so each answer is read as a foreign document, and one that will not parse is never green.
5
5
 
6
6
  // why: Bun exposes no path-join primitive; the installed bin is assembled from the app root.
7
7
  import { join } from 'node:path';
8
8
  import { t } from '@ultimat3/schema';
9
9
  import type { ExecResult, Runner } from './exec';
10
10
  import { execOutput } from './exec';
11
+ import { exerciseReportStamp } from './exercise-floor-report';
11
12
  import { LOCAL_CLI_BIN } from './local-cli';
13
+ import type { CoverageRebaseline, HopCoverage } from './upgrade-coverage';
14
+ import { rebaselineCoverage, statedCoverage } from './upgrade-coverage';
15
+ import { documentIn } from './upgrade-document';
16
+ import type { HopExerciseFloor } from './upgrade-exercise-floor';
17
+ import { ratchetExerciseFloor } from './upgrade-exercise-floor';
18
+ import type { WithheldGuard } from './upgrade-guards';
19
+ import { installMissingGuards } from './upgrade-guards';
12
20
  import { parseJson } from './upgrade-registry';
13
21
 
22
+ // Where it always was: `verify-exercise.ts` and `verify-budgets-build.ts` read it from here.
23
+ export { documentIn } from './upgrade-document';
24
+
14
25
  const FINDING = t.object({
15
26
  code: t.string,
16
27
  cause: t.string,
@@ -80,8 +91,14 @@ interface DoctorDocument {
80
91
  export interface HopGuards {
81
92
  /** False when the hop's `x doctor` predates the listing: unknown, which is not the same as none. */
82
93
  readonly reported: boolean;
94
+ /** Still missing after the hop: the ones it withheld, each with the command that adds it. */
83
95
  readonly missing: readonly { readonly name: string; readonly add: string }[];
96
+ /** Held in another form: the app's edit, listed and never touched. */
84
97
  readonly differs: readonly { readonly name: string; readonly refresh: string }[];
98
+ /** Written by this hop from the installed release's template; `boundaries` found nothing more. */
99
+ readonly installed: readonly string[];
100
+ /** Not written, with how many findings each would have added (`upgrade-guards.ts`). */
101
+ readonly withheld: readonly WithheldGuard[];
85
102
  }
86
103
 
87
104
  /**
@@ -98,7 +115,11 @@ export interface HopExercise {
98
115
  export interface HopGate {
99
116
  readonly manifest: { readonly ok: boolean; readonly findings: readonly GateFinding[] };
100
117
  readonly guards: HopGuards;
118
+ /** The coverage floor a Bun-floor hop moved to what it measured; null when none moved. */
119
+ readonly coverage: HopCoverage | null;
101
120
  readonly exercise: HopExercise;
121
+ /** The exercise figures the hop wrote into `x.verify.json` as its ratchet; null when none. */
122
+ readonly exerciseFloor: HopExerciseFloor | null;
102
123
  readonly verify: {
103
124
  readonly ok: boolean;
104
125
  readonly summary: string;
@@ -108,21 +129,6 @@ export interface HopGate {
108
129
  };
109
130
  }
110
131
 
111
- /**
112
- * The one JSON document on a child's stdout. Whole first; then its last line that parses, because
113
- * the CLI that keeps fd 1 to one document under `--json` is a recent one and a hop can install one
114
- * that still logs a boot line ahead of it.
115
- */
116
- export function documentIn(stdout: string): unknown {
117
- const whole = parseJson(stdout.trim());
118
- if (whole !== undefined) return whole;
119
- const lines = stdout.split('\n').filter((line) => line.trimStart().startsWith('{'));
120
- return lines
121
- .reverse()
122
- .map(parseJson)
123
- .find((parsed) => parsed !== undefined);
124
- }
125
-
126
132
  const flatten = (document: {
127
133
  readonly steps?: VerifyDocument['steps'];
128
134
  readonly findings?: readonly RawFinding[];
@@ -192,15 +198,31 @@ const readGuards = (result: ExecResult): HopGuards => {
192
198
  const parsed = DOCTOR.safeParse(documentIn(result.stdout));
193
199
  const guards =
194
200
  parsed.issues === undefined ? (parsed.value as DoctorDocument).data?.guards : undefined;
195
- if (guards === undefined) return { reported: false, missing: [], differs: [] };
196
- return { reported: true, missing: guards.missing ?? [], differs: guards.differs ?? [] };
201
+ if (guards === undefined) {
202
+ return { reported: false, missing: [], differs: [], installed: [], withheld: [] };
203
+ }
204
+ return {
205
+ reported: true,
206
+ missing: guards.missing ?? [],
207
+ differs: guards.differs ?? [],
208
+ installed: [],
209
+ withheld: [],
210
+ };
197
211
  };
198
212
 
199
- /** The four, in order, each told apart by `onStage` so a long gate is not a long silence. */
213
+ export type HopStage = 'manifest' | 'doctor' | 'guards' | 'coverage' | 'exercise' | 'verify';
214
+
215
+ /**
216
+ * The gate, in order, each stage told apart by `onStage` so a long gate is not a long silence.
217
+ * `guards` runs only when the doctor lists a missing one; `coverage` only on a hop that moved the
218
+ * Bun floor — both before `verify`, so the verdict is the one on the tree the hop leaves.
219
+ */
200
220
  export async function runHopGate(input: {
201
221
  readonly runner: Runner;
202
222
  readonly root: string;
203
- readonly onStage: (stage: 'manifest' | 'doctor' | 'exercise' | 'verify') => void;
223
+ readonly onStage: (stage: HopStage) => void;
224
+ /** Present when the hop moved the Bun floor: what the coverage rebaseline's `why` says. */
225
+ readonly bunMoved?: CoverageRebaseline;
204
226
  }): Promise<HopGate> {
205
227
  const { runner, root, onStage } = input;
206
228
  const installed = (args: readonly string[]): Promise<ExecResult> =>
@@ -208,12 +230,33 @@ export async function runHopGate(input: {
208
230
  onStage('manifest');
209
231
  const manifest = readManifest(await installed(['manifest', '--json']));
210
232
  onStage('doctor');
211
- const guards = readGuards(await installed(['doctor', '--json']));
233
+ const listed = readGuards(await installed(['doctor', '--json']));
234
+ let guards = listed;
235
+ if (listed.missing.length > 0) {
236
+ onStage('guards');
237
+ const done = await installMissingGuards({ cli: installed, root, missing: listed.missing });
238
+ const still = new Set(done.withheld.map((guard) => guard.name));
239
+ guards = {
240
+ ...listed,
241
+ missing: listed.missing.filter((guard) => still.has(guard.name)),
242
+ ...done,
243
+ };
244
+ }
245
+ let coverage: HopCoverage | null = null;
246
+ const stated = input.bunMoved === undefined ? undefined : await statedCoverage(root);
247
+ if (input.bunMoved !== undefined && stated !== undefined) {
248
+ onStage('coverage');
249
+ coverage = await rebaselineCoverage({ cli: installed, root, stated, bun: input.bunMoved });
250
+ }
251
+ // The report's stamp first: only a report this exercise rewrote is ratcheted.
252
+ const stamp = await exerciseReportStamp(root);
212
253
  onStage('exercise');
213
254
  const exercise = readExercise(await installed(['exercise', '--json']));
255
+ // Before `verify`, from the report that exercise just wrote: the gate judges the figures it holds.
256
+ const exerciseFloor = await ratchetExerciseFloor(root, stamp);
214
257
  onStage('verify');
215
258
  const verify = readVerify(await installed(['verify', '--json']));
216
- return { manifest, guards, exercise, verify };
259
+ return { manifest, guards, coverage, exercise, exerciseFloor, verify };
217
260
  }
218
261
 
219
262
  /** What a repository with no app can still be asked, in the order an author would run them. */
@@ -0,0 +1,159 @@
1
+ // A hop's missing shipped guards, installed by the CLI the hop just installed (`x g guard <name>`,
2
+ // that release's own template) — each one only if the `boundaries` step finds nothing more with it
3
+ // on disk. One the tree breaks is taken back out — every file its run listed, the refreshed manifest
4
+ // too, put back as it was — and listed; an app-modified guard is never touched (`differs`).
5
+
6
+ // why: Bun exposes no path-join primitive; a written guard's path is relative to the app root.
7
+ import { join } from 'node:path';
8
+ import { MANIFEST_FILENAME } from '@ultimat3/manifest';
9
+ import { t } from '@ultimat3/schema';
10
+ import type { ExecResult } from './exec';
11
+ import { documentIn } from './upgrade-document';
12
+
13
+ const GENERATED = t.object({
14
+ data: t.optional(t.object({ files: t.optional(t.array(t.string)) })),
15
+ });
16
+ const STEP = t.object({
17
+ name: t.string,
18
+ findings: t.optional(t.array(t.object({ code: t.string }))),
19
+ });
20
+ const BOUNDARIES = t.object({ steps: t.array(STEP) });
21
+
22
+ /** A missing guard the hop did not install, with what stood in the way. */
23
+ export interface WithheldGuard {
24
+ readonly name: string;
25
+ /** The command that writes it anyway; `x verify` then names what it finds. */
26
+ readonly add: string;
27
+ /** How many findings it would add to `boundaries`; null when that could not be measured. */
28
+ readonly findings: number | null;
29
+ }
30
+
31
+ export interface GuardInstall {
32
+ readonly installed: readonly string[];
33
+ readonly withheld: readonly WithheldGuard[];
34
+ }
35
+
36
+ /** Runs the installed CLI with these arguments in the app root. */
37
+ export type InstalledCli = (args: readonly string[]) => Promise<ExecResult>;
38
+
39
+ const MEASURE = ['verify', '--only', 'boundaries', '--json'] as const;
40
+
41
+ /** `boundaries`' finding count, or undefined when this CLI answered no step by that name. */
42
+ const boundariesCount = async (cli: InstalledCli): Promise<number | undefined> => {
43
+ const parsed = BOUNDARIES.safeParse(documentIn((await cli(MEASURE)).stdout));
44
+ if (parsed.issues !== undefined) return undefined;
45
+ const steps = (
46
+ parsed.value as { readonly steps: readonly { name: string; findings?: unknown[] }[] }
47
+ ).steps;
48
+ const step = steps.find((candidate) => candidate.name === 'boundaries');
49
+ return step === undefined ? undefined : (step.findings ?? []).length;
50
+ };
51
+
52
+ /** A path's bytes before a run, or null when it did not exist: what a rollback puts back. */
53
+ type Prior = ReadonlyMap<string, Uint8Array | null>;
54
+
55
+ /** One generator run: the paths it listed, and how to put each back. */
56
+ interface Generated {
57
+ readonly files: readonly string[];
58
+ readonly prior: Prior;
59
+ }
60
+
61
+ /**
62
+ * Every path a guard run can write, read before it runs: the guard and its test, and the generated
63
+ * contracts `x g` refreshes and lists beside them (`x.manifest.json`, `openapi*.json`). A listed
64
+ * path outside this set has no known prior state and is never deleted.
65
+ */
66
+ const snapshot = async (root: string, name: string): Promise<Prior> => {
67
+ const paths = new Set([`guards/${name}.ts`, `guards/${name}.test.ts`, MANIFEST_FILENAME]);
68
+ paths.add('openapi.json');
69
+ for await (const path of new Bun.Glob('openapi*.json').scan({ cwd: root })) paths.add(path);
70
+ const prior = new Map<string, Uint8Array | null>();
71
+ for (const path of paths) {
72
+ const file = Bun.file(join(root, path));
73
+ prior.set(path, (await file.exists()) ? await file.bytes() : null);
74
+ }
75
+ return prior;
76
+ };
77
+
78
+ /** Writes one guard; what it listed with what stood there before, or undefined when refused. */
79
+ const generate = async (
80
+ cli: InstalledCli,
81
+ root: string,
82
+ name: string,
83
+ ): Promise<Generated | undefined> => {
84
+ const prior = await snapshot(root, name);
85
+ const result = await cli(['g', 'guard', name, '--json']);
86
+ if (!result.ok) return undefined;
87
+ const parsed = GENERATED.safeParse(documentIn(result.stdout));
88
+ const listed =
89
+ parsed.issues === undefined
90
+ ? (parsed.value as { readonly data?: { readonly files?: readonly string[] } }).data?.files
91
+ : undefined;
92
+ return { files: listed ?? [`guards/${name}.ts`, `guards/${name}.test.ts`], prior };
93
+ };
94
+
95
+ /** Puts each listed path back: rewritten when it existed before the run, deleted when it did not. */
96
+ const rollback = async (root: string, run: Generated | undefined): Promise<void> => {
97
+ for (const path of run?.files ?? []) {
98
+ const before = run?.prior.get(path);
99
+ // Unknown prior state: leaving a file is recoverable, deleting a committed one is not.
100
+ if (before === undefined) continue;
101
+ const file = Bun.file(join(root, path));
102
+ if (before !== null) await Bun.write(file, before);
103
+ else if (await file.exists()) await file.delete();
104
+ }
105
+ };
106
+
107
+ /**
108
+ * Every missing guard, installed or withheld. All at once first — two `boundaries` runs when the
109
+ * tree breaks none of them, the usual case — and one at a time only when the count rose, so the
110
+ * guard that found something is the one taken back out.
111
+ */
112
+ export async function installMissingGuards(input: {
113
+ readonly cli: InstalledCli;
114
+ readonly root: string;
115
+ readonly missing: readonly { readonly name: string; readonly add: string }[];
116
+ }): Promise<GuardInstall> {
117
+ const { cli, root, missing } = input;
118
+ if (missing.length === 0) return { installed: [], withheld: [] };
119
+ const unmeasured = (guard: { name: string; add: string }): WithheldGuard => ({
120
+ name: guard.name,
121
+ add: guard.add,
122
+ findings: null,
123
+ });
124
+ const base = await boundariesCount(cli);
125
+ if (base === undefined) return { installed: [], withheld: missing.map(unmeasured) };
126
+
127
+ const written = new Map<string, Generated>();
128
+ const withheld: WithheldGuard[] = [];
129
+ for (const guard of missing) {
130
+ const run = await generate(cli, root, guard.name);
131
+ if (run === undefined) withheld.push(unmeasured(guard));
132
+ else written.set(guard.name, run);
133
+ }
134
+ if (written.size === 0) return { installed: [], withheld };
135
+ const together = await boundariesCount(cli);
136
+ if (together !== undefined && together <= base) {
137
+ return { installed: [...written.keys()], withheld: sortByName(withheld) };
138
+ }
139
+
140
+ // Newest first, so each artifact ends at the bytes it held before the first run.
141
+ for (const run of [...written.values()].reverse()) await rollback(root, run);
142
+ const installed: string[] = [];
143
+ let held = base;
144
+ for (const guard of missing.filter(({ name }) => written.has(name))) {
145
+ const run = await generate(cli, root, guard.name);
146
+ const count = run === undefined ? undefined : await boundariesCount(cli);
147
+ if (run !== undefined && count !== undefined && count <= held) {
148
+ installed.push(guard.name);
149
+ held = count;
150
+ continue;
151
+ }
152
+ await rollback(root, run);
153
+ withheld.push({ ...guard, findings: count === undefined ? null : count - held });
154
+ }
155
+ return { installed, withheld: sortByName(withheld) };
156
+ }
157
+
158
+ const sortByName = (list: readonly WithheldGuard[]): readonly WithheldGuard[] =>
159
+ [...list].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
@@ -88,10 +88,36 @@ export const humanLines = (input: {
88
88
  ...(agentsMd === 'link' || agentsMd === 'differs'
89
89
  ? [msg(agentsMd === 'link' ? 'cli.upgrade.agentsMd.link' : 'cli.upgrade.agentsMd.differs')]
90
90
  : []),
91
- ...(gate?.guards.missing ?? []).map((guard) => msg('cli.upgrade.guard', { fix: guard.add })),
91
+ ...(gate?.guards.installed ?? []).map((name) => msg('cli.upgrade.guardInstalled', { name })),
92
+ ...(gate?.guards.withheld ?? []).map((guard) =>
93
+ guard.findings === null
94
+ ? msg('cli.upgrade.guardUnmeasured', { fix: guard.add })
95
+ : msg('cli.upgrade.guardWithheld', { fix: guard.add, count: guard.findings }),
96
+ ),
92
97
  ...(gate?.guards.differs ?? []).map((guard) =>
93
98
  msg('cli.upgrade.guard', { fix: guard.refresh }),
94
99
  ),
100
+ ...(gate === undefined || gate.coverage === null
101
+ ? []
102
+ : [
103
+ msg('cli.upgrade.coverage', {
104
+ file: gate.coverage.file,
105
+ fromLines: gate.coverage.from.lines,
106
+ fromFuncs: gate.coverage.from.funcs,
107
+ toLines: gate.coverage.to.lines,
108
+ toFuncs: gate.coverage.to.funcs,
109
+ lines: Math.floor(gate.coverage.measured.lines * 10) / 10,
110
+ funcs: Math.floor(gate.coverage.measured.funcs * 10) / 10,
111
+ }),
112
+ ]),
113
+ ...(gate === undefined || gate.exerciseFloor === null
114
+ ? []
115
+ : [
116
+ msg('cli.upgrade.exerciseFloor', {
117
+ file: gate.exerciseFloor.file,
118
+ figures: JSON.stringify(gate.exerciseFloor.written),
119
+ }),
120
+ ]),
95
121
  // The exercise's own list first: every fix it has, before the gate's verdict on the same tree.
96
122
  ...findingLines([
97
123
  ...(gate?.exercise.findings ?? []),
@@ -144,8 +170,10 @@ export const report = (input: {
144
170
  typescript: input.typescript,
145
171
  agentsMd: input.agentsMd ?? null,
146
172
  guards: gate?.guards ?? null,
173
+ coverage: gate?.coverage ?? null,
147
174
  manifest: gate?.manifest ?? null,
148
175
  exercise: gate?.exercise ?? null,
176
+ exerciseFloor: gate?.exerciseFloor ?? null,
149
177
  verify: gate?.verify ?? null,
150
178
  scripts,
151
179
  then,
@@ -24,6 +24,7 @@ import { checkUngeneratableMigrations } from './db-ungeneratable';
24
24
  import { checkDocumentStyles, documentSurfaces } from './document-styles';
25
25
  import { driftOutcome } from './drift-store';
26
26
  import { checkErrorCodeResolution, checkErrorFixReport } from './error-contract';
27
+ import { withUnprovenFloor } from './exercise-floor-report';
27
28
  import { guardFindings } from './guards';
28
29
  import { catalogFindings } from './i18n-registration';
29
30
  import { isrQueryAdvice } from './isr-query-advice';
@@ -195,7 +196,8 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
195
196
  ...TEST_STEPS.slice(0, AFTER_JOB),
196
197
  // Every step that loads the app stands down while the load is red: the cause is `manifest`'s,
197
198
  // and what a half-filled registry looks like is not a finding (`load-findings.ts`).
198
- blockedByLoad(exerciseStep),
199
+ // The floor's verdict on the report the child wrote rides on the step (`exercise-floor-report.ts`).
200
+ blockedByLoad(withUnprovenFloor(exerciseStep)),
199
201
  ...TEST_STEPS.slice(AFTER_JOB),
200
202
  blockedByLoad({
201
203
  name: 'drift',