@nodii/dev 0.6.49 → 0.6.51

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.
@@ -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
 
@@ -92,7 +92,7 @@ export const doneCheckRecorded = (lane) =>
92
92
  || (lane?.steps ?? []).some((step) => step.stepKey === "dev_check" && step.state === "done")
93
93
  || FINISHED_LANE.has(lane?.status);
94
94
 
95
- /** A lane is BLOCKED by a blocked step (`lane step --block`) or a latest heartbeat note that says so. */
95
+ /** A lane is BLOCKED by a blocked step (`lane step --block`) or a latest heartbeat note that starts "blocked" or "WAITING:" (AGENT-HARNESS-46). */
96
96
  export const laneBlocked = (lane) => Boolean(laneBlockedReason(lane));
97
97
 
98
98
  /** Why a lane is BLOCKED, or null (the same rule Dev applies to a run's exit). */
@@ -101,7 +101,7 @@ export function laneBlockedReason(lane) {
101
101
  if (step) return `Lane step ${step.side}/${step.stepKey} is blocked.`;
102
102
  const heartbeat = (lane?.events ?? []).filter((event) => event.type === "heartbeat").at(-1);
103
103
  const note = String(heartbeat?.metadata?.note ?? "");
104
- return /^\s*blocked\b/i.test(note) ? `Lane heartbeat: ${note.slice(0, 500)}` : null;
104
+ return /^\s*blocked\b/i.test(note) || /^\s*WAITING\s*:/.test(note) ? `Lane heartbeat: ${note.slice(0, 500)}` : null;
105
105
  }
106
106
 
107
107
  /** The step a lane that stopped early goes back to (hub-58, NODII-DEV-CLI-8/9). */
package/dist/lanes.js CHANGED
@@ -657,10 +657,20 @@ export async function laneCommand(action, args, flags, { request = devRequest, c
657
657
  return { payload, human: `${ref}: subagent quota set to ${quota}.` };
658
658
  }
659
659
  if (action === "resume") {
660
+ // AGENT-HARNESS-46: --override resumes a lane the two-deaths rule stopped;
661
+ // Dev allows it only after a `lane amend`, and keeps the reason on the run.
662
+ if (flags.override && flags.reason === undefined)
663
+ throw new CliError("USAGE", "lane resume --override needs --reason TEXT.", 2);
664
+ if (!flags.override && flags.reason !== undefined)
665
+ throw new CliError("USAGE", "--reason goes with --override.", 2);
666
+ if (Array.isArray(flags.reason)) throw new CliError("USAGE", "Give --reason once.", 2);
667
+ const overrideReason = typeof flags.reason === "string" ? flags.reason.trim() : "";
668
+ if (flags.override && !overrideReason) throw new CliError("USAGE", "--reason needs TEXT: why resuming the amended lane is safe.", 2);
669
+ if (overrideReason.length > 2_000) throw new CliError("USAGE", `--reason is ${overrideReason.length} characters; Dev keeps at most 2,000.`, 2);
660
670
  const payload = await request(
661
671
  "POST",
662
672
  `/api/v1/lanes/${encode(id)}/resume`,
663
- via,
673
+ flags.override ? { override: true, reason: overrideReason, ...via } : via,
664
674
  );
665
675
  let launched;
666
676
  try {
@@ -686,7 +696,8 @@ export async function laneCommand(action, args, flags, { request = devRequest, c
686
696
  const continuation = next
687
697
  ? `${next.side}/${next.step}`
688
698
  : "the lane's next unfinished step";
689
- return `${ref}: resumed fresh run ${runId} as PID ${launched.pid}; continuing ${continuation} from ${checkpoint}.`;
699
+ const override = response.data.run.resumeOverrideReason;
700
+ return `${ref}: resumed fresh run ${runId} as PID ${launched.pid}; continuing ${continuation} from ${checkpoint}.${override ? ` Override past the two-deaths stop recorded ("${override}"); the death count restarts.` : ""}`;
690
701
  },
691
702
  };
692
703
  }
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.49",
3
+ "version": "0.6.51",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {