@ultimat3/cli 31.47.1 → 31.48.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 (51) hide show
  1. package/package.json +29 -29
  2. package/src/cmd-drill.ts +20 -1
  3. package/src/cmd-heavy-spec.ts +28 -0
  4. package/src/cmd-heavy.ts +160 -0
  5. package/src/cmd-test.ts +13 -3
  6. package/src/cmd-upgrade.ts +17 -4
  7. package/src/codemods/docs-many-agents.ts +30 -0
  8. package/src/codemods/index.ts +2 -0
  9. package/src/doctor-advisory-floors.ts +30 -8
  10. package/src/error-codes-tooling.ts +9 -3
  11. package/src/exec.ts +11 -3
  12. package/src/heavy-cores.ts +51 -0
  13. package/src/heavy-env.ts +19 -0
  14. package/src/heavy-errors.ts +36 -0
  15. package/src/heavy-flock.ts +73 -0
  16. package/src/heavy-ledger.ts +358 -0
  17. package/src/heavy-memory.ts +67 -0
  18. package/src/heavy-weights.ts +47 -0
  19. package/src/heavy.ts +290 -0
  20. package/src/local-cli.ts +6 -5
  21. package/src/mcp-errors.ts +3 -0
  22. package/src/messages.ts +11 -0
  23. package/src/registry.ts +2 -0
  24. package/src/role-replicator.ts +5 -3
  25. package/src/runtime-cache.ts +24 -3
  26. package/src/runtime-overrides.ts +4 -2
  27. package/src/templates/guard-released-forms.ts +5 -5
  28. package/src/templates/scaffold-claude-agents.ts +9 -6
  29. package/src/templates/scaffold-claude-commands.ts +1 -1
  30. package/src/templates/scaffold-docs.ts +5 -4
  31. package/src/test-batches.ts +9 -3
  32. package/src/test-shards.ts +3 -3
  33. package/src/test-slots.ts +35 -161
  34. package/src/verify-checks.ts +4 -3
  35. package/src/verify-coverage-run.ts +5 -4
  36. package/src/verify-deadline.ts +18 -2
  37. package/src/verify-heavy-steps.ts +26 -0
  38. package/src/verify-test-run.ts +3 -2
  39. package/src/verify-tests.ts +27 -20
  40. package/wiki/Building-Your-Own-Base.md +15 -2
  41. package/wiki/CI-Parallel-Gate.md +2 -3
  42. package/wiki/CLI-Reference.md +24 -12
  43. package/wiki/Caching-And-Invalidation.md +1 -1
  44. package/wiki/Configuration.md +22 -4
  45. package/wiki/Home.md +1 -0
  46. package/wiki/Interface-Rules.md +1 -1
  47. package/wiki/Known-Gaps.md +1 -1
  48. package/wiki/Mail.md +1 -1
  49. package/wiki/Many-Agents.md +60 -0
  50. package/wiki/Testing.md +5 -5
  51. package/wiki/Tutorial-01-First-App.md +2 -2
package/src/test-slots.ts CHANGED
@@ -1,168 +1,42 @@
1
- // The MACHINE's test budget, shared by every `x test` and `x verify` running on it at once.
2
- //
3
- // A run's own width (`test-workers.ts`) bounds one run. It cannot bound two: on 2026-09-27 two
4
- // agents' gates on one 45 GB box each planned 14-18 workers off the same free-memory reading and
5
- // the kernel OOM-killed the machine with 36 `bun` processes holding ~40 GB. So each batch of
6
- // workers first LEASES that many slots from a pool of lock files — one file per worker the machine
7
- // budget allows — and a second run on the same box gets what is left: it runs narrower, or waits
8
- // for one slot, instead of doubling the machine's memory.
9
- //
10
- // A slot is a file created with O_EXCL holding the leasing process's pid. A holder that died
11
- // without releasing (SIGKILL, OOM, a closed terminal) is detected by its pid no longer existing,
12
- // and its slot is taken over. Nothing here needs a daemon, and nothing survives a reboot that
13
- // matters: the directory is under the OS temp dir.
14
- //
15
- // Bun ships no O_EXCL create and no pid probe: `openSync(…, 'wx')` and `process.kill(pid, 0)` are
16
- // the node:fs / process primitives for exactly those two.
17
- // why: Bun ships no O_EXCL create (writeFileSync flag 'wx') and no sync unlink/mkdir.
18
- import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
19
- // why: Bun exposes no tmpdir(); only node:os answers the platform temp root.
20
- import { tmpdir } from 'node:os';
21
- // why: Bun ships no path-join primitive.
22
- import { join } from 'node:path';
1
+ // A test run's share of the machine: each batch of `bun test` workers reserves its measured memory
2
+ // in the machine ledger (`heavy-ledger.ts`) and takes the width the core cap and the ledger allow,
3
+ // so a second run on the same box narrows or queues instead of doubling its memory.
23
4
 
24
- /** Where the pool lives. Per user, so two accounts on one box never read each other's pids. */
25
- export const SLOTS_DIR_ENV = 'ULTIMATE_TEST_SLOTS_DIR';
5
+ import type { WorkerLease } from './heavy';
6
+ import { leaseWorkers } from './heavy';
7
+ import type { HeavyEnv } from './heavy-env';
8
+ import { E2E_LANE_PEAK_MB, TEST_RUN_BASE_MB, TEST_WORKER_PEAK_MB } from './heavy-weights';
26
9
 
27
- /** `0` turns the machine pool off — a CI runner that runs one job per VM has nothing to share. */
10
+ /** `0` turns the lease off for one run; the ledger's own switch is `ULTIMATE_HEAVY_MEMORY=0`. */
28
11
  export const SLOTS_ENV = 'ULTIMATE_TEST_SLOTS';
29
12
 
30
- /**
31
- * Set on every `bun test` a leased batch spawns: the slots are already held for that process
32
- * tree, so an `x test` / `x verify` a test runs inside it (the framework's own suites do) must
33
- * not lease again — it would wait on its own parent's slots.
34
- */
35
- export const SLOT_HELD_ENV = 'ULTIMATE_TEST_SLOT_HELD';
13
+ export type MachineLease = (want: number) => Promise<WorkerLease>;
36
14
 
37
- /** How long a run waits for its first slot before it runs one worker anyway, and says so. */
38
- export const SLOT_WAIT_MS = 10 * 60 * 1000;
15
+ /** What a run of this suite reserves: a browser lane is one measured whole. */
16
+ export const suiteWeight = (
17
+ type: string | undefined,
18
+ ): { readonly unitMb: number; readonly baseMb: number } =>
19
+ type === 'e2e'
20
+ ? { unitMb: E2E_LANE_PEAK_MB, baseMb: 0 }
21
+ : { unitMb: TEST_WORKER_PEAK_MB, baseMb: TEST_RUN_BASE_MB };
39
22
 
40
- const POLL_MS = 500;
41
-
42
- type Env = Readonly<Record<string, string | undefined>>;
43
-
44
- export const slotsDir = (env: Env = Bun.env): string =>
45
- env[SLOTS_DIR_ENV] ??
46
- join(tmpdir(), `ultimate-test-slots-${String(process.getuid?.() ?? 'user')}`);
47
-
48
- export const slotsEnabled = (env: Env = Bun.env): boolean =>
49
- env[SLOTS_ENV] !== '0' && env[SLOT_HELD_ENV] !== '1' && Bun.env[SLOT_HELD_ENV] !== '1';
50
-
51
- /** A lease on `count` workers' worth of the machine. `count` is at least 1. */
52
- export interface SlotLease {
53
- readonly count: number;
54
- /** Slots actually held — 0 when the wait ran out and the run went ahead unleased. */
55
- readonly held: number;
56
- /** How long the lease waited for its first slot. */
57
- readonly waitedMs: number;
58
- release(): void;
59
- }
60
-
61
- const pidAlive = (pid: number): boolean => {
62
- if (!Number.isInteger(pid) || pid <= 0) return false;
63
- try {
64
- process.kill(pid, 0);
65
- return true;
66
- } catch (error) {
67
- // EPERM is a live process another user owns — alive, and not ours to take.
68
- return (error as { code?: string } | null)?.code === 'EPERM';
69
- }
70
- };
71
-
72
- export interface AcquireInput {
73
- /** Workers this batch wants. */
74
- readonly want: number;
75
- /** Slots the machine budget allows in all — `defaultWorkers()` for this box. */
76
- readonly capacity: number;
77
- readonly dir?: string;
78
- readonly pid?: number;
79
- readonly alive?: (pid: number) => boolean;
80
- readonly waitMs?: number;
81
- readonly sleep?: (ms: number) => Promise<void>;
82
- readonly now?: () => number;
83
- }
84
-
85
- /** Take one slot file, or take it over from a dead holder. */
86
- function tryTake(path: string, pid: number, alive: (pid: number) => boolean): boolean {
87
- for (let attempt = 0; attempt < 2; attempt += 1) {
88
- try {
89
- writeFileSync(path, String(pid), { flag: 'wx' });
90
- return true;
91
- } catch (error) {
92
- if ((error as { code?: string } | null)?.code !== 'EEXIST') return false;
93
- }
94
- let holder: number;
95
- try {
96
- holder = Number.parseInt(readFileSync(path, 'utf8'), 10);
97
- } catch {
98
- // Released between the create and the read: try the create once more.
99
- continue;
100
- }
101
- if (alive(holder)) return false;
102
- try {
103
- unlinkSync(path);
104
- } catch {
105
- // Another run took it over first; the second create decides.
106
- }
107
- }
108
- return false;
109
- }
110
-
111
- /**
112
- * Lease up to `want` slots out of `capacity`. Never zero: with every slot held, it polls until one
113
- * frees, and after `waitMs` it runs one worker unleased rather than hang a gate forever.
114
- */
115
- export async function acquireSlots(input: AcquireInput): Promise<SlotLease> {
116
- const dir = input.dir ?? slotsDir();
117
- const pid = input.pid ?? process.pid;
118
- const alive = input.alive ?? pidAlive;
119
- const sleep = input.sleep ?? ((ms: number) => Bun.sleep(ms));
120
- const now = input.now ?? (() => performance.now());
121
- const want = Math.max(1, Math.trunc(input.want));
122
- const capacity = Math.max(1, Math.trunc(input.capacity));
123
- mkdirSync(dir, { recursive: true });
124
- const started = now();
125
- const waitMs =
126
- input.waitMs !== undefined && Number.isFinite(input.waitMs) && input.waitMs >= 0
127
- ? input.waitMs
128
- : SLOT_WAIT_MS;
129
- const deadline = started + waitMs;
130
- for (;;) {
131
- const held: string[] = [];
132
- for (let index = 0; index < capacity && held.length < want; index += 1) {
133
- const path = join(dir, `slot-${String(index)}`);
134
- if (tryTake(path, pid, alive)) held.push(path);
135
- }
136
- if (held.length > 0 || now() >= deadline) {
137
- const waitedMs = Math.round(now() - started);
138
- let released = false;
139
- return {
140
- count: Math.max(1, held.length),
141
- held: held.length,
142
- waitedMs,
143
- release: () => {
144
- if (released) return;
145
- released = true;
146
- for (const path of held) {
147
- try {
148
- if (readFileSync(path, 'utf8') === String(pid)) unlinkSync(path);
149
- } catch {
150
- // Already gone — a crashed-holder sweep by another run took it.
151
- }
152
- }
153
- },
154
- };
155
- }
156
- await sleep(POLL_MS);
157
- }
158
- }
159
-
160
- /**
161
- * The lease a default-width run takes per batch, or none: an explicit `--workers` is the caller's
162
- * call (as it is over the budget), and `ULTIMATE_TEST_SLOTS=0` turns the pool off.
163
- */
23
+ /** `exact` is an explicit `--workers`: that width, waited for, and no core cap. */
164
24
  export const machineLease = (
165
- capacity: number,
166
- env: Env = Bun.env,
167
- ): ((want: number) => Promise<SlotLease>) | undefined =>
168
- slotsEnabled(env) ? (want) => acquireSlots({ want, capacity, dir: slotsDir(env) }) : undefined;
25
+ env: HeavyEnv,
26
+ input: {
27
+ readonly cwd: string;
28
+ readonly label: string;
29
+ readonly type?: string;
30
+ readonly exact?: boolean;
31
+ },
32
+ ): MachineLease | undefined =>
33
+ env[SLOTS_ENV] === '0'
34
+ ? undefined
35
+ : (want) =>
36
+ leaseWorkers(want, {
37
+ label: input.label,
38
+ cwd: input.cwd,
39
+ env,
40
+ ...suiteWeight(input.type),
41
+ ...(input.exact === true ? { exact: true } : {}),
42
+ });
@@ -30,7 +30,7 @@ import { catalogFindings } from './i18n-registration';
30
30
  import { isrQueryAdvice } from './isr-query-advice';
31
31
  import { readJobBudgetFindings } from './job-budget';
32
32
  import { unregisteredJobFindings } from './job-registration';
33
- import { LINT_ARGV, lintOutcome } from './lint-findings';
33
+ import { lintOutcome } from './lint-findings';
34
34
  import { liveRouteFindings } from './live-routes';
35
35
  import { blockedByLoad, withLoadFindings } from './load-findings';
36
36
  import {
@@ -60,6 +60,7 @@ import { contractDiffStep } from './verify-contract-diff';
60
60
  import { nestedAppRootFindings } from './verify-drift-owner';
61
61
  import { exerciseStep } from './verify-exercise';
62
62
  import { floorProblemFindings, readVerifyFloor } from './verify-floor';
63
+ import { runLint, runTypecheck } from './verify-heavy-steps';
63
64
  import { mcpMountFindings } from './verify-mcp-mount';
64
65
  import { nativeFormWarnings } from './verify-native-form';
65
66
  import { roleLoadFindings } from './verify-role-load';
@@ -90,7 +91,7 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
90
91
  async run(ctx) {
91
92
  const floor = await readVerifyFloor(ctx.root);
92
93
  const argv = await typecheckArgs(ctx.root, floor?.typecheckBin ?? 'tsc');
93
- const result = await ctx.runner(['bunx', ...argv], { cwd: ctx.root });
94
+ const result = await runTypecheck(ctx, argv);
94
95
  return fromExec(result, {
95
96
  code: 'X_TYPECHECK_FAILED',
96
97
  cause: 'the project does not typecheck',
@@ -107,7 +108,7 @@ export const VERIFY_STEPS: readonly VerifyStep[] = [
107
108
  // the colour rule is `packages/ui/src/tokens/tokens.test.ts`, and rides on the `unit` step.
108
109
  summary: 'biome: format, no any, no default exports, no unused imports',
109
110
  async run(ctx) {
110
- return lintOutcome(await ctx.runner(LINT_ARGV, { cwd: ctx.root }));
111
+ return lintOutcome(await runLint(ctx));
111
112
  },
112
113
  },
113
114
  {
@@ -32,7 +32,7 @@ import { msg } from './messages';
32
32
  import { countsOf } from './test-counts';
33
33
  import { testEnvOverrides } from './test-dotenv';
34
34
  import { failureOf } from './test-shards';
35
- import { SLOT_HELD_ENV } from './test-slots';
35
+ import type { MachineLease } from './test-slots';
36
36
  import {
37
37
  costOf,
38
38
  junitDurations,
@@ -99,7 +99,7 @@ export interface CoveredRunOptions {
99
99
  readonly isolate?: boolean;
100
100
  readonly env?: Readonly<Record<string, string | undefined>>;
101
101
  readonly widthReason?: string;
102
- readonly lease?: (want: number) => Promise<{ readonly count: number; release(): void }>;
102
+ readonly lease?: MachineLease;
103
103
  /** Test files per process. Absent is `COVERAGE_SLICE_FILES`; a test cuts smaller. */
104
104
  readonly sliceFiles?: number;
105
105
  /** The machine's pace (`verify-pace.ts`): each test's default and declared deadline stretch by it. */
@@ -144,14 +144,14 @@ export const coveredArgs = (
144
144
  export async function runCovered(options: CoveredRunOptions): Promise<CoveredRun> {
145
145
  const slices = coverageSlices(options.files, options.sliceFiles);
146
146
  const want = Math.max(1, Math.min(Math.trunc(options.workers), slices.length));
147
- const lease = want > 1 ? await options.lease?.(want) : undefined;
147
+ const lease = await options.lease?.(want);
148
148
  const width = Math.min(want, lease?.count ?? want);
149
149
  const base = join(options.root, COVERAGE_DIR, `unit-${String(process.pid)}`);
150
150
  const isolate = options.isolate === true;
151
151
  const overrides = {
152
152
  ...testEnvOverrides(options.root, options.env ?? Bun.env),
153
153
  ...(isolate ? { [ISOLATED_ENV]: '1' } : {}),
154
- ...(lease === undefined ? {} : { [SLOT_HELD_ENV]: '1' }),
154
+ ...lease?.env,
155
155
  ...paceEnv(options.pace),
156
156
  };
157
157
  const results = new Array<ExecResult>(slices.length);
@@ -174,6 +174,7 @@ export async function runCovered(options: CoveredRunOptions): Promise<CoveredRun
174
174
  ),
175
175
  {
176
176
  cwd: options.root,
177
+ ...(lease?.fds === undefined || lease.fds.length === 0 ? {} : { inheritFds: lease.fds }),
177
178
  env: {
178
179
  ...overrides,
179
180
  ULTIMATE_TEST_WORKER: String(slot),
@@ -5,6 +5,7 @@
5
5
  import { TEST_TYPES } from '@ultimat3/testing';
6
6
  import type { ExecResult, Runner } from './exec';
7
7
  import { execOutput } from './exec';
8
+ import { heavyWaitClock } from './heavy';
8
9
  import type { VerifyStepName } from './verify-step';
9
10
 
10
11
  /** The `x.verify.json` key: `{ "stepTimeoutMs": { "unit": 900000 } }`. */
@@ -462,14 +463,29 @@ export async function killTagged(
462
463
  return [...killed.values()];
463
464
  }
464
465
 
465
- /** `work`, or `{ timedOut: true }` once `ms` passes. The abandoned promise is never unhandled. */
466
+ /**
467
+ * `work`, or `{ timedOut: true }` once `ms` of its own time passes. Time queued for the machine
468
+ * (`waited`, a monotonic clock) is not the step's: a gate behind another gate is not a hung one. The
469
+ * abandoned promise is never unhandled.
470
+ */
466
471
  export async function raceDeadline<T>(
467
472
  work: Promise<T>,
468
473
  ms: number,
474
+ waited: () => number = heavyWaitClock,
469
475
  ): Promise<{ readonly timedOut: false; readonly value: T } | { readonly timedOut: true }> {
470
476
  let timer: ReturnType<typeof setTimeout> | undefined;
477
+ const started = performance.now();
478
+ const waitedAtStart = waited();
471
479
  const expired = new Promise<{ readonly timedOut: true }>((resolve) => {
472
- timer = setTimeout(() => resolve({ timedOut: true }), ms);
480
+ const arm = (delay: number): void => {
481
+ timer = setTimeout(() => {
482
+ const due = started + ms + (waited() - waitedAtStart);
483
+ const left = due - performance.now();
484
+ if (left > 0) arm(left);
485
+ else resolve({ timedOut: true });
486
+ }, delay);
487
+ };
488
+ arm(ms);
473
489
  });
474
490
  try {
475
491
  const raced = await Promise.race([
@@ -0,0 +1,26 @@
1
+ // The gate's two whole-tree tools, each run inside its measured reservation in the machine ledger.
2
+ // Split from `verify-checks.ts`, which owns what the steps conclude from these results.
3
+
4
+ import type { ExecResult } from './exec';
5
+ import { withCheckoutLock, withChild, withHeavy } from './heavy';
6
+ import { LINT_PEAK_MB, typecheckPeakMb } from './heavy-weights';
7
+ import { LINT_ARGV } from './lint-findings';
8
+ import type { VerifyContext } from './verify-step';
9
+
10
+ /** The compiler's peak in the ledger, then this checkout's one `tsc` at a time. */
11
+ export function runTypecheck(ctx: VerifyContext, argv: readonly string[]): Promise<ExecResult> {
12
+ const env = ctx.env ?? Bun.env;
13
+ return withHeavy(
14
+ { label: 'typecheck', cwd: ctx.root, env, unitMb: typecheckPeakMb(argv) },
15
+ (held) =>
16
+ withCheckoutLock({ name: 'typecheck', root: ctx.root, env }, held, (child) =>
17
+ ctx.runner(['bunx', ...argv], withChild({ cwd: ctx.root }, child)),
18
+ ),
19
+ );
20
+ }
21
+
22
+ export const runLint = (ctx: VerifyContext): Promise<ExecResult> =>
23
+ withHeavy(
24
+ { label: 'lint', cwd: ctx.root, env: ctx.env ?? Bun.env, unitMb: LINT_PEAK_MB },
25
+ (child) => ctx.runner(LINT_ARGV, withChild({ cwd: ctx.root }, child)),
26
+ );
@@ -13,6 +13,7 @@ import { testEnvOverrides } from './test-dotenv';
13
13
  import { tidyBeforeTestRun } from './test-housekeeping';
14
14
  import type { TestFile } from './test-select';
15
15
  import { failureOf, TEST_TIMINGS_FILE, testArgs } from './test-shards';
16
+ import type { MachineLease } from './test-slots';
16
17
  import { loadTimings, slowestOf } from './test-timings';
17
18
  import { BATCH_FILES_PER_WORKER, SHARED_BATCH_FILES_PER_WORKER } from './test-workers';
18
19
  import type { MachinePace } from './verify-pace';
@@ -36,7 +37,7 @@ export interface ParallelRunOptions {
36
37
  /** Why the width is what it is — printed on the step line. */
37
38
  readonly widthReason?: string;
38
39
  /** The machine-pool lease (`test-slots.ts`), for a default-width run. */
39
- readonly lease?: (want: number) => Promise<{ readonly count: number; release(): void }>;
40
+ readonly lease?: MachineLease;
40
41
  /** The machine's pace (`verify-pace.ts`): each test's default and declared deadline stretch by it. */
41
42
  readonly pace?: MachinePace;
42
43
  }
@@ -76,7 +77,7 @@ export async function runParallel(options: ParallelRunOptions): Promise<StepOutc
76
77
  runner: options.runner,
77
78
  batches,
78
79
  workers,
79
- ...(options.lease === undefined || workers === 1 ? {} : { lease: options.lease }),
80
+ ...(options.lease === undefined ? {} : { lease: options.lease }),
80
81
  argsFor: (batch, width) =>
81
82
  testArgs({
82
83
  files: batch,
@@ -16,13 +16,14 @@ import { TEST_TYPES } from '@ultimat3/testing';
16
16
  import { narrowToApp } from './affected-tests';
17
17
  import { checkEvalBaselines, checkEvalCoverage, checkEvalRecording } from './app-evals';
18
18
  import { judgeCoverage } from './coverage-floor';
19
+ import { withHeavy } from './heavy';
19
20
  import { msg } from './messages';
20
21
  import { countsOf } from './test-counts';
21
22
  import { testEnvOverrides } from './test-dotenv';
22
23
  import type { TestFile } from './test-select';
23
24
  import { discoverTests } from './test-select';
24
25
  import { TEST_TIMINGS_FILE } from './test-shards';
25
- import { machineLease } from './test-slots';
26
+ import { machineLease, suiteWeight } from './test-slots';
26
27
  import type { WorkerPlan } from './test-workers';
27
28
  import { availableCpus, SERIAL_TYPES, totalMemory, workerPlan } from './test-workers';
28
29
  import { runCovered } from './verify-coverage-run';
@@ -126,25 +127,26 @@ const runSerial = async (
126
127
  // the slice: `bun test` reads a positional as a path filter either way.
127
128
  [...whole.filter((arg, at) => at < 2 || arg.startsWith('--')), ...[...files].sort()];
128
129
  const envOverrides = { ...testEnvOverrides(ctx.root, ctx.env ?? Bun.env), ...paceEnv(ctx.pace) };
129
- const exec = (e2e: { command: readonly string[]; env: typeof envOverrides }) =>
130
- ctx.runner(e2e.command, {
131
- cwd: ctx.root,
132
- ...(Object.keys(e2e.env).length === 0 ? {} : { env: e2e.env }),
133
- });
130
+ // One serial suite is one reservation for its whole length, the app it boots included.
131
+ const execWith =
132
+ (fds: readonly number[]) => (e2e: { command: readonly string[]; env: typeof envOverrides }) =>
133
+ ctx.runner(e2e.command, {
134
+ cwd: ctx.root,
135
+ ...(Object.keys(e2e.env).length === 0 ? {} : { env: e2e.env }),
136
+ ...(fds.length === 0 ? {} : { inheritFds: fds }),
137
+ });
138
+ const hostEnv = ctx.env ?? Bun.env;
134
139
  // The e2e step drives a real browser against the app it spawns, when this machine has one.
135
- const result =
136
- type === 'e2e'
137
- ? await withE2eApp(
138
- {
139
- root: ctx.root,
140
- isApp: isApp(ctx.root),
141
- command,
142
- env: envOverrides,
143
- hostEnv: ctx.env ?? Bun.env,
144
- },
145
- exec,
146
- )
147
- : await exec({ command, env: envOverrides });
140
+ const result = await withHeavy(
141
+ { label: `verify ${type}`, cwd: ctx.root, env: hostEnv, ...suiteWeight(type) },
142
+ (child) => {
143
+ const env = { ...envOverrides, ...child.env };
144
+ const exec = execWith(child.fds);
145
+ return type === 'e2e'
146
+ ? withE2eApp({ root: ctx.root, isApp: isApp(ctx.root), command, env, hostEnv }, exec)
147
+ : exec({ command, env });
148
+ },
149
+ );
148
150
  const outcome: StepOutcome = {
149
151
  ...fromExec(result, {
150
152
  code: 'X_TEST_FAILED',
@@ -220,7 +222,12 @@ const runType = async (ctx: VerifyContext, type: TestType): Promise<StepOutcome>
220
222
  const plan =
221
223
  ctx.workers === undefined ? workerPlan(availableCpus(), totalMemory(), env) : undefined;
222
224
  const workers = ctx.workers ?? (plan as WorkerPlan).workers;
223
- const lease = plan === undefined ? undefined : machineLease(plan.workers, env);
225
+ const lease = machineLease(env, {
226
+ cwd: ctx.root,
227
+ label: `verify ${type}`,
228
+ type,
229
+ ...(plan === undefined ? { exact: true } : {}),
230
+ });
224
231
  const widthReason =
225
232
  plan === undefined
226
233
  ? `${String(Math.min(workers, files.length))} workers (--workers)`
@@ -191,14 +191,16 @@ an operator then proves who they are with a short PIN, and that browser's sessio
191
191
  | the operator's PIN | the app's own entity (`operators`: `userId`, `pinHash`), never `x_users.password_hash` — a PIN is weaker than the password policy allows (`X_PASSWORD_WEAK`) | `hashPassword(pin)` on enrolment |
192
192
  | the lockout | **before** the KDF, keyed per operator and per device: a 4-digit PIN is 10 000 guesses, so the budget is the whole defence | `appAuth().limiter.reserve('pin:<operatorId>:<deviceId>')` — `X_ACCOUNT_LOCKED` refuses; `recordSuccess` on a match |
193
193
  | the check | constant cost whether or not the operator exists | `verifyPassword({ hash: row?.pinHash ?? null, password: pin })` |
194
- | the switch | a session for the operator, capped at the device session's ceiling, set as that browser's cookie; signing the operator out lands on the device sign-in again | `createSession(appAuth().sessions, { userId: operator.userId, absoluteExpiresAt: device.absoluteExpiresAt })`, then `sessionCookie(issued.token, appAuth().sessions.policy)` on the response |
194
+ | the switch | a session for the operator, capped at the device session's ceiling, set as that browser's cookie; signing the operator out lands on the device sign-in again | `createSession(appAuth().sessions, { userId: operator.userId, absoluteExpiresAt: device.absoluteExpiresAt })`, then `setCookie(sessionCookie(issued.token, appAuth().sessions.policy))` from the action |
195
195
  | who may switch | the app's policy on its own `switchOperator` action: the caller holds the `device` role | `can('operator:switch', …)` |
196
196
 
197
197
  The action is the app's (`apps/web/app/operators/actions/switch-operator.ts`), so it projects like
198
198
  any other — route, typed client, MCP tool, contract test. Nothing in the framework learns that a PIN
199
199
  exists, which is the point: the next app's PIN rules (length, rotation, which devices) are its own.
200
200
 
201
- The check itself, one file the action calls with the operator row it loaded:
201
+ The check itself, one file the action calls with the operator row it loaded. `switchOperator` knows
202
+ nothing of HTTP, so a job or a test can run it; the action's `handle` calls
203
+ `switchOperatorOnResponse`, and no route carries the cookie:
202
204
 
203
205
  ```ts
204
206
  // apps/web/shared/base/operator-pin.ts
@@ -212,6 +214,7 @@ import {
212
214
  sessionCookie,
213
215
  verifyPassword,
214
216
  } from '@ultimat3/auth';
217
+ import { setCookie } from '@ultimat3/http';
215
218
 
216
219
  /** The app's `operators` row: whose PIN, and its hash. Never `x_users.password_hash`. */
217
220
  export interface OperatorRow {
@@ -253,6 +256,16 @@ export async function switchOperator(
253
256
  });
254
257
  return { issued, cookie: sessionCookie(issued.token, auth.sessions.policy) };
255
258
  }
259
+
260
+ /** The action's half: the same switch, its cookie set on the response to this request. */
261
+ export async function switchOperatorOnResponse(
262
+ auth: Auth,
263
+ input: OperatorSwitch,
264
+ ): Promise<IssuedSession> {
265
+ const { issued, cookie } = await switchOperator(auth, input);
266
+ setCookie(cookie);
267
+ return issued;
268
+ }
256
269
  ```
257
270
 
258
271
  The comparison is the KDF's, constant-time inside `Bun.password.verify`; a PIN is never hashed
@@ -254,9 +254,8 @@ Each job sizes its own test width the same way the laptop does (`x verify` print
254
254
  line, e.g. `3 workers (budget 4.0 GB)`): a budget of `max(2.75 GiB, 25% of the runner's RAM)`,
255
255
  1.25 GiB planned per worker, never more workers than cores. On a 16 GB `ubuntu-latest` that is 3
256
256
  workers; a 62 GB, 16-core workstation plans 12 (`As of 2026-11-07`, when the fixed 4 GiB cap went —
257
- the machine-wide slot pool is what keeps two runs on one box inside one budget). `ULTIMATE_TEST_MEMORY_BUDGET=6g` or `ULTIMATE_TEST_MAX_WORKERS=4` override it; `--workers`
258
- wins over both. The machine-wide slot pool (see [Testing](Testing#memory-width-and-isolation))
259
- has nothing to share on a one-job VM; `ULTIMATE_TEST_SLOTS=0` turns it off.
257
+ the [machine ledger](Many-Agents) is what keeps two runs on one box inside one budget). `ULTIMATE_TEST_MEMORY_BUDGET=6g` or `ULTIMATE_TEST_MAX_WORKERS=4` override it; `--workers`
258
+ wins over both. The [machine ledger](Many-Agents) has nothing to share on a one-job VM and is off under `CI`.
260
259
 
261
260
  ## Skipping the build's duplicate preflight
262
261
 
@@ -72,6 +72,7 @@ x version # CLI version
72
72
  | `x cache graph\|bust <tag>\|clear` | the tag graph off the manifest (what each write evicts), a bust of one tag or every declared tag through the app's own tiers and bus · `stats` was removed `As of 2026-11-15` ([Known gaps](Known-Gaps#open-by-decision)) | shipped |
73
73
  | `x explain <query> [--input <json>] [--org <id>]` | one declared query run once on the dev database, every statement it sent planned by the `exercise` step's oracle | shipped |
74
74
  | `x profile <route> [--runs 20] [--top 10]` | a CPU profile of rendering one route in this process: the hottest functions, file and line | shipped |
75
+ | `x heavy [status]` · `x heavy run [--label s] [--mb n] -- <command…>` | the machine's shared memory ledger: who runs, who is queued, load and memory; any command run inside one reservation, its exit code passed through | shipped |
75
76
  | `x status [--url <origin>] [--samples n]` | the build each live worker runs (`x_job_workers`), and the build, status and role each sampled origin's `/readyz` answers | shipped |
76
77
 
77
78
  ## x new
@@ -1288,16 +1289,16 @@ x doctor [--port 3000] [--json]
1288
1289
 
1289
1290
  Checks Bun version, env completeness, source drift, **the newest migration's `.snapshot.json`**, port availability, PWA prerequisites and **embedded-Postgres readiness** — each failing check carries its own fix command.
1290
1291
 
1291
- It also lists the shipped guards the app holds that differ from the current template — a copy from an older release, or the app's own edit — and warns `X_SHIPPED_GUARD_MISSING` for each one the app's `guards/` does not hold, its fix `x g guard <name> && x verify --only boundaries --json` (`As of 31.22`: a warning beside the verdict in `data.warnings[]`, so the exit status is unchanged; it was a listing). `As of 2026-10-07` (owner decision 8: shipped guards stay copies the app owns).
1292
+ It also lists the copies of shipped guards the app's `guards/` still holds, each with `X_GUARD_VENDORED` beside the verdict in `data.warnings[]`: shipped guards run from the installed framework, so a copy runs in place of the shipped one and never receives a fix. `As of 31.28`. No shipped guard is ever missing, so `data.guards.missing` is always `[]`.
1292
1293
 
1293
1294
  | Listing | One line each | `--json` |
1294
1295
  |---|---|---|
1295
- | missing | its `X_SHIPPED_GUARD_MISSING` warning line (`As of 31.22`) | `data.guards.missing[]`: `{ name, add }`, and the warning in `data.warnings[]` |
1296
- | differs from the template (line endings ignored) | `x g guard <name> --force` — rewrites the guard and its test; review the diff, and restore your edit if it was deliberate | `data.guards.differs[]`: `{ name, refresh }` |
1296
+ | a copy, identical or edited | the edit that resolves it: `rm -f` for an identical copy; for an edited one, `mv` to `guards/app-<name>.ts` and `"<name>": "off"` in `guards/shipped.json` | `data.guards.vendored[]`: every copy's name |
1297
+ | an edited copy | the same line | `data.guards.differs[]`: `{ name, refresh, diff }` — `refresh` is that edit |
1297
1298
 
1298
- A listing, never a finding: deleting or editing a guard is how an app changes a rule, so the verdict does not move.
1299
+ A listing, never a finding: the verdict does not move. `x upgrade` applies the same migration (`vendored-guards` codemod); how a shipped guard reports is a row in `guards/shipped.json`.
1299
1300
 
1300
- Four warnings about how the app is held, `As of 31.16.0` (a fifth, `X_SHIPPED_GUARD_MISSING`, `As of 31.22`) — beside the verdict, never in it: the exit status, `findings` and `data.codes` stay as they were, and `--json` carries each as `data.warnings[]` (`{ code, cause, fix, docs, at }`). None is a gate step; on `next` they join the verdict, red:
1301
+ Warnings about how the app is held — beside the verdict, never in it: the exit status, `findings` and `data.codes` stay as they were, and `--json` carries each as `data.warnings[]` (`{ code, cause, fix, docs, at }`). None is a gate step; on `next` they join the verdict, red:
1301
1302
 
1302
1303
  | Code | Asked | Fix |
1303
1304
  |---|---|---|
@@ -1305,7 +1306,7 @@ Four warnings about how the app is held, `As of 31.16.0` (a fifth, `X_SHIPPED_GU
1305
1306
  | `X_VERIFY_STEP_UNFLOORED` | a gate step applies here — its suite files exist, its input is committed — and `x.verify.json` `"steps"` does not hold it, so a deleted suite reads as skipped. `e2e` is never proposed (the scaffold's placeholder skips until a browser driver is registered) | `x verify --only <steps> --json`, then add each step that passed to `"steps"` |
1306
1307
  | `X_FRAMEWORK_PIN_RANGE` | an `@ultimat3/*` dependency in any of the app's manifests is anything but an exact version or a `workspace:`/`file:`/`link:` path (`^31.0.0`, `*`, `latest`, `>=31 <32`; an `npm:` alias by its own spec), one finding per manifest | the exact version `bun install` resolved, at the line named; then `bun install` |
1307
1308
  | `X_ENV_NAME_RESERVED` | a name the app declares in `envSchema` or seals in `secrets.enc.json` is one `FRAMEWORK_ENV` (`@ultimat3/core`) lists as a `switch` or `internal` name — setting it for the app also switches that package's behaviour. Deploy-contract names (`DATABASE_URL`, `PORT`) and host names are not collisions | rename it `APP_<name>` (or delete it where the value is meant for the framework); then `x env example` |
1308
- | `X_SHIPPED_GUARD_MISSING` (`As of 31.22`) | a guard `x new` ships is not in the app's `guards/`, so the gate does not hold the app to that rule — one per guard | `x g guard <name> && x verify --only boundaries --json` |
1309
+ | `X_GUARD_VENDORED` (`As of 31.28`) | the app's `guards/` holds a copy of a shipped guard, which runs in place of the built-in one and never receives a fix — one per copy. `boundaries` lists it too | the resolving edit above |
1309
1310
 
1310
1311
  **Redundant indexes**, the same way (`As of 2026-11-14`): each implicit index the entities describe that another index, the primary key or a unique invariant already leads with, still in the newest migration's snapshot, is one line — `<table>.<index> (<columns>) — <covering index>` — under a header naming `x db gen "drop redundant indexes" --drop-redundant`; `--json`: `data.redundantIndexes[]` = `{ table, name, columns, coveredBy }`, `[]` when none, absent when the app would not load or has no snapshot. A listing, never a finding: every write pays for each twice, and dropping it is a migration the app opts into.
1311
1312
 
@@ -1614,9 +1615,11 @@ sampled throughout.
1614
1615
  | `roll-before-migrate` | the roles started before `ROLE=migrate`, on a schema stamped by an older build | `roles-wait`, `serves-after-migrate`, `one-wait-line` |
1615
1616
 
1616
1617
  `roll-before-migrate`, `As of 2026-11-15`, is the rollout order a deploy cannot always hold: no
1617
- proxy and no load. The scratch database is migrated, its framework stamp (`x_jobs`' table comment)
1618
+ fault and no load. The scratch database is migrated, its framework stamp (`x_jobs`' table comment)
1618
1619
  is rewound to name only an older build, then `web`, `worker` and `scheduler` start on it without
1619
- waiting for readiness. Once each has logged its wait (or exited), they are held 3 s and
1620
+ waiting for readiness, with `sync` when `TEST_NATS_URL` is set and `replicator` when
1621
+ `TEST_REPLICATION_URL` names a logical server (the scratch database then lives there) and the app
1622
+ has an entity on a table. A role left out is in `data.rolesNotPlayed[]`, `{ drill, role, needs }`. Once each has logged its wait (or exited), they are held 3 s and
1620
1623
  `ROLE=migrate` runs again. Each must stay up (`roles-wait`: an exit is a crash-loop), log exactly
1621
1624
  one line naming `X_FRAMEWORK_SCHEMA_UNAPPLIED` (`one-wait-line`), and answer `/readyz` 200 once
1622
1625
  migrate has run (`serves-after-migrate`). `ULTIMATE_SCHEMA_WAIT_MS` is inherited: `0` — refuse at
@@ -1635,7 +1638,7 @@ property is red when no job ran during the drill, `sync-resumes` when no sync cl
1635
1638
  A service the app uses must be up for every drill; an unset one is refused, never skipped. A named
1636
1639
  drill that faults a service the app does not declare is refused; a whole run lists it under
1637
1640
  `data.notRun`. `--list` prints the table and runs nothing. `--json`: `{ budgets, targets,
1638
- skippedWrites, drills[], notRun }`, each drill `{ name, verdict, evidence, budgets, baseline }`.
1641
+ skippedWrites, drills[], notRun, rolesNotPlayed }`, each drill `{ name, verdict, evidence, budgets, baseline }`.
1639
1642
 
1640
1643
  Errors: `X_DRILL_FAILED` (one per property that did not hold), `X_DRILL_SERVICE_MISSING`, `X_CLI_UNKNOWN_COMMAND`, `X_CLI_BAD_FLAG`.
1641
1644
 
@@ -1760,8 +1763,8 @@ One major per run, so each hop's gate attributes its red to that hop. `As of 30.
1760
1763
  | 2 | read every workspace's `@ultimat3/*` pins, `overrides` and `resolutions` included | `X_UPGRADE_PIN_UNREADABLE`, `X_UPGRADE_MIXED_PINS` |
1761
1764
  | 3 | `bun pm view @ultimat3/cli versions`: the next major's newest; the last major's newest when no later major exists | `X_UPGRADE_REGISTRY_UNREACHABLE`, `X_UPGRADE_HOP_TOO_WIDE`, `X_UPGRADE_VERSION_UNPUBLISHED`, `X_BUN_VERSION` |
1762
1765
  | 4 | write exact pins, raise the Bun floor | — |
1763
- | 5 | `bun install` | `X_UPGRADE_INSTALL_FAILED`, `fix:` carries the undo |
1764
- | 6 | the installed CLI: `x upgrade codemods --from <from> --to <to>` (below), then `x manifest`, `x doctor --json`, each missing guard (`x g guard <name>`, kept only when `x verify --only boundaries` finds nothing more), a Bun-floor hop's `x verify --only unit` coverage rebaseline, `x exercise --json` and its `exercise` floor figures, `x verify --json` | `X_UPGRADE_GATE_UNREADABLE`, as a finding on a red hop |
1766
+ | 5 | `bun install`, then `bun update <names>` for each transitive package `bun.lock` holds under an advisory floor (`X_ADVISORY_FLOOR_UNMET`) | `X_UPGRADE_INSTALL_FAILED`, `fix:` carries the undo |
1767
+ | 6 | the installed CLI: `x upgrade codemods --from <from> --to <to>` (below), then `x manifest`, `x doctor --json`, each guard that doctor reports missing (only a hop landing before 31.28: `x g guard <name>`, kept when `x verify --only boundaries` finds nothing more), a Bun-floor hop's `x verify --only unit` coverage rebaseline, `x exercise --json` and its `exercise` floor figures, `x verify --json` | `X_UPGRADE_GATE_UNREADABLE`, as a finding on a red hop |
1765
1768
 
1766
1769
  A dry run refuses exactly what the real run would, then stops before step 4 — after previewing this CLI's codemods for the span, written nowhere. It never commits; `git diff` is the hop. Under `--json` fd 1 is one document, fd 2 a `{"upgrade":"<stage>"}` line per stage and a heartbeat a minute.
1767
1770
 
@@ -1779,7 +1782,7 @@ A dry run refuses exactly what the real run would, then stops before step 4 —
1779
1782
  | `pins[]` | `{ file, name, from, to }` |
1780
1783
  | `bun` | `{ from, to, edited[], manual[] }`. `manual[]`: `{ path, line, text, why }`, a site only you can move, listed on every run |
1781
1784
  | `agentsMd` | `link`: `AGENTS.md` was byte-identical to `CLAUDE.md` and the hop makes it a relative symlink to it · `linked`: already one · `differs`: two different files, left alone; merge what only `AGENTS.md` says into `CLAUDE.md`, then `ln -sf CLAUDE.md AGENTS.md` · `none`: one of the two is missing · `null`: no hop planned |
1782
- | `guards` | `{ reported, missing[], differs[], installed[], withheld[] }` from the hop's own `x doctor`. `As of 31.16.0` each missing shipped guard is written from the installed release's template and kept when `boundaries` finds nothing more with it on disk: `installed[]` names it. One the tree already breaks is taken back out: `withheld[]` is `{ name, add, findings }` (`findings: null` when the count could not be measured) and `missing[]` still lists it. `differs[]` — the app's edit or an older copy — is never overwritten: `x g guard <name> --force` is yours. `reported: false` is a CLI too old to list them, which is not the same as none |
1785
+ | `guards` | `{ reported, missing[], differs[], installed[], withheld[], baselined[]? }` from the hop's own `x doctor`. A hop landing on 31.28 or later has `missing[]`, `installed[]` and `withheld[]` empty: shipped guards run built in. Landing earlier (`As of 31.16.0`), each missing shipped guard is written from the installed release's template and kept when `boundaries` finds nothing more with it on disk: `installed[]` names it; one the tree already breaks is taken back out: `withheld[]` is `{ name, add, findings }` (`findings: null` when the count could not be measured) and `missing[]` still lists it. `differs[]` is `{ name, refresh }`: an edited copy the hop's `vendored-guards` codemod left, never overwritten, `refresh` the edit that resolves it. `reported: false` is a CLI too old to list them, which is not the same as none |
1783
1786
  | `guards.baselined` | `[{ name, findings }]`, absent when empty, `As of 2026-11-15`: a guard the tree breaks, kept anyway — its measured count merged into `x.verify.json` as `"guardBaseline": { "<name>": n }` (beside the app's keys; a baseline the app already wrote for it, or a floor that is not a JSON object, is never touched) and kept only when the installed CLI's `boundaries` then finds no more than before. Also in `installed[]`. `findings: null` stays withheld |
1784
1787
  | `coverage` | a hop that moved the Bun floor re-measures unit coverage (`x verify --only unit`); only when that measurement is `X_COVERAGE_BELOW_FLOOR` is the `x.verify.json` `coverage` floor moved to it, the number that fell alone, with a dated `why`: `{ file, measured, from, to, why }`. `null` when nothing moved |
1785
1788
  | `exerciseFloor` | `{ file, written }`: the `exercise` keys (`unprovenMax`, `statementsMax` ≥ 100) the hop's own `x exercise` measured, written into an `x.verify.json` that stated none, so the hop stays green and the floor only falls. A key the app already wrote is never touched; `null` when nothing was written |
@@ -2164,6 +2167,15 @@ For each violation involving the file it reports the offending edge, the full ch
2164
2167
 
2165
2168
  Every flag is read before the database opens: a refusal costs no boot.
2166
2169
 
2170
+ ## x heavy
2171
+
2172
+ `As of 2026-11-18`. `x heavy [status] [--json]` · `x heavy run [--label s] [--mb n] [--json] -- <command…>` — the machine ledger every heavy run on this machine reserves its measured memory in, from any directory, in any repository. The rules, the weights and what stays outside: [Working with many agents](Many-Agents).
2173
+
2174
+ | Form | Answers |
2175
+ |---|---|
2176
+ | `x heavy` / `x heavy status` | `data.holds` and `data.queue` (label, directory, MB, pid, age), `data.capacityMb`, `data.usedMb`, `data.coreCap`, `data.machine` (load, runnable tasks, available and usable memory); `data.enabled: false` with `data.off` naming why (`ci`, `test-run`, `disabled`, `unsupported`) |
2177
+ | `x heavy run -- <command…>` | runs it inside one reservation of `--mb` (default: a monorepo typecheck). Exit code passed through, `128 + n` for a signal, 127 and `X_HEAVY_COMMAND_NOT_FOUND` for no such program. SIGTERM and SIGHUP are forwarded. Its summary goes to stderr, so stdout stays the command's; with `--json` the one document is on stdout and the command's stdout moves to stderr |
2178
+
2167
2179
  ## x status
2168
2180
 
2169
2181
  `As of 2026-11-15`. `x status [--url <origin>[,<origin>…]] [--samples n] [--json]` — what the running deployment is, from what it already records. A read, exit 0 whatever it finds: whether one build is fully out is [`x deploy verify`](#x-deploy-verify)'s question.
@@ -302,7 +302,7 @@ From code: `invalidateTags([...])` from `@ultimat3/cache`, the call `x cache bus
302
302
  |---|---|---|
303
303
  | `X_CACHE_UNTAGGED_QUERY` | **reserved, nothing raises it** `As of 2026-08` — a query's tables are covered by no tag, so it could never be invalidated ([Error codes → Reserved codes](Error-Codes#reserved-codes)) | declare the entity tag, then `x manifest` |
304
304
  | `X_CACHE_TAG_UNKNOWN` | `tag "<name>" is not declared by any entity` | `declareTags(['<name>'])` beside the app's other declared tags, plus the name in its `CacheTagRegistry`; for a typo, correct the tag |
305
- | `X_CACHE_TOO_LARGE` | `entry "<key>" is <n>B, over the <tier> budget of <m>B` | `lruTier({ maxBytes: <n> })` / `redisTier({ maxValueBytes: <n> })` where the tier is built, or cache a projection instead of the row |
305
+ | `X_CACHE_TOO_LARGE` | `entry "<key>" is <n>B, over the <tier> budget of <m>B` | `cacheTiers: [lruTier({ maxBytes: <n> })]` / `cacheTiers: [redisTier({ maxValueBytes: <n> })]` in `apps/web/runtime.ts` ([limits](Configuration#cache)), or cache a projection instead of the row |
306
306
  | `X_CACHE_DRIVER_UNAVAILABLE` | `cache tier "<driver>" is unavailable` — a Redis command missed its deadline, or the tier is parked after one; or a purge driver built without its token | the error carries the exact config or command to fix |
307
307
  | `X_CACHE_PURGE_FAILED` | `<driver> refused the purge (HTTP <status>)` — a wrong token, a zone without tag purge, a throttle, or a key a CDN would split | `meta.retryable === true` → the identical purge can land again; otherwise set the env key the `fix` names |
308
308