@nodii/dev 0.6.129 → 0.6.131

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,20 +89,46 @@ 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
+ ## Tests: only what changed (hub-401)
93
+
94
+ A lane, a pre-push hook and per-push CI run only the tests the change reaches. The full suite runs in the twice-daily scheduled CI and the release gate.
95
+
96
+ ```sh
97
+ nodii-dev test affected # what changed against origin/main, the affected tests, and the command per package
98
+ nodii-dev test affected --run # run them, in a light slot when at most 20 test files are affected
99
+ nodii-dev lane check KEY --gate 'pnpm typecheck' --gate 'pnpm lint' --gate 'nodii-dev test affected --run'
100
+ ```
101
+
102
+ - The change is the worktree against its merge base with `--base` (default `origin/main`), with uncommitted, untracked and deleted files.
103
+ - The graph is read from source: static and dynamic imports, re-exports, `require`, `vi.mock`, `jest.mock` and `mock.module`, `new URL("./x", import.meta.url)`, the nearest tsconfig's `paths`, and workspace packages by name. A data file (SQL, JSON, a template) reaches the code that names it.
104
+ - It fails closed. A manifest, lockfile, tsconfig, test or build config, a data file no source names, or a changed source file no test reaches selects the full suite (`full` lists why). Docs, `.github/` and the policy file select nothing.
105
+ - Each package runs its tests with its own `test` script's runner and flags, and the selected files replace the script's paths. A script that is not one runner call (`bun run gate && bun test`) runs whole.
106
+ - `lane check` refuses a full-suite gate (`GATE_FULL_SUITE`) unless `--full-suite` is passed.
107
+
92
108
  ## Heavy work: one machine-wide slot queue
93
109
 
94
110
  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
111
 
96
112
  ```sh
97
113
  nodii-dev heavy run -- pnpm -r typecheck
114
+ nodii-dev heavy run --size light -- bun test tests/unit/money.test.ts
98
115
  nodii-dev heavy run -- git push -u origin HEAD
99
116
  nodii-dev heavy status
100
117
  ```
101
118
 
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.
119
+ - Slots are sized (v27, hub-401). A light job takes one of `LIGHT_SLOTS` light slots beside the heavy ones, under `LIGHT_MIN_AVAIL_GB` (default: the heavy floor) and with no stagger. The machine's measured limits file sizes the pool (K02-4): without `LIGHT_SLOTS` there is no light pool and every job takes a heavy slot. A light job is a test run naming at most `LIGHT_MAX_TEST_FILES` (20) test files (`bun test a.test.ts`, `vitest run x.spec.ts`, optionally piped to tail, head, grep or tee), as `test affected --run` sends for a small change. `--size light` or `HEAVY_SIZE=light` on anything else is refused and takes a heavy slot. Everything else, and every landing, takes a heavy slot. The floor's one-job-alone exception counts both pools, so a light job beside running heavy jobs waits for its floor. Light locks live in `/tmp/nodii-heavy-slots/light`, which older copies never touch.
120
+ - The queue is `heavy-slot` v27, 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.
121
+ - Limits come from `~/.config/nodii-resources/limits.env`, re-read on every admission: `HEAVY_SLOTS`, `HEAVY_MIN_AVAIL_GB`, `HEAVY_STAGGER_SEC`, `HEAVY_LANDING_RESERVE`, `HEAVY_RECLAIM_MIN`, `LIGHT_SLOTS`, `LIGHT_MIN_AVAIL_GB` and `LIGHT_MAX_TEST_FILES`. 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
122
  - 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
123
  - 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.
124
+ - **No nested queuing (NODII-DEV-CLI-86).** A job that holds a slot sees `NODII_HEAVY_SLOT=<n>` (`light/<n>` for a light slot). Heavy work inside it (another `heavy run`, `lane check`'s gates, a reviewer) runs in that same slot and never queues for a second one. A marker naming a slot that is no longer held queues for a slot of its own.
125
+ - **Orphaned slots are reclaimed (NODII-DEV-CLI-86).** A slot records its lane, the agent session that took it, the job's worktree and its process group. A slot's holder (the `heavy run` that started the job) checks its own slot once a minute, and reclaims it only when all of these hold:
126
+ - it has been held at least `HEAVY_RECLAIM_MIN` minutes (default 10; 0 turns the reclaim off);
127
+ - Dev reports its lane down (`nodii-dev heavy lane-state <key>`: liveness `orphan` or `ended`, or status `stopped` or `non_issue`);
128
+ - the agent session that took it is gone;
129
+ - no `claude` or `codex` process works in the job's worktree.
130
+
131
+ It then stops its own job's process tree and logs the reclaim (slot, lane, time held and why) to `/tmp/nodii-heavy-slots/reclaim.log`. `heavy status` shows each slot's lane, marks a reclaim candidate and lists the last reclaims. No session ever signals another session's processes (MW2-49): a waiter only waits. A slot taken outside a lane, or held by a pre-v26 copy, is never reclaimed this way; a check that can't tell (Dev unreachable, no `lsof`) keeps the slot.
106
132
  - 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
133
  - `[TOOL GAP hub-86]` MW5-19 places this helper as the `heavy-slot` util. It ships here until the util pipeline exists.
108
134
 
package/dist/cli.js CHANGED
@@ -24,7 +24,8 @@ import {
24
24
  import { FIGMA_HOOK_DENIALS, heartbeatFromHook, postHook, postHookFailure, preHook, settingsSnippet, workflowSuggestion } from "./hooks.js";
25
25
  import { setupCommand } from "./setup.js";
26
26
  import { harnessCommand } from "./harness.js";
27
- import { repoCommand } from "./repo-policy.js";
27
+ import { readPolicy, repoCommand } from "./repo-policy.js";
28
+ import { testCommand } from "./impact.js";
28
29
  import { hookRuntime, recordHookFire, safetyContext, safetyPostHook, safetyPreHook } from "./safety.js";
29
30
  import { isLaneRunSession, isReviewSession } from "./review-session.js";
30
31
  import { SUBMIT_CHECK_FLAGS, changedPaths, nudgeCandidate, nudgePre, nudgeStop, recordGathered, recordGuidelineRead, recordSubmitChecks, steerAct, stewardSteerNudges, surfaceGenPre } from "./nudges.js";
@@ -368,13 +369,28 @@ Usage: nodii-dev <command> [options] [--json]
368
369
  [--run CMD ...] [--from-file DETAILS.json] [--out FILE]
369
370
  # one signed receipt (STD-22); --run gates stop at the first failure and exit 1
370
371
  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
+ test affected [--base REF] [--max-light N] [--run]
373
+ # hub-401: only the tests the change reaches (MW2-20): the import
374
+ # graph from the files changed against origin/main (uncommitted and
375
+ # untracked included) back to the test files that import them, run with
376
+ # each package's own runner. A manifest, lockfile, test or build config, or
377
+ # a data file nothing names selects the full suite. --run runs them in a
378
+ # light slot (where the machine has a light pool) when at most --max-light (20) files are affected, else heavy
379
+ heavy run [--size light|heavy] -- <command...>
380
+ # run heavy work (tests, typecheck, build, gate, git push, image build,
372
381
  # detached stack start) under one machine-wide slot (MW2-51): waits in FIFO
373
382
  # order, printing its place and wait, while slots are full, memory is under
374
383
  # 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
384
+ # nodii-resources/limits.env. A push uses the landing reserve. The job sees
385
+ # NODII_HEAVY_SLOT=<n>; heavy work inside it (a heavy run, lane check's gates)
386
+ # runs in that slot and never queues for a second (K02-6). A slot held
387
+ # HEAVY_RECLAIM_MIN (10) whose lane is down in Dev and whose agent is gone is
388
+ # reclaimed and logged. A lane's safety hook refuses unqueued heavy work.
389
+ # A test run naming at most LIGHT_MAX_TEST_FILES test files takes a light
390
+ # slot (many in parallel, low memory floor, no stagger); --size light asks for one
391
+ heavy status # limits, available memory, the slots held (with lane and reclaim candidates)
392
+ # and the queues
393
+ heavy lane-state <lane-key> # up|down|unknown: Dev's view of a slot's lane, as the reclaim reads it
378
394
  sync pending [--discard FILE --reason TEXT]
379
395
  # send the lane records queued while Dev was down (MW1-64); --discard drops
380
396
  # one Dev refuses for good, with a note on its lane
@@ -947,6 +963,7 @@ export async function main(argv = process.argv.slice(2)) {
947
963
  return emitCommand(await harnessCommand(action, f, { installManaged: installManagedLatest }));
948
964
  }
949
965
  if (command === "repo" && ["policy", "lint"].includes(action)) return emitCommand(await repoCommand(action, rest, f));
966
+ if (command === "test") return emitCommand(await testCommand(action, rest, f, { readPolicy }));
950
967
  if (command === "watchdog") {
951
968
  if (rest.length) throw new CliError("USAGE", `watchdog ${action ?? ""} takes no arguments, got: ${rest.join(" ")}.`, 2);
952
969
  return emitCommand(await watchdogCommand(action, f));
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.129";
7
+ export const VERSION = "0.6.131";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
package/dist/flags.js CHANGED
@@ -55,6 +55,7 @@ export const COMMAND_FLAGS = {
55
55
  "lane land": [],
56
56
  "lane verify": ["dev-check", "checks"],
57
57
  "repo policy": ["root"],
58
+ "test affected": ["base", "max-light", "run"],
58
59
  "repo lint": ["root"],
59
60
  "lane review": ["file", "not-required", "decision", "question", "quote", "at", "treat", "ruling"],
60
61
  "lane non-issue": ["reason", "reroute", "evidence", "commits", "branch"],
@@ -1,11 +1,18 @@
1
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,
2
+ # heavy-slot (v27, shipped with @nodii/dev): run a memory-heavy job (typecheck, build, full or affected test suite,
3
3
  # a gate, `git push` and its pre-push hooks, an image build, a detached stack start) only when a machine-wide slot
4
4
  # is free AND enough REAL memory is available. Every session and lane on this machine shares one queue (MW2-51, K02-4).
5
5
  #
6
- # nodii-dev heavy run -- <command...> wait for a slot, run the command, release the slot when it exits
6
+ # nodii-dev heavy run [--size light|heavy] -- <command...>
7
+ # wait for a slot of that size, run the command, release the slot when it exits
7
8
  # nodii-dev heavy status the limits, available memory, the slots held and the queue
8
9
  #
10
+ # v27 (13 Nov, hub-401): slots are sized to the job. A LIGHT job (a test run that names at most
11
+ # LIGHT_MAX_TEST_FILES test files, or anything run with --size light / HEAVY_SIZE=light, as
12
+ # `nodii-dev test affected --run` does for a small change) takes a light slot: many run in parallel, under a low
13
+ # memory floor and with no stagger. Everything else takes a heavy slot, as before. Light slots are lock dirs under
14
+ # $D/light/<n> with their own queue $D/lq, so a v24/v25 copy still running sees only the heavy slots it knows.
15
+ #
9
16
  # [TOOL GAP hub-86] MW5-19 places this helper as the `heavy-slot` util (MW5-26: the first util to publish).
10
17
  # Until the util pipeline (`nodii-dev util run`, ~/.nodii/utils) exists, @nodii/dev ships it and its hooks enforce it
11
18
  # (hub-377). It carries heavy-slot.sh v23 (nodii-hr-service docs/figma-ux-drive/dev/heavy-slot.sh) and uses
@@ -18,9 +25,19 @@
18
25
  # `memory_pressure`'s "free percentage" is NOT used: it read 84% while far less was available.
19
26
  # HEAVY_STAGGER_SEC=60 minimum gap between two admissions, so a job's memory growth shows before the next one starts
20
27
  # 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).
28
+ # HEAVY_RECLAIM_MIN=10 reclaim a slot held at least this long whose lane is down and whose agent is gone (0: never)
29
+ # LIGHT_SLOTS= concurrent light jobs machine-wide (v27); they do not count against HEAVY_SLOTS. Unset or
30
+ # 0: no light pool, every job takes a heavy slot. Only the machine's measured limits set it (K02-4).
31
+ # LIGHT_MIN_AVAIL_GB= admit a light job only when available memory >= this (v27); unset: HEAVY_MIN_AVAIL_GB
32
+ # LIGHT_MAX_TEST_FILES=20 a test run naming at most this many test files is light without --size (v27)
33
+ # Environment: NODII_RESOURCE_LIMITS (the limits file), HEAVY_SLOT_DIR (the lock directory), HEAVY_SLOT_POLL_SEC (10),
34
+ # HEAVY_LANE_PROBE (a command printing `up|down|unknown <why>` for a lane key; default `nodii-dev heavy lane-state`),
35
+ # HEAVY_RECLAIM_POLL_SEC (60: how often a holder checks whether its own slot is an orphan).
22
36
  #
23
37
  # Locks are mkdir dirs under /tmp/nodii-heavy-slots/<n> holding the owner pid; stale locks (dead pid) are reclaimed.
38
+ # v26 (NODII-DEV-CLI-86): a slot also records when it was granted (since), the lane (lane), the agent session that
39
+ # asked (session, session-start), the job's worktree (worktree) and the job's process group (job). The job sees
40
+ # NODII_HEAVY_SLOT=<n>; a heavy-slot inside it runs in that slot. Reclaims are logged to <lock dir>/reclaim.log.
24
41
  # The whole body is one function, called on the last line: bash then parses the entire file before running any of it,
25
42
  # so overwriting this file while copies are running cannot splice old and new code (15 Oct: an in-place cp of v6
26
43
  # over a running v5 produced 'others: unbound variable'). Runs on the bash macOS ships (3.2) (MW5-22).
@@ -28,20 +45,31 @@ main() {
28
45
  set -u
29
46
  LIMITS="${NODII_RESOURCE_LIMITS:-$HOME/.config/nodii-resources/limits.env}"
30
47
  D="${HEAVY_SLOT_DIR:-/tmp/nodii-heavy-slots}"
48
+ # The pool this job takes a slot from: $D for heavy (where every older copy looks), $D/light for light (v27).
49
+ SD="$D"
31
50
  POLL="${HEAVY_SLOT_POLL_SEC:-10}"; case "$POLL" in ''|*[!0-9]*|0) POLL=10;; esac
32
51
  IS_LANDING=0
52
+ SIZE=heavy
33
53
  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=""
54
+ SLOTS=2; MIN_GB=16; STAGGER=60; RESERVE=1; RECLAIM_MIN=10; LSLOTS=0; LMIN_GB=""; LMAX=20
55
+ HEAVY_SLOTS=""; HEAVY_MIN_AVAIL_GB=""; HEAVY_STAGGER_SEC=""; HEAVY_LANDING_RESERVE=""; HEAVY_RECLAIM_MIN=""
56
+ LIGHT_SLOTS=""; LIGHT_MIN_AVAIL_GB=""; LIGHT_MAX_TEST_FILES=""
36
57
  if [ -r "$LIMITS" ]; then
37
58
  # shellcheck disable=SC1090
38
59
  . "$LIMITS"
39
60
  fi
40
61
  SLOTS="${HEAVY_SLOTS:-$SLOTS}"; MIN_GB="${HEAVY_MIN_AVAIL_GB:-$MIN_GB}"; STAGGER="${HEAVY_STAGGER_SEC:-$STAGGER}"
41
- RESERVE="${HEAVY_LANDING_RESERVE:-$RESERVE}"
62
+ RESERVE="${HEAVY_LANDING_RESERVE:-$RESERVE}"; RECLAIM_MIN="${HEAVY_RECLAIM_MIN:-$RECLAIM_MIN}"
63
+ LSLOTS="${LIGHT_SLOTS:-$LSLOTS}"; LMIN_GB="${LIGHT_MIN_AVAIL_GB:-$LMIN_GB}"; LMAX="${LIGHT_MAX_TEST_FILES:-$LMAX}"
42
64
  # A garbled limit must never break the arithmetic below (an arithmetic error aborts the wait loop).
43
65
  case "$SLOTS" in ''|*[!0-9]*|0) SLOTS=2;; esac; case "$MIN_GB" in ''|*[!0-9]*) MIN_GB=16;; esac
44
66
  case "$STAGGER" in ''|*[!0-9]*) STAGGER=60;; esac; case "$RESERVE" in ''|*[!0-9]*) RESERVE=1;; esac
67
+ case "$RECLAIM_MIN" in ''|*[!0-9]*) RECLAIM_MIN=10;; esac
68
+ # v27: no light pool unless the limits file sizes one, and its floor is the heavy floor unless the file sets its own.
69
+ case "$LSLOTS" in ''|*[!0-9]*) LSLOTS=0;; esac; case "$LMIN_GB" in ''|*[!0-9]*) LMIN_GB=$MIN_GB;; esac
70
+ case "$LMAX" in ''|*[!0-9]*) LMAX=20;; esac
71
+ # v27: a light job uses the light pool's own cap and floor, with no stagger and no landing reserve.
72
+ if [ "$SIZE" = light ]; then SLOTS=$LSLOTS; MIN_GB=$LMIN_GB; STAGGER=0; RESERVE=0; fi
45
73
  # v15 (24 Oct): landings get a reserved slot. A `git push` (whose pre-push runs the gates) stuck behind
46
74
  # typechecks/tests blocks the whole fleet (HR's FE landings queued ~70 min, 10:30Z). Non-landing jobs may use
47
75
  # only slots 1..SLOTS-RESERVE.
@@ -67,7 +95,7 @@ mtime() { local m; m=$(stat -f %m "$1" 2>/dev/null) || m=$(stat -c %Y "$1" 2>/de
67
95
  since_last_admit() {
68
96
  # Any missing/empty/garbled stamp means "long ago". Never feed an empty string to $(( )): in bash an arithmetic
69
97
  # 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
98
+ local t; t=$(cat "$SD/last-admit" 2>/dev/null); case "$t" in ''|*[!0-9]*) echo 999999; return;; esac
71
99
  echo $(( $(date +%s) - t ))
72
100
  }
73
101
  admit_lock_age() {
@@ -81,36 +109,112 @@ dead() { local e; [ -n "$1" ] || return 1; e=$(kill -0 "$1" 2>&1) && return 1; c
81
109
  # v17 (24 Oct): reclaim dead holders in EVERY slot dir (a slot numbered above a lowered cap was never scanned, so a
82
110
  # dead holder kept it "held" forever), and count only LIVE holders.
83
111
  held_count() { local o op n=0
84
- for o in "$D"/[0-9]*; do
112
+ for o in "${1:-$SD}"/[0-9]*; do
85
113
  [ -d "$o" ] || continue
86
114
  op=$(cat "$o/pid" 2>/dev/null || echo)
87
115
  if dead "$op"; then rm -rf "$o"; continue; fi
88
116
  n=$((n + 1))
89
117
  done; echo "$n"; }
90
118
 
119
+ # --- v26 (NODII-DEV-CLI-86): orphaned slots -------------------------------------------------------------------------
120
+ # 13 Nov: lane infra32-services's session died while its `bun test` gate hung on a down Redis. The holder (this script)
121
+ # stayed alive, so `dead` never fired, and slot 6 was held 2h20m. A slot is reclaimed only when ALL of these hold:
122
+ # - it has been held at least HEAVY_RECLAIM_MIN minutes;
123
+ # - it was taken by a lane (a slot with no lane is never reclaimed this way);
124
+ # - the agent session that took it is gone: its pid is dead, or now belongs to a process started at another time;
125
+ # - no `claude` or `codex` process has its working directory in the job's worktree (a relaunched session);
126
+ # - Dev reports the lane down: liveness orphan or ended, or status stopped or non_issue (`heavy lane-state`).
127
+ # Any check that cannot tell (no lsof, Dev unreachable) keeps the slot. The HOLDER watches its own slot and, once it
128
+ # is an orphan, logs the reclaim and stops its own job's tree (MW2-49: a session tears down only what it started);
129
+ # a waiter never signals another session's processes. `heavy status` shows a slot that is a candidate.
130
+ lane_key() { local b
131
+ if [ -n "${NODII_LANE_KEY:-}" ]; then echo "$NODII_LANE_KEY"; return; fi
132
+ b=$(basename -- "${NODII_DEV_CONFIG_PATH:-}" .json); case "$b" in lane-?*) echo "${b#lane-}";; esac; }
133
+ started() { ps -o lstart= -p "$1" 2>/dev/null | tr -s ' '; }
134
+ # Seconds since path $1 changed; 0 when it is gone (another waiter may remove it between a test and the stat, and an
135
+ # empty operand in $(( )) is an arithmetic error that aborts the wait loop).
136
+ age_of() { local m; m=$(mtime "$1"); echo $(( $(date +%s) - ${m:-$(date +%s)} )); }
137
+ slot_since() { local s; s=$(cat "$1/since" 2>/dev/null); case "$s" in ''|*[!0-9]*) s=$(mtime "$1");; esac; echo "${s:-$(date +%s)}"; }
138
+ # The session that took slot dir $1 is still running (same pid, same start time).
139
+ session_alive() { local sp st; sp=$(cat "$1/session" 2>/dev/null); st=$(cat "$1/session-start" 2>/dev/null)
140
+ case "$sp" in ''|*[!0-9]*) return 1;; esac
141
+ dead "$sp" && return 1
142
+ [ -z "$st" ] || [ "$(started "$sp")" = "$st" ]; }
143
+ # A claude or codex process works in worktree $1. Without lsof we can't tell, so we say yes.
144
+ agent_in() { local wt="$1" c
145
+ [ -n "$wt" ] || return 1
146
+ command -v lsof >/dev/null 2>&1 || return 0
147
+ while IFS= read -r c; do case "$c/" in "$wt"/*) return 0;; esac
148
+ done < <(lsof -a -d cwd -c claude -c codex -Fn 2>/dev/null | sed -n 's/^n//p')
149
+ return 1; }
150
+ lane_state() {
151
+ if [ -n "${HEAVY_LANE_PROBE:-}" ]; then "$HEAVY_LANE_PROBE" "$1" 2>/dev/null; return 0; fi
152
+ # K04-1, K04-3: the nodii-dev on PATH. One without `heavy lane-state` fails, which reads as unknown and keeps the slot.
153
+ nodii-dev heavy lane-state "$1" 2>/dev/null || echo "unknown probe failed"; }
154
+ # Why slot dir $1 is an orphan, or fail. Skips the age check when $2 is "any-age" (heavy status).
155
+ orphan_why() { local o="$1" now lane age st wt
156
+ [ "$RECLAIM_MIN" -gt 0 ] || return 1
157
+ lane=$(cat "$o/lane" 2>/dev/null); [ -n "$lane" ] || return 1
158
+ now=$(date +%s); age=$(( now - $(slot_since "$o") ))
159
+ [ "${2:-}" = any-age ] || [ "$age" -ge $(( RECLAIM_MIN * 60 )) ] || return 1
160
+ session_alive "$o" && return 1
161
+ wt=$(cat "$o/worktree" 2>/dev/null)
162
+ agent_in "$wt" && return 1
163
+ st=$(lane_state "$lane"); case "$st" in down*) ;; *) return 1;; esac
164
+ echo "lane $lane is down in Dev (${st#down }), its agent session $(cat "$o/session" 2>/dev/null || echo '?') is gone and no agent works in ${wt:-its worktree}"; }
165
+ # One line per reclaim, in <lock dir>/reclaim.log and in the slot (the holder's stop trap prints it on its stderr).
166
+ log_reclaim() { local o="$1" why="$2" line
167
+ line="$(date -u +%Y-%m-%dT%H:%M:%SZ) reclaimed slot $(basename "$o") held $(( $(date +%s) - $(slot_since "$o") ))s by lane $(cat "$o/lane" 2>/dev/null || echo '?') (holder $$, job group $(cat "$o/job" 2>/dev/null || echo '?')): $why"
168
+ echo "$line" >> "$D/reclaim.log"; echo "$line" > "$o/reclaimed"; }
169
+
91
170
  if [ "${1:-}" = "--status" ]; then
92
171
  [ -d "$D" ] || mkdir -p "$D" 2>/dev/null
93
172
  load_limits
94
- local now held q t tp o; now=$(date +%s); held=$(held_count)
95
- echo "heavy-slot v25 · limits $LIMITS"
173
+ local now held lheld q t tp o qd; now=$(date +%s); held=$(held_count "$D"); lheld=$(held_count "$D/light")
174
+ echo "heavy-slot v27 · limits $LIMITS"
96
175
  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
176
+ if [ "$LSLOTS" -eq 0 ]; then echo "light slots off (the limits file sets no LIGHT_SLOTS): every job takes a heavy slot"
177
+ else echo "light slots ${lheld}/${LSLOTS} held (floor ${LMIN_GB} GB, no stagger; a test run naming at most ${LMAX} test files is light)"; fi
178
+ echo "available memory $(avail_gb) GB (floor ${MIN_GB} GB) · stagger ${STAGGER}s · reclaim after ${RECLAIM_MIN} min"
179
+ local lane why age
180
+ for o in "$D"/[0-9]* "$D"/light/[0-9]*; do
99
181
  [ -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)"
182
+ case "$o" in */light/*) qd="light slot";; *) qd="slot";; esac
183
+ t=$(slot_since "$o"); lane=$(cat "$o/lane" 2>/dev/null)
184
+ echo " ${qd} $(basename "$o") pid $(cat "$o/pid" 2>/dev/null) for $(( now - ${t:-$now} ))s${lane:+ lane $lane}: $(cat "$o/what" 2>/dev/null)"
185
+ if [ -n "$lane" ] && ! session_alive "$o" && why=$(orphan_why "$o" any-age); then
186
+ age=$(( RECLAIM_MIN * 60 - (now - ${t:-$now}) ))
187
+ if [ "$age" -gt 0 ]; then echo " reclaim candidate: $why; reclaimed in ${age}s"
188
+ else echo " reclaim candidate: $why; its holder reclaims it at its next check"; fi
189
+ fi
101
190
  done
102
- q=0; local sp=0 st; st=" $(ps -axo pid=,stat= 2>/dev/null | awk '$2 ~ /^T/ {print $1}' | tr '\n' ' ') "
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
- case "$st" in *" $tp "*) sp=$((sp + 1)); echo " stopped: pid ${tp} waiting $(( now - ${t%%.*} ))s (holds no place until it resumes)"; continue;; esac
107
- q=$((q + 1)); echo " queued $q: pid ${tp} waiting $(( now - ${t%%.*} ))s"
191
+ [ -s "$D/reclaim.log" ] && { echo "last reclaims ($D/reclaim.log):"; tail -3 "$D/reclaim.log" | sed 's/^/ /'; }
192
+ local sp=0 st hq=0; st=" $(ps -axo pid=,stat= 2>/dev/null | awk '$2 ~ /^T/ {print $1}' | tr '\n' ' ') "
193
+ for qd in q lq; do
194
+ q=0
195
+ for t in $(ls "$D/$qd" 2>/dev/null | sort); do
196
+ tp=$(cat "$D/$qd/$t" 2>/dev/null)
197
+ if dead "$tp"; then rm -f "$D/$qd/$t"; continue; fi
198
+ case "$st" in *" $tp "*) sp=$((sp + 1)); echo " stopped: pid ${tp} waiting $(( now - ${t%%.*} ))s (holds no place until it resumes)"; continue;; esac
199
+ q=$((q + 1)); if [ "$qd" = lq ]; then echo " light queued $q: pid ${tp} waiting $(( now - ${t%%.*} ))s"; else echo " queued $q: pid ${tp} waiting $(( now - ${t%%.*} ))s"; fi
200
+ done
201
+ if [ "$qd" = q ]; then hq=$q; else echo "queue ${hq} waiting, light queue ${q} waiting, ${sp} stopped"; fi
108
202
  done
109
- echo "queue ${q} waiting, ${sp} stopped"
110
203
  return 0
111
204
  fi
112
205
 
113
- [ $# -gt 0 ] || { echo "usage: nodii-dev heavy run -- <command...> | nodii-dev heavy status" >&2; return 2; }
206
+ # v27: --size light|heavy before the command (`nodii-dev heavy run --size light -- CMD`), or HEAVY_SIZE.
207
+ SIZE="${HEAVY_SIZE:-}"
208
+ while [ $# -gt 0 ]; do
209
+ case "$1" in
210
+ --size) [ $# -ge 2 ] || { echo "usage: nodii-dev heavy run [--size light|heavy] -- <command...>" >&2; return 2; }; SIZE="$2"; shift 2;;
211
+ --size=*) SIZE="${1#--size=}"; shift;;
212
+ --) shift; break;;
213
+ *) break;;
214
+ esac
215
+ done
216
+ case "$SIZE" in ''|auto|light|heavy) ;; *) echo "[heavy-slot] --size must be light or heavy, got: $SIZE" >&2; return 2;; esac
217
+ [ $# -gt 0 ] || { echo "usage: nodii-dev heavy run [--size light|heavy] -- <command...> | nodii-dev heavy status" >&2; return 2; }
114
218
  # Long-running dev/preview servers are not jobs: they never exit, so they would hold a slot forever
115
219
  # (15 Oct: a `vite --port 5260` sat in a slot while 7 real jobs queued). Refuse them; run them outside the gate,
116
220
  # at most DEV_SERVER_CAP host-wide, and kill them by PID when done (K02-7). `vite build`, vitest and typechecks are jobs.
@@ -123,7 +227,17 @@ if { printf '%s' "$cmd" | grep -Eq '[ /]vite( |$)' && ! printf '%s' "$cmd" | gre
123
227
  fi
124
228
  # v20 (24 Oct): already inside a heavy slot (an outer heavy-slot or a gated-bin wrapper set this) -> run directly.
125
229
  # 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).
126
- [ "${NODII_HEAVY_SLOT_HELD:-}" = 1 ] && exec "$@"
230
+ # v26 (NODII-DEV-CLI-86): the job of a held slot sees NODII_HEAVY_SLOT=<n>. Inside it, heavy work (a `heavy run`, a
231
+ # `lane check` gate, a reviewer) runs in that same slot and never queues for a second one. A marker whose slot is no
232
+ # longer held (a process that outlived its job) queues like any other job. A marker-less NODII_HEAVY_SLOT_HELD=1 comes
233
+ # from an older copy (v20-v25) or a gated-bin wrapper and still runs at once.
234
+ if [ -n "${NODII_HEAVY_SLOT:-}" ]; then
235
+ # v27: light/<n> names a light slot.
236
+ case "${NODII_HEAVY_SLOT#light/}" in ''|*[!0-9]*) ;; *)
237
+ if [ -d "$D/$NODII_HEAVY_SLOT" ] && ! dead "$(cat "$D/$NODII_HEAVY_SLOT/pid" 2>/dev/null)"; then exec "$@"; fi;; esac
238
+ echo "[heavy-slot] NODII_HEAVY_SLOT=${NODII_HEAVY_SLOT} names a slot that is no longer held; queueing for a slot of its own." >&2
239
+ unset NODII_HEAVY_SLOT NODII_HEAVY_SLOT_HELD
240
+ elif [ "${NODII_HEAVY_SLOT_HELD:-}" = 1 ]; then exec "$@"; fi
127
241
  # v18 (24 Oct): a teardown FREES memory, so it never waits for a slot. `docker compose … down -v` sat 3 min behind
128
242
  # 14 queued jobs (12:27Z) while its stack kept its containers' memory.
129
243
  case " $* " in *" compose "*" down"*|*" down "*|*stack:down*|*":down "*) exec "$@";; esac
@@ -159,10 +273,44 @@ is_push() {
159
273
  esac
160
274
  done; return 1; }
161
275
  is_push "$@" && IS_LANDING=1; [ "${HEAVY_LANDING:-}" = 1 ] && IS_LANDING=1
276
+ # v27 (hub-401): a job's size. Unsized, a test run that names its test files, at most LIGHT_MAX_TEST_FILES
277
+ # of them (`bun test a.test.ts`, `vitest run x.spec.ts`, `node --test t/a.test.js`, optionally piped to tail, head,
278
+ # grep or tee), is light; everything else is heavy. A landing is always heavy: it keeps its reserve.
279
+ light_test_run() {
280
+ local s="$*" w n=0 runner=0 prev=""
281
+ case "$s" in "/bin/sh -c "*|"sh -c "*|"bash -c "*|"/bin/bash -c "*) s="${s#* -c }";; esac
282
+ s=$(printf '%s' "$s" | sed -E 's/[0-9]?>&[0-9]//g; s/[|][[:space:]]*(tail|head|grep|tee)([[:space:]][^|;&]*)?$//')
283
+ case "$s" in *"&&"*|*"||"*|*";"*|*"|"*|*'$('*|*'`'*|*"<"*|*">"*) return 1;; esac
284
+ load_limits
285
+ set -f
286
+ for w in $s; do
287
+ case "$w" in
288
+ vitest|*/vitest|jest|*/jest|mocha|*/mocha) runner=1;;
289
+ test) case "$prev" in bun|*/bun) runner=1;; esac;;
290
+ --test) case "$prev" in node|*/node) runner=1;; esac;;
291
+ *'*'*|*'?'*) set +f; return 1;;
292
+ *.test.[cm][jt]s|*.test.[jt]s|*.test.[jt]sx|*.spec.[cm][jt]s|*.spec.[jt]s|*.spec.[jt]sx) n=$((n + 1));;
293
+ esac
294
+ prev="$w"
295
+ done
296
+ set +f
297
+ [ "$runner" = 1 ] && [ "$n" -ge 1 ] && [ "$n" -le "$LMAX" ]
298
+ }
299
+ # A light slot skips the heavy cap, floor and stagger, so only a test run naming its test files may take one: an
300
+ # explicit --size light (or HEAVY_SIZE=light) on anything else is refused and takes a heavy slot (K02-4).
301
+ load_limits
302
+ if [ "$IS_LANDING" = 1 ]; then SIZE=heavy
303
+ elif [ "$LSLOTS" -eq 0 ]; then SIZE=heavy
304
+ elif [ -z "$SIZE" ] || [ "$SIZE" = auto ]; then if light_test_run "$@"; then SIZE=light; else SIZE=heavy; fi
305
+ elif [ "$SIZE" = light ] && ! light_test_run "$@"; then
306
+ echo "[heavy-slot] --size light is only for a test run naming at most ${LMAX} test files; this job takes a heavy slot: $*" >&2
307
+ SIZE=heavy
308
+ fi
309
+ if [ "$SIZE" = light ]; then SD="$D/light"; mkdir -p "$SD" 2>/dev/null; fi
162
310
  # v19 (24 Oct): FIFO. Waiters raced for freed slots, so an unlucky job starved: tenant's `test:stack:up` waited 71 min
163
311
  # behind 14 newer jobs (12:27Z). Each non-landing waiter takes a ticket (time-ordered name); only the oldest
164
312
  # (limit - held) live tickets may try for a slot. Landings keep their reserve and skip the line.
165
- local Q="$D/q" TICKET=""; mkdir -p "$Q" 2>/dev/null
313
+ local Q="$D/q" TICKET=""; [ "$SIZE" = light ] && Q="$D/lq"; mkdir -p "$Q" 2>/dev/null
166
314
  if [ "$IS_LANDING" != 1 ]; then TICKET="$Q/$(date +%s).$(printf '%06d' $$)"; echo $$ > "$TICKET"; fi
167
315
  trap '[ -n "$TICKET" ] && rm -f "$TICKET"' EXIT
168
316
  # v25 (13 Nov, hub-377): a STOPPED waiter (ps state T: ^Z, SIGSTOP, a suspended session) never polls, so it can never
@@ -176,7 +324,7 @@ fifo_rank() { local r=0 t tp st; st=" $(stopped_pids | tr '\n' ' ') "
176
324
  [ "$Q/$t" = "$TICKET" ] && { echo "$r"; return; }
177
325
  case "$st" in *" $tp "*) continue;; esac
178
326
  r=$((r + 1)); done; echo 0; }
179
- local slot="" waited=0 said=-1 held rank LIMIT i l o a g others av why
327
+ local slot="" waited=0 said=-1 held rank LIMIT i l o a g others alone av why
180
328
  # A queued job says its place and its wait when it starts waiting and then once a minute; it never gives up, so a
181
329
  # gate is never timed out by the queue (hub-377).
182
330
  say() { if [ "$said" -lt 0 ] || [ $((waited - said)) -ge 60 ]; then said=$waited; echo "[heavy-slot] waiting ${waited}s: $1. Job: $JOB" >&2; fi; }
@@ -199,7 +347,7 @@ while :; do
199
347
  pause; continue
200
348
  fi
201
349
  for i in $(seq 1 "$SLOTS"); do
202
- l="$D/$i"
350
+ l="$SD/$i"
203
351
  if [ -d "$l" ]; then o=$(cat "$l/pid" 2>/dev/null || echo); dead "$o" && rm -rf "$l"; fi
204
352
  if mkdir "$l" 2>/dev/null; then
205
353
  echo $$ > "$l/pid"; echo "$(pwd) :: $*" > "$l/what"
@@ -212,7 +360,10 @@ while :; do
212
360
  # The stagger only matters while another admitted job is still running (its memory may still be growing).
213
361
  # With every other slot idle, admit at once: a fixed 60 s gap serialised quick jobs (biome, lint) to one a
214
362
  # minute and queued 29 of them with zero heavy jobs running (15 Oct 15:38Z).
215
- others=0; for o in "$D"/[0-9]*; do [ -d "$o" ] && [ "$o" != "$l" ] && others=$((others + 1)); done
363
+ others=0; for o in "$SD"/[0-9]*; do [ -d "$o" ] && [ "$o" != "$l" ] && others=$((others + 1)); done
364
+ # v27: "no other job is running" counts both pools. A light job alone in its pool beside running heavy jobs
365
+ # (or a heavy job beside light ones) is held by the floor like any other job: waiting can free memory then.
366
+ if [ "$SD" = "$D" ]; then alone=$(( others + $(held_count "$D/light") )); else alone=$(( others + $(held_count "$D") )); fi
216
367
  # v24 (hub-377): with NO heavy job running, waiting cannot free memory (heavy jobs hold none of it), so the
217
368
  # floor would stop every job on the machine for good, landings too: once every lane went through the queue,
218
369
  # 6 GB available under a 14 GB floor with 0 slots held queued all of them. One job is then admitted, with a
@@ -223,10 +374,10 @@ while :; do
223
374
  # v24 (hub-377): the cap is checked again HERE, under the admit lock. The held count at the top of the loop
224
375
  # is read before the lock, so two waiters could both see one free slot, take two slot numbers and run one
225
376
  # job over the cap (seen in the suite under load: 3 at once with a limit of 2; v23 had the same race).
226
- if [ "$others" -lt "$LIMIT" ] && { [ "$a" -ge "$MIN_GB" ] || [ "$others" -eq 0 ] || [ "$IS_LANDING" = 1 ]; } && { [ "$others" -eq 0 ] || [ "$g" -ge "$STAGGER" ]; }; then
227
- 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
377
+ if [ "$others" -lt "$LIMIT" ] && { [ "$a" -ge "$MIN_GB" ] || [ "$alone" -eq 0 ] || [ "$IS_LANDING" = 1 ]; } && { [ "$others" -eq 0 ] || [ "$g" -ge "$STAGGER" ]; }; then
378
+ if [ "$a" -lt "$MIN_GB" ] && [ "$alone" -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
228
379
  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
229
- date +%s > "$D/last-admit"; rmdir "$D/.admit"; slot="$l"; [ -n "$TICKET" ] && rm -f "$TICKET"; TICKET=""; break 2
380
+ date +%s > "$SD/last-admit"; rmdir "$D/.admit"; slot="$l"; [ -n "$TICKET" ] && rm -f "$TICKET"; TICKET=""; break 2
230
381
  fi
231
382
  rmdir "$D/.admit"
232
383
  fi
@@ -243,13 +394,22 @@ while :; do
243
394
  done
244
395
  # belt and braces: never run without a slot
245
396
  [ -n "$slot" ] && [ -d "$slot" ] || { echo "[heavy-slot] internal error: no slot acquired; refusing to run: $*" >&2; exit 70; }
246
- echo "[heavy-slot] got $(basename "$slot")/${SLOTS} after ${waited}s (available $(avail_gb) GB): $*" >&2
397
+ LBL=""; [ "$SIZE" = light ] && LBL=" light"
398
+ echo "[heavy-slot] got $(basename "$slot")/${SLOTS}${LBL} after ${waited}s (available $(avail_gb) GB): $*" >&2
399
+ # v26: who holds the slot, for the orphan reclaim, and the marker the job's own heavy work runs under.
400
+ date +%s > "$slot/since"
401
+ lane_key > "$slot/lane"
402
+ echo "${CLAUDE_PID:-}" > "$slot/session"; [ -n "${CLAUDE_PID:-}" ] && started "$CLAUDE_PID" > "$slot/session-start"
403
+ { git rev-parse --show-toplevel 2>/dev/null || pwd; } > "$slot/worktree"
404
+ # v27: a light slot's marker is light/<n>, so the nested check finds it under $D.
405
+ if [ "$SIZE" = light ]; then export NODII_HEAVY_SLOT="light/$(basename "$slot")"; else export NODII_HEAVY_SLOT="$(basename "$slot")"; fi
247
406
  # Run the job as its OWN process group and forward INT/TERM to the whole group. Without this, stopping the wrapper
248
407
  # left the job running (15 Oct: a sharded tsc kept spawning 4 GB shards after its wrapper was killed) AND released
249
408
  # the slot, so the gate under-counted live memory.
250
409
  set -m
251
410
  "$@" &
252
411
  child=$!
412
+ echo "$child" > "$slot/job"
253
413
  # v13 (24 Oct): a wrapper killed with SIGKILL (Codex's per-command timeout) can't run its traps, and the job
254
414
  # lives in its own process group, so it was orphaned and kept running with NO slot. A watchdog in ITS OWN group
255
415
  # outlives the wrapper and takes the job down with it.
@@ -272,11 +432,25 @@ kill_tree() { local g gs; gs=$(tree_groups "$child"); gs=$(printf '%s\n%s\n' "$c
272
432
  kill_tree ) </dev/null >/dev/null 2>&1 &
273
433
  watchdog=$!
274
434
  set +m
275
- stop() { kill_tree; rm -rf "$slot"; exit 143; }
435
+ # v26 (NODII-DEV-CLI-86): the orphan watch. Once a minute (HEAVY_RECLAIM_POLL_SEC) the holder asks whether its own slot
436
+ # is an orphan (orphan_why); if so it logs the reclaim and stops itself, and its stop trap takes down the job's tree.
437
+ POLL_RECLAIM="${HEAVY_RECLAIM_POLL_SEC:-60}"; case "$POLL_RECLAIM" in ''|*[!0-9]*|0) POLL_RECLAIM=60;; esac
438
+ ( trap '' HUP PIPE
439
+ while sleep "$POLL_RECLAIM"; do
440
+ dead "$wrapper" && exit 0; [ -d "$slot" ] || exit 0
441
+ load_limits
442
+ if why=$(orphan_why "$slot"); then log_reclaim "$slot" "$why"; kill -TERM "$wrapper" 2>/dev/null; exit 0; fi
443
+ done ) </dev/null >/dev/null 2>&1 &
444
+ # Its output goes nowhere: a watch (or its sleep) holding the holder's stdout or stderr kept a caller's pipe open up to
445
+ # a minute after the job ended.
446
+ orphanwatch=$!
447
+ stop() { kill "$orphanwatch" 2>/dev/null
448
+ [ -s "$slot/reclaimed" ] && echo "[heavy-slot] $(cat "$slot/reclaimed" 2>/dev/null)" >&2
449
+ kill_tree; rm -rf "$slot"; exit 143; }
276
450
  trap stop INT TERM
277
451
  trap 'rm -rf "$slot"' EXIT
278
452
  wait "$child"; rc=$?
279
- kill "$watchdog" 2>/dev/null
453
+ kill "$watchdog" "$orphanwatch" 2>/dev/null
280
454
  exit "$rc"
281
455
  }
282
456
  main "$@"; exit $?
package/dist/heavy.js CHANGED
@@ -9,23 +9,50 @@
9
9
  import { spawn } from "node:child_process";
10
10
  import { basename } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
- import { CliError } from "./core.js";
12
+ import { CliError, devRequest, encode } from "./core.js";
13
13
 
14
14
  export const HEAVY_SLOT_SCRIPT = fileURLToPath(new URL("./heavy-slot.sh", import.meta.url));
15
15
  export const HEAVY_PREFIX = "nodii-dev heavy run -- ";
16
- export const HEAVY_USAGE = "nodii-dev heavy run -- <command...> | nodii-dev heavy status";
16
+ export const HEAVY_USAGE = "nodii-dev heavy run [--size light|heavy] -- <command...> | nodii-dev heavy status";
17
17
 
18
18
  /** The process that runs ARGV under a heavy slot: `[file, args]` for spawn. A nested call runs at once (K02-6). */
19
19
  export const heavySlotArgv = (argv) => ["/bin/bash", [HEAVY_SLOT_SCRIPT, ...argv]];
20
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 } = {}) {
21
+ // NODII-DEV-CLI-86: Dev's view of a slot's lane for the orphan reclaim. Down means no live run (liveness orphan or
22
+ // ended) or a lane that was stopped or closed. Quiet and blocked lanes are up: a lane waiting on another still owns its job.
23
+ const DOWN_LIVENESS = new Set(["orphan", "ended"]);
24
+ const DOWN_STATUS = new Set(["stopped", "non_issue"]);
25
+
26
+ /** `up|down <why>` for a lane record from Dev. */
27
+ export function laneUpOrDown(lane) {
28
+ const why = `liveness=${lane?.liveness ?? "none"} status=${lane?.status ?? "none"}`;
29
+ return DOWN_LIVENESS.has(lane?.liveness) || DOWN_STATUS.has(lane?.status) ? `down ${why}` : `up ${why}`;
30
+ }
31
+
32
+ /** `nodii-dev heavy lane-state KEY`: one line, `up|down|unknown <why>`. Unknown keeps the slot; it never throws. */
33
+ export async function laneState(key, { request = devRequest, timeoutMs = 15_000 } = {}) {
34
+ try {
35
+ const payload = await request("GET", `/api/v1/lanes/${encode(key)}`, undefined, { signal: AbortSignal.timeout(timeoutMs) });
36
+ return laneUpOrDown(payload?.data);
37
+ } catch (error) {
38
+ return `unknown ${String(error?.code ?? error?.name ?? "error").replace(/\s+/g, "_")}`;
39
+ }
40
+ }
41
+
42
+ /** `nodii-dev heavy run|status|lane-state` when the CLI was started on Node or Bun rather than through bin/nodii-dev. */
43
+ export async function heavyCommand(args, { spawnImpl = spawn, env = process.env, signals = process, request = devRequest, write = (text) => process.stdout.write(text) } = {}) {
23
44
  const [action, ...rest] = args;
24
45
  let argv;
46
+ if (action === "lane-state") {
47
+ if (!rest[0]) throw new CliError("USAGE", "nodii-dev heavy lane-state <lane-key>", 2);
48
+ write(`${await laneState(rest[0], { request })}\n`);
49
+ return 0;
50
+ }
25
51
  if (action === "status") argv = ["--status"];
26
52
  else if (action === "run") {
53
+ // heavy-slot.sh reads --size and the `--` itself (v27); only a bare `--` in front is dropped here.
27
54
  argv = rest[0] === "--" ? rest.slice(1) : rest;
28
- if (!argv.length) throw new CliError("USAGE", HEAVY_USAGE, 2);
55
+ if (argv.every((word) => word === "--")) throw new CliError("USAGE", HEAVY_USAGE, 2);
29
56
  } else throw new CliError("USAGE", HEAVY_USAGE, 2);
30
57
  const [file, fileArgs] = heavySlotArgv(argv);
31
58
  return new Promise((resolve) => {
@@ -249,13 +276,14 @@ function queued(argv) {
249
276
  return ["bash", "sh", "zsh"].includes(name) && /(?:^|\/)heavy-slot\.sh$/.test(argv.find((word, i) => i > 0 && !word.startsWith("-")) ?? "");
250
277
  }
251
278
 
252
- // `nodii-dev lane check --gate …` and `nodii-dev receipt write --run …` queue each gate themselves, and
253
- // `nodii-dev run … -- CMD` queues CMD when it is heavy (needsSlot).
279
+ // `nodii-dev lane check --gate …` and `nodii-dev receipt write --run …` queue each gate themselves,
280
+ // `nodii-dev run … -- CMD` queues CMD when it is heavy (needsSlot), and `nodii-dev test affected --run`
281
+ // queues each job at the change's size (hub-401).
254
282
  function selfQueued(argv) {
255
283
  const name = plainName(argv[0]);
256
284
  if (!/^nodii-dev(?:\.js)?$/.test(name)) return false;
257
285
  const [command, action] = argv.slice(1).filter((word) => !word.startsWith("-"));
258
- return (command === "lane" && action === "check") || (command === "receipt" && action === "write") || command === "run";
286
+ return (command === "lane" && action === "check") || (command === "receipt" && action === "write") || command === "run" || (command === "test" && action === "affected");
259
287
  }
260
288
 
261
289
  /** Whether ARGV, run directly (no shell), is heavy work not yet in the queue; a shell running a string counts its commands. */
package/dist/impact.js ADDED
@@ -0,0 +1,470 @@
1
+ // hub-401 (MW2-20, K01-27, MW2-51): tests run only on what changed.
2
+ //
3
+ // `nodii-dev test affected [--base REF] [--run] [--json]` reads the change
4
+ // (the worktree against its merge base with origin/main, uncommitted and
5
+ // untracked files included), walks the import graph backwards from each
6
+ // changed file to the test files that reach it, and prints the command that
7
+ // runs exactly those tests, one per package. With --run it runs them, each
8
+ // under a slot sized to the change: a small change takes a light slot, a large
9
+ // one a heavy slot (heavy-slot.sh v27).
10
+ //
11
+ // The graph is the repository's own source, read without a bundler: static
12
+ // and dynamic imports, require, re-exports, vi/jest/bun module mocks, and
13
+ // `new URL("./x", import.meta.url)` file references. Specifiers resolve as
14
+ // relative paths, through the nearest tsconfig's `paths`, or to a workspace
15
+ // package by name. A changed file the graph cannot place (a manifest, a
16
+ // lockfile, a test or build config, or an unreferenced data file) selects the
17
+ // full suite: the selection fails closed, never open.
18
+ import { execFile, spawn } from "node:child_process";
19
+ import { readFile } from "node:fs/promises";
20
+ import { join, posix } from "node:path";
21
+ import { promisify } from "node:util";
22
+ import { CliError } from "./core.js";
23
+ import { heavySlotArgv } from "./heavy.js";
24
+
25
+ const execFileAsync = promisify(execFile);
26
+
27
+ export const TEST_USAGE = "nodii-dev test affected [--base REF] [--max-light N] [--run] [--json]";
28
+ export const DEFAULT_BASE = "origin/main";
29
+ /** A change whose affected tests number at most this runs in a light slot (heavy-slot.sh LIGHT_MAX_TEST_FILES). */
30
+ export const DEFAULT_MAX_LIGHT = 20;
31
+
32
+ const CODE = /\.(?:[cm]?[jt]sx?)$/;
33
+ const TEST_FILE = /(?:^|\/)(?:__tests__\/.+|[^/]+\.(?:test|spec)\.[cm]?[jt]sx?)$/;
34
+ const EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
35
+
36
+ // A change to one of these can change every test's outcome: it selects the full suite.
37
+ const GLOBAL_FILE = [
38
+ /(?:^|\/)package\.json$/,
39
+ /(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|yarn\.lock|bun\.lockb?|npm-shrinkwrap\.json)$/,
40
+ /(?:^|\/)tsconfig(?:\.[^/]*)?\.json$/,
41
+ /(?:^|\/)(?:vitest|vite|jest|babel|playwright|turbo)\.(?:config|workspace)(?:\.[^/]*)?\.[cm]?[jt]s$/,
42
+ /(?:^|\/)(?:jest\.config|turbo|nx|babel\.config)\.json$/,
43
+ /(?:^|\/)\.babelrc(?:\.json)?$/,
44
+ /(?:^|\/)(?:bunfig\.toml|\.nvmrc|\.node-version|\.tool-versions)$/,
45
+ ];
46
+ // A change to one of these changes no test's outcome.
47
+ const NO_TEST_FILE = [
48
+ /\.(?:md|mdx|txt|png|jpe?g|gif|svg|webp|ico)$/i,
49
+ /(?:^|\/)(?:LICENSE|CODEOWNERS|\.gitignore|\.gitattributes|\.editorconfig|\.prettierignore|\.eslintignore)$/,
50
+ /^\.github\//,
51
+ /^\.claude\//,
52
+ /^docs\//,
53
+ /^nodii\.repo\.yaml$/,
54
+ /^lefthook\.ya?ml$/,
55
+ /^scratchpad\//,
56
+ ];
57
+
58
+ const IMPORT_PATTERNS = [
59
+ /\b(?:import|export)\s+(?:type\s+)?(?:[\w*{}\s,$]+?\s+from\s+)?["']([^"'\n]+)["']/g,
60
+ /\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)/g,
61
+ /\brequire\s*\(\s*["']([^"'\n]+)["']\s*\)/g,
62
+ /\b(?:vi|jest)\.(?:mock|doMock|requireActual|importActual)\s*\(\s*["']([^"'\n]+)["']/g,
63
+ /\bmock\.module\s*\(\s*["']([^"'\n]+)["']/g,
64
+ ];
65
+ const URL_PATTERN = /\bnew\s+URL\s*\(\s*["'](\.{1,2}\/[^"'\n]+)["']\s*,\s*import\.meta\.url\s*\)/g;
66
+
67
+ /** Every module specifier SOURCE names, and the files it reaches with `new URL(…, import.meta.url)`. */
68
+ export function specifiers(source) {
69
+ const text = String(source ?? "");
70
+ const found = new Set();
71
+ for (const pattern of IMPORT_PATTERNS) for (const match of text.matchAll(pattern)) found.add(match[1]);
72
+ const urls = new Set();
73
+ for (const match of text.matchAll(URL_PATTERN)) urls.add(match[1]);
74
+ return { modules: [...found], urls: [...urls] };
75
+ }
76
+
77
+ const stripJsonComments = (text) => text
78
+ .replace(/("(?:\\.|[^"\\])*")|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, (all, string) => string ?? "")
79
+ .replace(/,(\s*[}\]])/g, "$1");
80
+
81
+ /** The key a file is known by in the graph: its path without a code extension or a trailing /index. */
82
+ export const moduleKey = (path) => path.replace(CODE, "").replace(/\/index$/, "");
83
+
84
+ /**
85
+ * The repository's import graph from FILES (repo-relative paths) and READ
86
+ * (path -> text). Returns `importers`: a map from each module key to the set
87
+ * of files that import it, and `unresolved` bare specifiers that name no
88
+ * workspace package (third-party; ignored).
89
+ */
90
+ export async function importGraph(files, read) {
91
+ const all = new Set(files);
92
+ const code = files.filter((file) => CODE.test(file));
93
+ const keys = new Set(code.map(moduleKey));
94
+ const importers = new Map();
95
+ const edge = (key, from) => { if (!importers.has(key)) importers.set(key, new Set()); importers.get(key).add(from); };
96
+
97
+ // Workspace packages by name: a bare import of one is an edge into its source.
98
+ const packages = new Map();
99
+ for (const manifest of files.filter((file) => /(?:^|\/)package\.json$/.test(file))) {
100
+ try {
101
+ const json = JSON.parse(await read(manifest));
102
+ if (json?.name) packages.set(json.name, { dir: posix.dirname(manifest) === "." ? "" : posix.dirname(manifest), json });
103
+ } catch { /* an unreadable manifest names no package */ }
104
+ }
105
+ // The nearest tsconfig's baseUrl and paths, per directory, `extends` followed within the repository.
106
+ const tsconfigs = new Map();
107
+ const loadTsconfig = async (path, depth = 0) => {
108
+ if (depth > 5 || !all.has(path)) return null;
109
+ try {
110
+ const json = JSON.parse(stripJsonComments(await read(path)));
111
+ const dir = posix.dirname(path) === "." ? "" : posix.dirname(path);
112
+ let base = null;
113
+ if (typeof json.extends === "string" && json.extends.startsWith(".")) base = await loadTsconfig(posix.normalize(posix.join(dir, json.extends.endsWith(".json") ? json.extends : `${json.extends}.json`)), depth + 1);
114
+ const options = json.compilerOptions ?? {};
115
+ const own = options.paths ? { paths: options.paths, base: posix.normalize(posix.join(dir, options.baseUrl ?? ".")) } : null;
116
+ return own ?? base;
117
+ } catch { return null; }
118
+ };
119
+ const tsconfigFor = async (file) => {
120
+ let dir = posix.dirname(file);
121
+ const chain = [];
122
+ for (;;) {
123
+ if (tsconfigs.has(dir)) break;
124
+ chain.push(dir);
125
+ const candidate = dir === "." ? "tsconfig.json" : `${dir}/tsconfig.json`;
126
+ if (all.has(candidate)) { tsconfigs.set(dir, await loadTsconfig(candidate)); break; }
127
+ if (dir === "." || dir === "") { tsconfigs.set(dir, null); break; }
128
+ dir = posix.dirname(dir);
129
+ }
130
+ const found = tsconfigs.get(dir) ?? null;
131
+ for (const visited of chain) tsconfigs.set(visited, found);
132
+ return found;
133
+ };
134
+
135
+ const resolvePath = (target) => {
136
+ const normal = posix.normalize(target).replace(/^\.\//, "");
137
+ if (all.has(normal)) return CODE.test(normal) ? moduleKey(normal) : normal;
138
+ // `./x.js` written for a `x.ts` source (NodeNext), or no extension at all.
139
+ const bare = normal.replace(CODE, "");
140
+ if (keys.has(bare)) return bare;
141
+ return null;
142
+ };
143
+ const resolvePackage = (specifier) => {
144
+ const name = specifier.startsWith("@") ? specifier.split("/").slice(0, 2).join("/") : specifier.split("/")[0];
145
+ const found = packages.get(name);
146
+ if (!found) return null;
147
+ const sub = specifier.slice(name.length).replace(/^\//, "");
148
+ const roots = [found.dir, found.dir ? `${found.dir}/src` : "src"];
149
+ for (const root of roots) {
150
+ const key = resolvePath(posix.join(root || ".", sub || "index"));
151
+ if (key) return key;
152
+ }
153
+ // Entry points named in the manifest, with a build directory mapped back to src.
154
+ for (const entry of [found.json.source, found.json.module, found.json.main, found.json.types].filter((value) => typeof value === "string")) {
155
+ for (const candidate of [entry, entry.replace(/^\.?\/?(?:dist|build|lib|out)\//, "src/").replace(/\.d\.ts$/, ".ts")]) {
156
+ const key = resolvePath(posix.join(found.dir || ".", candidate));
157
+ if (key) return key;
158
+ }
159
+ }
160
+ return moduleKey(posix.join(found.dir || ".", "src/index"));
161
+ };
162
+
163
+ const unresolved = new Set();
164
+ for (const file of code) {
165
+ let text;
166
+ try { text = await read(file); } catch { continue; }
167
+ const { modules, urls } = specifiers(text);
168
+ const dir = posix.dirname(file);
169
+ for (const url of urls) {
170
+ const target = posix.normalize(posix.join(dir, url));
171
+ edge(CODE.test(target) ? moduleKey(target) : target, file);
172
+ }
173
+ for (const specifier of modules) {
174
+ if (specifier.startsWith("node:")) continue;
175
+ if (specifier.startsWith(".")) {
176
+ const target = posix.join(dir, specifier);
177
+ // A missing target still gets an edge: deleting a module affects its importers.
178
+ edge(resolvePath(target) ?? moduleKey(posix.normalize(target)), file);
179
+ continue;
180
+ }
181
+ const config = await tsconfigFor(file);
182
+ let mapped = null;
183
+ if (config) {
184
+ for (const [pattern, targets] of Object.entries(config.paths)) {
185
+ const star = pattern.indexOf("*");
186
+ const matches = star === -1 ? specifier === pattern : specifier.startsWith(pattern.slice(0, star)) && specifier.endsWith(pattern.slice(star + 1));
187
+ if (!matches) continue;
188
+ const middle = star === -1 ? "" : specifier.slice(star, specifier.length - (pattern.length - star - 1));
189
+ for (const target of Array.isArray(targets) ? targets : []) {
190
+ const key = resolvePath(posix.join(config.base, target.replace("*", middle)));
191
+ if (key) { mapped = key; break; }
192
+ }
193
+ if (mapped) break;
194
+ }
195
+ }
196
+ mapped ??= resolvePackage(specifier);
197
+ if (mapped) edge(mapped, file);
198
+ else unresolved.add(specifier.split("/")[0]);
199
+ }
200
+ }
201
+ return { importers, unresolved: [...unresolved] };
202
+ }
203
+
204
+ /** How one changed path counts: `code` (walk the graph), `global` (full suite), `none` (no test), or `data`. */
205
+ export function classify(path) {
206
+ if (GLOBAL_FILE.some((pattern) => pattern.test(path))) return "global";
207
+ if (NO_TEST_FILE.some((pattern) => pattern.test(path))) return "none";
208
+ if (CODE.test(path)) return "code";
209
+ return "data";
210
+ }
211
+
212
+ /**
213
+ * The test files CHANGED reaches through IMPORTERS. A data file (JSON, SQL,
214
+ * shell, YAML) reaches the code files that name it, by its file name in a
215
+ * string; one nobody names selects the full suite (`full` lists why), and so
216
+ * does a changed source file that no test reaches.
217
+ */
218
+ export function selectTests(changed, { importers, files, sources }) {
219
+ const tests = new Set();
220
+ const full = [];
221
+ const seen = new Set();
222
+ const queue = [];
223
+ const visit = (key) => { if (!seen.has(key)) { seen.add(key); queue.push(key); } };
224
+ for (const path of changed) {
225
+ const kind = classify(path);
226
+ if (kind === "global") { full.push({ path, reason: "a manifest, lockfile or test or build config" }); continue; }
227
+ if (kind === "none") continue;
228
+ if (kind === "code") {
229
+ if (TEST_FILE.test(path) && files.has(path)) tests.add(path);
230
+ visit(moduleKey(path));
231
+ continue;
232
+ }
233
+ // Data: the files that import it (new URL) or name it.
234
+ visit(path);
235
+ const name = posix.basename(path);
236
+ let named = importers.has(path);
237
+ for (const [file, text] of sources) {
238
+ if (text.includes(`"${name}"`) || text.includes(`'${name}'`) || text.includes(`/${name}"`) || text.includes(`/${name}'`) || text.includes(`/${name}\``) || text.includes(`\`${name}\``)) {
239
+ named = true;
240
+ visit(moduleKey(file));
241
+ if (TEST_FILE.test(file)) tests.add(file);
242
+ }
243
+ }
244
+ if (!named) full.push({ path, reason: "a data file no source names" });
245
+ }
246
+ while (queue.length) {
247
+ const key = queue.shift();
248
+ for (const importer of importers.get(key) ?? []) {
249
+ if (TEST_FILE.test(importer)) tests.add(importer);
250
+ visit(moduleKey(importer));
251
+ }
252
+ }
253
+ // Fail closed (MW2-20): a changed source file that no test reaches through the graph may still be reached some
254
+ // way the graph cannot see (a path built at run time, a spawned script, a fixture): it selects the full suite.
255
+ for (const path of changed) {
256
+ if (classify(path) !== "code" || TEST_FILE.test(path)) continue;
257
+ if (!reachesTest(moduleKey(path), importers)) full.push({ path, reason: "no test reaches it through the import graph" });
258
+ }
259
+ return { tests: [...tests].sort(), full };
260
+ }
261
+
262
+ /** Whether any test file imports KEY, directly or through other modules. */
263
+ function reachesTest(key, importers) {
264
+ const seen = new Set([key]);
265
+ const queue = [key];
266
+ while (queue.length) {
267
+ for (const importer of importers.get(queue.shift()) ?? []) {
268
+ if (TEST_FILE.test(importer)) return true;
269
+ const next = moduleKey(importer);
270
+ if (!seen.has(next)) { seen.add(next); queue.push(next); }
271
+ }
272
+ }
273
+ return false;
274
+ }
275
+
276
+ // ─── runners ────────────────────────────────────────────────────────────────
277
+ /** The nearest package directory ("" for the root) that holds FILE, from the set of manifest dirs. */
278
+ function owningPackage(file, dirs) {
279
+ let dir = posix.dirname(file);
280
+ for (;;) {
281
+ const key = dir === "." ? "" : dir;
282
+ if (dirs.has(key)) return key;
283
+ if (dir === "." || dir === "") return "";
284
+ dir = posix.dirname(dir);
285
+ }
286
+ }
287
+
288
+ // Runner flags that always take a value, even one that looks like a path (`--config ./jest.config.mjs`).
289
+ export const VALUE_FLAGS = new Set(["--config", "-c", "--timeout", "--preload", "-r", "--require", "--import", "--loader", "--experimental-loader",
290
+ "--project", "--root", "--dir", "--reporter", "--test-reporter", "--test-reporter-destination", "--env-file", "--tsconfig", "--tsconfig-override",
291
+ "--setupFiles", "--testTimeout", "--maxWorkers", "-w", "--pool", "--environment", "--conditions", "--rootDir", "--selectProjects", "--rerun-each", "--test-name-pattern", "-t"]);
292
+ const tokenize = (script) => String(script ?? "").trim().split(/\s+/).filter(Boolean);
293
+ const shellQuote = (word) => (/^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, "'\\''")}'`);
294
+
295
+ /**
296
+ * The command that runs FILES (relative to the package) with the package's
297
+ * own runner. The runner and its flags come from the package's `test` script
298
+ * (paths and globs in it are dropped, the files appended), so a script's
299
+ * config, timeout and preload flags carry over. Null when the script is not
300
+ * one plain runner call: the caller then runs the full script.
301
+ */
302
+ export function runnerCommand(script, files, { exec = "npx --no-install" } = {}) {
303
+ const text = String(script ?? "");
304
+ if (!text.trim() || /&&|\|\||;|\||\$\(|`/.test(text)) return null;
305
+ const words = tokenize(text);
306
+ let at = 0;
307
+ while (at < words.length && /^[A-Z_][A-Z0-9_]*=/.test(words[at])) at += 1;
308
+ const env = words.slice(0, at);
309
+ const rest = words.slice(at);
310
+ let lead;
311
+ let flags;
312
+ const name = posix.basename(rest[0] ?? "");
313
+ if (name === "bun" && rest[1] === "test") { lead = ["bun", "test"]; flags = rest.slice(2); }
314
+ else if (name === "node" && rest.includes("--test")) { lead = ["node"]; flags = rest.slice(1); }
315
+ else if (name === "vitest") { lead = [...exec.split(" "), "vitest", "run"]; flags = rest.slice(rest[1] === "run" ? 2 : 1); }
316
+ else if (name === "jest") { lead = [...exec.split(" "), "jest"]; flags = rest.slice(1); }
317
+ else if (name === "mocha") { lead = [...exec.split(" "), "mocha"]; flags = rest.slice(1); }
318
+ else return null;
319
+ // Keep flags and their values; drop paths, globs and directories the script names.
320
+ const kept = [];
321
+ for (let i = 0; i < flags.length; i += 1) {
322
+ const word = flags[i];
323
+ if (word.startsWith("-")) {
324
+ kept.push(word);
325
+ const next = flags[i + 1];
326
+ const takesValue = VALUE_FLAGS.has(word) || !/[*/]|\.[cm]?[jt]sx?$/.test(next ?? "");
327
+ if (!word.includes("=") && next !== undefined && !next.startsWith("-") && takesValue && !["--test", "--watch", "--run", "--runInBand", "-i"].includes(word)) { kept.push(next); i += 1; }
328
+ continue;
329
+ }
330
+ // A bare word: a path, glob or directory. The selected files replace it.
331
+ }
332
+ if (name === "jest") kept.push("--runTestsByPath");
333
+ if (name === "vitest") kept.push("--passWithNoTests");
334
+ return [...env, ...lead, ...kept, ...files].map(shellQuote).join(" ");
335
+ }
336
+
337
+ /** How a package's tools are run: the lockfile at the repository root decides. */
338
+ export function execPrefix(files) {
339
+ if (files.has("pnpm-lock.yaml")) return "pnpm exec";
340
+ if (files.has("bun.lock") || files.has("bun.lockb")) return "bunx";
341
+ if (files.has("yarn.lock")) return "yarn";
342
+ return "npx --no-install";
343
+ }
344
+ const runScript = (files, script) => (files.has("pnpm-lock.yaml") ? `pnpm run ${script}` : files.has("bun.lock") || files.has("bun.lockb") ? `bun run ${script}` : files.has("yarn.lock") ? `yarn ${script}` : `npm run ${script}`);
345
+
346
+ /**
347
+ * The plan for TESTS: one job per package, each with its directory and the
348
+ * command that runs that package's selected tests. FULL non-empty: the
349
+ * repository's full test script, one job at the root.
350
+ */
351
+ export async function planJobs({ tests, full, files, read, fullScript = "test" }) {
352
+ if (full.length) return [{ dir: "", command: runScript(files, fullScript), tests: [], full: true }];
353
+ const manifests = [...files].filter((file) => /(?:^|\/)package\.json$/.test(file));
354
+ const dirs = new Set(manifests.map((file) => (posix.dirname(file) === "." ? "" : posix.dirname(file))));
355
+ const groups = new Map();
356
+ for (const test of tests) {
357
+ const dir = owningPackage(test, dirs);
358
+ if (!groups.has(dir)) groups.set(dir, []);
359
+ groups.get(dir).push(dir ? test.slice(dir.length + 1) : test);
360
+ }
361
+ const exec = execPrefix(files);
362
+ const jobs = [];
363
+ for (const [dir, relative] of groups) {
364
+ let scripts = {};
365
+ try { scripts = JSON.parse(await read(dir ? `${dir}/package.json` : "package.json")).scripts ?? {}; } catch { /* no manifest: no script */ }
366
+ const script = scripts.test ?? scripts["test:unit"];
367
+ const command = runnerCommand(script, relative, { exec });
368
+ if (command) jobs.push({ dir, command, tests: relative, full: false });
369
+ // A package whose test script is not one runner call: run its whole script there.
370
+ else jobs.push({ dir, command: runScript(files, scripts.test ? "test" : fullScript), tests: relative, full: true });
371
+ }
372
+ return jobs.sort((a, b) => a.dir.localeCompare(b.dir));
373
+ }
374
+
375
+ // ─── git ────────────────────────────────────────────────────────────────────
376
+ async function git(cwd, args) {
377
+ const { stdout } = await execFileAsync("git", ["-C", cwd, ...args], { maxBuffer: 256 * 1024 * 1024 });
378
+ return stdout;
379
+ }
380
+ const lines = (text) => text.split("\n").map((line) => line.trim()).filter(Boolean);
381
+
382
+ /** The repository root, the merge base with BASE, the changed paths (committed, staged, unstaged, untracked) and every file. */
383
+ export async function changeSet(cwd, base = DEFAULT_BASE) {
384
+ let root;
385
+ try { root = (await git(cwd, ["rev-parse", "--show-toplevel"])).trim(); } catch { throw new CliError("USAGE", "Run nodii-dev test affected inside a git repository.", 2); }
386
+ let mergeBase;
387
+ try { mergeBase = (await git(root, ["merge-base", "HEAD", base])).trim(); } catch {
388
+ throw new CliError("IMPACT_BASE_MISSING", `No merge base with ${base}: fetch it (git fetch origin main) or pass --base REF.`, 2);
389
+ }
390
+ const changed = new Set([
391
+ ...lines(await git(root, ["diff", "--name-only", "--no-renames", mergeBase])),
392
+ ...lines(await git(root, ["ls-files", "--others", "--exclude-standard"])),
393
+ ]);
394
+ const files = new Set(lines(await git(root, ["ls-files", "--cached", "--others", "--exclude-standard", "--deduplicate"])));
395
+ // A deleted file is in the diff but not on disk: keep it for the graph, never read it.
396
+ return { root, mergeBase, changed: [...changed].sort(), files };
397
+ }
398
+
399
+ /** The whole analysis for the worktree at CWD. */
400
+ export async function affected(cwd, { base = DEFAULT_BASE, maxLight = DEFAULT_MAX_LIGHT, fullScript = "test" } = {}) {
401
+ const { root, mergeBase, changed, files } = await changeSet(cwd, base);
402
+ const cache = new Map();
403
+ const read = async (path) => {
404
+ if (!cache.has(path)) cache.set(path, readFile(join(root, path), "utf8"));
405
+ return cache.get(path);
406
+ };
407
+ const present = [...files].filter((file) => !/(?:^|\/)node_modules\//.test(file));
408
+ const { importers } = await importGraph(present, read);
409
+ const sources = [];
410
+ for (const file of present.filter((path) => CODE.test(path))) {
411
+ try { sources.push([file, await read(file)]); } catch { /* deleted or unreadable */ }
412
+ }
413
+ const fileSet = new Set(present);
414
+ const { tests, full } = selectTests(changed, { importers, files: fileSet, sources });
415
+ const jobs = await planJobs({ tests, full, files: fileSet, read, fullScript });
416
+ const size = full.length || jobs.some((job) => job.full) || tests.length > maxLight ? "heavy" : "light";
417
+ return { root, base, mergeBase, changed, tests, full, jobs, size, maxLight };
418
+ }
419
+
420
+ // ─── command ────────────────────────────────────────────────────────────────
421
+ const human = (result) => {
422
+ const out = [`${result.changed.length} changed file(s) against ${result.base} (merge base ${result.mergeBase.slice(0, 12)}).`];
423
+ if (result.full.length) {
424
+ out.push("Full suite: the change reaches every test.");
425
+ for (const item of result.full) out.push(` ${item.path}: ${item.reason}`);
426
+ } else if (!result.tests.length) out.push("No test is affected by this change.");
427
+ else {
428
+ out.push(`${result.tests.length} affected test file(s), ${result.size} slot:`);
429
+ for (const test of result.tests) out.push(` ${test}`);
430
+ }
431
+ for (const job of result.jobs) out.push(`run${job.dir ? ` in ${job.dir}` : ""}: ${job.command}`);
432
+ if (result.ran) for (const ran of result.ran) out.push(`${ran.code === 0 ? "passed" : `failed (exit ${ran.code})`}: ${ran.command}`);
433
+ return out.join("\n");
434
+ };
435
+
436
+ /** One job through the heavy-slot queue at its size, output streamed. */
437
+ export function runJob(job, { root, size, spawnImpl = spawn, argv = heavySlotArgv } = {}) {
438
+ return new Promise((resolve) => {
439
+ const [file, args] = argv(["--size", size, "--", "/bin/sh", "-c", job.command]);
440
+ const child = spawnImpl(file, args, { cwd: job.dir ? join(root, job.dir) : root, stdio: ["ignore", "inherit", "inherit"] });
441
+ child.on("error", () => resolve(127));
442
+ child.on("close", (code, signal) => resolve(code ?? (signal ? 128 : 1)));
443
+ });
444
+ }
445
+
446
+ export async function testCommand(action, rest, flags = {}, { analyse = affected, run = runJob, readPolicy } = {}) {
447
+ if (action !== "affected") throw new CliError("USAGE", TEST_USAGE, 2);
448
+ if (rest.length) throw new CliError("USAGE", `test affected takes no arguments, got: ${rest.join(" ")}. ${TEST_USAGE}`, 2);
449
+ const base = flags.base && flags.base !== true ? String(flags.base) : DEFAULT_BASE;
450
+ const maxLight = flags["max-light"] === undefined ? DEFAULT_MAX_LIGHT : Number(flags["max-light"]);
451
+ if (!Number.isInteger(maxLight) || maxLight < 0) throw new CliError("USAGE", "--max-light needs a whole number of test files.", 2);
452
+ let fullScript = "test";
453
+ if (readPolicy) {
454
+ try {
455
+ const root = (await execFileAsync("git", ["rev-parse", "--show-toplevel"])).stdout.trim();
456
+ fullScript = (await readPolicy(root))?.tests?.full ?? "test";
457
+ } catch { /* no policy file: the `test` script is the full suite */ }
458
+ }
459
+ const result = await analyse(process.cwd(), { base, maxLight, fullScript });
460
+ if (flags.run) {
461
+ result.ran = [];
462
+ for (const job of result.jobs) {
463
+ const code = await run(job, { root: result.root, size: result.size });
464
+ result.ran.push({ dir: job.dir, command: job.command, code });
465
+ if (code !== 0) return { payload: result, human, exitCode: code };
466
+ }
467
+ }
468
+ return { payload: result, human, exitCode: 0 };
469
+ }
470
+
package/dist/lanes.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { readPolicy } from "./repo-policy.js";
1
2
  import { execFile } from "node:child_process";
2
3
  import { readFile, realpath, writeFile } from "node:fs/promises";
3
4
  import { isAbsolute } from "node:path";
@@ -821,6 +822,8 @@ export async function laneCommand(action, args, flags, deps = {}) {
821
822
  ...(checkDeps.reviewer ? { reviewer: checkDeps.reviewer } : {}),
822
823
  ...(checkDeps.picker ? { picker: checkDeps.picker } : {}),
823
824
  ...(checkDeps.now ? { now: checkDeps.now } : {}),
825
+ // hub-401: the policy file names the full-suite script a gate may not run per lane.
826
+ fullScript: checkDeps.fullScript ?? (await readPolicy(context.worktree).then((policy) => policy?.tests?.full).catch(() => null)) ?? "test",
824
827
  });
825
828
  // AGENT-HARNESS-61: an agent here without the lane's config gets no managed
826
829
  // hooks. Reported, never blocking: the check itself cannot fix a process.
@@ -17,7 +17,8 @@ export const POLICY_FILE = "nodii.repo.yaml";
17
17
  export const SCHEMA_VERSION = 1;
18
18
  export const DOCS_LAYOUTS = ["standard", "drive", "existing"];
19
19
  export const CI_PR_MODES = ["none", "affected", "full"];
20
- export const CI_FULL_TRIGGERS = ["weekly", "dispatch", "pr", "push", "release", "label"];
20
+ // `scheduled`: a cron more often than weekly, such as the twice-daily full suite of hub-401.
21
+ export const CI_FULL_TRIGGERS = ["weekly", "scheduled", "dispatch", "pr", "push", "release", "label"];
21
22
  // MW4-31.1. pre-launch.md is optional, so it is not listed.
22
23
  export const STANDARD_DOCS = ["docs/README.md", "docs/open.md", "docs/answered.md", "docs/architecture/", "docs/runbooks/", "docs/reports/", "docs/archive/"];
23
24
 
@@ -152,7 +153,9 @@ export function validatePolicy(policy) {
152
153
  const perPush = pr !== "none" || (fullOk && (full.includes("pr") || full.includes("push")));
153
154
  if (perPush && !named.length) errors.push("ci.required / ci.reporting: a repository that runs PR or push CI must name which checks are required and which only report (MW3-22)");
154
155
  if (Array.isArray(required) && Array.isArray(reporting)) for (const name of required) if (reporting.includes(name)) errors.push(`ci: "${name}" is both required and reporting (MW3-22)`);
155
- if (pr === "none" && fullOk && !perPush && !(full.includes("weekly") && full.includes("dispatch"))) errors.push("ci.full: a weekly repository must run its full suite on weekly and dispatch (MW3-15)");
156
+ if (pr === "none" && fullOk && !perPush && !((full.includes("weekly") || full.includes("scheduled")) && full.includes("dispatch"))) errors.push("ci.full: a repository without PR CI must run its full suite on a schedule (weekly or scheduled) and on dispatch (MW3-15)");
157
+ // hub-401: a repository whose PRs run only the affected tests still runs the whole suite somewhere.
158
+ if (pr === "affected" && fullOk && !full.some((item) => ["weekly", "scheduled", "release"].includes(item))) errors.push("ci.full: a repository whose PRs run only the affected tests must run its full suite on a schedule or a release");
156
159
  }
157
160
 
158
161
  if (isObject(policy.review)) {
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 { VALUE_FLAGS } from "./impact.js";
17
18
  import { heavySlotArgv } from "./heavy.js";
18
19
 
19
20
  const execFileAsync = promisify(execFile);
@@ -73,7 +74,9 @@ export const privateStore = (cwd) => ({
73
74
  export function runGate(command, cwd, { argv = heavySlotArgv } = {}) {
74
75
  return new Promise((resolve) => {
75
76
  let tail = "";
76
- const [file, args] = argv(["/bin/sh", "-c", command]);
77
+ // `nodii-dev test affected --run` takes a slot sized to the change itself (hub-401): around it, a
78
+ // heavy slot would hold the large size for a small change.
79
+ const [file, args] = selfSizedGate(command) ? ["/bin/sh", ["-c", command]] : argv(["/bin/sh", "-c", command]);
77
80
  const child = spawn(file, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
78
81
  const keep = (chunk) => {
79
82
  process.stderr.write(chunk);
@@ -86,6 +89,50 @@ export function runGate(command, cwd, { argv = heavySlotArgv } = {}) {
86
89
  });
87
90
  }
88
91
 
92
+ /** A gate that is one `nodii-dev test affected … --run` call, which queues its own jobs at their size. */
93
+ export function selfSizedGate(command) {
94
+ const text = String(command ?? "").trim();
95
+ if (/&&|\|\||;|\||\$\(|`|\n/.test(text)) return false;
96
+ const words = text.split(/\s+/);
97
+ const at = words.findIndex((word) => /(?:^|\/)nodii-dev(?:\.js)?$/.test(word));
98
+ if (at === -1 || words.slice(0, at).some((word) => !/^(?:[A-Z_][A-Z0-9_]*=\S*|node|bun|npx|bunx)$/.test(word))) return false;
99
+ const rest = words.slice(at + 1).filter((word) => !word.startsWith("-"));
100
+ return rest[0] === "test" && rest[1] === "affected" && words.includes("--run");
101
+ }
102
+
103
+ /**
104
+ * hub-401: a gate that runs the repository's whole test suite. Per lane and per push only the affected
105
+ * tests run (`nodii-dev test affected --run`); the full suite runs in the twice-daily CI and the release gate.
106
+ * FULL_SCRIPT is the policy file's tests.full script.
107
+ */
108
+ export function fullSuiteGate(command, fullScript = "test") {
109
+ const text = String(command ?? "").trim();
110
+ const scripts = new Set(["test", "t", fullScript]);
111
+ for (const part of text.split(/&&|\|\||;/).map((x) => x.trim()).filter(Boolean)) {
112
+ let words = part.split(/\s+/).filter((word) => !/^[A-Z_][A-Z0-9_]*=/.test(word) && !/^(?:[0-9]?>|\|)/.test(word));
113
+ // `npx vitest`, `bunx jest`, `pnpm exec vitest run`: the tool they start.
114
+ for (;;) {
115
+ const first = (words[0] ?? "").split("/").pop();
116
+ if (["npx", "bunx", "pnpx"].includes(first)) words = words.slice(1).filter((word, i) => i > 0 || !word.startsWith("-"));
117
+ else if (["npm", "pnpm", "yarn"].includes(first) && ["exec", "dlx"].includes(words.find((word, i) => i > 0 && !word.startsWith("-")))) words = words.slice(words.findIndex((word) => ["exec", "dlx"].includes(word)) + 1);
118
+ else break;
119
+ while (words[0]?.startsWith("-")) words = words.slice(1);
120
+ }
121
+ const [tool, ...args] = words;
122
+ const name = (tool ?? "").split("/").pop();
123
+ // Operands: not a flag, and not the value of one (`--timeout 30000`, `--config ./jest.config.mjs`).
124
+ const operands = args.filter((word, i) => !word.startsWith("-") && !(i > 0 && (VALUE_FLAGS.has(args[i - 1]) || /^\d+$/.test(word))));
125
+ if (["npm", "pnpm", "yarn", "bun"].includes(name)) {
126
+ const [sub, script] = operands;
127
+ if (["run", "run-script"].includes(sub) && scripts.has(script) && operands.length === 2) return true;
128
+ if (sub === "test" && name === "bun") { if (operands.length === 1) return true; continue; }
129
+ if (scripts.has(sub) && operands.length === 1) return true;
130
+ }
131
+ if (["vitest", "jest"].includes(name) && operands.filter((word) => word !== "run").length === 0) return true;
132
+ }
133
+ return false;
134
+ }
135
+
89
136
  /** The content a receipt and a review cover: the diff itself, so uncommitted changes count too. */
90
137
  export const diffDigest = (text) => createHash("sha256").update(text).digest("hex");
91
138
 
@@ -342,7 +389,7 @@ export function spawnReviewer({ command, args, env, cwd, input, timeoutMs }, { a
342
389
  }, timeoutMs);
343
390
  };
344
391
  // 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();
392
+ if (runEnv.NODII_HEAVY_SLOT || runEnv.NODII_HEAVY_SLOT_HELD === "1" || file === command) start();
346
393
  child.stdout.on("data", (chunk) => { stdout += chunk; });
347
394
  child.stderr.on("data", (chunk) => {
348
395
  stderr = (stderr + chunk).slice(-4000);
@@ -877,13 +924,16 @@ const errorCheck = (check, error, iterationCount, inputs) => ({ check, outcome:
877
924
  * caller saves the round (saveLoop) once it is kept: still looping, or
878
925
  * recorded; a run that records nothing leaves the loop where it was.
879
926
  */
880
- export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, picker = pickByAgent, now, exceptions = exceptionFiles, templates = codeConnectUnits }) {
927
+ export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, picker = pickByAgent, now, exceptions = exceptionFiles, templates = codeConnectUnits, fullScript = "test" }) {
881
928
  const critical = flags.critical === true;
882
929
  const maxIterations = flags["max-iterations"] === undefined ? MAX_ITERATIONS : Number(flags["max-iterations"]);
883
930
  if (!Number.isInteger(maxIterations) || maxIterations < 1 || maxIterations > 100)
884
931
  throw new CliError("USAGE", "--max-iterations needs a whole number from 1 to 100.", 2);
885
932
  const gates = [flags.gate ?? []].flat();
886
- if (gates.some((x) => typeof x !== "string" || !x.trim())) throw new CliError("USAGE", "--gate needs a command, e.g. --gate 'npm test'.", 2);
933
+ if (gates.some((x) => typeof x !== "string" || !x.trim())) throw new CliError("USAGE", "--gate needs a command, e.g. --gate 'nodii-dev test affected --run'.", 2);
934
+ const whole = flags["full-suite"] === true ? [] : gates.filter((command) => fullSuiteGate(command, fullScript));
935
+ if (whole.length)
936
+ throw new CliError("GATE_FULL_SUITE", `Gate ${whole.map((command) => `\`${command}\``).join(", ")} runs the whole test suite. A lane runs only the tests its change reaches (MW2-20; hub-401): use --gate 'nodii-dev test affected --run', which also sizes the slot to the change. The full suite runs in the twice-daily CI and the release gate; pass --full-suite only when the change needs it (a release, or test infrastructure itself).`, 2, { gates: whole });
887
937
  const changed = await gatesReceipt(gates, { cwd, current, store, diff, run: gate, ...(now ? { now } : {}) });
888
938
  if (!changed.text.trim()) throw new CliError("LANE_DIFF_EMPTY", `${ref}: this worktree has no change against origin/main, so there is nothing to review.`, 1);
889
939
  const runtime = lane.launch?.runtime === "codex" ? "codex" : "claude";
package/dist/watchdog.js CHANGED
@@ -398,9 +398,23 @@ export async function sweepWatchdog({
398
398
 
399
399
  const xml = (value) => String(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
400
400
 
401
- export function launchdPlist({ runtime, entry, config, interval, stdoutPath, stderrPath }) {
401
+ /**
402
+ * hub-251: launchd starts a job with PATH=/usr/bin:/bin:/usr/sbin:/sbin, where
403
+ * a lane runtime such as `claude` (~/.local/bin) or `codex` is not found, so a
404
+ * resume-due lane's relaunch failed with `Executable not found in $PATH`. The
405
+ * plist carries the installing shell's PATH, plus the directory of the runtime
406
+ * that runs the CLI.
407
+ */
408
+ export function watchdogPath(envPath = process.env.PATH, runtime = process.execPath) {
409
+ const dirs = [dirname(runtime), ...String(envPath ?? "").split(":"), "/usr/bin", "/bin", "/usr/sbin", "/sbin"];
410
+ // A package runner's own bins (npx's _npx cache, node_modules/.bin) are left out: they are temporary.
411
+ const kept = dirs.filter((dir) => dir && dir.startsWith("/") && !dir.includes("/node_modules/") && !dir.includes("/_npx/"));
412
+ return [...new Set(kept)].join(":");
413
+ }
414
+
415
+ export function launchdPlist({ runtime, entry, config, interval, stdoutPath, stderrPath, path = watchdogPath(undefined, runtime) }) {
402
416
  const args = [runtime, entry, "watchdog", "sweep", "--json"].map((value) => `<string>${xml(value)}</string>`).join("");
403
- return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${WATCHDOG_LABEL}</string><key>ProgramArguments</key><array>${args}</array><key>EnvironmentVariables</key><dict><key>NODII_DEV_CONFIG_PATH</key><string>${xml(config)}</string></dict><key>RunAtLoad</key><true/><key>StartInterval</key><integer>${interval}</integer><key>ProcessType</key><string>Background</string><key>StandardOutPath</key><string>${xml(stdoutPath)}</string><key>StandardErrorPath</key><string>${xml(stderrPath)}</string></dict></plist>\n`;
417
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${WATCHDOG_LABEL}</string><key>ProgramArguments</key><array>${args}</array><key>EnvironmentVariables</key><dict><key>NODII_DEV_CONFIG_PATH</key><string>${xml(config)}</string><key>PATH</key><string>${xml(path)}</string></dict><key>RunAtLoad</key><true/><key>StartInterval</key><integer>${interval}</integer><key>ProcessType</key><string>Background</string><key>StandardOutPath</key><string>${xml(stdoutPath)}</string><key>StandardErrorPath</key><string>${xml(stderrPath)}</string></dict></plist>\n`;
404
418
  }
405
419
 
406
420
  export async function installWatchdog({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.129",
3
+ "version": "0.6.131",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {