@nodii/dev 0.6.177 → 0.6.179

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
@@ -595,7 +595,9 @@ blocks, silently when satisfied (AGENT-HARNESS-15):
595
595
  `docker compose down -v` or volume deletes on stacks the run didn't create;
596
596
  deploy/apply without a `GO deploy <sha>` grant; shell writes outside the
597
597
  worktree (redirects, `tee`, `cp`, `mv`, `rm`, `mkdir`, `touch` …; temp space
598
- is fine) and mutating `git -C` into another checkout; Edit/Write outside the
598
+ is fine; a `$NAME` or `${NAME}` in the path is expanded from the command's
599
+ own assignments, then the environment, before the check, NODII-DEV-CLI-211)
600
+ and mutating `git -C` into another checkout; Edit/Write outside the
599
601
  worktree, outside owned paths or on generated files. One exception
600
602
  (hub-548): an edit to a generated Surface (`*.surface.generated.tsx`)
601
603
  is allowed when it only adds or changes keyed `@handrolled <KEY>: ...` /
@@ -700,8 +702,8 @@ nodii-dev lane resume KEY [--override --reason TEXT]
700
702
  # that is not yet old enough to be dead: one process per
701
703
  # lane (the coordinator's own heartbeats do not count)
702
704
  nodii-dev lane resume KEY --if-changed
703
- # OFF unless NODII_DEV_RESUME_IF_CHANGED=1 (see "Switched-off
704
- # lane features"); off, it refuses RESUME_IF_CHANGED_OFF.
705
+ # On unless NODII_DEV_RESUME_IF_CHANGED=0 (see "Lane feature
706
+ # switches"); off, it refuses RESUME_IF_CHANGED_OFF.
705
707
  # NODII-DEV-CLI-191: resume only when what blocks the lane
706
708
  # changed since its last resume: each PR wait's state, head
707
709
  # and merge commit (gh), each issue wait's status and each
@@ -715,14 +717,15 @@ nodii-dev lane resume KEY --if-changed
715
717
  # lane whose work is landed (MW1-30.1: its changed paths
716
718
  # match origin/main) before deploy is refused as
717
719
  # LANDED_NOT_DONE and never stopped: landed is not done
718
- # (MW1-28), so it goes on to deploy and the dev check. With
719
- # NODII_DEV_SAME_SESSION_RESUME=1, every resume
720
+ # (MW1-28), so it goes on to deploy and the dev check. Unless
721
+ # NODII_DEV_SAME_SESSION_RESUME=0, every resume
720
722
  # continues the dead run's own session when this machine has
721
723
  # its log and the lane stayed on its account (`claude
722
724
  # --resume`, `codex exec resume`), with a prompt of its last
723
725
  # conclusion, what changed and the claim-and-fix directive,
724
726
  # never the full Freeze; otherwise it starts fresh with the
725
- # Freeze as before
727
+ # Freeze as text (each pinned clause once, the Clause map as
728
+ # ID-and-gist lines) and the log tail's events one line each
726
729
  nodii-dev lane check KEY [--gate CMD ...] [--critical] [--max-iterations N] [--picker agent]
727
730
  # from the lane's worktree: the rules, Figma and code checks (DEV-REV) over
728
731
  # the diff against origin/main, tracked and untracked; --gate runs the gates
@@ -979,15 +982,16 @@ when `stop_hook_active`); Codex passes it through its managed dispatcher.
979
982
  Before that, in a lane session (a `lane-*.json` identity), the same hook holds
980
983
  the stop while the lane's done check is not recorded (NODII-DEV-CLI-8), even
981
984
  after an earlier block: it reads the lane from Dev and answers `Lane KEY: done
982
- check not recorded. Continue the Task: STEP.` By default a blocked step, an
983
- open wait or a heartbeat note that starts "blocked" or "WAITING:" lets the stop
984
- through, except where leeway covers the blocker (MW1-12.6). With
985
- `NODII_DEV_BLOCKED_NOT_EXIT=1` (NODII-DEV-CLI-191; off until its clause is in
986
- force, as lane questions were, DEC-0503), BLOCKED is not an exit:
985
+ check not recorded. Continue the Task: STEP.` BLOCKED is not an exit
986
+ (NODII-DEV-CLI-191; ratified 18 Nov, on unless `NODII_DEV_BLOCKED_NOT_EXIT=0`):
987
987
  only a typed human gate lets the stop through. The gates
988
988
  are a wait on an operator question (`Q-n`), a decision (`DEC-n`), a release or
989
989
  launch day; a wait on a `steward-*` lane; or a latest heartbeat typed
990
- `WAITING: human-gate totp|steward|spend: WHAT THE PERSON MUST DO`. Any other
990
+ `WAITING: human-gate totp|steward|coordinator|spend: WHAT THE PERSON MUST DO`.
991
+ `coordinator` is for a coordinator-only step that leeway may not reach, such
992
+ as uploading an operator-approved lock-change decision (MW1 1.33, DEC-0508).
993
+ When a launched run ends on it, the supervisor reports the end to the machine's
994
+ coordinator as a lane message (MW1-12.11). Any other
991
995
  blocker, such as a blocked step, a PR, an issue, another lane, or an untyped
992
996
  BLOCKED or WAITING note, holds the stop. The answer then names the blocker and
993
997
  says to claim it with `lane leeway` (MW1-12.6), fix it with the lane's
@@ -1628,6 +1632,8 @@ To recover a machine, in order:
1628
1632
 
1629
1633
  ```
1630
1634
  nodii-dev coordinator start --machine NAME
1635
+ nodii-dev coordinator gather --objective "<current focus>" --picker agent
1636
+ nodii-dev coordinator gather --show
1631
1637
  nodii-dev lane resume --host-lost
1632
1638
  nodii-dev doctor
1633
1639
  ```
@@ -1799,12 +1805,18 @@ continuations included, the supervisor heartbeats its run every
1799
1805
  runtime that is alive but writes nothing gets no heartbeat from the supervisor,
1800
1806
  so it goes Quiet at 15 minutes and Orphan at 45 (MW1-36). A write to the
1801
1807
  session's Claude transcript (`<profile>/projects/<worktree>/<session>.jsonl`,
1802
- and its subagents' transcripts) counts as one too. The same tick is the lane's
1808
+ and its subagents' transcripts) counts as one too. So does a tool call that is
1809
+ still running: a long command writes nothing until it ends, so while the
1810
+ runtime has recorded a call's start and not its end (a Claude `tool_use` with no
1811
+ `tool_result`, a Codex `item.started` with no `item.completed`), the supervisor
1812
+ keeps beating for at most 2 hours of silence, with the note `a tool call is
1813
+ still running; last write <time>`. A call that hangs longer goes Quiet and then
1814
+ Orphan (MW1-34, MW1-36). The same tick is the lane's
1803
1815
  harness heartbeat (`POST /lanes/KEY/heartbeat` with `source: "hook"`), which
1804
1816
  keeps Dev's `stuck` meaningful, and the run heartbeat's note ends `last
1805
- activity <time>` (NODII-DEV-CLI-191). This lighter tracking is off unless
1806
- `NODII_DEV_STOP_ONLY_HEARTBEAT=1` (see "Switched-off lane features"); off, the
1807
- harness registers `hook lane-heartbeat` on every tool call and on `Stop` as
1817
+ activity <time>` (NODII-DEV-CLI-191, MW1-34). This lighter tracking is on
1818
+ unless `NODII_DEV_STOP_ONLY_HEARTBEAT=0` (see "Lane feature switches"); at `0`,
1819
+ the harness registers `hook lane-heartbeat` on every tool call and on `Stop` as
1808
1820
  before, and neither the supervisor nor `hook nudge-pre` beats the lane. On, no
1809
1821
  hook process runs on every tool call for it: the harness's `hook lane-heartbeat`
1810
1822
  is registered on `Stop` only. A session with no lane supervisor (no `NODII_DEV_RUN_ID`) is beaten from
@@ -1984,18 +1996,21 @@ ask and, when Dev has no such ask, as a leeway, and `--leeway` goes straight to
1984
1996
  the leeway. `lane asks [--machine M] [--state S] [--lane KEY] [--cursor C]
1985
1997
  [--limit N]` lists asks.
1986
1998
 
1987
- ### Switched-off lane features (NODII-DEV-CLI-191)
1999
+ ### Lane feature switches (NODII-DEV-CLI-191)
1988
2000
 
1989
- These features ship off by default until their clauses are in Dev's rulebook,
1990
- as lane questions (`NODII_DEV_LANE_ASKS`) and BLOCKED is not an exit
1991
- (`NODII_DEV_BLOCKED_NOT_EXIT`) did. The clauses are drafted on NODII-DEV-CLI-191
1992
- for a Docs change; when a clause is in force, its default flips. Each
1993
- is on only when its variable is exactly `1`, in the environment of the process
1994
- that does the work: the coordinator's for `lane resume`, the lane session's for
1995
- hooks, and the harness's for `harness update`.
2001
+ Each NODII-DEV-CLI-191 lane feature has its own switch, read in the
2002
+ environment of the process that does the work: the coordinator's for
2003
+ `lane resume`, the lane session's for hooks, and the harness's for
2004
+ `harness update`.
1996
2005
 
1997
- | Variable | Feature | Off (the default) |
2006
+ All seven are ruled: four in MW1 1.30 (MW1-12.10, MW1-102, MW1-102.1 and
2007
+ MW1-38.16; the operator's "ratify 191", 18 Nov) and three in MW1 1.32
2008
+ (MW1-66, MW1-12.11 and MW1-34; DEC-0506). They are on by default; the variable
2009
+ set to exactly `0` turns one off.
2010
+
2011
+ | Variable | Feature (on by default) | With `=0` |
1998
2012
  |---|---|---|
2013
+ | `NODII_DEV_BLOCKED_NOT_EXIT` | BLOCKED is not an exit: only a typed human gate ends a run early | A BLOCKED lane ends its run as before, except where leeway covers it (MW1-12.6) |
1999
2014
  | `NODII_DEV_RESUME_IF_CHANGED` | `lane resume --if-changed` | Refused `RESUME_IF_CHANGED_OFF`; resume without it |
2000
2015
  | `NODII_DEV_SAME_SESSION_RESUME` | A resume continues the dead run's own session with a short prompt | A resume starts a fresh session with the Freeze |
2001
2016
  | `NODII_DEV_SUBAGENT_BUDGET` | The subagent budget line in the launch brief, gather's next step and the resume prompt | No line |
@@ -2005,7 +2020,7 @@ hooks, and the harness's for `harness update`.
2005
2020
 
2006
2021
  ### Lane messages (NODII-DEV-CLI-191)
2007
2022
 
2008
- Off unless `NODII_DEV_LANE_MESSAGES=1` (see "Switched-off lane features").
2023
+ MW1-12.11. On unless `NODII_DEV_LANE_MESSAGES=0` (see "Lane feature switches").
2009
2024
 
2010
2025
  Lanes, stewards and the coordinator message each other by name: a lane by its
2011
2026
  lane key, a steward by its steward lane key, the machine's coordinator as
@@ -2013,7 +2028,10 @@ lane key, a steward by its steward lane key, the machine's coordinator as
2013
2028
  The sender is the session's own identity: the current lane (`NODII_DEV_LANE_KEY`),
2014
2029
  else this agent's Dev name. No flag names it (P-8). A delivered message is
2015
2030
  marked as information from another session, not an instruction: the lane's
2016
- Freeze and the rulebook still govern.
2031
+ Freeze and the rulebook still govern. A coordinator messages only its own
2032
+ machine's lanes (MW1-37.3): `lane message` from a coordinator to a lane Dev
2033
+ places on another machine, or on none, is refused `COORDINATOR_OTHER_MACHINE`
2034
+ and records nothing.
2017
2035
 
2018
2036
  Dev keeps the durable record: the message is a comment on the recipient lane's
2019
2037
  issue (a message to the coordinator goes on the sending lane's issue; `--issue
@@ -2283,3 +2301,18 @@ is denied. It exits `2`, which makes Claude Code block the call. The post-hook
2283
2301
  best-effort logs the write and never blocks; it exits `2` only for
2284
2302
  `WRITE_OUT_OF_SCOPE`, after the write is logged, so the agent sees it. Per D1433, Codex remains read-only
2285
2303
  for Figma; this package does not write to Figma itself.
2304
+
2305
+ ### Coordinator Gather
2306
+
2307
+ `coordinator gather` uses the caller's live coordinator run and its repository
2308
+ grants from Dev. The first call needs `--objective`; later calls may reuse the
2309
+ stored focus. With `--picker agent`, it prints the trigger shortlist and an exact
2310
+ follow-up command for recording the chosen document codes. Without that flag it
2311
+ uses the local picker, with the same agent fallback as lane Gather. `--delta`
2312
+ keeps previously searched documents; `--show` reads the stored map.
2313
+
2314
+ Dev stores the Clause map on the coordinator run. SessionStart restores it at
2315
+ startup and after compaction, and asks the coordinator to Gather again with the
2316
+ operator's current focus. An ended run, another agent's run or a replaced machine
2317
+ coordinator cannot read or replace that map. Missing maps prompt a first Gather;
2318
+ other failures remain errors.
package/dist/cli.js CHANGED
@@ -166,9 +166,8 @@ Usage: nodii-dev <command> [options] [--json]
166
166
  # can't be used again
167
167
  issues list|show|create|update|claim|release
168
168
  issues group --objective TEXT [--service ID ...] [--min N>=10] [--max N]
169
- # OFF unless NODII_DEV_ISSUES_GROUP=1 (NODII-DEV-CLI-191: off until its clause
170
- # is in Dev's rulebook); off, it refuses ISSUES_GROUP_OFF and calls nothing. On:
171
- # NODII-DEV-CLI-191 (MW1-21.1): propose a lane's issue set from the open
169
+ # On unless NODII_DEV_ISSUES_GROUP=0 (MW1-66; =0 refuses ISSUES_GROUP_OFF and
170
+ # calls nothing). NODII-DEV-CLI-191 (MW1-21.1): propose a lane's issue set from the open
172
171
  # issues: titles that share the objective's terms (rarer terms weigh more)
173
172
  # plus the dependency chain (an issue naming a picked one), with each
174
173
  # issue's reason, the repos they touch and the lane launch line; under
@@ -389,6 +388,8 @@ Usage: nodii-dev <command> [options] [--json]
389
388
  # lane answer|defer, lane leeway grant|refuse, lane resume|close|stop pass.
390
389
  # The gate runs only where coordinator start wrote coordinator.json beside
391
390
  # the config, and passes when Dev cannot be read
391
+ coordinator gather [--objective TEXT] [--picker agent] [--delta] [--show]
392
+ # record or restore the live coordinator run’s Clause map
392
393
  coordinator start --machine NAME [--account RUNTIME:PROFILE ...]
393
394
  # register this machine's one watched coordinator; refuses a live second;
394
395
  # registers each --account and reports every account's usage; a background
@@ -550,10 +551,9 @@ Usage: nodii-dev <command> [options] [--json]
550
551
  # reaches it as an amendment it acknowledges with lane gather --delta;
551
552
  # lane ask withdraw <ask id> takes the question back
552
553
  lane message <to> --body TEXT|--body-file FILE [--issue ISSUE]
553
- # OFF unless NODII_DEV_LANE_MESSAGES=1 (off until its clause is in Dev's
554
- # rulebook): lane message and lane inbox then refuse LANE_MESSAGES_OFF and
555
- # call nothing, and no hook delivers from an inbox file. On:
556
- # NODII-DEV-CLI-191: message a lane, a steward (its lane key) or the
554
+ # On unless NODII_DEV_LANE_MESSAGES=0 (MW1-12.11; =0: lane message and lane
555
+ # inbox refuse LANE_MESSAGES_OFF and call nothing, and no hook delivers from
556
+ # an inbox file). NODII-DEV-CLI-191: message a lane, a steward (its lane key) or the
557
557
  # coordinator by name. Dev keeps the record: a comment on the recipient
558
558
  # lane's issue (the coordinator's: the sending lane's; --issue overrides),
559
559
  # headed "[lane message] from <sender> to <to> · <time> · id <id>". When <to>
@@ -561,7 +561,9 @@ Usage: nodii-dev <command> [options] [--json]
561
561
  # The sender is the session's identity: its lane, else its Dev agent's name.
562
562
  # A lane gets an unread message at its next tool call (nudge-pre), its next
563
563
  # stop (the Stop hook holds it) or its next continuation (the supervisor
564
- # puts it ahead of the prompt), Claude and Codex alike
564
+ # puts it ahead of the prompt), Claude and Codex alike. A coordinator
565
+ # messages only its own machine's lanes (MW1-37.3): a lane on another
566
+ # machine, or on none, is refused COORDINATOR_OTHER_MACHINE, nothing recorded
565
567
  lane inbox [<key>] [--all] # the unread messages (--all: every one), marked read; also pulls in Dev's
566
568
  # record of messages sent from another machine
567
569
  lane answer <ask id> --text TEXT # the coordinator (or staff) answers; Dev delivers it as that amendment
@@ -593,8 +595,8 @@ Usage: nodii-dev <command> [options] [--json]
593
595
  # then moves the lane to another account of its runtime with headroom, saying so,
594
596
  # or refuses ACCOUNT_EXHAUSTED; --profile naming another account still goes
595
597
  lane resume <key> --if-changed
596
- # OFF unless NODII_DEV_RESUME_IF_CHANGED=1 (off until its clause is in Dev's
597
- # rulebook); off, it refuses RESUME_IF_CHANGED_OFF and resumes nothing. On:
598
+ # On unless NODII_DEV_RESUME_IF_CHANGED=0; with =0 it refuses
599
+ # RESUME_IF_CHANGED_OFF and resumes nothing. On:
598
600
  # NODII-DEV-CLI-191: resume only when what blocks the lane changed since its
599
601
  # last resume (a PR's state, head or merge; an issue's status; a blocking
600
602
  # lane's status; a leeway; an amendment), else print BLOCKERS_UNCHANGED and
@@ -603,9 +605,9 @@ Usage: nodii-dev <command> [options] [--json]
603
605
  # by the MW1-28 exit that fits.
604
606
  # A lane whose work is landed (MW1-30.1) before deploy is refused as
605
607
  # LANDED_NOT_DONE and never stopped: landed is not done (MW1-28), so it goes
606
- # on to deploy and the dev check. With NODII_DEV_SAME_SESSION_RESUME=1, a resume
608
+ # on to deploy and the dev check. Unless NODII_DEV_SAME_SESSION_RESUME=0, a resume
607
609
  # continues the dead run's own session when this machine has its log, with a
608
- # short prompt instead of the Freeze; off (the default) it starts fresh as before
610
+ # short prompt instead of the Freeze; with =0 it starts fresh as before
609
611
  lane resume --host-lost [--min-free-gb N] [--stagger-seconds N]
610
612
  # coordinator, after a reboot: resume every host_lost lane on this machine
611
613
  # in priority order under its own key, agent, worktree and branch. No
@@ -749,9 +751,10 @@ Refusals of leeway, lane questions, the coordinator's items, lane finish, lane r
749
751
  LANE_NOTES_FULL The grant's or answer's note would take the lane past its note cap. Next: fold superseded amendments into one note first (lane amendments fold)
750
752
  MACHINE_REQUIRED The caller coordinates no machine, so Dev cannot tell whose items or asks to list. Next: pass --machine NAME|ID
751
753
  LANE_ASKS_OFF lane ask, lane answer or lane asks while lane questions are off (the default). Next: write the question as an issue comment or a heartbeat note; NODII_DEV_LANE_ASKS=1 turns the commands on
752
- RESUME_IF_CHANGED_OFF lane resume --if-changed while it is off (the default). Next: resume without it, as before; NODII_DEV_RESUME_IF_CHANGED=1 turns it on
753
- LANE_MESSAGES_OFF lane message or lane inbox while lane messages are off (the default). Next: write to the other lane as a comment on its issue; NODII_DEV_LANE_MESSAGES=1 turns them on
754
- ISSUES_GROUP_OFF issues group while it is off (the default). Next: choose the lane's issue set by hand with issues list; NODII_DEV_ISSUES_GROUP=1 turns it on
754
+ RESUME_IF_CHANGED_OFF lane resume --if-changed while NODII_DEV_RESUME_IF_CHANGED=0 turns it off. Next: resume without it, as before; unset the variable to turn it back on
755
+ LANE_MESSAGES_OFF lane message or lane inbox while NODII_DEV_LANE_MESSAGES=0 turns lane messages off. Next: write to the other lane as a comment on its issue, or unset NODII_DEV_LANE_MESSAGES
756
+ COORDINATOR_OTHER_MACHINE lane message from a coordinator to a lane Dev places on another machine, or on none (MW1-37.3); nothing is recorded. Next: that machine's coordinator messages it
757
+ ISSUES_GROUP_OFF issues group while NODII_DEV_ISSUES_GROUP=0 turns it off. Next: choose the lane's issue set by hand with issues list, or unset NODII_DEV_ISSUES_GROUP
755
758
  ASK_NOT_FOUND Dev has no lane ask with this id. Next: list them with lane asks
756
759
  ASK_DECIDED The ask is already answered or withdrawn. Next: read it with lane asks --lane KEY
757
760
  LANE_NOT_FINISHED lane close before the lane's own agent marked the lane finished. Next: the lane runs lane finish KEY --reason TEXT --evidence REF
@@ -0,0 +1,65 @@
1
+ import { CliError, devRequest, encode, readConfig } from "./core.js";
2
+ import { agentFallbackReason, coordinatorGatherPayload, gatherDeadline, gatherText, pickDocuments, pickerModelName, warmPicker, withPickLock } from "./gather.js";
3
+ import { findCoordinatorRun } from "./starting.js";
4
+
5
+ const list = (value) => String(value ?? "").split(",").map((item) => item.trim()).filter(Boolean);
6
+ const quote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
7
+ const role = "Coordinator role (MW1-94.1); operator's current focus: ";
8
+
9
+ export async function coordinatorGather(flags, {
10
+ request = devRequest, config = readConfig, findRun = findCoordinatorRun,
11
+ picker = pickDocuments, warm = warmPicker, lock = withPickLock,
12
+ } = {}) {
13
+ if (flags.picker !== undefined && flags.picker !== "agent") throw new CliError("USAGE", "--picker accepts agent; omit it to use the local picker.", 2);
14
+ const documents = list(flags.documents);
15
+ if (Boolean(flags.shortlist) !== Boolean(documents.length) || (flags.shortlist && flags.picker !== "agent"))
16
+ throw new CliError("USAGE", "Record an agent pick with --picker agent --shortlist ID --documents CODE[,CODE].", 2);
17
+ const deadline = gatherDeadline();
18
+ const timed = (method, path, body) => request(method, path, body, { signal: deadline.signal });
19
+ try {
20
+ const current = await config();
21
+ const agent = (await timed("GET", `/api/v1/agents/${encode(current.agentId)}`)).data;
22
+ const run = await findRun(flags.machine ?? agent.machineId, { request: timed, agentId: current.agentId });
23
+ if (!run || run.kind !== "coordinator" || run.status !== "running" || run.ownerAgentId !== current.agentId)
24
+ throw new CliError("COORDINATOR_RUN_REQUIRED", "Start this machine's coordinator run before Gather.", 1);
25
+ const base = `/api/v1/coordinator-runs/${encode(run.id)}`;
26
+ if (flags.show) {
27
+ const payload = coordinatorGatherPayload(await timed("GET", `${base}/gather`));
28
+ return { payload, human: (p) => gatherText(p, p.data.objective) };
29
+ }
30
+ const context = (await timed("GET", `${base}/gather-context`)).data;
31
+ const focus = typeof flags.objective === "string" ? flags.objective.trim() : "";
32
+ const objective = focus ? (focus.startsWith(role) ? focus : role + focus) : context.objective;
33
+ if (!objective) throw new CliError("GATHER_OBJECTIVE_MISSING", "Pass --objective with the operator's current focus for the first coordinator Gather.", 2);
34
+ if (objective.length > 20_000) throw new CliError("USAGE", "The Gather objective exceeds 20,000 characters.", 2);
35
+ const shortlist = flags.shortlist ? { shortlistId: flags.shortlist, triggers: [] }
36
+ : (await timed("POST", "/api/v1/rules/shortlist", { objective, repos: context.repos, paths: [], components: ["coordinator"] })).data;
37
+ const next = {
38
+ command: `nodii-dev coordinator gather --picker agent --shortlist ${shortlist.shortlistId} --documents CODE[,CODE] --objective ${quote(objective)}${flags.delta ? " --delta" : ""}${flags.machine ? ` --machine ${quote(flags.machine)}` : ""}`,
39
+ fill: "Pick every applicable document code from the triggers; Dev adds forced documents.",
40
+ };
41
+ const offered = (fallback) => ({
42
+ payload: { data: { recorded: false, picker: "agent", ...shortlist, objective, next, ...(fallback ? { fallback } : {}) } },
43
+ human: () => [`Trigger shortlist ${shortlist.shortlistId}`, objective, ...shortlist.triggers.map((t) => `${t.code}: ${t.sentence}`), next.command].join("\n"),
44
+ });
45
+ if (flags.picker === "agent" && !flags.shortlist) return offered();
46
+ let picked = { documents, model: "agent" };
47
+ if (flags.picker !== "agent") {
48
+ try {
49
+ picked = await deadline.hold(() => lock(run.id, async () => {
50
+ await warm();
51
+ return picker({ objective, files: [], triggers: shortlist.triggers.map((t) => ({ code: t.code, trigger: t.sentence, forcedBy: t.forcedBy })) });
52
+ }));
53
+ } catch (error) {
54
+ const reason = agentFallbackReason(error);
55
+ if (!reason) throw error;
56
+ return offered(reason);
57
+ }
58
+ }
59
+ const payload = coordinatorGatherPayload(await timed("POST", `${base}/gather`, {
60
+ objective, document_codes: picked.documents, shortlist_id: shortlist.shortlistId,
61
+ picker: flags.picker === "agent" ? "agent" : picked.model ?? pickerModelName(), mode: flags.delta ? "delta" : "full",
62
+ }));
63
+ return { payload, human: (p) => gatherText(p, objective) };
64
+ } finally { deadline.clear(); }
65
+ }
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.177";
7
+ export const VERSION = "0.6.179";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
package/dist/gather.js CHANGED
@@ -594,7 +594,7 @@ export function gatherText(payload, objective = "", reasons = {}) {
594
594
  // NODII-DEV-CLI-191: the objective and lane notes are in the contract
595
595
  // above; the header no longer repeats them as JSON (4.7 KB on a long lane).
596
596
  void objective;
597
- const lines = ["Lane contract", data.laneContract ?? LANE_CONTRACT, "", "Clause map"];
597
+ const lines = [data.coordinator ? "Coordinator context" : "Lane contract", data.laneContract ?? LANE_CONTRACT, "", "Clause map"];
598
598
  for (const notice of data.notices ?? []) lines.push(`Notice: ${notice}`);
599
599
  const documents = new Map();
600
600
  for (const clause of data.clauses ?? []) {
@@ -677,3 +677,10 @@ async function setupEmbedModel({ check, inspect, exec }) {
677
677
  if (!ready.modelMatches) throw new CliError("EMBED_MODEL_VERSION_MISMATCH", `The Ollama registry serves ${EMBED_MODEL} at ${ready.digest ?? "an unknown digest"}, but this CLI pins ${EMBED_MODEL_DIGEST}: the pin is stale, so pulling again will not help. Update nodii-dev to a release with the current pin.`, 1, { ...ready, stalePin: true });
678
678
  return { changed: [EMBED_MODEL], ...ready };
679
679
  }
680
+
681
+ /** Decode the coordinator REST shape for the shared Gather renderer. */
682
+ export function coordinatorGatherPayload(value) {
683
+ if (Array.isArray(value)) return value.map(coordinatorGatherPayload);
684
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()), coordinatorGatherPayload(item)]));
685
+ return value;
686
+ }
package/dist/hooks.js CHANGED
@@ -240,9 +240,9 @@ const LANE_ENDED = new Set(["LANE_NOT_FOUND", "LANE_TERMINAL"]);
240
240
  // beat. A session with no supervisor beats from nudge-pre, which already runs
241
241
  // on each tool call, at most once per 5 minutes (Dev marks a lane quiet at 15).
242
242
  export const HEARTBEAT_UNSUPERVISED_INTERVAL_MS = 5 * 60_000;
243
- // Off unless NODII_DEV_STOP_ONLY_HEARTBEAT=1 until its clause is in force: the
244
- // harness then keeps the tool-call beat as before, and neither the supervisor
245
- // nor nudge-pre beats the lane.
243
+ // MW1-34 (MW1 1.32): on unless NODII_DEV_STOP_ONLY_HEARTBEAT=0. At 0 the harness
244
+ // keeps the tool-call beat as before, and neither the supervisor nor nudge-pre
245
+ // beats the lane.
246
246
  export const heartbeatSettingsSnippet = (env = process.env) => {
247
247
  const beat = [{ hooks: [{ type: "command", command: "nodii-dev hook lane-heartbeat" }] }];
248
248
  return { hooks: laneSwitchOn("stopOnlyHeartbeat", env) ? { Stop: beat } : { PostToolUse: beat, Stop: beat } };
@@ -29,9 +29,9 @@ import { assertLaneSwitchOn, laneSwitchOn } from "./lane-switches.js";
29
29
  * a Claude or Codex lane gets them as its next turn. `lane inbox` also reads
30
30
  * Dev's record, so a message sent from another machine still arrives.
31
31
  *
32
- * Off unless NODII_DEV_LANE_MESSAGES=1 until its clause is in force: the
33
- * commands refuse LANE_MESSAGES_OFF and call nothing, and no hook or
34
- * continuation delivers from an inbox file.
32
+ * MW1-12.11 (MW1 1.32): on unless NODII_DEV_LANE_MESSAGES=0. At 0 the commands
33
+ * refuse LANE_MESSAGES_OFF and call nothing, and no hook or continuation
34
+ * delivers from an inbox file.
35
35
  */
36
36
  const MESSAGES_INSTEAD = "Write to the other lane as a comment on its issue, as before.";
37
37
 
@@ -226,6 +226,11 @@ export async function laneMessageCommand(args, flags, {
226
226
  let issueKey = flagText(flags, "issue");
227
227
  if (!coordinator) {
228
228
  lane = (await request("GET", `/api/v1/lanes/${encode(to)}`)).data;
229
+ // MW1-37.3: a coordinator acts only on its own machine's lanes. A lane Dev
230
+ // places on no machine is not known to be its own, so it is refused too.
231
+ const sender = senderLane ? null : await thisAgent();
232
+ if (sender?.role === "coordinator" && (!lane?.machineId || lane.machineId !== sender.machineId))
233
+ throw new CliError("COORDINATOR_OTHER_MACHINE", `Lane ${to} does not run on this coordinator's machine${lane?.machineId ? "" : " (Dev places it on none)"}, and a coordinator acts only on its own machine's lanes (MW1-37.3). Nothing was recorded. That machine's coordinator messages it.`, 1);
229
234
  issueKey ??= laneIssueKey(lane);
230
235
  } else if (!issueKey && senderLane) {
231
236
  issueKey = laneIssueKey((await request("GET", `/api/v1/lanes/${encode(senderLane)}`)).data);
@@ -1,12 +1,12 @@
1
1
  import { execFile as execFileCallback, spawn as nodeSpawn } from "node:child_process";
2
- import { readdirSync, statSync } from "node:fs";
2
+ import { closeSync, fstatSync, openSync, readSync, readdirSync, statSync } from "node:fs";
3
3
  import { open, readFile, writeFile } from "node:fs/promises";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
  import { promisify } from "node:util";
7
7
  import { profilePath, recordExhaustedAccount } from "./accounts.js";
8
8
  import { CliError, devRequest, encode } from "./core.js";
9
- import { inboxForContinuation } from "./lane-messages.js";
9
+ import { inboxForContinuation, laneMessageCommand } from "./lane-messages.js";
10
10
  import { laneSwitchOn } from "./lane-switches.js";
11
11
  import { redactRunText } from "./runs.js";
12
12
  import { processStartedAt, saveWatchedRun, watchdogRunDir } from "./watchdog.js";
@@ -277,12 +277,13 @@ export function laneBlockedReason(lane) {
277
277
  // NODII-DEV-CLI-191: only a typed human gate ends a lane's run. A wait on
278
278
  // an operator question, a decision, a release (the steward judges it) or launch
279
279
  // day, a wait on a steward lane, or a latest heartbeat typed
280
- // `WAITING: human-gate totp|steward|spend: ...`. Every other blocker (a blocked
280
+ // `WAITING: human-gate totp|steward|coordinator|spend: ...` (coordinator:
281
+ // MW1 1.33, DEC-0508, a coordinator-only step leeway may not reach). Every other blocker (a blocked
281
282
  // step, a PR, an issue, another lane, an untyped BLOCKED or WAITING note) is
282
283
  // the lane's to claim and fix.
283
284
  const HUMAN_GATE_WAITS = new Set(["question", "decision", "release", "launch_day"]);
284
- const HUMAN_GATE_NOTE = /^\s*(?:BLOCKED|WAITING)\s*:?\s*human[- ]gate\s*\(?\s*(totp|steward|spend)\b/i;
285
- export const HUMAN_GATE_COMMAND = (laneKey) => `nodii-dev lane heartbeat ${laneKey} --note "WAITING: human-gate totp|steward|spend: <what the person must do>"`;
285
+ const HUMAN_GATE_NOTE = /^\s*(?:BLOCKED|WAITING)\s*:?\s*human[- ]gate\s*\(?\s*(totp|steward|coordinator|spend)\b/i;
286
+ export const HUMAN_GATE_COMMAND = (laneKey) => `nodii-dev lane heartbeat ${laneKey} --note "WAITING: human-gate totp|steward|coordinator|spend: <what the person must do>"`;
286
287
 
287
288
  const latestNote = (lane) => String((lane?.events ?? [])
288
289
  .filter((event) => event.type === "heartbeat" && event.metadata?.source !== "hook" && String(event.metadata?.note ?? "").trim())
@@ -294,7 +295,7 @@ const latestNote = (lane) => String((lane?.events ?? [])
294
295
  * Null when the quota is unknown.
295
296
  */
296
297
  export function subagentBudgetLine(quota, env = process.env) {
297
- // Off unless NODII_DEV_SUBAGENT_BUDGET=1 until its clause is in force.
298
+ // Ratified (18 Nov): on unless NODII_DEV_SUBAGENT_BUDGET=0.
298
299
  if (!laneSwitchOn("subagentBudget", env)) return null;
299
300
  const n = Number(quota);
300
301
  if (quota == null || !Number.isInteger(n) || n < 0) return null;
@@ -303,6 +304,12 @@ export function subagentBudgetLine(quota, env = process.env) {
303
304
  return `You have ${n} subagent slot${n === 1 ? "" : "s"} (the Agent tool; MW1-38.15). Fan independent work out to them as MW1-11 says.`;
304
305
  }
305
306
 
307
+ /** The latest heartbeat note when it types the coordinator gate (MW1-12.10, DEC-0508), or null. */
308
+ export function coordinatorGateNote(lane) {
309
+ const note = latestNote(lane);
310
+ return HUMAN_GATE_NOTE.exec(note)?.[1]?.toLowerCase() === "coordinator" ? note.slice(0, 500) : null;
311
+ }
312
+
306
313
  /** The typed human gate that ends a lane's run, or null (NODII-DEV-CLI-191). */
307
314
  export function laneHumanGate(lane) {
308
315
  for (const wait of lane?.waits ?? []) {
@@ -315,13 +322,11 @@ export function laneHumanGate(lane) {
315
322
  }
316
323
 
317
324
  /**
318
- * NODII-DEV-CLI-191: "BLOCKED is not an exit" is ahead of its clause (the
319
- * draft on NODII-DEV-CLI-191 waits for its
320
- * Docs change), so it ships off, as lane questions did (DEC-0503):
321
- * NODII_DEV_BLOCKED_NOT_EXIT=1 turns it on. Off, a BLOCKED lane ends its run as
322
- * before, except where leeway covers it (MW1-12.6, DEC-0486).
325
+ * NODII-DEV-CLI-191: "BLOCKED is not an exit" (ratified, "ratify 191", 18 Nov)
326
+ * is on by default; NODII_DEV_BLOCKED_NOT_EXIT=0 turns it off. Off, a BLOCKED
327
+ * lane ends its run as before, except where leeway covers it (MW1-12.6, DEC-0486).
323
328
  */
324
- export const blockedIsNotExit = (env = process.env) => env?.NODII_DEV_BLOCKED_NOT_EXIT === "1";
329
+ export const blockedIsNotExit = (env = process.env) => laneSwitchOn("blockedNotExit", env);
325
330
 
326
331
  /** Why a lane's run may end before its done check, or null. */
327
332
  export const laneRunEnds = (lane, env = process.env) => (blockedIsNotExit(env) ? laneHumanGate(lane) : laneBlockedReason(lane));
@@ -345,6 +350,10 @@ export function continueTaskMessage(laneKey, lane, env = process.env) {
345
350
  return `Lane ${laneKey}: done check not recorded. Continue the Task: ${step}.`;
346
351
  }
347
352
 
353
+ /** A lane message to this machine's coordinator, recorded on the ended run's own lane issue (MW1-12.11). */
354
+ const messageCoordinator = (laneKey, body, { env = process.env } = {}) =>
355
+ laneMessageCommand(["coordinator"], { body }, { env: { ...env, NODII_DEV_LANE_KEY: laneKey } });
356
+
348
357
  /**
349
358
  * The lane's Dev status and whether its done check is recorded. Unreadable
350
359
  * reads as unfinished.
@@ -352,9 +361,9 @@ export function continueTaskMessage(laneKey, lane, env = process.env) {
352
361
  async function laneProgress(request, laneKey) {
353
362
  try {
354
363
  const lane = (await request("GET", `/api/v1/lanes/${encode(laneKey)}`)).data;
355
- return { status: lane?.status ?? null, finished: doneCheckRecorded(lane), blocked: laneBlockedReason(lane), finishEvidence: laneFinishEvidence(lane) };
364
+ return { status: lane?.status ?? null, finished: doneCheckRecorded(lane), blocked: laneBlockedReason(lane), finishEvidence: laneFinishEvidence(lane), coordinatorGate: coordinatorGateNote(lane) };
356
365
  } catch {
357
- return { status: null, finished: false, blocked: null, finishEvidence: null };
366
+ return { status: null, finished: false, blocked: null, finishEvidence: null, coordinatorGate: null };
358
367
  }
359
368
  }
360
369
 
@@ -398,9 +407,10 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
398
407
  markTerminal = markWatchedTerminal,
399
408
  now = () => new Date(),
400
409
  markExhausted = recordExhaustedAccount,
410
+ tellCoordinator = messageCoordinator,
401
411
  } = {}) {
402
412
  const worktree = await inspect(worktrees);
403
- const { status, finished, blocked, finishEvidence } = await laneProgress(request, laneKey);
413
+ const { status, finished, blocked, finishEvidence, coordinatorGate } = await laneProgress(request, laneKey);
404
414
  const clean = exitCode === 0 && !signal;
405
415
  const exitRef = signal ? `signal ${signal}` : String(exitCode ?? -1);
406
416
  const exited = signal ? `was ended by ${signal}` : `exited with code ${exitCode ?? -1}`;
@@ -471,6 +481,10 @@ export async function reportLaneExit({ runId, laneKey, exitCode, signal, worktre
471
481
  const laneFinish = finished && clean && !blocked && worktree.state === "clean" && finishEvidence
472
482
  ? await finishLane(request, laneKey, `The lane's done check was recorded and its process exited 0 with its worktree ${worktree.state}; recorded by the lane supervisor on exit.`, finishEvidence)
473
483
  : null;
484
+ // MW1-12.10 (DEC-0508): a run that ends on a coordinator-only step is
485
+ // reported to the coordinator. A report that fails changes nothing else.
486
+ if (outcome === "blocked" && coordinatorGate)
487
+ await tellCoordinator(laneKey, `Lane ${laneKey}'s run ended on a coordinator-only step (MW1-12.10, DEC-0508): ${coordinatorGate}. The lane resumes when that step is done.`).catch(() => {});
474
488
  await markTerminal(runId).catch(() => {});
475
489
  return { outcome, exitCode: exitCode ?? null, signal: signal ?? null, worktree: worktree.state, laneStatus: status, ...(laneFinish ? { laneFinish } : {}), ...(accountFailure ? { accountFailure } : {}) };
476
490
  }
@@ -570,6 +584,73 @@ export function runActivity({ logPath, transcripts = () => [], now = Date.now })
570
584
  };
571
585
  }
572
586
 
587
+ /**
588
+ * MW1-34 with MW1-36: a running tool call writes nothing until it ends, so a
589
+ * long command would read as a hung runtime. The supervisor beats through a
590
+ * call that is still open, for at most this much silence; a call that hangs
591
+ * longer still goes Quiet and then Orphan.
592
+ */
593
+ export const OPEN_CALL_MAX_MS = 2 * 60 * 60_000;
594
+ const OPEN_CALL_TAIL_BYTES = 256 * 1024;
595
+
596
+ /**
597
+ * Whether the tail of a Claude session transcript or a Codex `--json` stream
598
+ * holds a tool call that started and has not ended: a Claude `tool_use` with
599
+ * no `tool_result` for its id, or a Codex `item.started` with no
600
+ * `item.completed`. Unparseable lines (a tail cut mid-line) are skipped.
601
+ */
602
+ export function openToolCall(text, runtime) {
603
+ const open = new Set();
604
+ for (const line of String(text ?? "").split("\n")) {
605
+ if (!line) continue;
606
+ let entry;
607
+ try { entry = JSON.parse(line); } catch { continue; }
608
+ if (runtime === "codex") {
609
+ const id = entry?.item?.id;
610
+ if (!id) continue;
611
+ if (entry.type === "item.started") open.add(id);
612
+ else if (entry.type === "item.completed") open.delete(id);
613
+ continue;
614
+ }
615
+ const content = Array.isArray(entry?.message?.content) ? entry.message.content : [];
616
+ for (const part of content) {
617
+ if (entry.type === "assistant" && part?.type === "tool_use" && part.id) open.add(part.id);
618
+ else if (entry.type === "user" && part?.type === "tool_result" && part.tool_use_id) open.delete(part.tool_use_id);
619
+ }
620
+ }
621
+ return open.size > 0;
622
+ }
623
+
624
+ // Synchronous, unlike readTail: the tick sends its beats before it returns, so none follows the exit report.
625
+ const readTailSync = (path, bytes = OPEN_CALL_TAIL_BYTES) => {
626
+ let fd;
627
+ try {
628
+ fd = openSync(path, "r");
629
+ const size = fstatSync(fd).size;
630
+ const length = Math.min(size, bytes);
631
+ const buffer = Buffer.alloc(length);
632
+ readSync(fd, buffer, 0, length, size - length);
633
+ return buffer.toString("utf8");
634
+ } catch { return null; } finally {
635
+ if (fd !== undefined) try { closeSync(fd); } catch {}
636
+ }
637
+ };
638
+
639
+ /**
640
+ * The last write of a runtime whose tool call is still open, when that write
641
+ * is at most OPEN_CALL_MAX_MS ago; else null. Codex's stream is the run log;
642
+ * Claude's is the session's own transcript (a subagent's open call is the
643
+ * session's open Agent call).
644
+ */
645
+ export function openCallSince({ logPath, transcripts = () => [], runtime, now = Date.now }) {
646
+ const path = runtime === "codex" ? logPath : transcripts()[0];
647
+ if (!path) return null;
648
+ const last = mtimeOf(path);
649
+ if (last === null || now() - last > OPEN_CALL_MAX_MS) return null;
650
+ const tail = readTailSync(path);
651
+ return tail !== null && openToolCall(tail, runtime) ? last : null;
652
+ }
653
+
573
654
  /** Claude's transcript of a session in a lane worktree, and its subagents' transcripts. */
574
655
  export function claudeTranscripts(invocation, sessionId, { home = homedir() } = {}) {
575
656
  const project = join(invocation.env?.CLAUDE_CONFIG_DIR ?? join(home, ".claude"), "projects", String(invocation.cwd).replace(/[^A-Za-z0-9]/g, "-"));
@@ -629,9 +710,12 @@ export async function superviseLane({
629
710
  if (state !== "running") return;
630
711
  // Both beats leave inside the tick, so none follows the exit report.
631
712
  const at = activity();
632
- if (at !== null) {
633
- request("POST", `/api/v1/runs/${encode(runId)}/heartbeat`, { note: `lane runtime pid ${child.pid} alive (supervisor ${process.pid}); last activity ${new Date(at).toISOString()}` }).catch(() => {});
634
- // Off (NODII_DEV_STOP_ONLY_HEARTBEAT unset), the harness's tool-call hook beats the lane instead.
713
+ // A tool call still running writes nothing; it beats for at most OPEN_CALL_MAX_MS of silence.
714
+ const open = at === null ? openCallSince({ logPath, transcripts, runtime: invocation.command }) : null;
715
+ if (at !== null || open !== null) {
716
+ const note = at !== null ? `last activity ${new Date(at).toISOString()}` : `a tool call is still running; last write ${new Date(open).toISOString()}`;
717
+ request("POST", `/api/v1/runs/${encode(runId)}/heartbeat`, { note: `lane runtime pid ${child.pid} alive (supervisor ${process.pid}); ${note}` }).catch(() => {});
718
+ // At NODII_DEV_STOP_ONLY_HEARTBEAT=0 the harness's tool-call hook beats the lane instead.
635
719
  if (laneKey && laneSwitchOn("stopOnlyHeartbeat", env)) request("POST", `/api/v1/lanes/${encode(laneKey)}/heartbeat`, { via: "nodii-dev", source: "hook" }).catch(() => {});
636
720
  }
637
721
  // The session's transcript is found once its id is in the log.
@@ -1,14 +1,20 @@
1
1
  import { CliError } from "./core.js";
2
2
 
3
3
  /**
4
- * NODII-DEV-CLI-191 (the coordinator's instruction of 18 Nov, done as
5
- * NODII_DEV_LANE_ASKS and NODII_DEV_BLOCKED_NOT_EXIT were): the lane-orchestration
6
- * features whose clauses are drafted but not yet in Dev's rulebook ship off by
7
- * default. Each is on only when its variable is exactly "1"; off, it behaves as
8
- * before NODII-DEV-CLI-191. When a clause is in force (its version lands), its
9
- * default flips.
4
+ * NODII-DEV-CLI-191: the lane-orchestration features each have a switch.
5
+ *
6
+ * Ruled in MW1 1.30 (the operator's "ratify 191", 18 Nov: MW1-12.10, MW1-102,
7
+ * MW1-102.1, MW1-38.16) and MW1 1.32 (MW1-12.11 lane messages, MW1-34 the
8
+ * Stop-only heartbeat, MW1-66 issues group): on by default. The variable set to
9
+ * exactly "0" is the off-ramp.
10
+ *
11
+ * A switch outside RATIFIED_LANE_SWITCHES (none today) is off by default, on
12
+ * only when its variable is exactly "1" (the coordinator's instruction of 18 Nov
13
+ * 01:55Z, done as NODII_DEV_LANE_ASKS was).
10
14
  */
11
15
  export const LANE_SWITCHES = Object.freeze({
16
+ // "BLOCKED is not an exit": only a typed human gate ends a run early.
17
+ blockedNotExit: "NODII_DEV_BLOCKED_NOT_EXIT",
12
18
  // Amended MW1-102: resume only when a blocker changed.
13
19
  resumeIfChanged: "NODII_DEV_RESUME_IF_CHANGED",
14
20
  // "A resume continues the lane's own session".
@@ -23,10 +29,19 @@ export const LANE_SWITCHES = Object.freeze({
23
29
  stopOnlyHeartbeat: "NODII_DEV_STOP_ONLY_HEARTBEAT",
24
30
  });
25
31
 
26
- export const laneSwitchOn = (name, env = process.env) => env?.[LANE_SWITCHES[name]] === "1";
32
+ /** The switches whose clauses the operator ratified: on unless set to "0". */
33
+ export const RATIFIED_LANE_SWITCHES = Object.freeze(new Set(Object.keys(LANE_SWITCHES)));
34
+
35
+ export const laneSwitchOn = (name, env = process.env) => {
36
+ const value = env?.[LANE_SWITCHES[name]];
37
+ return RATIFIED_LANE_SWITCHES.has(name) ? value !== "0" : value === "1";
38
+ };
27
39
 
28
40
  /** Refuse `<CODE>` when the switch is off: `what` is off, `instead` says what to do meanwhile. */
29
41
  export function assertLaneSwitchOn(name, code, what, instead, env = process.env) {
30
42
  if (laneSwitchOn(name, env)) return;
31
- throw new CliError(code, `${what} is off: it ships off until its clause is in Dev's rulebook (NODII-DEV-CLI-191). ${instead} ${LANE_SWITCHES[name]}=1 turns it on.`, 1);
43
+ const variable = LANE_SWITCHES[name];
44
+ throw new CliError(code, RATIFIED_LANE_SWITCHES.has(name)
45
+ ? `${what} is off on this machine: ${variable}=0 turns it off (NODII-DEV-CLI-191). ${instead} Unset ${variable} to turn it back on.`
46
+ : `${what} is off: it ships off until its clause is in Dev's rulebook (NODII-DEV-CLI-191). ${instead} ${variable}=1 turns it on.`, 1);
32
47
  }
package/dist/nudges.js CHANGED
@@ -684,8 +684,8 @@ export async function transcriptToolUses(path) {
684
684
  * NODII-DEV-CLI-8 (hub-58, gate for AGENT-HARNESS-13): a lane session may not
685
685
  * stop before its done check is recorded. NODII-DEV-CLI-191: BLOCKED is not an
686
686
  * exit. A blocker the lane can claim and fix holds the stop; only a typed
687
- * human gate (`laneHumanGate`: operator TOTP, a steward-only step, spend, an
688
- * operator question or decision) lets it through. The lane is read fresh: the
687
+ * human gate (`laneHumanGate`: operator TOTP, a steward-only step, a
688
+ * coordinator-only step, spend, an operator question or decision) lets it through. The lane is read fresh: the
689
689
  * lane this hook call just read from Dev by key (`context.laneDetail`), else
690
690
  * one slim read here (hub-528). An unreadable lane lets the stop through.
691
691
  * The no-progress guard: a stop held NODII_DEV_STOP_STALL_LIMIT (2) times in a
@@ -737,9 +737,8 @@ export async function nudgeStop(payload, context, { lastText = lastAssistantText
737
737
  const text = await lastText(payload);
738
738
  if (claimsDone(text) && lane.status !== "on_dev")
739
739
  notes.push(`${lane.key} reads ${lane.status}, not on_dev: done means merged, deployed and verified live on dev (MW3). Run \`nodii-dev lane show ${lane.key}\`, and say what is left instead of "done"`);
740
- // NODII-DEV-CLI-191: a blocker is the lane's to fix, not to file and stop on.
741
- // NODII-DEV-CLI-191: with NODII_DEV_BLOCKED_NOT_EXIT=1 a blocker is the lane's to
742
- // fix, not to file and stop on; off, the ratified text (MW1-12.6, DEC-0486).
740
+ // NODII-DEV-CLI-191 (ratified 18 Nov): a blocker is the lane's to fix, not to
741
+ // file and stop on. With NODII_DEV_BLOCKED_NOT_EXIT=0, the MW1-12.6 text (DEC-0486).
743
742
  if (COULDNT.test(text) && blockedIsNotExit()) {
744
743
  const cited = text.match(ISSUE_KEY)?.[0];
745
744
  const gateLine = `. Stop only on a typed human gate (\`${HUMAN_GATE_COMMAND(lane.key)}\`)`;
package/dist/receipt.js CHANGED
@@ -146,12 +146,18 @@ const SECRET_FLAG = new RegExp(String.raw`(^|\s)(--?[\w-]*(?:token|secret|pass|p
146
146
  const URL_USER_INFO = /(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@]*(?::[^/\s@]*)?@/gi;
147
147
  const AUTH_SCHEME = /\b(bearer|basic|token)\s+[A-Za-z0-9._~+/=-]{8,}/gi;
148
148
  const TOKEN_SHAPED = /\b(?:gh[pousr]_[A-Za-z0-9]{10,}|github_pat_\w{10,}|sk-[\w-]{10,}|xox[abprs]-[\w-]{10,}|AKIA[0-9A-Z]{12,}|eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]*|[A-Fa-f0-9]{32,}|[A-Za-z0-9+/_-]{40,}={0,2})\b/g;
149
+ // NODII-DEV-CLI-213: a long repository path (`packages/dev/test/some-long-name`)
150
+ // fills the 40-character class too. A match is a path, not a token, when it has
151
+ // a slash and every segment between slashes is a lowercase word (letters, digits,
152
+ // `.`, `_` or `-`, with a letter). Random base64 is mixed case, so it still redacts.
153
+ const PATH_SEGMENT = /^[a-z0-9._-]*[a-z][a-z0-9._-]*$/;
154
+ const pathShaped = (match) => match.includes("/") && match.split("/").every((segment) => PATH_SEGMENT.test(segment));
149
155
  export const redactCommand = (command) => String(command)
150
156
  .replace(URL_USER_INFO, "$1<redacted>@")
151
157
  .replace(SECRET_FLAG, "$1$2 <redacted>")
152
158
  .replace(ANY_ASSIGNMENT, "$1$2=<redacted>")
153
159
  .replace(AUTH_SCHEME, "$1 <redacted>")
154
- .replace(TOKEN_SHAPED, "<redacted>");
160
+ .replace(TOKEN_SHAPED, (match) => (pathShaped(match) ? match : "<redacted>"));
155
161
 
156
162
  const many = (value) => (value === undefined ? [] : [value].flat().map(String));
157
163
  const ranAt = () => new Date().toISOString();
@@ -158,6 +158,96 @@ export function buildResumePrompt(data, sessionId, env = process.env) {
158
158
  ].join("\n");
159
159
  }
160
160
 
161
+ const KNOWN_FREEZE = new Set(["objective", "boundaries", "clauseMap", "pinnedClauses", "lookups", "unconfirmed", "laneDecisions"]);
162
+ const compactJson = (value) => JSON.stringify(value);
163
+ const nonEmpty = (value) => (Array.isArray(value) ? value.length > 0 : value && typeof value === "object" ? Object.keys(value).length > 0 : Boolean(value));
164
+
165
+ /**
166
+ * NODII-DEV-CLI-191 (the same-session resume and the start-context cut; MW1-102.1): the Freeze for a resume that starts a
167
+ * fresh session, as text. Each pinned clause appears once, in its fullest
168
+ * wording (its text, section or gist: the Freeze often holds the same
169
+ * truncated line twice); the Clause map is one `ID gist` line per clause. A
170
+ * field this does not know is kept as compact JSON, so nothing is dropped.
171
+ */
172
+ export function freezeText(freeze) {
173
+ if (!freeze || typeof freeze !== "object" || Array.isArray(freeze)) return printable(freeze);
174
+ const lines = [];
175
+ const objective = freeze.objective;
176
+ if (objective && typeof objective === "object") {
177
+ if (objective.ask) lines.push(`Objective: ${objective.ask}`);
178
+ const issue = objective.issue;
179
+ if (issue?.key) lines.push(`Issue: ${issue.key}${issue.title ? ` · ${issue.title}` : ""}${issue.bodyGist ? ` (${issue.bodyGist})` : ""}`);
180
+ if (objective.doneCheck) lines.push(`Done check: ${objective.doneCheck}`);
181
+ const notes = Array.isArray(objective.laneNotes) ? objective.laneNotes : [];
182
+ if (notes.length) lines.push("Lane notes:", ...notes.map((note) => `- ${note}`));
183
+ const rest = Object.fromEntries(Object.entries(objective).filter(([key]) => !["ask", "issue", "doneCheck", "laneNotes"].includes(key)));
184
+ if (nonEmpty(rest)) lines.push(`Objective, other fields: ${compactJson(rest)}`);
185
+ } else if (objective !== undefined) lines.push(`Objective: ${printable(objective)}`);
186
+ const repos = freeze.boundaries?.repos;
187
+ if (Array.isArray(repos) && repos.length) {
188
+ lines.push("Repositories:", ...repos.map((repo) => `- ${[repo.repo, repo.branch, repo.worktree].filter(Boolean).join(" · ")}${repo.readOnly ? " (read-only)" : ""}`));
189
+ const rest = Object.fromEntries(Object.entries(freeze.boundaries).filter(([key]) => key !== "repos"));
190
+ if (nonEmpty(rest)) lines.push(`Boundaries, other fields: ${compactJson(rest)}`);
191
+ } else if (freeze.boundaries !== undefined) lines.push(`Boundaries: ${compactJson(freeze.boundaries)}`);
192
+ const pinned = Array.isArray(freeze.pinnedClauses) ? freeze.pinnedClauses : [];
193
+ if (pinned.length) {
194
+ lines.push("Pinned ⚑ clauses (counter-instinct; each in force):");
195
+ for (const clause of pinned) {
196
+ const fullest = [clause.text, clause.section, clause.gist].filter((x) => typeof x === "string").sort((a, b) => b.length - a.length)[0] ?? "";
197
+ const where = [clause.documentCode && `${clause.documentCode} ${clause.documentVersion ?? ""}`.trim(), Array.isArray(clause.repos) && clause.repos.length ? clause.repos.join(", ") : null].filter(Boolean).join("; ");
198
+ lines.push(`- ${clause.clauseId}${where ? ` (${where})` : ""}: ${fullest}`);
199
+ }
200
+ }
201
+ const map = freeze.clauseMap;
202
+ if (map && typeof map === "object") {
203
+ const clauses = Array.isArray(map.clauses) ? map.clauses : [];
204
+ if (clauses.length) lines.push("Clause map (references; `nodii-dev rules show <ID>` prints a clause):", ...clauses.map((clause) => `- ${clause.clauseId} ${clause.gist ?? ""}`.trimEnd()));
205
+ if (Array.isArray(map.inForce) && map.inForce.length) lines.push(`In force: ${map.inForce.join(", ")}`);
206
+ if (Array.isArray(map.laneBase) && map.laneBase.length)
207
+ lines.push(`Lane base: ${map.laneBase.map((base) => `${base.documentCode} ${base.documentVersion}${base.clauses !== undefined ? ` (${base.clauses} clauses)` : ""}`).join("; ")}`);
208
+ if (Array.isArray(map.lookups) && map.lookups.length) lines.push(`Clause map lookups: ${compactJson(map.lookups)}`);
209
+ const rest = Object.fromEntries(Object.entries(map).filter(([key]) => !["clauses", "inForce", "laneBase", "lookups", "gatherId"].includes(key)));
210
+ if (map.gatherId) lines.push(`Gather: ${map.gatherId}`);
211
+ if (nonEmpty(rest)) lines.push(`Clause map, other fields: ${compactJson(rest)}`);
212
+ }
213
+ for (const key of ["lookups", "unconfirmed", "laneDecisions"])
214
+ if (nonEmpty(freeze[key])) lines.push(`${key}: ${compactJson(freeze[key])}`);
215
+ for (const [key, value] of Object.entries(freeze))
216
+ if (!KNOWN_FREEZE.has(key)) lines.push(`${compactJson({ [key]: value }).slice(1, -1)}`);
217
+ return lines.join("\n");
218
+ }
219
+
220
+ const textOf = (content) => (Array.isArray(content) ? content.filter((part) => part?.type === "text").map((part) => part.text).join(" ") : typeof content === "string" ? content : "");
221
+
222
+ /**
223
+ * The dead run's log tail for a fresh resume: each runtime JSON event as one
224
+ * line of what happened (the init event without its tool and command lists,
225
+ * a rate limit, what the model said, how the run ended). Other lines stay.
226
+ */
227
+ export function compactLogTail(tail) {
228
+ if (typeof tail !== "string") return printable(tail);
229
+ const out = [];
230
+ for (const line of tail.split("\n")) {
231
+ const trimmed = line.trim();
232
+ let event = null;
233
+ if (trimmed.startsWith("{")) try { event = JSON.parse(trimmed); } catch { event = null; }
234
+ if (!event || typeof event !== "object") { if (trimmed) out.push(line); continue; }
235
+ if (event.type === "system")
236
+ out.push(`[${event.subtype ?? "system"}${event.model ? ` model ${event.model}` : ""}${event.session_id ? ` session ${event.session_id}` : ""}]`);
237
+ else if (event.type === "rate_limit_event") {
238
+ const info = event.rate_limit_info ?? {};
239
+ out.push(`[rate limit: ${info.status ?? "?"} ${info.rateLimitType ?? ""}${info.resetsAt ? ` resets ${new Date(info.resetsAt * 1000).toISOString()}` : ""}]`);
240
+ } else if (event.type === "assistant" || event.type === "user") {
241
+ const said = textOf(event.message?.content).trim();
242
+ if (said) out.push(`${event.type}: ${said.slice(0, 2000)}`);
243
+ if (event.error) out.push(`[${event.type} error: ${event.error}]`);
244
+ } else if (event.type === "result")
245
+ out.push(`[result: ${[event.subtype, event.is_error ? "error" : null, event.terminal_reason, event.api_error].filter(Boolean).join(", ")}] ${String(event.result ?? "").slice(0, 2000)}`.trimEnd());
246
+ else out.push(trimmed.length > 500 ? `${trimmed.slice(0, 500)}…` : trimmed);
247
+ }
248
+ return out.join("\n");
249
+ }
250
+
161
251
  /** Build the complete recovery message passed to the fresh runtime over stdin. */
162
252
  export function buildRecoveryPrompt(data) {
163
253
  const { runId, laneKey } = validateData(data);
@@ -169,10 +259,10 @@ export function buildRecoveryPrompt(data) {
169
259
  "",
170
260
  `Last pushed commit:\n${printable(data.recovery?.lastPushedCommit)}`,
171
261
  "",
172
- `Freeze:\n${printable(data.recovery?.freeze)}`,
262
+ `Freeze:\n${freezeText(data.recovery?.freeze)}`,
173
263
  "",
174
264
  ...amendmentsSinceFreeze(data.lane, data.recovery?.freeze),
175
- `Dead run log tail:\n${printable(data.recovery?.logTail)}`,
265
+ `Dead run log tail:\n${compactLogTail(data.recovery?.logTail)}`,
176
266
  "",
177
267
  ].join("\n");
178
268
  }
@@ -383,8 +473,8 @@ export async function launchRecovery(payload, {
383
473
  const fresh = buildRecoveryInvocation(data, { env, home });
384
474
  // NODII-DEV-CLI-191: continue the dead run's own session when its log
385
475
  // names one and the lane stays on the same account (a session lives in its
386
- // profile); otherwise start fresh with the Freeze. Off unless
387
- // NODII_DEV_SAME_SESSION_RESUME=1 until its clause is in force.
476
+ // profile); otherwise start fresh with the Freeze. Ratified (18 Nov): on
477
+ // unless NODII_DEV_SAME_SESSION_RESUME=0.
388
478
  const sourceRunId = data.recovery?.sourceRunId;
389
479
  const sessionId = sourceRunId && !data.accountMove && laneSwitchOn("sameSessionResume", env)
390
480
  ? await session(join(root, sourceRunId, "process.log"), runtime).catch(() => null)
package/dist/safety.js CHANGED
@@ -318,6 +318,33 @@ function writeTargets(command) {
318
318
  return targets.map(closeParen).filter(Boolean);
319
319
  }
320
320
 
321
+ const VARIABLE = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g;
322
+
323
+ /** `$NAME` and `${NAME}` from the command's own assignments, else the environment; one it cannot resolve is left as written. */
324
+ function expandVars(text, vars, env = process.env) {
325
+ return String(text).replace(VARIABLE, (whole, braced, bare) => {
326
+ const name = braced ?? bare;
327
+ const value = vars.has(name) ? vars.get(name) : env[name];
328
+ return value === undefined ? whole : value;
329
+ });
330
+ }
331
+
332
+ /**
333
+ * NODII-DEV-CLI-211: the `NAME=value` and `export NAME=value` assignments in a
334
+ * command, in order, each value expanded by those before it (single quotes
335
+ * stay literal), so a variable set in the command cannot carry a write past
336
+ * the worktree guard.
337
+ */
338
+ function shellAssignments(command, env = process.env) {
339
+ const vars = new Map();
340
+ const assignment = /(?:^|[;&|\n(]\s*|\bexport\s+)([A-Za-z_][A-Za-z0-9_]*)=("[^"]*"|'[^']*'|[^\s;&|)]*)/g;
341
+ for (const [, name, raw] of String(command).matchAll(assignment)) {
342
+ const value = raw.replace(/^(["'])([\s\S]*)\1$/, "$2");
343
+ vars.set(name, raw.startsWith("'") ? value : expandVars(value, vars, env));
344
+ }
345
+ return vars;
346
+ }
347
+
321
348
  function outsideWorktree(target, context, relativeKnown) {
322
349
  let path = target;
323
350
  if (path === "~" || path.startsWith("~/")) path = join(homedir(), path.slice(1));
@@ -610,7 +637,8 @@ export function commandViolations(raw, context) {
610
637
  const other = gitOutsideWorktree(tokens, context);
611
638
  if (other) block("SAFETY_OTHER_WORKTREE", `git ${other.verb} in ${other.target} touches a checkout outside this lane's worktree${context.laneRoots?.length > 1 ? `s (${context.laneRoots.join(", ")})` : ` ${context.root}`}.`);
612
639
  const relativeKnown = !/(?:^|[;&|(\s])(?:cd|pushd)\s/.test(command);
613
- const outside = writeTargets(command).filter((target) => outsideWorktree(target, context, relativeKnown));
640
+ const vars = shellAssignments(command);
641
+ const outside = writeTargets(command).map((target) => expandVars(target, vars)).filter((target) => outsideWorktree(target, context, relativeKnown));
614
642
  if (outside.length)
615
643
  block("SAFETY_WRITE_OUTSIDE_WORKTREE", `Write blocked outside the lane worktree ${context.root}: ${[...new Set(outside)].join(", ")}. Use the worktree or a temp/scratch directory.`);
616
644
  }
@@ -12,7 +12,7 @@ import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/p
12
12
  import { basename, dirname, join } from "node:path";
13
13
  import { CliError, configPath, devRequest, encode, query, readConfig, requireFlag } from "./core.js";
14
14
  import { currentLane, regroundLane } from "./freeze.js";
15
- import { gatherText } from "./gather.js";
15
+ import { coordinatorGatherPayload, gatherText } from "./gather.js";
16
16
  import { laneAsksOn } from "./lane-asks.js";
17
17
  import { managedBehindText } from "./managed-version.js";
18
18
 
@@ -35,7 +35,10 @@ export async function activeSteward(agentId, { request = devRequest } = {}) {
35
35
  }
36
36
 
37
37
  /** What Dev records about this session. */
38
- export async function kindFromDev({ cwd = process.cwd(), env = process.env } = {}, { request = devRequest, config = readConfig } = {}) {
38
+ export async function kindFromDev({ cwd = process.cwd(), env = process.env } = {}, {
39
+ request = devRequest, config = readConfig,
40
+ findRun = async (...args) => (await import("./starting.js")).findCoordinatorRun(...args),
41
+ } = {}) {
39
42
  let current = null;
40
43
  try { current = await config(false); } catch {}
41
44
  const lane = current?.agentId ? await currentLane({ cwd }, { request, config }).catch(() => null) : null;
@@ -45,6 +48,11 @@ export async function kindFromDev({ cwd = process.cwd(), env = process.env } = {
45
48
  const steward = await activeSteward(current.agentId, { request }).catch(() => null);
46
49
  if (steward) return { kind: "steward", steward, source: `Dev steward registration ${steward.key} for this agent` };
47
50
  const agent = (await request("GET", `/api/v1/agents/${encode(current.agentId)}`).catch(() => null))?.data;
51
+ const coordinator = agent?.machineId
52
+ ? await findRun(agent.machineId, { request, agentId: current.agentId }).catch(() => null)
53
+ : null;
54
+ if (coordinator?.kind === "coordinator" && coordinator.status === "running" && coordinator.ownerAgentId === current.agentId)
55
+ return { kind: "coordinator", coordinator, source: `Dev coordinator run ${coordinator.id} for this agent and machine` };
48
56
  if (agent?.role === "coordinator") return { kind: "coordinator", source: "this agent is its machine's coordinator in Dev" };
49
57
  return { kind: "operator_assistant", source: "Dev has no lane, steward or coordinator record for this session" };
50
58
  }
@@ -172,6 +180,19 @@ export async function sessionStartText(payload, { managed = async () => null, re
172
180
  parts.push(result.shown ? `${context.trimEnd()}${pointer}` : `Freeze re-grounding: ${resolved.lane.key} has no initialized Freeze; run \`nodii-dev lane freeze show ${resolved.lane.key}\` (and \`nodii-dev lane gather show ${resolved.lane.key}\` for its Clause map) before continuing.`);
173
181
  } else if (resolved.kind === "lane" && compact)
174
182
  parts.push("Freeze re-grounding: no active Dev lane with initialized Freeze was available for this worktree; run `nodii-dev lane freeze show <key>` (and `nodii-dev lane gather show <key>` for its Clause map) before continuing.");
183
+ if (resolved.kind === "coordinator") {
184
+ const next = "Run `nodii-dev coordinator gather --picker agent --objective \"<the operator's current focus>\"` now (MW1-94.1).";
185
+ if (!resolved.coordinator) parts.push(`Clause map unavailable: start this machine's coordinator run. ${next}`);
186
+ else {
187
+ try {
188
+ const map = await request("GET", `/api/v1/coordinator-runs/${encode(resolved.coordinator.id)}/gather`);
189
+ parts.push(`${gatherText(coordinatorGatherPayload(map), map.data.objective)}\n${next}`);
190
+ } catch (error) {
191
+ if (error?.code !== "GATHER_NOT_FOUND") throw error;
192
+ parts.push(`Clause map: this coordinator run has no Gather yet. ${next}`);
193
+ }
194
+ }
195
+ }
175
196
  if (resolved.kind === "steward") {
176
197
  if (compact) {
177
198
  let context = "";
package/dist/starting.js CHANGED
@@ -364,6 +364,7 @@ export async function coordinatorCommand(action, flags, {
364
364
  // Only the CLI passes the watchdog's installer, so no caller touches launchd or systemd by default.
365
365
  installWatchdog = null,
366
366
  } = {}) {
367
+ if (action === "gather") return (await import("./coordinator-gather.js")).coordinatorGather(flags, { request, config, findRun });
367
368
  if (action === "heartbeat") {
368
369
  const result = await heartbeatLoop({
369
370
  machine: requireFlag(flags, "machine"),
package/dist/surface.js CHANGED
@@ -34,7 +34,7 @@ import { MIN_FIGMA_INTERVAL_MS, figmaRest } from "./figma-rest.js";
34
34
  import { createRenderer } from "./vendor/render-templates.mjs";
35
35
 
36
36
  /** Bumped whenever the emitted code changes shape for the same inputs. */
37
- export const GENERATOR_FORMAT = 39;
37
+ export const GENERATOR_FORMAT = 40;
38
38
  export const TREE_DIR = "docs/figma-ux-ds/figma/surface-trees";
39
39
  export const GENERATED_SUFFIX = ".surface.generated.tsx";
40
40
  /** Where every generated product page lives, as a git glob (NODII-DEV-CLI-77). */
@@ -87,7 +87,7 @@ export const catalogNode = (runtime = process) => (runtime.versions?.bun ? "node
87
87
  export function loadCatalog(root, { exec = execFileSync, runtime = process } = {}) {
88
88
  const script = [
89
89
  `const { productPageCatalog } = await import(${JSON.stringify(join(root, CATALOG_PATH))});`,
90
- "const rows = productPageCatalog.map((x) => ({ id: x.id, title: x.title, product: x.product, surfaceType: x.surfaceType, frontendRoute: x.frontendRoute ?? null, sourcePath: x.sourcePath, fileKey: x.figma?.fileKey ?? null, componentSetKey: x.figma?.componentSetKey ?? null, componentSetName: x.figma?.componentSetName ?? null, states: x.figma?.states ?? {} }));",
90
+ "const rows = productPageCatalog.map((x) => ({ id: x.id, title: x.title, product: x.product, surfaceType: x.surfaceType, frontendRoute: x.frontendRoute ?? null, sourcePath: x.sourcePath, fileKey: x.figma?.fileKey ?? null, componentSetKey: x.figma?.componentSetKey ?? null, componentSetName: x.figma?.componentSetName ?? null, states: x.figma?.states ?? {}, ...(x.figma?.figmaVersion ? { figmaVersion: String(x.figma.figmaVersion) } : {}), ...(x.figma?.pendingPublication ? { pendingPublication: true } : {}), ...(x.figma?.standalone ? { standalone: true } : {}) }));",
91
91
  "process.stdout.write(JSON.stringify(rows));",
92
92
  ].join("\n");
93
93
  let out;
@@ -274,6 +274,58 @@ function paints(list) {
274
274
  .map((p) => ({ variable: p.boundVariables?.color ? variableKey(p.boundVariables.color) : null, hex: hex(p.color, (p.opacity ?? 1) * (p.color?.a ?? 1)) }));
275
275
  }
276
276
 
277
+ const PUBLISHED_KEY = /^[0-9a-f]{40}$/;
278
+
279
+ /**
280
+ * The catalog's `figma.states` names each page state by the published component key of its
281
+ * variant (DESIGN-SYSTEM-582, SWAP-7cb36363): the join reads `entry.components[variant.id].key`
282
+ * and keeps the catalog's state name, never the variant's slug. It fails closed when the read
283
+ * set is not the row's, or a state key is not a variant of that set at the version read
284
+ * (NODII-DEV-CLI-180). Node-id locators stay readable for a draft that says
285
+ * `pendingPublication`, and for a catalog not yet migrated (no `figmaVersion`). The join
286
+ * happens here, inside the fetch, and the tree keeps only the state's name: no node id or
287
+ * variant key crosses into the committed tree or a later hop (MW8-20).
288
+ * Returns variant → state name, or null for a variant the catalog does not name.
289
+ */
290
+ function catalogStateJoin(entry, row, version) {
291
+ const doc = entry.document;
292
+ const named = Object.entries(row.states ?? {});
293
+ const where = `${row.componentSetName ?? row.id} at version ${version ?? "latest"}`;
294
+ const byKey = named.filter(([, ref]) => PUBLISHED_KEY.test(ref));
295
+ if (byKey.length === 0) {
296
+ if (row.figmaVersion && named.length && !row.pendingPublication)
297
+ throw new CliError("SURFACE_STATE_IDENTITY", `${row.componentSetName ?? row.id}: the catalog pins figmaVersion ${row.figmaVersion} but names its states by node id; name each state by its published variant key, or mark a draft row pendingPublication (DESIGN-SYSTEM-582, MW8-20)`, 1);
298
+ const nodeToState = new Map(named.map(([state, nodeId]) => [nodeId, state]));
299
+ return (variant) => nodeToState.get(variant.id) ?? null;
300
+ }
301
+ if (byKey.length !== named.length) {
302
+ const stray = named.filter(([, ref]) => !PUBLISHED_KEY.test(ref)).map(([state]) => state);
303
+ throw new CliError("SURFACE_STATE_IDENTITY", `${row.componentSetName ?? row.id}: states ${stray.join(", ")} are named by node id beside published keys; every state names its published variant key, or a draft row names node ids only and says pendingPublication (DESIGN-SYSTEM-582, MW8-20)`, 1);
304
+ }
305
+ const components = entry.components ?? {};
306
+ const ownKey = doc.type === "COMPONENT_SET" ? (entry.componentSets?.[doc.id]?.key ?? null) : (components[doc.id]?.key ?? null);
307
+ if (ownKey && row.componentSetKey && ownKey !== row.componentSetKey)
308
+ throw new CliError("SURFACE_STATE_KEY_UNRESOLVED", `${where}: the set read has key ${ownKey}, not the catalog's ${row.componentSetKey} (MW8-20)`, 1);
309
+ const variants = doc.type === "COMPONENT_SET" ? (doc.children ?? []).filter((c) => c.type === "COMPONENT") : [doc];
310
+ const keyToVariant = new Map();
311
+ for (const variant of variants) {
312
+ const component = components[variant.id];
313
+ if (!component?.key) continue;
314
+ if (doc.type === "COMPONENT_SET" && component.componentSetId && component.componentSetId !== doc.id) continue;
315
+ keyToVariant.set(component.key, variant.id);
316
+ }
317
+ const variantToState = new Map();
318
+ const missing = [];
319
+ for (const [state, key] of byKey) {
320
+ const id = keyToVariant.get(key);
321
+ if (!id) missing.push(`${state} (${key})`);
322
+ else variantToState.set(id, state);
323
+ }
324
+ if (missing.length)
325
+ throw new CliError("SURFACE_STATE_KEY_UNRESOLVED", `${where}: catalog state${missing.length === 1 ? "" : "s"} ${missing.join(", ")} name no variant of ${row.componentSetKey}${row.figmaVersion ? `; the catalog resolved its keys at version ${row.figmaVersion}` : ""}. Refresh the catalog's state keys at this version, or read the version they were resolved at (DESIGN-SYSTEM-582, MW8-20)`, 1);
326
+ return (variant) => variantToState.get(variant.id) ?? null;
327
+ }
328
+
277
329
  export function trimTree(entry, { row, version }) {
278
330
  const components = entry.components ?? {};
279
331
  const sets = entry.componentSets ?? {};
@@ -422,11 +474,8 @@ export function trimTree(entry, { row, version }) {
422
474
  };
423
475
 
424
476
  const doc = entry.document;
425
- // The catalog's `figma.states` names each state by its variant's node id (its own contract, which
426
- // the frame-conformance check reads too). The join happens here, inside the fetch, and the tree
427
- // keeps only the state's name: no node id crosses into the committed tree or a later hop (MW8-20).
428
- const nodeToState = new Map(Object.entries(row.states ?? {}).map(([state, nodeId]) => [nodeId, state]));
429
- const variants = (doc.type === "COMPONENT_SET" ? doc.children : [doc]).map((variant) => ({ name: variant.name, state: nodeToState.get(variant.id) ?? slug(variantValue(variant.name)), root: trim(variant, null) }));
477
+ const stateOf = catalogStateJoin(entry, row, version);
478
+ const variants = (doc.type === "COMPONENT_SET" ? doc.children : [doc]).map((variant) => ({ name: variant.name, state: stateOf(variant) ?? slug(variantValue(variant.name)), root: trim(variant, null) }));
430
479
  return {
431
480
  $comment: "Generated by `nodii-dev surface generate --fetch --write` from Figma's REST nodes API (read-only). The input of the product page's generated file; never edit by hand.",
432
481
  generator: "nodii-dev surface generate",
@@ -567,7 +616,7 @@ export function emitSurface(tree, row, ds) {
567
616
  const shapes = new Map();
568
617
  // The marked identifiers a template lists as optional, and the ones it doesn't (DESIGN-SYSTEM-507).
569
618
  const optionals = { optional: new Set(), required: new Set() };
570
- const views = tree.variants.map((variant) => {
619
+ const views = graftAbsentSlots(tree.variants).map((variant) => {
571
620
  let state = variant.state;
572
621
  while (used.has(state)) state += "-x";
573
622
  used.add(state);
@@ -730,9 +779,23 @@ function scopeName(node, code = "", ctx = null) {
730
779
  const own = [props.label, props.title].find(named);
731
780
  const at = own ? placeInView(node, ctx) : null;
732
781
  if (at) return camelName(`${node.instance.set} ${at}`);
782
+ // A layer named after its own sample (`PiiText · Asha Rao`) names the record, not the part:
783
+ // in a slot it takes its owner's label (`Created by`), else its set's name.
784
+ if (!own && sampleNamed(node)) {
785
+ const ownerProps = ctx?.slotOwner?.instance?.props ?? ctx?.slotOwner?.props ?? {};
786
+ const label = [ownerProps.label, ownerProps.title].find(named);
787
+ return nameOf(label ?? node.instance?.set ?? "", node.instance?.set ?? "");
788
+ }
733
789
  return nameOf(own ?? node.name ?? "", node.instance?.set ?? node.name ?? "");
734
790
  }
735
791
 
792
+ /** A layer whose name after `·` repeats one of its own text values: the designer's sample, not a name. */
793
+ function sampleNamed(node) {
794
+ const suffix = /·\s*(.+)$/.exec(node.name ?? "")?.[1]?.trim();
795
+ if (!suffix) return false;
796
+ return Object.values(node.instance?.props ?? {}).some((v) => typeof v === "string" && v.trim() === suffix);
797
+ }
798
+
736
799
  /** Where an instance stands among the instances of its set in its view (1, 2, …), when the view holds two or more; else null. */
737
800
  function placeInView(node, ctx) {
738
801
  const root = ctx?.chain?.[0];
@@ -874,6 +937,53 @@ function optionalMark(ctx, scope, name, layer = ctx.layer) {
874
937
  * numbered (`Frame`, `Frame#1`). The view's own name is left out, so the same
875
938
  * layer in another state view is the same layer, one prop (hub-468).
876
939
  */
940
+ /**
941
+ * Figma leaves a slot out of an instance whose variant does not show it (a
942
+ * `pane=hidden` Detail Page has no `right pane` SLOT), but the template still
943
+ * reads it, so that view drew the slot empty and named its controls apart from
944
+ * the open view's (NODII-DEV-CLI-188). Fill such a slot from the same
945
+ * instance in another view, the default view's first, matched by layer path
946
+ * and component set. Only the slots listed in GRAFTED_SLOTS: other parts leave
947
+ * a slot out on purpose (a Loading view's Data Table Toolbar has no `table`).
948
+ * A slot drawn empty stays empty. The saved tree is never changed: this works
949
+ * on a copy.
950
+ */
951
+ const GRAFTED_SLOTS = new Map([["Detail Page", new Set(["right pane"])]]);
952
+ function graftAbsentSlots(variants) {
953
+ const walk = (node, path, visit) => {
954
+ visit(node, path);
955
+ const seen = new Map();
956
+ for (const child of node.children ?? []) {
957
+ const at = seen.get(child.name) ?? 0;
958
+ seen.set(child.name, at + 1);
959
+ walk(child, `${path} › ${child.name}${at ? `#${at}` : ""}`, visit);
960
+ }
961
+ };
962
+ const keyOf = (node, path) => (node.type === "INSTANCE" && node.instance?.remote && GRAFTED_SLOTS.has(node.instance.set) ? `${node.instance.set}@${path}` : null);
963
+ const ordered = [...variants].sort((a, b) => (b.state === "default") - (a.state === "default"));
964
+ const drawn = new Map();
965
+ for (const variant of ordered) {
966
+ walk(variant.root, "", (node, path) => {
967
+ const key = keyOf(node, path);
968
+ if (!key) return;
969
+ const slots = drawn.get(key) ?? new Map();
970
+ for (const child of node.children ?? []) if (child.type === "SLOT" && GRAFTED_SLOTS.get(node.instance.set).has(child.slot) && !slots.has(child.slot)) slots.set(child.slot, child);
971
+ drawn.set(key, slots);
972
+ });
973
+ }
974
+ if (![...drawn.values()].some((slots) => slots.size)) return variants;
975
+ return variants.map((variant) => {
976
+ const copy = structuredClone(variant);
977
+ walk(copy.root, "", (node, path) => {
978
+ const slots = drawn.get(keyOf(node, path));
979
+ if (!slots?.size) return;
980
+ const own = new Set((node.children ?? []).filter((c) => c.type === "SLOT").map((c) => c.slot));
981
+ for (const [name, slot] of slots) if (!own.has(name)) node.children = [...(node.children ?? []), structuredClone(slot)];
982
+ });
983
+ return copy;
984
+ });
985
+ }
986
+
877
987
  function layerOf(node, ctx) {
878
988
  if (ctx.root) return "";
879
989
  const same = (ctx.parent?.children ?? []).filter((c) => c.name === node.name);
@@ -1267,7 +1377,8 @@ function showCondition(code, node, ctx, path) {
1267
1377
  * are (tabStrip).
1268
1378
  */
1269
1379
  function hideable(code) {
1270
- let out = code.replace(/<AlertAction>([\s\S]*?)<\/AlertAction>/g, (block, inner) => {
1380
+ // A parent template may include a child Alert that was already processed (NODII-DEV-CLI-209).
1381
+ let out = code.replace(/(?<!!== false && \()<AlertAction>([\s\S]*?)<\/AlertAction>/g, (block, inner) => {
1271
1382
  const flagOf = (part) => {
1272
1383
  const own = /\bonClick=\{(__s\d+)_on([A-Z]\w*)Click\}/.exec(part);
1273
1384
  return own ? `${own[1]}_show${own[2]}` : null;
@@ -1281,7 +1392,7 @@ function hideable(code) {
1281
1392
  let held = inner;
1282
1393
  for (const b of buttons.reverse()) {
1283
1394
  const flag = flagOf(b.code);
1284
- if (flag) held = `${held.slice(0, b.at)}{${flag} !== false && (${b.code})}${held.slice(b.at + b.code.length)}`;
1395
+ if (flag && !held.slice(0, b.at).endsWith(" !== false && (")) held = `${held.slice(0, b.at)}{${flag} !== false && (${b.code})}${held.slice(b.at + b.code.length)}`;
1285
1396
  }
1286
1397
  return `<AlertAction>${held}</AlertAction>`;
1287
1398
  });
@@ -2335,7 +2446,7 @@ function emitNode(node, ctx) {
2335
2446
  return comment(`unmapped: slot ${JSON.stringify(prop)} has no auto layout`);
2336
2447
  }
2337
2448
  const textOwner = TEXT_PROPERTY_PARTS.has(node.instance.set) ? node.instance.set : ctx.textOwner;
2338
- const slotCtx = { ...ctx, depth: 0, parent: slotNode, grand: null, path: `${path} › ${prop}`, root: false, textOwner, inTable: false, inSlot: true, chain: slotNode ? [...chain, slotNode] : chain, layer: `${ctx.layer}${nestedPath.map(part => ` › ${part}`).join("")} › ${prop}` };
2449
+ const slotCtx = { ...ctx, depth: 0, parent: slotNode, grand: null, path: `${path} › ${prop}`, root: false, textOwner, slotOwner: owner, inTable: false, inSlot: true, chain: slotNode ? [...chain, slotNode] : chain, layer: `${ctx.layer}${nestedPath.map(part => ` › ${part}`).join("")} › ${prop}` };
2339
2450
  const inner = emitChildren(slotNode?.children ?? [], (c) => emitNode(c, slotCtx), slotCtx);
2340
2451
  return inner.length === 0 ? "<></>" : inner.length === 1 ? inner[0] : `<>\n${inner.map((x) => indent(x, 1)).join("\n")}\n</>`;
2341
2452
  };
@@ -2348,7 +2459,10 @@ function emitNode(node, ctx) {
2348
2459
  ctx.imports.push(...rendered.imports);
2349
2460
  // Detail Section owns its grid. The Row template emits sibling facts,
2350
2461
  // not a layout box: a wrapper would turn the entire row into one grid cell.
2351
- const sizing = ctx.bare || node.instance.set === "Detail Section / Row" ? [] : sizeClasses(node, parent, false);
2462
+ // A Right Pane / Row is a <dt>/<dd> pair inside its Section's <dl>: a
2463
+ // wrapper would put the pair a level below the list (axe dlitem;
2464
+ // NODII-DEV-CLI-210).
2465
+ const sizing = ctx.bare || node.instance.set === "Detail Section / Row" || node.instance.set === "Right Pane / Row" ? [] : sizeClasses(node, parent, false);
2352
2466
  // A data slot passed straight to a prop is that prop (`trailing={<>{trailing}</>}` → `trailing={trailing}`).
2353
2467
  let own = rendered.code.trim().replace(/=\{<>\{([a-z][A-Za-z0-9]*)\}<\/>\}/g, "={$1}");
2354
2468
  // The toolbar owns table rendering, so its template does not emit this slot.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.177",
3
+ "version": "0.6.179",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {