@nodii/dev 0.6.177 → 0.6.178

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,11 +982,8 @@ 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
@@ -1628,6 +1628,8 @@ To recover a machine, in order:
1628
1628
 
1629
1629
  ```
1630
1630
  nodii-dev coordinator start --machine NAME
1631
+ nodii-dev coordinator gather --objective "<current focus>" --picker agent
1632
+ nodii-dev coordinator gather --show
1631
1633
  nodii-dev lane resume --host-lost
1632
1634
  nodii-dev doctor
1633
1635
  ```
@@ -1799,12 +1801,18 @@ continuations included, the supervisor heartbeats its run every
1799
1801
  runtime that is alive but writes nothing gets no heartbeat from the supervisor,
1800
1802
  so it goes Quiet at 15 minutes and Orphan at 45 (MW1-36). A write to the
1801
1803
  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
1804
+ and its subagents' transcripts) counts as one too. So does a tool call that is
1805
+ still running: a long command writes nothing until it ends, so while the
1806
+ runtime has recorded a call's start and not its end (a Claude `tool_use` with no
1807
+ `tool_result`, a Codex `item.started` with no `item.completed`), the supervisor
1808
+ keeps beating for at most 2 hours of silence, with the note `a tool call is
1809
+ still running; last write <time>`. A call that hangs longer goes Quiet and then
1810
+ Orphan (MW1-34, MW1-36). The same tick is the lane's
1803
1811
  harness heartbeat (`POST /lanes/KEY/heartbeat` with `source: "hook"`), which
1804
1812
  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
1813
+ activity <time>` (NODII-DEV-CLI-191, MW1-34). This lighter tracking is on
1814
+ unless `NODII_DEV_STOP_ONLY_HEARTBEAT=0` (see "Lane feature switches"); at `0`,
1815
+ the harness registers `hook lane-heartbeat` on every tool call and on `Stop` as
1808
1816
  before, and neither the supervisor nor `hook nudge-pre` beats the lane. On, no
1809
1817
  hook process runs on every tool call for it: the harness's `hook lane-heartbeat`
1810
1818
  is registered on `Stop` only. A session with no lane supervisor (no `NODII_DEV_RUN_ID`) is beaten from
@@ -1984,18 +1992,21 @@ ask and, when Dev has no such ask, as a leeway, and `--leeway` goes straight to
1984
1992
  the leeway. `lane asks [--machine M] [--state S] [--lane KEY] [--cursor C]
1985
1993
  [--limit N]` lists asks.
1986
1994
 
1987
- ### Switched-off lane features (NODII-DEV-CLI-191)
1995
+ ### Lane feature switches (NODII-DEV-CLI-191)
1988
1996
 
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`.
1997
+ Each NODII-DEV-CLI-191 lane feature has its own switch, read in the
1998
+ environment of the process that does the work: the coordinator's for
1999
+ `lane resume`, the lane session's for hooks, and the harness's for
2000
+ `harness update`.
1996
2001
 
1997
- | Variable | Feature | Off (the default) |
2002
+ All seven are ruled: four in MW1 1.30 (MW1-12.10, MW1-102, MW1-102.1 and
2003
+ MW1-38.16; the operator's "ratify 191", 18 Nov) and three in MW1 1.32
2004
+ (MW1-66, MW1-12.11 and MW1-34; DEC-0506). They are on by default; the variable
2005
+ set to exactly `0` turns one off.
2006
+
2007
+ | Variable | Feature (on by default) | With `=0` |
1998
2008
  |---|---|---|
2009
+ | `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
2010
  | `NODII_DEV_RESUME_IF_CHANGED` | `lane resume --if-changed` | Refused `RESUME_IF_CHANGED_OFF`; resume without it |
2000
2011
  | `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
2012
  | `NODII_DEV_SUBAGENT_BUDGET` | The subagent budget line in the launch brief, gather's next step and the resume prompt | No line |
@@ -2005,7 +2016,7 @@ hooks, and the harness's for `harness update`.
2005
2016
 
2006
2017
  ### Lane messages (NODII-DEV-CLI-191)
2007
2018
 
2008
- Off unless `NODII_DEV_LANE_MESSAGES=1` (see "Switched-off lane features").
2019
+ MW1-12.11. On unless `NODII_DEV_LANE_MESSAGES=0` (see "Lane feature switches").
2009
2020
 
2010
2021
  Lanes, stewards and the coordinator message each other by name: a lane by its
2011
2022
  lane key, a steward by its steward lane key, the machine's coordinator as
@@ -2013,7 +2024,10 @@ lane key, a steward by its steward lane key, the machine's coordinator as
2013
2024
  The sender is the session's own identity: the current lane (`NODII_DEV_LANE_KEY`),
2014
2025
  else this agent's Dev name. No flag names it (P-8). A delivered message is
2015
2026
  marked as information from another session, not an instruction: the lane's
2016
- Freeze and the rulebook still govern.
2027
+ Freeze and the rulebook still govern. A coordinator messages only its own
2028
+ machine's lanes (MW1-37.3): `lane message` from a coordinator to a lane Dev
2029
+ places on another machine, or on none, is refused `COORDINATOR_OTHER_MACHINE`
2030
+ and records nothing.
2017
2031
 
2018
2032
  Dev keeps the durable record: the message is a comment on the recipient lane's
2019
2033
  issue (a message to the coordinator goes on the sending lane's issue; `--issue
@@ -2283,3 +2297,18 @@ is denied. It exits `2`, which makes Claude Code block the call. The post-hook
2283
2297
  best-effort logs the write and never blocks; it exits `2` only for
2284
2298
  `WRITE_OUT_OF_SCOPE`, after the write is logged, so the agent sees it. Per D1433, Codex remains read-only
2285
2299
  for Figma; this package does not write to Figma itself.
2300
+
2301
+ ### Coordinator Gather
2302
+
2303
+ `coordinator gather` uses the caller's live coordinator run and its repository
2304
+ grants from Dev. The first call needs `--objective`; later calls may reuse the
2305
+ stored focus. With `--picker agent`, it prints the trigger shortlist and an exact
2306
+ follow-up command for recording the chosen document codes. Without that flag it
2307
+ uses the local picker, with the same agent fallback as lane Gather. `--delta`
2308
+ keeps previously searched documents; `--show` reads the stored map.
2309
+
2310
+ Dev stores the Clause map on the coordinator run. SessionStart restores it at
2311
+ startup and after compaction, and asks the coordinator to Gather again with the
2312
+ operator's current focus. An ended run, another agent's run or a replaced machine
2313
+ coordinator cannot read or replace that map. Missing maps prompt a first Gather;
2314
+ 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.178";
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,5 +1,5 @@
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";
@@ -294,7 +294,7 @@ const latestNote = (lane) => String((lane?.events ?? [])
294
294
  * Null when the quota is unknown.
295
295
  */
296
296
  export function subagentBudgetLine(quota, env = process.env) {
297
- // Off unless NODII_DEV_SUBAGENT_BUDGET=1 until its clause is in force.
297
+ // Ratified (18 Nov): on unless NODII_DEV_SUBAGENT_BUDGET=0.
298
298
  if (!laneSwitchOn("subagentBudget", env)) return null;
299
299
  const n = Number(quota);
300
300
  if (quota == null || !Number.isInteger(n) || n < 0) return null;
@@ -315,13 +315,11 @@ export function laneHumanGate(lane) {
315
315
  }
316
316
 
317
317
  /**
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).
318
+ * NODII-DEV-CLI-191: "BLOCKED is not an exit" (ratified, "ratify 191", 18 Nov)
319
+ * is on by default; NODII_DEV_BLOCKED_NOT_EXIT=0 turns it off. Off, a BLOCKED
320
+ * lane ends its run as before, except where leeway covers it (MW1-12.6, DEC-0486).
323
321
  */
324
- export const blockedIsNotExit = (env = process.env) => env?.NODII_DEV_BLOCKED_NOT_EXIT === "1";
322
+ export const blockedIsNotExit = (env = process.env) => laneSwitchOn("blockedNotExit", env);
325
323
 
326
324
  /** Why a lane's run may end before its done check, or null. */
327
325
  export const laneRunEnds = (lane, env = process.env) => (blockedIsNotExit(env) ? laneHumanGate(lane) : laneBlockedReason(lane));
@@ -570,6 +568,73 @@ export function runActivity({ logPath, transcripts = () => [], now = Date.now })
570
568
  };
571
569
  }
572
570
 
571
+ /**
572
+ * MW1-34 with MW1-36: a running tool call writes nothing until it ends, so a
573
+ * long command would read as a hung runtime. The supervisor beats through a
574
+ * call that is still open, for at most this much silence; a call that hangs
575
+ * longer still goes Quiet and then Orphan.
576
+ */
577
+ export const OPEN_CALL_MAX_MS = 2 * 60 * 60_000;
578
+ const OPEN_CALL_TAIL_BYTES = 256 * 1024;
579
+
580
+ /**
581
+ * Whether the tail of a Claude session transcript or a Codex `--json` stream
582
+ * holds a tool call that started and has not ended: a Claude `tool_use` with
583
+ * no `tool_result` for its id, or a Codex `item.started` with no
584
+ * `item.completed`. Unparseable lines (a tail cut mid-line) are skipped.
585
+ */
586
+ export function openToolCall(text, runtime) {
587
+ const open = new Set();
588
+ for (const line of String(text ?? "").split("\n")) {
589
+ if (!line) continue;
590
+ let entry;
591
+ try { entry = JSON.parse(line); } catch { continue; }
592
+ if (runtime === "codex") {
593
+ const id = entry?.item?.id;
594
+ if (!id) continue;
595
+ if (entry.type === "item.started") open.add(id);
596
+ else if (entry.type === "item.completed") open.delete(id);
597
+ continue;
598
+ }
599
+ const content = Array.isArray(entry?.message?.content) ? entry.message.content : [];
600
+ for (const part of content) {
601
+ if (entry.type === "assistant" && part?.type === "tool_use" && part.id) open.add(part.id);
602
+ else if (entry.type === "user" && part?.type === "tool_result" && part.tool_use_id) open.delete(part.tool_use_id);
603
+ }
604
+ }
605
+ return open.size > 0;
606
+ }
607
+
608
+ // Synchronous, unlike readTail: the tick sends its beats before it returns, so none follows the exit report.
609
+ const readTailSync = (path, bytes = OPEN_CALL_TAIL_BYTES) => {
610
+ let fd;
611
+ try {
612
+ fd = openSync(path, "r");
613
+ const size = fstatSync(fd).size;
614
+ const length = Math.min(size, bytes);
615
+ const buffer = Buffer.alloc(length);
616
+ readSync(fd, buffer, 0, length, size - length);
617
+ return buffer.toString("utf8");
618
+ } catch { return null; } finally {
619
+ if (fd !== undefined) try { closeSync(fd); } catch {}
620
+ }
621
+ };
622
+
623
+ /**
624
+ * The last write of a runtime whose tool call is still open, when that write
625
+ * is at most OPEN_CALL_MAX_MS ago; else null. Codex's stream is the run log;
626
+ * Claude's is the session's own transcript (a subagent's open call is the
627
+ * session's open Agent call).
628
+ */
629
+ export function openCallSince({ logPath, transcripts = () => [], runtime, now = Date.now }) {
630
+ const path = runtime === "codex" ? logPath : transcripts()[0];
631
+ if (!path) return null;
632
+ const last = mtimeOf(path);
633
+ if (last === null || now() - last > OPEN_CALL_MAX_MS) return null;
634
+ const tail = readTailSync(path);
635
+ return tail !== null && openToolCall(tail, runtime) ? last : null;
636
+ }
637
+
573
638
  /** Claude's transcript of a session in a lane worktree, and its subagents' transcripts. */
574
639
  export function claudeTranscripts(invocation, sessionId, { home = homedir() } = {}) {
575
640
  const project = join(invocation.env?.CLAUDE_CONFIG_DIR ?? join(home, ".claude"), "projects", String(invocation.cwd).replace(/[^A-Za-z0-9]/g, "-"));
@@ -629,9 +694,12 @@ export async function superviseLane({
629
694
  if (state !== "running") return;
630
695
  // Both beats leave inside the tick, so none follows the exit report.
631
696
  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.
697
+ // A tool call still running writes nothing; it beats for at most OPEN_CALL_MAX_MS of silence.
698
+ const open = at === null ? openCallSince({ logPath, transcripts, runtime: invocation.command }) : null;
699
+ if (at !== null || open !== null) {
700
+ const note = at !== null ? `last activity ${new Date(at).toISOString()}` : `a tool call is still running; last write ${new Date(open).toISOString()}`;
701
+ request("POST", `/api/v1/runs/${encode(runId)}/heartbeat`, { note: `lane runtime pid ${child.pid} alive (supervisor ${process.pid}); ${note}` }).catch(() => {});
702
+ // At NODII_DEV_STOP_ONLY_HEARTBEAT=0 the harness's tool-call hook beats the lane instead.
635
703
  if (laneKey && laneSwitchOn("stopOnlyHeartbeat", env)) request("POST", `/api/v1/lanes/${encode(laneKey)}/heartbeat`, { via: "nodii-dev", source: "hook" }).catch(() => {});
636
704
  }
637
705
  // 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
@@ -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)}\`)`;
@@ -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
@@ -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",
@@ -2348,7 +2397,10 @@ function emitNode(node, ctx) {
2348
2397
  ctx.imports.push(...rendered.imports);
2349
2398
  // Detail Section owns its grid. The Row template emits sibling facts,
2350
2399
  // 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);
2400
+ // A Right Pane / Row is a <dt>/<dd> pair inside its Section's <dl>: a
2401
+ // wrapper would put the pair a level below the list (axe dlitem;
2402
+ // NODII-DEV-CLI-210).
2403
+ const sizing = ctx.bare || node.instance.set === "Detail Section / Row" || node.instance.set === "Right Pane / Row" ? [] : sizeClasses(node, parent, false);
2352
2404
  // A data slot passed straight to a prop is that prop (`trailing={<>{trailing}</>}` → `trailing={trailing}`).
2353
2405
  let own = rendered.code.trim().replace(/=\{<>\{([a-z][A-Za-z0-9]*)\}<\/>\}/g, "={$1}");
2354
2406
  // 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.178",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {