@nodii/dev 0.6.132 → 0.6.134

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.
@@ -0,0 +1,207 @@
1
+ // nodii-dev figma publish FILE --sets CS-1,CS-2 [--dry-run]
2
+ //
3
+ // Publishes a Figma library through the machine's shared Chrome with only the
4
+ // components of finished change sets ticked (operator, 13 Nov 2026, N44: "if
5
+ // you need to publish - you can do it through the chrome without waiting for
6
+ // me!"). A finished set is decided and applied: Dev shows it awaiting_publish.
7
+ // Every other row in the dialog is unticked, so a set still being drawn or in
8
+ // review never ships early (MW8-7.1, MW8-4.1).
9
+ //
10
+ // It opens its own tab and closes only that tab (K02-16, K02-17), checks the
11
+ // tab is on www.figma.com and on the named file before it touches anything,
12
+ // and records each fully published set in Dev (figma published).
13
+ import { appendFile, mkdir } from "node:fs/promises";
14
+ import { homedir } from "node:os";
15
+ import { join } from "node:path";
16
+ import { CliError, devRequest, encode } from "./core.js";
17
+ import { cdpConnect } from "./cdp.js";
18
+ import { sharedChromePort } from "./chrome.js";
19
+ import { figmaClient, figmaToken } from "./design.js";
20
+ import { figmaFileKey } from "./figma.js";
21
+
22
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
23
+ export const FINISHED_STATE = "awaiting_publish";
24
+ export const publishLogPath = (home = homedir()) => join(home, ".config", "nodii-dev", "coordinator", "publishes.jsonl");
25
+
26
+ /** The ids in --sets, upper-cased and checked. */
27
+ export function parseSets(value) {
28
+ if (typeof value !== "string" || !value.trim()) throw new CliError("USAGE", "figma publish FILE_KEY --sets CS-1,CS-2 [--dry-run]", 2);
29
+ const ids = [...new Set(value.split(",").map((s) => s.trim().toUpperCase()).filter(Boolean))];
30
+ for (const id of ids) if (!/^CS-\d+$/.test(id)) throw new CliError("USAGE", `${id} is not a change set id (CS-123).`, 2);
31
+ return ids;
32
+ }
33
+
34
+ /** The component names an approved set publishes: its approved items, by name. */
35
+ export function setComponentNames(set) {
36
+ return [...new Set((set.items ?? []).filter((item) => item.decision === "approved" && !item.withdrawnReason && item.name).map((item) => item.name.trim()))];
37
+ }
38
+
39
+ /**
40
+ * Reads each set from Dev and refuses the publish when any set is not finished or
41
+ * is on another file. Returns the sets with the names each one publishes.
42
+ */
43
+ export async function finishedSets(fileKey, ids, { request = devRequest } = {}) {
44
+ const sets = [];
45
+ const refused = [];
46
+ for (const id of ids) {
47
+ const set = (await request("GET", `/api/v1/design/change-sets/${encode(id)}`)).data;
48
+ if (set.fileKey !== fileKey) refused.push(`${id} is on file ${set.fileKey}, not ${fileKey}`);
49
+ else if (set.state !== FINISHED_STATE) refused.push(`${id} is ${set.state}, not ${FINISHED_STATE} (only decided and applied sets publish)`);
50
+ else sets.push({ id, title: set.title ?? "", names: setComponentNames(set) });
51
+ }
52
+ if (refused.length) throw new CliError("PUBLISH_SETS_NOT_FINISHED", `Not published: ${refused.join("; ")}.`, 1, { refused });
53
+ return sets;
54
+ }
55
+
56
+ // Runs in the page. Walks the dialog's virtualized list from top to bottom and
57
+ // sets each row's checkbox: ticked when its name is wanted, unticked otherwise.
58
+ // Returns every row seen, with its state before and after.
59
+ export const DIALOG_SYNC = `async function(wanted, apply){
60
+ const sleep=(ms)=>new Promise(r=>setTimeout(r,ms));
61
+ const want=new Set(wanted);
62
+ const boxes=()=>[...document.querySelectorAll('input[data-testid=publish-library-item-checkbox]')];
63
+ const first=boxes()[0];
64
+ if(!first) return {error:'no publish rows'};
65
+ let scroller=first.parentElement;
66
+ while(scroller && !(scroller.scrollHeight>scroller.clientHeight+4 && /(auto|scroll)/.test(getComputedStyle(scroller).overflowY))) scroller=scroller.parentElement;
67
+ const rows=new Map();
68
+ const visit=async()=>{
69
+ for(const box of boxes()){
70
+ const row=box.closest('label.library_item_row--libraryItemRow--69LPl')||box.closest('label[class*=libraryItemRow]')||box.closest('label');
71
+ const name=(row?.querySelector('[class*=name] [title], span[title]')?.getAttribute('title')||(row?.querySelector('label[for]')?.textContent||'').replace(/^Include /,'').replace(/ in publish$/,'')).trim();
72
+ if(!name) continue;
73
+ const status=(row?.querySelector('[class*=statusTag]')?.textContent||'').trim();
74
+ const before=rows.has(name)?rows.get(name).before:box.checked;
75
+ if(apply && box.checked!==want.has(name)){ box.click(); await sleep(60); }
76
+ rows.set(name,{name,status,before,after:box.checked});
77
+ }
78
+ };
79
+ const head=[...document.querySelectorAll('*')].find(e=>e.childElementCount<=2&&/^Changes\s*\(\d+ of \d+\)$/.test(e.textContent.trim()));
80
+ const total=head?Number(head.textContent.trim().match(/of (\d+)\)/)[1]):null;
81
+ if(!scroller){ await visit(); return {rows:[...rows.values()],total}; }
82
+ scroller.scrollTop=0; await sleep(300);
83
+ for(let guard=0; guard<400; guard++){
84
+ await visit();
85
+ if(scroller.scrollTop+scroller.clientHeight>=scroller.scrollHeight-2) break;
86
+ scroller.scrollTop+=Math.max(40,scroller.clientHeight-60); await sleep(250);
87
+ }
88
+ await visit();
89
+ scroller.scrollTop=0;
90
+ return {rows:[...rows.values()],total};
91
+ }`;
92
+
93
+ const FILL_DESCRIPTION = `function(text){const t=[...document.querySelectorAll('textarea')].find(x=>/description/i.test(x.placeholder||''));
94
+ if(!t) return false; const s=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set; s.call(t,text);
95
+ t.dispatchEvent(new Event('input',{bubbles:true})); return true;}`;
96
+ const CLICK_BUTTON = `function(label){const b=[...document.querySelectorAll('button')].find(x=>x.textContent.trim()===label && !x.disabled);
97
+ if(!b) return false; b.click(); return true;}`;
98
+ const DIALOG_OPEN = "!!document.querySelector('input[data-testid=publish-library-item-checkbox]')";
99
+
100
+ /** What the dialog must look like after the sync: every wanted row ticked, nothing else. */
101
+ export function syncReport(sets, rows, total) {
102
+ const byName = new Map(rows.map((row) => [row.name, row]));
103
+ const wanted = new Set(sets.flatMap((set) => set.names));
104
+ const unmapped = sets.flatMap((set) => set.names.filter((name) => !byName.has(name)).map((name) => ({ set: set.id, name })));
105
+ const wrong = rows.filter((row) => row.after !== wanted.has(row.name)).map((row) => row.name);
106
+ // Every row the dialog counts must have been seen, or an unseen row could ship.
107
+ if (total === undefined) {} // a caller that does not check the count
108
+ else if (!Number.isInteger(total)) wrong.push("(could not read the dialog's change count, so unseen rows can't be ruled out)");
109
+ else if (total !== rows.length) wrong.push(`(saw ${rows.length} of the dialog's ${total} changes)`);
110
+ const ticked = rows.filter((row) => row.after).map((row) => row.name);
111
+ const unticked = rows.filter((row) => !row.after).map((row) => row.name);
112
+ // A set is recorded only when every one of its components is in this publish (P-4).
113
+ const complete = sets.filter((set) => set.names.length && set.names.every((name) => byName.get(name)?.after)).map((set) => set.id);
114
+ return { ticked, unticked, unmapped, wrong, complete, incomplete: sets.map((s) => s.id).filter((id) => !complete.includes(id)) };
115
+ }
116
+
117
+ async function newestVersion(figmaGet, fileKey) {
118
+ const body = await figmaGet(`/v1/files/${encode(fileKey)}/versions`);
119
+ return body?.versions?.[0]?.id ?? null;
120
+ }
121
+
122
+ export async function figmaPublish(file, flags = {}, {
123
+ request = devRequest, connect = cdpConnect, home = homedir(), env = process.env, sleep = delay,
124
+ figmaGet, log = (line) => appendFile(publishLogPath(home), `${line}\n`), loadSeconds = 20, portOf,
125
+ } = {}) {
126
+ if (!file) throw new CliError("USAGE", "figma publish FILE_KEY --sets CS-1,CS-2 [--dry-run]", 2);
127
+ const fileKey = figmaFileKey(file);
128
+ const ids = parseSets(flags.sets);
129
+ const dryRun = Boolean(flags["dry-run"]);
130
+ const sets = await finishedSets(fileKey, ids, { request });
131
+ const get = dryRun ? null : (figmaGet ?? figmaClient(figmaToken(env)));
132
+ const before = get ? await newestVersion(get, fileKey) : null;
133
+ const port = await (portOf ?? (() => sharedChromePort({ home, request })))();
134
+ const cdp = await connect(port);
135
+ let report;
136
+ let published = false;
137
+ try {
138
+ report = await cdp.withTab(`https://www.figma.com/design/${encode(fileKey)}`, async (tab) => {
139
+ await sleep(loadSeconds * 1000);
140
+ const where = await tab.evaluate("location.host + ' ' + location.pathname");
141
+ if (!String(where).startsWith(`www.figma.com /design/${fileKey}`))
142
+ throw new CliError("PUBLISH_WRONG_PAGE", `The tab is on ${where}, not www.figma.com/design/${fileKey}; nothing was touched.`, 1);
143
+ // Quick actions (Cmd+/) -> "Publish changes to library".
144
+ await tab.key("/", { modifiers: 4, code: "Slash", keyCode: 191 });
145
+ await sleep(1500);
146
+ await tab.send("Input.insertText", { text: "Publish changes to library" });
147
+ await sleep(1500);
148
+ await tab.key("Enter", { keyCode: 13 });
149
+ if (!(await tab.waitFor(DIALOG_OPEN, 30, { sleep })))
150
+ throw new CliError("PUBLISH_DIALOG_NOT_FOUND", "Figma's Publish library dialog did not open (nothing to publish, or the file is not a library).", 1);
151
+ const synced = await tab.call(DIALOG_SYNC, [sets.flatMap((set) => set.names), true]);
152
+ if (synced?.error) throw new CliError("PUBLISH_DIALOG_UNREADABLE", synced.error, 1);
153
+ // Read it again without touching it: the dialog is what gets published.
154
+ const check = await tab.call(DIALOG_SYNC, [[], false]);
155
+ const result = syncReport(sets, check.rows, check.total ?? null);
156
+ if (result.wrong.length) {
157
+ await tab.call(CLICK_BUTTON, ["Cancel"]);
158
+ throw new CliError("PUBLISH_DIALOG_MISMATCH", `These rows would not settle to the wanted state: ${result.wrong.join(", ")}. Nothing was published.`, 1, result);
159
+ }
160
+ if (dryRun || !result.ticked.length) {
161
+ await tab.call(CLICK_BUTTON, ["Cancel"]);
162
+ return result;
163
+ }
164
+ await tab.call(FILL_DESCRIPTION, [sets.map((set) => `${set.id} ${set.title}`.trim()).join("; ").slice(0, 900)]);
165
+ if (!(await tab.call(CLICK_BUTTON, ["Publish"]))) throw new CliError("PUBLISH_BUTTON_NOT_FOUND", "The Publish button was not found or was disabled.", 1, result);
166
+ published = true;
167
+ await tab.waitFor(`!(${DIALOG_OPEN})`, 120, { sleep });
168
+ return result;
169
+ });
170
+ } finally {
171
+ await cdp.close();
172
+ }
173
+ let version = null;
174
+ const recorded = [];
175
+ const notRecorded = report.incomplete.map((id) => ({ id, reason: "not every component of the set was in this publish" }));
176
+ if (published) {
177
+ for (let i = 0; i < 24 && (!version || version === before); i++) {
178
+ await sleep(5000);
179
+ version = await newestVersion(get, fileKey).catch(() => null);
180
+ }
181
+ if (!version || version === before) notRecorded.push(...report.complete.map((id) => ({ id, reason: "Figma showed no new version after the publish" })));
182
+ else
183
+ for (const id of report.complete) {
184
+ try {
185
+ await request("POST", `/api/v1/design/change-sets/${encode(id)}/published`, { figmaVersion: version });
186
+ recorded.push(id);
187
+ } catch (error) {
188
+ notRecorded.push({ id, reason: `${error?.code ?? "PUBLISHED_REFUSED"}: ${error?.message ?? error}` });
189
+ }
190
+ }
191
+ }
192
+ const data = { fileKey, dryRun, published, version, sets: ids, ...report, recorded, notRecorded };
193
+ await mkdir(join(home, ".config", "nodii-dev", "coordinator"), { recursive: true, mode: 0o700 }).catch(() => {});
194
+ await log(JSON.stringify({ at: new Date().toISOString(), ...data })).catch(() => {});
195
+ return data;
196
+ }
197
+
198
+ export function figmaPublishText(d) {
199
+ return [
200
+ d.dryRun ? `Dry run on ${d.fileKey}: nothing published.` : d.published ? `Published ${d.fileKey} as version ${d.version ?? "(not seen yet)"}.` : `Nothing to publish on ${d.fileKey}.`,
201
+ `ticked (${d.ticked.length}): ${d.ticked.join(", ") || "none"}`,
202
+ `unticked (${d.unticked.length}): ${d.unticked.join(", ") || "none"}`,
203
+ ...(d.unmapped.length ? [`NOT IN THE DIALOG: ${d.unmapped.map((u) => `${u.set} ${u.name}`).join(", ")}`] : []),
204
+ ...(d.recorded.length ? [`recorded in Dev: ${d.recorded.join(", ")}`] : []),
205
+ ...d.notRecorded.map((n) => `not recorded: ${n.id} (${n.reason})`),
206
+ ].join("\n");
207
+ }
package/dist/figma.js CHANGED
@@ -706,11 +706,14 @@ export async function figmaScopeAdd(id, scopes, { request = devRequest, laneScop
706
706
  * sit inside what the set holds: the whole file holds everything, a page its
707
707
  * components and creates.
708
708
  */
709
- export async function figmaScopeSet(id, scopes, { request = devRequest, laneScope = currentLaneFigmaScope } = {}) {
710
- if (!id || !scopes.length) throw new CliError("USAGE", `figma scope set CHANGE_SET ${SCOPE_USAGE} [--scope ...]`, 2);
709
+ export async function figmaScopeSet(id, scopes, { request = devRequest, laneScope = currentLaneFigmaScope, laneReads, progress } = {}) {
710
+ if (!id || !scopes.length) throw new CliError("USAGE", `figma scope set CHANGE_SET ${SCOPE_USAGE} [--scope ...] [--lane-reads FILE]`, 2);
711
711
  await assertChangeSetInLaneScope(id, scopes, request, laneScope);
712
712
  try {
713
- return await request("PUT", `/api/v1/design/change-sets/${encode(id)}/scopes`, { scopes });
713
+ // MW1-57.11: the narrowing's gate runs on the lane's reads; reads over a
714
+ // chunk go up to the set first and are named by readIds (hub-310).
715
+ const reads = await laneReadsBody(id, laneReads, { request, ...(progress ? { progress } : {}) });
716
+ return await request("PUT", `/api/v1/design/change-sets/${encode(id)}/scopes`, { scopes, ...reads });
714
717
  } catch (error) {
715
718
  if (error?.code === "SCOPE_NOT_NARROWER")
716
719
  throw new CliError(error.code, `${error.message}\nscope set only narrows; to claim more, run nodii-dev figma scope add ${id} --scope ...`, error.exitCode ?? 1, error.details);
@@ -725,7 +728,7 @@ export async function figmaScopeSet(id, scopes, { request = devRequest, laneScop
725
728
  error.exitCode ?? 1,
726
729
  error.details,
727
730
  );
728
- throw scopeRefusal(error, id) ?? error;
731
+ throw laneReadsRefusal(scopeRefusal(error, id) ?? error);
729
732
  }
730
733
  }
731
734
 
package/dist/flags.js CHANGED
@@ -75,6 +75,7 @@ export const COMMAND_FLAGS = {
75
75
  "figma changeset": ["file", "actionable", "all", "limit"],
76
76
  "figma apply": ["file", "figma-version", "lane-reads"],
77
77
  "figma lock": ["title", "scope", "lane-reads"],
78
+ "figma scope": ["scope", "lane-reads"],
78
79
  "surface generate": ["write", "check", "fetch", "all", "module", "type", "figma-version", "report", "post-scoreboard", "resume"],
79
80
  };
80
81
 
package/dist/governor.js CHANGED
@@ -101,7 +101,9 @@ export async function governorSessionStart(deps = {}) {
101
101
  const { kind, agent } = await governorSessionKind(deps);
102
102
  if (!kind || !agent?.machineId) return "";
103
103
  const g = await readGovernor(agent.machineId, deps);
104
- return [`Session kind: ${kind}.`, ...governorLines(g)].join("\n");
104
+ // hub-405: the coordinator watch's new alerts reach the coordinator session here.
105
+ const alerts = kind === "coordinator" ? await (deps.coordinatorAlerts ?? (async () => (await import("./coordinator-watch.js")).coordinatorAlertLines()))().catch(() => []) : [];
106
+ return [`Session kind: ${kind}.`, ...governorLines(g), ...alerts].join("\n");
105
107
  }
106
108
 
107
109
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.132",
3
+ "version": "0.6.134",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {