@nodii/dev 0.6.172 → 0.6.173

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,272 @@
1
+ // The one Figma REST client (cli-170). Every nodii-dev process that calls
2
+ // Figma's REST API with a token goes through here, so that:
3
+ //
4
+ // 1. Calls on one token are queued across the whole machine. Each process
5
+ // reserves the next slot in a small file under the machine's nodii-dev
6
+ // directory, one slot per `minIntervalMs`, and waits for it. The lock is
7
+ // held only while the slot is reserved, never during the call. Each token
8
+ // has its own queue. A slot that cannot be reserved fails the call with
9
+ // FIGMA_QUEUE_UNAVAILABLE: no process paces only itself.
10
+ // 2. A 429 waits what Retry-After says and is sent again, at most twice. A
11
+ // third 429 fails with FIGMA_RATE_LIMITED, as a first one did before. A
12
+ // Retry-After longer than a minute is not waited out: it fails at once.
13
+ // 3. A /nodes read at a pinned version is immutable, so each node read that
14
+ // way is kept on disk, keyed by file key, version and node id (and the
15
+ // read's other query parameters), and shared by every process and token on
16
+ // the machine. A read with no version is the live file and is never kept.
17
+ import { createHash, randomUUID } from "node:crypto";
18
+ import { mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
19
+ import { basename, dirname, join } from "node:path";
20
+ import { CliError, configPath } from "./core.js";
21
+
22
+ export const FIGMA_API = "https://api.figma.com/v1";
23
+ /** One call per this long, per token, across the machine. */
24
+ export const MIN_FIGMA_INTERVAL_MS = 8_000;
25
+ /** How many times a 429 is sent again. */
26
+ export const MAX_RATE_RETRIES = 2;
27
+ /** The longest Retry-After that is waited out. */
28
+ export const MAX_RETRY_AFTER_MS = 60_000;
29
+ /** The wait when a 429 names none. */
30
+ const NO_RETRY_AFTER_MS = 30_000;
31
+ const BACKOFF_MS = 30_000;
32
+ // The slot file's lock is held for milliseconds; one older than this belongs to a process that died.
33
+ const LOCK_STALE_MS = 5_000;
34
+ const LOCK_WAIT_MS = 15_000;
35
+ const LOCK_POLL_MS = 20;
36
+ // A slot this far ahead is not a queue: the file is damaged, or the clock moved.
37
+ const MAX_QUEUE_MS = 30 * 60_000;
38
+ const CACHE_PRUNE_AFTER_MS = 14 * 24 * 60 * 60_000;
39
+ const delay = (ms) => new Promise((done) => setTimeout(done, ms));
40
+
41
+ /** The machine's nodii-dev directory (an agent's config sits two below it), or NODII_DEV_FIGMA_REST_DIR. */
42
+ export function figmaRestRoot() {
43
+ if (process.env.NODII_DEV_FIGMA_REST_DIR) return process.env.NODII_DEV_FIGMA_REST_DIR;
44
+ const dir = dirname(configPath());
45
+ return basename(dir) === "agents" ? dirname(dir) : dir;
46
+ }
47
+
48
+ const queueUnavailable = (why) => new CliError("FIGMA_QUEUE_UNAVAILABLE", `This machine's Figma queue cannot be used (${why}), so the call was not sent: a process must not pace only itself (MW1-57.13). Check that ${figmaRestRoot()} is a directory this user can write.`, 1);
49
+
50
+ /** Run `task` holding the slot file's lock. A lock that can't be taken fails the call: the queue is the only pace there is. */
51
+ async function withLock(lock, task) {
52
+ let held = false;
53
+ const deadline = Date.now() + LOCK_WAIT_MS;
54
+ while (!held && Date.now() < deadline) {
55
+ try {
56
+ await (await open(lock, "wx", 0o600)).close();
57
+ held = true;
58
+ } catch (error) {
59
+ if (error?.code !== "EEXIST") throw queueUnavailable(`its lock could not be made: ${error?.code ?? error?.message}`);
60
+ try {
61
+ if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS) await rm(lock, { force: true });
62
+ else await delay(LOCK_POLL_MS);
63
+ } catch {}
64
+ }
65
+ }
66
+ if (!held) throw queueUnavailable(`its lock was held for ${LOCK_WAIT_MS / 1000} s`);
67
+ try {
68
+ return await task();
69
+ } finally {
70
+ await rm(lock, { force: true }).catch(() => {});
71
+ }
72
+ }
73
+
74
+ /**
75
+ * The machine-wide queue for one token. `take()` reserves the next slot and
76
+ * waits for it; `defer(ms)` moves every slot not yet used at least `ms` from
77
+ * now, one a call is already waiting for included (a 429's Retry-After holds
78
+ * back every process on the token, not only the one that got it). The token is never written: the file is named by its hash.
79
+ * A slot that cannot be saved fails the call with FIGMA_QUEUE_UNAVAILABLE.
80
+ */
81
+ export function figmaPace(token, { root = figmaRestRoot(), minIntervalMs = MIN_FIGMA_INTERVAL_MS, now = Date.now, sleep = delay } = {}) {
82
+ const slots = join(root, `figma-rest-${createHash("sha256").update(String(token)).digest("hex").slice(0, 16)}.slot`);
83
+ // What this process has reserved itself, should the file be new or damaged.
84
+ const local = { last: -Infinity, notBefore: -Infinity };
85
+ const change = (update) =>
86
+ withLock(`${slots}.lock`, async () => {
87
+ const at = now();
88
+ let last = local.last;
89
+ let notBefore = local.notBefore;
90
+ try {
91
+ const saved = JSON.parse(await readFile(slots, "utf8"));
92
+ if (Number.isFinite(saved.last) && saved.last - at < MAX_QUEUE_MS) last = Math.max(last, saved.last);
93
+ if (Number.isFinite(saved.notBefore) && saved.notBefore - at < MAX_QUEUE_MS) notBefore = Math.max(notBefore, saved.notBefore);
94
+ } catch (error) {
95
+ // No file yet, or a damaged one, starts the queue again; a file that can't be read is not a queue.
96
+ if (error?.code !== "ENOENT" && !(error instanceof SyntaxError)) throw queueUnavailable(`its slot file could not be read: ${error?.code ?? error?.message}`);
97
+ }
98
+ const next = update({ at, last, notBefore });
99
+ const temporary = `${slots}.${process.pid}.${randomUUID()}`;
100
+ try {
101
+ await writeFile(temporary, JSON.stringify(next), { mode: 0o600 });
102
+ await rename(temporary, slots);
103
+ } catch (error) {
104
+ await rm(temporary, { force: true }).catch(() => {});
105
+ throw queueUnavailable(`its slot file could not be saved: ${error?.code ?? error?.message}`);
106
+ }
107
+ Object.assign(local, next);
108
+ return next;
109
+ });
110
+ const ready = mkdir(root, { recursive: true, mode: 0o700 }).catch(() => {});
111
+ return {
112
+ /** Wait for this call's slot; answers how long it waited. */
113
+ async take() {
114
+ await ready;
115
+ let waited = 0;
116
+ for (;;) {
117
+ const { last: mine } = await change(({ at, last, notBefore }) => ({ last: Math.max(at, last + minIntervalMs, notBefore), notBefore }));
118
+ const wait = mine - now();
119
+ if (wait > 0) {
120
+ await sleep(wait);
121
+ waited += wait;
122
+ }
123
+ // A 429 on this token while this call waited moves it too: its slot is void, so it takes the next one.
124
+ const { notBefore } = await change(({ last, notBefore }) => ({ last, notBefore }));
125
+ if (notBefore <= mine) return waited;
126
+ }
127
+ },
128
+ async defer(ms) {
129
+ await ready;
130
+ await change(({ at, last, notBefore }) => ({ last, notBefore: Math.max(notBefore, at + ms) }));
131
+ },
132
+ };
133
+ }
134
+
135
+ /**
136
+ * The shared cache of pinned /nodes reads: one file per (file key, version,
137
+ * node id, shape of read). Every file error is a miss; the cache never fails a read.
138
+ */
139
+ export function figmaTreeCache({ dir = join(figmaRestRoot(), "figma-tree-cache"), now = Date.now } = {}) {
140
+ const file = ({ fileKey, version, nodeId, shape = "" }) => join(dir, `${createHash("sha256").update([fileKey, version, nodeId, shape].join("\n")).digest("hex").slice(0, 40)}.json`);
141
+ return {
142
+ async get(key) {
143
+ try {
144
+ const saved = JSON.parse(await readFile(file(key), "utf8"));
145
+ if (saved.fileKey !== key.fileKey || saved.version !== key.version || saved.nodeId !== key.nodeId || saved.shape !== (key.shape ?? "")) return undefined;
146
+ return saved.value;
147
+ } catch {
148
+ return undefined;
149
+ }
150
+ },
151
+ async set(key, value) {
152
+ try {
153
+ await mkdir(dir, { recursive: true, mode: 0o700 });
154
+ const target = file(key);
155
+ const temporary = `${target}.${process.pid}.${randomUUID()}`;
156
+ await writeFile(temporary, JSON.stringify({ fileKey: key.fileKey, version: key.version, nodeId: key.nodeId, shape: key.shape ?? "", value }), { mode: 0o600 });
157
+ await rename(temporary, target);
158
+ if (Math.random() < 0.02) await prune(dir, now());
159
+ } catch {}
160
+ },
161
+ };
162
+ }
163
+
164
+ async function prune(dir, at) {
165
+ for (const name of await readdir(dir)) {
166
+ try {
167
+ const path = join(dir, name);
168
+ if (at - (await stat(path)).mtimeMs > CACHE_PRUNE_AFTER_MS) await rm(path, { force: true });
169
+ } catch {}
170
+ }
171
+ }
172
+
173
+ /** A /files/:key/nodes read at a pinned version, taken apart; null for every other path. */
174
+ function pinnedNodesRead(path) {
175
+ const match = /^\/files\/([^/?]+)\/nodes\?(.+)$/.exec(path);
176
+ if (!match) return null;
177
+ const parts = match[2].split("&");
178
+ const value = (name) => {
179
+ const part = parts.find((x) => x.startsWith(`${name}=`));
180
+ return part ? decodeURIComponent(part.slice(name.length + 1)) : null;
181
+ };
182
+ const version = value("version");
183
+ const ids = (value("ids") ?? "").split(",").filter(Boolean);
184
+ if (!version || !ids.length) return null;
185
+ const shape = parts.filter((x) => !x.startsWith("ids=") && !x.startsWith("version=")).sort().join("&");
186
+ const pathFor = (some) => `/files/${match[1]}/nodes?${parts.map((x) => (x.startsWith("ids=") ? `ids=${encodeURIComponent(some.join(","))}` : x)).join("&")}`;
187
+ return { fileKey: decodeURIComponent(match[1]), version, ids: [...new Set(ids)], shape, pathFor };
188
+ }
189
+
190
+ const retryAfterMs = (response) => {
191
+ const seconds = Number(response.headers?.get?.("retry-after"));
192
+ return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : null;
193
+ };
194
+
195
+ /**
196
+ * A Figma REST GET: `figmaGet(path)` answers the parsed body. Queued per token
197
+ * across the machine, a 429 retried at most twice, pinned /nodes reads cached.
198
+ * `cache: null` reads Figma every time. `serverBackoffMs(attempt)` and
199
+ * `errorBackoffMs(attempt)` are the waits after a 5xx and after a failed
200
+ * connection; `timeoutError(path)` makes a timeout final; `hint(status)` adds
201
+ * to the refusal's message.
202
+ */
203
+ export function figmaRest(token, {
204
+ fetchImpl = fetch, sleep = delay, now = Date.now, root = figmaRestRoot(), minIntervalMs = MIN_FIGMA_INTERVAL_MS,
205
+ pace = figmaPace(token, { root, minIntervalMs, now, sleep }),
206
+ cache = figmaTreeCache({ dir: join(root, "figma-tree-cache"), now }),
207
+ attempts = 5, timeoutMs = 180_000, log = () => {},
208
+ serverBackoffMs = (attempt) => BACKOFF_MS * 2 ** (attempt - 1), errorBackoffMs = () => BACKOFF_MS,
209
+ timeoutError = null, hint = () => "",
210
+ } = {}) {
211
+ const name = (path) => path.split("?")[0];
212
+ async function send(path) {
213
+ let limited = 0;
214
+ for (let attempt = 1; ; attempt++) {
215
+ const queued = await pace.take();
216
+ if (queued > 30_000) log(`waited ${Math.round(queued / 1000)} s in this machine's Figma queue for ${name(path)}`);
217
+ let response;
218
+ try {
219
+ response = await fetchImpl(`${FIGMA_API}${path}`, { headers: { "X-Figma-Token": token }, signal: AbortSignal.timeout(timeoutMs) });
220
+ // The clock runs while a large body streams in, too.
221
+ if (response.ok) return await response.json();
222
+ } catch (error) {
223
+ if (error instanceof SyntaxError) throw new CliError("FIGMA_ERROR", `Figma answered ${name(path)} with a body that isn't JSON`);
224
+ if (error?.name === "TimeoutError" && timeoutError) throw timeoutError(path);
225
+ if (attempt >= attempts) throw new CliError("FIGMA_UNREACHABLE", `Cannot reach Figma: ${error.message}`);
226
+ await sleep(errorBackoffMs(attempt));
227
+ continue;
228
+ }
229
+ if (response.status === 429) {
230
+ const asked = retryAfterMs(response);
231
+ const wait = asked ?? NO_RETRY_AFTER_MS;
232
+ if (limited < MAX_RATE_RETRIES && wait <= MAX_RETRY_AFTER_MS) {
233
+ limited += 1;
234
+ log(`Figma answered 429 for ${name(path)}; waiting ${Math.round(wait / 1000)} s, then sending it again (retry ${limited} of ${MAX_RATE_RETRIES})`);
235
+ // Every process on this token waits, through the queue; so does this one, at its next slot.
236
+ await pace.defer(wait);
237
+ continue;
238
+ }
239
+ throw new CliError("FIGMA_RATE_LIMITED", `Figma answered 429 for ${name(path)}${limited ? ` after ${limited} retr${limited === 1 ? "y" : "ies"}` : ""}`, 1, { status: 429, ...(asked ? { retryAfterSeconds: asked / 1000 } : {}) });
240
+ }
241
+ if (response.status >= 500 && attempt < attempts) {
242
+ const ms = serverBackoffMs(attempt);
243
+ log(`Figma answered ${response.status} for ${name(path)}; waiting ${Math.round(ms / 1000)} s`);
244
+ await sleep(ms);
245
+ continue;
246
+ }
247
+ const code = { 404: "FIGMA_NOT_FOUND", 403: "FIGMA_FORBIDDEN" }[response.status] ?? "FIGMA_ERROR";
248
+ throw new CliError(code, `Figma answered ${response.status} for ${name(path)}${hint(response.status)}`, 1, { status: response.status });
249
+ }
250
+ }
251
+
252
+ return async function figmaGet(path) {
253
+ const read = cache ? pinnedNodesRead(path) : null;
254
+ if (!read) return send(path);
255
+ const key = (nodeId) => ({ fileKey: read.fileKey, version: read.version, nodeId, shape: read.shape });
256
+ const kept = new Map();
257
+ for (const id of read.ids) {
258
+ const hit = await cache.get(key(id));
259
+ if (hit) kept.set(id, hit);
260
+ }
261
+ const missing = read.ids.filter((id) => !kept.has(id));
262
+ let body = null;
263
+ if (missing.length) {
264
+ body = await send(missing.length === read.ids.length ? path : read.pathFor(missing));
265
+ const { nodes = {}, ...meta } = body ?? {};
266
+ for (const id of missing) if (nodes?.[id]?.document) await cache.set(key(id), { meta, entry: nodes[id] });
267
+ if (!kept.size) return body;
268
+ }
269
+ const { nodes: fresh = {}, ...meta } = body ?? { ...kept.get(read.ids[0]).meta };
270
+ return { ...meta, nodes: Object.fromEntries(read.ids.map((id) => [id, kept.has(id) ? kept.get(id).entry : (fresh?.[id] ?? null)])) };
271
+ };
272
+ }
@@ -6,7 +6,7 @@
6
6
  import { homedir } from "node:os";
7
7
  import { join } from "node:path";
8
8
  import { readCache, writeCache } from "./api.js";
9
- import { CliError, devRequest } from "./core.js";
9
+ import { CliError, devRequest, hookLanePath } from "./core.js";
10
10
  import { currentLane } from "./freeze.js";
11
11
 
12
12
  /** The DS catalog as the design site publishes it (`build:public-assets`). */
@@ -396,6 +396,6 @@ export async function currentLaneFigmaScope({ cwd = process.cwd() } = {}, deps =
396
396
  let lane = await currentLane({ cwd }, deps);
397
397
  if (!lane) return null;
398
398
  // A lane found through the list carries no launch record; read its detail.
399
- if (!("launch" in lane)) lane = (await (deps.request ?? devRequest)("GET", `/api/v1/lanes/${encodeURIComponent(lane.key)}`)).data ?? lane;
399
+ if (!("launch" in lane)) lane = (await (deps.request ?? devRequest)("GET", deps.hook ? hookLanePath(lane.key) : `/api/v1/lanes/${encodeURIComponent(lane.key)}`)).data ?? lane;
400
400
  return laneFigmaScope(lane);
401
401
  }
package/dist/flags.js CHANGED
@@ -77,6 +77,7 @@ export const COMMAND_FLAGS = {
77
77
  "figma apply": ["file", "figma-version", "lane-reads"],
78
78
  "figma lock": ["title", "scope", "lane-reads"],
79
79
  "figma scope": ["scope", "lane-reads"],
80
+ "surface corpus": ["ds", "ref", "module", "report", "baseline", "update"],
80
81
  "surface generate": ["write", "check", "fetch", "all", "module", "type", "figma-version", "node", "report", "post-scoreboard", "resume"],
81
82
  };
82
83
 
package/dist/freeze.js CHANGED
@@ -2,7 +2,7 @@ import { execFile } from "node:child_process";
2
2
  import { readFile, realpath } from "node:fs/promises";
3
3
  import { resolve } from "node:path";
4
4
  import { promisify } from "node:util";
5
- import { CliError, devRequest, encode, query, readConfig, requireFlag } from "./core.js";
5
+ import { CliError, devRequest, encode, query, readConfig, requireFlag, hookLanePath, LIVE_LANE_STATUSES } from "./core.js";
6
6
  import { cachedGet, cachingRequest } from "./read-cache.js";
7
7
 
8
8
  const execFileAsync = promisify(execFile);
@@ -187,10 +187,14 @@ export async function storeGatherFreeze(
187
187
  return payload;
188
188
  }
189
189
 
190
- /** Find this agent's active lane from both the legacy worktree and Freeze boundaries. */
190
+ /**
191
+ * Find this agent's active lane from both the legacy worktree and Freeze boundaries.
192
+ * `hook: true` is for a hook that runs on every tool call (hub-528): it asks Dev
193
+ * for the slim lane and for this agent's live lanes only, and decides the same.
194
+ */
191
195
  export async function currentLane(
192
196
  { cwd = process.cwd() } = {},
193
- { request = devRequest, config = readConfig } = {},
197
+ { request = devRequest, config = readConfig, hook = false } = {},
194
198
  ) {
195
199
  let context;
196
200
  let agent;
@@ -219,14 +223,15 @@ export async function currentLane(
219
223
  })();
220
224
  if (markerKey) {
221
225
  try {
222
- const marked = (await request("GET", `/api/v1/lanes/${encode(markerKey)}`)).data;
226
+ const marked = (await request("GET", hook ? hookLanePath(markerKey) : `/api/v1/lanes/${encode(markerKey)}`)).data;
223
227
  if (marked.agentId === agent && !TERMINAL.has(marked.status) && await laneContains(marked, context)) return marked;
224
228
  } catch {}
225
229
  }
226
230
  const lanes = (
227
231
  await request(
228
232
  "GET",
229
- `/api/v1/lanes${query({ agent, limit: 200 })}`,
233
+ // Every status left out is one the filter below drops; it stays for a Dev that ignores `status`.
234
+ `/api/v1/lanes${query({ agent, ...(hook ? { status: LIVE_LANE_STATUSES.join(",") } : {}), limit: 200 })}`,
230
235
  )
231
236
  ).data ?? [];
232
237
  const candidates = lanes.filter((lane) => !TERMINAL.has(lane.status));
package/dist/hooks.js CHANGED
@@ -1,4 +1,4 @@
1
- import { CliError, devRequest } from "./core.js";
1
+ import { CliError, LIVE_LANE_STATUSES, devRequest, hookLanePath, query } from "./core.js";
2
2
  import { FOUNDATIONS_ID, figmaLockCheck, outOfScopeText } from "./figma.js";
3
3
  import { assertWithinLaneScope, currentLaneFigmaScope } from "./figma-scope.js";
4
4
  import { execFile } from "node:child_process";
@@ -125,7 +125,8 @@ export async function preHook(payload, request = devRequest, laneScope = current
125
125
  // A write outside the lane's Freeze Figma scope is refused before the lock check.
126
126
  let scope;
127
127
  try {
128
- scope = await laneScope({ cwd: payload.cwd ?? process.cwd() }, { request });
128
+ // This runs on every Figma write: the slim lane read (hub-528).
129
+ scope = await laneScope({ cwd: payload.cwd ?? process.cwd() }, { request, hook: true });
129
130
  } catch (error) {
130
131
  // A lane whose stored scope is invalid is refused, never left unbounded.
131
132
  if (error?.code === "FIGMA_SCOPE_INVALID") throw error;
@@ -224,6 +225,15 @@ export const settingsSnippet = () => {
224
225
  // the agent acted, which is what keeps `stuck` meaningful.
225
226
  export const HEARTBEAT_STAMP = "nodii-lane-heartbeat-at";
226
227
  export const HEARTBEAT_MIN_INTERVAL_MS = 60_000;
228
+ // hub-528: reading a lane costs hundreds of KB, so the hook keeps the lane it
229
+ // resolved in the worktree's git private dir, beside the marker and the stamp,
230
+ // and reads Dev again only when the branch or the lane key changes, when Dev
231
+ // says the lane is gone or ended, or when the kept answer is this old. "No lane
232
+ // here" is kept for a short time only, so a lane made later still starts beating.
233
+ export const HEARTBEAT_LANE_CACHE = "nodii-lane-heartbeat-lane.json";
234
+ export const HEARTBEAT_LANE_TTL_MS = 60 * 60_000;
235
+ export const HEARTBEAT_NO_LANE_TTL_MS = 5 * 60_000;
236
+ const LANE_ENDED = new Set(["LANE_NOT_FOUND", "LANE_TERMINAL"]);
227
237
  export const heartbeatSettingsSnippet = () => {
228
238
  const beat = [{ hooks: [{ type: "command", command: "nodii-dev hook lane-heartbeat" }] }];
229
239
  return { hooks: { PostToolUse: beat, Stop: beat } };
@@ -240,33 +250,69 @@ export async function heartbeatFromHook(payload, { request = devRequest, now = D
240
250
  // A stamp from the future (a clock change) must not silence the lane.
241
251
  if (at >= last && at - last < minIntervalMs) return { heartbeated: false, reason: "rate limited" };
242
252
  await writeFile(stamp, String(at));
243
- return heartbeatCurrentLane(request, { cwd, env });
253
+ return heartbeatCurrentLane(request, { cwd, env, now });
244
254
  }
245
255
 
246
- export async function heartbeatCurrentLane(request = devRequest, { cwd = process.cwd(), env = process.env } = {}) {
256
+ export async function heartbeatCurrentLane(request = devRequest, { cwd = process.cwd(), env = process.env, now = Date.now } = {}) {
247
257
  let branch;
248
258
  try { branch = (await execFileAsync("git", ["branch", "--show-current"], { cwd, encoding: "utf8" })).stdout.trim(); }
249
259
  catch { return { heartbeated: false, reason: "not a git worktree" }; }
250
260
  if (!branch) return { heartbeated: false, reason: "detached HEAD" };
261
+ const gitPath = async (name) => (await execFileAsync("git", ["rev-parse", "--path-format=absolute", "--git-path", name], { cwd, encoding: "utf8" })).stdout.trim();
262
+ const beat = (lane) => request("POST", `/api/v1/lanes/${encodeURIComponent(lane.id)}/heartbeat`, { via: "nodii-dev", source: "hook" });
263
+ const none = { heartbeated: false, reason: "no lane for current branch" };
264
+ const at = now();
265
+ // A launched run names its lane in NODII_DEV_LANE_KEY. Older worktrees have
266
+ // no marker, and the branch lookup below only sees the newest 200 lanes, so
267
+ // a lane older than that page would never beat without this (AGENT-HARNESS-86).
268
+ let laneKey = env.NODII_DEV_LANE_KEY ?? null;
269
+ let cachePath = null;
270
+ try {
271
+ const marker = await readFile(await gitPath("nodii-lane.json"), "utf8").then(JSON.parse).catch(() => null);
272
+ laneKey = marker?.laneKey ?? laneKey;
273
+ cachePath = await gitPath(HEARTBEAT_LANE_CACHE);
274
+ } catch {}
275
+ // A cache that cannot be written only costs the read it would have saved.
276
+ const keep = async (lane) => {
277
+ if (cachePath) await writeFile(cachePath, JSON.stringify({ branch, laneKey, lane: lane ? { id: lane.id, key: lane.key } : null, at })).catch(() => {});
278
+ };
279
+ const kept = cachePath ? await readFile(cachePath, "utf8").then(JSON.parse).catch(() => null) : null;
280
+ const usable = kept && kept.branch === branch && (kept.laneKey ?? null) === laneKey && (kept.lane === null || (kept.lane?.id && kept.lane?.key));
281
+ // An answer kept at a later time than now (a clock change) is read again.
282
+ if (usable && at >= kept.at && at - kept.at < (kept.lane ? HEARTBEAT_LANE_TTL_MS : HEARTBEAT_NO_LANE_TTL_MS)) {
283
+ if (!kept.lane) return none;
284
+ try {
285
+ await beat(kept.lane);
286
+ return { heartbeated: true, key: kept.lane.key };
287
+ } catch (error) {
288
+ // Any other failure (Dev unreachable, sign-in) says nothing about the lane: keep it.
289
+ if (!LANE_ENDED.has(error?.code)) throw error;
290
+ }
291
+ }
292
+ let unsure = false;
251
293
  try {
252
- const markerPath = (await execFileAsync("git", ["rev-parse", "--path-format=absolute", "--git-path", "nodii-lane.json"], { cwd, encoding: "utf8" })).stdout.trim();
253
- // A launched run names its lane in NODII_DEV_LANE_KEY. Older worktrees have
254
- // no marker, and the branch lookup below only sees the newest 200 lanes, so
255
- // a lane older than that page would never beat without this (AGENT-HARNESS-86).
256
- const marker = await readFile(markerPath, "utf8").then(JSON.parse).catch(() => null);
257
- const laneKey = marker?.laneKey ?? env.NODII_DEV_LANE_KEY;
258
294
  if (laneKey) {
259
- const lane = (await request("GET", `/api/v1/lanes/${encodeURIComponent(laneKey)}`)).data;
295
+ const lane = (await request("GET", hookLanePath(laneKey))).data;
260
296
  if (lane.repositories?.some((repository) => repository.branch === branch)) {
261
- await request("POST", `/api/v1/lanes/${encodeURIComponent(lane.id)}/heartbeat`, { via: "nodii-dev", source: "hook" });
297
+ await beat(lane);
298
+ await keep(lane);
262
299
  return { heartbeated: true, key: lane.key };
263
300
  }
264
301
  }
265
- } catch {}
266
- const lanes = (await request("GET", "/api/v1/lanes?limit=200")).data ?? [];
302
+ } catch (error) {
303
+ // The named lane could not be read or beaten for a reason that is not its
304
+ // end: "no lane" from the list below is then not an answer worth keeping.
305
+ unsure = !LANE_ENDED.has(error?.code);
306
+ }
307
+ // Only a live lane can be beaten (Dev refuses an ended one), so only live lanes are asked for.
308
+ const lanes = (await request("GET", `/api/v1/lanes${query({ status: LIVE_LANE_STATUSES.join(","), limit: 200 })}`)).data ?? [];
267
309
  const lane = lanes.find((x) => x.branch === branch && !["on_dev", "stopped"].includes(x.status));
268
- if (!lane) return { heartbeated: false, reason: "no lane for current branch" };
269
- await request("POST", `/api/v1/lanes/${encodeURIComponent(lane.id)}/heartbeat`, { via: "nodii-dev", source: "hook" });
310
+ if (!lane) {
311
+ if (!unsure) await keep(null);
312
+ return none;
313
+ }
314
+ await beat(lane);
315
+ await keep(lane);
270
316
  return { heartbeated: true, key: lane.key };
271
317
  }
272
318
 
@@ -0,0 +1,103 @@
1
+ // Can a lane runtime (`claude`, or `codex` for Codex accounts) be found from a
2
+ // clean environment, and not only from the current shell's PATH? (hub-527)
3
+ //
4
+ // A lane is launched by name (`claude`, `codex`), so it starts only where that
5
+ // name is an executable file on the PATH of whatever starts it. A shell that was
6
+ // given the runtime's directory by hand finds it. A down lane is resumed by
7
+ // coordinator watch, a service the manager starts, so what matters is the PATH
8
+ // that service has: the one its unit or plist carries (written when it was
9
+ // installed), or, where it is not installed, the manager's own PATH, which is
10
+ // what any service gets when no shell hands it one. doctor's lane_runtime line
11
+ // asks that question, and says which directory only the shell knows when they
12
+ // differ.
13
+ import { constants } from "node:fs";
14
+ import { access, lstat, readlink, stat } from "node:fs/promises";
15
+ import { homedir, platform } from "node:os";
16
+ import { dirname, isAbsolute, join } from "node:path";
17
+ import { watchServicePath } from "./coordinator-watch.js";
18
+ import { managerEnv } from "./systemd.js";
19
+
20
+ /** systemd's own PATH for a user service, when the manager cannot be asked. */
21
+ export const SYSTEMD_DEFAULT_PATH = "/usr/local/bin:/usr/bin:/bin";
22
+ /** launchd's PATH, plus the Homebrew directories coordinator watch's install adds to its job. */
23
+ export const LAUNCHD_PATH = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
24
+
25
+ /**
26
+ * The PATH a clean environment has: what the service that resumes lanes, started
27
+ * by the service manager, gets. That is the PATH coordinator watch's installed
28
+ * unit or plist carries; where it is not installed, the manager's own, which a
29
+ * service gets when no shell hands it one. Null where nodii-dev runs no service.
30
+ */
31
+ export async function cleanPath({ os = platform(), home = homedir(), execute } = {}) {
32
+ if (os !== "linux" && os !== "darwin") return null;
33
+ const service = await watchServicePath({ home, os, ...(execute ? { execute } : {}) });
34
+ if (service) return { path: service, source: os === "linux" ? "coordinator watch's unit PATH" : "coordinator watch's launchd PATH" };
35
+ if (os === "linux") {
36
+ const manager = (await managerEnv(execute ? { execute } : {})).PATH;
37
+ return manager ? { path: manager, source: "the systemd user manager's PATH" } : { path: SYSTEMD_DEFAULT_PATH, source: "systemd's default PATH" };
38
+ }
39
+ return { path: LAUNCHD_PATH, source: "launchd's PATH" };
40
+ }
41
+
42
+ /**
43
+ * Looks `command` up as a process start does: the first absolute directory
44
+ * whose entry of that name is an executable file (a link is followed). A link
45
+ * that points at nothing is skipped, as exec skips it, but remembered, because
46
+ * it is the usual reason a runtime that "is installed" is not found.
47
+ */
48
+ export async function resolveOnPath(command, pathString) {
49
+ const dangling = [];
50
+ for (const dir of String(pathString ?? "").split(":")) {
51
+ if (!dir || !isAbsolute(dir)) continue;
52
+ const candidate = join(dir, command);
53
+ try {
54
+ if (!(await stat(candidate)).isFile()) continue;
55
+ await access(candidate, constants.X_OK);
56
+ return { path: candidate, dangling };
57
+ } catch (error) {
58
+ if (error?.code !== "ENOENT") continue;
59
+ try { if ((await lstat(candidate)).isSymbolicLink()) dangling.push({ path: candidate, target: await readlink(candidate) }); } catch {}
60
+ }
61
+ }
62
+ return { path: null, dangling };
63
+ }
64
+
65
+ /**
66
+ * For each runtime: where a clean environment finds it and where the current
67
+ * shell does. `shellPath` is the PATH of the process that asks.
68
+ */
69
+ export async function laneRuntimeReport({ runtimes, shellPath = process.env.PATH, os = platform(), home = homedir(), execute } = {}) {
70
+ const clean = await cleanPath({ os, home, execute });
71
+ if (!clean) return { supported: false, rows: [] };
72
+ const rows = [];
73
+ for (const runtime of runtimes) rows.push({ runtime, clean: await resolveOnPath(runtime, clean.path), shell: await resolveOnPath(runtime, shellPath) });
74
+ return { supported: true, cleanPath: clean.path, cleanSource: clean.source, rows };
75
+ }
76
+
77
+ const tilde = (path, home) => (path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path);
78
+
79
+ /**
80
+ * One runtime's line for doctor: { ok, message, fix }. A runtime is found only
81
+ * when a clean environment finds it. `fix` names a directory on the clean PATH
82
+ * the user owns, so the fix works without sudo and a clean environment sees it.
83
+ */
84
+ export function describeRuntime(row, { cleanPath: clean, cleanSource, home = homedir() }) {
85
+ const { runtime } = row;
86
+ const t = (path) => tilde(path, home);
87
+ if (row.clean.path) return { ok: true, message: `${runtime} is found at ${t(row.clean.path)} in a clean environment (${cleanSource})` };
88
+ const ownDir = clean.split(":").find((dir) => isAbsolute(dir) && dir.startsWith(`${home}/`));
89
+ const link = ownDir ? `${t(ownDir)}/${runtime}` : null;
90
+ const dangling = row.clean.dangling.map((item) => `${t(item.path)} is a link to ${t(item.target)}, which does not exist`);
91
+ if (row.shell.path) {
92
+ return {
93
+ ok: false,
94
+ message: `${runtime} is found at ${t(row.shell.path)} only because this shell's PATH has ${t(dirname(row.shell.path))}; a clean environment (${cleanSource}) does not find it${dangling.length ? `: ${dangling.join("; ")}` : ""}`,
95
+ fix: link ? `ln -sf ${t(row.shell.path)} ${link}` : `link ${t(row.shell.path)} into a directory on ${cleanSource}`,
96
+ };
97
+ }
98
+ return {
99
+ ok: false,
100
+ message: `${runtime} is not found, neither in this shell's PATH nor in a clean environment (${cleanSource})${dangling.length ? `: ${dangling.join("; ")}` : ""}`,
101
+ fix: `${dangling.length ? "reinstall" : "install"} ${runtime} so that ${link ?? `a directory on ${cleanSource}`} is a real executable`,
102
+ };
103
+ }
package/dist/lanes.js CHANGED
@@ -1403,7 +1403,7 @@ export async function builtCommand(action, args, flags, { request = devRequest,
1403
1403
  const results = await Promise.all(args.map(async (ref) => {
1404
1404
  // STD-22: the acknowledgement is signed and linked to what contributed; it is never verification.
1405
1405
  const lane = (await request("GET", `/api/v1/lanes/${encode(ref)}`)).data;
1406
- const receipt = await signAck(ref, lane);
1406
+ const receipt = await signAck(ref, lane, { request });
1407
1407
  return request("POST", `/api/v1/built/${encode(ref)}/acknowledge`, { ...(flags.note !== undefined ? { note: flags.note } : {}), receipt, ...via });
1408
1408
  }));
1409
1409
  return { payload: args.length === 1 ? results[0] : { data: results.map((x) => x.data) }, human: `Acknowledged ${args.join(", ")}.` };
package/dist/nudges.js CHANGED
@@ -9,7 +9,7 @@ import { execFile } from "node:child_process";
9
9
  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
- import { devRequest, encode } from "./core.js";
12
+ import { devRequest, hookLanePath } from "./core.js";
13
13
  import { indexed, laneFigmaScope, loadDsFigmaIndex, squashName } from "./figma-scope.js";
14
14
  import { extractFileKey, extractNodeIds, isFigmaTool, isReadTool } from "./hooks.js";
15
15
  import { continueTaskMessage, doneCheckRecorded, laneBlocked } from "./lane-supervisor.js";
@@ -482,7 +482,7 @@ export function figmaGuidelineNudges(payload, knowledge, entries) {
482
482
 
483
483
  /** The lane's Figma scope, from its detail unless the lane at hand already carries its Freeze and launch record. */
484
484
  export async function laneScopeOf(lane, request = devRequest) {
485
- const detailed = "freeze" in lane && "launch" in lane ? lane : (await request("GET", `/api/v1/lanes/${encode(lane.key)}`)).data ?? lane;
485
+ const detailed = "freeze" in lane && "launch" in lane ? lane : (await request("GET", hookLanePath(lane.key))).data ?? lane;
486
486
  return laneFigmaScope(detailed);
487
487
  }
488
488
 
@@ -669,14 +669,17 @@ const stopBlockLimit = (env) => {
669
669
  /**
670
670
  * NODII-DEV-CLI-8 (hub-58, gate for AGENT-HARNESS-13): a lane session may not
671
671
  * stop before its done check is recorded unless the lane is BLOCKED. The
672
- * lane is read fresh; an unreadable lane lets the stop through (fail open).
672
+ * lane is read fresh: the lane this hook call just read from Dev by key
673
+ * (`context.laneDetail`), else one slim read here (hub-528). An unreadable
674
+ * lane lets the stop through (fail open).
673
675
  * Each session is held at most NODII_DEV_STOP_BLOCK_LIMIT times (5) in a row,
674
676
  * a cost backstop; the launch supervisor then continues it (NODII-DEV-CLI-9).
675
677
  */
676
678
  export async function doneCheckStopGate(payload, context, { request = devRequest, env = process.env, state = (update) => writePrivateJson(context.root, STOP_GATE, update) } = {}) {
677
679
  if (context?.role !== "lane" || !context.lane?.key) return null;
678
680
  let lane;
679
- try { lane = (await request("GET", `/api/v1/lanes/${encode(context.lane.key)}`)).data; } catch { return null; }
681
+ if (context.laneDetail === true) lane = context.lane;
682
+ else try { lane = (await request("GET", hookLanePath(context.lane.key))).data; } catch { return null; }
680
683
  const session = String(payload.session_id ?? "");
681
684
  const forget = (before) => { const sessions = { ...before.sessions }; delete sessions[session]; return { sessions }; };
682
685
  if (!lane || doneCheckRecorded(lane) || laneBlocked(lane)) {
@@ -1,8 +1,9 @@
1
1
  // The publish plan's compares, run in the lane's own session (MW1-57.11, hub-295).
2
2
  // The Figma MCP has no version history, so these reads go through REST, on the
3
3
  // token the lane was launched with. They're named in restReads. One failed read
4
- // never clears anything: a read that fails lists its nodes as changed, and a 429
5
- // stops the run, since it means stop reading.
4
+ // never clears anything: a read that fails lists its nodes as changed. A 429 is
5
+ // retried twice after Retry-After by the shared client (./figma-rest.js,
6
+ // cli-170); a third one stops the run.
6
7
  import { CliError, encode } from "./core.js";
7
8
  import { componentsToCompare, sameAuthored } from "./vendor/authored.mjs";
8
9