@nodii/dev 0.6.125 → 0.6.127

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.
package/README.md CHANGED
@@ -89,6 +89,23 @@ checks the local stack.
89
89
  Every command accepts `--json`; without it, output is formatted for humans.
90
90
  Dev failures print Dev's error code to stderr and exit non-zero.
91
91
 
92
+ ## Heavy work: one machine-wide slot queue
93
+
94
+ Every heavy command a lane runs waits for one machine-wide heavy slot (MW2-51, K02-4; hub-377): typechecks, full and affected test suites, builds, gates, `git push` (its pre-push hooks run the gates), image builds and a detached `docker compose up`.
95
+
96
+ ```sh
97
+ nodii-dev heavy run -- pnpm -r typecheck
98
+ nodii-dev heavy run -- git push -u origin HEAD
99
+ nodii-dev heavy status
100
+ ```
101
+
102
+ - The queue is `heavy-slot` v24, shipped in this package (`src/heavy-slot.sh`, run by bash 3.2 or later). It carries v23's rules: a slot cap, a memory floor, a stagger between admissions, a landing reserve that only a push may use, FIFO order, reclaiming dead holders, and pass-through for teardowns (`compose down`, `stack:down`), a single `pnpm validate:<name>`, and a command that already holds a slot (K02-6). It refuses dev servers (K02-7). A foreground `docker compose up` never exits, so it never takes a slot either.
103
+ - Limits come from `~/.config/nodii-resources/limits.env`, re-read on every admission: `HEAVY_SLOTS`, `HEAVY_MIN_AVAIL_GB`, `HEAVY_STAGGER_SEC` and `HEAVY_LANDING_RESERVE`. The script header (`src/heavy-slot.sh`) gives the schema and the defaults. Locks live in `/tmp/nodii-heavy-slots`, the same directory v23 copies use, so every copy counts against the same slots.
104
+ - When no heavy job holds a slot, waiting can free no memory, so one job is admitted even under the floor, with a warning. The floor still holds every job beside it.
105
+ - A waiting job prints its queue place and its wait when it starts waiting and once a minute after. It never gives up, so the queue never times out a gate.
106
+ - It can't be skipped. In a lane, the safety hook (`hook safety-pre`) refuses an unqueued heavy command and prints the same command with `nodii-dev heavy run --` in front of each heavy part. `lane check --gate` and `receipt write --run` queue every gate themselves, `lane check` runs each reviewer under a slot (its timeout starts once the slot is granted), and `lane closeout` pushes through the landing reserve.
107
+ - `[TOOL GAP hub-86]` MW5-19 places this helper as the `heavy-slot` util. It ships here until the util pipeline exists.
108
+
92
109
  ## Receipts
93
110
 
94
111
  A gate that lets work move writes a signed receipt (STD-22, K04-27, S06-53 to S06-56). `lane check` and `lane review` write and attach a `review` receipt listing the `--gate` commands and the review checks, and stop if they cannot. A `test` receipt needs what those commands cannot see (scope, stack, auth posture), so it comes from `receipt write` or the stack tool's `test --receipt`. A receipt must name the lane it is attached to. Anything else uses:
package/bin/nodii-dev CHANGED
@@ -9,6 +9,17 @@ while [ -L "$self" ]; do
9
9
  done
10
10
  root="$(cd "$(dirname "$self")/.." && pwd)"
11
11
  entry="$root/dist/nodii-dev.js"
12
+ # The machine-wide heavy-slot queue (hub-377) is a shell program: exec
13
+ # it straight into bash, so the job's slot holder is that bash and nothing
14
+ # sits between them (its process groups and watchdog stay exactly as written).
15
+ if [ "${1:-}" = heavy ]; then
16
+ slot="$root/dist/heavy-slot.sh"
17
+ [ -f "$slot" ] || slot="$root/src/heavy-slot.sh"
18
+ case "${2:-}" in
19
+ run) shift 2; [ "${1:-}" = "--" ] && shift; exec /bin/bash "$slot" "$@" ;;
20
+ status) exec /bin/bash "$slot" --status ;;
21
+ esac
22
+ fi
12
23
  # A checkout's own build can be older than its package.json (Dev issue 88: a
13
24
  # stale 0.3.1 build once answered `npx @nodii/dev@0.6.10` inside a nodii-clis
14
25
  # worktree). Refuse to run one.
package/dist/cli.js CHANGED
@@ -368,6 +368,13 @@ Usage: nodii-dev <command> [options] [--json]
368
368
  [--run CMD ...] [--from-file DETAILS.json] [--out FILE]
369
369
  # one signed receipt (STD-22); --run gates stop at the first failure and exit 1
370
370
  receipt verify <file> [--commit SHA] # the signature, and that it names this commit (S06-55)
371
+ heavy run -- <command...> # run heavy work (tests, typecheck, build, gate, git push, image build,
372
+ # detached stack start) under one machine-wide slot (MW2-51): waits in FIFO
373
+ # order, printing its place and wait, while slots are full, memory is under
374
+ # the floor or the stagger runs; never times out. Limits: ~/.config/
375
+ # nodii-resources/limits.env. A push uses the landing reserve; a nested call
376
+ # runs at once (K02-6). A lane's safety hook refuses unqueued heavy work.
377
+ heavy status # limits, available memory, the slots held and the queue
371
378
  sync pending [--discard FILE --reason TEXT]
372
379
  # send the lane records queued while Dev was down (MW1-64); --discard drops
373
380
  # one Dev refuses for good, with a note on its lane
package/dist/closeout.js CHANGED
@@ -20,6 +20,7 @@ import { existsSync } from "node:fs";
20
20
  import { dirname, resolve, sep } from "node:path";
21
21
  import { promisify } from "node:util";
22
22
  import { encode } from "./core.js";
23
+ import { heavySlotArgv } from "./heavy.js";
23
24
 
24
25
  const execFileAsync = promisify(execFile);
25
26
  export const STOPPED_LABEL = "Stopped";
@@ -148,7 +149,8 @@ export async function closeoutRepository(lane, repository, { reason, issueKeys =
148
149
  } else {
149
150
  // The repository's own pre-push hook runs here, and on a large repository it takes minutes.
150
151
  say(`pushing ${ahead} leftover commit(s) to ${branch}, through the repository's pre-push hook; this can take minutes`);
151
- await git("push", "--quiet", "-u", "origin", `HEAD:refs/heads/${branch}`);
152
+ // A push is a landing: it waits for the heavy slot queue's landing reserve (hub-377).
153
+ await exec(...heavySlotArgv(["git", "-C", worktree, "push", "--quiet", "-u", "origin", `HEAD:refs/heads/${branch}`]));
152
154
  const remote = (await git("ls-remote", "origin", `refs/heads/${branch}`)).trim().split(/\s+/)[0] ?? "";
153
155
  pushedOk = remote === head;
154
156
  out.pushed = { ahead, head, remote, needed: true, readBack: pushedOk };
package/dist/core.js CHANGED
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { homedir, platform } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.125";
7
+ export const VERSION = "0.6.127";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
@@ -0,0 +1,274 @@
1
+ #!/usr/bin/env bash
2
+ # heavy-slot (v24, shipped with @nodii/dev): run a memory-heavy job (typecheck, build, full or affected test suite,
3
+ # a gate, `git push` and its pre-push hooks, an image build, a detached stack start) only when a machine-wide slot
4
+ # is free AND enough REAL memory is available. Every session and lane on this machine shares one queue (MW2-51, K02-4).
5
+ #
6
+ # nodii-dev heavy run -- <command...> wait for a slot, run the command, release the slot when it exits
7
+ # nodii-dev heavy status the limits, available memory, the slots held and the queue
8
+ #
9
+ # [TOOL GAP hub-86] MW5-19 places this helper as the `heavy-slot` util (MW5-26: the first util to publish).
10
+ # Until the util pipeline (`nodii-dev util run`, ~/.nodii/utils) exists, @nodii/dev ships it and its hooks enforce it
11
+ # (hub-377). It carries heavy-slot.sh v23 (nodii-hr-service docs/figma-ux-drive/dev/heavy-slot.sh) and uses
12
+ # the same lock directory, so a v23 copy still running elsewhere counts against the same slots.
13
+ #
14
+ # Limits live in ~/.config/nodii-resources/limits.env (owned by the machine's coordinator) and are re-read on every
15
+ # admission attempt, so changing them needs no lane restart. Schema and defaults (MW5-23):
16
+ # HEAVY_SLOTS=2 concurrent heavy jobs machine-wide
17
+ # HEAVY_MIN_AVAIL_GB=16 admit only when available memory (RAM - app - wired - compressed, as Activity Monitor) >= this.
18
+ # `memory_pressure`'s "free percentage" is NOT used: it read 84% while far less was available.
19
+ # HEAVY_STAGGER_SEC=60 minimum gap between two admissions, so a job's memory growth shows before the next one starts
20
+ # HEAVY_LANDING_RESERVE=1 slots only a landing (`git push`, or anything under HEAVY_LANDING=1) may use
21
+ # Environment: NODII_RESOURCE_LIMITS (the limits file), HEAVY_SLOT_DIR (the lock directory), HEAVY_SLOT_POLL_SEC (10).
22
+ #
23
+ # Locks are mkdir dirs under /tmp/nodii-heavy-slots/<n> holding the owner pid; stale locks (dead pid) are reclaimed.
24
+ # The whole body is one function, called on the last line: bash then parses the entire file before running any of it,
25
+ # so overwriting this file while copies are running cannot splice old and new code (15 Oct: an in-place cp of v6
26
+ # over a running v5 produced 'others: unbound variable'). Runs on the bash macOS ships (3.2) (MW5-22).
27
+ main() {
28
+ set -u
29
+ LIMITS="${NODII_RESOURCE_LIMITS:-$HOME/.config/nodii-resources/limits.env}"
30
+ D="${HEAVY_SLOT_DIR:-/tmp/nodii-heavy-slots}"
31
+ POLL="${HEAVY_SLOT_POLL_SEC:-10}"; case "$POLL" in ''|*[!0-9]*|0) POLL=10;; esac
32
+ IS_LANDING=0
33
+ load_limits() {
34
+ SLOTS=2; MIN_GB=16; STAGGER=60; RESERVE=1
35
+ HEAVY_SLOTS=""; HEAVY_MIN_AVAIL_GB=""; HEAVY_STAGGER_SEC=""; HEAVY_LANDING_RESERVE=""
36
+ if [ -r "$LIMITS" ]; then
37
+ # shellcheck disable=SC1090
38
+ . "$LIMITS"
39
+ fi
40
+ SLOTS="${HEAVY_SLOTS:-$SLOTS}"; MIN_GB="${HEAVY_MIN_AVAIL_GB:-$MIN_GB}"; STAGGER="${HEAVY_STAGGER_SEC:-$STAGGER}"
41
+ RESERVE="${HEAVY_LANDING_RESERVE:-$RESERVE}"
42
+ # A garbled limit must never break the arithmetic below (an arithmetic error aborts the wait loop).
43
+ case "$SLOTS" in ''|*[!0-9]*|0) SLOTS=2;; esac; case "$MIN_GB" in ''|*[!0-9]*) MIN_GB=16;; esac
44
+ case "$STAGGER" in ''|*[!0-9]*) STAGGER=60;; esac; case "$RESERVE" in ''|*[!0-9]*) RESERVE=1;; esac
45
+ # v15 (24 Oct): landings get a reserved slot. A `git push` (whose pre-push runs the gates) stuck behind
46
+ # typechecks/tests blocks the whole fleet (HR's FE landings queued ~70 min, 10:30Z). Non-landing jobs may use
47
+ # only slots 1..SLOTS-RESERVE.
48
+ MAXSLOT=$SLOTS
49
+ if [ "$IS_LANDING" != 1 ]; then MAXSLOT=$(( SLOTS - RESERVE )); [ "$MAXSLOT" -lt 1 ] && MAXSLOT=1; fi
50
+ }
51
+ avail_gb() {
52
+ # Activity Monitor's accounting: used = app memory (anonymous - purgeable) + wired + compressor; available = RAM - used.
53
+ # Counting inactive/free pages instead overstated headroom by ~5 GB, because the compressor (26 GB on 15 Oct,
54
+ # mostly the Docker VM) holds live processes' memory that no resident-size figure shows.
55
+ # A sandboxed lane (Codex seatbelt) can't read hw.memsize: an empty ram made available memory negative and the
56
+ # gate refused every job forever (23 Oct, DOCCLOUD-VIEW-1). Fall back to the value the coordinator records (v10).
57
+ if [ -r /proc/meminfo ] && ! command -v vm_stat >/dev/null 2>&1; then
58
+ awk '/^MemAvailable:/{printf "%d", $2/1048576; f=1} END{if(!f) printf "0"}' /proc/meminfo; return
59
+ fi
60
+ local ram; ram=$(sysctl -n hw.memsize 2>/dev/null); case "$ram" in ''|*[!0-9]*) ram=$(cat "$HOME/.config/nodii-resources/hw.memsize" 2>/dev/null);; esac
61
+ case "$ram" in ''|*[!0-9]*) echo 0; return;; esac
62
+ vm_stat | awk -v ram="$ram" '/page size of/{ps=$8} /Anonymous pages/{an=$3} /Pages purgeable/{p=$3}
63
+ /Pages wired/{w=$4} /occupied by compressor/{c=$5}
64
+ END{used=(an-p+w+c)*ps; printf "%d", (ram-used)/1073741824}'
65
+ }
66
+ mtime() { local m; m=$(stat -f %m "$1" 2>/dev/null) || m=$(stat -c %Y "$1" 2>/dev/null); case "$m" in ''|*[!0-9]*) echo "";; *) echo "$m";; esac; }
67
+ since_last_admit() {
68
+ # Any missing/empty/garbled stamp means "long ago". Never feed an empty string to $(( )): in bash an arithmetic
69
+ # error aborts the enclosing loop, which once let a job run with NO slot (15 Oct, found by task-tracking).
70
+ local t; t=$(cat "$D/last-admit" 2>/dev/null); case "$t" in ''|*[!0-9]*) echo 999999; return;; esac
71
+ echo $(( $(date +%s) - t ))
72
+ }
73
+ admit_lock_age() {
74
+ local m; m=$(mtime "$D/.admit"); [ -n "$m" ] || { echo 0; return; }
75
+ echo $(( $(date +%s) - m ))
76
+ }
77
+ # Reclaim ONLY on "No such process". `kill -0` also fails with "Operation not permitted" when this waiter runs in a
78
+ # sandbox (Codex seatbelt) that can't signal other processes, so a live job looked dead and its slot was deleted
79
+ # under it: 23 Oct 10:05Z, four jobs running with ZERO slot dirs (v9).
80
+ dead() { local e; [ -n "$1" ] || return 1; e=$(kill -0 "$1" 2>&1) && return 1; case "$e" in *"No such process"*) return 0;; esac; return 1; }
81
+ # v17 (24 Oct): reclaim dead holders in EVERY slot dir (a slot numbered above a lowered cap was never scanned, so a
82
+ # dead holder kept it "held" forever), and count only LIVE holders.
83
+ held_count() { local o op n=0
84
+ for o in "$D"/[0-9]*; do
85
+ [ -d "$o" ] || continue
86
+ op=$(cat "$o/pid" 2>/dev/null || echo)
87
+ if dead "$op"; then rm -rf "$o"; continue; fi
88
+ n=$((n + 1))
89
+ done; echo "$n"; }
90
+
91
+ if [ "${1:-}" = "--status" ]; then
92
+ [ -d "$D" ] || mkdir -p "$D" 2>/dev/null
93
+ load_limits
94
+ local now held q t tp o; now=$(date +%s); held=$(held_count)
95
+ echo "heavy-slot v24 · limits $LIMITS"
96
+ echo "slots ${held}/${SLOTS} held (landing reserve ${RESERVE}: other jobs use at most $(( SLOTS - RESERVE < 1 ? 1 : SLOTS - RESERVE )))"
97
+ echo "available memory $(avail_gb) GB (floor ${MIN_GB} GB) · stagger ${STAGGER}s"
98
+ for o in "$D"/[0-9]*; do
99
+ [ -d "$o" ] || continue
100
+ t=$(mtime "$o"); echo " slot $(basename "$o") pid $(cat "$o/pid" 2>/dev/null) for $(( now - ${t:-$now} ))s: $(cat "$o/what" 2>/dev/null)"
101
+ done
102
+ q=0
103
+ for t in $(ls "$D/q" 2>/dev/null | sort); do
104
+ tp=$(cat "$D/q/$t" 2>/dev/null)
105
+ if dead "$tp"; then rm -f "$D/q/$t"; continue; fi
106
+ q=$((q + 1)); echo " queued $q: pid ${tp} waiting $(( now - ${t%%.*} ))s"
107
+ done
108
+ echo "queue ${q} waiting"
109
+ return 0
110
+ fi
111
+
112
+ [ $# -gt 0 ] || { echo "usage: nodii-dev heavy run -- <command...> | nodii-dev heavy status" >&2; return 2; }
113
+ # Long-running dev/preview servers are not jobs: they never exit, so they would hold a slot forever
114
+ # (15 Oct: a `vite --port 5260` sat in a slot while 7 real jobs queued). Refuse them; run them outside the gate,
115
+ # at most DEV_SERVER_CAP host-wide, and kill them by PID when done (K02-7). `vite build`, vitest and typechecks are jobs.
116
+ local cmd=" $* " JOB="$*"
117
+ if { printf '%s' "$cmd" | grep -Eq '[ /]vite( |$)' && ! printf '%s' "$cmd" | grep -Eq '[ /]vite build'; } \
118
+ || printf '%s' "$cmd" | grep -Eq ' (next|storybook) dev |[ /](pnpm|npm|bun|yarn)( run)? dev( |$)'; then
119
+ echo "[heavy-slot] refusing a long-running dev server (it would hold a slot forever): $*" >&2
120
+ echo "[heavy-slot] run it OUTSIDE heavy-slot, at most DEV_SERVER_CAP host-wide, and kill it by PID when done." >&2
121
+ return 64
122
+ fi
123
+ # v20 (24 Oct): already inside a heavy slot (an outer heavy-slot or a gated-bin wrapper set this) -> run directly.
124
+ # A nested heavy-slot used to wait for a SECOND slot while its parent held one: tenant's db:setup sat 74 min that way (K02-6).
125
+ [ "${NODII_HEAVY_SLOT_HELD:-}" = 1 ] && exec "$@"
126
+ # v18 (24 Oct): a teardown FREES memory, so it never waits for a slot. `docker compose … down -v` sat 3 min behind
127
+ # 14 queued jobs (12:27Z) while its stack kept its containers' memory.
128
+ case " $* " in *" compose "*" down"*|*" down "*|*stack:down*|*":down "*) exec "$@";; esac
129
+ # v24: a DETACHED `docker compose … up` (-d, --detach, --wait) starts a stack and exits: it takes a slot like any
130
+ # other heavy job (hub-377), replacing v22's pass-through. A foreground `up` never exits, so like a dev
131
+ # server it never holds a slot (K02-7); STACK_CAP still limits running stacks.
132
+ case " $* " in *" compose up "*|*" compose "*" up "*)
133
+ case " $* " in *" -d "*|*" --detach "*|*" --wait "*|*" --wait="*|*" -"[a-zA-Z]*d[a-zA-Z]*" "*) ;; *) exec "$@";; esac;; esac
134
+ # v23 (25 Oct, infra-e3): a SINGLE `pnpm validate:<name>` is a cheap file scan (<10 s, little memory; TT measured
135
+ # the gate validators). It never waits for a heavy slot. Typecheck, test, lint, build and the full `pnpm gate` still queue.
136
+ case "$*" in "pnpm validate:"*|"pnpm run validate:"*) case "$*" in *" "*" "*|*"&&"*|*";"*) ;; *) exec "$@";; esac;; esac
137
+ mkdir -p "$D" 2>/dev/null
138
+ # v11 (23 Oct): a Codex workspace-write sandbox denies writes here unless /private/tmp/nodii-heavy-slots is in
139
+ # [sandbox_workspace_write] writable_roots. Without it every `mkdir "$l"` below failed with EPERM, which the loop
140
+ # read as "slot busy", and jobs waited FOREVER with slots free. Fail fast and loudly instead.
141
+ if ! { : > "$D/.writable.$$"; } 2>/dev/null; then
142
+ echo "[heavy-slot] FATAL: cannot write $D (sandboxed? add /private/tmp/nodii-heavy-slots to the lane's writable_roots and relaunch it). Refusing to wait forever: $*" >&2
143
+ return 77
144
+ fi
145
+ rm -f "$D/.writable.$$"
146
+ export NODII_HEAVY_SLOT_HELD=1
147
+ # v16: a landing script that runs its pre-push gates itself (then pushes --no-verify) marks the whole landing with
148
+ # HEAVY_LANDING=1, so every gate of the landing uses the reserve, not only the final push (HR land.sh, 10-24).
149
+ # v24: `git -C dir push` and `git -c k=v push` are landings too.
150
+ is_push() {
151
+ case "$(basename -- "${1:-}")" in git) ;; *) return 1;; esac; shift
152
+ while [ $# -gt 0 ]; do
153
+ case "$1" in
154
+ push) return 0;;
155
+ -C|-c|--git-dir|--work-tree|--namespace|--exec-path|--config-env) [ $# -ge 2 ] || return 1; shift 2;;
156
+ -*) shift;;
157
+ *) return 1;;
158
+ esac
159
+ done; return 1; }
160
+ is_push "$@" && IS_LANDING=1; [ "${HEAVY_LANDING:-}" = 1 ] && IS_LANDING=1
161
+ # v19 (24 Oct): FIFO. Waiters raced for freed slots, so an unlucky job starved: tenant's `test:stack:up` waited 71 min
162
+ # behind 14 newer jobs (12:27Z). Each non-landing waiter takes a ticket (time-ordered name); only the oldest
163
+ # (limit - held) live tickets may try for a slot. Landings keep their reserve and skip the line.
164
+ local Q="$D/q" TICKET=""; mkdir -p "$Q" 2>/dev/null
165
+ if [ "$IS_LANDING" != 1 ]; then TICKET="$Q/$(date +%s).$(printf '%06d' $$)"; echo $$ > "$TICKET"; fi
166
+ trap '[ -n "$TICKET" ] && rm -f "$TICKET"' EXIT
167
+ fifo_rank() { local r=0 t tp
168
+ for t in $(ls "$Q" 2>/dev/null | sort); do
169
+ tp=$(cat "$Q/$t" 2>/dev/null); if dead "$tp"; then rm -f "$Q/$t"; continue; fi
170
+ [ "$Q/$t" = "$TICKET" ] && { echo "$r"; return; }; r=$((r + 1)); done; echo 0; }
171
+ local slot="" waited=0 said=-1 held rank LIMIT i l o a g others av why
172
+ # A queued job says its place and its wait when it starts waiting and then once a minute; it never gives up, so a
173
+ # gate is never timed out by the queue (hub-377).
174
+ say() { if [ "$said" -lt 0 ] || [ $((waited - said)) -ge 60 ]; then said=$waited; echo "[heavy-slot] waiting ${waited}s: $1. Job: $JOB" >&2; fi; }
175
+ pause() { sleep "$POLL"; waited=$((waited + POLL)); }
176
+ while :; do
177
+ load_limits
178
+ # v17: admit only while the LIVE held count is under this job's limit. v16 only looked for a free slot number
179
+ # <= cap, so after the cap dropped 5->3 a freed slot 1 was refilled at once with 5 jobs still running (10:42Z).
180
+ held=$(held_count)
181
+ LIMIT=$MAXSLOT
182
+ if [ -n "$TICKET" ] && [ "$held" -lt "$LIMIT" ]; then
183
+ rank=$(fifo_rank)
184
+ if [ "$rank" -ge $((LIMIT - held)) ]; then
185
+ say "queue position $((rank + 1)) (${held}/${LIMIT} slots held)"; pause; continue
186
+ fi
187
+ fi
188
+ if [ "$held" -ge "$LIMIT" ]; then
189
+ if [ -n "$TICKET" ]; then rank=$(fifo_rank); say "queue position $((rank + 1)); ${held} slots held >= limit ${LIMIT} (cap ${SLOTS}, landing reserve ${RESERVE})"
190
+ else say "landing: ${held} slots held >= cap ${SLOTS}"; fi
191
+ pause; continue
192
+ fi
193
+ for i in $(seq 1 "$SLOTS"); do
194
+ l="$D/$i"
195
+ if [ -d "$l" ]; then o=$(cat "$l/pid" 2>/dev/null || echo); dead "$o" && rm -rf "$l"; fi
196
+ if mkdir "$l" 2>/dev/null; then
197
+ echo $$ > "$l/pid"; echo "$(pwd) :: $*" > "$l/what"
198
+ a=$(avail_gb); a=${a:-0}
199
+ # admission check and last-admit stamp happen while holding the admit lock, so two jobs can't pass the stagger together
200
+ # an admit lock older than 30s belongs to a process that died mid-check: reclaim it
201
+ if [ "$(admit_lock_age)" -gt 30 ]; then rmdir "$D/.admit" 2>/dev/null; fi
202
+ if mkdir "$D/.admit" 2>/dev/null; then
203
+ g=$(since_last_admit)
204
+ # The stagger only matters while another admitted job is still running (its memory may still be growing).
205
+ # With every other slot idle, admit at once: a fixed 60 s gap serialised quick jobs (biome, lint) to one a
206
+ # minute and queued 29 of them with zero heavy jobs running (15 Oct 15:38Z).
207
+ others=0; for o in "$D"/[0-9]*; do [ -d "$o" ] && [ "$o" != "$l" ] && others=$((others + 1)); done
208
+ # v24 (hub-377): with NO heavy job running, waiting cannot free memory (heavy jobs hold none of it), so the
209
+ # floor would stop every job on the machine for good, landings too: once every lane went through the queue,
210
+ # 6 GB available under a 14 GB floor with 0 slots held queued all of them. One job is then admitted, with a
211
+ # warning; the floor still holds every job beside it.
212
+ # v24 (hub-377): a landing is not held by the floor either, only by the cap and the stagger. On 13 Nov a
213
+ # landing waited 105 s with 3/6 slots held, because the machine's own load (no heavy job's) kept memory
214
+ # under the floor; a stuck landing blocks the fleet (v15), and a landing runs once and frees its lane.
215
+ # v24 (hub-377): the cap is checked again HERE, under the admit lock. The held count at the top of the loop
216
+ # is read before the lock, so two waiters could both see one free slot, take two slot numbers and run one
217
+ # job over the cap (seen in the suite under load: 3 at once with a limit of 2; v23 had the same race).
218
+ if [ "$others" -lt "$LIMIT" ] && { [ "$a" -ge "$MIN_GB" ] || [ "$others" -eq 0 ] || [ "$IS_LANDING" = 1 ]; } && { [ "$others" -eq 0 ] || [ "$g" -ge "$STAGGER" ]; }; then
219
+ if [ "$a" -lt "$MIN_GB" ] && [ "$others" -eq 0 ]; then echo "[heavy-slot] available ${a} GB is under the floor ${MIN_GB} GB, but no other heavy job is running, so waiting cannot free memory: admitting this one job alone." >&2
220
+ elif [ "$a" -lt "$MIN_GB" ]; then echo "[heavy-slot] available ${a} GB is under the floor ${MIN_GB} GB; a landing is held only by the cap and the stagger: admitting it." >&2; fi
221
+ date +%s > "$D/last-admit"; rmdir "$D/.admit"; slot="$l"; [ -n "$TICKET" ] && rm -f "$TICKET"; TICKET=""; break 2
222
+ fi
223
+ rmdir "$D/.admit"
224
+ fi
225
+ rm -rf "$l"
226
+ fi
227
+ done
228
+ # v12 (24 Oct): say WHICH gate is holding.
229
+ held=$(held_count); av=$(avail_gb)
230
+ if [ "$held" -ge "$SLOTS" ]; then why="all ${SLOTS} slots held"
231
+ elif [ "${av:-0}" -lt "$MIN_GB" ]; then why="available ${av} GB < floor ${MIN_GB} GB (${held}/${SLOTS} slots held)"
232
+ else why="${STAGGER}s stagger after the last admission (${held}/${SLOTS} held, ${av} GB available)"; fi
233
+ say "$why"
234
+ pause
235
+ done
236
+ # belt and braces: never run without a slot
237
+ [ -n "$slot" ] && [ -d "$slot" ] || { echo "[heavy-slot] internal error: no slot acquired; refusing to run: $*" >&2; exit 70; }
238
+ echo "[heavy-slot] got $(basename "$slot")/${SLOTS} after ${waited}s (available $(avail_gb) GB): $*" >&2
239
+ # Run the job as its OWN process group and forward INT/TERM to the whole group. Without this, stopping the wrapper
240
+ # left the job running (15 Oct: a sharded tsc kept spawning 4 GB shards after its wrapper was killed) AND released
241
+ # the slot, so the gate under-counted live memory.
242
+ set -m
243
+ "$@" &
244
+ child=$!
245
+ # v13 (24 Oct): a wrapper killed with SIGKILL (Codex's per-command timeout) can't run its traps, and the job
246
+ # lives in its own process group, so it was orphaned and kept running with NO slot. A watchdog in ITS OWN group
247
+ # outlives the wrapper and takes the job down with it.
248
+ # v14 (24 Oct): killing only the job's group missed `git push` → lefthook → `pnpm typecheck`, which runs in a
249
+ # group of its own. Snapshot the WHOLE descendant tree first (once parents die, children reparent and can't be
250
+ # found), then signal every group in it.
251
+ wrapper=$$
252
+ tree_groups() { local all="$1" frontier="$1" next c k pp
253
+ while [ -n "$frontier" ]; do next=""
254
+ # v21 (24 Oct): ps, not `pgrep -P`. pgrep needs macOS sysmond; when sysmond died, pgrep returned nothing.
255
+ pp=$(ps -axo pid=,ppid= 2>/dev/null || ps -eo pid=,ppid=)
256
+ for c in $frontier; do for k in $(awk -v p="$c" '$2==p{print $1}' <<<"$pp"); do all="$all $k"; next="$next $k"; done; done
257
+ frontier="$next"; done
258
+ for c in $all; do ps -o pgid= -p "$c" 2>/dev/null; done | tr -d ' ' | sort -u; }
259
+ kill_tree() { local g gs; gs=$(tree_groups "$child"); gs=$(printf '%s\n%s\n' "$child" "$gs" | sort -u)
260
+ for g in $gs; do [ "$g" -gt 1 ] && kill -TERM -- "-$g" 2>/dev/null; done; sleep 5
261
+ for g in $gs; do [ "$g" -gt 1 ] && kill -KILL -- "-$g" 2>/dev/null; done; }
262
+ ( trap '' HUP
263
+ while :; do dead "$wrapper" && break; sleep 2; done
264
+ kill_tree ) </dev/null >/dev/null 2>&1 &
265
+ watchdog=$!
266
+ set +m
267
+ stop() { kill_tree; rm -rf "$slot"; exit 143; }
268
+ trap stop INT TERM
269
+ trap 'rm -rf "$slot"' EXIT
270
+ wait "$child"; rc=$?
271
+ kill "$watchdog" 2>/dev/null
272
+ exit "$rc"
273
+ }
274
+ main "$@"; exit $?