@nodii/dev 0.6.125 → 0.6.126

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.126";
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,267 @@
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
+ if { [ "$a" -ge "$MIN_GB" ] || [ "$others" -eq 0 ]; } && { [ "$others" -eq 0 ] || [ "$g" -ge "$STAGGER" ]; }; then
213
+ [ "$a" -lt "$MIN_GB" ] && 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
214
+ date +%s > "$D/last-admit"; rmdir "$D/.admit"; slot="$l"; [ -n "$TICKET" ] && rm -f "$TICKET"; TICKET=""; break 2
215
+ fi
216
+ rmdir "$D/.admit"
217
+ fi
218
+ rm -rf "$l"
219
+ fi
220
+ done
221
+ # v12 (24 Oct): say WHICH gate is holding.
222
+ held=$(held_count); av=$(avail_gb)
223
+ if [ "$held" -ge "$SLOTS" ]; then why="all ${SLOTS} slots held"
224
+ elif [ "${av:-0}" -lt "$MIN_GB" ]; then why="available ${av} GB < floor ${MIN_GB} GB (${held}/${SLOTS} slots held)"
225
+ else why="${STAGGER}s stagger after the last admission (${held}/${SLOTS} held, ${av} GB available)"; fi
226
+ say "$why"
227
+ pause
228
+ done
229
+ # belt and braces: never run without a slot
230
+ [ -n "$slot" ] && [ -d "$slot" ] || { echo "[heavy-slot] internal error: no slot acquired; refusing to run: $*" >&2; exit 70; }
231
+ echo "[heavy-slot] got $(basename "$slot")/${SLOTS} after ${waited}s (available $(avail_gb) GB): $*" >&2
232
+ # Run the job as its OWN process group and forward INT/TERM to the whole group. Without this, stopping the wrapper
233
+ # left the job running (15 Oct: a sharded tsc kept spawning 4 GB shards after its wrapper was killed) AND released
234
+ # the slot, so the gate under-counted live memory.
235
+ set -m
236
+ "$@" &
237
+ child=$!
238
+ # v13 (24 Oct): a wrapper killed with SIGKILL (Codex's per-command timeout) can't run its traps, and the job
239
+ # lives in its own process group, so it was orphaned and kept running with NO slot. A watchdog in ITS OWN group
240
+ # outlives the wrapper and takes the job down with it.
241
+ # v14 (24 Oct): killing only the job's group missed `git push` → lefthook → `pnpm typecheck`, which runs in a
242
+ # group of its own. Snapshot the WHOLE descendant tree first (once parents die, children reparent and can't be
243
+ # found), then signal every group in it.
244
+ wrapper=$$
245
+ tree_groups() { local all="$1" frontier="$1" next c k pp
246
+ while [ -n "$frontier" ]; do next=""
247
+ # v21 (24 Oct): ps, not `pgrep -P`. pgrep needs macOS sysmond; when sysmond died, pgrep returned nothing.
248
+ pp=$(ps -axo pid=,ppid= 2>/dev/null || ps -eo pid=,ppid=)
249
+ 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
250
+ frontier="$next"; done
251
+ for c in $all; do ps -o pgid= -p "$c" 2>/dev/null; done | tr -d ' ' | sort -u; }
252
+ kill_tree() { local g gs; gs=$(tree_groups "$child"); gs=$(printf '%s\n%s\n' "$child" "$gs" | sort -u)
253
+ for g in $gs; do [ "$g" -gt 1 ] && kill -TERM -- "-$g" 2>/dev/null; done; sleep 5
254
+ for g in $gs; do [ "$g" -gt 1 ] && kill -KILL -- "-$g" 2>/dev/null; done; }
255
+ ( trap '' HUP
256
+ while :; do dead "$wrapper" && break; sleep 2; done
257
+ kill_tree ) </dev/null >/dev/null 2>&1 &
258
+ watchdog=$!
259
+ set +m
260
+ stop() { kill_tree; rm -rf "$slot"; exit 143; }
261
+ trap stop INT TERM
262
+ trap 'rm -rf "$slot"' EXIT
263
+ wait "$child"; rc=$?
264
+ kill "$watchdog" 2>/dev/null
265
+ exit "$rc"
266
+ }
267
+ main "$@"; exit $?
package/dist/heavy.js ADDED
@@ -0,0 +1,302 @@
1
+ // hub-377 (MW2-51, K02-4, K02-6, K02-7): every heavy command a lane
2
+ // runs goes through one machine-wide slot queue. The queue itself is
3
+ // heavy-slot.sh, beside this file; `nodii-dev heavy run -- CMD` reaches it
4
+ // (bin/nodii-dev execs it straight into bash). This module is the Node side:
5
+ // which shell commands are heavy, the rewrite that queues them, the argv the
6
+ // gate runner spawns, and a fallback for `heavy` when the CLI starts on Node.
7
+ // [TOOL GAP hub-86] MW5-19 places heavy-slot as a util; until the util
8
+ // pipeline exists it ships here.
9
+ import { spawn } from "node:child_process";
10
+ import { basename } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { CliError } from "./core.js";
13
+
14
+ export const HEAVY_SLOT_SCRIPT = fileURLToPath(new URL("./heavy-slot.sh", import.meta.url));
15
+ export const HEAVY_PREFIX = "nodii-dev heavy run -- ";
16
+ export const HEAVY_USAGE = "nodii-dev heavy run -- <command...> | nodii-dev heavy status";
17
+
18
+ /** The process that runs ARGV under a heavy slot: `[file, args]` for spawn. A nested call runs at once (K02-6). */
19
+ export const heavySlotArgv = (argv) => ["/bin/bash", [HEAVY_SLOT_SCRIPT, ...argv]];
20
+
21
+ /** `nodii-dev heavy run|status` when the CLI was started on Node or Bun rather than through bin/nodii-dev. */
22
+ export async function heavyCommand(args, { spawnImpl = spawn, env = process.env, signals = process } = {}) {
23
+ const [action, ...rest] = args;
24
+ let argv;
25
+ if (action === "status") argv = ["--status"];
26
+ else if (action === "run") {
27
+ argv = rest[0] === "--" ? rest.slice(1) : rest;
28
+ if (!argv.length) throw new CliError("USAGE", HEAVY_USAGE, 2);
29
+ } else throw new CliError("USAGE", HEAVY_USAGE, 2);
30
+ const [file, fileArgs] = heavySlotArgv(argv);
31
+ return new Promise((resolve) => {
32
+ const child = spawnImpl(file, fileArgs, { stdio: "inherit", env });
33
+ // The slot holder is the bash child; pass a stop on to it so it frees the slot and stops the job.
34
+ const forward = (signal) => () => child.kill(signal);
35
+ const handlers = ["SIGINT", "SIGTERM", "SIGHUP"].map((signal) => [signal, forward(signal)]);
36
+ for (const [signal, handler] of handlers) signals.on?.(signal, handler);
37
+ const done = (code) => {
38
+ for (const [signal, handler] of handlers) signals.off?.(signal, handler);
39
+ resolve(code);
40
+ };
41
+ child.on("error", () => done(127));
42
+ child.on("close", (code, signal) => done(code ?? (signal ? 128 : 1)));
43
+ });
44
+ }
45
+
46
+ // --- which shell commands are heavy -------------------------------------------
47
+
48
+ /**
49
+ * Shell words with their source offsets, split into simple commands on control
50
+ * operators (`&&`, `||`, `;`, `|`, `&`, newline). Quotes are kept out of a word's
51
+ * text; a word's `start` is where it begins in COMMAND, so a prefix can be
52
+ * inserted in front of it.
53
+ */
54
+ export function shellCommands(command) {
55
+ const text = String(command ?? "");
56
+ const out = [[]];
57
+ let word = null;
58
+ const finish = (end) => {
59
+ if (word) out.at(-1).push({ ...word, end });
60
+ word = null;
61
+ };
62
+ for (let i = 0; i < text.length; i += 1) {
63
+ const c = text[i];
64
+ if (c === "\\" && i + 1 < text.length) {
65
+ word ??= { text: "", start: i, quoted: false };
66
+ if (text[i + 1] !== "\n") word.text += text[i + 1];
67
+ i += 1;
68
+ continue;
69
+ }
70
+ if (c === "'" || c === '"') {
71
+ word ??= { text: "", start: i, quoted: false };
72
+ word.quoted = true;
73
+ let j = i + 1;
74
+ while (j < text.length && text[j] !== c) {
75
+ if (c === '"' && text[j] === "\\" && j + 1 < text.length) { word.text += text[j + 1]; j += 2; continue; }
76
+ word.text += text[j];
77
+ j += 1;
78
+ }
79
+ i = j;
80
+ continue;
81
+ }
82
+ if (c === " " || c === "\t") { finish(i); continue; }
83
+ const two = text.slice(i, i + 2);
84
+ // `2>&1`, `>&2` and `&>file` are redirections, not the background operator.
85
+ const redirect = c === "&" && ((word && /[<>]$/.test(word.text)) || text[i + 1] === ">");
86
+ if (!redirect && (two === "&&" || two === "||" || two === "|&" || two === ";;")) { finish(i); out.push([]); i += 1; continue; }
87
+ if (!redirect && (c === ";" || c === "|" || c === "&" || c === "\n")) { finish(i); out.push([]); continue; }
88
+ word ??= { text: "", start: i, quoted: false };
89
+ word.text += c;
90
+ }
91
+ finish(text.length);
92
+ return out.filter((segment) => segment.length);
93
+ }
94
+
95
+ // Words that start a command without being it. After these the queue prefix goes after them...
96
+ const KEYWORDS = new Set(["if", "then", "else", "elif", "do", "while", "until", "!", "exec", "command", "{", "("]);
97
+ // ...and these wrap the job, so the prefix goes in front of them (the slot is held for all of it).
98
+ const WRAPPERS = new Set(["time", "nohup", "env", "timeout", "gtimeout", "nice", "caffeinate"]);
99
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
100
+ const HELP = new Set(["--version", "-v", "-V", "--help", "-h"]);
101
+
102
+ // A package script is heavy when any `:`-part of its name is one of these (`test:unit`, `typecheck`,
103
+ // `build:all`, `gate`), or when it starts a stack. A lone `validate:<name>` is a cheap scan (heavy-slot v23).
104
+ const HEAVY_SCRIPT_PARTS = new Set(["test", "tests", "typecheck", "type-check", "types", "tsc", "check", "build", "gate", "gates", "lint", "e2e", "ci", "verify", "coverage", "prepush", "pre-push", "integration", "regression"]);
105
+ export function heavyScript(name) {
106
+ const script = String(name ?? "");
107
+ if (!script || script.startsWith("validate:")) return false;
108
+ if (/stack:up|stack-up/.test(script)) return true;
109
+ return script.split(/[:\s]/).some((part) => HEAVY_SCRIPT_PARTS.has(part));
110
+ }
111
+
112
+ const plainName = (word) => basename(String(word ?? "").replace(/^[({]+/, "").replace(/[)}]+$/, ""));
113
+ const firstOperand = (args, valueFlags = new Set()) => {
114
+ for (let i = 0; i < args.length; i += 1) {
115
+ if (args[i] === "--") return args[i + 1] ? { word: args[i + 1], at: i + 1 } : null;
116
+ if (args[i].startsWith("-")) { if (valueFlags.has(args[i])) i += 1; continue; }
117
+ return { word: args[i], at: i };
118
+ }
119
+ return null;
120
+ };
121
+
122
+ const PM_VALUE_FLAGS = {
123
+ npm: new Set(["-w", "--workspace", "--prefix", "-C"]),
124
+ pnpm: new Set(["-C", "--dir", "--filter", "-F", "--filter-prod", "--workspace-concurrency", "--reporter", "--test-pattern", "--changed-files-ignore-pattern"]),
125
+ yarn: new Set(["--cwd"]),
126
+ bun: new Set(["--cwd", "-F", "--filter", "--config", "-c"]),
127
+ };
128
+
129
+ /** What a package manager command runs: a script name, an inner command, or nothing heavy. */
130
+ function packageManager(name, args) {
131
+ const values = PM_VALUE_FLAGS[name];
132
+ let found = firstOperand(args, values);
133
+ if (!found) return false;
134
+ let sub = found.word;
135
+ let rest = args.slice(found.at + 1);
136
+ if (["recursive", "multi", "m"].includes(sub) && name === "pnpm") {
137
+ found = firstOperand(rest, values);
138
+ if (!found) return false;
139
+ sub = found.word; rest = rest.slice(found.at + 1);
140
+ }
141
+ if (name === "yarn" && sub === "workspace") return packageManager(name, rest.slice(1));
142
+ if (name === "yarn" && sub === "workspaces") {
143
+ const run = rest.indexOf("run");
144
+ return run !== -1 && heavyScript(firstOperand(rest.slice(run + 1))?.word);
145
+ }
146
+ if (["run", "run-script", "rum", "urn"].includes(sub)) return heavyScript(firstOperand(rest, values)?.word);
147
+ if (["exec", "dlx", "x"].includes(sub)) return heavyArgv(rest.filter((word, i) => !(i === 0 && word === "--")));
148
+ if (["test", "t", "tst"].includes(sub)) return true;
149
+ if (name === "npm") return false;
150
+ if (name === "bun" && sub === "build") return true;
151
+ if (HELP.has(sub)) return false;
152
+ return heavyScript(sub);
153
+ }
154
+
155
+ /**
156
+ * Whether ARGV (a simple command, its name first) is heavy work: a gate, a
157
+ * full or affected test suite, a typecheck, a build, an image build, a detached
158
+ * stack start, or a push whose hooks run the gates.
159
+ */
160
+ export function heavyArgv(argv) {
161
+ const [first, ...args] = argv;
162
+ const name = plainName(first);
163
+ if (!name) return false;
164
+ // `tsc --version`, `vitest -h`: a question, not a run.
165
+ if (args.length === 1 && HELP.has(args[0])) return false;
166
+ const sub = firstOperand(args)?.word;
167
+ switch (name) {
168
+ case "npm": case "pnpm": case "yarn": case "bun":
169
+ return packageManager(name, args);
170
+ case "npx": case "pnpx": case "bunx": {
171
+ const inner = args.filter((word) => !["-y", "--yes", "--no-install", "--"].includes(word));
172
+ return heavyArgv(inner);
173
+ }
174
+ case "vitest": case "jest": case "mocha": case "ava": case "tsc": case "vue-tsc": case "tsgo": case "turbo": case "nx": case "pytest": case "tox":
175
+ return !args.some((word) => ["--init", "--showConfig"].includes(word));
176
+ case "playwright": return sub === "test";
177
+ case "cypress": return sub === "run";
178
+ case "node": return args.some((word) => word === "--test" || word.startsWith("--test="));
179
+ case "python": case "python3": return args[0] === "-m" && ["pytest", "unittest"].includes(args[1]);
180
+ case "go": return ["test", "build", "vet"].includes(sub);
181
+ case "cargo": return ["test", "build", "check", "clippy", "bench", "nextest"].includes(sub);
182
+ case "gradle": case "gradlew": return args.some((word) => ["build", "test", "check", "assemble"].includes(word));
183
+ case "mvn": case "mvnw": return args.some((word) => ["test", "verify", "package", "install"].includes(word));
184
+ case "make": case "gmake": return args.some((word) => !word.startsWith("-") && !ASSIGNMENT.test(word) && heavyScript(word));
185
+ case "docker": {
186
+ if (sub === "build") return true;
187
+ if (sub === "buildx" || sub === "image") return args.includes("build");
188
+ if (sub === "compose") return composeHeavy(args.slice(args.indexOf("compose") + 1));
189
+ return false;
190
+ }
191
+ case "docker-compose": return composeHeavy(args);
192
+ case "git": return gitPush(args);
193
+ default: return false;
194
+ }
195
+ }
196
+
197
+ // `compose build`, and an `up` that starts a stack and exits (-d, --detach, --wait). A foreground `up` never
198
+ // exits, so like a dev server it never holds a slot (K02-7); a `down` frees memory and never waits.
199
+ function composeHeavy(args) {
200
+ const values = new Set(["-f", "--file", "-p", "--project-name", "--profile", "--env-file", "--project-directory", "--ansi", "--progress", "--parallel"]);
201
+ const found = firstOperand(args, values);
202
+ if (!found) return false;
203
+ if (found.word === "build") return true;
204
+ if (found.word !== "up") return false;
205
+ return args.slice(found.at + 1).some((word) => word === "--detach" || word === "--wait" || word.startsWith("--wait=") || /^-[a-zA-Z]*d[a-zA-Z]*$/.test(word));
206
+ }
207
+
208
+ function gitPush(args) {
209
+ for (let i = 0; i < args.length; i += 1) {
210
+ if (["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env"].includes(args[i])) { i += 1; continue; }
211
+ if (args[i].startsWith("-")) continue;
212
+ return args[i] === "push";
213
+ }
214
+ return false;
215
+ }
216
+
217
+ /** The words of one simple command up to its name, and where the queue prefix goes. */
218
+ function commandStart(segment) {
219
+ let at = 0;
220
+ let insertAt = null;
221
+ while (at < segment.length) {
222
+ const word = segment[at];
223
+ const text = word.text.replace(/^[({]+/, "");
224
+ if (!word.quoted && (ASSIGNMENT.test(text) || KEYWORDS.has(word.text))) { at += 1; continue; }
225
+ if (!word.quoted && WRAPPERS.has(text)) {
226
+ insertAt ??= word.start + (word.text.length - text.length);
227
+ at += 1;
228
+ // A wrapper's own options and operands: env's assignments, timeout's duration, nice's -n value.
229
+ while (at < segment.length && (segment[at].text.startsWith("-") || ASSIGNMENT.test(segment[at].text) || /^\d+(?:\.\d+)?[smhd]?$/.test(segment[at].text))) {
230
+ if (["-n", "-s", "-k", "--signal", "--kill-after", "-u"].includes(segment[at].text)) at += 1;
231
+ at += 1;
232
+ }
233
+ continue;
234
+ }
235
+ const lead = word.text.length - text.length;
236
+ return { at, insertAt: insertAt ?? word.start + lead };
237
+ }
238
+ return null;
239
+ }
240
+
241
+ /** Already queued: `nodii-dev heavy run …`, a heavy-slot.sh copy, or a shell running one. */
242
+ function queued(argv) {
243
+ const name = plainName(argv[0]);
244
+ if (/^nodii-dev(?:\.js)?$/.test(name) || (["node", "bun"].includes(name) && /nodii-dev(?:\.js)?$/.test(argv[1] ?? ""))) {
245
+ const rest = /^nodii-dev(?:\.js)?$/.test(name) ? argv.slice(1) : argv.slice(2);
246
+ return rest.find((word) => !word.startsWith("-")) === "heavy";
247
+ }
248
+ if (name === "heavy-slot.sh") return true;
249
+ return ["bash", "sh", "zsh"].includes(name) && /(?:^|\/)heavy-slot\.sh$/.test(argv.find((word, i) => i > 0 && !word.startsWith("-")) ?? "");
250
+ }
251
+
252
+ // `nodii-dev lane check --gate …` and `nodii-dev receipt write --run …` queue each gate themselves.
253
+ function selfQueued(argv) {
254
+ const name = plainName(argv[0]);
255
+ if (!/^nodii-dev(?:\.js)?$/.test(name)) return false;
256
+ const [command, action] = argv.slice(1).filter((word) => !word.startsWith("-"));
257
+ return (command === "lane" && action === "check") || (command === "receipt" && action === "write");
258
+ }
259
+
260
+ /**
261
+ * The heavy jobs in a shell COMMAND that are not in the queue, and COMMAND
262
+ * rewritten so that each runs under `nodii-dev heavy run --`. Nothing heavy
263
+ * and unqueued: `jobs` is empty.
264
+ */
265
+ export function unqueuedHeavy(command) {
266
+ const text = String(command ?? "");
267
+ const jobs = [];
268
+ for (const segment of shellCommands(text)) {
269
+ const start = commandStart(segment);
270
+ if (!start) continue;
271
+ // A subshell's closing `)` stays on its last word: `(cd x && pnpm test)`.
272
+ const argv = segment.slice(start.at).map((word) => (word.quoted ? word.text : word.text.replace(/\)+$/, "")));
273
+ if (queued(argv) || selfQueued(argv)) continue;
274
+ const name = plainName(argv[0]);
275
+ // A shell running a string runs every command in it.
276
+ const inner = ["bash", "sh", "zsh"].includes(name) ? argv.findIndex((word) => /^-[a-z]*c[a-z]*$/.test(word)) : -1;
277
+ const heavy = inner !== -1 ? unqueuedHeavy(argv[inner + 1] ?? "").jobs.length > 0 : heavyArgv(argv);
278
+ if (!heavy) continue;
279
+ const words = segment.slice(start.at);
280
+ jobs.push({ insertAt: start.insertAt, text: text.slice(start.insertAt, words.at(-1).end).trim() });
281
+ }
282
+ let rewritten = text;
283
+ for (const job of [...jobs].sort((a, b) => b.insertAt - a.insertAt))
284
+ rewritten = `${rewritten.slice(0, job.insertAt)}${HEAVY_PREFIX}${rewritten.slice(job.insertAt)}`;
285
+ return { jobs: jobs.map((job) => job.text), command: rewritten };
286
+ }
287
+
288
+ /** The safety hook's refusal for an unqueued heavy command (null when there is none). */
289
+ export function heavyViolation(command, { original = command } = {}) {
290
+ const found = unqueuedHeavy(command);
291
+ if (!found.jobs.length) return null;
292
+ // When heredoc bodies were left out to judge the command, the rewrite can't be the whole command.
293
+ const instead = command === original ? `Run instead:\n ${found.command}` : `Put \`${HEAVY_PREFIX.trim()}\` in front of each:\n${found.jobs.map((job) => ` ${HEAVY_PREFIX}${job}`).join("\n")}`;
294
+ return {
295
+ code: "SAFETY_HEAVY_UNQUEUED",
296
+ message: [
297
+ `Heavy work runs only through the machine's heavy-slot queue (MW2-51, K02-4; hub-377). Not queued: ${found.jobs.map((job) => `\`${job}\``).join(", ")}.`,
298
+ instead,
299
+ "It waits for a slot (printing its queue place and wait), runs the command, and frees the slot when the command exits; `git push` uses the landing reserve, and a nested call never takes a second slot. A long wait can outlast the tool's timeout: when `nodii-dev heavy status` shows the slots busy, run it in the background.",
300
+ ].join("\n"),
301
+ };
302
+ }
package/dist/nodii-dev.js CHANGED
@@ -13,6 +13,12 @@ routeStdout();
13
13
  const argv = process.argv.slice(2);
14
14
 
15
15
  async function run() {
16
+ // hub-377: bin/nodii-dev execs the heavy-slot queue itself; this is for a CLI started on Node or Bun.
17
+ if (argv[0] === "heavy") {
18
+ const { heavyCommand } = await import("./heavy.js");
19
+ process.exitCode = await heavyCommand(argv.slice(1));
20
+ return;
21
+ }
16
22
  // AGENT-HARNESS-19: this is the executable boundary, so every ordinary CLI
17
23
  // invocation re-grounds without adding hidden requests to library callers.
18
24
  if (shouldReground(argv)) await regroundCurrentLane();
package/dist/review.js CHANGED
@@ -14,6 +14,7 @@ import { pickerPrompt } from "./gather.js";
14
14
  import { componentSetsIn, designCatalogSets } from "./figma-scope.js";
15
15
  import { gitPrivatePath } from "./safety.js";
16
16
  import { GENERATED_PAGE_GLOB, GENERATED_SUFFIX, hasGeneratedPageStamp } from "./surface.js";
17
+ import { heavySlotArgv } from "./heavy.js";
17
18
 
18
19
  const execFileAsync = promisify(execFile);
19
20
  export const CHECKS = ["rules", "figma", "code"];
@@ -64,11 +65,16 @@ export const privateStore = (cwd) => ({
64
65
  },
65
66
  });
66
67
 
67
- /** One gate through the shell in the worktree; its output goes to stderr, its tail is kept. */
68
- export function runGate(command, cwd) {
68
+ /**
69
+ * One gate through the shell in the worktree; its output goes to stderr, its tail is kept.
70
+ * Every gate waits for a machine-wide heavy slot first and holds it while it runs (hub-377,
71
+ * MW2-51); inside a command that already holds one it runs at once (K02-6). The queue never times out.
72
+ */
73
+ export function runGate(command, cwd, { argv = heavySlotArgv } = {}) {
69
74
  return new Promise((resolve) => {
70
75
  let tail = "";
71
- const child = spawn("/bin/sh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
76
+ const [file, args] = argv(["/bin/sh", "-c", command]);
77
+ const child = spawn(file, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
72
78
  const keep = (chunk) => {
73
79
  process.stderr.write(chunk);
74
80
  tail = (tail + chunk).slice(-4000);
@@ -313,19 +319,40 @@ export function reviewerInvocation({ runtime, model, profile, schema, workdir, s
313
319
  };
314
320
  }
315
321
 
316
- /** Spawn with stdin; never throws for the process's own failures, the caller maps them. */
317
- export function spawnReviewer({ command, args, env, cwd, input, timeoutMs }) {
322
+ /**
323
+ * Spawn with stdin; never throws for the process's own failures, the caller maps them.
324
+ * A review loop is heavy work (MW2-51), so the reviewer runs under a machine-wide heavy slot (hub-377).
325
+ * Its timeout starts when the slot is granted, never while it waits in the queue; on timeout the slot
326
+ * holder gets SIGTERM, which stops the reviewer's whole process tree and frees the slot.
327
+ */
328
+ export function spawnReviewer({ command, args, env, cwd, input, timeoutMs }, { argv = heavySlotArgv } = {}) {
318
329
  return new Promise((resolve) => {
319
330
  let stdout = "";
320
331
  let stderr = "";
321
332
  let timedOut = false;
322
- const child = spawn(command, args, { cwd, env: { ...process.env, ...env }, stdio: ["pipe", "pipe", "pipe"] });
323
- const timer = setTimeout(() => { timedOut = true; child.kill("SIGKILL"); }, timeoutMs);
333
+ let timer = null;
334
+ const runEnv = { ...process.env, ...env };
335
+ const [file, fileArgs] = argv([command, ...args]);
336
+ const child = spawn(file, fileArgs, { cwd, env: runEnv, stdio: ["pipe", "pipe", "pipe"] });
337
+ const start = () => {
338
+ timer ??= setTimeout(() => {
339
+ timedOut = true;
340
+ child.kill("SIGTERM");
341
+ setTimeout(() => child.kill("SIGKILL"), 10_000).unref();
342
+ }, timeoutMs);
343
+ };
344
+ // Inside a held slot, or when not queued at all, the reviewer starts at once.
345
+ if (runEnv.NODII_HEAVY_SLOT_HELD === "1" || file === command) start();
324
346
  child.stdout.on("data", (chunk) => { stdout += chunk; });
325
- child.stderr.on("data", (chunk) => { stderr = (stderr + chunk).slice(-4000); });
347
+ child.stderr.on("data", (chunk) => {
348
+ stderr = (stderr + chunk).slice(-4000);
349
+ if (/\[heavy-slot\] got /.test(String(chunk))) start();
350
+ });
326
351
  child.stdin.on("error", () => {});
327
- child.on("error", (error) => { clearTimeout(timer); resolve({ code: null, stdout, stderr, timedOut, missing: error.code === "ENOENT", error: error.message }); });
328
- child.on("close", (code) => { clearTimeout(timer); resolve({ code, stdout, stderr, timedOut, missing: false }); });
352
+ const done = (result) => { if (timer) clearTimeout(timer); resolve(result); };
353
+ child.on("error", (error) => done({ code: null, stdout, stderr, timedOut, missing: error.code === "ENOENT", error: error.message }));
354
+ // Under the queue a missing reviewer is bash's "command not found" (exit 127), not a spawn error.
355
+ child.on("close", (code) => done({ code, stdout, stderr, timedOut, missing: code === 127 && /command not found|No such file or directory/.test(stderr) }));
329
356
  child.stdin.end(input);
330
357
  });
331
358
  }
package/dist/safety.js CHANGED
@@ -6,6 +6,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "nod
6
6
  import { promisify } from "node:util";
7
7
  import { CliError, LANE_CAP_RAISE_PROMPT, configPath, devRequest, encode, readConfig } from "./core.js";
8
8
  import { laneCapReminder } from "./watchdog.js";
9
+ import { heavyViolation } from "./heavy.js";
9
10
 
10
11
  const execFileAsync = promisify(execFile);
11
12
  const ACTIVE = new Set(["queued", "building", "built", "review", "on_main"]);
@@ -844,6 +845,10 @@ export async function safetyPreHook(payload, contextOrResolver = safetyContext,
844
845
  context.devBoundaries = provenLane(context) && createsAnyBranch(command) ? await devBoundaries(context.lane?.key, request) : null;
845
846
  const violation = commandViolations(command, context)[0];
846
847
  if (violation && provenLane(context)) blocked(violation);
848
+ // hub-377 (MW2-51, K02-4): a lane's heavy work goes through the machine's slot queue. A heredoc body
849
+ // read as text is not a command, so it is left out before the command is judged.
850
+ const heavy = provenLane(context) ? heavyViolation(withoutHeredocBodies(command), { original: command }) : null;
851
+ if (heavy) blocked(heavy);
847
852
  if (usesNoVerify(command) && context.role === "coordinator" && context.noVerifyReason)
848
853
  await recordNoVerifyReason(cwd, context.noVerifyReason);
849
854
  const reminder = context.role === "coordinator" ? await laneCapReminder() : null;
package/dist/surface.js CHANGED
@@ -32,7 +32,7 @@ import { CliError, VERSION, devRequest, readConfig } from "./core.js";
32
32
  import { createRenderer } from "./vendor/render-templates.mjs";
33
33
 
34
34
  /** Bumped whenever the emitted code changes shape for the same inputs. */
35
- export const GENERATOR_FORMAT = 8;
35
+ export const GENERATOR_FORMAT = 9;
36
36
  export const TREE_DIR = "docs/figma-ux-ds/figma/surface-trees";
37
37
  export const GENERATED_SUFFIX = ".surface.generated.tsx";
38
38
  /** Where every generated product page lives, as a git glob (NODII-DEV-CLI-77). */
@@ -373,7 +373,17 @@ export function trimTree(entry, { row, version }) {
373
373
  if (Object.keys(exposed).length) out.instance.exposed = exposed;
374
374
  }
375
375
  // A library instance is the template's to draw: only its slots' content is the Surface's.
376
- const children = main.remote ? (node.children ?? []).filter((c) => c.type === "SLOT") : (node.children ?? []);
376
+ // A slot can sit inside the component's own frames (the App Frame's `mainContent` in its
377
+ // Main column, the Data Table Toolbar's `trailing` in its toolbar row), so every slot of
378
+ // this instance is kept, down to (not into) a nested instance or another slot
379
+ // (NODII-DEV-CLI-81).
380
+ const slotsOf = function* (parent) {
381
+ for (const child of parent.children ?? []) {
382
+ if (child.type === "SLOT") yield child;
383
+ else if (child.type !== "INSTANCE") yield* slotsOf(child);
384
+ }
385
+ };
386
+ const children = main.remote ? [...slotsOf(node)] : (node.children ?? []);
377
387
  if (children.length) out.children = children.map((c) => trim(c, box));
378
388
  return out;
379
389
  }
@@ -496,17 +506,20 @@ export function emitSurface(tree, row, ds) {
496
506
  used.add(state);
497
507
  const fn = `${pascal(state)}View`;
498
508
  const note = (path, kind, detail) => unmapped.push({ variant: variant.name, path, kind, detail });
499
- const emitted = emitNode(variant.root, { depth: 2, parent: null, path: variant.name, ds, imports, note, root: true, scopes }) ?? "";
500
- // A refused root is only a comment, and `return ({/* … */})` is an object, not JSX.
501
- const body = emitted.trimStart().startsWith("{/*") ? [" <>", indent(emitted.trim(), 3), " </>"].join("\n") : emitted;
502
- return { state, fn, body };
509
+ const emitted = emitNode(pageBody(variant, row), { depth: 2, parent: null, path: variant.name, ds, imports, note, root: true, scopes, state }) ?? "";
510
+ // A view the generator can't lay out is no page at all: generation fails rather than ship
511
+ // an empty view (NODII-DEV-CLI-81).
512
+ if (emitted.trimStart().startsWith("{/*")) {
513
+ throw new CliError("SURFACE_VIEW_NOT_LAID_OUT", `${row.id}: view ${JSON.stringify(variant.name)} has no auto layout, so it would generate as an empty page; give the variant (or the App Frame's mainContent) auto layout in Figma, publish, and refetch`, 1);
514
+ }
515
+ return { state, fn, body: emitted };
503
516
  });
504
517
  const component = `${pascal(row.id)}Surface`;
505
518
  const stateType = `${component}State`;
506
519
  const propsType = `${component}Props`;
507
520
  resolveScopes(views, scopes);
508
521
  const data = dataProps(views);
509
- const reactTypes = [data.size && "ComponentProps", [...data.values()].some((d) => d.child) && "ReactNode"].filter(Boolean);
522
+ const reactTypes = [data.size && "ComponentProps", [...data.values()].some((d) => /\bReactNode\b/.test(propType(d))) && "ReactNode"].filter(Boolean);
510
523
  const drawn = [...data.values()].some((d) => [...d.attrs.values(), ...[...d.members.values()].flatMap((refs) => [...refs.values()])].some((r) => r.keys));
511
524
  const header = [
512
525
  "// GENERATED by `nodii-dev surface generate` from Code Connect (MW8-17). Do not edit:",
@@ -544,6 +557,34 @@ export function emitSurface(tree, row, ds) {
544
557
  return { code: lines.join("\n"), unmapped, states: views.map((v) => v.state) };
545
558
  }
546
559
 
560
+ /**
561
+ * The DS App Frame (sidebar, navbar and the page in its `mainContent` slot). The
562
+ * frontend's /app shell owns the frame, so a view drawn inside it generates only
563
+ * the page: the slot's content (NODII-DEV-CLI-81).
564
+ */
565
+ export const APP_FRAME = { set: "App Frame", slot: "mainContent" };
566
+
567
+ /**
568
+ * What a view generates as its page: the App Frame's `mainContent` slot when
569
+ * the view draws its page in the App Frame, else the variant itself. An App
570
+ * Frame beside other layers, or one whose tree has no `mainContent` (read before
571
+ * nested slots were kept), is refused, never guessed.
572
+ */
573
+ export function pageBody(variant, row) {
574
+ const root = variant.root;
575
+ const shown = (root.children ?? []).filter((c) => c.visible !== false);
576
+ const frames = shown.filter((c) => c.instance?.remote && c.instance.set === APP_FRAME.set);
577
+ if (!frames.length) return root;
578
+ if (frames.length > 1 || shown.length > 1) {
579
+ throw new CliError("SURFACE_VIEW_NOT_LAID_OUT", `${row.id}: view ${JSON.stringify(variant.name)} draws the App Frame beside ${shown.length - 1} other layer${shown.length === 2 ? "" : "s"}; a page in the App Frame puts all of its content in mainContent`, 1);
580
+ }
581
+ const slot = (frames[0].children ?? []).find((c) => c.type === "SLOT" && c.slot === APP_FRAME.slot);
582
+ if (!slot) {
583
+ throw new CliError("SURFACE_TREE_STALE", `${row.id}: view ${JSON.stringify(variant.name)} draws the App Frame, but its committed tree holds no ${APP_FRAME.slot} slot (it was read before nested slots were kept); refetch it with \`nodii-dev surface generate ${row.componentSetKey} --fetch --write\``, 1);
584
+ }
585
+ return { ...slot, name: root.name };
586
+ }
587
+
547
588
  /**
548
589
  * The free identifiers the templates emit (`onSelect={onSelect}`, a child
549
590
  * `{title}`, `size={file.size}`): the page's data and callbacks, lifted into
@@ -556,12 +597,20 @@ const JS_LITERALS = new Set(["true", "false", "null", "undefined", "this"]);
556
597
  /** Strings blanked to spaces of the same length, so a position still points into `code`. */
557
598
  const maskStrings = (code) => code.replace(/"(?:[^"\\\n]|\\.)*"|`[^`]*`/g, (s) => `"${" ".repeat(s.length - 2)}"`);
558
599
 
600
+ /** A list the generator lifts opens `{rows.map((row) => (`: [{ at, list, param }] in order. */
601
+ const LIST_OPEN = /\{([A-Za-z_][A-Za-z0-9_]*)\.map\(\(([a-z][A-Za-z0-9]*)\) => \(/g;
602
+ const listOpeners = (code) => [...code.matchAll(LIST_OPEN)].map((m) => ({ at: m.index, list: m[1], param: m[2] }));
603
+ /** The list whose item `param` names at position `at`: the nearest opener before it that binds it. */
604
+ const listAt = (openers, at, param) => openers.filter((o) => o.at < at && o.param === param).at(-1)?.list ?? null;
605
+
559
606
  /** Every free identifier a template emits in `code`: [{ at, name }], in the three forms dataProps reads. */
560
607
  function freeIdentifiers(code) {
561
608
  const masked = maskStrings(code);
562
609
  const found = new Map();
610
+ // A lifted list's item (`row` in `rows.map((row) => …)`) is bound, not free.
611
+ const params = new Set(listOpeners(masked).map((o) => o.param));
563
612
  const add = (at, name) => {
564
- if (!JS_LITERALS.has(name)) found.set(at, name);
613
+ if (!JS_LITERALS.has(name) && !params.has(name)) found.set(at, name);
565
614
  };
566
615
  for (const m of masked.matchAll(/([A-Za-z][\w-]*)=\{([a-z][A-Za-z0-9]*)(?:\.[A-Za-z][A-Za-z0-9]*)?\}/g)) add(m.index + m[1].length + 2, m[2]);
567
616
  for (const m of masked.matchAll(/(^|>)(\s*)\{([a-z][A-Za-z0-9]*)\}/gm)) add(m.index + m[1].length + m[2].length + 1, m[3]);
@@ -577,11 +626,75 @@ function freeIdentifiers(code) {
577
626
  function scopeName(node) {
578
627
  const props = node.instance?.props ?? {};
579
628
  const text = [props.label, props.title].find((v) => typeof v === "string" && /[A-Za-z0-9]/.test(v)) ?? node.name ?? "";
580
- const words = text.match(/[A-Za-z0-9]+/g) ?? [];
629
+ return camelName(text);
630
+ }
631
+
632
+ /** Text in camelCase as an identifier (`Subject kind` → `subjectKind`, `2FA` → `field2fa`). */
633
+ function camelName(text) {
634
+ const words = String(text ?? "").match(/[A-Za-z0-9]+/g) ?? [];
581
635
  const name = words.map((w, i) => (i === 0 ? w.toLowerCase() : w[0].toUpperCase() + w.slice(1).toLowerCase())).join("");
582
636
  return /^[a-z]/.test(name) ? name : `field${name.replace(/^./, (c) => c.toUpperCase())}`;
583
637
  }
584
638
 
639
+ /** `name` marked with `scope` (`__s<n>_name`), as scopeIdentifiers marks a template's identifiers. */
640
+ function mark(ctx, scope, name) {
641
+ if (!ctx.scopes) return name;
642
+ if (!ctx.scopes.has(scope)) ctx.scopes.set(scope, ctx.scopes.size);
643
+ return `__s${ctx.scopes.get(scope)}_${name}`;
644
+ }
645
+
646
+ /** What the generator lifted from Figma's sample into the page's props: listed, not counted (NODII-DEV-CLI-82). */
647
+ const LIFTED = "lifted";
648
+
649
+ /**
650
+ * Slots whose content is the page's data, never Figma's sample: the template
651
+ * passes them as a prop, so the generator passes the page's own node through
652
+ * (NODII-DEV-CLI-83: the Data Table Toolbar's `trailing` holds the list's filter controls).
653
+ */
654
+ export const DATA_SLOTS = new Map([["Data Table Toolbar", new Set(["trailing"])]]);
655
+
656
+ const LITERAL = String.raw`(?:"(?:[^"\\\n]|\\.)*"|\{"(?:[^"\\\n]|\\.)*"\})`;
657
+ const literalText = (lit) => JSON.parse(lit.startsWith("{") ? lit.slice(1, -1) : lit);
658
+
659
+ /**
660
+ * A record's values that a template draws from Figma's sample, lifted into
661
+ * the page's props so a real tenant never sees an invented record
662
+ * (NODII-DEV-CLI-82). Each rule is keyed by what the template emits:
663
+ * - a Dialog's or AlertDialog's title and description: `<view state>Title`,
664
+ * `<view state>Description`;
665
+ * - a DescriptionItem's value, named by its label (the label is copy and stays);
666
+ * - a StatusPill's label and tone, named by where it sits.
667
+ * A run of sibling DescriptionLists and a table's body rows are lifted as lists
668
+ * (liftedDescriptionList, tableOf). Real copy (headings, labels, buttons) stays.
669
+ */
670
+ function liftRecordData(code, node, ctx, path) {
671
+ const lifted = [];
672
+ const lift = (scope, name) => (lifted.push(name), mark(ctx, scope, name));
673
+ let out = code.replace(new RegExp(String.raw`<((?:Alert)?Dialog(Title|Description))\b([^>]*)>\{"(?:[^"\\\n]|\\.)*"\}</\1>`, "g"), (_, tag, part, attrs) => `<${tag}${attrs}>{${lift(camelName(ctx.state ?? "dialog"), part.toLowerCase())}}</${tag}>`);
674
+ out = out.replace(/<DescriptionItem\b([^>]*?)\/>/g, (all, attrs) => {
675
+ const value = new RegExp(String.raw`\bvalue=${LITERAL}`).exec(attrs);
676
+ if (!value) return all;
677
+ const label = new RegExp(String.raw`\blabel=(${LITERAL})`).exec(attrs);
678
+ const scope = camelName(label ? literalText(label[1]) : node.name);
679
+ return `<DescriptionItem${attrs.replace(value[0], `value={${lift(scope, "value")}}`)}/>`;
680
+ });
681
+ out = out.replace(/<StatusPill\b([^>]*?)(\/?)>/g, (all, attrs, close) => {
682
+ const label = new RegExp(String.raw`\blabel=${LITERAL}`).exec(attrs);
683
+ if (!label) return all;
684
+ const siblings = (ctx.parent?.children ?? []).filter((c) => c.visible !== false && c.instance?.set === node.instance?.set);
685
+ const scope = camelName(`${ctx.parent?.name ?? "status"} status${siblings.length > 1 ? ` ${siblings.indexOf(node) + 1}` : ""}`);
686
+ const tone = new RegExp(String.raw`\btone=${LITERAL}`).exec(attrs);
687
+ let next = attrs.replace(label[0], `label={${lift(scope, "label")}}`);
688
+ next = tone ? next.replace(tone[0], `tone={${lift(scope, "tone")}}`) : next.replace(`label={`, `tone={${lift(scope, "tone")}} label={`);
689
+ return `<StatusPill${next}${close}>`;
690
+ });
691
+ if (lifted.length) ctx.note(path, LIFTED, `${[...new Set(lifted)].join(", ")} lifted from Figma's sample into the page's props (NODII-DEV-CLI-82)`);
692
+ return out;
693
+ }
694
+
695
+ /** Tabs the page controls: its tab is a prop, and choosing one calls back (NODII-DEV-CLI-83). */
696
+ const CONTROLLED_TABS = (value, onChange) => `<Tabs panelless value={${value}} onValueChange={${onChange}}>`;
697
+
585
698
  /**
586
699
  * Marks each free identifier in one instance's code with its instance's
587
700
  * scope (`__s<n>_date`); resolveScopes later keeps the plain name or scopes it.
@@ -616,17 +729,35 @@ function resolveScopes(views, scopes) {
616
729
 
617
730
  function dataProps(views) {
618
731
  const data = new Map();
619
- const entry = (name) => data.get(name) ?? data.set(name, { attrs: new Map(), child: false, nested: false, members: new Map() }).get(name);
732
+ const entry = (name) => data.get(name) ?? data.set(name, { attrs: new Map(), child: false, nested: false, members: new Map(), list: false }).get(name);
733
+ const member = (d, name) => d.members.get(name) ?? d.members.set(name, new Map()).get(name);
620
734
  for (const view of views) {
621
735
  view.uses = new Set();
622
736
  const body = view.body;
737
+ // A lifted list (`{rows.map((row) => (`): its item's reads are the list's members.
738
+ const openers = listOpeners(body);
739
+ for (const o of openers) {
740
+ entry(o.list).list = true;
741
+ view.uses.add(o.list);
742
+ }
743
+ const itemList = (at, name) => (openers.some((o) => o.param === name) ? listAt(openers, at, name) : null);
623
744
  for (const m of body.matchAll(/([A-Za-z][\w-]*)=\{([a-z][A-Za-z0-9]*)(?:\.([A-Za-z][A-Za-z0-9]*))?\}/g)) {
624
745
  if (JS_LITERALS.has(m[2])) continue;
746
+ const list = m[3] ? itemList(m.index, m[2]) : null;
747
+ // A list item's React key is its own: a string, never a DS prop.
748
+ if (list && m[1] === "key") {
749
+ member(entry(list), m[3]).set("\u0000key", { raw: "string" });
750
+ continue;
751
+ }
625
752
  const start = openingTag(body, m.index);
626
753
  if (start === null) continue;
627
- const d = entry(m[2]);
628
- addDrawn(m[3] ? (d.members.get(m[3]) ?? d.members.set(m[3], new Map()).get(m[3])) : d.attrs, drawnProps(body, start), m[1]);
629
- view.uses.add(m[2]);
754
+ const d = entry(list ?? m[2]);
755
+ addDrawn(m[3] ? member(d, m[3]) : d.attrs, drawnProps(body, start), m[1]);
756
+ if (!list) view.uses.add(m[2]);
757
+ }
758
+ for (const m of body.matchAll(/(^|>)\s*\{([a-z][A-Za-z0-9]*)\.([A-Za-z][A-Za-z0-9]*)\}/gm)) {
759
+ const list = itemList(m.index, m[2]);
760
+ if (list) member(entry(list), m[3]).set("\u0000child", { raw: "ReactNode" });
630
761
  }
631
762
  for (const m of body.matchAll(/(^|>)\s*\{([a-z][A-Za-z0-9]*)\}/gm)) {
632
763
  if (JS_LITERALS.has(m[2])) continue;
@@ -693,7 +824,8 @@ function addDrawn(refs, drawn, attr) {
693
824
  }
694
825
 
695
826
  /** A prop's type: `Drawn<ComponentProps<typeof Tag>, keys, literals>["attr"]`, or the plain props when unnarrowed. */
696
- function drawnRef({ tag, attr, keys, literals }) {
827
+ function drawnRef({ tag, attr, keys, literals, raw }) {
828
+ if (raw) return raw;
697
829
  const props = `ComponentProps<typeof ${tag}>`;
698
830
  if (!keys) return `${props}[${JSON.stringify(attr)}]`;
699
831
  const lits = [...literals.entries()].sort(([a], [b]) => a.localeCompare(b));
@@ -772,7 +904,10 @@ function tagAttributes(body, at) {
772
904
  const propType = (d) => {
773
905
  // A value nested in an object prop has no ComponentProps path the generator can name.
774
906
  const parts = [...[...d.attrs.values()].map(drawnRef), ...(d.child ? ["ReactNode"] : []), ...(d.nested ? ["any"] : [])];
775
- if (d.members.size) parts.push(`{ ${[...d.members.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, refs]) => `${k}: ${[...refs.values()].map(drawnRef).join(" & ")}`).join("; ")} }`);
907
+ const shape = `{ ${[...d.members.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, refs]) => `${k}: ${[...refs.values()].map(drawnRef).join(" & ")}`).join("; ")} }`;
908
+ // A lifted list is an array of its items (NODII-DEV-CLI-82).
909
+ if (d.list) parts.push(`Array<${shape}>`);
910
+ else if (d.members.size) parts.push(shape);
776
911
  return parts.join(" & ");
777
912
  };
778
913
 
@@ -867,7 +1002,7 @@ function colour(prefix, paint, scope, ds, report) {
867
1002
  const BOUND_TEXT = "bound-text";
868
1003
  /** What the generator assembled from Code Connect parts (MW8-17.3): listed, not counted. */
869
1004
  const ASSEMBLED = "assembled";
870
- const LISTED_ONLY = new Set([BOUND_TEXT, ASSEMBLED]);
1005
+ const LISTED_ONLY = new Set([BOUND_TEXT, ASSEMBLED, LIFTED]);
871
1006
  const counted = (unmapped) => unmapped.filter((u) => !LISTED_ONLY.has(u.kind));
872
1007
 
873
1008
  /** DS parts whose text should be a component property, not slot content (the Q-211 Lock-Change). */
@@ -901,6 +1036,10 @@ function emitNode(node, ctx) {
901
1036
  .map(([layer, e]) => [layer, { nodeId: ds.byKey.get(e.key), values: valuesOf(e.props) }]),
902
1037
  );
903
1038
  const slotContent = (prop) => {
1039
+ if (DATA_SLOTS.get(node.instance.set)?.has(prop)) {
1040
+ note(`${path} › ${prop}`, LIFTED, `slot ${prop} of ${node.instance.set} is the page's own content, passed through as a prop (NODII-DEV-CLI-83)`);
1041
+ return `<>{${prop}}</>`;
1042
+ }
904
1043
  const slotNode = (node.children ?? []).find((c) => c.type === "SLOT" && c.slot === prop);
905
1044
  if (slotNode && !slotNode.layout && (slotNode.children ?? []).filter((c) => c.visible !== false && !c.absolute).length > 1) {
906
1045
  note(`${path} › ${prop}`, "layout", `slot ${prop} has no auto layout`);
@@ -919,7 +1058,12 @@ function emitNode(node, ctx) {
919
1058
  }
920
1059
  ctx.imports.push(...rendered.imports);
921
1060
  const sizing = ctx.bare ? [] : sizeClasses(node, parent, false);
922
- const code = ctx.scopes ? scopeIdentifiers(rendered.code.trim(), scopeName(node), ctx.scopes) : rendered.code.trim();
1061
+ // A data slot passed straight to a prop is that prop (`trailing={<>{trailing}</>}` → `trailing={trailing}`).
1062
+ let own = rendered.code.trim().replace(/=\{<>\{([a-z][A-Za-z0-9]*)\}<\/>\}/g, "={$1}");
1063
+ // A tab strip the page controls (tabOf reads the template's own strip first, to gather a run).
1064
+ if (!ctx.tabProbe) own = own.replace(/<Tabs panelless(?: defaultValue="[^"]*")?>/g, CONTROLLED_TABS("tab", "onTabChange"));
1065
+ own = liftRecordData(own, node, ctx, path);
1066
+ const code = ctx.scopes ? scopeIdentifiers(own, scopeName(node), ctx.scopes) : own;
923
1067
  // A Table part is valid only inside the DS Table. One the generator could not assemble
924
1068
  // into a Table stays reported, never passed off as mapped (MW8-17.3).
925
1069
  const tag = /^<([A-Za-z]+)/.exec(code)?.[1];
@@ -988,15 +1132,22 @@ function emitNode(node, ctx) {
988
1132
  function emitChildren(children, emitOne, ctx) {
989
1133
  const out = [];
990
1134
  let run = [];
1135
+ let runKind = null;
991
1136
  const flush = () => {
992
- if (run.length >= 2) out.push(tabStrip(run, ctx));
1137
+ if (run.length >= 2 && runKind === "tab") out.push(tabStrip(run, ctx));
1138
+ else if (run.length >= 2) out.push(descriptionRun(run, ctx));
993
1139
  else out.push(...run.map(emitOne).filter((x) => x !== null));
994
1140
  run = [];
1141
+ runKind = null;
995
1142
  };
996
1143
  for (const c of children) {
997
1144
  if (c.visible === false) continue;
998
- if (tabOf(c, ctx)) run.push(c);
999
- else {
1145
+ const kind = tabOf(c, ctx) ? "tab" : descriptionOf(c, ctx) ? `dl${descriptionOf(c, ctx).open}` : null;
1146
+ if (kind && kind !== runKind) flush();
1147
+ if (kind) {
1148
+ run.push(c);
1149
+ runKind = kind;
1150
+ } else {
1000
1151
  flush();
1001
1152
  const code = emitOne(c);
1002
1153
  if (code !== null) out.push(code);
@@ -1006,13 +1157,48 @@ function emitChildren(children, emitOne, ctx) {
1006
1157
  return out;
1007
1158
  }
1008
1159
 
1160
+ /** What the DescriptionList template emits for one field: one DescriptionItem in its list. */
1161
+ const ONE_DESCRIPTION = /^<DescriptionList((?:\s[^>]*)?)>\n\s*<DescriptionItem\b[^>]*?\/>\n\s*<\/DescriptionList>$/;
1162
+
1163
+ /** A DS instance whose template emits a one-field DescriptionList: { open, imports } (its list's attributes), else null. */
1164
+ function descriptionOf(node, ctx) {
1165
+ if (!node.instance?.remote || node.visible === false) return null;
1166
+ const imports = [];
1167
+ const code = emitNode(node, { ...ctx, depth: 0, parent: null, bare: true, inTable: false, tabProbe: true, scopes: null, imports, note: () => {} });
1168
+ const m = ONE_DESCRIPTION.exec(code?.trim() ?? "");
1169
+ return m ? { open: m[1], imports } : null;
1170
+ }
1171
+
1172
+ /**
1173
+ * A run of sibling one-field DescriptionLists is a record's fields, or a list
1174
+ * (a cart's lines): either way the page's data, never Figma's sample. It is one
1175
+ * DescriptionList over an `items` prop of { label, value } (NODII-DEV-CLI-82).
1176
+ */
1177
+ function descriptionRun(run, ctx) {
1178
+ const { depth, path } = ctx;
1179
+ const { open, imports } = descriptionOf(run[0], ctx);
1180
+ ctx.imports.push(...imports);
1181
+ const items = mark(ctx, scopeName(ctx.parent ?? { name: "items" }), "items");
1182
+ ctx.note(path, LIFTED, `${run.length} sibling Description Lists lifted as one list of items (NODII-DEV-CLI-82)`);
1183
+ const list = [
1184
+ `<DescriptionList${open}>`,
1185
+ ` {${items}.map((item) => (`,
1186
+ " <DescriptionItem key={item.label} label={item.label} value={item.value} />",
1187
+ " ))}",
1188
+ "</DescriptionList>",
1189
+ ];
1190
+ const sizing = sizeClasses(run[0], ctx.parent, false);
1191
+ if (!sizing.length) return indent(list.join("\n"), depth);
1192
+ return [indent(`<div className="${cls(["flex", "flex-col", ...sizing])}">`, depth), indent(list.join("\n"), depth + 1), indent("</div>", depth)].join("\n");
1193
+ }
1194
+
1009
1195
  /** The single-tab strip the Tab template emits: Tabs › TabsList › one TabsTrigger. */
1010
1196
  const TAB_STRIP = /^<Tabs panelless( defaultValue="tab")?>\n\s*<TabsList>\n(\s*)(<TabsTrigger\b[\s\S]*?<\/TabsTrigger>)\n\s*<\/TabsList>\n\s*<\/Tabs>$/;
1011
1197
 
1012
1198
  /** A DS instance whose template emits one tab: { selected, trigger } (trigger dedented to column 0), else null. */
1013
1199
  function tabOf(node, ctx, { imports = [], note = () => {} } = {}) {
1014
1200
  if (!node.instance?.remote || node.visible === false) return null;
1015
- const code = emitNode(node, { ...ctx, depth: 0, parent: null, bare: true, inTable: false, imports, note });
1201
+ const code = emitNode(node, { ...ctx, depth: 0, parent: null, bare: true, inTable: false, tabProbe: true, imports, note });
1016
1202
  const m = TAB_STRIP.exec(code?.trim() ?? "");
1017
1203
  if (!m || (m[3].match(/<TabsTrigger\b/g) ?? []).length !== 1) return null;
1018
1204
  const pad = m[2].length;
@@ -1023,11 +1209,11 @@ function tabOf(node, ctx, { imports = [], note = () => {} } = {}) {
1023
1209
  function tabStrip(run, ctx) {
1024
1210
  const { depth, path } = ctx;
1025
1211
  const tabs = run.map((c) => tabOf(c, { ...ctx, path: `${path} › ${c.name}` }, { imports: ctx.imports, note: ctx.note }));
1026
- const selected = tabs.findIndex((t) => t.selected);
1027
- ctx.note(path, ASSEMBLED, `${run.length} sibling Tabs gathered into one DS Tab strip (MW8-17.3)`);
1212
+ ctx.note(path, ASSEMBLED, `${run.length} sibling Tabs gathered into one DS Tab strip (MW8-17.3)`);
1028
1213
  const triggers = tabs.map((t, i) => indent(t.trigger.replace(/(<TabsTrigger\b[\s\S]*?)\bvalue="tab"/, `$1value="tab-${i + 1}"`), 2));
1029
1214
  return [
1030
- indent(`<Tabs panelless${selected >= 0 ? ` defaultValue="tab-${selected + 1}"` : ""}>`, depth),
1215
+ // The page controls which tab is shown (NODII-DEV-CLI-83); Figma's selected tab is only the drawn one.
1216
+ indent(CONTROLLED_TABS(mark(ctx, scopeName(ctx.parent ?? { name: "tabs" }), "tab"), mark(ctx, scopeName(ctx.parent ?? { name: "tabs" }), "onTabChange")), depth),
1031
1217
  indent(" <TabsList>", depth),
1032
1218
  ...triggers.map((t) => indent(t, depth)),
1033
1219
  indent(" </TabsList>", depth),
@@ -1070,13 +1256,32 @@ export function columnWidth(cell) {
1070
1256
  const widthAttr = (w) => (w === null ? "" : typeof w === "number" ? ` width={${w}}` : ` width="${w}"`);
1071
1257
  /** Add `width` to a TableHead/TableCell's opening tag, unless its template already declares one. */
1072
1258
  function withWidth(code, w) {
1073
- if (w === null || !code) return code;
1259
+ if (!code) return code;
1260
+ // A cell whose sizing says no width takes none: the placeholder is never left for the page to fill.
1261
+ if (w === null) return code.replace(/^(\s*<Table[A-Za-z]*\b[^>]*?)\swidth=\{(?:__s\d+_)?width\}/, "$1");
1074
1262
  const m = /^(\s*<Table[A-Za-z]*)([\s>/])/.exec(code);
1075
1263
  if (!m) return code;
1076
1264
  const tagEnd = code.indexOf(">", m[0].length - 1);
1077
- if (/\bwidth=/.test(code.slice(0, tagEnd === -1 ? code.length : tagEnd))) return code;
1265
+ const open = code.slice(0, tagEnd === -1 ? code.length : tagEnd);
1266
+ // The Table templates pass the column's width as the frame-sized placeholder `width={width}`:
1267
+ // it is bound here, per placed cell, from the cell's own sizing (DESIGN-SYSTEM-252, NODII-DEV-CLI-79).
1268
+ if (/\bwidth=\{(?:__s\d+_)?width\}/.test(open)) return code.replace(/\swidth=\{(?:__s\d+_)?width\}/, widthAttr(w));
1269
+ if (/\bwidth=/.test(open)) return code;
1078
1270
  return code.replace(m[1], `${m[1]}${widthAttr(w)}`);
1079
1271
  }
1272
+ /** Where a JSX opening tag that starts `code` ends (its `>`), stepping over braces and strings. */
1273
+ function openTagEnd(code) {
1274
+ let depth = 0;
1275
+ for (let i = 0; i < code.length; i++) {
1276
+ const c = code[i];
1277
+ if (c === '"' || c === "'" || c === "`") {
1278
+ for (i++; i < code.length && code[i] !== c; i++) if (code[i] === "\\") i++;
1279
+ } else if (c === "{") depth++;
1280
+ else if (c === "}") depth--;
1281
+ else if (c === ">" && depth === 0) return i;
1282
+ }
1283
+ return code.length - 1;
1284
+ }
1080
1285
  function tableOf(node, ctx) {
1081
1286
  const shown = (node.children ?? []).filter((c) => c.visible !== false);
1082
1287
  // What follows the rows (a table's Empty State, bare or in its own frame) follows the Table:
@@ -1144,6 +1349,7 @@ function tableOf(node, ctx) {
1144
1349
  if (p.kind) continue;
1145
1350
  if (p.cells.length !== columns) return null;
1146
1351
  p.kind = "body";
1352
+ p.framesOnly = true;
1147
1353
  }
1148
1354
  const module = imports.map((s) => /\{[^}]*\bTable[A-Za-z]*(Cell|Head)\b[^}]*\}\s+from\s+["']([^"']+)["']/.exec(s)?.[2]).find(Boolean);
1149
1355
  if (!module) return null;
@@ -1179,7 +1385,7 @@ function tableOf(node, ctx) {
1179
1385
  ASSEMBLED,
1180
1386
  `${rows.length} row${rows.length === 1 ? "" : "s"} of Table parts${plain ? ` (${plain} of them frame cells only)` : ""} assembled into one DS Table${skeleton ? ` (its ${loadingRows.length} row${loadingRows.length === 1 ? "" : "s"} of loading cells as one ${SKELETON_ROWS})` : ""} (MW8-17.3)`,
1181
1387
  );
1182
- ctx.imports.push(...imports, `import { Table, TableBody, TableHeader, TableRow${skeleton ? `, ${SKELETON_ROWS}` : ""} } from "${module}";`);
1388
+ ctx.imports.push(...imports, `import { Table, TableBody, TableCell, TableHeader, TableRow${skeleton ? `, ${SKELETON_ROWS}` : ""} } from "${module}";`);
1183
1389
  const { depth } = ctx;
1184
1390
  // A cell the generator wraps has no template to say its density, so it takes the one
1185
1391
  // its row's template cells declare, or the table's: a row is one height in Figma.
@@ -1220,6 +1426,45 @@ function tableOf(node, ctx) {
1220
1426
  const cellProps = props.some((p) => p.length) ? ` cellProps={[${props.map((p) => (p.length ? `{ ${p.join(", ")} }` : "{}")).join(", ")}]}` : "";
1221
1427
  return indent(`<${SKELETON_ROWS} columns={${columnCount}} rows={${loadingRows.length}}${cellProps} />`, depth + 2);
1222
1428
  };
1429
+ // The body's rows are the page's records, never Figma's sample: one row, drawn as the
1430
+ // first body row draws its cells, mapped over a `rows` prop, each column a ReactNode named
1431
+ // by its header (NODII-DEV-CLI-82). Rows that differ in their cells, or a row the generator
1432
+ // couldn't recognise, stay as drawn.
1433
+ const dataRows = parsed.filter((p) => p.kind === "body");
1434
+ const liftable = !skeleton && dataRows.length > 0 && dataRows.every((p) => !p.unrecognised && !p.framesOnly && p.cells.length === dataRows[0].cells.length) && (!headRow || headRow.cells.length === dataRows[0].cells.length);
1435
+ const liftedRows = () => {
1436
+ const keys = [];
1437
+ const first = dataRows[0];
1438
+ first.cells.forEach((_, i) => {
1439
+ const head = headRow?.cells[i];
1440
+ const text = head?.code ? (/\{"((?:[^"\\\n]|\\.)*)"\}/.exec(head.code)?.[1] ?? /\blabel="([^"]*)"/.exec(head.code)?.[1] ?? "") : "";
1441
+ let key = /[A-Za-z0-9]/.test(text) ? camelName(text) : `column${i + 1}`;
1442
+ while (keys.includes(key) || key === "id") key = `${key}${i + 1}`;
1443
+ keys.push(key);
1444
+ });
1445
+ const rowsName = mark(ctx, scopeName(node), "rows");
1446
+ ctx.note(ctx.path, LIFTED, `${dataRows.length} body row${dataRows.length === 1 ? "" : "s"} lifted as data: rows of { id, ${keys.join(", ")} } (NODII-DEV-CLI-82)`);
1447
+ const cells = first.cells.map((c, i) => {
1448
+ const w = columnWidth(c.cell);
1449
+ let open = `<TableCell${wrapperAttrs(w, first.row)}>`;
1450
+ let close = "</TableCell>";
1451
+ if (c.code && !c.held) {
1452
+ const own = withWidth(emitNode(c.cell, { ...ctx, depth: 0, parent: null, path: `${ctx.path} › ${first.row.name}`, root: false, bare: true, inTable: true, scopes: null, note: () => {} }), w).trim();
1453
+ const end = openTagEnd(own);
1454
+ const tag = /^<([A-Za-z]+)/.exec(own)[1];
1455
+ open = own.slice(0, end + 1).replace(/\s*\/>$/, ">");
1456
+ close = `</${tag}>`;
1457
+ }
1458
+ return indent(`${open}{row.${keys[i]}}${close}`, depth + 4);
1459
+ });
1460
+ return [
1461
+ indent(`{${rowsName}.map((row) => (`, depth + 2),
1462
+ indent("<TableRow key={row.id}>", depth + 3),
1463
+ ...cells,
1464
+ indent("</TableRow>", depth + 3),
1465
+ indent("))}", depth + 2),
1466
+ ];
1467
+ };
1223
1468
  const section = (kind, tag) => {
1224
1469
  const list = parsed.filter((p) => p.kind === kind);
1225
1470
  if (!list.length) return [];
@@ -1227,6 +1472,8 @@ function tableOf(node, ctx) {
1227
1472
  indent(`<${tag}>`, depth + 1),
1228
1473
  ...(kind === "body" && skeleton
1229
1474
  ? [skeletonRows()]
1475
+ : kind === "body" && liftable
1476
+ ? liftedRows()
1230
1477
  : list.flatMap((p) => (p.unrecognised ? [indent(comment(p.unrecognised), depth + 2)] : [indent("<TableRow>", depth + 2), ...p.cells.map((c) => cellCode(c, p.row, depth + 3)), indent("</TableRow>", depth + 2)]))),
1231
1478
  indent(`</${tag}>`, depth + 1),
1232
1479
  ];
@@ -1265,7 +1512,7 @@ export function unmappedMarkdown(files) {
1265
1512
  const lines = [
1266
1513
  "# Surface layers with no Code Connect mapping (U08-14)",
1267
1514
  "",
1268
- "Generated by `nodii-dev surface generate --report`. Kinds: `instance` (a library instance the generator cannot emit through a template), `text` (text missing a DS text style or colour role, or text in a part that should own it as a property), `frame` (a frame that paints its own fill, stroke, radius or effect: only its layout is generated), `table` (a Table part outside any table the generator recognises), `layout` (a frame or slot with no auto layout), `shape` (a rectangle, ellipse or vector: marked, not drawn), `token` (a text colour that matches no colour v2 role: left out), `bound-text` (text bound to a DS text style and colour role, with no Code Connect mapping: listed, not counted against a Surface being clean), `assembled` (rows of Table parts assembled into one DS Table, or sibling Tabs gathered into one Tab strip, MW8-17.3: listed, not counted).",
1515
+ "Generated by `nodii-dev surface generate --report`. Kinds: `instance` (a library instance the generator cannot emit through a template), `text` (text missing a DS text style or colour role, or text in a part that should own it as a property), `frame` (a frame that paints its own fill, stroke, radius or effect: only its layout is generated), `table` (a Table part outside any table the generator recognises), `layout` (a frame or slot with no auto layout), `shape` (a rectangle, ellipse or vector: marked, not drawn), `token` (a text colour that matches no colour v2 role: left out), `bound-text` (text bound to a DS text style and colour role, with no Code Connect mapping: listed, not counted against a Surface being clean), `assembled` (rows of Table parts assembled into one DS Table, or sibling Tabs gathered into one Tab strip, MW8-17.3: listed, not counted), `lifted` (a record's values, a table's body rows, a run of Description Lists or a data slot taken out of Figma's sample into the page's props, NODII-DEV-CLI-82/-83: listed, not counted).",
1269
1516
  "",
1270
1517
  ];
1271
1518
  for (const [fileKey, file] of Object.entries(files)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.125",
3
+ "version": "0.6.126",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {