@nodii/dev 0.6.171 → 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.
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
2
+ import { mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
4
  import { configPath } from "./core.js";
5
5
 
@@ -12,6 +12,15 @@ import { configPath } from "./core.js";
12
12
  // the lane or asks for an acknowledgement is always read fresh.
13
13
  export const READ_CACHE_TTL_MS = 15_000;
14
14
  const PRUNE_AFTER_MS = 60 * 60_000;
15
+ // A miss is single-flight across processes: the calls in flight at an expiry
16
+ // all missed together, so nodii-dev twice a second read the Freeze twice per
17
+ // 15 seconds. One process takes the path's lock and reads Dev; the others wait
18
+ // for its answer, up to WAIT_MS, then read Dev themselves. A lock older than
19
+ // LOCK_STALE_MS belongs to a process that died and is taken over.
20
+ const LOCK_STALE_MS = 10_000;
21
+ const WAIT_MS = 3_000;
22
+ const POLL_MS = 50;
23
+ const pause = (ms) => new Promise((done) => setTimeout(done, ms));
15
24
 
16
25
  const defaultDir = () => join(dirname(configPath()), "read-cache");
17
26
 
@@ -43,6 +52,36 @@ export function laneReadCache({ dir = defaultDir(), ttlMs = READ_CACHE_TTL_MS, n
43
52
  if (Math.random() < 0.05) await prune(dir, now());
44
53
  } catch {}
45
54
  },
55
+ /** Take the path's lock: a release function, or null while another live process holds it. */
56
+ async lock(path) {
57
+ const target = `${file(path)}.lock`;
58
+ for (let attempt = 0; attempt < 2; attempt += 1) {
59
+ try {
60
+ await mkdir(dir, { recursive: true, mode: 0o700 });
61
+ const handle = await open(target, "wx", 0o600);
62
+ await handle.writeFile(String(now()));
63
+ await handle.close();
64
+ return () => rm(target, { force: true }).catch(() => {});
65
+ } catch (error) {
66
+ if (error?.code !== "EEXIST") return () => {};
67
+ let at = Number.NaN;
68
+ try {
69
+ at = Number(await readFile(target, "utf8"));
70
+ } catch {}
71
+ if (now() - at < LOCK_STALE_MS) return null;
72
+ await rm(target, { force: true }).catch(() => {});
73
+ }
74
+ }
75
+ return null;
76
+ },
77
+ async locked(path) {
78
+ try {
79
+ await stat(`${file(path)}.lock`);
80
+ return true;
81
+ } catch {
82
+ return false;
83
+ }
84
+ },
46
85
  async drop(path) {
47
86
  try {
48
87
  await rm(file(path), { force: true });
@@ -65,9 +104,22 @@ export async function cachedGet(cache, request, path, keep = () => true) {
65
104
  if (!cache) return request("GET", path);
66
105
  const hit = await cache.get(path);
67
106
  if (hit !== undefined) return hit;
68
- const answer = await request("GET", path);
69
- if (keep(answer)) await cache.set(path, answer);
70
- return answer;
107
+ const release = cache.lock ? await cache.lock(path) : () => {};
108
+ if (!release) {
109
+ // Another process is reading Dev: wait for its answer. If it is not kept
110
+ // (it blocks or asks for an acknowledgement), the lock goes and we read Dev.
111
+ for (let waited = 0; waited < WAIT_MS && (await cache.locked(path)); waited += POLL_MS) await pause(POLL_MS);
112
+ const shared = await cache.get(path);
113
+ if (shared !== undefined) return shared;
114
+ return request("GET", path);
115
+ }
116
+ try {
117
+ const answer = await request("GET", path);
118
+ if (keep(answer)) await cache.set(path, answer);
119
+ return answer;
120
+ } finally {
121
+ await release();
122
+ }
71
123
  }
72
124
 
73
125
  /** A request function whose GETs go through the cache; every other method goes to Dev. */
package/dist/receipt.js CHANGED
@@ -10,7 +10,7 @@ import { link, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/p
10
10
  import { homedir, hostname } from "node:os";
11
11
  import { basename, dirname, join } from "node:path";
12
12
  import { promisify } from "node:util";
13
- import { CliError, devRequest, encode, readConfig } from "./core.js";
13
+ import { CliError, devRequest, encode, readConfig, query } from "./core.js";
14
14
  import { runGate } from "./review.js";
15
15
  import { gitPrivatePath } from "./safety.js";
16
16
 
@@ -202,9 +202,44 @@ export async function writeReceipt(flags, { cwd = process.cwd(), run = runGate,
202
202
  return { receipt, path: out, failed };
203
203
  }
204
204
 
205
+ const EVIDENCE_PAGE = 500;
206
+
207
+ /**
208
+ * Every evidence event of a lane, oldest first (hub-528). Dev's lane read
209
+ * carries only the lane's newest events and says so with a non-null
210
+ * `events_next_cursor`; the rest is paged from the lane's events route. A lane
211
+ * carried whole, and a Dev from before paging (no `events_next_cursor` key),
212
+ * are read from the lane as given. A list that can't be read in full is an
213
+ * error, never a shorter list: what is signed must not leave a change out.
214
+ */
215
+ export async function laneEvidenceEvents(ref, lane, { request = devRequest } = {}) {
216
+ if (lane?.events_next_cursor === undefined || lane.events_next_cursor === null)
217
+ return (lane?.events ?? []).filter((event) => event.type === "evidence");
218
+ const incomplete = (why) => new CliError("BUILT_ACK_EVIDENCE_INCOMPLETE", `${ref}: the lane's evidence could not be read in full from Dev (${why}), so nothing was signed or acknowledged. Run it again.`, 1);
219
+ const newestFirst = [];
220
+ const cursors = new Set();
221
+ let cursor;
222
+ let total = null;
223
+ do {
224
+ let page;
225
+ try { page = await request("GET", `/api/v1/lanes/${encode(lane.id ?? ref)}/events${query({ type: "evidence", limit: EVIDENCE_PAGE, cursor })}`); }
226
+ catch (error) { throw incomplete(`${error?.code ?? "ERROR"}: ${error?.message ?? error}`); }
227
+ const next = page?.meta?.next_cursor;
228
+ if (!Array.isArray(page?.data) || !(next === null || (typeof next === "string" && next))) throw incomplete("Dev's answer is not a page of events");
229
+ if (next !== null && cursors.has(next)) throw incomplete("Dev repeated a page");
230
+ // Counted on the first page: an event recorded while paging is newer than every later page.
231
+ if (total === null && Number.isInteger(page.meta.total)) total = page.meta.total;
232
+ newestFirst.push(...page.data);
233
+ cursor = next ?? undefined;
234
+ if (cursor) cursors.add(cursor);
235
+ } while (cursor);
236
+ if (total !== null && newestFirst.length < total) throw incomplete(`Dev counts ${total} evidence events and listed ${newestFirst.length}`);
237
+ return newestFirst.filter((event) => event?.type === "evidence").reverse();
238
+ }
239
+
205
240
  /** STD-22: what the operator acknowledged, linked to every change and release that contributed. */
206
- export async function signedBuiltAck(ref, lane, { keyPath = receiptKeyPath(), config = readConfig, now = ranAt } = {}) {
207
- const contributing = (lane.events ?? []).filter((event) => event.type === "evidence" && ["pr", "commit", "deploy"].includes(event.metadata?.kind));
241
+ export async function signedBuiltAck(ref, lane, { keyPath = receiptKeyPath(), config = readConfig, now = ranAt, request = devRequest } = {}) {
242
+ const contributing = (await laneEvidenceEvents(ref, lane, { request })).filter((event) => ["pr", "commit", "deploy"].includes(event.metadata?.kind));
208
243
  const at = now();
209
244
  const c = await config().catch(() => ({}));
210
245
  const commit = lane.mergeCommit ?? contributing.findLast((item) => item.metadata.kind === "commit")?.metadata.ref;
package/dist/safety.js CHANGED
@@ -4,12 +4,12 @@ import { appendFile, mkdir, readFile, realpath, writeFile } from "node:fs/promis
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
6
  import { promisify } from "node:util";
7
- import { CliError, LANE_CAP_RAISE_PROMPT, configPath, devRequest, encode, readConfig } from "./core.js";
7
+ import { CliError, LANE_CAP_RAISE_PROMPT, LIVE_LANE_STATUSES, configPath, devRequest, encode, hookLanePath, query, readConfig } from "./core.js";
8
8
  import { laneCapReminder } from "./watchdog.js";
9
9
  import { heavyViolation } from "./heavy.js";
10
10
 
11
11
  const execFileAsync = promisify(execFile);
12
- const ACTIVE = new Set(["queued", "building", "built", "review", "on_main"]);
12
+ const ACTIVE = new Set(LIVE_LANE_STATUSES);
13
13
  const SHELL_TOOLS = new Set(["Bash", "shell", "exec_command"]);
14
14
  const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit", "apply_patch"]);
15
15
  const GENERATED_MARK = /(?:do not edit|auto-?generated|generated (?:file|code)|@generated)/i;
@@ -751,17 +751,25 @@ async function currentLane(cwd, request, config) {
751
751
  const rootText = await git(cwd, "rev-parse", "--show-toplevel");
752
752
  const root = await realpath(rootText).catch(() => resolve(rootText));
753
753
  const markerText = await optional(await gitPrivatePath(cwd, "nodii-lane.json"));
754
+ // hub-528: every read here is made on every tool call, so each asks Dev for
755
+ // as little as decides the same thing. `detail` says the lane was read by key
756
+ // in this call, so nothing reads it again.
757
+ let marked = null;
754
758
  if (markerText) {
755
759
  const marker = JSON.parse(markerText);
756
- const lane = (await request("GET", `/api/v1/lanes/${encode(marker.laneKey)}`)).data;
757
- const repository = lane.repositories?.find((item) => item.branch === branch && resolve(item.worktree) === root);
758
- if (lane.agentId === config.agentId && repository && ACTIVE.has(lane.status)) return lane;
760
+ marked = (await request("GET", hookLanePath(marker.laneKey))).data;
761
+ const repository = marked.repositories?.find((item) => item.branch === branch && resolve(item.worktree) === root);
762
+ if (marked.agentId === config.agentId && repository && ACTIVE.has(marked.status)) return { lane: marked, detail: true };
759
763
  }
760
- const lanes = (await request("GET", "/api/v1/lanes?limit=200")).data ?? [];
764
+ // Only this agent's live lanes can match below, so only those are asked for.
765
+ // The checks stay: a Dev that ignores a filter still lists every lane.
766
+ const lanes = (await request("GET", `/api/v1/lanes${query({ agent: config.agentId, status: LIVE_LANE_STATUSES.join(","), limit: 200 })}`)).data ?? [];
761
767
  for (const lane of lanes) {
762
768
  if (lane.agentId !== config.agentId || lane.branch !== branch || !ACTIVE.has(lane.status)) continue;
763
769
  const worktree = await realpath(lane.worktree ?? root).catch(() => resolve(lane.worktree ?? root));
764
- if (worktree === root) return lane;
770
+ if (worktree !== root) continue;
771
+ // The marker's read was this lane's detail: use it, never read it twice.
772
+ return marked && !Array.isArray(marked) && marked.key === lane.key ? { lane: { ...lane, ...marked }, detail: true } : { lane, detail: false };
765
773
  }
766
774
  return null;
767
775
  }
@@ -784,14 +792,23 @@ export async function safetyContext(cwd = process.cwd(), { request = devRequest,
784
792
  try { role = (await request("GET", `/api/v1/agents/${encode(config.agentId)}`)).data?.role ?? role; } catch {}
785
793
  }
786
794
  let lane = null;
787
- try { lane = await currentLane(cwd, request, config); } catch {}
795
+ let laneDetail = false;
796
+ try {
797
+ const found = await currentLane(cwd, request, config);
798
+ if (found) ({ lane, detail: laneDetail } = found);
799
+ } catch {}
788
800
  let reviewFlowKnown = false;
789
801
  if (lane) {
790
802
  if (Array.isArray(lane.reviews)) reviewFlowKnown = true;
791
- else try {
792
- const detailed = (await request("GET", `/api/v1/lanes/${encode(lane.key)}`)).data;
803
+ // A list row is read by key once. A lane already read by key that has no
804
+ // reviews comes from a Dev without the review flow; asking again says the same.
805
+ else if (!laneDetail) try {
806
+ const detailed = (await request("GET", hookLanePath(lane.key))).data;
793
807
  reviewFlowKnown = Array.isArray(detailed?.reviews);
794
- if (detailed && !Array.isArray(detailed)) lane = { ...lane, ...detailed };
808
+ if (detailed && !Array.isArray(detailed)) {
809
+ lane = { ...lane, ...detailed };
810
+ laneDetail = true;
811
+ }
795
812
  } catch {}
796
813
  }
797
814
  const receiptPath = await gitPrivatePath(cwd, REVIEW_RECEIPT);
@@ -807,6 +824,8 @@ export async function safetyContext(cwd = process.cwd(), { request = devRequest,
807
824
  const loadLaneRoots = lane ? async () => (laneRoots ??= await laneWorktrees(lane, { request, root })) : null;
808
825
  return {
809
826
  cwd: await realpath(cwd).catch(() => payloadCwd(cwd)), root, branch, head, base, role, lane, provenLane: Boolean(lane), reviewFlowKnown,
827
+ // True when `lane` was read from Dev by key during this call (the Stop gate then reads nothing more).
828
+ laneDetail,
810
829
  ownedPaths: ownership.paths,
811
830
  ownershipKnown: role === "coordinator" || ownership.known,
812
831
  generatedPaths: [...await harnessGenerated(root), ...(state.generatedPaths ?? [])],
package/dist/starting.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { execFile as execFileCallback } from "node:child_process";
2
- import { mkdir, readFile, rmdir, writeFile } from "node:fs/promises";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
3
  import { setTimeout as delay } from "node:timers/promises";
4
4
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { CliError, configPath, devRequest, encode, query, readConfig, requireFlag } from "./core.js";
7
+ import { figmaRest } from "./figma-rest.js";
7
8
  import { assertKnownSets, checkComponentSetKey, checkFileKey, loadDsCatalog, mergeScopes, scopesFromRoutes } from "./figma-scope.js";
8
9
  import { GATHER_TIMEOUT_MS, gatherDeadline } from "./gather.js";
9
10
  import { laneCommand, nextCommand } from "./lanes.js";
@@ -501,58 +502,27 @@ async function defaultLaunchRuntime(options) {
501
502
  return module.launchRuntime(options);
502
503
  }
503
504
 
504
- export async function verifyFigmaSeat({ env = process.env, fetchImpl = fetch, rateLimit = figmaRateLimit } = {}) {
505
+ /**
506
+ * The `--figma` seat preflight: one `GET /v1/me` on the assigned token, through
507
+ * the shared Figma REST client (MW1-57.13; ./figma-rest.js), so it waits in the
508
+ * machine's queue for that token and a 429 is retried like any other call's.
509
+ * `client` passes options to that client.
510
+ */
511
+ export async function verifyFigmaSeat({ env = process.env, fetchImpl = fetch, client = {} } = {}) {
505
512
  const token = env.FIGMA_PAT || env.FIGMA_TOKEN;
506
513
  if (!token) throw new CliError("FIGMA_TOKEN_REQUIRED", "--figma preflight needs FIGMA_PAT for the assigned Figma account.", 2);
507
- let response;
514
+ let account;
508
515
  try {
509
- response = await rateLimit(() => fetchImpl("https://api.figma.com/v1/me", {
510
- headers: { "X-Figma-Token": token },
511
- signal: AbortSignal.timeout(10_000),
512
- }));
516
+ account = await figmaRest(token, { fetchImpl, attempts: 1, timeoutMs: 10_000, cache: null, ...client })("/me");
513
517
  } catch (error) {
514
- throw new CliError("FIGMA_SEAT_UNAVAILABLE", `Figma seat preflight could not complete: ${error.message}`, 1);
518
+ // A token that is rate limited is not a missing seat: the caller stops its reads on it (MW1-57.13).
519
+ if (error?.code === "FIGMA_RATE_LIMITED") throw error;
520
+ throw new CliError("FIGMA_SEAT_UNAVAILABLE", error?.details?.status ? `Figma seat preflight returned HTTP ${error.details.status}.` : `Figma seat preflight could not complete: ${error.message}`, 1);
515
521
  }
516
- if (!response.ok) throw new CliError("FIGMA_SEAT_UNAVAILABLE", `Figma seat preflight returned HTTP ${response.status}.`, 1);
517
- const account = await response.json();
518
522
  if (!account?.id) throw new CliError("FIGMA_SEAT_UNAVAILABLE", "Figma did not identify the assigned account.", 1);
519
523
  return true;
520
524
  }
521
525
 
522
- /** Serialize the machine's shared Figma token and keep call starts 10s apart. */
523
- export async function figmaRateLimit(task, {
524
- root = basename(dirname(configPath())) === "agents" ? dirname(dirname(configPath())) : dirname(configPath()),
525
- sleep = delay,
526
- now = Date.now,
527
- fs = { mkdir, readFile, rmdir, writeFile },
528
- } = {}) {
529
- const lock = join(root, "figma-rest.lock");
530
- const stamp = join(root, "figma-rest-last-call");
531
- await fs.mkdir(root, { recursive: true, mode: 0o700 });
532
- const deadline = now() + 30_000;
533
- for (;;) {
534
- try {
535
- await fs.mkdir(lock, { mode: 0o700 });
536
- break;
537
- } catch (error) {
538
- if (error?.code !== "EEXIST") throw error;
539
- if (now() >= deadline) throw new CliError("FIGMA_RATE_LOCKED", "Another Figma REST call has held the machine lock for 30 seconds.", 1);
540
- await sleep(100);
541
- }
542
- }
543
- try {
544
- let previous = 0;
545
- try { previous = Number(await fs.readFile(stamp, "utf8")) || 0; }
546
- catch (error) { if (error?.code !== "ENOENT") throw error; }
547
- const wait = Math.max(0, 10_000 - (now() - previous));
548
- if (wait) await sleep(wait);
549
- await fs.writeFile(stamp, `${now()}\n`, { mode: 0o600 });
550
- return await task();
551
- } finally {
552
- await fs.rmdir(lock);
553
- }
554
- }
555
-
556
526
  async function refreshAccountUsage(machineId, runtime, profile, { request }) {
557
527
  const accounts = (await listAccounts(machineId, { request })).filter((a) => a.runtime === runtime && a.profile === profile);
558
528
  // A launch is about to spend this account anyway, so an opted-in Codex