@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
@@ -0,0 +1,36 @@
1
+ // The failures of the machine memory ledger. Admission is a courtesy between processes, so the two
2
+ // environment failures are reported and the work goes ahead; only `x heavy run` refuses anything.
3
+
4
+ import { UltimateError } from '@ultimat3/core';
5
+ import { HEAVY_MEMORY_ENV } from './heavy-env';
6
+ import { quoteArg } from './shell-quote';
7
+
8
+ export class HeavyLedgerUnavailableError extends UltimateError {
9
+ constructor(reason: string) {
10
+ super({
11
+ code: 'X_HEAVY_LEDGER_UNAVAILABLE',
12
+ cause: `the machine memory ledger cannot be used: ${reason}; this run continues unadmitted`,
13
+ fix: 'x heavy status --json',
14
+ });
15
+ }
16
+ }
17
+
18
+ export class HeavyMemoryInvalidError extends UltimateError {
19
+ constructor(raw: string) {
20
+ super({
21
+ code: 'X_HEAVY_MEMORY_INVALID',
22
+ cause: `${HEAVY_MEMORY_ENV}=${JSON.stringify(raw)} is not a byte size`,
23
+ fix: 'export ULTIMATE_HEAVY_MEMORY=8g # or 0 to turn the ledger off',
24
+ });
25
+ }
26
+ }
27
+
28
+ export class HeavyCommandNotFoundError extends UltimateError {
29
+ constructor(command: string) {
30
+ super({
31
+ code: 'X_HEAVY_COMMAND_NOT_FOUND',
32
+ cause: `${JSON.stringify(command)} is not an executable on PATH`,
33
+ fix: `bun --print ${quoteArg(`Bun.which(${JSON.stringify(command)})`)} # null: install it or correct the name, then: x heavy run -- <command>`,
34
+ });
35
+ }
36
+ }
@@ -0,0 +1,73 @@
1
+ // flock(2) through `bun:ffi`: the one primitive the ledger stands on. The kernel drops the lock when
2
+ // the last descriptor closes, which includes the holder dying by any signal, so "the holder died"
3
+ // and "the lock is free" are one event and nothing has to detect a stale file.
4
+ //
5
+ // WINDOWS has no flock, and a Node descriptor there is not the HANDLE `LockFileEx` wants, so the
6
+ // ledger is OFF on Windows: `x heavy status` says so and the core cap still applies. An honest gap
7
+ // beats a pid file that reintroduces the stale-lock race this module exists to remove.
8
+
9
+ import { HeavyLedgerUnavailableError } from './heavy-errors';
10
+
11
+ const LOCK_EX = 2;
12
+ const LOCK_NB = 4;
13
+ const EINTR = 4;
14
+
15
+ const LIBC: Readonly<Record<string, { libs: readonly string[]; errno: string; busy: number }>> = {
16
+ // glibc first; the two musl names are Alpine's, the base of many app images.
17
+ linux: {
18
+ libs: ['libc.so.6', 'libc.musl-x86_64.so.1', 'libc.musl-aarch64.so.1'],
19
+ errno: '__errno_location',
20
+ busy: 11,
21
+ },
22
+ darwin: { libs: ['libSystem.B.dylib'], errno: '__error', busy: 35 },
23
+ };
24
+
25
+ /** True when this descriptor now holds the lock, false when another one does. */
26
+ export type TryLock = (fd: number) => boolean;
27
+
28
+ export type FlockBinding =
29
+ | { readonly ok: true; readonly tryLock: TryLock }
30
+ | { readonly ok: false; readonly reason: string };
31
+
32
+ const bound = new Map<string, Promise<FlockBinding>>();
33
+
34
+ async function bind(platform: string): Promise<FlockBinding> {
35
+ const spec = Object.hasOwn(LIBC, platform) ? LIBC[platform] : undefined;
36
+ if (spec === undefined) return { ok: false, reason: `flock(2) does not exist on ${platform}` };
37
+ // Imported here so a command that never reaches the ledger never loads FFI.
38
+ const { dlopen, FFIType, read } = await import('bun:ffi');
39
+ for (const lib of spec.libs) {
40
+ try {
41
+ const { symbols } = dlopen(lib, {
42
+ flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 },
43
+ [spec.errno]: { args: [], returns: FFIType.ptr },
44
+ });
45
+ const errnoAt = symbols[spec.errno] as unknown as () => Parameters<typeof read.i32>[0];
46
+ const flock = symbols.flock as unknown as (fd: number, operation: number) => number;
47
+ return {
48
+ ok: true,
49
+ tryLock: (fd) => {
50
+ if (flock(fd, LOCK_EX | LOCK_NB) === 0) return true;
51
+ const errno = read.i32(errnoAt(), 0);
52
+ if (errno === spec.busy || errno === EINTR) return false;
53
+ // Reading this as "busy" would wait forever on a filesystem that cannot lock at all.
54
+ throw new HeavyLedgerUnavailableError(
55
+ `flock(2) failed with errno ${String(errno)}, which is not contention`,
56
+ );
57
+ },
58
+ };
59
+ } catch {
60
+ // Not this libc: the next name, and "no libc" below when none loads.
61
+ }
62
+ }
63
+ return { ok: false, reason: `no libc with flock(2) loaded (${spec.libs.join(', ')})` };
64
+ }
65
+
66
+ /** The process's one binding, loaded on first use. */
67
+ export const flockBinding = (platform: string = process.platform): Promise<FlockBinding> => {
68
+ const known = bound.get(platform);
69
+ if (known !== undefined) return known;
70
+ const binding = bind(platform);
71
+ bound.set(platform, binding);
72
+ return binding;
73
+ };
@@ -0,0 +1,358 @@
1
+ // The machine's memory ledger: reservations weighted in MB, admitted first come, first served, every
2
+ // one a file its owner holds an flock on. A file nobody holds is dead by definition, so a holder or
3
+ // waiter killed by any signal stops counting at that instant and no take-over exists to race.
4
+ //
5
+ // queue/<time>-<pid>-<id> a waiter holds/<pid>-<id> an admitted reservation
6
+ // gate the admission critical section; only the queue's head takes it
7
+ //
8
+ // A holder hands its locked descriptor to the workload, so the kernel frees a reservation only when
9
+ // the holder AND the workload are gone: killing a wrapper never frees memory its child still uses.
10
+ // Holders never wait while holding and children inherit the hold, so the ledger cannot deadlock.
11
+
12
+ // why: flock needs real descriptors, and Bun ships no descriptor-level file API.
13
+ import {
14
+ closeSync,
15
+ ftruncateSync,
16
+ mkdirSync,
17
+ openSync,
18
+ readdirSync,
19
+ readFileSync,
20
+ renameSync,
21
+ statSync,
22
+ unlinkSync,
23
+ writeSync,
24
+ } from 'node:fs';
25
+ // why: Bun ships no path-join primitive.
26
+ import { join } from 'node:path';
27
+ import { HeavyLedgerUnavailableError } from './heavy-errors';
28
+ import type { TryLock } from './heavy-flock';
29
+
30
+ export const LEDGER_POLL_MS = 100;
31
+ /** A temp file this old lost its creator: creating one takes microseconds. */
32
+ const STALE_TEMP_MS = 60_000;
33
+
34
+ export interface LedgerEntry {
35
+ readonly pid: number;
36
+ readonly mb: number;
37
+ readonly label: string;
38
+ readonly cwd: string;
39
+ readonly at: number;
40
+ }
41
+
42
+ export interface LedgerView {
43
+ readonly holds: readonly LedgerEntry[];
44
+ /** Oldest first: index 0 is the next admission. */
45
+ readonly queue: readonly LedgerEntry[];
46
+ }
47
+
48
+ export interface Held {
49
+ readonly path: string;
50
+ /** The locked descriptor. Handed to a child, it keeps the lock for as long as the child lives. */
51
+ readonly fd: number;
52
+ release(): void;
53
+ }
54
+
55
+ export interface Reservation extends Held {
56
+ readonly units: number;
57
+ readonly mb: number;
58
+ readonly waitedMs: number;
59
+ }
60
+
61
+ export interface ReserveInput {
62
+ readonly dir: string;
63
+ readonly capacityMb: number;
64
+ /** MB one unit costs: a measured peak (`heavy-weights.ts`). */
65
+ readonly unitMb: number;
66
+ readonly units: number;
67
+ /** MB the run costs however wide it is: the parent and whatever its workers share. */
68
+ readonly baseMb?: number;
69
+ /** Fewest units worth starting with. A run of workers narrows to what fits, down to this. */
70
+ readonly minUnits?: number;
71
+ readonly label: string;
72
+ readonly cwd: string;
73
+ readonly tryLock: TryLock;
74
+ readonly pollMs?: number;
75
+ readonly onWait?: (wait: LedgerWait) => void;
76
+ }
77
+
78
+ export interface LedgerWait {
79
+ readonly needMb: number;
80
+ readonly usedMb: number;
81
+ readonly capacityMb: number;
82
+ readonly position: number;
83
+ readonly queued: number;
84
+ readonly holds: readonly LedgerEntry[];
85
+ }
86
+
87
+ const codeOf = (error: unknown): unknown =>
88
+ typeof error === 'object' && error !== null ? Reflect.get(error, 'code') : undefined;
89
+
90
+ function unlinkQuiet(path: string): void {
91
+ try {
92
+ unlinkSync(path);
93
+ } catch (error) {
94
+ if (codeOf(error) !== 'ENOENT') throw error;
95
+ }
96
+ }
97
+
98
+ function once(run: () => void): () => void {
99
+ let spent = false;
100
+ return () => {
101
+ if (spent) return;
102
+ spent = true;
103
+ run();
104
+ };
105
+ }
106
+
107
+ export function prepareLedger(dir: string): void {
108
+ for (const sub of ['queue', 'holds', 'locks']) {
109
+ mkdirSync(join(dir, sub), { recursive: true, mode: 0o700 });
110
+ }
111
+ }
112
+
113
+ const parseEntry = (text: string): LedgerEntry | undefined => {
114
+ try {
115
+ const value: unknown = JSON.parse(text);
116
+ if (typeof value !== 'object' || value === null) return undefined;
117
+ const field = (name: string): unknown => Reflect.get(value, name);
118
+ const [pid, mb, at] = [field('pid'), field('mb'), field('at')];
119
+ if (typeof pid !== 'number' || typeof mb !== 'number' || typeof at !== 'number') {
120
+ return undefined;
121
+ }
122
+ return { pid, mb, at, label: String(field('label')), cwd: String(field('cwd')) };
123
+ } catch {
124
+ return undefined;
125
+ }
126
+ };
127
+
128
+ interface Live {
129
+ readonly name: string;
130
+ readonly entry: LedgerEntry;
131
+ }
132
+
133
+ /** The entries whose owner still holds their lock, in name order. A dead one is dropped. */
134
+ function liveEntries(dir: string, tryLock: TryLock, sweep: boolean): Live[] {
135
+ let names: string[];
136
+ try {
137
+ names = readdirSync(dir).sort();
138
+ } catch (error) {
139
+ if (codeOf(error) === 'ENOENT') return [];
140
+ throw error;
141
+ }
142
+ const live: Live[] = [];
143
+ for (const name of names) {
144
+ const path = join(dir, name);
145
+ let fd: number;
146
+ try {
147
+ fd = openSync(path, 'r');
148
+ } catch (error) {
149
+ if (codeOf(error) === 'ENOENT') continue;
150
+ throw error;
151
+ }
152
+ try {
153
+ if (tryLock(fd)) {
154
+ if (sweep) unlinkQuiet(path);
155
+ continue;
156
+ }
157
+ const entry = parseEntry(readFileSync(fd, 'utf8'));
158
+ if (entry !== undefined) live.push({ name, entry });
159
+ } finally {
160
+ closeSync(fd);
161
+ }
162
+ }
163
+ return live;
164
+ }
165
+
166
+ export const readLedger = (dir: string, tryLock: TryLock): LedgerView => ({
167
+ holds: liveEntries(join(dir, 'holds'), tryLock, false).map((one) => one.entry),
168
+ queue: liveEntries(join(dir, 'queue'), tryLock, false).map((one) => one.entry),
169
+ });
170
+
171
+ /** Whether the file at `path` is a reservation some live process still holds. */
172
+ export function isHeld(path: string, tryLock: TryLock): boolean {
173
+ let fd: number;
174
+ try {
175
+ fd = openSync(path, 'r');
176
+ } catch {
177
+ return false;
178
+ }
179
+ try {
180
+ return !tryLock(fd);
181
+ } finally {
182
+ closeSync(fd);
183
+ }
184
+ }
185
+
186
+ /** Created under a temp name, locked, THEN renamed in: no live entry is ever visible unlocked. */
187
+ function createEntry(root: string, sub: string, name: string, entry: LedgerEntry, lock: TryLock) {
188
+ const temp = join(root, `tmp-${name}`);
189
+ const fd = openSync(temp, 'wx');
190
+ if (!lock(fd)) {
191
+ closeSync(fd);
192
+ unlinkQuiet(temp);
193
+ return undefined;
194
+ }
195
+ writeSync(fd, JSON.stringify(entry));
196
+ const path = join(root, sub, name);
197
+ renameSync(temp, path);
198
+ // Unlink before close: the lock must outlast the file, or a sweeper could judge it dead.
199
+ return {
200
+ path,
201
+ fd,
202
+ release: once(() => {
203
+ unlinkQuiet(path);
204
+ closeSync(fd);
205
+ }),
206
+ };
207
+ }
208
+
209
+ function sweepTemps(root: string, now: number): void {
210
+ for (const name of readdirSync(root)) {
211
+ if (!name.startsWith('tmp-')) continue;
212
+ const path = join(root, name);
213
+ try {
214
+ if (now - statSync(path).mtimeMs > STALE_TEMP_MS) unlinkQuiet(path);
215
+ } catch (error) {
216
+ if (codeOf(error) !== 'ENOENT') throw error;
217
+ }
218
+ }
219
+ }
220
+
221
+ /** A short exclusive lock on `path`, or nothing when another descriptor has it. */
222
+ export function tryLockPath(path: string, label: string, tryLock: TryLock): Held | undefined {
223
+ const fd = openSync(path, 'a');
224
+ let held = false;
225
+ try {
226
+ held = tryLock(fd);
227
+ } finally {
228
+ if (!held) closeSync(fd);
229
+ }
230
+ if (!held) return undefined;
231
+ ftruncateSync(fd, 0);
232
+ writeSync(fd, `pid ${String(process.pid)}: ${label}\n`);
233
+ return { path, fd, release: once(() => closeSync(fd)) };
234
+ }
235
+
236
+ /** Wait for `path`. `onWait` is told once, with whoever the file names as its holder. */
237
+ export async function lockPath(
238
+ path: string,
239
+ label: string,
240
+ tryLock: TryLock,
241
+ onWait?: (holder: string) => void,
242
+ pollMs: number = LEDGER_POLL_MS,
243
+ ): Promise<Held> {
244
+ let told = false;
245
+ for (;;) {
246
+ const held = tryLockPath(path, label, tryLock);
247
+ if (held !== undefined) return held;
248
+ if (!told) {
249
+ told = true;
250
+ onWait?.(readFileSync(path, 'utf8').trim() || 'an unnamed holder');
251
+ }
252
+ await Bun.sleep(pollMs);
253
+ }
254
+ }
255
+
256
+ const unique = (): string => `${String(process.pid)}-${crypto.randomUUID()}`;
257
+
258
+ /** How many units fit now, or 0 when even `min` does not. Too big for the ledger runs alone. */
259
+ export function unitsThatFit(input: {
260
+ readonly capacityMb: number;
261
+ readonly usedMb: number;
262
+ readonly unitMb: number;
263
+ readonly units: number;
264
+ readonly minUnits: number;
265
+ readonly baseMb?: number;
266
+ }): number {
267
+ const { usedMb, unitMb, units } = input;
268
+ const capacityMb = input.capacityMb - (input.baseMb ?? 0);
269
+ const most = Math.max(1, Math.floor(capacityMb / unitMb));
270
+ const want = Math.min(units, most);
271
+ const min = Math.min(input.minUnits, want);
272
+ if (usedMb === 0) return want;
273
+ const fit = Math.min(want, Math.floor((capacityMb - usedMb) / unitMb));
274
+ return fit >= min ? fit : 0;
275
+ }
276
+
277
+ /**
278
+ * Join the queue and return once admitted. First come, first served: only the head may admit, so a
279
+ * big request is never starved by small ones slipping past it. The gate is held for one check at a
280
+ * time and never across a wait, so a head that dies leaves nothing behind.
281
+ */
282
+ export async function reserve(input: ReserveInput): Promise<Reservation> {
283
+ const { dir, tryLock, capacityMb, unitMb, units } = input;
284
+ const baseMb = input.baseMb ?? 0;
285
+ // A NaN passes `??` and would turn the wait into a spin on the ledger directory.
286
+ const pollMs = Number.isFinite(input.pollMs) ? (input.pollMs as number) : LEDGER_POLL_MS;
287
+ prepareLedger(dir);
288
+ const started = performance.now();
289
+ const base = { pid: process.pid, label: input.label, cwd: input.cwd };
290
+ const name = `${String(Date.now()).padStart(15, '0')}-${unique()}`;
291
+ const ticket = createEntry(
292
+ dir,
293
+ 'queue',
294
+ name,
295
+ { ...base, mb: baseMb + units * unitMb, at: Date.now() },
296
+ tryLock,
297
+ );
298
+ if (ticket === undefined) throw new HeavyLedgerUnavailableError('a new queue file was locked');
299
+ const minUnits = input.minUnits ?? 1;
300
+ let said = '';
301
+ try {
302
+ for (;;) {
303
+ const queue = liveEntries(join(dir, 'queue'), tryLock, true);
304
+ const position = queue.findIndex((one) => one.name === name);
305
+ if (position === -1) throw new HeavyLedgerUnavailableError(`${dir} was removed mid-wait`);
306
+ let holds = liveEntries(join(dir, 'holds'), tryLock, position === 0);
307
+ if (position === 0) {
308
+ const gate = tryLockPath(join(dir, 'gate'), input.label, tryLock);
309
+ if (gate !== undefined) {
310
+ try {
311
+ sweepTemps(dir, Date.now());
312
+ // Re-read under the gate: an admission may have landed since the read above.
313
+ holds = liveEntries(join(dir, 'holds'), tryLock, true);
314
+ const usedMb = holds.reduce((sum, one) => sum + one.entry.mb, 0);
315
+ const granted = unitsThatFit({ capacityMb, usedMb, unitMb, units, minUnits, baseMb });
316
+ if (granted > 0) {
317
+ const mb = baseMb + granted * unitMb;
318
+ const hold = createEntry(
319
+ dir,
320
+ 'holds',
321
+ unique(),
322
+ { ...base, mb, at: Date.now() },
323
+ tryLock,
324
+ );
325
+ if (hold === undefined) {
326
+ throw new HeavyLedgerUnavailableError('a new reservation file was locked');
327
+ }
328
+ return {
329
+ ...hold,
330
+ units: granted,
331
+ mb,
332
+ waitedMs: Math.round(performance.now() - started),
333
+ };
334
+ }
335
+ } finally {
336
+ gate.release();
337
+ }
338
+ }
339
+ }
340
+ const usedMb = holds.reduce((sum, one) => sum + one.entry.mb, 0);
341
+ const key = `${String(position)}|${holds.map((one) => one.name).join(',')}`;
342
+ if (key !== said) {
343
+ said = key;
344
+ input.onWait?.({
345
+ needMb: Math.min(baseMb + units * unitMb, capacityMb),
346
+ usedMb,
347
+ capacityMb,
348
+ position: position + 1,
349
+ queued: queue.length,
350
+ holds: holds.map((one) => one.entry),
351
+ });
352
+ }
353
+ await Bun.sleep(pollMs);
354
+ }
355
+ } finally {
356
+ ticket.release();
357
+ }
358
+ }
@@ -0,0 +1,67 @@
1
+ // What the ledger may admit: half of the memory this process can really use. `totalmem()` is the
2
+ // host's figure, so inside a capped cgroup it plans for memory the kernel will never grant; the
3
+ // binding limit is the smallest `memory.max` along this process's own cgroup-v2 ancestry.
4
+
5
+ // why: Bun ships no synchronous file read, and `/proc` and `/sys` must be read at their real size.
6
+ import { readFileSync } from 'node:fs';
7
+ // why: Bun exposes no total-memory or free-memory primitive.
8
+ import { freemem, totalmem } from 'node:os';
9
+ import type { HeavyEnv } from './heavy-env';
10
+ import { HEAVY_MEMORY_ENV } from './heavy-env';
11
+ import { HeavyMemoryInvalidError } from './heavy-errors';
12
+ import { parseBytes } from './test-workers';
13
+
14
+ /** RAM's other half stays for the agent sessions, editors and servers no ledger can see. */
15
+ export const LEDGER_SHARE = 0.5;
16
+
17
+ const CGROUP_ROOT = '/sys/fs/cgroup';
18
+ const MIB = 2 ** 20;
19
+
20
+ export type ReadFile = (path: string) => string | undefined;
21
+
22
+ const readOrNothing: ReadFile = (path) => {
23
+ try {
24
+ return readFileSync(path, 'utf8');
25
+ } catch {
26
+ return undefined;
27
+ }
28
+ };
29
+
30
+ /** The smallest numeric `memory.max` from the mount root down to this process's cgroup. */
31
+ export function cgroupLimitBytes(read: ReadFile = readOrNothing): number | undefined {
32
+ const line = read('/proc/self/cgroup')
33
+ ?.split('\n')
34
+ .find((candidate) => candidate.startsWith('0::'));
35
+ if (line === undefined) return undefined;
36
+ const limits: number[] = [];
37
+ let dir = CGROUP_ROOT;
38
+ // The root counts: inside a container the namespace shows `/` and the limit sits on the mount.
39
+ for (const part of ['', ...line.slice(3).trim().split('/').filter(Boolean)]) {
40
+ if (part !== '') dir = `${dir}/${part}`;
41
+ const raw = read(`${dir}/memory.max`)?.trim();
42
+ if (raw !== undefined && /^\d+$/.test(raw)) limits.push(Number(raw));
43
+ }
44
+ return limits.length === 0 ? undefined : Math.min(...limits);
45
+ }
46
+
47
+ /** The machine as this process may use it, bytes. */
48
+ export const usableMemoryBytes = (
49
+ host: number = totalmem(),
50
+ limit: number | undefined = cgroupLimitBytes(),
51
+ ): number => (limit === undefined ? host : Math.min(host, limit));
52
+
53
+ /** MB the ledger admits; 0 means it is off. Throws `X_HEAVY_MEMORY_INVALID` on a bad override. */
54
+ export function ledgerCapacityMb(env: HeavyEnv, usable: number = usableMemoryBytes()): number {
55
+ const raw = env[HEAVY_MEMORY_ENV]?.trim();
56
+ if (raw === undefined || raw === '') return Math.floor((usable * LEDGER_SHARE) / MIB);
57
+ if (raw === '0') return 0;
58
+ const bytes = parseBytes(raw);
59
+ if (bytes === undefined) throw new HeavyMemoryInvalidError(raw);
60
+ return Math.max(1, Math.floor(bytes / MIB));
61
+ }
62
+
63
+ /** Memory a new process could get now: `MemAvailable` where Linux reports it. */
64
+ export function availableMemoryBytes(read: ReadFile = readOrNothing): number {
65
+ const match = /^MemAvailable:\s+(\d+) kB/m.exec(read('/proc/meminfo') ?? '');
66
+ return match === null ? freemem() : Number(match[1]) * 1024;
67
+ }
@@ -0,0 +1,47 @@
1
+ // What each heavy command reserves: its MEASURED peak, whole process tree, rounded up to 64 MB. A
2
+ // weight is a claim the ledger's bound rests on, so each carries the command that re-reads it, run
3
+ // on a clean `git archive` snapshot through `bun run scripts/heavy-peak.ts -- <command>`.
4
+ // Measured 2026-11-18, 8 cores / 31 GB, Bun 1.4.4, TypeScript 7.0.2, GOMAXPROCS=RAYON_NUM_THREADS=4.
5
+
6
+ import { WORKER_BYTES } from './test-workers';
7
+
8
+ const MIB = 2 ** 20;
9
+
10
+ /** `tsc -b --pretty false` from cold over this repository's 32 projects: 5,973 MB, 120 s. */
11
+ export const TYPECHECK_BUILD_PEAK_MB = 6016;
12
+
13
+ /** `tsc -p . --pretty false --noEmit` in `examples/dummy`, one program: 763 MB, 8 s. */
14
+ export const TYPECHECK_APP_PEAK_MB = 768;
15
+
16
+ /** `-b` walks every project of a monorepo; `-p .` is the one program of a scaffolded app. */
17
+ export const typecheckPeakMb = (argv: readonly string[]): number =>
18
+ argv.includes('-b') ? TYPECHECK_BUILD_PEAK_MB : TYPECHECK_APP_PEAK_MB;
19
+
20
+ /** `biome check .` at this repository's root: 2,072 MB (1,855 in `examples/dummy`). */
21
+ export const LINT_PEAK_MB = 2112;
22
+
23
+ /**
24
+ * One `bun test` worker: the planner's figure (`WORKER_BYTES`, with its table in `test-workers.ts`).
25
+ * Re-read here: `bun test ./packages/core ./packages/schema ./packages/entity ./packages/action`,
26
+ * one process tree, peaked at 1,229 MB.
27
+ */
28
+ export const TEST_WORKER_PEAK_MB = Math.ceil(WORKER_BYTES / MIB);
29
+
30
+ /**
31
+ * What a test run costs beside its workers: the `x` parent and the first database boot. One worker
32
+ * in `examples/dummy` peaked at 1,915 MB (`x test unit --workers 1`) and 1,964 MB with coverage
33
+ * (`ULTIMATE_HEAVY_CORES=1 x verify --only unit`), which is this plus one worker.
34
+ */
35
+ export const TEST_RUN_BASE_MB = 704;
36
+
37
+ /**
38
+ * `x test e2e` in `examples/dummy`, app server and browser: 2,871 MB. That run ended red on the
39
+ * snapshot, so the figure is a floor and this keeps a margin above it.
40
+ */
41
+ export const E2E_LANE_PEAK_MB = 3072;
42
+
43
+ /** At most this many selected files run free: a worker's own files never queue behind a gate. */
44
+ export const FREE_RUN_FILES = 3;
45
+
46
+ /** `x heavy run` with no `--mb`: an unknown command is assumed to cost a whole-repo typecheck. */
47
+ export const DEFAULT_RUN_MB = TYPECHECK_BUILD_PEAK_MB;