@nodii/dev 0.6.209 → 0.6.211

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.
@@ -0,0 +1,526 @@
1
+ // DEV-PROCESS-2 (O2, "the machine cannot be overcommitted"): the machine's floor.
2
+ //
3
+ // One rule, read first by every heavy or light check, lane launch, lane resume and keepalive resume: available memory
4
+ // after the expected peaks of running jobs, swap used and disk free each clear the floor, or the work is refused at
5
+ // once with MACHINE_UNDER_FLOOR, naming the reading, the figure and the five largest holders of memory. Nothing waits
6
+ // under the floor and nothing is let through: no lone-job, landing or priority exception.
7
+ //
8
+ // The floor, the class peaks, the slot ceilings and the stagger live in root-owned /etc/nodii/floor.env, which only
9
+ // the machine owner's password changes; when it is missing or anyone else can write it, the shipped defaults hold. No
10
+ // environment variable moves that file or the slot directory. `--tighten READING=GB` makes one call stricter and is a
11
+ // USAGE error if it would loosen. Every decision goes to the admission log, which `heavy status` lists.
12
+ //
13
+ // heavy-slot.sh runs this file as a script (`limits`, `check`, `record`, `status`) by its own path, on the install's
14
+ // node, so the shell queue and the Node CLI share one rule.
15
+ import { execFile as execFileCb } from "node:child_process";
16
+ import { existsSync, realpathSync } from "node:fs";
17
+ import { access, appendFile, constants, mkdir, readFile, readdir, stat } from "node:fs/promises";
18
+ import { homedir, platform } from "node:os";
19
+ import { basename, dirname, join } from "node:path";
20
+ import { fileURLToPath } from "node:url";
21
+ import { promisify } from "node:util";
22
+ import { CliError } from "./core.js";
23
+
24
+ const execFileAsync = promisify(execFileCb);
25
+ const GB = 1024 ** 3;
26
+
27
+ /** The one floor file. Root owns it and its directory: `sudo install -o root -g wheel -m 644 floor.env /etc/nodii/floor.env`. */
28
+ export const FLOOR_FILE = "/etc/nodii/floor.env";
29
+ /** The one slot directory every copy of the queue counts against. */
30
+ export const SLOT_DIR = "/tmp/nodii-heavy-slots";
31
+
32
+ /**
33
+ * The shipped defaults (hub-377, 651; DEV-PROCESS-2 must-items 2-4): 10 GB available (light jobs 5), at most
34
+ * 24 GB swap used, 15 GB disk free; a running job holds back its class's peak (7 GB heavy, 1 GB light) less what it
35
+ * uses; 3 heavy slots, one of them only for landings; 8 light slots; a 10 s
36
+ * stagger between admissions while another job runs. Only end-to-end, real-stack and browser work is heavy (heavy-slot.sh). Fixed numbers: no script tunes them.
37
+ */
38
+ // One line, so a test's copy of this file can replace it whole.
39
+ export const DEFAULTS = Object.freeze({ minAvailGb: 10, lightMinAvailGb: 5, maxSwapGb: 24, minDiskGb: 15, heavyPeakGb: 7, lightPeakGb: 1, heavySlots: 3, landingReserve: 1, lightSlots: 8, staggerSec: 10 });
40
+ const KEYS = {
41
+ MIN_AVAIL_GB: "minAvailGb", LIGHT_MIN_AVAIL_GB: "lightMinAvailGb", MAX_SWAP_GB: "maxSwapGb", MIN_DISK_GB: "minDiskGb",
42
+ HEAVY_PEAK_GB: "heavyPeakGb", LIGHT_PEAK_GB: "lightPeakGb",
43
+ HEAVY_SLOTS: "heavySlots", LANDING_RESERVE: "landingReserve", LIGHT_SLOTS: "lightSlots", STAGGER_SEC: "staggerSec",
44
+ };
45
+ /** The heavy class's floor at the shipped defaults. */
46
+ export const MACHINE_FLOOR = Object.freeze({ minAvailGb: DEFAULTS.minAvailGb, maxSwapGb: DEFAULTS.maxSwapGb, minDiskGb: DEFAULTS.minDiskGb });
47
+
48
+ export const UNDER_FLOOR = "MACHINE_UNDER_FLOOR";
49
+ export const CLASSES = ["heavy", "light", "launch", "resume", "keepalive"];
50
+ const KIND_WORDS = { heavy: "heavy check", light: "light check", launch: "lane launch", resume: "lane resume", keepalive: "keepalive resume" };
51
+
52
+ /** The CLI's own error, so `fail` prints the code and exits with the code's exit status. */
53
+ export class FloorError extends CliError {
54
+ constructor(code, message, exitCode = 1) {
55
+ super(code, message, exitCode);
56
+ }
57
+ }
58
+
59
+ // ---- The floor file ------------------------------------------------------------------
60
+
61
+ /** KEY=VALUE lines (comments allowed). Unknown keys and garbled values are ignored. */
62
+ export function parseFloorFile(text) {
63
+ const out = {};
64
+ for (const raw of String(text ?? "").split("\n")) {
65
+ const m = /^\s*([A-Z_]+)\s*=\s*"?([0-9]+(?:\.[0-9]+)?)"?\s*(?:#.*)?$/.exec(raw);
66
+ if (m && KEYS[m[1]]) out[KEYS[m[1]]] = Number(m[2]);
67
+ }
68
+ return out;
69
+ }
70
+
71
+ /**
72
+ * The floor settings, from FILE when root owns it and its directory and neither is group- or world-writable (and
73
+ * this user cannot write it); else the shipped defaults, with why.
74
+ */
75
+ export async function floorSettings({ file = FLOOR_FILE, statImpl = stat, read = readFile, accessImpl = access } = {}) {
76
+ const writable = async (path) => { try { await accessImpl(path, constants.W_OK); return true; } catch { return false; } };
77
+ const settled = (values, trusted, why) => {
78
+ const v = { ...DEFAULTS, ...values };
79
+ return {
80
+ floor: { minAvailGb: v.minAvailGb, lightMinAvailGb: v.lightMinAvailGb, maxSwapGb: v.maxSwapGb, minDiskGb: v.minDiskGb },
81
+ peaks: { heavyGb: v.heavyPeakGb, lightGb: v.lightPeakGb },
82
+ ceilings: { heavySlots: Math.max(1, Math.trunc(v.heavySlots)), landingReserve: Math.max(0, Math.trunc(v.landingReserve)), lightSlots: Math.max(0, Math.trunc(v.lightSlots)) },
83
+ staggerSec: Math.max(0, v.staggerSec),
84
+ file, trusted, why,
85
+ };
86
+ };
87
+ let info;
88
+ try { info = await statImpl(file); }
89
+ catch { return settled({}, false, `${file} is not installed: the shipped defaults hold`); }
90
+ let problem = null;
91
+ if (info.uid !== 0) problem = `it is owned by uid ${info.uid}, not root`;
92
+ else if (info.mode & 0o022) problem = `it is group- or world-writable (mode ${(info.mode & 0o777).toString(8)})`;
93
+ else {
94
+ try {
95
+ const d = await statImpl(dirname(file));
96
+ if (d.uid !== 0) problem = `its directory is owned by uid ${d.uid}, not root`;
97
+ else if (d.mode & 0o022) problem = `its directory is group- or world-writable (mode ${(d.mode & 0o777).toString(8)})`;
98
+ } catch { problem = "its directory cannot be read"; }
99
+ }
100
+ if (!problem && (await writable(file))) problem = "this user can write it";
101
+ if (problem) return settled({}, false, `${file} is ignored because ${problem}: the shipped defaults hold`);
102
+ try { return settled(parseFloorFile(await read(file, "utf8")), true, `${file} (root-owned; this user cannot write it)`); }
103
+ catch { return settled({}, false, `${file} cannot be read: the shipped defaults hold`); }
104
+ }
105
+
106
+ /** The floor a call of KIND is held to: a light check has its own memory floor; everything else the heavy one. */
107
+ export function floorFor(kind, settings) {
108
+ const f = settings.floor;
109
+ return { minAvailGb: kind === "light" ? f.lightMinAvailGb : f.minAvailGb, maxSwapGb: f.maxSwapGb, minDiskGb: f.minDiskGb };
110
+ }
111
+
112
+ // ---- --tighten ---------------------------------------------------------------------
113
+
114
+ const READINGS = {
115
+ memory: { field: "minAvailGb", stricter: (a, b) => a >= b, words: "available memory", unit: "GB at least" },
116
+ swap: { field: "maxSwapGb", stricter: (a, b) => a <= b, words: "swap used", unit: "GB at most" },
117
+ disk: { field: "minDiskGb", stricter: (a, b) => a >= b, words: "disk free", unit: "GB at least" },
118
+ };
119
+ export const TIGHTEN_USAGE = "--tighten takes memory=GB, swap=GB or disk=GB (repeat it for more than one reading)";
120
+
121
+ /**
122
+ * `--tighten memory=40 --tighten swap=0` (or `memory=40,swap=0`) applied to FLOOR.
123
+ * A figure looser than the floor is a USAGE error: --tighten only ever makes one call stricter.
124
+ */
125
+ export function tighten(floor, specs) {
126
+ const list = (Array.isArray(specs) ? specs : specs === undefined ? [] : [specs]).flatMap((s) => {
127
+ if (typeof s !== "string" || !s.trim()) throw new FloorError("USAGE", TIGHTEN_USAGE, 2);
128
+ return s.split(",");
129
+ });
130
+ const out = { ...floor };
131
+ for (const spec of list) {
132
+ const m = /^\s*([a-z]+)\s*=\s*([0-9]+(?:\.[0-9]+)?)\s*$/.exec(spec);
133
+ const reading = m && READINGS[m[1]];
134
+ if (!reading) throw new FloorError("USAGE", `${TIGHTEN_USAGE}; got ${JSON.stringify(spec)}`, 2);
135
+ const figure = Number(m[2]);
136
+ if (!reading.stricter(figure, floor[reading.field]))
137
+ throw new FloorError("USAGE", `--tighten ${m[1]}=${figure} would loosen the floor (${reading.words} ${floor[reading.field]} ${reading.unit}): --tighten only makes a call stricter.`, 2);
138
+ if (reading.stricter(figure, out[reading.field])) out[reading.field] = figure;
139
+ }
140
+ return out;
141
+ }
142
+
143
+ // ---- Readings ----------------------------------------------------------------------
144
+
145
+ const round1 = (n) => (Number.isFinite(n) ? Math.round(n * 10) / 10 : null);
146
+ const run = async (execute, file, args) => (await execute(file, args, { timeout: 15_000, maxBuffer: 32 * 1024 * 1024 })).stdout;
147
+ // The system's own tools by absolute path: a `vm_stat` first on PATH must not change a reading.
148
+ const BIN = { sysctl: "/usr/sbin/sysctl", vm_stat: "/usr/bin/vm_stat", df: "/bin/df", ps: "/bin/ps" };
149
+ // Linux too reads ps and df by absolute path (procps and coreutils put both under /bin, or /usr/bin on a merged /usr).
150
+ const psPath = (os) => (os === "linux" ? (existsSync("/bin/ps") ? "/bin/ps" : "/usr/bin/ps") : BIN.ps);
151
+ const dfPath = (os) => (os === "linux" ? (existsSync("/bin/df") ? "/bin/df" : "/usr/bin/df") : BIN.df);
152
+
153
+ /** `ps -o etime=` ([[dd-]hh:]mm:ss) in seconds, or null. */
154
+ export function elapsedSeconds(etime) {
155
+ const m = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(String(etime ?? "").trim());
156
+ return m ? ((Number(m[1] ?? 0) * 24 + Number(m[2] ?? 0)) * 60 + Number(m[3])) * 60 + Number(m[4]) : null;
157
+ }
158
+
159
+ /** Activity Monitor's available memory: RAM - (app memory + wired + compressed), in GB. */
160
+ export function availableFromVmStat(vmStat, ramBytes) {
161
+ const n = (re) => Number(re.exec(vmStat)?.[1] ?? NaN);
162
+ const page = n(/page size of (\d+) bytes/);
163
+ const used = (n(/Anonymous pages:\s+(\d+)/) - n(/Pages purgeable:\s+(\d+)/) + n(/Pages wired down:\s+(\d+)/) + n(/Pages occupied by compressor:\s+(\d+)/)) * page;
164
+ const ram = Number(String(ramBytes ?? "").trim() || NaN);
165
+ if (!(ram > 0)) return null;
166
+ const available = (ram - used) / GB;
167
+ return Number.isFinite(available) ? available : null;
168
+ }
169
+
170
+ /** `used = 4888.31M` from `sysctl vm.swapusage`, in GB. */
171
+ export function swapFromSysctl(text) {
172
+ const m = /used\s*=\s*([0-9.]+)([KMGT])/.exec(String(text ?? ""));
173
+ return m ? Number(m[1]) * { K: 1 / 1024 ** 2, M: 1 / 1024, G: 1, T: 1024 }[m[2]] : null;
174
+ }
175
+
176
+ /** Free space in GB from `df -Pk PATH...`: the fourth column, the least over every filesystem listed. */
177
+ export function diskFromDf(text) {
178
+ const kbs = String(text ?? "").trim().split("\n").slice(1).map((line) => Number(line.trim().split(/\s+/)[3])).filter(Number.isFinite);
179
+ return kbs.length ? Math.min(...kbs) / 1024 ** 2 : null;
180
+ }
181
+
182
+ /** The three readings, in GB. One that cannot be taken is null, and a null reading fails the floor. */
183
+ export async function readMachine({ os = platform(), execute = execFileAsync, read = readFile, home = homedir() } = {}) {
184
+ let availGb = null;
185
+ let swapUsedGb = null;
186
+ let diskFreeGb = null;
187
+ if (os === "linux") {
188
+ try {
189
+ const meminfo = await read("/proc/meminfo", "utf8");
190
+ const kb = (name) => Number(new RegExp(`^${name}:\\s+(\\d+) kB`, "m").exec(meminfo)?.[1] ?? NaN);
191
+ availGb = kb("MemAvailable") / 1024 ** 2;
192
+ swapUsedGb = (kb("SwapTotal") - kb("SwapFree")) / 1024 ** 2;
193
+ } catch {}
194
+ } else {
195
+ try {
196
+ let ram = (await run(execute, BIN.sysctl, ["-n", "hw.memsize"]).catch(() => "")).trim();
197
+ // A sandboxed session can't read hw.memsize; the coordinator records it (heavy-slot v10).
198
+ if (!/^\d+$/.test(ram)) ram = (await read(join(home, ".config", "nodii-resources", "hw.memsize"), "utf8").catch(() => "")).trim();
199
+ availGb = availableFromVmStat(await run(execute, BIN.vm_stat, []), ram);
200
+ } catch {}
201
+ try { swapUsedGb = swapFromSysctl(await run(execute, BIN.sysctl, ["vm.swapusage"])); } catch {}
202
+ }
203
+ // The root filesystem and the one holding home (worktrees, caches, the slot logs): the tighter of the two counts.
204
+ try { diskFreeGb = diskFromDf(await run(execute, dfPath(os), ["-Pk", "/", ...(home && home !== "/" ? [home] : [])])); } catch {}
205
+ return { availGb: round1(availGb), swapUsedGb: round1(swapUsedGb), diskFreeGb: round1(diskFreeGb) };
206
+ }
207
+
208
+ /** What holds memory: the five largest programs by resident memory, with their process counts. */
209
+ export async function memoryHolders({ execute = execFileAsync, os = platform(), top = 5 } = {}) {
210
+ let text = "";
211
+ try { text = await run(execute, psPath(os), ["-axo", "rss=,comm="]); } catch { return []; }
212
+ const groups = new Map();
213
+ for (const line of text.split("\n")) {
214
+ const m = /^\s*(\d+)\s+(.+)$/.exec(line);
215
+ if (!m) continue;
216
+ const name = basename(m[2].trim()) || m[2].trim();
217
+ const g = groups.get(name) ?? { name, count: 0, gb: 0 };
218
+ g.count += 1;
219
+ g.gb += Number(m[1]) / 1024 ** 2;
220
+ groups.set(name, g);
221
+ }
222
+ return [...groups.values()].sort((a, b) => b.gb - a.gb).slice(0, top).map((g) => ({ ...g, gb: round1(g.gb) }));
223
+ }
224
+
225
+ export const holdersLine = (holders) =>
226
+ holders.length ? holders.map((h) => `${h.name}${h.count > 1 ? ` ×${h.count}` : ""} ${h.gb} GB`).join(", ") : "(the process list could not be read)";
227
+ export const readingsLine = (r) => `available ${r.availGb ?? "?"} GB, swap used ${r.swapUsedGb ?? "?"} GB, disk free ${r.diskFreeGb ?? "?"} GB`;
228
+ export const floorLine = (f) => `available ≥ ${f.minAvailGb} GB, swap used ≤ ${f.maxSwapGb} GB, disk free ≥ ${f.minDiskGb} GB`;
229
+
230
+ // ---- Running jobs' reservations ------------------------------------------------------
231
+
232
+ /**
233
+ * What running jobs hold back: each held slot (SLOTS_DIR/<n> heavy, SLOTS_DIR/light/<n> light) reserves its class's
234
+ * peak less what its job's process tree uses now. SELF (the slot being decided) is left out.
235
+ * A slot whose holder is dead holds nothing (hub-ee on #501): its recorded pid is not in the process list, or that pid
236
+ * now belongs to a process started after the slot was granted (a reused pid). A holder killed with SIGKILL never runs
237
+ * its EXIT trap, so its slot stays on disk; it must not keep 7 GB from every later job. When the process list cannot
238
+ * be read, no holder is judged dead and every slot holds its whole peak.
239
+ */
240
+ export async function reservations({ slotsDir = SLOT_DIR, self = "", settings, execute = execFileAsync, os = platform(), read = readFile, list = readdir, now = Date.now() } = {}) {
241
+ const peaks = (settings ?? { peaks: { heavyGb: DEFAULTS.heavyPeakGb, lightGb: DEFAULTS.lightPeakGb } }).peaks;
242
+ const slots = [];
243
+ for (const [dir, size] of [[slotsDir, "heavy"], [join(slotsDir, "light"), "light"]]) {
244
+ let names = [];
245
+ try { names = await list(dir); } catch { continue; }
246
+ for (const name of names.filter((n) => /^\d+$/.test(n)).sort()) {
247
+ const path = join(dir, name);
248
+ if (self && path.replace(/\/+$/, "") === String(self).replace(/\/+$/, "")) continue;
249
+ const get = async (f) => (await read(join(path, f), "utf8").catch(() => "")).trim();
250
+ const recorded = await get("size");
251
+ const cls = recorded === "light" || recorded === "heavy" ? recorded : size;
252
+ slots.push({ slot: size === "light" ? `light/${name}` : name, size: cls, job: (await get("job")).replace(/\D/g, ""), what: (await get("what")).replace(/^.* :: /, "").slice(0, 80), holder: (await get("pid")).replace(/\D/g, ""), since: Number((await get("since")).replace(/\D/g, "")) || 0 });
253
+ }
254
+ }
255
+ if (!slots.length) return { gb: 0, jobs: [] };
256
+ // Resident memory by process, and each process's parent, to sum a job's whole tree.
257
+ const rss = new Map();
258
+ const children = new Map();
259
+ const startedAt = new Map();
260
+ let listed = false;
261
+ try {
262
+ for (const line of (await run(execute, psPath(os), ["-axo", "pid=,ppid=,rss=,etime="])).split("\n")) {
263
+ const [pid, ppid, kb, etime] = line.trim().split(/\s+/);
264
+ if (!pid) continue;
265
+ rss.set(pid, Number(kb) / 1024 ** 2);
266
+ const age = elapsedSeconds(etime);
267
+ if (age !== null) startedAt.set(pid, Math.floor(now / 1000) - age);
268
+ if (!children.has(ppid)) children.set(ppid, []);
269
+ children.get(ppid).push(pid);
270
+ listed = true;
271
+ }
272
+ } catch {}
273
+ // A dead holder holds nothing. The 5 s allowance covers ps rounding and the gap between fork and the `since` stamp.
274
+ const dead = (s) => listed && Boolean(s.holder) && (!rss.has(s.holder) || (s.since > 0 && (startedAt.get(s.holder) ?? 0) > s.since + 5));
275
+ const live = slots.filter((s) => !dead(s));
276
+ if (!live.length) return { gb: 0, jobs: [] };
277
+ const treeGb = (root) => {
278
+ let sum = 0;
279
+ const seen = new Set();
280
+ const stack = root ? [root] : [];
281
+ while (stack.length) {
282
+ const pid = stack.pop();
283
+ if (seen.has(pid)) continue;
284
+ seen.add(pid);
285
+ sum += rss.get(pid) ?? 0;
286
+ stack.push(...(children.get(pid) ?? []));
287
+ }
288
+ return sum;
289
+ };
290
+ const jobs = live.map(({ holder, since, ...s }) => {
291
+ const peakGb = s.size === "light" ? peaks.lightGb : peaks.heavyGb;
292
+ const usedGb = round1(treeGb(s.job));
293
+ return { ...s, peakGb, usedGb, heldGb: round1(Math.max(0, peakGb - usedGb)) };
294
+ });
295
+ return { gb: round1(jobs.reduce((sum, j) => sum + j.heldGb, 0)), jobs };
296
+ }
297
+
298
+ const reservationLine = (reserved) =>
299
+ reserved.jobs.filter((j) => j.heldGb > 0).map((j) => `slot ${j.slot} ${j.size} ${j.heldGb} GB (peak ${j.peakGb} less ${j.usedGb} used${j.what ? `: ${j.what}` : ""})`).join("; ");
300
+
301
+ // ---- The rule ------------------------------------------------------------------------
302
+
303
+ /**
304
+ * The readings that fail FLOOR, as sentences naming the reading and the figure. Available memory is counted after
305
+ * RESERVED, what running jobs hold back for their peaks.
306
+ */
307
+ export function failingReadings(readings, floor, reserved = { gb: 0, jobs: [] }) {
308
+ const out = [];
309
+ const { availGb, swapUsedGb, diskFreeGb } = readings ?? {};
310
+ const held = Number(reserved?.gb) || 0;
311
+ if (!Number.isFinite(availGb)) out.push("available memory could not be read");
312
+ else if (availGb - held < floor.minAvailGb)
313
+ out.push(held > 0
314
+ ? `available memory ${availGb} GB, ${round1(availGb - held)} GB after ${held} GB held back for running jobs' peaks (${reservationLine(reserved) || "reserved"}), is under the floor ${floor.minAvailGb} GB`
315
+ : `available memory ${availGb} GB is under the floor ${floor.minAvailGb} GB`);
316
+ if (!Number.isFinite(swapUsedGb)) out.push("swap used could not be read");
317
+ else if (swapUsedGb > floor.maxSwapGb) out.push(`swap used ${swapUsedGb} GB is over the ceiling ${floor.maxSwapGb} GB`);
318
+ if (!Number.isFinite(diskFreeGb)) out.push("disk free could not be read");
319
+ else if (diskFreeGb < floor.minDiskGb) out.push(`disk free ${diskFreeGb} GB is under the floor ${floor.minDiskGb} GB`);
320
+ return out;
321
+ }
322
+
323
+ /**
324
+ * Check work of KIND against its floor, tightened by TIGHTEN, with running jobs' reservations held back; log the
325
+ * decision when LOG says to ("all", "refusals" or "none"); return the verdict. Nothing in the environment changes it.
326
+ */
327
+ export async function checkFloor({
328
+ kind = "heavy",
329
+ what = "",
330
+ tighten: specs,
331
+ landing = false,
332
+ preflight = false,
333
+ // The queue admitted the job (heavy-slot.sh's `record`): the entry is an admission, whatever the readings.
334
+ admitted = false,
335
+ self = "",
336
+ slotsDir = SLOT_DIR,
337
+ log = "all",
338
+ home = homedir(),
339
+ os = platform(),
340
+ now = Date.now(),
341
+ env = process.env,
342
+ settings: givenSettings,
343
+ readings: given,
344
+ reserved: givenReserved,
345
+ holders: givenHolders,
346
+ execute = execFileAsync,
347
+ } = {}) {
348
+ if (!CLASSES.includes(kind)) throw new FloorError("USAGE", `the class must be one of ${CLASSES.join(", ")}`, 2);
349
+ const settings = givenSettings ?? (await floorSettings());
350
+ const floor = tighten(floorFor(kind, settings), specs);
351
+ const readings = given ?? (await readMachine({ os, execute, home }));
352
+ const reserved = givenReserved ?? (await reservations({ slotsDir, self, settings, execute, os }));
353
+ const failing = failingReadings(readings, floor, reserved);
354
+ const ok = admitted || failing.length === 0;
355
+ const holders = !failing.length ? [] : givenHolders ?? (await memoryHolders({ execute, os }));
356
+ const message = !failing.length
357
+ ? `${KIND_WORDS[kind]}: ${readingsLine(readings)}${reserved.gb ? ` (${reserved.gb} GB held back for running jobs)` : ""} clear the floor (${floorLine(floor)}).`
358
+ : [
359
+ `Refused ${KIND_WORDS[kind]}${what ? ` \`${what}\`` : ""}: ${failing.join("; ")}.`,
360
+ `Memory is held by: ${holdersLine(holders)}.`,
361
+ "Nothing waits and nothing was started. Try again once the readings clear the floor.",
362
+ ...(landing ? [LANDING_UNDER_FLOOR] : []),
363
+ ].join("\n");
364
+ const verdict = { ok, code: failing.length ? UNDER_FLOOR : null, kind, what, landing, preflight, tightened: specs !== undefined, readings, reserved, floor, failing, holders, message, settings };
365
+ if (log === "all" || (log === "refusals" && !ok)) await logDecision(verdict, { home, now, env }).catch(() => {});
366
+ return verdict;
367
+ }
368
+
369
+ /**
370
+ * The sanctioned path for an urgent landing under the floor (hub-ee on #501): nothing on this machine. A revert is
371
+ * opened with GitHub's Revert button on the merged pull request, checked by CI on the runner and merged there; a
372
+ * fix is pushed from a machine that clears its floor. There is no local pass under the floor (hub-490).
373
+ */
374
+ export const LANDING_UNDER_FLOOR =
375
+ "To land something urgent now, use a path that runs nothing here: for a revert, press Revert on the merged pull request on GitHub, let CI check it on the runner and merge it there; push anything else from a machine that clears its floor.";
376
+
377
+ /** checkFloor that throws MACHINE_UNDER_FLOOR (exit 75) on a refusal. */
378
+ export async function requireFloor(options) {
379
+ const verdict = await checkFloor(options);
380
+ if (!verdict.ok) throw new FloorError(UNDER_FLOOR, verdict.message, 75);
381
+ return verdict;
382
+ }
383
+
384
+ // ---- Admission log ---------------------------------------------------------------------
385
+
386
+ export const admissionsLog = (home = homedir()) => join(home, ".config", "nodii-resources", "admissions.jsonl");
387
+
388
+ /**
389
+ * The command text with what looks like a secret masked, before it is stored: an assignment or flag whose name says
390
+ * token, secret, password, PAT or key, an Authorization or Bearer value, and credentials in a URL.
391
+ */
392
+ export function redactCommand(text) {
393
+ return String(text ?? "")
394
+ .replace(/\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|PAT|API_?KEY|KEY)[A-Za-z0-9_]*=)("[^"]*"|'[^']*'|\S+)/gi, "$1***")
395
+ .replace(/(--?[a-z0-9-]*(?:token|secret|password|passwd|pat|api-?key)[a-z0-9-]*(?:=|\s+))("[^"]*"|'[^']*'|\S+)/gi, "$1***")
396
+ .replace(/\b(authorization:\s*(?:bearer\s+|basic\s+|token\s+)?|bearer\s+)("[^"]*"|'[^']*'|\S+)/gi, "$1***")
397
+ .replace(/(\w+:\/\/)[^/\s:@]+:[^/\s@]+@/g, "$1***@");
398
+ }
399
+
400
+ async function logDecision(verdict, { home, now, env }) {
401
+ const file = admissionsLog(home);
402
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
403
+ const entry = {
404
+ at: new Date(now).toISOString(),
405
+ kind: verdict.kind,
406
+ ok: verdict.ok,
407
+ what: redactCommand(verdict.what).slice(0, 300),
408
+ ...(verdict.landing ? { landing: true } : {}),
409
+ ...(verdict.preflight ? { preflight: true } : {}),
410
+ ...(verdict.tightened ? { tightened: true } : {}),
411
+ readings: verdict.readings,
412
+ reservedGb: verdict.reserved.gb,
413
+ floor: verdict.floor,
414
+ ...(verdict.failing.length ? { failing: verdict.failing.map(redactCommand) } : {}),
415
+ ...(verdict.holders.length ? { holders: verdict.holders } : {}),
416
+ ...(env.NODII_LANE_KEY ? { lane: env.NODII_LANE_KEY } : {}),
417
+ pid: process.ppid,
418
+ cwd: process.cwd(),
419
+ };
420
+ await appendFile(file, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
421
+ }
422
+
423
+ /** An admission whose own readings, after its reservations, fail its own floor. A preflight admits nothing. */
424
+ export const admittedUnderFloor = (entry) =>
425
+ Boolean(entry.ok && !entry.preflight && entry.floor && failingReadings(entry.readings, entry.floor, { gb: entry.reservedGb ?? 0, jobs: [] }).length);
426
+
427
+ /** The log's entries from the last SINCE_MS. */
428
+ export async function readAdmissions({ home = homedir(), now = Date.now(), sinceMs = 3_600_000 } = {}) {
429
+ let text = "";
430
+ try { text = await readFile(admissionsLog(home), "utf8"); } catch {}
431
+ return text.split("\n").filter(Boolean).flatMap((line) => { try { return [JSON.parse(line)]; } catch { return []; } })
432
+ .filter((entry) => Date.parse(entry.at) >= now - sinceMs);
433
+ }
434
+
435
+ /** The admissions part of `heavy status`: the last hour's decisions, and any admission under the floor. */
436
+ export function admissionsLines(entries, file) {
437
+ const refused = entries.filter((e) => !e.ok).length;
438
+ const passed = entries.filter((e) => e.ok && e.preflight).length;
439
+ const under = entries.filter(admittedUnderFloor).length;
440
+ const line = (e) => {
441
+ const verb = e.ok ? (e.preflight ? "passed " : "admitted") : "refused ";
442
+ const head = ` ${e.at.slice(11, 19)}Z ${verb} ${String(e.kind).padEnd(9)} ${readingsLine(e.readings ?? {})}${e.reservedGb ? `, ${e.reservedGb} GB held back` : ""} | floor ${e.floor ? floorLine(e.floor) : "?"}${admittedUnderFloor(e) ? " | UNDER THE FLOOR" : ""}`;
443
+ const tail = [e.lane && `lane ${e.lane}`, e.landing && "landing", e.what].filter(Boolean).join(" | ");
444
+ return `${head}${tail ? ` | ${tail}` : ""}`;
445
+ };
446
+ return [
447
+ `admissions in the last hour (${file}): ${entries.length - refused - passed} admitted, ${passed} preflights passed, ${refused} refused, ${under} admitted under the floor`,
448
+ ...entries.map(line),
449
+ ];
450
+ }
451
+
452
+ // ---- heavy-slot.sh's entry -------------------------------------------------------------
453
+
454
+ function scriptFlags(rest) {
455
+ const flags = { tighten: [] };
456
+ for (let i = 0; i < rest.length; i += 1) {
457
+ const m = /^--([a-z-]+)(?:=(.*))?$/.exec(rest[i]);
458
+ if (!m) continue;
459
+ const value = m[2] !== undefined ? m[2] : rest[i + 1] !== undefined && !rest[i + 1].startsWith("--") ? rest[(i += 1)] : true;
460
+ if (m[1] === "tighten") flags.tighten.push(value);
461
+ else flags[m[1]] = value;
462
+ }
463
+ return flags;
464
+ }
465
+
466
+ /** Shell assignments of the ceilings and stagger, for heavy-slot.sh's load_limits. */
467
+ export function shellLimits(settings) {
468
+ const c = settings.ceilings;
469
+ return [`SLOTS=${c.heavySlots}`, `RESERVE=${c.landingReserve}`, `LSLOTS=${c.lightSlots}`, `STAGGER=${Math.round(settings.staggerSec)}`].join("\n");
470
+ }
471
+
472
+ /** `heavy status`'s floor part: the file, the readings beside the floor, the classes, the ceilings, the admissions. */
473
+ export async function statusLines({ home = homedir(), now = Date.now(), settings: given, readings: givenReadings, reserved: givenReserved, entries: givenEntries } = {}) {
474
+ const settings = given ?? (await floorSettings());
475
+ const readings = givenReadings ?? (await readMachine({ home }));
476
+ const reserved = givenReserved ?? (await reservations({ settings }));
477
+ const f = settings.floor;
478
+ const c = settings.ceilings;
479
+ const after = Number.isFinite(readings.availGb) ? round1(readings.availGb - reserved.gb) : "?";
480
+ const failing = failingReadings(readings, floorFor("heavy", settings), reserved);
481
+ return [
482
+ `floor file: ${settings.why}`,
483
+ `memory available ${readings.availGb ?? "?"} GB, ${after} GB after ${reserved.gb} GB held back for ${reserved.jobs.length} running job(s) (floor ${f.minAvailGb} GB heavy, ${f.lightMinAvailGb} GB light)`,
484
+ `swap used ${readings.swapUsedGb ?? "?"} GB (ceiling ${f.maxSwapGb} GB) · disk free ${readings.diskFreeGb ?? "?"} GB (floor ${f.minDiskGb} GB)${failing.length ? ` · under the floor: ${failing.join("; ")}` : ""}`,
485
+ `classes: heavy floor ${f.minAvailGb} GB, peak ${settings.peaks.heavyGb} GB; light floor ${f.lightMinAvailGb} GB, peak ${settings.peaks.lightGb} GB (only end-to-end, real-stack and browser work is heavy)`,
486
+ `ceilings: ${c.heavySlots} heavy slots (${c.landingReserve} only for landings), ${c.lightSlots} light slots, ${settings.staggerSec} s stagger`,
487
+ ...(reserved.jobs.length ? reserved.jobs.map((j) => ` reserved: slot ${j.slot} ${j.size} ${j.heldGb} GB (peak ${j.peakGb} less ${j.usedGb} used)${j.what ? `: ${j.what}` : ""}`) : []),
488
+ ...admissionsLines(givenEntries ?? (await readAdmissions({ home, now })), admissionsLog(home)),
489
+ ];
490
+ }
491
+
492
+ /**
493
+ * `limits` (the ceilings as shell assignments), `check` (the floor, before a job queues and again at admission with
494
+ * --self SLOT: refusals are logged), `record` (the queue admitted a job: logged with its readings) and `status`.
495
+ */
496
+ export async function scriptMain(argv, { write = (t) => process.stdout.write(t), warn = (t) => process.stderr.write(t) } = {}) {
497
+ const [action, ...rest] = argv;
498
+ const flags = scriptFlags(rest);
499
+ const base = {
500
+ kind: typeof flags.class === "string" ? flags.class : "heavy",
501
+ what: typeof flags.what === "string" ? flags.what : "",
502
+ landing: Boolean(flags.landing),
503
+ self: typeof flags.self === "string" ? flags.self : "",
504
+ ...(flags.tighten.length ? { tighten: flags.tighten } : {}),
505
+ };
506
+ try {
507
+ if (action === "limits") { write(`${shellLimits(await floorSettings())}\n`); return 0; }
508
+ if (action === "status") { write(`${(await statusLines()).join("\n")}\n`); return 0; }
509
+ if (action === "check") {
510
+ const verdict = await checkFloor({ ...base, log: "refusals" });
511
+ if (!verdict.ok) { warn(`[heavy-slot] ${UNDER_FLOOR}: ${verdict.message.replace(/\n/g, "\n[heavy-slot] ")}\n`); return 75; }
512
+ return 0;
513
+ }
514
+ if (action === "record") { await checkFloor({ ...base, admitted: true, log: "all" }); return 0; }
515
+ warn("usage: machine-floor.js limits | status | check|record --class heavy|light [--what TEXT] [--landing] [--self SLOT] [--tighten READING=GB ...]\n");
516
+ return 2;
517
+ } catch (error) {
518
+ warn(`[heavy-slot] ${error?.code ?? UNDER_FLOOR}: ${error?.message ?? error}\n`);
519
+ return error?.exitCode === 2 ? 2 : 75;
520
+ }
521
+ }
522
+
523
+ // Run as a script (heavy-slot.sh). Compared through realpath: /tmp and /private/tmp, or a symlinked install, must
524
+ // still run the check rather than exit 0 having checked nothing.
525
+ const realOrSelf = (path) => { try { return realpathSync(path); } catch { return path; } };
526
+ if (process.argv[1] && realOrSelf(fileURLToPath(import.meta.url)) === realOrSelf(process.argv[1])) process.exitCode = await scriptMain(process.argv.slice(2));
package/dist/review.js CHANGED
@@ -496,12 +496,13 @@ export function spawnReviewer({ command, args, env, cwd, input, timeoutMs }, { a
496
496
  setTimeout(() => child.kill("SIGKILL"), 10_000).unref();
497
497
  }, timeoutMs);
498
498
  };
499
- // Inside a held slot, or when not queued at all, the reviewer starts at once.
500
- if (runEnv.NODII_HEAVY_SLOT || runEnv.NODII_HEAVY_SLOT_HELD === "1" || file === command) start();
499
+ // Not queued at all, the reviewer starts at once; queued, once heavy-slot grants a slot or finds it already runs
500
+ // inside one (nesting is proven by the process tree, heavy-slot v29: no variable skips the queue).
501
+ if (file === command) start();
501
502
  child.stdout.on("data", (chunk) => { stdout += chunk; });
502
503
  child.stderr.on("data", (chunk) => {
503
504
  stderr = (stderr + chunk).slice(-4000);
504
- if (/\[heavy-slot\] got /.test(String(chunk))) start();
505
+ if (/\[heavy-slot\] (?:got |nested in slot )/.test(String(chunk))) start();
505
506
  });
506
507
  child.stdin.on("error", () => {});
507
508
  const done = (result) => { if (timer) clearTimeout(timer); resolve(result); };
package/dist/rulings.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // this machine and never sent: the text must be an exact substring of that
6
6
  // turn's prompt, else RULING_NOT_TYPED and nothing is sent. Only the ruling's
7
7
  // own words leave the machine; it binds nothing until sorted and uploaded.
8
+ import { readFileSync } from "node:fs";
8
9
  import { CliError, devRequest } from "./core.js";
9
10
  import { readTurns } from "./session-kind.js";
10
11
 
@@ -24,11 +25,12 @@ export function typedForm(prompt, text) {
24
25
  }
25
26
 
26
27
  /** The session this command runs in, as the runtime names it; null when it does not. */
27
- export const sessionOf = (env = process.env) => env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || null;
28
+ export const sessionOf = (env = process.env) =>
29
+ env.CODEX_SESSION_ID || env.CODEX_THREAD_ID || env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || null;
28
30
 
29
31
  /**
30
- * The turn that typed the text: the session's own (CLAUDE_SESSION_ID or
31
- * CLAUDE_CODE_SESSION_ID), within the window. No session id, or no turn the
32
+ * The turn that typed the text: the current Codex or Claude session's own,
33
+ * within the window. No session id, or no turn the
32
34
  * hook recorded for it, is no proof: another session's turn never stands in.
33
35
  */
34
36
  export function typingTurn(turns, text, { env = process.env, now = Date.now() } = {}) {
@@ -45,11 +47,8 @@ export function typingTurn(turns, text, { env = process.env, now = Date.now() }
45
47
  return holding[0] ?? null;
46
48
  }
47
49
 
48
- async function readStdin(stream = process.stdin) {
49
- const chunks = [];
50
- for await (const chunk of stream) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
51
- return Buffer.concat(chunks).toString("utf8");
52
- }
50
+ // Read the descriptor directly so Bun reads both pipes and file-backed shell heredocs.
51
+ const readStdin = () => readFileSync(0, "utf8");
53
52
 
54
53
  export async function rulingCommand(action, args, flags, { request = devRequest, turns = readTurns, env = process.env, now = Date.now, stdin = readStdin } = {}) {
55
54
  if (action !== "file" || args.length) throw new CliError("USAGE", USAGE, 2);
@@ -63,7 +62,7 @@ export async function rulingCommand(action, args, flags, { request = devRequest,
63
62
  if (!match)
64
63
  throw new CliError("RULING_NOT_TYPED", sessionOf(env)
65
64
  ? "This session's prompt hook did not see these words typed in its current turn (within 30 minutes), so nothing was sent. File only the person's exact words, in the turn they typed them (MW1-115)."
66
- : "This command does not know its session (no CLAUDE_SESSION_ID or CLAUDE_CODE_SESSION_ID), so no turn proves these words were typed and nothing was sent (MW1-115).", 2);
65
+ : "This command does not know its session (no Codex or Claude session ID in the environment), so no turn proves these words were typed and nothing was sent (MW1-115).", 2);
67
66
  const payload = await request("POST", "/api/v1/rulings", { text: match.text, sessionId: match.turn.sessionId, typedAt: match.turn.at });
68
67
  return {
69
68
  payload,