@nodii/dev 0.6.73 → 0.6.74

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
@@ -400,13 +400,33 @@ nodii-dev hook claude-figma-pre # reads Claude Code hook JSON on stdin
400
400
  nodii-dev hook claude-figma-post # reads Claude Code hook JSON on stdin
401
401
  nodii-dev hook safety-pre # silent safety decision; blocks with exit 2
402
402
  nodii-dev hook safety-post # silently records resources created by successful commands
403
- nodii-dev hook nudge-pre # guideline nudges before a tool call; never blocks
403
+ nodii-dev hook nudge-pre # guideline nudges before a tool call; never blocks. In a steward
404
+ # session: cite before you steer (MW1-95)
405
+ nodii-dev hook surface-gen-pre # MW8-17 Surface-generation nudge; every session, never blocks
406
+ nodii-dev hook session-start # every SessionStart: the session's kind and contract (MW1-92); after
407
+ # compaction also the lane's or steward's Freeze
408
+ nodii-dev hook session-kind # first prompt only: confirms or corrects the kind from the prompt
409
+ nodii-dev steward register --focus TEXT --repos R,... # a steward is a lane of kind steward (MW1-93)
404
410
  nodii-dev hook nudge-stop # holds a lane session's stop until its done check is recorded;
405
411
  # guideline nudges when a lane session stops; asks once
406
412
  nodii-dev figma checked CS-n --unused-properties --stale-placeholders --dialog-body
407
413
  nodii-dev hook print-settings # prints managed-settings JSON; writes nothing
408
414
  ```
409
415
 
416
+ **Session kinds (DEC-0421, MW1-92 to MW1-96).** Every session is a lane, a
417
+ coordinator, a steward or an operator assistant. `hook session-start` reads it
418
+ from Dev: a lane record for the worktree, a steward registration for the agent,
419
+ or the agent's coordinator role; `hook session-kind` reads the first prompt
420
+ ("You are lane X", "You are the steward"). Dev's record wins, and a prompt that
421
+ disagrees is printed as a note. Both print `kind: <kind>` and its contract. The
422
+ managed dispatcher runs these two, and `nudge-pre` for a possible steering act,
423
+ in every session; every other managed hook stays lane-only. A steward is a lane
424
+ of kind `steward` with no branch or worktree (`steward register`), so
425
+ `lane gather <key> --picker agent`, the Freeze and the post-compaction
426
+ re-grounding work for it unchanged; a fresh steward session prints its Clause
427
+ map. Gather pins the always-on clauses for a lane's repository and side
428
+ (`GET /rules/gather-pins`), marked `always-on` in the Clause map.
429
+
410
430
  `hook safety-pre` (installed by `harness install` for Claude Code and Codex)
411
431
  blocks, silently when satisfied (AGENT-HARNESS-15):
412
432
 
@@ -655,6 +675,22 @@ in any session that is not a Dev lane. Each cites the clause it protects.
655
675
  | AskUserQuestion | The question is also an item in `docs/figma-ux-drive/qa-with-abhi/open.md` (R7) | open.md already holds the question |
656
676
  | Stop | The lane is not `on_dev` but "done" was claimed (MW3); an "I couldn't" with no filed issue; Unconfirmed Freeze items still open; uncommitted work | none of those; a Stop that was already nudged once may stop |
657
677
 
678
+ **One nudge reaches every session, lane or not: Surface generation (MW8-17).**
679
+ Product pages in the design-system repository are generated from their
680
+ Surfaces through Code Connect. An Edit, Write, MultiEdit or `apply_patch` of a
681
+ product-page source (`packages/blocks/src/product-pages/**/*.tsx`, not its
682
+ tests, stories, fixtures or catalog data) that changes JSX elements,
683
+ `className` or `style` (in a tag, or a class list built with `cn`, `clsx`,
684
+ `cva` or `twMerge`) gets the nudge; a data-prop, callback or prop-wiring edit
685
+ gets nothing (DS-BLK-1). Inside a lane it comes through `hook nudge-pre`.
686
+ Outside a lane the managed dispatcher sends such an edit (its payload
687
+ names `product-pages/` and an edit tool) to `hook surface-gen-pre`, which reads
688
+ the edit alone: no Dev, no git, no lane. It ships in the managed hook install:
689
+ `harness update --system` stages it, and a plain `harness install` or
690
+ `harness update` refreshes an already staged dispatcher in place, keeping the
691
+ CLI path its metadata names and stamping `dispatchVersion` there with the
692
+ nodii-dev that rewrote it (MW5-6). The root-owned managed settings do not change.
693
+
658
694
  The lane's gathered set is the private Git file `nodii-lane-knowledge.json`:
659
695
  `lane gather --components a,b` adds the components it covered to `guidelines`,
660
696
  `lane gather --delta` adds the paths it saw (`--paths`, else every path this
@@ -754,6 +790,79 @@ version. A set never submitted needs `--file`: the body `figma submit --file`
754
790
  would send. A cold run can outlast the edge's gateway; the CLI then says
755
791
  `DEV_TIMEOUT` and to run it again (Dev keeps the mains it read for 5 minutes).
756
792
 
793
+ ### Whole-file Surfaces check: `design check --surfaces` (DESIGN-SYSTEM-253)
794
+
795
+ ```bash
796
+ nodii-dev design check --surfaces FILE_KEY|LINK [--all] [--json]
797
+ ```
798
+
799
+ Dev reads every "Surface / …" set in a Surfaces file, a few at a time at
800
+ Figma's pace, and lists every layer the product-page generator cannot map
801
+ (U08-14): `looseText` (a text layer outside a DS instance), `selfPainted` (a
802
+ frame or shape outside a DS instance that paints its own fill or stroke),
803
+ `noAutoLayout` (a frame or group holding layers without auto layout),
804
+ `unboundValue` (a solid colour, gap, padding, corner radius or stroke width not
805
+ bound to a variable) and `nonDsInstance` (an instance of a local component that
806
+ is not the file's own Surface, or of a component no registered library
807
+ publishes). Dev runs it as a job (`startDesignSurfacesCheck`), and the CLI polls
808
+ it (`getDesignSurfacesCheckJob`), printing progress on stderr. Dev reads Figma
809
+ on its own token, so `FIGMA_PAT` isn't needed.
810
+
811
+ The text lists the findings by Surface, then up to 20 of each check (`--all`
812
+ lists every one; `--json` gives the full report, each finding with its node id,
813
+ Surface and page). Exit 1 (`SURFACES_CHECK_FAILED`) when any finding is listed.
814
+ Submit checks the same findings on any Surface node a change set touches. By
815
+ default it only reports them (in the dry run's and the submit's `warnings`); it
816
+ refuses them only for the Surfaces files the host enforces, which the Steward
817
+ turns on per file once that product's cleanup lands. A file not registered as Surfaces
818
+ is refused `NOT_A_SURFACES_FILE`; `SURFACES_CHECK_JOB_LOST` means Dev restarted:
819
+ run the same command again.
820
+
821
+ ### Product pages from Surfaces: `surface generate` (MW8-17)
822
+
823
+ ```sh
824
+ nodii-dev surface generate <componentSetKey|route> [--write] [--check] [--fetch] [--figma-version V] [--report FILE]
825
+ nodii-dev surface generate --all [--module M] [--type page|dialog] [--write] [--check] [--fetch] [--report FILE]
826
+ ```
827
+
828
+ Run in a design-system checkout. It turns a Figma Surface into its product
829
+ page's presentational code, mechanically, so nobody draws a page by hand. The
830
+ product-page catalog names the Surface by its published component-set key
831
+ (MW8-20), never a node id; a frontend route picks every Surface on it.
832
+
833
+ - **`--fetch`** reads the Surface set from Figma's REST nodes API with
834
+ `FIGMA_PAT` (read-only, one call per 8 s, a 429 waits Retry-After or 30 s
835
+ doubling), at the version the committed tree pins (or `--figma-version`, or
836
+ the Surface reference's). Without it, the committed tree under
837
+ `docs/figma-ux-ds/figma/surface-trees/<fileKey>/<componentSetKey>.json` is
838
+ read and Figma is not called.
839
+ - Each DS instance is emitted through its Code Connect template exactly as the
840
+ template gives it (component, props, import), run by the design system's own
841
+ template harness, vendored byte-for-byte in `src/vendor/render-templates.mjs`
842
+ (sha256 pinned in `test/surface.test.js`). Auto-layout becomes flex or grid
843
+ with Tailwind spacing steps, never an arbitrary value. Table parts that a
844
+ Surface draws as rows of frames are put in the DS Table's own anatomy, and
845
+ each head and cell declares its column `width` as Figma sizes it (px for
846
+ FIXED, `"fill"`, `"hug"`; DESIGN-SYSTEM-177) unless its template already
847
+ does. A table with no hug column gets `layout="fixed"`.
848
+ - Loose text takes the DS type utility and colour v2 role, and nothing else.
849
+ A frame that paints its own fill, stroke, radius or effect keeps only its
850
+ layout. A shape, or a library instance with no template, is a marked gap in
851
+ the code, never a look-alike (MW2-37.2). Each of these is a Surface layer
852
+ with no Code Connect mapping (U08-14). `--report FILE` writes that list per Figma file
853
+ (`.md`, or `.json`).
854
+ - **`--write`** writes `<page>.surface.generated.tsx` beside the hand-built
855
+ page (and, with `--fetch`, the tree). It exports `<Id>Surface({ state })`,
856
+ one state per Surface variant, named as the catalog's `figma.states` name it.
857
+ That map is keyed by variant node id, so `--fetch` joins it while it reads
858
+ and the tree keeps only each variant's state name; no node id is committed
859
+ (MW8-20). A tree that still holds one is refused with `SURFACE_TREE_STALE`.
860
+ - **`--check`** writes nothing and exits 1 when a generated file differs from
861
+ the generator's output. The design system's `surface-gen-equal` CI gate runs
862
+ `surface generate --all --check` with a pinned `@nodii/dev`; `--all`
863
+ without `--fetch` covers the Surfaces that have a committed tree or a
864
+ generated file and lists the rest as not generated yet.
865
+
757
866
  ### Large sets: submit as a Dev job
758
867
 
759
868
  `figma submit`, `figma resubmit` and `design check --change-set` send
@@ -1224,15 +1333,32 @@ change; `show|history` reads the current contract or its append-only history.
1224
1333
  A lane Gather warms the local picker (Gemma) as it starts, alongside Dev's
1225
1334
  requests. Dev's requests share a 60 s deadline. The deadline stops while the
1226
1335
  pick runs: the pick waits for the warm-up (up to 180 s), then the first pick
1227
- has 120 s once the model is warm (`PICKER_TIMEOUT` past it, and the model is
1228
- unloaded). Each pick is logged on this Mac (`~/.cache/nodii-dev/gather-timings.jsonl`,
1336
+ has 120 s once the model is warm (past it, the model is unloaded and the pick
1337
+ falls back to the agent, below). Each pick is logged on this Mac (`~/.cache/nodii-dev/gather-timings.jsonl`,
1229
1338
  or `NODII_DEV_GATHER_TIMINGS`). Gather prints the pick's warm-up and pick time
1230
1339
  with this Mac's p50/p95, and `gather timings` prints the spread.
1231
- If this Mac has no picker (the model isn't installed, or no Ollama answers),
1232
- Gather falls back to the agent picker on the same shortlist. It prints
1233
- `picker: agent (gemma4:12b not installed; run nodii-dev setup)` and the
1340
+ **Choosing the Gather model on this Mac.** The local picker is `gemma4:12b` by
1341
+ default. A Mac with less memory can run the smaller `gemma4:e4b` instead: set
1342
+ `NODII_DEV_PICKER_MODEL=gemma4:e4b` in the shell profile, then run
1343
+ `nodii-dev setup --yes` (it pulls the model that is set) and `nodii-dev doctor`
1344
+ (it checks that model). The setting is per machine: other machines keep the
1345
+ default. Only models this CLI pins are accepted (`gemma4:12b`, `gemma4:e4b`,
1346
+ `gemma4:26b`), each with its pinned digest; any other value fails with a `USAGE`
1347
+ error that lists them. There is no `config.json` option, because that file is
1348
+ per-login and per-lane, not per-machine. `lane gather`, `lane check`,
1349
+ `gather picker-latency`, `gather timings`, the slow-picker fallback, `setup`
1350
+ and `doctor` all follow the setting.
1351
+
1352
+ If this Mac has no usable picker (the model isn't installed, no Ollama answers,
1353
+ or the model is too slow to answer within its budget), Gather falls back to the
1354
+ agent picker on the same shortlist. It prints
1355
+ `picker: agent (gemma4:12b not installed; run nodii-dev setup)` (it names the
1356
+ model this Mac is set to) and the
1234
1357
  shortlist, then the agent records its pick with `--picker agent --shortlist ID
1235
- --documents …`. A wrong model digest or a timeout still fails.
1358
+ --documents …`. A wrong model digest still fails. In `lane check`, the lane's
1359
+ own runtime (headless, no tools) makes that pick from Dev's shortlist and the
1360
+ Delta gather is recorded as `picker: agent`; an answer that names no offered
1361
+ document, or one Dev did not offer, is refused and nothing is recorded.
1236
1362
 
1237
1363
  `lane start` creates and starts a lane. It infers the repository (by short
1238
1364
  name, as Dev compares it), branch and worktree from git unless overridden, and resolves `--issue` keys to the UUIDs
package/dist/cli.js CHANGED
@@ -21,12 +21,13 @@ import {
21
21
  refuseFromLane,
22
22
  revokeOAuth,
23
23
  } from "./oauth.js";
24
- import { FIGMA_HOOK_DENIALS, heartbeatCurrentLane, postHook, postHookFailure, preHook, sessionStartContext, settingsSnippet, workflowSuggestion } from "./hooks.js";
24
+ import { FIGMA_HOOK_DENIALS, heartbeatCurrentLane, postHook, postHookFailure, preHook, settingsSnippet, workflowSuggestion } from "./hooks.js";
25
25
  import { setupCommand } from "./setup.js";
26
26
  import { harnessCommand } from "./harness.js";
27
27
  import { repoCommand } from "./repo-policy.js";
28
28
  import { hookRuntime, recordHookFire, safetyContext, safetyPostHook, safetyPreHook } from "./safety.js";
29
- import { SUBMIT_CHECK_FLAGS, changedPaths, nudgeCandidate, nudgePre, nudgeStop, recordGathered, recordGuidelineRead, recordSubmitChecks } from "./nudges.js";
29
+ import { SUBMIT_CHECK_FLAGS, changedPaths, nudgeCandidate, nudgePre, nudgeStop, recordGathered, recordGuidelineRead, recordSubmitChecks, steerAct, stewardSteerNudges, surfaceGenPre } from "./nudges.js";
30
+ import { activeSteward, firstPromptText, isLaneConfig, sessionStartText, stewardCommand } from "./session-kind.js";
30
31
  import { doctorCommand } from "./doctor.js";
31
32
  import { dispatchManagedClaudeHook, dispatchManagedHook } from "./managed-hooks.js";
32
33
  import { freezeCommand } from "./freeze.js";
@@ -62,11 +63,12 @@ import {
62
63
  } from "./figma.js";
63
64
  export { figmaLock, figmaWithdrawItems, figmaWithdrawItemsText, submitMode, withdrawItemsFrom } from "./figma.js";
64
65
  import { tuneCommand } from "./tune.js";
65
- import { PICKER_MODEL, TUNING_MODELS, measurePickerLatency, pickTimingStats, pickTimingText, pickTimingsPath, readPickTimings } from "./gather.js";
66
+ import { TUNING_MODELS, pickerModelName, pickerPin, measurePickerLatency, pickTimingStats, pickTimingText, pickTimingsPath, readPickTimings } from "./gather.js";
66
67
  import { docsCommand, rulebookCommand, rulesCommand } from "./upload.js";
67
68
  import { changeSetCommand, guidelineCommand } from "./guidelines.js";
68
69
  import { designCheck, designCheckChangeSet, designCheckText, designRoles, designRolesText, surfacesBehind, surfacesBehindText } from "./design.js";
69
70
  import { assertKnownFlags } from "./flags.js";
71
+ import { SURFACE_USAGE, surfaceCommand } from "./surface.js";
70
72
  import { installWatchdog, watchdogCommand } from "./watchdog.js";
71
73
  import { machineCapacityCommand } from "./accounts.js";
72
74
  import { prepareGate, receiptCommand, syncCommand } from "./receipt.js";
@@ -90,6 +92,7 @@ import {
90
92
  import {
91
93
  agentWorkflowCommand,
92
94
  builtCommand,
95
+ deltaGatherFlags,
93
96
  laneCommand,
94
97
  machineCommand,
95
98
  nextCommand,
@@ -150,6 +153,19 @@ Usage: nodii-dev <command> [options] [--json]
150
153
  design check --change-set CS [--file SUBMIT.json] [--figma-version V] [--sync]
151
154
  # Dev's dry run of the submit gate on a set, with the image guard;
152
155
  # a stale version is a warning that prints when to retry
156
+ design check --surfaces FILE_KEY|LINK [--all]
157
+ # Dev's whole-file Surfaces check (U08-14): every "Surface / ..." set,
158
+ # listing loose text, self-painted frames, frames without auto layout,
159
+ # values not bound to a variable and non-DS instances; submit reports the
160
+ # same on any Surface node a set touches (refuses where the host enforces).
161
+ # Reads Figma on Dev's token; exit 1 = SURFACES_CHECK_FAILED
162
+ surface generate <componentSetKey|route> [--write] [--check] [--fetch] [--figma-version V] [--report FILE]
163
+ surface generate --all [--module M] [--type page|dialog] [--write] [--check] [--fetch] [--report FILE]
164
+ # a Surface -> its product page's presentational code, from Code Connect
165
+ # (MW8-17), in a design-system checkout. --fetch reads Figma (FIGMA_PAT, one
166
+ # call per 8 s); --write writes <page>.surface.generated.tsx (and, with --fetch,
167
+ # the committed tree); --check refuses a difference (the surface-gen-equal gate);
168
+ # --report writes the unmapped layers per file (U08-14), .md or .json
153
169
  figma lock FILE_KEY --title TEXT [--scope KIND:ID ...]
154
170
  # scopes: component:NODE page:NODE section:NODE foundations create:PAGE:NAME;
155
171
  # no --scope locks the whole file (DEC-0032)
@@ -187,8 +203,15 @@ Usage: nodii-dev <command> [options] [--json]
187
203
  figma changeset show CHANGE_SET # write-up, items, context, variants, round, decision and comment (with the previous round's)
188
204
  figma file add FILE_KEY --name TEXT --kind design-system|surfaces|prototype [--module M]
189
205
  # register a Figma file in Dev so it can be locked
190
- hook claude-figma-pre|claude-figma-post|safety-pre|safety-post|nudge-pre|nudge-stop|session-start|managed-dispatch|claude-managed-dispatch|print-settings
206
+ hook claude-figma-pre|claude-figma-post|safety-pre|safety-post|nudge-pre|nudge-stop|surface-gen-pre|session-start|session-kind|managed-dispatch|claude-managed-dispatch|print-settings
207
+ # session-start and session-kind (first prompt) print the session's kind:
208
+ # lane, coordinator, steward or operator assistant, with its contract (MW1-92)
209
+ steward register --focus TEXT --repos R,... [--side frontend|backend|both] [--key KEY]
210
+ # a steward is a lane of kind steward with no branch or worktree (MW1-93);
211
+ # then lane gather <key> --picker agent (MW1-94); a new focus is a lane amend
212
+ steward show # this agent's live steward registration
191
213
  setup [--yes|--check] # dry-run by default; installs/checks Ollama and pulls the Gather model
214
+ # (gemma4:12b; NODII_DEV_PICKER_MODEL=gemma4:e4b|gemma4:26b picks another per machine)
192
215
  harness install|update [--include-drafts[=false]] [--adopt PATH,...] [--dry-run] [--system]
193
216
  # --system stages managed hooks and only prints operator-reviewed sudo commands
194
217
  harness check # 0 current, 1 differs from Dev, 2 not installed
@@ -228,7 +251,7 @@ Usage: nodii-dev <command> [options] [--json]
228
251
  gather tune finalize <run-id> [--supersedes <run-id> --reason TEXT]
229
252
  # Dev scores the run's own picker x 5-repeat matrix; --supersedes
230
253
  # retires an earlier run in favour of this one (its trials are kept)
231
- gather picker-latency [--picker gemma-12b|gemma-e4b|gemma-26b]
254
+ gather picker-latency [--picker gemma-12b|gemma-e4b|gemma-26b] # default: this machine's NODII_DEV_PICKER_MODEL
232
255
  # cold (model unloaded first) and warm pick latency, for the tuning record
233
256
  gather timings [--model M] [--last N] # this Mac's lane Gather picks: warm-up and first-pick p50/p95
234
257
  # (each lane gather logs one; the first pick has 120 s once warm)
@@ -612,7 +635,8 @@ export async function main(argv = process.argv.slice(2)) {
612
635
  // Amendment acknowledgement is a lane-wide backstop for every other command.
613
636
  // A nudge hook is fail-open and writes only its own JSON: it cannot run a
614
637
  // Delta gather, and a waiting-results banner would corrupt its output.
615
- if (argv[0] !== "__run-supervisor" && !readsHelp(argv) && !(argv[0] === "hook" && argv[1]?.startsWith("nudge-"))) {
638
+ // surface-gen-pre runs in every session, lane or not, so it never reaches Dev.
639
+ if (argv[0] !== "__run-supervisor" && !readsHelp(argv) && !(argv[0] === "hook" && (argv[1]?.startsWith("nudge-") || argv[1] === "surface-gen-pre"))) {
616
640
  await amendmentGuard(argv);
617
641
  await showWaitingResults({ acknowledge: argv[0] !== "hook" });
618
642
  }
@@ -770,8 +794,9 @@ export async function main(argv = process.argv.slice(2)) {
770
794
  if (command === "rulebook" && ["list", "show", "diff"].includes(action)) return emitCommand(await rulebookCommand(action, rest, f));
771
795
  if (command === "rules") return emitCommand(await rulesCommand(action, rest, f));
772
796
  if (command === "gather" && action === "picker-latency") {
773
- const name = f.picker ?? "gemma-12b";
774
- const model = Object.hasOwn(TUNING_MODELS, name) ? TUNING_MODELS[name] : null;
797
+ // Without --picker, measure the model this machine is set to (NODII_DEV_PICKER_MODEL).
798
+ const name = f.picker;
799
+ const model = name === undefined ? pickerPin() : Object.hasOwn(TUNING_MODELS, name) ? TUNING_MODELS[name] : null;
775
800
  if (!model) throw new CliError("USAGE", `gather picker-latency [--picker ${Object.keys(TUNING_MODELS).join("|")}]`, 2);
776
801
  const result = await measurePickerLatency({ model });
777
802
  const line = (label, x) => `${label} ${x.wallMs} ms (Ollama total ${x.totalMs ?? "?"} ms, model load ${x.loadMs ?? "?"} ms)`;
@@ -780,7 +805,7 @@ export async function main(argv = process.argv.slice(2)) {
780
805
  if (command === "gather" && action === "timings") {
781
806
  const last = f.last === undefined ? 50 : Number(f.last);
782
807
  if (!Number.isInteger(last) || last < 1) throw new CliError("USAGE", "gather timings [--model M] [--last N]", 2);
783
- const model = typeof f.model === "string" ? f.model : PICKER_MODEL;
808
+ const model = typeof f.model === "string" ? f.model : pickerModelName();
784
809
  const path = pickTimingsPath();
785
810
  const entries = await readPickTimings({ path, model, last });
786
811
  const stats = pickTimingStats(entries);
@@ -806,17 +831,23 @@ export async function main(argv = process.argv.slice(2)) {
806
831
  return emit(await surfacesBehind({ onlyBehind: Boolean(f.behind) }), json, surfacesBehindText);
807
832
  }
808
833
  if (command === "design" && action === "check") {
809
- if ((!rest[0] && f["change-set"] === undefined) || rest.length > 1)
810
- throw new CliError("USAGE", "design check FILE_KEY|LINK [--nodes A,B] [--roles R,S] [--library] | design check --change-set CS [--file SUBMIT.json] [--figma-version V] [--sync]", 2);
834
+ if ((!rest[0] && f["change-set"] === undefined && typeof f.surfaces !== "string") || rest.length > 1)
835
+ throw new CliError("USAGE", "design check FILE_KEY|LINK [--nodes A,B] [--roles R,S] [--library] | design check --change-set CS [--file SUBMIT.json] [--figma-version V] [--sync] | design check --surfaces FILE_KEY|LINK [--all]", 2);
811
836
  const result = await designCheck(rest[0], f);
812
837
  emit(result.payload, json, result.human ?? designCheckText);
813
838
  if (result.exitCode) {
814
- if (!json) console.error(`DS_CONFORMANCE_FAILED: ${result.payload.data.findings.length} finding(s)`);
839
+ const code = f.surfaces !== undefined ? "SURFACES_CHECK_FAILED" : "DS_CONFORMANCE_FAILED";
840
+ if (!json) console.error(`${code}: ${result.payload.data.findings.length} finding(s)`);
815
841
  process.exitCode = result.exitCode;
816
842
  }
817
843
  return;
818
844
  }
845
+ if (command === "surface") {
846
+ if (action !== "generate") throw new CliError("USAGE", SURFACE_USAGE, 2);
847
+ return emitCommand(await surfaceCommand(action, rest, f));
848
+ }
819
849
  if (command === "coordinator") return emitCommand(await coordinatorCommand(action, f, { installWatchdog }));
850
+ if (command === "steward") return emitCommand(await stewardCommand(action, rest, f));
820
851
  if (command === "lane" && action === "launch") return emitCommand(await launchLaneCommand(rest[0], f));
821
852
  if (command === "lane" && action === "amend") return emitCommand(await amendLaneCommand(rest[0], f));
822
853
  if (command === "lane" && action === "gather") {
@@ -830,7 +861,7 @@ export async function main(argv = process.argv.slice(2)) {
830
861
  }
831
862
  if (command === "lane" && action === "check") {
832
863
  // The Delta gather goes through lane gather's own path (amendments included).
833
- const result = await laneCommand("check", rest, f, { signReceipt: gateSigner, check: { deltaGather: (key, paths) => gatherLaneCommand(key, { delta: true, paths: paths.join(",") }) } });
864
+ const result = await laneCommand("check", rest, f, { signReceipt: gateSigner, check: { deltaGather: (key, paths, pick) => gatherLaneCommand(key, deltaGatherFlags(paths, pick)) } });
834
865
  emit(result.payload, json, result.human);
835
866
  if (result.exitCode) process.exitCode = result.exitCode;
836
867
  return;
@@ -1331,12 +1362,29 @@ export async function main(argv = process.argv.slice(2)) {
1331
1362
  try {
1332
1363
  const payload = JSON.parse(await stdinText());
1333
1364
  await recordHookFire(payload).catch(() => {});
1365
+ // Cite before you steer (MW1-95): a steward session, which is never a lane config.
1366
+ if (!isLaneConfig() && steerAct(payload)) {
1367
+ const config = await readConfig(false).catch(() => null);
1368
+ const steward = await activeSteward(config?.agentId).catch(() => null);
1369
+ const nudges = await stewardSteerNudges(payload, { steward });
1370
+ if (nudges.length) console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: nudges.join("\n") } }));
1371
+ if (steward) return;
1372
+ }
1334
1373
  if (!(await nudgeCandidate(payload))) return;
1335
1374
  const nudges = await nudgePre(payload, await safetyContext(payload.cwd ?? process.cwd()));
1336
1375
  if (nudges.length) console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: nudges.join("\n") } }));
1337
1376
  } catch {}
1338
1377
  return;
1339
1378
  }
1379
+ // MW8-17, for every session (the managed dispatcher calls it outside lanes
1380
+ // too): reads only the edit, never blocks, and any error is no output.
1381
+ if (action === "surface-gen-pre") {
1382
+ try {
1383
+ const nudges = await surfaceGenPre(JSON.parse(await stdinText()));
1384
+ if (nudges.length) console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: nudges.join("\n") } }));
1385
+ } catch {}
1386
+ return;
1387
+ }
1340
1388
  if (action === "nudge-stop") {
1341
1389
  try {
1342
1390
  const payload = JSON.parse(await stdinText());
@@ -1352,8 +1400,14 @@ export async function main(argv = process.argv.slice(2)) {
1352
1400
  }
1353
1401
  const payload = JSON.parse(await stdinText());
1354
1402
  await recordHookFire(payload).catch(() => {});
1403
+ // The session's kind and contract (MW1-92). Fails open: no output on any error.
1355
1404
  if (action === "session-start") {
1356
- const context = await sessionStartContext(payload);
1405
+ const context = await sessionStartText(payload).catch(() => null);
1406
+ if (context) console.log(context);
1407
+ return;
1408
+ }
1409
+ if (action === "session-kind") {
1410
+ const context = await firstPromptText(payload).catch(() => null);
1357
1411
  if (context) console.log(context);
1358
1412
  return;
1359
1413
  }
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.73";
7
+ export const VERSION = "0.6.74";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
@@ -222,7 +222,7 @@ export async function checkLogin() {
222
222
  export const encode = (value) => encodeURIComponent(value);
223
223
  // Switches never take the next token as their value, so
224
224
  // `docs upload --wait rulebook/` keeps rulebook/ as a path.
225
- const SWITCHES = new Set(["json", "wait", "pending", "dry-run", "check", "all", "fleet", "help", "yes", "mine", "no-browser", "include-drafts", "drafted", "library", "async", "sync", "force", "system", "delta", "probe", "no-probe", "not-required", "override", "critical", "no-embed", "behind"]);
225
+ const SWITCHES = new Set(["json", "wait", "pending", "dry-run", "check", "all", "fleet", "help", "yes", "mine", "no-browser", "include-drafts", "drafted", "library", "async", "sync", "force", "system", "delta", "probe", "no-probe", "not-required", "override", "critical", "no-embed", "behind", "write", "fetch"]);
226
226
  export function parseArgs(argv) {
227
227
  const flags = {};
228
228
  const args = [];
package/dist/design.js CHANGED
@@ -8,7 +8,7 @@
8
8
  // library main.
9
9
  import { readFile } from "node:fs/promises";
10
10
  import { CliError, devRequest } from "./core.js";
11
- import { conformanceLines, figmaConformance, figmaFileKey, submitMode } from "./figma.js";
11
+ import { conformanceLines, figmaConformance, figmaFileKey, submitMode, surfacesCheck } from "./figma.js";
12
12
  import { checkConformance, neededMains, VERSION as CHECK_VERSION } from "./vendor/ds-conformance.mjs";
13
13
 
14
14
  const FIGMA_API = "https://api.figma.com/v1";
@@ -303,8 +303,9 @@ const nodeId = (x) => (/^\d+-\d+$/.test(x) ? x.replace("-", ":") : x);
303
303
  * finding fails; stale overrides (a value equal to the main's) are listed but
304
304
  * never fail (DEC-0035).
305
305
  */
306
- export async function designCheck(target, flags = {}, { request = devRequest, send, progress, env = process.env, figmaGet, read } = {}) {
306
+ export async function designCheck(target, flags = {}, { request = devRequest, send, progress, env = process.env, figmaGet, read, sleep } = {}) {
307
307
  submitMode(flags);
308
+ if (flags.surfaces !== undefined) return designCheckSurfaces(target, flags, { request, ...(progress ? { progress } : {}), ...(sleep ? { sleep } : {}) });
308
309
  if (flags["change-set"] !== undefined)
309
310
  return designCheckChangeSet(target, flags, { request, ...(send ? { send } : {}), ...(progress ? { progress } : {}), ...(read ? { read } : {}) });
310
311
  // A --nodes that names nothing must not widen to every page.
@@ -384,6 +385,49 @@ export async function designCheck(target, flags = {}, { request = devRequest, se
384
385
  return { payload: { data }, exitCode: data.passed ? 0 : 1 };
385
386
  }
386
387
 
388
+ const SURFACES_USAGE = "design check --surfaces FILE_KEY|LINK [--all]";
389
+ // How many findings of each check the text lists before "… more" (--all lists every one).
390
+ const SURFACES_SHOWN = 20;
391
+
392
+ /**
393
+ * `design check --surfaces FILE [--all]`: Dev's whole-file Surfaces check
394
+ * (DESIGN-SYSTEM-253, U08-14). Dev reads every "Surface / …" set in the file
395
+ * and lists every layer the product-page generator cannot map: looseText,
396
+ * selfPainted, noAutoLayout, unboundValue and nonDsInstance. Submit reports
397
+ * the same findings on any Surface node a change set touches, and refuses them
398
+ * only for the Surfaces files the host enforces. Exit 1 when
399
+ * any finding is listed. Reads Figma on Dev's token, so FIGMA_PAT isn't needed.
400
+ */
401
+ export async function designCheckSurfaces(target, flags = {}, { request = devRequest, progress, sleep } = {}) {
402
+ const value = typeof flags.surfaces === "string" ? flags.surfaces : target;
403
+ if (!value || (typeof flags.surfaces === "string" && target)) throw new CliError("USAGE", SURFACES_USAGE, 2);
404
+ for (const flag of ["nodes", "roles", "library", "change-set", "file", "figma-version"])
405
+ if (flags[flag] !== undefined) throw new CliError("USAGE", `--${flag} doesn't go with --surfaces: ${SURFACES_USAGE}`, 2);
406
+ const data = await surfacesCheck(value, { request, ...(progress ? { progress } : {}), ...(sleep ? { sleep } : {}) });
407
+ return { payload: { data }, exitCode: data.passed ? 0 : 1, human: (payload) => designCheckSurfacesText(payload, { all: flags.all === true }) };
408
+ }
409
+
410
+ export function designCheckSurfacesText({ data }, { all = false } = {}) {
411
+ const counts = Object.entries(data.counts ?? {}).filter(([, n]) => n > 0);
412
+ const lines = [
413
+ `${data.fileName} (${data.fileKey}) at version ${data.figmaVersion}: ${data.checked.surfaces} Surface(s), ${data.findings.length} finding(s)`,
414
+ data.passed ? "PASSED: every Surface is built from DS instances in bound auto-layout frames" : `SURFACES_CHECK_FAILED: ${counts.map(([c, n]) => `${c} ${n}`).join(", ")}`,
415
+ ];
416
+ if (!data.checked.surfaces) lines.push('note: no "Surface / …" set was found on any page, so nothing was checked');
417
+ const dirty = (data.surfaces ?? []).filter((x) => x.findings > 0);
418
+ if (dirty.length) {
419
+ lines.push("by Surface:");
420
+ for (const x of dirty) lines.push(` ${x.findings}\t${x.page} › ${x.name} (${x.id})`);
421
+ }
422
+ for (const [check] of counts) {
423
+ const rows = data.findings.filter((f) => f.check === check);
424
+ lines.push(`${check} (${rows.length}):`);
425
+ for (const f of all ? rows : rows.slice(0, SURFACES_SHOWN)) lines.push(` ${f.nodeId}\t${f.surface}: ${f.detail}`);
426
+ if (!all && rows.length > SURFACES_SHOWN) lines.push(` … ${rows.length - SURFACES_SHOWN} more (--all lists every one; --json gives the full report)`);
427
+ }
428
+ return lines.join("\n");
429
+ }
430
+
387
431
  export function designCheckText({ data }) {
388
432
  const lines = [`${data.fileKey}: ${data.nodeIds.length} node(s), ${data.roles} role(s), check ${data.checkVersion}`];
389
433
  if (!data.roles) lines.push("note: no role in Dev's role map names a DS component yet, so roleMismatch had nothing to check against");
package/dist/doctor.js CHANGED
@@ -5,7 +5,7 @@ import { devRequest, encode, isOAuthConfig, query, setAuthProvider } from "./cor
5
5
  import { OAuthAuthProvider, decodeClaims, loadRefreshToken } from "./oauth.js";
6
6
  import { inferGitContext, repoName } from "./lanes.js";
7
7
  import { figmaFileKey, figmaLockCheck, holdsSet, notRegisteredHint, scopeText } from "./figma.js";
8
- import { EMBED_MODEL, EMBED_MODEL_DIGEST, EMBED_PIN, PICKER_CONTEXT, PICKER_MODEL, PICKER_MODEL_DIGESTS, STALE_PIN_HINT, inspectOllama, pickerBuild, pinnedDigests } from "./gather.js";
8
+ import { EMBED_MODEL, EMBED_MODEL_DIGEST, EMBED_PIN, PICKER_CONTEXT, PICKER_MODEL_ENV, STALE_PIN_HINT, inspectOllama, pickerBuild, pickerModelName, pickerPin, pinDigests, pinnedDigests } from "./gather.js";
9
9
  import { hookDiagnostics } from "./hook-doctor.js";
10
10
  import { hostBootedAt } from "./host.js";
11
11
  import { listAccounts } from "./accounts.js";
@@ -269,22 +269,32 @@ export async function doctorCommand(deps = {}) {
269
269
 
270
270
  // 9. The local Gather picker: Ollama itself, its version, and the exact
271
271
  // pinned model. This is a host prerequisite, independent of Dev sign-in.
272
+ // The model checked is the one this machine is set to (NODII_DEV_PICKER_MODEL).
273
+ let pin = null;
274
+ const PICKER_MODEL = pickerModelName(env);
275
+ try { pin = pickerPin(env); }
276
+ catch (error) {
277
+ checks.push(missing("picker_model", error.message, `unset ${PICKER_MODEL_ENV}, or set it to one of ${error.details.allowed.join(", ")}`, { model: PICKER_MODEL, allowed: error.details.allowed }));
278
+ }
272
279
  try {
273
- const picker = await (deps.ollamaInspector ?? inspectOllama)();
280
+ // An unknown name is already reported above; Ollama itself and the embedding pin are still checked.
281
+ const picker = await (deps.ollamaInspector ?? inspectOllama)(pin ? { model: pin } : {});
274
282
  checks.push(ok("ollama", `version ${picker.version} at the local Gather endpoint`, { version: picker.version }));
275
- // Two registry builds of gemma4:12b are accepted; say which one is installed.
276
- if (picker.modelInstalled && picker.modelMatches) {
283
+ // Two registry builds of gemma4:12b are accepted (other pinned models have one); say which one is installed.
284
+ if (!pin) { /* reported above */ }
285
+ else if (picker.modelInstalled && picker.modelMatches) {
277
286
  const build = pickerBuild(picker.digest);
278
287
  checks.push(ok("picker_model", `${PICKER_MODEL} installed${picker.digest ? ` (${picker.digest}${build ? `, the ${build.build}` : ""})` : ""}`, {
279
288
  model: PICKER_MODEL, digest: picker.digest ?? null, build: build?.build ?? null, size: picker.size ?? null,
280
289
  }));
281
290
  }
282
291
  else if (!picker.modelInstalled) checks.push(missing("picker_model", `${PICKER_MODEL} is not installed`, "nodii-dev setup --yes", { model: PICKER_MODEL }));
283
- else checks.push(missing("picker_model", `${PICKER_MODEL} digest is ${picker.digest ?? "unknown"}; this CLI pins ${pinnedDigests()}; ${STALE_PIN_HINT}`, "nodii-dev setup --yes", { model: PICKER_MODEL, digest: picker.digest ?? null, acceptedDigests: PICKER_MODEL_DIGESTS }));
292
+ else checks.push(missing("picker_model", `${PICKER_MODEL} digest is ${picker.digest ?? "unknown"}; this CLI pins ${pinnedDigests(pin)}; ${STALE_PIN_HINT}`, "nodii-dev setup --yes", { model: PICKER_MODEL, digest: picker.digest ?? null, acceptedDigests: pinDigests(pin) }));
284
293
  // Gather loads the picker at an explicit num_ctx; a copy resident at another
285
294
  // context (Ollama's default is the model's full window) holds far more memory.
286
295
  const context = picker.loadedContext ?? null;
287
- if (context === null) checks.push(ok("picker_context", `${PICKER_MODEL} not loaded; Gather loads it with num_ctx ${PICKER_CONTEXT}`, { model: PICKER_MODEL, context: null, requiredContext: PICKER_CONTEXT }));
296
+ if (!pin) { /* reported above */ }
297
+ else if (context === null) checks.push(ok("picker_context", `${PICKER_MODEL} not loaded; Gather loads it with num_ctx ${PICKER_CONTEXT}`, { model: PICKER_MODEL, context: null, requiredContext: PICKER_CONTEXT }));
288
298
  else if (context === PICKER_CONTEXT) checks.push(ok("picker_context", `${PICKER_MODEL} loaded with num_ctx ${PICKER_CONTEXT}`, { model: PICKER_MODEL, context, requiredContext: PICKER_CONTEXT }));
289
299
  else checks.push(missing("picker_context", `${PICKER_MODEL} is loaded with context ${context}, not ${PICKER_CONTEXT}; the next lane gather reloads it`, `ollama stop ${PICKER_MODEL}`, { model: PICKER_MODEL, context, requiredContext: PICKER_CONTEXT }));
290
300
  // The section embedding pin `docs upload` embeds changed sections with
@@ -296,7 +306,7 @@ export async function doctorCommand(deps = {}) {
296
306
  else checks.push(missing("embed_model", `${EMBED_MODEL} digest is ${embed.digest ?? "unknown"}; this CLI pins ${EMBED_MODEL_DIGEST}; ${STALE_PIN_HINT}`, "nodii-dev setup --yes", { model: EMBED_MODEL, digest: embed.digest ?? null, requiredDigest: EMBED_MODEL_DIGEST }));
297
307
  } catch (error) {
298
308
  checks.push(missing("ollama", error?.message ?? "Ollama is unavailable", "nodii-dev setup --yes", { code: error?.code ?? null }));
299
- checks.push(cannot("picker_model", `needs local Ollama; expected ${PICKER_MODEL}`, { model: PICKER_MODEL }));
309
+ if (pin) checks.push(cannot("picker_model", `needs local Ollama; expected ${PICKER_MODEL}`, { model: PICKER_MODEL }));
300
310
  checks.push(cannot("picker_context", `needs local Ollama; expected num_ctx ${PICKER_CONTEXT}`, { model: PICKER_MODEL, requiredContext: PICKER_CONTEXT }));
301
311
  checks.push(cannot("embed_model", `needs local Ollama; expected ${EMBED_MODEL}`, { model: EMBED_MODEL }));
302
312
  }
package/dist/figma.js CHANGED
@@ -708,6 +708,50 @@ export async function figmaPublishPlan(value, { request = devRequest, sleep = de
708
708
  return planJobOutcome(job);
709
709
  }
710
710
 
711
+ // The whole-file Surfaces check (DESIGN-SYSTEM-253): Dev reads every Surface of
712
+ // the file as a job, a few at a time at Figma's pace, so the POST answers 202 and
713
+ // the job is polled until it ends, as the publish plan is.
714
+ const SURFACES_JOB_WAIT_MS = 65 * 60_000;
715
+ const surfacesJobPath = (key, id) => `/api/v1/design/files/${encode(key)}/surfaces-check/jobs/${encode(id)}`;
716
+
717
+ /** A finished Surfaces check job as its report, or the refusal Dev ended it with. */
718
+ export function surfacesJobOutcome(job) {
719
+ if (job.state === "succeeded") return job.result;
720
+ const e = job.error ?? {};
721
+ if (e.code === "SURFACES_CHECK_JOB_LOST") throw new CliError(e.code, `${e.message ?? "Dev lost this job"} (job ${job.id} on ${job.fileKey}). Run the same command again.`, 1, e.details);
722
+ throw new CliError(!e.code || GATEWAY.has(e.code) ? "SURFACES_CHECK_JOB_FAILED" : e.code, e.message ?? `Dev's Surfaces check job ${job.id} failed with HTTP ${job.httpStatus}`, 1, e.details);
723
+ }
724
+
725
+ /** Starts or joins the file's Surfaces check (startDesignSurfacesCheck) and polls it until it ends. */
726
+ export async function surfacesCheck(value, { request = devRequest, sleep = delay, progress = stderrLine, now = Date.now } = {}) {
727
+ const key = figmaFileKey(value);
728
+ const call = fileCall(key, request);
729
+ let job = (await call("POST", `/api/v1/design/files/${encode(key)}/surfaces-check`, {})).data;
730
+ const start = now();
731
+ let printed = start;
732
+ let misses = 0;
733
+ for (let n = 0; !DONE.has(job.state); n++) {
734
+ if (now() - start > SURFACES_JOB_WAIT_MS)
735
+ throw new CliError("SURFACES_CHECK_JOB_TIMEOUT", `Dev's Surfaces check job ${job.id} on ${key} is still running after ${Math.round(SURFACES_JOB_WAIT_MS / 60_000)} minutes. Run the same command again to join it.`, 1);
736
+ await sleep(JOB_POLL_MS[Math.min(n, JOB_POLL_MS.length - 1)]);
737
+ try {
738
+ job = (await call("GET", surfacesJobPath(key, job.id))).data;
739
+ misses = 0;
740
+ } catch (error) {
741
+ if (!TRANSIENT.has(error?.code)) throw error;
742
+ if (++misses > 5) throw new CliError("SURFACES_CHECK_JOB_UNREACHABLE", `Lost touch with Dev (${error.code}) while its Surfaces check job ${job.id} on ${key} runs. Run the same command again to join it.`, 1);
743
+ progress(`polling ${job.id} again (${error.code})`);
744
+ continue;
745
+ }
746
+ if (!DONE.has(job.state) && now() - printed >= JOB_PROGRESS_MS) {
747
+ printed = now();
748
+ const done = job.progress ? `, ${job.progress.checked} of ${job.progress.total} Surfaces checked` : "";
749
+ progress(`${key}: Surfaces check job ${job.id} still running (${Math.round((printed - start) / 1000)} s${done})`);
750
+ }
751
+ }
752
+ return surfacesJobOutcome(job);
753
+ }
754
+
711
755
  const planLine = (x) => ` ${x.nodeId ?? (x.kind ? scopeText(x) : "(no node)")} ${x.name ?? ""} (${x.changeSetId} ${x.state}${x.title ? `: ${x.title}` : ""})`;
712
756
 
713
757
  /** The publish plan as two groups: what to publish, and what to leave unchecked in Figma's publish dialog. */
package/dist/flags.js CHANGED
@@ -57,6 +57,7 @@ export const COMMAND_FLAGS = {
57
57
  "figma abandon": ["file"],
58
58
  "figma apply": ["file", "figma-version"],
59
59
  "figma lock": ["title", "scope"],
60
+ "surface generate": ["write", "check", "fetch", "all", "module", "type", "figma-version", "report"],
60
61
  };
61
62
 
62
63
  /** Refuse a flag the command does not declare (USAGE, exit 2), naming the valid ones. */
package/dist/freeze.js CHANGED
@@ -266,6 +266,18 @@ export async function regroundCurrentLane(
266
266
  ) {
267
267
  const lane = await currentLane({ cwd }, { request, config });
268
268
  if (!lane) return { shown: false, reason: "no active lane" };
269
+ return regroundLane(lane, { force, write }, { request });
270
+ }
271
+
272
+ /**
273
+ * Re-ground one known lane: a worktree's lane, or a steward's, which has no
274
+ * worktree and is found by its agent (MW1-94).
275
+ */
276
+ export async function regroundLane(
277
+ lane,
278
+ { force = false, write = (text) => process.stderr.write(text) } = {},
279
+ { request = devRequest } = {},
280
+ ) {
269
281
  const response = await request(
270
282
  "GET",
271
283
  `/api/v1/lanes/${encode(lane.key)}/freeze`,