@nodii/dev 0.6.172 → 0.6.173

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -89,6 +89,16 @@ checks the local stack.
89
89
  Every command accepts `--json`; without it, output is formatted for humans.
90
90
  Dev failures print Dev's error code to stderr and exit non-zero.
91
91
 
92
+ ## The Figma token (hub-527)
93
+
94
+ `design check`, `surface generate --fetch`, the lane's publish compares and the `--figma` preflight read the
95
+ Figma token from the environment: `FIGMA_PAT`, or `FIGMA_TOKEN`. `nodii-dev doctor` reports it in its
96
+ `figma_token` line (the variable's name, never its value). Set it once, for the shell you use:
97
+
98
+ - zsh: add `export FIGMA_PAT=...` to `~/.zshenv`.
99
+ - bash: add `export FIGMA_PAT=...` to `~/.bashrc` (or `~/.bash_profile` for a login shell).
100
+ - fish: `set -Ux FIGMA_PAT ...`.
101
+
92
102
  ## Tests: only what changed (hub-401)
93
103
 
94
104
  A lane, a pre-push hook and per-push CI run only the tests the change reaches. The full suite runs in the twice-daily scheduled CI and the release gate.
@@ -134,6 +144,41 @@ nodii-dev heavy status
134
144
  - It can't be skipped. In a lane, the safety hook (`hook safety-pre`) refuses an unqueued heavy command and prints the same command with `nodii-dev heavy run --` in front of each heavy part. `lane check --gate` and `receipt write --run` queue every gate themselves, `lane check` runs each reviewer under a slot (its timeout starts once the slot is granted), and `lane closeout` pushes through the landing reserve.
135
145
  - `[TOOL GAP hub-86]` MW5-19 places this helper as the `heavy-slot` util. It ships here until the util pipeline exists.
136
146
 
147
+ ## Figma REST reads: one queue, two retries, one cache (cli-170)
148
+
149
+ Most Figma work goes through the MCP (MW1-57.11). The reads the MCP can't do
150
+ (a Surface's tree at a pinned version, `design check`, the publish plan's
151
+ version compares, `figma publish`'s version read and the `--figma` seat
152
+ preflight) call Figma's REST API with `FIGMA_PAT`. Every one of them goes
153
+ through one client, `src/figma-rest.js`:
154
+
155
+ - **One queue per token, across the machine.** Each process reserves the next
156
+ slot in `figma-rest-<hash of the token>.slot` under the machine's nodii-dev
157
+ directory (`~/.config/nodii-dev`) and waits for it: one call per 8 s per
158
+ token, however many lanes read at once. The file's lock is held only while a
159
+ slot is reserved, never during the call. Two tokens are two queues. The
160
+ token is never written. A wait of over 30 s in the queue is printed. A slot
161
+ that cannot be reserved (the directory can't be written, or the lock stays
162
+ held for 15 s) fails the call with `FIGMA_QUEUE_UNAVAILABLE` before anything
163
+ is sent: no process paces only itself.
164
+ - **A 429 is retried at most twice.** The client waits what Retry-After says
165
+ (30 s when Figma names none), holds every other process on that token back
166
+ for as long (a call already waiting for its slot included), and sends the read again. A third 429 fails with
167
+ `FIGMA_RATE_LIMITED`, as a first one did before. A Retry-After of over a
168
+ minute is not waited out: the read fails at once and reports
169
+ `retryAfterSeconds`.
170
+ The `--figma` seat preflight is retried the same way; a rate-limited
171
+ preflight fails with `FIGMA_RATE_LIMITED`, not `FIGMA_SEAT_UNAVAILABLE`.
172
+ - **Pinned tree reads are cached.** A `/files/:key/nodes` read with `version=`
173
+ is immutable, so each node read that way is kept under `figma-tree-cache/`
174
+ in the same directory, keyed by file key, version and node id (and the
175
+ read's other query parameters), and shared by every process and token on the
176
+ machine. A read of several nodes asks Figma only for the ones not kept. A
177
+ read with no version is the live file and is never kept. Entries older than
178
+ 14 days are removed. Deleting the directory is always safe.
179
+
180
+ `NODII_DEV_FIGMA_REST_DIR` moves the queue and the cache (tests use it).
181
+
137
182
  ## The coordinator's board, watch and shared Chrome (hub-405)
138
183
 
139
184
  The machine's coordinator runs these. The clauses that make them procedure are drafted in `docs/reports/2026-11-13-coordinator-watch-rules-draft.md` for the coordinator to upload. Until then the draft is not a rule (P-1.3).
@@ -153,7 +198,7 @@ nodii-dev figma publish FILE --sets CS-1,CS-2 [--dry-run]
153
198
 
154
199
  - **Board.** "Waiting on" comes from Dev's real state: the lane's status, the change sets it holds (state, pending items, file order), Dev's wait records, the heavy-slot queue and `answered.md`. It never comes from the lane's note, which is shown as written in its own column. A question counts as the operator's only when it is an open item on the sheet. `--write` puts "What's running" on the status page `docs/open/<sheet>-status.md` and only the lanes that wait on the operator on the sheet, because MW4-31 keeps status off the sheet. It works in the worktree `nodii-infra/.claude/worktrees/<sheet>-board` and merges through a PR. First it copies every answer the operator typed in their checkout, verbatim, into `answered.md` and into the sheet. Then it fast-forwards the operator's checkout, and only when nothing else there differs from main. An empty board, or one that drops by more than half, is refused (`--force` once you have checked Dev). Priority domains are coordinator configuration in `~/.config/nodii-dev/coordinator/settings.json` (`domains`); a lane outside them is listed under "Other lanes".
155
200
  - **Watch.** Jobs and intervals: board 15 min, apply-watch 3, publish-watch 10, real-stuck 30, complexity 30, orphan-slots 10, keepalive 10. Everything goes to one log, `coordinator-watch.log`, under `~/Library/Logs/nodii-dev/` on macOS and `~/.local/state/nodii-dev/logs/` on Linux. On Linux the memory guard on a resume reads `MemAvailable` from `/proc/meminfo`. Alerts go to `~/.config/nodii-dev/coordinator/alerts.log` and open the coordinator's next session. A job is paused by `~/.config/nodii-dev/coordinator/hold-<job>`. A resume tries the lane's own account first. On an account refusal it tries the accounts listed in `settings.json` `keepaliveProfiles` (`[{ "profile": "/abs/path", "class": "short" }]`), because the account roster is the operator's call (MW1-38.3). The watch never stops a process it did not start (K02-15). It reports an orphaned slot instead.
156
- - **publish-watch** stays off until the coordinator sets `"publishWatch": true` in `settings.json`. MW8-7 still names the operator as publisher until hub-429 lands. It needs a Figma token to read the new version. It reads `FIGMA_PAT` from the keychain (`security add-generic-password -s nodii-dev-figma-pat -a "$USER" -w`; on Linux the Secret Service, `secret-tool store --label "nodii-dev Figma token" service nodii-dev-figma-pat account "$USER"`), never from the plist, a unit or a file. On Linux the job answers "macOS only".
201
+ - **publish-watch** stays off until the coordinator sets `"publishWatch": true` in `settings.json`. MW8-7 still names the operator as publisher until hub-429 lands. It needs a Figma token to read the new version. It reads the token from `FIGMA_PAT` (or `FIGMA_TOKEN`) in the daemon's own environment first, then from the macOS keychain (`security add-generic-password -s nodii-dev-figma-pat -a "$USER" -w`). The plist that `coordinator watch install` writes carries no token, so the keychain is the usual source; a token someone adds to the plist's environment would be used before it. It never reads a file. On Linux the job answers "macOS only", so nothing there reads a Secret Service for the token.
157
202
  - **Chrome.** `chrome start` adopts the Chrome already serving the port, or starts one on the profile, and records the endpoint on Dev's machine record (`hostFacts.sharedChrome`; coordinator or staff only). Every command opens its own background tab and closes only that tab (K02-16, K02-17). `chrome signin` refuses anything but a `tech-*` tenant and a yopmail test identity. It signs in within its own tab and opens `--open PATH` if given. Then it signs out (the app's logout, then that origin's storage and cookies cleared), so no session or token outlives it (MW3-40.2). It never prints or stores a credential, tries each tenant at most once an hour, skips a tenant another tab has open, and rests a tenant after a failed sign-in until `--clear-rest`.
158
203
  - **figma publish** refuses a set that is not `awaiting_publish`. It ticks exactly the approved components of the named sets in Figma's Publish library dialog and unticks every other row. It stops if a row won't settle or if it saw fewer rows than the dialog counts. It records a set in Dev only when all of the set's components were published.
159
204
 
@@ -522,6 +567,16 @@ re-grounding work for it unchanged; a fresh steward session prints its Clause
522
567
  map. Gather pins the always-on clauses for a lane's repository and side
523
568
  (`GET /rules/gather-pins`), marked `always-on` in the Clause map.
524
569
 
570
+ The hooks that run on every tool call or stop (`safety-pre`, `nudge-pre`,
571
+ `nudge-stop`, `lane-heartbeat`, and `claude-figma-pre` on a Figma write) read the lane from Dev on each call, never from
572
+ a kept copy, and ask for as little as decides the same thing
573
+ (hub-528). A lane is read as `GET /lanes/KEY?view=hook`: only the
574
+ fields the hooks use, without the lane's timeline. A Dev that does not know
575
+ the view answers with the whole lane. A worktree with no lane marker lists
576
+ only this agent's live lanes (`agent`, `status`), not every lane. Within one
577
+ hook call a lane is read once: the Stop gate uses the lane the call already
578
+ read.
579
+
525
580
  `hook safety-pre` (installed by `harness install` for Claude Code and Codex)
526
581
  blocks, silently when satisfied (AGENT-HARNESS-15):
527
582
 
@@ -622,6 +677,9 @@ nodii-dev next KEY [--paths A,B] [--components K,L] [--role ROLE]
622
677
 
623
678
  nodii-dev built list [--cursor CURSOR] [--include-acknowledged true]
624
679
  nodii-dev built ack KEY [KEY ...] [--note TEXT]
680
+ # signs every pr, commit and deploy the lane recorded; a long
681
+ # lane's evidence is paged from Dev, and an incomplete read
682
+ # signs nothing (BUILT_ACK_EVIDENCE_INCOMPLETE)
625
683
  nodii-dev machine list|show
626
684
  nodii-dev machine set-coordinator MACHINE AGENT
627
685
  nodii-dev machine assign MACHINE AGENT --home-repo REPO
@@ -868,7 +926,8 @@ nodii-dev design check FILE_KEY|LINK [--nodes 12:34,12:56] [--roles decision.app
868
926
  ```
869
927
 
870
928
  `design check` reads the nodes from Figma's REST API with `FIGMA_PAT` (or
871
- `FIGMA_TOKEN`) and the role map from Dev (`listDesignRoles`). It then reads
929
+ `FIGMA_TOKEN`), through the machine's Figma queue (see "Figma REST reads"
930
+ below), and the role map from Dev (`listDesignRoles`). It then reads
872
931
  each instance's main the way Dev's submit gate does, so both reach one verdict:
873
932
 
874
933
  - A local component is read from the file.
@@ -969,8 +1028,8 @@ product-page catalog names the Surface by its published component-set key
969
1028
  (MW8-20), never a node id; a frontend route picks every Surface on it.
970
1029
 
971
1030
  - **`--fetch`** reads the Surface set from Figma's REST nodes API with
972
- `FIGMA_PAT` (read-only, one call per 8 s, a 429 waits Retry-After or 30 s
973
- doubling), at the version the file's last library publish closed (MW8-17),
1031
+ `FIGMA_PAT` (read-only, through the machine's Figma queue: see "Figma REST
1032
+ reads" below), at the version the file's last library publish closed (MW8-17),
974
1033
  by the design system's snapshot-pin rule: the publish time is the newest
975
1034
  `updated_at` across the file's published components, component sets and
976
1035
  styles, and the version read is the newest one whose own `lastModified` is
@@ -1039,7 +1098,9 @@ product-page catalog names the Surface by its published component-set key
1039
1098
  is not among its file's published sets, names it as not published (`--json`:
1040
1099
  `data.unpublished`), and still generates and scores the rest. A Surface named
1041
1100
  on its own still fails with `SURFACE_NOT_PUBLISHED`.
1042
- - **A 429 stops the read.** `--fetch` never retries a 429. `--all` then generates
1101
+ - **A 429 is retried twice, then stops the read.** `--fetch` waits what
1102
+ Retry-After says and sends the read again, at most twice. After a third 429
1103
+ (or one whose Retry-After is over a minute) `--all` generates
1043
1104
  and scores what it read, reports the rest as not generated yet (`--json`:
1044
1105
  `data.stopped`) and exits 1. A Surface named on its own fails with
1045
1106
  `FIGMA_RATE_LIMITED`. With `--write`, each tree is saved as soon as it is read,
@@ -1088,6 +1149,89 @@ product-page catalog names the Surface by its published component-set key
1088
1149
  on that issue, and needs a Dev sign-in. If the post fails, the command exits 1
1089
1150
  with `COMMENT_FAILED`; any files from `--write` are already written.
1090
1151
 
1152
+
1153
+ ### The generator's corpus gate: `surface corpus`
1154
+
1155
+ ```
1156
+ nodii-dev surface corpus [--ds DIR] [--ref REV] [--module M] [--report FILE] [--baseline FILE] [--update]
1157
+ ```
1158
+
1159
+ Every change to the generator is checked against every committed Surface, not
1160
+ against a handful of fixtures (NODII-DEV-CLI-163; the plan is
1161
+ `docs/generator-plan/README.md`, section d). The command regenerates each
1162
+ catalog Surface that has a committed tree, in memory, with the generator this
1163
+ CLI carries, and judges what the generator wrote. It never reads Figma and
1164
+ never writes into design-system. It does not compare with the pages committed
1165
+ there: those are on older generator formats.
1166
+
1167
+ **What it counts, per page.**
1168
+
1169
+ | Count | What it is |
1170
+ |---|---|
1171
+ | fixed samples | a literal in a place that holds a record's value (a table cell, a Timeline entry's time or actor, a badge), or one that reads like a record's value (a date, an amount, a count, an identifier) outside copy |
1172
+ | suspect copy | a literal written as copy (a button, a title, a column head) that reads like a record's value |
1173
+ | undecided | a literal no rule places as data or as copy |
1174
+ | unmapped layers | the generator's own counted layers with no Code Connect mapping (U08-14) |
1175
+ | shallow input | 1 for a saved tree that is not tree format 2, so nested slot content is not kept |
1176
+
1177
+ Prop churn (a prop renamed while its value is still drawn) is reported as not
1178
+ checked until the names locks exist.
1179
+
1180
+ **What it refuses outright.** A Surface whose generation throws; an identifier
1181
+ a page uses but never imports or declares; an import that names nothing its
1182
+ module exports; a run that produced no page (MW2-17).
1183
+
1184
+ **The baseline only shrinks.** `packages/dev/test/corpus/baseline.json` holds
1185
+ the five counts for each page, one page to a line. The run fails when a count is
1186
+ higher than the baseline, when a baseline page was not generated, when a
1187
+ generated page is not in the baseline, and also when a count is **lower** and
1188
+ the file was not updated: a fix lowers the number in the same change, so a
1189
+ later regression cannot hide in the slack. `--update` rewrites the file. It
1190
+ refuses a run that raises any count or drops a page (`CORPUS_BASELINE_RAISED`)
1191
+ and a run in which a Surface threw (`CORPUS_RUN_FAILED`). Never edit the file
1192
+ by hand.
1193
+
1194
+ **The corpus is pinned.** `packages/dev/test/corpus/design-system.ref` holds the
1195
+ design-system commit the baseline was counted on. `--ds DIR` names a
1196
+ design-system repository on this machine (a checkout or a bare repository, with
1197
+ its dependencies installed); without it the command reads `NODII_CORPUS_DS`,
1198
+ then `design-system` beside this repository. A checkout at the pinned commit
1199
+ with nothing uncommitted is read as it is. Otherwise the commit is exported once with
1200
+ `git archive` into `~/.cache/nodii-dev/surface-corpus/<commit>` and the
1201
+ repository's `node_modules` are linked in; nothing is written into the
1202
+ repository. The catalog loads through its `tsx`, the templates through its
1203
+ `figma` CLI, and the pages are parsed with its TypeScript, so this CLI carries
1204
+ no parser.
1205
+
1206
+ **Taking a later design-system commit.** `--ref REV --update` counts the corpus
1207
+ at REV and writes both files. Surfaces changed, so counts may rise and pages
1208
+ may go, but only in a change that touches no generator source
1209
+ (`packages/dev/src/surface.js`, `src/surface/`, `src/vendor/`,
1210
+ `src/surface-corpus.js`, against `origin/main`; MW8-17.15). With a generator
1211
+ change in the same working copy it is refused
1212
+ (`CORPUS_REF_WITH_GENERATOR_CHANGE`), whatever the counts. Without `--update`,
1213
+ a run on a commit other than the pinned one is a difference.
1214
+
1215
+ **Other flags.** `--module M` regenerates and compares one module (not with
1216
+ `--update`). `--report FILE` writes every finding as JSON: for each page its
1217
+ counts, its props and callbacks, and each literal with its check, text, tag,
1218
+ attribute, line and the reason. That file is the work list for a Surface
1219
+ cleanup lane. `--baseline FILE` names another baseline; the pinned commit is
1220
+ read from `design-system.ref` beside it. `--json` prints `data.totals` (all and
1221
+ per module), `data.baselineTotals`, `data.failures`, `data.coverage` (catalog
1222
+ Surfaces with no committed tree, committed pages with no catalog row: reported,
1223
+ not held) and `data.propChurn`.
1224
+
1225
+ **Where it runs.** `test/surface-corpus-gate.test.js` runs the whole gate with
1226
+ the generator in the working copy. It imports the generator, so
1227
+ `nodii-dev test affected` (the lane check) selects it for any change to
1228
+ `surface.js`, the vendored renderer, the baseline or the pinned commit, and the
1229
+ full suite includes it. nodii-clis CI cannot read design-system yet (it is
1230
+ private and the workflow has no credential), so there the gate and the scan
1231
+ tests skip; on any other machine a missing design-system repository fails
1232
+ them. The scan is the plan's first draft and is replaced by the generator's own
1233
+ manifest when the one data rule lands.
1234
+
1091
1235
  ### Large sets: submit as a Dev job
1092
1236
 
1093
1237
  `figma submit`, `figma resubmit` and `design check --change-set` send
@@ -1301,6 +1445,9 @@ exits 0 only when every check is `OK`. `--json` returns the same checks as
1301
1445
  | `hooks_codex_personal`, `hooks_codex_work` | For `~/.codex` and `~/.codex-work`, whether Codex's own hook registry reports the hooks installed and trusted (including managed status), whether the managed absolute CLI is present and new enough, and whether that profile has fired one. |
1302
1446
  | `host_restart` | For the machine's coordinator: whether Dev has recorded this machine's boot, then whether any lane is still `host_lost`. `MISSING` names the next command. Other agents read `OK`. |
1303
1447
  | `watchdog` | For the machine's coordinator: whether the watchdog job is installed, running, and runs under this coordinator's config (launchd on macOS, `nodii-watchdog.timer` on Linux). `MISSING` names `watchdog install`. Other agents read `OK`. |
1448
+ | `figma_token` | Whether `FIGMA_PAT` (or `FIGMA_TOKEN`) is set in the environment, the variable that design check, `surface generate --fetch`, the lane's publish compares and the `--figma` preflight read. `OK` names the variable, never the value. `MISSING` names the fix for zsh (`~/.zshenv`), bash (`~/.bashrc` or `~/.bash_profile`) and fish (`set -Ux FIGMA_PAT ...`). |
1449
+ | `coordinator_watch` | For the machine's coordinator: whether the coordinator watch daemon is installed and running (launchd on macOS, `nodii-coordinator-watch.service` on Linux), whether its keepalive job is enabled (it is, unless `~/.config/nodii-dev/coordinator/hold-keepalive` exists), and when keepalive last ran, with how long ago. `MISSING` for a daemon that is not installed or not running names `nodii-dev coordinator watch install`; for a held, not-yet-run, failing or late keepalive it names the hold file or the log. Other agents read `OK`. |
1450
+ | `lane_runtime` | Whether the lane runtime is found from a clean environment, not only from this shell's PATH: `claude`, plus `codex` when the machine has a Codex account. A lane is launched by name, so the name must be an executable file on the PATH of whatever starts it. A clean environment is the PATH of the service that resumes down lanes: where coordinator watch is installed, the PATH its unit or plist carries (written by `coordinator watch install`); where it is not, the service manager's own PATH (`systemctl --user show-environment` on Linux, launchd's PATH with Homebrew's directories on macOS). `OK` names where it is found there. `MISSING` says when only this shell finds it (a directory added to PATH by hand, such as the editor extension's `native-binary`), or that a link on the clean PATH points at nothing (such as `~/.local/bin/claude`), and names the fix: link the real file into a directory of yours on the clean PATH (`ln -sf REAL ~/.local/bin/claude`), or reinstall the runtime. Reads only. |
1304
1451
  | `lane_env` | Every `claude` and `codex` process whose working directory is in an active lane's worktree on this machine, and whether its environment carries `NODII_DEV_CONFIG_PATH` naming that lane's `lane-<key>.json`. The managed hooks exit without acting for a process without it (AGENT-HARNESS-61). Run inside a lane, it checks that lane only. `MISSING` names each process; `lane launch` and `lane resume` start the agent with the variable set. `lane check` prints the same report for its lane as `lane_env:` lines, without blocking the review. |
1305
1452
 
1306
1453
  Doctor may refresh the access token, as any command does. The permission table
@@ -1517,7 +1664,13 @@ continuations included, the supervisor heartbeats its run every
1517
1664
  runtime that is alive but writes nothing gets no heartbeat from the supervisor,
1518
1665
  so it goes Quiet at 15 minutes and Orphan at 45 (MW1-36). `lane heartbeat` and
1519
1666
  the harness's `hook lane-heartbeat` (on `PostToolUse` and `Stop`) also heartbeat
1520
- the run. After the last continuation, the exit is
1667
+ the run. The hook beats at most once a minute per worktree. It reads its lane
1668
+ from Dev once and keeps the lane's id and key in the worktree's git private dir
1669
+ (`nodii-lane-heartbeat-lane.json`, beside `nodii-lane.json`), so a beat is one
1670
+ small POST. It reads the lane again when the branch or the lane key changes,
1671
+ when Dev answers that the lane is gone or ended (`LANE_NOT_FOUND`,
1672
+ `LANE_TERMINAL`), and after an hour. A worktree with no lane asks again after
1673
+ five minutes (hub-528). After the last continuation, the exit is
1521
1674
  reported as above and its reason counts the continuations. A supervisor runs
1522
1675
  the CLI version that started it, so a fix to this rule reaches a lane only
1523
1676
  when it is launched or resumed on that version.
package/dist/cli.js CHANGED
@@ -83,6 +83,7 @@ import { changeSetCommand, guidelineCommand } from "./guidelines.js";
83
83
  import { designCheck, designCheckChangeSet, designCheckText, designRoles, designRolesText, surfacesBehind, surfacesBehindText } from "./design.js";
84
84
  import { assertKnownFlags } from "./flags.js";
85
85
  import { SURFACE_USAGE, surfaceCommand } from "./surface.js";
86
+ import { CORPUS_USAGE } from "./surface-corpus.js";
86
87
  import { installWatchdog, watchdogCommand } from "./watchdog.js";
87
88
  import { machineCapacityCommand } from "./accounts.js";
88
89
  import { prepareGate, receiptCommand, syncCommand } from "./receipt.js";
@@ -146,7 +147,8 @@ Usage: nodii-dev <command> [options] [--json]
146
147
  # login says so when the machine is already signed in; --force
147
148
  # replaces that one sign-in (never from a lane)
148
149
  doctor [--figma-file KEY] [--json] # preflight: sign-in, agent, permissions, machine, repo, lane slots,
149
- # local Ollama + pinned Gather model, and optional Figma registration
150
+ # local Ollama + pinned Gather model, the Figma token, the coordinator watch daemon (for a
151
+ # coordinator), whether a clean environment finds the lane runtime, and optional Figma registration
150
152
  agent register --name NAME | agent heartbeat
151
153
  agent rename [ID] --name NAME # fix a name; no ID renames this config's agent, an ID
152
154
  # may be another of your own agents
@@ -195,7 +197,19 @@ Usage: nodii-dev <command> [options] [--json]
195
197
  # --report writes the unmapped layers per file (U08-14), .md or .json;
196
198
  # --all --fetch skips and reports a Surface that is not published;
197
199
  # --post-scoreboard comments the per-module scoreboard on the issue;
198
- # a 429 stops the read, and --fetch --write --resume keeps what is saved
200
+ # --fetch reads through the machine's Figma queue (one call per 8 s per token);
201
+ # a 429 is retried twice after Retry-After, then stops the read, and
202
+ # --fetch --write --resume keeps what is saved
203
+ surface corpus [--ds DIR] [--ref REV] [--module M] [--report FILE] [--baseline FILE] [--update]
204
+ # the generator's corpus gate (plan: docs/generator-plan): regenerates every
205
+ # committed Surface offline from a design-system checkout at the pinned commit
206
+ # (test/corpus/design-system.ref; never Figma, nothing written there), scans what
207
+ # the generator wrote and holds the counts per page to test/corpus/baseline.json:
208
+ # fixed samples, suspect copy, undecided, unmapped layers, shallow input. Exit 1
209
+ # (SURFACE_CORPUS_FAILED) on a Surface that throws, an unresolved import or
210
+ # identifier, or any count that differs. --update rewrites the baseline and
211
+ # refuses to raise a count; --report writes every finding as JSON. --ds defaults
212
+ # to NODII_CORPUS_DS, then design-system beside this repository
199
213
  figma lock FILE_KEY --title TEXT [--scope KIND:ID ...] [--lane-reads FILE]
200
214
  # scopes: component:NODE page:NODE section:NODE foundations create:PAGE:NAME;
201
215
  # no --scope locks the whole file (DEC-0032)
@@ -206,7 +220,8 @@ Usage: nodii-dev <command> [options] [--json]
206
220
  figma publish-plan FILE_KEY [--lane-reads FILE]
207
221
  # what to publish, and what to leave unchecked in Figma's dialog. With
208
222
  # --lane-reads Dev runs no job: it takes your MCP reads, and the version
209
- # compares run here through REST on FIGMA_PAT, paced, stopping at a 429
223
+ # compares run here through REST on FIGMA_PAT, in the machine's Figma queue;
224
+ # a 429 is retried twice after Retry-After, then stops the run
210
225
  figma published FILE_KEY|CHANGE_SET --figma-version V [--lane-reads FILE]
211
226
  # a file key marks every awaiting set published. Dev reads no Figma here:
212
227
  # FIGMA_READS_NEEDED names a node to place, or a version it hasn't seen
@@ -1098,7 +1113,8 @@ export async function main(argv = process.argv.slice(2)) {
1098
1113
  return;
1099
1114
  }
1100
1115
  if (command === "surface") {
1101
- if (action !== "generate") throw new CliError("USAGE", SURFACE_USAGE, 2);
1116
+ if (action === "corpus") return emitCommand(await (await import("./surface-corpus.js")).corpusCommand(rest, f));
1117
+ if (action !== "generate") throw new CliError("USAGE", `${SURFACE_USAGE}\n${CORPUS_USAGE}`, 2);
1102
1118
  return emitCommand(await surfaceCommand(action, rest, f));
1103
1119
  }
1104
1120
  if (command === "chrome") return emitCommand(await (await import("./chrome.js")).chromeCommand(action, rest, f));
@@ -27,7 +27,7 @@ import {
27
27
  DEFAULT_DOMAINS, boardCommand, coordinatorHome, heavyQueue, laneDomain, laneProcesses, liveChangeSets, machineLanes, readCoordinatorSettings,
28
28
  } from "./coordinator-board.js";
29
29
  import { governorMachineId } from "./governor.js";
30
- import { envAssignment, execLine, installNote, installSupervised, lingerLine, logsDir, supervisedDirs, unitPath, unitText } from "./systemd.js";
30
+ import { envAssignment, execLine, installNote, installSupervised, lingerLine, logsDir, supervisedDirs, unitActive, unitPath, unitText } from "./systemd.js";
31
31
 
32
32
  const execFile = promisify(execFileCallback);
33
33
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -308,16 +308,15 @@ export const JOB_RUNNERS = {
308
308
  // ---- The context the jobs run in ----------------------------------------------
309
309
 
310
310
  const FIGMA_PAT_SERVICE = "nodii-dev-figma-pat";
311
- const figmaPatStoreCommand = (os) => os === "linux"
312
- ? `secret-tool store --label "nodii-dev Figma token" service ${FIGMA_PAT_SERVICE} account "$USER"`
313
- : `security add-generic-password -s ${FIGMA_PAT_SERVICE} -a "$USER" -w`;
314
-
315
- /** The Figma token from the machine's secret store: the macOS keychain, or the Secret Service on Linux. */
316
- export async function figmaPatFromKeychain(execute, os = platform()) {
317
- const [command, args] = os === "linux"
318
- ? ["secret-tool", ["lookup", "service", FIGMA_PAT_SERVICE]]
319
- : ["security", ["find-generic-password", "-s", FIGMA_PAT_SERVICE, "-w"]];
320
- try { return (await execute(command, args, { timeout: 10_000 })).stdout.trim() || null; }
311
+ const figmaPatStoreCommand = `security add-generic-password -s ${FIGMA_PAT_SERVICE} -a "$USER" -w`;
312
+
313
+ /**
314
+ * The Figma token from the macOS keychain. Only publish-watch reads it, and
315
+ * publish-watch answers "macOS only" on every other platform, so there is no
316
+ * Linux (Secret Service) path to keep.
317
+ */
318
+ export async function figmaPatFromKeychain(execute) {
319
+ try { return (await execute("security", ["find-generic-password", "-s", FIGMA_PAT_SERVICE, "-w"], { timeout: 10_000 })).stdout.trim() || null; }
321
320
  catch { return null; }
322
321
  }
323
322
 
@@ -365,8 +364,8 @@ export function watchContext({ home = homedir(), request = devRequest, config =
365
364
  const { figmaPublish } = await import("./figma-publish.js");
366
365
  const env = { ...process.env };
367
366
  if (!env.FIGMA_PAT && !env.FIGMA_TOKEN) {
368
- const pat = await figmaPatFromKeychain(execute, os);
369
- if (!pat) throw new CliError("FIGMA_TOKEN_REQUIRED", `publish-watch needs a Figma token to read the new version: store it once with ${figmaPatStoreCommand(os)}`, 1);
367
+ const pat = await figmaPatFromKeychain(execute);
368
+ if (!pat) throw new CliError("FIGMA_TOKEN_REQUIRED", `publish-watch needs a Figma token to read the new version: store it once with ${figmaPatStoreCommand}`, 1);
370
369
  env.FIGMA_PAT = pat;
371
370
  }
372
371
  return figmaPublish(file, { sets: ids.join(",") }, { request, home, env });
@@ -481,6 +480,44 @@ export async function watchStatus({ home = homedir(), now = Date.now, os = platf
481
480
  return { running, pid, jobs, unreadAlerts: unread, log };
482
481
  }
483
482
 
483
+ /**
484
+ * Whether the daemon is installed and running (launchd on macOS, a systemd user
485
+ * service on Linux), and what its keepalive job did last: doctor's
486
+ * coordinator_watch line. Reads only. Keepalive is enabled unless its hold file
487
+ * is present (runJob skips a held job); `late` is watchStatus's own measure.
488
+ */
489
+ export async function coordinatorWatchStatus({ home = homedir(), uid = process.getuid?.(), os = platform(), execute = execFile, now = Date.now } = {}) {
490
+ let manager;
491
+ let label;
492
+ let path;
493
+ let log;
494
+ let active = false;
495
+ if (os === "linux") {
496
+ const { unitDir, logs } = await supervisedDirs({ home, execute });
497
+ [manager, label, path, log] = ["systemd", WATCH_SERVICE, join(unitDir, WATCH_SERVICE), join(logs, "coordinator-watch.log")];
498
+ } else if (os === "darwin") {
499
+ [manager, label, path, log] = ["launchd", WATCH_LABEL, join(home, "Library", "LaunchAgents", `${WATCH_LABEL}.plist`), watchLogPath(home, os)];
500
+ } else return { supported: false, manager: null, label: null, path: null, log: null, installed: false, active: false, keepalive: null };
501
+ const installed = await exists(path);
502
+ if (installed && os === "linux") active = await unitActive(WATCH_SERVICE, { execute });
503
+ // `launchctl print` exits 0 for any loaded job, so a KeepAlive job that crashed and waits out its
504
+ // ThrottleInterval ("state = not running") is loaded but not running: read the state line.
505
+ else if (installed) { try { active = /^\s*state = running$/m.test((await execute("launchctl", ["print", `gui/${uid}/${WATCH_LABEL}`])).stdout); } catch {} }
506
+ const record = (await readJson(statePath(home), { jobs: {} })).jobs?.keepalive ?? null;
507
+ const holdFile = holdPath(home, "keepalive");
508
+ const held = await exists(holdFile);
509
+ const lastStart = record?.lastStart ?? null;
510
+ return {
511
+ supported: true, manager, label, path, log, installed, active,
512
+ keepalive: {
513
+ enabled: !held, held, holdFile, lastStart, lastOk: record?.lastOk ?? null, ok: record ? Boolean(record.ok) : null,
514
+ summary: record?.summary ?? null, failures: record?.failures ?? 0, intervalMinutes: JOBS.keepalive / MIN,
515
+ late: lastStart !== null && now() - Date.parse(lastStart) > JOBS.keepalive * 2 + 5 * MIN,
516
+ minutesAgo: lastStart === null ? null : Math.max(0, Math.round((now() - Date.parse(lastStart)) / MIN)),
517
+ },
518
+ };
519
+ }
520
+
484
521
  export async function unreadAlerts({ home = homedir(), all = false, markRead = false } = {}) {
485
522
  const lines = (await readFile(alertsPath(home), "utf8").catch(() => "")).split("\n").filter(Boolean);
486
523
  const read = Number((await readFile(alertsReadPath(home), "utf8").catch(() => "0")).trim()) || 0;
@@ -529,6 +566,32 @@ export function watchUnit({ runtime, entry, config, log, path }) {
529
566
  ]);
530
567
  }
531
568
 
569
+ /** The file's text, or "" when it does not exist; any other read failure propagates, so doctor says it cannot check. */
570
+ async function readServiceFile(file) {
571
+ try { return await readFile(file, "utf8"); } catch (error) { if (error?.code === "ENOENT") return ""; throw error; }
572
+ }
573
+
574
+ /**
575
+ * The PATH the installed daemon starts with: the one `install` wrote into its
576
+ * unit or plist, read back (the inverse of watchUnit's and watchPlist's own
577
+ * escaping). Null when the daemon is not installed or its file holds no PATH.
578
+ * The daemon is what resumes down lanes, so this, and not the service
579
+ * manager's own PATH, is what a lane's runtime must be found on (doctor's
580
+ * lane_runtime line).
581
+ */
582
+ export async function watchServicePath({ home = homedir(), os = platform(), execute = execFile } = {}) {
583
+ if (os === "linux") {
584
+ const { unitDir } = await supervisedDirs({ home, execute });
585
+ const found = /^Environment="PATH=(.*)"$/m.exec(await readServiceFile(join(unitDir, WATCH_SERVICE)));
586
+ return found ? found[1].replace(/\\(["\\])|%%/g, (_, escaped) => escaped ?? "%") : null;
587
+ }
588
+ if (os === "darwin") {
589
+ const found = /<key>PATH<\/key><string>([^<]*)<\/string>/.exec(await readServiceFile(join(home, "Library", "LaunchAgents", `${WATCH_LABEL}.plist`)));
590
+ return found ? found[1].replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", '"').replaceAll("&apos;", "'").replaceAll("&amp;", "&") : null;
591
+ }
592
+ return null;
593
+ }
594
+
532
595
  /**
533
596
  * Installs the daemon for this machine's coordinator. The plist or unit names
534
597
  * the coordinator's own config; it carries no secret (the Figma token stays in
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.172";
7
+ export const VERSION = "0.6.173";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
@@ -434,6 +434,16 @@ export function requireFlag(flags, name) {
434
434
  return value;
435
435
  }
436
436
 
437
+ /**
438
+ * The lane read a hook makes (hub-528): `view=hook` asks Dev for only the
439
+ * fields the hooks read off a lane, in place of the whole lane with its
440
+ * timeline. A Dev that does not know the view answers with the whole lane,
441
+ * which holds every one of those fields.
442
+ */
443
+ export const hookLanePath = (key) => `/api/v1/lanes/${encode(key)}?view=hook`;
444
+ /** The lane statuses a hook counts as live; also the list filter it sends. */
445
+ export const LIVE_LANE_STATUSES = ["queued", "building", "built", "review", "on_main"];
446
+
437
447
  export const query = (pairs) => {
438
448
  const p = new URLSearchParams();
439
449
  for (const [key, value] of Object.entries(pairs))
package/dist/design.js CHANGED
@@ -8,10 +8,10 @@
8
8
  // library main.
9
9
  import { readFile } from "node:fs/promises";
10
10
  import { CliError, devRequest } from "./core.js";
11
+ import { FIGMA_API, figmaRest } from "./figma-rest.js";
11
12
  import { conformanceLines, figmaConformance, figmaFileKey, laneReadsBody, submitMode, surfacesCheck } from "./figma.js";
12
13
  import { checkConformance, neededMains, VERSION as CHECK_VERSION } from "./vendor/ds-conformance.mjs";
13
14
 
14
- const FIGMA_API = "https://api.figma.com/v1";
15
15
  // The Figma nodes endpoint takes many ids per call; keep URLs well short of limits.
16
16
  const IDS_PER_CALL = 50;
17
17
  // Dev's gate stops after six rounds of mains; so does the check here.
@@ -90,35 +90,23 @@ export function figmaToken(env = process.env) {
90
90
  return token;
91
91
  }
92
92
 
93
- /** A Figma REST GET, retried on 429 and 5xx. */
94
- export function figmaClient(token, { fetchImpl = fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), attempts = 6, timeoutMs = 120_000 } = {}) {
95
- return async function figmaGet(path) {
96
- for (let attempt = 1; ; attempt++) {
97
- let response;
98
- try {
99
- response = await fetchImpl(`${FIGMA_API}${path}`, { headers: { "X-Figma-Token": token }, signal: AbortSignal.timeout(timeoutMs) });
100
- // The clock runs while a large body streams in, too.
101
- if (response.ok) return await response.json();
102
- } catch (error) {
103
- if (error instanceof SyntaxError) throw new CliError("FIGMA_ERROR", `Figma answered ${path.split("?")[0]} with a body that isn't JSON`);
104
- // A read that runs out the clock is too large, and would again: say how to narrow it.
105
- if (error?.name === "TimeoutError")
106
- throw new CliError("FIGMA_TIMEOUT", `Figma took over ${timeoutMs / 1000}s for ${path.split("?")[0]}; check fewer nodes with --nodes`);
107
- if (attempt >= attempts) throw new CliError("FIGMA_UNREACHABLE", `Cannot reach Figma: ${error.message}`);
108
- await sleep(1000 * attempt);
109
- continue;
110
- }
111
- const retry = response.status === 429 || response.status >= 500;
112
- if (retry && attempt < attempts) {
113
- const after = Number(response.headers?.get?.("retry-after"));
114
- await sleep(Number.isFinite(after) && after > 0 ? Math.min(after, 60) * 1000 : 1000 * 2 ** attempt);
115
- continue;
116
- }
117
- const code = { 404: "FIGMA_NOT_FOUND", 403: "FIGMA_FORBIDDEN", 429: "FIGMA_RATE_LIMITED" }[response.status] ?? "FIGMA_ERROR";
118
- const hint = response.status === 400 ? " (a malformed node id, or a request too large? check the ids, or fewer nodes, with --nodes)" : "";
119
- throw new CliError(code, `Figma answered ${response.status} for ${path.split("?")[0]}${hint}`, 1, { status: response.status });
120
- }
121
- };
93
+ /**
94
+ * The Figma REST GET of a design check: the machine's shared client (cli-170),
95
+ * with this command's waits. Calls on one token are queued across the machine;
96
+ * a 429 waits Retry-After and is sent again at most twice; a 5xx is retried;
97
+ * a read that runs out the clock is final; a read at a pinned version is cached.
98
+ */
99
+ export function figmaClient(token, { attempts = 6, timeoutMs = 120_000, ...options } = {}) {
100
+ return figmaRest(token, {
101
+ attempts,
102
+ timeoutMs,
103
+ serverBackoffMs: (attempt) => 1000 * 2 ** attempt,
104
+ errorBackoffMs: (attempt) => 1000 * attempt,
105
+ // A read that runs out the clock is too large, and would again: say how to narrow it.
106
+ timeoutError: (path) => new CliError("FIGMA_TIMEOUT", `Figma took over ${timeoutMs / 1000}s for ${path.split("?")[0]}; check fewer nodes with --nodes`),
107
+ hint: (status) => (status === 400 ? " (a malformed node id, or a request too large? check the ids, or fewer nodes, with --nodes)" : ""),
108
+ ...options,
109
+ });
122
110
  }
123
111
 
124
112
  const chunks = (list, size) => Array.from({ length: Math.ceil(list.length / size) }, (_, i) => list.slice(i * size, (i + 1) * size));
package/dist/doctor.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { readFile } from "node:fs/promises";
2
- import { homedir } from "node:os";
2
+ import { homedir, platform } from "node:os";
3
3
  import { basename, join, resolve } from "node:path";
4
4
  import { devRequest, encode, isOAuthConfig, query, setAuthProvider } from "./core.js";
5
5
  import { OAuthAuthProvider, decodeClaims, loadRefreshToken } from "./oauth.js";
@@ -12,6 +12,11 @@ import { hostBootedAt } from "./host.js";
12
12
  import { listAccounts } from "./accounts.js";
13
13
  import { LANE_ENV_FIX, agentProcesses, laneConfigName, laneEnvProblem, laneEnvReport } from "./lane-env.js";
14
14
  import { watchdogStatus } from "./watchdog.js";
15
+ import { coordinatorWatchStatus } from "./coordinator-watch.js";
16
+ import { describeRuntime, laneRuntimeReport } from "./lane-runtime.js";
17
+
18
+ // Where to set the Figma token for each shell, said the same way wherever doctor asks for it.
19
+ const FIGMA_TOKEN_FIX_TEXT = "zsh: add export FIGMA_PAT=... to ~/.zshenv; bash: add export FIGMA_PAT=... to ~/.bashrc (or ~/.bash_profile for a login shell); fish: run set -Ux FIGMA_PAT ...";
15
20
 
16
21
  /**
17
22
  * What a lane's commands need, in Dev's route policy (staffRuleFor in Dev's
@@ -427,6 +432,62 @@ export async function doctorCommand(deps = {}) {
427
432
  }
428
433
  }
429
434
 
435
+ // The Figma token (hub-527): design check, surface generate --fetch, the lane's
436
+ // publish compares and the --figma preflight read it from the environment as
437
+ // FIGMA_PAT, or FIGMA_TOKEN. Only the variable's name is said, never its value.
438
+ {
439
+ const name = ["FIGMA_PAT", "FIGMA_TOKEN"].find((key) => env[key]);
440
+ if (name) checks.push(ok("figma_token", `${name} is set in the environment`, { variable: name }));
441
+ else checks.push(missing("figma_token", "no Figma token: neither FIGMA_PAT nor FIGMA_TOKEN is set in the environment", FIGMA_TOKEN_FIX_TEXT));
442
+ }
443
+
444
+ // The machine's coordinator watch daemon (launchd on macOS, a systemd user
445
+ // service on Linux): it resumes down lanes through its keepalive job, so a
446
+ // missing, stopped, held or stale one leaves them down. It is the
447
+ // coordinator's to keep, so a lane reads ok here, as for the watchdog.
448
+ if (!agent?.machineId) checks.push(cannot("coordinator_watch", "needs a machine"));
449
+ else if (agent.role !== "coordinator") checks.push(ok("coordinator_watch", "the machine's coordinator keeps coordinator watch running"));
450
+ else {
451
+ const installFix = `${prefix}nodii-dev coordinator watch install`;
452
+ try {
453
+ const job = await (deps.coordinatorWatchStatus ?? coordinatorWatchStatus)({ home: deps.home ?? homedir(), now: deps.now ?? Date.now });
454
+ const keepalive = job.keepalive;
455
+ const extra = { manager: job.manager, label: job.label, path: job.path, log: job.log, installed: job.installed, active: job.active, keepalive };
456
+ const ago = keepalive?.lastStart ? `${keepalive.lastStart} (${keepalive.minutesAgo} min ago)` : null;
457
+ if (!job.supported) checks.push(cannot("coordinator_watch", "coordinator watch installs on macOS (launchd) and Linux (systemd) only", extra));
458
+ else if (!job.installed) checks.push(missing("coordinator_watch", `${job.label} is not installed (${job.manager}); keepalive does not resume down lanes`, installFix, extra));
459
+ else if (!job.active) checks.push(missing("coordinator_watch", `${job.label} is installed but not running (${job.manager}); keepalive does not resume down lanes`, installFix, extra));
460
+ else if (keepalive.held) checks.push(missing("coordinator_watch", `${job.label} is running, but keepalive is held (${keepalive.holdFile} exists), so down lanes are not resumed${ago ? `; it last ran ${ago}` : ""}`, `rm ${keepalive.holdFile} when the hold is over`, extra));
461
+ else if (!keepalive.lastStart) checks.push(missing("coordinator_watch", `${job.label} is running, but keepalive has not run yet`, `tail -n 50 ${job.log}`, extra));
462
+ else if (keepalive.ok === false) checks.push(missing("coordinator_watch", `${job.label} is running, but keepalive's last run (${ago}) failed ${keepalive.failures} time(s) running: ${keepalive.summary}`, `tail -n 50 ${job.log}`, extra));
463
+ else if (keepalive.late) checks.push(missing("coordinator_watch", `${job.label} is running, but keepalive last ran ${ago}, which is late (it runs every ${keepalive.intervalMinutes} min)`, `tail -n 50 ${job.log}`, extra));
464
+ else checks.push(ok("coordinator_watch", `${job.label} is running (${job.manager}); keepalive is enabled and last ran ${ago}`, extra));
465
+ } catch (error) {
466
+ checks.push(cannot("coordinator_watch", error?.message ?? String(error)));
467
+ }
468
+ }
469
+
470
+ // The lane runtime (hub-527): a lane is launched by name, so `claude` (or `codex`
471
+ // for a Codex account) must be an executable file on the PATH of whatever
472
+ // starts it. A shell given the directory by hand finds it; coordinator watch,
473
+ // which resumes down lanes, may not: it has the PATH its unit or plist was
474
+ // written with, or the service manager's own where it is not installed. A
475
+ // runtime is found only when that clean environment finds it.
476
+ try {
477
+ const wanted = [...new Set((profiles ?? []).map((profile) => profile.runtime))];
478
+ const report = await (deps.laneRuntimeReport ?? laneRuntimeReport)({ runtimes: wanted.length ? wanted : ["claude"], shellPath: env.PATH, os: deps.os ?? platform(), home: deps.home ?? homedir(), execute: deps.execute });
479
+ if (!report.supported) checks.push(cannot("lane_runtime", "a clean environment is defined for macOS (launchd) and Linux (systemd) only"));
480
+ else {
481
+ const described = report.rows.map((row) => ({ row, ...describeRuntime(row, { cleanPath: report.cleanPath, cleanSource: report.cleanSource, home: deps.home ?? homedir() }) }));
482
+ const extra = { cleanPath: report.cleanPath, cleanSource: report.cleanSource, runtimes: report.rows.map((row) => ({ runtime: row.runtime, clean: row.clean.path, shell: row.shell.path, dangling: row.clean.dangling })) };
483
+ const bad = described.filter((item) => !item.ok);
484
+ if (!bad.length) checks.push(ok("lane_runtime", described.map((item) => item.message).join("; "), extra));
485
+ else checks.push(missing("lane_runtime", bad.map((item) => item.message).join("; "), bad.map((item) => item.fix).join("; "), extra));
486
+ }
487
+ } catch (error) {
488
+ checks.push(cannot("lane_runtime", error?.message ?? String(error)));
489
+ }
490
+
430
491
  // No managed hooks means no managed copy: the hook checks above report that.
431
492
  try {
432
493
  // Someone asked now, so not the hour-old answer SessionStart can use: it would