@nodii/dev 0.6.50 → 0.6.52

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
@@ -283,26 +283,70 @@ already decided (`CHANGE_SET_HAS_DECISIONS`: ask the reviewer to request
283
283
  changes instead). The CLI prints each refusal in plain words and keeps the
284
284
  code. Withdrawing an undecided re-submit returns the set to `applying`.
285
285
 
286
- `figma changeset show` lists a Figma change set's current items (the latest
287
- round of each): each one's decision, its comment (a rejection always has one), its
288
- round, the previous round's decision and comment when it was re-submitted,
289
- and its variants. It reads Dev's `getDesignChangeSet`; `--json` also gives the
290
- replaced rows (`previousRounds`) and the write log. Guideline change sets are
291
- `design changeset show`.
286
+ `figma changeset show` prints a Figma change set's write-up and lists its current
287
+ items (the latest round of each): each one's decision, its comment (a rejection
288
+ always has one), its round, the previous round's decision and comment when it was
289
+ re-submitted, its context, and each variant's node id, name and context. A set
290
+ submitted before 31 Oct 2026 has none of these: the CLI says
291
+ `none (submitted before 31 Oct)` and shows the variant's node id with
292
+ `(no name: submitted before 31 Oct)`. An item with no variants is flagged
293
+ `Needs resubmit: no variants`, never hidden. It reads Dev's `getDesignChangeSet`;
294
+ `--json` also gives the replaced rows (`previousRounds`) and the write log.
295
+ Guideline change sets are `design changeset show`.
296
+
297
+ **Change-set context (DEC-0204).** A submit tells the reviewer what they are
298
+ looking at. `figma submit CHANGE_SET --file SUBMIT.json` takes:
299
+
300
+ ```json
301
+ {
302
+ "figmaVersion": "VERSION",
303
+ "writeUp": "What the operator is looking at and why",
304
+ "items": [
305
+ {
306
+ "entryKey": "button",
307
+ "figmaNodeId": "1:2",
308
+ "change": "changed",
309
+ "context": "Button: used on every console form; this round adds the Tonal fill",
310
+ "variants": [
311
+ { "nodeId": "1:3", "name": "Button / Tonal", "context": "The Tonal fill, for secondary actions", "afterPngBase64": "..." }
312
+ ]
313
+ }
314
+ ]
315
+ }
316
+ ```
317
+
318
+ `writeUp` (up to 2000 characters), each item's `context` (500), and each
319
+ variant's `name` (120) and `context` (500) are required. Each is trimmed, and
320
+ none may be only a Figma node id (`1:3`, `I1:2;3:4`). Every item needs at least
321
+ one variant, each one the item's node or a direct child of it: split unrelated
322
+ components into separate items. The CLI checks the text rules before it calls
323
+ Dev and exits `2` with `CHANGE_SET_ITEM_NO_VARIANTS` or
324
+ `CHANGE_SET_CONTEXT_MISSING`, naming each item and variant and what it lacks,
325
+ for example `item 2 (1:40) variant 1:41: name is only a node id`. Dev refuses
326
+ the same with `422`, and `CHANGE_SET_MIXED_COMPONENTS` when a variant lies
327
+ outside its item (the CLI lists each item and the variants outside it). When
328
+ Figma can't answer that check, Dev refuses with `503 FIGMA_UNAVAILABLE`; the CLI
329
+ says when to retry (`details.retryAfter` seconds).
292
330
 
293
331
  `figma resubmit` is round 2 inside the same change set (Dev's
294
332
  `resubmitDesignChangeSet`). When every item is decided and some were
295
333
  rejected, the set is `applying`: rework the rejected items in Figma (the lock
296
334
  check allows writes in `applying`, and refuses them only while a submit is
297
335
  `in_review`), then re-submit them. The payload names every rejected item, by
298
- `itemId` or `figmaNodeId`, with its new variants, exported at 2x as for
299
- `figma submit`:
336
+ `itemId` or `figmaNodeId`, with its context and its new variants (each with a
337
+ name and context), exported at 2x as for `figma submit`. `writeUp` is optional:
338
+ sent, it replaces the set's write-up; left out, the set keeps its own. The same
339
+ context checks run before the CLI calls Dev:
300
340
 
301
341
  ```json
302
342
  {
303
343
  "figmaVersion": "VERSION",
304
344
  "items": [
305
- { "figmaNodeId": "36:531", "variants": [{ "nodeId": "36:532", "afterPngBase64": "..." }] }
345
+ {
346
+ "figmaNodeId": "36:531",
347
+ "context": "Select field: errors read bluntly now",
348
+ "variants": [{ "nodeId": "36:532", "name": "Select / Error", "context": "The error state, reworded", "afterPngBase64": "..." }]
349
+ }
306
350
  ]
307
351
  }
308
352
  ```
@@ -510,6 +554,7 @@ in any session that is not a Dev lane. Each cites the clause it protects.
510
554
  | Edit or write | `className` or `style` on a DS component (U07-19) | the tag is not a DS import, or has neither prop |
511
555
  | Edit or write | A new migration: journal `when` = max + 1, then a Delta gather. A `_journal.json` write whose `when` values do not rise | the migration is covered by a Delta gather, or already exists |
512
556
  | Edit or write | Code renders a person: `PiiText` without `self`, a raw `.email`/`.phone`/`.displayName`, or the page masks a value itself (R5, U05-25) | `PiiText` carries `self`, or no person is rendered |
557
+ | Figma write | `use_figma` or another Figma write touches a DS component, block or pattern whose guideline is not in the lane's gathered set (MW6-4, DEC-0010). Touched = a published component(-set) key it imports (a Surface's key brings the entries it is built from), a component it compares a node name with (`.name === "Icon Button"`, `.name === "Button/Cancel"`, `.name.startsWith("PiiText")`; capitalised, DS-FIG-2 normalized exact name, never on a line that looks for a TEXT node), or on the DS file an entry node it addresses; a canvas script (`use_figma`'s code) that names none falls back to the Surfaces its lane's Figma scope names in that file (a whole-file scope names none) | the guideline is in the gathered set or was read; the DS catalogue is unreachable with no cached copy |
513
558
  | Figma read | A code lane reads by node id (`get_design_context`, `get_metadata`, `get_screenshot`, ...) instead of the published key (MW8-20) | a Figma lane, or no node id |
514
559
  | `figma submit CS-n` | The unused-property, stale `Blocked on DS` placeholder and Dialog-without-body hand checks (F-34, CS-2453) | all three are recorded with `figma checked CS-n --unused-properties --stale-placeholders --dialog-body` |
515
560
  | AskUserQuestion | The question is also an item in `docs/figma-ux-drive/qa-with-abhi/open.md` (R7) | open.md already holds the question |
@@ -523,6 +568,12 @@ show` adds to `guidelinesRead`. A part's guideline is its root's (`dialog`
523
568
  covers `dialog-content`). Edits are judged against the file they produce, so
524
569
  an Edit or `apply_patch` that only changes an attribute is read in full.
525
570
 
571
+ The Figma write nudge reads the design catalogue
572
+ (`https://design.nodii.co/design-catalog.json`) and the DS registry, kept as a
573
+ compact index in `~/.cache/nodii-dev/ds-figma-index.json` for an hour
574
+ (`NODII_DEV_DS_FIGMA_INDEX_CACHE`); a failed refresh keeps the last good index
575
+ and is retried after ten minutes, not on every write.
576
+
526
577
  The Stop nudge asks the session to continue once (`decision: block`, skipped
527
578
  when `stop_hook_active`); Codex passes it through its managed dispatcher.
528
579
  Before that, in a lane session (a `lane-*.json` identity), the same hook holds
package/dist/api.js CHANGED
@@ -30,7 +30,7 @@ const isSpec = (value) => value && typeof value === "object" && typeof value.ope
30
30
  // Only Dev's own API is reachable through the edge's /devops prefix.
31
31
  const edgeReachable = (spec) => ({ ...spec, paths: Object.fromEntries(Object.entries(spec.paths).filter(([path]) => path.startsWith("/api/v1/"))) });
32
32
 
33
- async function readCache(path) {
33
+ export async function readCache(path) {
34
34
  try {
35
35
  return JSON.parse(await readFile(path, "utf8"));
36
36
  } catch {
@@ -38,7 +38,7 @@ async function readCache(path) {
38
38
  }
39
39
  }
40
40
 
41
- async function writeCache(path, value) {
41
+ export async function writeCache(path, value) {
42
42
  try {
43
43
  await mkdir(dirname(path), { recursive: true });
44
44
  const tmp = `${path}.${process.pid}.tmp`;
package/dist/cli.js CHANGED
@@ -135,14 +135,20 @@ Usage: nodii-dev <command> [options] [--json]
135
135
  figma published FILE_KEY|CHANGE_SET --figma-version V # a file key marks every awaiting set published
136
136
  figma check|log-write|submit|apply|abandon|release
137
137
  figma submit CHANGE_SET --file SUBMIT.json [--sync]
138
+ # SUBMIT.json: { figmaVersion, writeUp, items: [{ figmaNodeId, change, context,
139
+ # variants: [{ nodeId, name, context, afterPngBase64 }] }] } (DEC-0204);
140
+ # a missing writeUp, context or variant name, or an item with no variants,
141
+ # is refused before Dev is called (writeUp <= 2000, context <= 500, name <= 120;
142
+ # never a bare node id)
138
143
  figma checked CHANGE_SET --unused-properties --stale-placeholders --dialog-body # the hand checks the submit nudge asks for
139
144
  # submit, resubmit and design check --change-set run as a job in Dev
140
145
  # and poll it (a large set outlasts the edge's timeout); --sync waits
141
146
  # on one request instead. A 502/504 is checked against the set, never resent
142
147
  figma withdraw CHANGE_SET # holder takes back a submit: in_review -> editing (or a re-submit -> applying)
143
148
  figma resubmit CHANGE_SET PAYLOAD.json [--sync]
144
- # holder re-submits every rejected item: applying -> in_review, round + 1
145
- figma changeset show CHANGE_SET # items, variants, round, decision and comment (with the previous round's)
149
+ # holder re-submits every rejected item: applying -> in_review, round + 1;
150
+ # each item needs context, each variant name and context; writeUp optional
151
+ figma changeset show CHANGE_SET # write-up, items, context, variants, round, decision and comment (with the previous round's)
146
152
  figma file add FILE_KEY --name TEXT --kind design-system|surfaces|prototype [--module M]
147
153
  # register a Figma file in Dev so it can be locked
148
154
  hook claude-figma-pre|claude-figma-post|safety-pre|safety-post|nudge-pre|nudge-stop|session-start|managed-dispatch|print-settings
@@ -963,7 +969,7 @@ export async function main(argv = process.argv.slice(2)) {
963
969
  if (action === "submit") {
964
970
  const payload = f.file ? JSON.parse(await readFile(f.file, "utf8")) : { figmaVersion: requireFlag(f, "figma-version") };
965
971
  // A 200 carries top-level warnings (STALE_FIGMA_VERSION): print them.
966
- return emit(await figmaSubmit(rest[0], payload, { sync: submitMode(f) }), json, (p) =>
972
+ return emit(await figmaSubmit(rest[0], payload, { sync: submitMode(f), file: f.file || "the submit (no --file)" }), json, (p) =>
967
973
  [JSON.stringify(p.data, null, 2), ...conformanceLines({ warnings: p.warnings })].join("\n"));
968
974
  }
969
975
  if (action === "file") {
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.50";
7
+ export const VERSION = "0.6.52";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
@@ -3,12 +3,17 @@
3
3
  // from the DS catalog (route → Surfaces → componentSetKey → file); Gather turns
4
4
  // it into the DS components whose guidelines apply; the hooks refuse Figma
5
5
  // locks and writes outside it.
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { readCache, writeCache } from "./api.js";
6
9
  import { CliError, devRequest } from "./core.js";
7
10
  import { currentLane } from "./freeze.js";
8
11
 
9
12
  /** The DS catalog as the design site publishes it (`build:public-assets`). */
10
13
  export const DS_REGISTRY_URL = "https://design.nodii.co/registry.json";
11
14
  export const DS_REGISTRY_TIMEOUT_MS = 20_000;
15
+ /** The design catalogue (DS-GAC-2): every guideline entry, its title and its DS-file node. */
16
+ export const DS_DESIGN_CATALOG_URL = "https://design.nodii.co/design-catalog.json";
12
17
  export const FIGMA_FILE_KEY = /^[A-Za-z0-9]{10,64}$/;
13
18
  export const COMPONENT_SET_KEY = /^[0-9a-f]{40}$/;
14
19
  const NODE_ID = /^I?\d+[:-]\d+/;
@@ -69,10 +74,8 @@ export function surfacesFrom(registry) {
69
74
  });
70
75
  }
71
76
 
72
- let cached;
73
- /** Fetch the DS catalog once per process. */
74
- export async function loadDsCatalog({ fetchImpl = fetch, url = process.env.NODII_DEV_DS_REGISTRY_URL ?? DS_REGISTRY_URL, timeoutMs = DS_REGISTRY_TIMEOUT_MS, signal } = {}) {
75
- if (cached?.url === url) return cached.surfaces;
77
+ /** One JSON file the design site publishes, its failures as refusals. */
78
+ async function fetchDsJson(url, { fetchImpl = fetch, timeoutMs = DS_REGISTRY_TIMEOUT_MS, signal } = {}) {
76
79
  let response;
77
80
  try {
78
81
  // A caller's signal (Gather's deadline) bounds the read; otherwise our own.
@@ -81,15 +84,124 @@ export async function loadDsCatalog({ fetchImpl = fetch, url = process.env.NODII
81
84
  throw new CliError("DS_CATALOG_UNAVAILABLE", `Could not read the DS catalog at ${url}: ${error.message}`, 1);
82
85
  }
83
86
  if (!response.ok) throw new CliError("DS_CATALOG_UNAVAILABLE", `The DS catalog at ${url} returned HTTP ${response.status}.`, 1);
84
- let registry;
85
- try { registry = await response.json(); }
86
- catch { throw new CliError("DS_CATALOG_INVALID", `The DS catalog at ${url} is not JSON.`, 1); }
87
- const surfaces = surfacesFrom(registry);
87
+ try { return await response.json(); }
88
+ catch (error) {
89
+ // A body cut off by the deadline is unread, not malformed.
90
+ if (signal?.aborted) throw new CliError("DS_CATALOG_UNAVAILABLE", `Could not read the DS catalog at ${url}: ${signal.reason?.message ?? error.message}`, 1);
91
+ throw new CliError("DS_CATALOG_INVALID", `The DS catalog at ${url} is not JSON.`, 1);
92
+ }
93
+ }
94
+
95
+ let cached;
96
+ /** Fetch the DS catalog once per process. */
97
+ export async function loadDsCatalog({ fetchImpl = fetch, url = process.env.NODII_DEV_DS_REGISTRY_URL || DS_REGISTRY_URL, timeoutMs = DS_REGISTRY_TIMEOUT_MS, signal } = {}) {
98
+ if (cached?.url === url) return cached.surfaces;
99
+ const surfaces = surfacesFrom(await fetchDsJson(url, { fetchImpl, timeoutMs, signal }));
88
100
  cached = { url, surfaces };
89
101
  return surfaces;
90
102
  }
91
103
  export const clearDsCatalogCache = () => { cached = undefined; };
92
104
 
105
+ // ─── what a Figma write names (AGENT-HARNESS-47) ──────────────────────────
106
+
107
+ const GUIDED_KINDS = new Set(["component", "block", "pattern"]);
108
+ /** A name as the DS node map compares it: case, spaces and punctuation dropped (DS-FIG-2). */
109
+ export const squashName = (name) => String(name).toLowerCase().replace(/[^a-z0-9]/g, "");
110
+ /** An index lookup that never reads Object.prototype ("constructor"). */
111
+ export const indexed = (map, key) => (map && Object.hasOwn(map, key) ? map[key] : undefined);
112
+
113
+ /**
114
+ * The compact lookup a Figma write is read against: guideline entries by
115
+ * squashed title and key, published component(-set) keys, DS-file node ids,
116
+ * and each Surface's set key with the entries it is built from.
117
+ */
118
+ export function dsFigmaIndex(designCatalog, registry) {
119
+ const entries = (Array.isArray(designCatalog?.entries) ? designCatalog.entries : []).filter((entry) => GUIDED_KINDS.has(entry?.kind) && entry.key);
120
+ if (!entries.length) throw new CliError("DS_CATALOG_INVALID", "The design catalogue has no component, block or pattern entries.", 1);
121
+ const known = new Set(entries.map((entry) => entry.key));
122
+ const names = {};
123
+ const keys = {};
124
+ const nodes = {};
125
+ // Several entries can share one key or one DS node (date-picker and picker-text are one node).
126
+ const add = (map, key, entry) => { map[key] = [...new Set([...(indexed(map, key) ?? []), entry])]; };
127
+ for (const entry of entries) {
128
+ names[squashName(entry.key)] = entry.key;
129
+ if (entry.title && !Object.hasOwn(names, squashName(entry.title))) names[squashName(entry.title)] = entry.key;
130
+ for (const key of [entry.figma?.componentKey, entry.figma?.componentSetKey]) if (COMPONENT_SET_KEY.test(key ?? "")) add(keys, key, entry.key);
131
+ if (entry.figma?.nodeId) add(nodes, entry.figma.nodeId, entry.key);
132
+ }
133
+ const items = Array.isArray(registry?.items) ? registry.items : [];
134
+ for (const item of items)
135
+ if (!item?.meta?.productPage && known.has(item?.name) && COMPONENT_SET_KEY.test(item.meta?.figma?.componentSetKey ?? "")) add(keys, item.meta.figma.componentSetKey, item.name);
136
+ // A Surface is built from components and blocks, some through a kit it shares
137
+ // (`/r/blocks/product-pages/hr/hr-record-kit.json`): follow every dependency.
138
+ const byName = new Map(items.map((item) => [item?.name, item]));
139
+ const built = (name) => {
140
+ const seen = new Set([name]);
141
+ const queue = [name];
142
+ while (queue.length)
143
+ for (const dependency of byName.get(queue.shift())?.registryDependencies ?? []) {
144
+ const next = /\/r\/(?:[a-z0-9-]+\/)*([a-z0-9-]+)\.json$/.exec(String(dependency))?.[1];
145
+ if (next && !seen.has(next)) { seen.add(next); queue.push(next); }
146
+ }
147
+ return [...seen].filter((entry) => entry !== name && known.has(entry)).sort();
148
+ };
149
+ const surfaces = surfacesFrom(registry).map((surface) => ({
150
+ name: surface.name,
151
+ fileKey: surface.fileKey,
152
+ componentSetKey: surface.componentSetKey,
153
+ entries: built(surface.name),
154
+ }));
155
+ return { fileKey: designCatalog.figma?.fileKey ?? null, names, keys, nodes, surfaces };
156
+ }
157
+
158
+ // The cached index's shape; a cache of another shape is refetched, never read.
159
+ export const DS_FIGMA_INDEX_SCHEMA = 2;
160
+ export const DS_FIGMA_INDEX_TTL_MS = 60 * 60 * 1000;
161
+ export const DS_FIGMA_INDEX_RETRY_MS = 10 * 60 * 1000;
162
+ export const DS_FIGMA_INDEX_TIMEOUT_MS = 8_000;
163
+ export const dsFigmaIndexPath = (env = process.env) =>
164
+ env.NODII_DEV_DS_FIGMA_INDEX_CACHE || join(homedir(), ".cache", "nodii-dev", "ds-figma-index.json");
165
+
166
+ const unavailable = (failure) => new CliError("DS_CATALOG_UNAVAILABLE", `The DS Figma index is unavailable: ${failure}`, 1);
167
+
168
+ /**
169
+ * The DS Figma index, cached on disk for an hour so a hook on every Figma
170
+ * write reads the two catalogues at most hourly. A failed refresh keeps the
171
+ * last good index and is not retried for ten minutes, so an unreachable
172
+ * design site costs one timeout, not one per write; with no index it throws
173
+ * (the nudge then stays silent).
174
+ */
175
+ export async function loadDsFigmaIndex({ fetchImpl = fetch, env = process.env, now = Date.now(), timeoutMs = DS_FIGMA_INDEX_TIMEOUT_MS } = {}) {
176
+ const urls = { catalogUrl: env.NODII_DEV_DS_DESIGN_CATALOG_URL || DS_DESIGN_CATALOG_URL, registryUrl: env.NODII_DEV_DS_REGISTRY_URL || DS_REGISTRY_URL };
177
+ const path = dsFigmaIndexPath(env);
178
+ const cache = await readCache(path);
179
+ const mine = cache?.schema === DS_FIGMA_INDEX_SCHEMA && cache.catalogUrl === urls.catalogUrl && cache.registryUrl === urls.registryUrl ? cache : null;
180
+ // An age below zero (a clock moved back) is no age.
181
+ const within = (at, ms) => { const age = now - Date.parse(at); return age >= 0 && age < ms; };
182
+ if (mine?.index && within(mine.fetchedAt, DS_FIGMA_INDEX_TTL_MS)) return mine.index;
183
+ if (mine?.failedAt && within(mine.failedAt, DS_FIGMA_INDEX_RETRY_MS)) {
184
+ if (mine.index) return mine.index;
185
+ throw unavailable(mine.failure);
186
+ }
187
+ // One deadline for both reads; the first failure ends the other, so a dead site never holds the hook.
188
+ const controller = new AbortController();
189
+ const timer = setTimeout(() => controller.abort(new Error(`timed out after ${timeoutMs} ms`)), timeoutMs);
190
+ const read = (url) => fetchDsJson(url, { fetchImpl, signal: controller.signal }).catch((error) => { controller.abort(error); throw error; });
191
+ try {
192
+ const [catalog, registry] = await Promise.all([read(urls.catalogUrl), read(urls.registryUrl)]);
193
+ const index = dsFigmaIndex(catalog, registry);
194
+ await writeCache(path, { schema: DS_FIGMA_INDEX_SCHEMA, ...urls, fetchedAt: new Date(now).toISOString(), index });
195
+ return index;
196
+ } catch (error) {
197
+ await writeCache(path, { schema: DS_FIGMA_INDEX_SCHEMA, ...urls, fetchedAt: mine?.fetchedAt ?? null, index: mine?.index ?? null, failedAt: new Date(now).toISOString(), failure: error.message });
198
+ if (mine?.index) return mine.index;
199
+ throw error;
200
+ } finally {
201
+ clearTimeout(timer);
202
+ }
203
+ }
204
+
93
205
  /** route → Surfaces → published componentSetKey → file (rules-AB E5). */
94
206
  const routeKey = (route) => (route.length > 1 ? route.replace(/\/+$/, "") : route);
95
207
 
package/dist/figma.js CHANGED
@@ -35,7 +35,7 @@ const RESUBMIT_REFUSALS = {
35
35
  CHANGE_SET_CHANGED: (id) => `${id} changed while re-submitting; read it with nodii-dev figma changeset show ${id} and try again.`,
36
36
  };
37
37
 
38
- /** A round-2 payload: { figmaVersion, items: [{ itemId | figmaNodeId, variants: [{ nodeId, beforePngBase64?, afterPngBase64? }] }] }. */
38
+ /** A round-2 payload: { figmaVersion, writeUp?, items: [{ itemId | figmaNodeId, context, variants: [{ nodeId, name, context, beforePngBase64?, afterPngBase64? }] }] }. */
39
39
  export function resubmitPayload(text, file) {
40
40
  let body;
41
41
  try {
@@ -49,14 +49,116 @@ export function resubmitPayload(text, file) {
49
49
  if (!Array.isArray(body.items) || body.items.length === 0) throw bad("items must list the rejected items");
50
50
  body.items.forEach((item, n) => {
51
51
  if (!item?.itemId && !item?.figmaNodeId) throw bad(`items[${n}] needs itemId or figmaNodeId`);
52
- if (!Array.isArray(item.variants) || item.variants.length === 0) throw bad(`items[${n}] needs at least one variant`);
53
- item.variants.forEach((v, m) => {
52
+ (Array.isArray(item.variants) ? item.variants : []).forEach((v, m) => {
54
53
  if (!v?.nodeId) throw bad(`items[${n}].variants[${m}] needs nodeId`);
55
54
  });
56
55
  });
57
56
  return body;
58
57
  }
59
58
 
59
+ // Change-set context (DEC-0204, DEV-DSN-19 to DEV-DSN-21, DEV-DSN-27): the set's
60
+ // write-up, each item's context and each variant's name and context, checked
61
+ // with Dev's own text rules before anything is sent (DEV-DSN-25).
62
+ const CONTEXT_LIMITS = { writeUp: 2000, "item.context": 500, "variant.name": 120, "variant.context": 500 };
63
+ const BARE_NODE_ID = /^(?:\d+:\d+|I\d+:\d+(?:;\d+:\d+)*)$/;
64
+
65
+ /** Why Dev refuses a context text: "missing", "too_long", "node_id", or null when it passes. */
66
+ export function textProblem(value, limit) {
67
+ const text = typeof value === "string" ? value.trim() : "";
68
+ if (!text) return "missing";
69
+ if (text.length > limit) return "too_long";
70
+ return BARE_NODE_ID.test(text) ? "node_id" : null;
71
+ }
72
+
73
+ /**
74
+ * Every item without a variant, and every context problem, in the shape of Dev's
75
+ * CHANGE_SET_ITEM_NO_VARIANTS and CHANGE_SET_CONTEXT_MISSING details. A re-submit
76
+ * may leave out writeUp (the set keeps its own); one it sends must pass.
77
+ */
78
+ export function contextProblems(body, { resubmit = false } = {}) {
79
+ const items = [];
80
+ const problems = [];
81
+ const check = (field, value, where) => {
82
+ const problem = textProblem(value, CONTEXT_LIMITS[field]);
83
+ if (problem) problems.push({ field, problem, ...where });
84
+ };
85
+ if (!resubmit || body?.writeUp !== undefined) check("writeUp", body?.writeUp, {});
86
+ (Array.isArray(body?.items) ? body.items : []).forEach((item, itemIndex) => {
87
+ const at = { itemIndex, ...(item?.figmaNodeId ? { figmaNodeId: item.figmaNodeId } : {}), ...(item?.itemId ? { itemId: item.itemId } : {}) };
88
+ check("item.context", item?.context, at);
89
+ const variants = Array.isArray(item?.variants) ? item.variants : [];
90
+ if (!variants.length) items.push({ index: itemIndex, figmaNodeId: item?.figmaNodeId ?? item?.itemId ?? null });
91
+ for (const v of variants) {
92
+ check("variant.name", v?.name, { ...at, variantNodeId: v?.nodeId ?? null });
93
+ check("variant.context", v?.context, { ...at, variantNodeId: v?.nodeId ?? null });
94
+ }
95
+ });
96
+ return { items, problems };
97
+ }
98
+
99
+ const itemLabel = (p) => `item ${(p.itemIndex ?? p.index ?? 0) + 1} (${p.figmaNodeId ?? p.itemId ?? "no node id"})`;
100
+ const FIELD_HINT = {
101
+ writeUp: ["writeUp", "say what the operator is looking at and why"],
102
+ "item.context": ["context", "say what the component is, where it is used and what this round changes"],
103
+ "variant.name": ["name", `give the variant's name, e.g. "Button / Tonal"`],
104
+ "variant.context": ["context", "say what changed for this variant and where it is used"],
105
+ };
106
+
107
+ /** One plain-English line per context problem, naming the item and variant. */
108
+ export function contextProblemLines(problems = []) {
109
+ return problems.map((p) => {
110
+ const [name, hint] = FIELD_HINT[p.field] ?? [p.field, "fix it"];
111
+ const where =
112
+ p.field === "writeUp" ? "" : `${itemLabel(p)}${p.field.startsWith("variant.") ? ` variant ${p.variantNodeId ?? "with no nodeId"}` : ""}: `;
113
+ const what =
114
+ p.problem === "too_long" ? `is longer than ${CONTEXT_LIMITS[p.field] ?? "its limit of"} characters; shorten it`
115
+ : p.problem === "node_id" ? `is only a node id; ${hint}`
116
+ : `is missing; ${hint}`;
117
+ return ` ${where}${name} ${what}`;
118
+ });
119
+ }
120
+
121
+ const noVariantLines = (items = []) =>
122
+ items.map((i) => ` ${itemLabel(i)} has no variants; add at least one { nodeId, name, context } (an empty item reaches review with nothing to see)`);
123
+
124
+ /** Refuses, before any call to Dev, a submit or re-submit body that Dev would refuse for its context (DEV-DSN-25). */
125
+ export function assertContext(body, { resubmit = false, file = "the payload" } = {}) {
126
+ const { items, problems } = contextProblems(body, { resubmit });
127
+ if (items.length)
128
+ throw new CliError(
129
+ "CHANGE_SET_ITEM_NO_VARIANTS",
130
+ [`${file}: ${items.length} item(s) list no variants (DEV-DSN-27); nothing was sent:`, ...noVariantLines(items),
131
+ ...(problems.length ? ["Also fix:", ...contextProblemLines(problems)] : [])].join("\n"),
132
+ 2,
133
+ { items, ...(problems.length ? { problems } : {}) },
134
+ );
135
+ if (problems.length)
136
+ throw new CliError(
137
+ "CHANGE_SET_CONTEXT_MISSING",
138
+ [`${file}: ${problems.length} context problem(s) (DEC-0204); nothing was sent:`, ...contextProblemLines(problems)].join("\n"),
139
+ 2,
140
+ { problems },
141
+ );
142
+ return body;
143
+ }
144
+
145
+ // Dev's refusals of a submit or re-submit's context and component scope (DEC-0204), with what to do next.
146
+ const CONTEXT_REFUSALS = {
147
+ CHANGE_SET_ITEM_NO_VARIANTS: (message, details) => [message, ...noVariantLines(details?.items)].join("\n"),
148
+ CHANGE_SET_CONTEXT_MISSING: (message, details) => [message, ...contextProblemLines(details?.problems)].join("\n"),
149
+ CHANGE_SET_MIXED_COMPONENTS: (message, details) =>
150
+ [
151
+ message,
152
+ ...(details?.items ?? []).map((i) => ` item ${i.figmaNodeId}: outside it ${(i.outside ?? []).join(", ") || "?"}`),
153
+ "Each variant must be its item's node or a direct child of it at the submitted version: split unrelated components into separate items, then submit again.",
154
+ ].join("\n"),
155
+ FIGMA_UNAVAILABLE: (message, details) =>
156
+ [
157
+ message,
158
+ `Figma could not answer Dev's read (on a submit, the component check), so Dev refused and changed nothing. ${details?.retryAfter ? `Retry after ${details.retryAfter} seconds.` : "Retry in a few minutes."}`,
159
+ ].join("\n"),
160
+ };
161
+
60
162
  // Async submit, re-submit and dry run (`Prefer: respond-async`): a large set's
61
163
  // gate outlasts the edge's 30 s timeout (CS-2470 got a 504 while Dev went on to
62
164
  // answer 422), so Dev answers 202 with a job, polled here until it ends. A Dev
@@ -216,7 +318,7 @@ export async function figmaResubmit(id, file, { request = devRequest, read = (f)
216
318
  } catch (error) {
217
319
  throw new CliError("USAGE", `cannot read ${file}: ${error.message}`, 2);
218
320
  }
219
- const body = resubmitPayload(text, file);
321
+ const body = assertContext(resubmitPayload(text, file), { resubmit: true, file });
220
322
  try {
221
323
  return await submitCall(id, "resubmit", body, { request, ...options });
222
324
  } catch (error) {
@@ -236,23 +338,32 @@ export async function figmaChangeSetShow(id, { request = devRequest } = {}) {
236
338
  }
237
339
  }
238
340
 
341
+ // A set submitted before 31 Oct 2026 has no write-up, context or variant names (null).
342
+ const BEFORE_CONTEXT = "submitted before 31 Oct";
239
343
  const variantLine = (v) =>
240
- `${v.figmaNodeId} (${[v.beforeImageId && "before", v.afterImageId && "after"].filter(Boolean).join(", ") || "no images"})`;
344
+ ` variant ${v.figmaNodeId} ${v.name ?? `(no name: ${BEFORE_CONTEXT})`} (${[v.beforeImageId && "before", v.afterImageId && "after"].filter(Boolean).join(", ") || "no images"})${v.context ? `: ${v.context}` : ""}`;
241
345
 
242
- /** One change set as lines: its items' round, decision, comment, the previous round's decision and comment, and variants. */
346
+ /**
347
+ * One change set as lines: its write-up, and its items' round, decision, comment,
348
+ * the previous round's decision and comment, context and variants. An item with
349
+ * no variants needs a re-submit (DESIGN-SYSTEM-PARITY-4): it is flagged, never hidden.
350
+ */
243
351
  export function figmaChangeSetText(cs) {
244
352
  const c = cs.itemCounts ?? {};
245
353
  const lines = [
246
354
  `${cs.id} ${cs.state} ${cs.title}`,
247
355
  `file ${cs.file?.name ?? cs.fileKey} (${cs.fileKey}); holder ${cs.holder?.agent?.displayName ?? cs.holder?.agent?.id ?? "none"}`,
248
356
  `${c.total ?? cs.items.length} items: ${c.approved ?? 0} approved, ${c.rejected ?? 0} rejected, ${c.pending ?? 0} pending`,
357
+ `write-up: ${cs.writeUp ?? (cs.state === "editing" ? "none yet" : `none (${BEFORE_CONTEXT})`)}`,
249
358
  ];
250
359
  for (const item of cs.items ?? []) {
251
360
  lines.push(`- ${item.decision} round ${item.round} ${item.figmaNodeId} ${item.entryKey ?? "(new)"} ${item.change} item ${item.id}`);
252
361
  if (item.comment) lines.push(` comment: ${item.comment}`);
253
362
  if (item.previousItemId)
254
363
  lines.push(` round ${item.round - 1}: ${item.previousDecision ?? "?"}${item.previousComment ? `: ${item.previousComment}` : ""}`);
255
- if (item.variants?.length) lines.push(` variants: ${item.variants.map(variantLine).join("; ")}`);
364
+ lines.push(` context: ${item.context ?? `none (${BEFORE_CONTEXT})`}`);
365
+ if (item.variants?.length) lines.push(...item.variants.map(variantLine));
366
+ else lines.push(" Needs resubmit: no variants");
256
367
  }
257
368
  if (cs.previousRounds?.length) lines.push(`${cs.previousRounds.length} earlier-round item(s) replaced by a re-submit; --json lists them.`);
258
369
  return lines.join("\n");
@@ -374,6 +485,8 @@ function scopeRefusal(error, id) {
374
485
  return new CliError(error.code, conflictText(error.message, error.details), error.exitCode ?? 1, error.details);
375
486
  if (error?.code === "WRITE_OUT_OF_SCOPE")
376
487
  return new CliError(error.code, outOfScopeText(error.message, error.details, id), error.exitCode ?? 1, error.details);
488
+ const say = CONTEXT_REFUSALS[error?.code];
489
+ if (say) return new CliError(error.code, say(error.message, error.details), error.exitCode ?? 1, error.details);
377
490
  return null;
378
491
  }
379
492
 
@@ -484,10 +597,19 @@ export const figmaScopeSetText = (id, data) =>
484
597
  ...(data?.released?.length ? [`Released for other sets: ${data.released.map(scopeText).join(", ")}`] : []),
485
598
  ].join("\n");
486
599
 
487
- /** A submit, async unless `sync` (options: sync, request, send, progress, sleep). */
488
- export const figmaSubmit = (id, payload, { request = devRequest, ...options } = {}) =>
489
- changeSetCall(id, (method, path, body) => submitCall(id, "submit", body, { request, ...options }))(
600
+ /**
601
+ * A submit, async unless `sync` (options: sync, request, send, progress, sleep).
602
+ * A body without its context (writeUp, item context, variant name and context)
603
+ * is refused here, before any call to Dev (DEV-DSN-25).
604
+ */
605
+ export async function figmaSubmit(id, payload, { request = devRequest, file = "the submit body", ...options } = {}) {
606
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) throw new CliError("USAGE", `${file}: expected a JSON object`, 2);
607
+ if (!Array.isArray(payload.items) || payload.items.length === 0)
608
+ throw new CliError("USAGE", `${file}: items must list the set's items, each with its context and variants (figma submit CHANGE_SET --file SUBMIT.json)`, 2);
609
+ assertContext(payload, { file });
610
+ return changeSetCall(id, (method, path, body) => submitCall(id, "submit", body, { request, ...options }))(
490
611
  "POST", `/api/v1/design/change-sets/${encode(id)}/submit`, payload);
612
+ }
491
613
 
492
614
  /** checkDesignConformance: the submit gate's dry run on a change set; changes no state. Body: { figmaVersion?, items? }. Async unless `sync`. */
493
615
  export const figmaConformance = (id, body = {}, { request = devRequest, sync = false, ...options } = {}) =>
package/dist/nudges.js CHANGED
@@ -10,7 +10,8 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
10
10
  import { dirname, isAbsolute, relative, resolve } from "node:path";
11
11
  import { promisify } from "node:util";
12
12
  import { devRequest, encode } from "./core.js";
13
- import { isFigmaTool, isReadTool } from "./hooks.js";
13
+ import { indexed, laneFigmaScope, loadDsFigmaIndex, squashName } from "./figma-scope.js";
14
+ import { extractFileKey, extractNodeIds, isFigmaTool, isReadTool } from "./hooks.js";
14
15
  import { continueTaskMessage, doneCheckRecorded, laneBlocked } from "./lane-supervisor.js";
15
16
  import { patchPaths } from "./safety.js";
16
17
 
@@ -321,6 +322,76 @@ export function figmaReadNudges(payload, lane) {
321
322
  return ["nodii-dev nudge: this code lane reads Figma by node id. Find the surface by its published component-set key (`figma:keys:refresh`), never a node id; a node id is not a stable reference across hops (MW8-20, MW8-17)."];
322
323
  }
323
324
 
325
+ const isFigmaWrite = (tool) => isFigmaTool(tool) && !isReadTool(tool);
326
+ const inputText = (value) => (typeof value === "string" ? [value] : value && typeof value === "object" ? Object.values(value).flatMap(inputText) : []);
327
+ const LITERAL = String.raw`(["'\x60])((?:(?!\1)[^\\\n$])+)\1`;
328
+ // A node's name compared or tested: `.name === "Button/Cancel"`, `"Tabs" === n.name`, `.name.startsWith("Icon Button")`.
329
+ // Setting a name is not touching a component, and a line that looks for a TEXT node names a text layer.
330
+ const TEXT_LOOKUP = /\btype\s*===?\s*["'\x60]TEXT["'\x60]/;
331
+ const NAMED = [
332
+ new RegExp(String.raw`\.name\s*[!=]==?\s*${LITERAL}`, "g"),
333
+ new RegExp(String.raw`${LITERAL}\s*[!=]==?\s*[\w$.?]+\.name\b`, "g"),
334
+ new RegExp(String.raw`\.name\??\.(?:startsWith|endsWith|includes)\(\s*${LITERAL}`, "g"),
335
+ ];
336
+ const KEY_IN_TEXT = /(?<![0-9a-f])[0-9a-f]{40}(?![0-9a-f])/g;
337
+ const NODE_IN_TEXT = /(["'\x60])(I?\d+[:-]\d+)\1/g;
338
+
339
+ /**
340
+ * The guideline entries a Figma write touches: published keys it imports, DS
341
+ * components it names (a component name, or its first `/` segment, matched by
342
+ * the DS node map's normalized exact name, DS-FIG-2), and on the DS file the
343
+ * entry nodes it addresses. A write that names none may fall back to its
344
+ * lane's scope (scopeEntries).
345
+ */
346
+ export function figmaWriteEntries(payload, index) {
347
+ const input = payload.tool_input ?? {};
348
+ const text = inputText(input).join("\n");
349
+ const found = new Set();
350
+ for (const key of text.match(KEY_IN_TEXT) ?? []) {
351
+ for (const entry of indexed(index.keys, key) ?? []) found.add(entry);
352
+ for (const surface of index.surfaces.filter((item) => item.componentSetKey === key)) for (const entry of surface.entries) found.add(entry);
353
+ }
354
+ for (const line of text.split("\n").filter((item) => !TEXT_LOOKUP.test(item)))
355
+ for (const pattern of NAMED)
356
+ for (const [, , name] of line.matchAll(pattern))
357
+ for (const part of new Set([name, name.split("/")[0]]))
358
+ if (/^[A-Z]/.test(part.trim()) && indexed(index.names, squashName(part))) found.add(indexed(index.names, squashName(part)));
359
+ const fileKey = extractFileKey(input);
360
+ if (fileKey && fileKey === index.fileKey) {
361
+ const ids = [...extractNodeIds(input), ...[...text.matchAll(NODE_IN_TEXT)].map(([, , id]) => id.replace(/(\d+)-(\d+)/g, "$1:$2"))];
362
+ for (const id of ids) for (const entry of indexed(index.nodes, id) ?? []) found.add(entry);
363
+ }
364
+ return [...found];
365
+ }
366
+
367
+ /**
368
+ * A canvas script (`use_figma`'s code) that names no entry edits the
369
+ * Surfaces its lane's Figma scope names in that file. A whole-file scope
370
+ * names none, and an upload or a Code Connect call is no canvas script.
371
+ */
372
+ export function scopeEntries(payload, index, scope) {
373
+ const input = payload.tool_input ?? {};
374
+ const fileKey = extractFileKey(input);
375
+ if (typeof input.code !== "string" || !fileKey || !Array.isArray(scope)) return [];
376
+ const sets = scope.find((file) => file.fileKey === fileKey)?.componentSets ?? [];
377
+ return [...new Set(index.surfaces.filter((item) => sets.includes(item.componentSetKey)).flatMap((surface) => surface.entries))];
378
+ }
379
+
380
+ /** A Figma write touching a DS component whose guideline is not in the lane's gathered set (MW6-4). */
381
+ export function figmaGuidelineNudges(payload, knowledge, entries) {
382
+ if (!isFigmaWrite(payload.tool_name ?? "")) return [];
383
+ const known = [...(knowledge.guidelines ?? []), ...(knowledge.guidelinesRead ?? [])].map(kebab);
384
+ const missing = entries.filter((key) => !covers(known, key)).sort();
385
+ if (!missing.length) return [];
386
+ return [`nodii-dev nudge: no guideline for ${listed(missing)} in this lane's gathered set. Read it before editing it: ${missing.slice(0, 3).map((key) => `\`nodii-dev design guideline show ${key}\``).join(", ")} (MW6-4, DEC-0010).`];
387
+ }
388
+
389
+ /** The lane's Figma scope, from its detail unless the lane at hand already carries its Freeze and launch record. */
390
+ export async function laneScopeOf(lane, request = devRequest) {
391
+ const detailed = "freeze" in lane && "launch" in lane ? lane : (await request("GET", `/api/v1/lanes/${encode(lane.key)}`)).data ?? lane;
392
+ return laneFigmaScope(detailed);
393
+ }
394
+
324
395
  const SUBMIT_COMMAND = /(?:nodii-dev|@nodii\/dev(?:@\S+)?)\s+figma\s+submit\b([^;&|\n]*)/;
325
396
  const CHECKED_COMMAND = /(?:nodii-dev|@nodii\/dev(?:@\S+)?)\s+figma\s+checked\s+(CS-[\w-]+)([^;&|\n]*)/g;
326
397
 
@@ -354,7 +425,7 @@ const SIGNALS = /@cognion-nucleus|PiiText|\bmask\w*\(|\b[A-Za-z]\*{3,}|\.(?:emai
354
425
  /** Whether any nudge could apply to this call, so most calls never resolve the lane. */
355
426
  export async function nudgeCandidate(payload) {
356
427
  const tool = payload.tool_name ?? "";
357
- if (isFigmaTool(tool)) return isReadTool(tool) && NODE_ID_TOOLS.test(tool);
428
+ if (isFigmaTool(tool)) return isFigmaWrite(tool) || NODE_ID_TOOLS.test(tool);
358
429
  if (tool === "AskUserQuestion") return true;
359
430
  if (SHELL_TOOLS.has(tool)) return /\bfigma\s+submit\b/.test(String(payload.tool_input?.command ?? ""));
360
431
  if (!EDIT_TOOLS.has(tool)) return false;
@@ -368,12 +439,21 @@ export async function nudgeCandidate(payload) {
368
439
  }
369
440
 
370
441
  /** PreToolUse nudges for one tool call. Returns [] outside a lane. */
371
- export async function nudgePre(payload, context, { knowledge = laneKnowledge } = {}) {
442
+ export async function nudgePre(payload, context, { knowledge = laneKnowledge, figmaIndex = loadDsFigmaIndex, figmaScope = laneScopeOf } = {}) {
372
443
  const lane = context?.lane;
373
444
  if (!lane) return [];
374
445
  const tool = payload.tool_name ?? "";
375
446
  const root = context.root;
376
447
  const cwd = payload.cwd ?? context.cwd ?? root;
448
+ if (isFigmaWrite(tool)) {
449
+ // No catalogue, no nudge; an unreadable scope only loses the fallback.
450
+ const [index, known] = await Promise.all([figmaIndex().catch(() => null), knowledge(cwd)]);
451
+ if (!index) return [];
452
+ // The scope is read only for a write that names no entry itself.
453
+ const named = figmaWriteEntries(payload, index);
454
+ const entries = named.length ? named : scopeEntries(payload, index, await figmaScope(lane).catch(() => null));
455
+ return figmaGuidelineNudges(payload, known, entries);
456
+ }
377
457
  if (isFigmaTool(tool)) return figmaReadNudges(payload, lane);
378
458
  if (tool === "AskUserQuestion") return askNudges(payload, { root });
379
459
  if (SHELL_TOOLS.has(tool)) return submitNudges(payload.tool_input?.command, { cwd });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.50",
3
+ "version": "0.6.52",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {