@ultimat3/cli 31.47.0 → 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 (62) 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 +22 -11
  7. package/src/codemods/docs-many-agents.ts +30 -0
  8. package/src/codemods/e2e-suite-floor.ts +42 -0
  9. package/src/codemods/e2e-suite.ts +71 -0
  10. package/src/codemods/index.ts +4 -0
  11. package/src/codemods/pending.ts +2 -2
  12. package/src/codemods/test-ports.ts +40 -33
  13. package/src/codemods/test-suites.ts +11 -22
  14. package/src/codemods/verify-floor-skips.ts +18 -6
  15. package/src/doctor-advisory-floors.ts +30 -8
  16. package/src/error-codes-tooling.ts +9 -3
  17. package/src/exec.ts +11 -3
  18. package/src/heavy-cores.ts +51 -0
  19. package/src/heavy-env.ts +19 -0
  20. package/src/heavy-errors.ts +36 -0
  21. package/src/heavy-flock.ts +73 -0
  22. package/src/heavy-ledger.ts +358 -0
  23. package/src/heavy-memory.ts +67 -0
  24. package/src/heavy-weights.ts +47 -0
  25. package/src/heavy.ts +290 -0
  26. package/src/local-cli.ts +6 -5
  27. package/src/mcp-errors.ts +4 -1
  28. package/src/messages.ts +11 -0
  29. package/src/registry.ts +2 -0
  30. package/src/role-replicator.ts +5 -3
  31. package/src/runtime-cache.ts +24 -3
  32. package/src/runtime-overrides.ts +4 -2
  33. package/src/templates/guard-released-forms.ts +35 -13
  34. package/src/templates/scaffold-claude-agents.ts +9 -6
  35. package/src/templates/scaffold-claude-commands.ts +1 -1
  36. package/src/templates/scaffold-docs.ts +5 -4
  37. package/src/templates/scaffold-suites.ts +22 -0
  38. package/src/test-batches.ts +9 -3
  39. package/src/test-shards.ts +3 -3
  40. package/src/test-slots.ts +35 -161
  41. package/src/upgrade-gate-codemods.ts +1 -18
  42. package/src/verify-checks.ts +4 -3
  43. package/src/verify-coverage-run.ts +5 -4
  44. package/src/verify-deadline.ts +18 -2
  45. package/src/verify-heavy-steps.ts +26 -0
  46. package/src/verify-test-run.ts +3 -2
  47. package/src/verify-tests.ts +27 -20
  48. package/wiki/Building-Your-Own-Base.md +15 -2
  49. package/wiki/CI-Parallel-Gate.md +2 -3
  50. package/wiki/CLI-Reference.md +25 -13
  51. package/wiki/Caching-And-Invalidation.md +1 -1
  52. package/wiki/Compared.md +13 -11
  53. package/wiki/Configuration.md +22 -4
  54. package/wiki/Home.md +1 -0
  55. package/wiki/Interface-Rules.md +1 -1
  56. package/wiki/Known-Gaps.md +1 -1
  57. package/wiki/Mail.md +1 -1
  58. package/wiki/Many-Agents.md +60 -0
  59. package/wiki/Stability.md +1 -1
  60. package/wiki/Testing.md +5 -5
  61. package/wiki/Tutorial-01-First-App.md +2 -2
  62. package/wiki/Upgrading.md +2 -1
@@ -23,7 +23,7 @@ import { testServicesFiles } from './scaffold-test-services';
23
23
  */
24
24
  const conventions = (app: NameSet): string => `# ${app.pascal}
25
25
 
26
- Human-authored, short, stable — one file under two names, \`AGENTS.md\` being a symlink to it.
26
+ One file, two names: \`AGENTS.md\` is a symlink to it.
27
27
  Facts live in \`x.manifest.json\`; this file holds only what an agent cannot infer from the code.
28
28
 
29
29
  Every row below names what refuses it. A rule with nothing in the last column does not exist.
@@ -40,6 +40,7 @@ queries, jobs, MCP tools, published operations and tests it touches, each with p
40
40
  |---|---|---|
41
41
  | One gate | \`bun run verify\` — \`bunx x verify\`, which builds what its \`budgets\` step weighs. Green means shippable; never merge red. CI runs the same gate, cut into parts: \`bun run verify plan --json\` names them, each runner runs \`bun run setup && bun run verify --only <steps>\`, and \`bun run verify merge\` is the verdict | the gate itself, and \`.github/workflows/ci.yml\` on every push and pull request; \`.github/workflows/image.yml\` publishes only a commit it passed |
42
42
  | Coverage | the unit suite covers 95% of the lines and functions of this app's own source — every file under \`apps/\` and \`packages/\`, one no test loads counted at 0%. A floor, not the goal: a test added to raise it is proven by mutation — break the source, watch it go red, restore | \`X_COVERAGE_BELOW_FLOOR\` on the \`unit\` step; \`coverage\` in \`x.verify.json\` states the floor, and it only rises |
43
+ | Many agents | a worker runs its own files; the coordinator runs the gate once | \`bunx x heavy status\` |
43
44
  | One way | generators, not hand-rolled files: \`bunx x g resource\`, \`bunx x g action\`, \`bunx x g route\` | review |
44
45
  | Surfaces | \`site/\` is 0kb JS and may not import \`app/\`; \`shared/\` is a leaf | \`X_BOUNDARY_SITE_TO_APP\` |
45
46
  | Data | routes call actions and queries; only \`repo.ts\` touches the database | \`X_BOUNDARY_ROUTE_TO_DB\` |
@@ -134,11 +135,11 @@ Commands: \`bun run setup\`, \`bun run dev\`, \`bun run verify\`, \`bunx x g <pr
134
135
  | Tool | What it answers | How to reach it |
135
136
  |---|---|---|
136
137
  | \`x.manifest.json\` | every route, action, query, job and policy, generated — read it before searching the tree | \`bunx x manifest\` rewrites it |
137
- | \`bunx x impact <file|primitive> --json\` · \`bunx x graph --json\` | what an edit reaches, and the app as one graph (declared, import and observed edges) | rebuilt from the loaded app on every call |
138
+ | \`bunx x impact <file|primitive> --json\` · \`bunx x graph --json\` | what an edit reaches, and the app as one graph (declared, import and observed edges) | rebuilt on every call |
138
139
  | \`.mcp.json\` | the dev tools over MCP: routes, schema, policies, the database, tests, the gate — \`bunx x mcp tools\` lists them | a client that reads \`.mcp.json\` starts it; from any other, run \`bunx @ultimat3/cli mcp serve --transport stdio\` here |
139
140
  | \`POST /mcp\` | this app's own tools — every action declaring \`mcp: { expose: true }\` — for a remote agent | \`apps/web/mcp.ts\`; under \`bun run dev\`, \`Authorization: Bearer dev-agent.admin\`, else an API key |
140
- | \`.claude/commands/feature.md\` | build or fix one thing end to end, done when \`bun run verify\` is green | plain markdown: any agent can read one and follow it |
141
- | \`.claude/commands/planx.md\` | write a plan to \`docs/plans/\` for another agent to execute | the same |
141
+ | \`.claude/commands/feature.md\` | build or fix one thing end to end, done when \`bun run verify\` is green | plain markdown any agent can follow |
142
+ | \`.claude/commands/planx.md\` | write a plan to \`docs/plans/\` | the same |
142
143
  | \`.claude/commands/verify.md\` | run the gate and fix what it reports | the same |
143
144
 
144
145
  Project notes for ${app.kebab}: replace this line with the conventions a newcomer could not guess.
@@ -61,6 +61,28 @@ e2eTest('/ loads in a browser and names itself', async ({ page }) => {
61
61
  });
62
62
  `;
63
63
 
64
+ /**
65
+ * The suite `x upgrade` gives an app with no landing page, beside the page it visits. The status and
66
+ * never the title: an anonymous browser may be refused a page behind sign-in, which is the page
67
+ * working; a 5xx, or an app that does not boot, is what no app should ship.
68
+ */
69
+ export const pageE2eSuite = (
70
+ url: string,
71
+ ): string => `// ${url} in a real browser, against the running app. A page behind sign-in may refuse this anonymous
72
+ // visit, and that passes: what fails is a server error, or an app that does not boot. Sign in here
73
+ // to assert more. Its own file because the gate types a test by its FILENAME.
74
+ import { e2eTest, expect } from '@ultimat3/testing';
75
+
76
+ e2eTest('${url} answers a browser without a server error', async ({ page }) => {
77
+ await page.goto('${url}');
78
+ const status = await page.evaluate(() => {
79
+ const [navigation] = performance.getEntriesByType('navigation');
80
+ return (navigation as PerformanceNavigationTiming).responseStatus;
81
+ });
82
+ expect(status).toBeLessThan(500);
83
+ });
84
+ `;
85
+
64
86
  /** The live suite, in the db package every scaffold writes. */
65
87
  export const liveSuiteFiles = (): readonly GeneratedFile[] => [
66
88
  { path: LIVE_SUITE_PATH, contents: liveSuite() },
@@ -31,7 +31,7 @@
31
31
  import type { ExecResult, Runner } from './exec';
32
32
  import { execOutput } from './exec';
33
33
  import { msg } from './messages';
34
- import { SLOT_HELD_ENV } from './test-slots';
34
+ import type { MachineLease } from './test-slots';
35
35
  import { BATCH_FILES_PER_WORKER } from './test-workers';
36
36
 
37
37
  /**
@@ -89,7 +89,7 @@ export async function runBatches(input: {
89
89
  * Lease the batch's workers from the machine pool (`test-slots.ts`) before it starts, and give
90
90
  * them back when it exits — so two runs on one box share its budget batch by batch.
91
91
  */
92
- readonly lease?: (want: number) => Promise<{ readonly count: number; release(): void }>;
92
+ readonly lease?: MachineLease;
93
93
  readonly options: Parameters<Runner>[1];
94
94
  /**
95
95
  * Launch no further batch once one is red. Set for a caller-forwarded `--bail`: Bun stops a
@@ -109,7 +109,13 @@ export async function runBatches(input: {
109
109
  input.argsFor(files, width),
110
110
  lease === undefined
111
111
  ? input.options
112
- : { ...input.options, env: { ...input.options.env, [SLOT_HELD_ENV]: '1' } },
112
+ : {
113
+ ...input.options,
114
+ env: { ...input.options.env, ...lease.env },
115
+ ...(lease.fds === undefined || lease.fds.length === 0
116
+ ? {}
117
+ : { inheritFds: lease.fds }),
118
+ },
113
119
  );
114
120
  } finally {
115
121
  lease?.release();
@@ -51,6 +51,7 @@ import { msg } from './messages';
51
51
  import type { CommandResult, Finding, JsonValue, StepResult } from './output';
52
52
  import { quoteArg } from './shell-quote';
53
53
  import { testEnvOverrides } from './test-dotenv';
54
+ import type { MachineLease } from './test-slots';
54
55
 
55
56
  /** Bun's per-file durations, cached under the run's root and refreshed by every parallel run. */
56
57
  export const TEST_TIMINGS_FILE = '.x/test-timings.json';
@@ -201,7 +202,7 @@ export interface RunShardsOptions {
201
202
  /** `--seed`: handed to the children by the caller's runner, printed back in the reproduce. */
202
203
  readonly seed?: number;
203
204
  /** The machine-pool lease (`test-slots.ts`), for a default-width run. */
204
- readonly lease?: (want: number) => Promise<{ readonly count: number; release(): void }>;
205
+ readonly lease?: MachineLease;
205
206
  }
206
207
 
207
208
  const isolatedRun = (options: RunShardsOptions): boolean => {
@@ -297,8 +298,7 @@ export async function runShards(options: RunShardsOptions): Promise<CommandResul
297
298
  batches,
298
299
  stopOnFailure: bailing,
299
300
  workers: pass.workers,
300
- // A serial pass is one worker: only a default-width parallel pass leases from the pool.
301
- ...(pass.workers > 1 && options.lease !== undefined ? { lease: options.lease } : {}),
301
+ ...(options.lease === undefined ? {} : { lease: options.lease }),
302
302
  argsFor: (batch, width) =>
303
303
  testArgs({
304
304
  files: batch,
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
+ });
@@ -130,22 +130,5 @@ export async function previewCodemods(
130
130
  return { codemods: { ...own, source: 'driver' }, superseded: await supersededFindings(root) };
131
131
  }
132
132
 
133
- /** Below every release: an app already at its target reruns every codemod, which are idempotent. */
133
+ /** Below every release: a resumed hop reruns every codemod, which are idempotent. */
134
134
  export const EVERY_RELEASE = '0.0.0';
135
-
136
- /**
137
- * No version moves, and still no copy of an old template stays: every codemod up to the release
138
- * the app is on, through the installed CLI as a hop would (a dry run previews this CLI's list).
139
- * Each is idempotent, so one already applied is a run that changes nothing.
140
- */
141
- export async function atTargetCodemods(input: {
142
- readonly runner: Runner;
143
- readonly root: string;
144
- readonly to: string;
145
- readonly dryRun: boolean;
146
- }): Promise<{ readonly codemods: HopCodemods; readonly superseded: readonly Finding[] }> {
147
- const { runner, root, to } = input;
148
- if (input.dryRun) return previewCodemods(root, EVERY_RELEASE, to);
149
- const codemods = await applyHopCodemods({ runner, root, from: EVERY_RELEASE, to });
150
- return { codemods, superseded: await supersededFindings(root) };
151
- }
@@ -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