@nodii/dev 0.6.208 → 0.6.210

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.
@@ -250,7 +250,14 @@ export function assertKnownSets(surfaces, scopes) {
250
250
  export function laneFigmaScope(lane) {
251
251
  const stored = lane?.freeze?.boundaries?.figma;
252
252
  if (Array.isArray(stored))
253
- return stored.map((file) => ({ fileKey: file.fileKey, componentSets: file.componentSetKeys ?? [], ...(file.creates?.length ? { creates: file.creates } : {}) }));
253
+ return stored.map((file) => ({
254
+ fileKey: file.fileKey,
255
+ componentSets: file.componentSetKeys ?? [],
256
+ ...(file.creates?.length ? { creates: file.creates } : {}),
257
+ // hub-643: sections and pages the Freeze grants by node id.
258
+ ...(file.sectionIds?.length ? { sections: grantedNodeIds(lane, "sectionIds", file.sectionIds) } : {}),
259
+ ...(file.pageIds?.length ? { pages: grantedNodeIds(lane, "pageIds", file.pageIds) } : {}),
260
+ }));
254
261
  const launch = lane?.launch?.figmaScopes;
255
262
  if (!Array.isArray(launch) || !launch.length) return null;
256
263
  try {
@@ -263,6 +270,18 @@ export function laneFigmaScope(lane) {
263
270
  }
264
271
  }
265
272
 
273
+ /**
274
+ * A Freeze's granted section or page ids (hub-643): plain top-level
275
+ * node ids, as `--scope section:ID` takes them. Anything else is refused, never
276
+ * read as a wider grant.
277
+ */
278
+ function grantedNodeIds(lane, field, ids) {
279
+ const bad = ids.filter((id) => typeof id !== "string" || !/^\d+:\d+$/.test(id));
280
+ if (bad.length)
281
+ throw Object.assign(new CliError("FIGMA_SCOPE_INVALID", `Lane ${lane?.key ?? ""}'s Freeze grants ${field} that are not plain node ids (${bad.map((id) => JSON.stringify(id)).join(", ")}). Fix them with ${SWAP_BOUNDARIES(lane?.key)}.`, 1), { reason: `${field}: ${bad.join(", ")}` });
282
+ return [...ids];
283
+ }
284
+
266
285
  /** The DS components (guideline keys) and Surfaces a scope covers. */
267
286
  export function componentsForScope(surfaces, scope) {
268
287
  const keys = new Set(scope.flatMap((file) => file.componentSets));
@@ -286,7 +305,7 @@ export function guidelineLookup(components) {
286
305
  };
287
306
  }
288
307
 
289
- export const SWAP_BOUNDARIES = (key = "<key>") => `\`nodii-dev lane freeze swap ${key} --section boundaries --file BOUNDARIES.json --reason TEXT\` (the whole section: repos plus figma: [{fileKey, componentSetKeys, creates: [{pageId, name}]}]; start from \`nodii-dev lane freeze show ${key}\`)`;
308
+ export const SWAP_BOUNDARIES = (key = "<key>") => `\`nodii-dev lane freeze swap ${key} --section boundaries --file BOUNDARIES.json --reason TEXT\` (the whole section: repos plus figma: [{fileKey, componentSetKeys, creates: [{pageId, name}], sectionIds, pageIds}]; start from \`nodii-dev lane freeze show ${key}\`)`;
290
309
 
291
310
  /** A create's name as Dev compares it (sameCreateName in the hub's scopes.ts). */
292
311
  export const createName = (name) =>
@@ -365,16 +384,22 @@ export async function assertWithinLaneScope(scope, fileKey, lockScopes, { catalo
365
384
  if (!file)
366
385
  throw outside(`${fileKey} is outside this lane's Figma scope (${scope.length ? scope.map((item) => item.fileKey).join(", ") : "no Figma files"}).`, { fileKey, scope });
367
386
  const creates = file.creates ?? [];
368
- if (lockScopes === null || (!file.componentSets.length && !creates.length)) return { checked: true, fileKey };
387
+ const sections = file.sections ?? [];
388
+ const pages = file.pages ?? [];
389
+ if (lockScopes === null || (!file.componentSets.length && !creates.length && !sections.length && !pages.length)) return { checked: true, fileKey };
369
390
  // DS-254: a create the Freeze grants, on its page and under its name.
370
391
  // A name with no letters or digits names nothing, so it matches nothing.
371
392
  const granted = (item) => Boolean(item.pageId && createName(item.name ?? "")) && creates.some((create) => create.pageId === item.pageId && createName(create.name ?? "") === createName(item.name));
372
393
  const ungranted = lockScopes.filter((item) => item.kind === "create" && !granted(item));
373
394
  if (ungranted.length)
374
395
  throw outside(`${ungranted.map((item) => `create "${item.name}" on page ${item.pageId}`).join(", ")} in ${fileKey} is not a create this lane's Freeze grants (${creates.length ? creates.map((create) => `"${create.name}" on page ${create.pageId}`).join(", ") : "none"}).`, { fileKey, scope: file });
375
- const wide = lockScopes.length ? lockScopes.filter((item) => item.kind !== "component" && item.kind !== "create") : [{ kind: "file" }];
376
- if (wide.length)
377
- throw outside(`This lane may lock only its component sets${creates.length ? " and granted creates" : ""} in ${fileKey}, not ${wide.map((item) => item.kind).join(", ")}.`, { fileKey, scope: file });
396
+ // hub-643: a section or page the Freeze grants by id, exactly.
397
+ const grantedNode = (item) => (item.kind === "section" && sections.includes(item.nodeId)) || (item.kind === "page" && pages.includes(item.nodeId));
398
+ const wide = lockScopes.length ? lockScopes.filter((item) => item.kind !== "component" && item.kind !== "create" && !grantedNode(item)) : [{ kind: "file" }];
399
+ if (wide.length) {
400
+ const grants = [creates.length && "granted creates", sections.length && `granted sections (${sections.join(", ")})`, pages.length && `granted pages (${pages.join(", ")})`].filter(Boolean);
401
+ throw outside(`This lane may lock only its component sets${grants.length ? ` and ${grants.join(" and ")}` : ""} in ${fileKey}, not ${wide.map((item) => (item.nodeId ? `${item.kind} ${item.nodeId}` : item.kind)).join(", ")}.`, { fileKey, scope: file });
402
+ }
378
403
  lockScopes = lockScopes.filter((item) => item.kind === "component");
379
404
  if (!lockScopes.length) return { checked: true, fileKey };
380
405
  // Surfaces first; a DS set's key is looked up only when a node is still unaccounted for.
package/dist/flags.js CHANGED
@@ -16,9 +16,6 @@ export const COMMAND_FLAGS = {
16
16
  "figma transfer": ["to", "reason"],
17
17
  "coordinator start": ["machine", "account", "heartbeat-seconds"],
18
18
  "coordinator items": ["machine"],
19
- "lane ask": ["question", "options"],
20
- "lane asks": ["machine", "state", "lane", "cursor", "limit"],
21
- "lane answer": ["text"],
22
19
  // NODII-DEV-CLI-191: lane-to-lane messaging.
23
20
  "lane message": [...BODY, "issue"],
24
21
  "lane inbox": ["all"],
@@ -51,7 +48,10 @@ export const COMMAND_FLAGS = {
51
48
  "lane ready": ["withdraw", "reason"],
52
49
  "lane cap": ["confirm-raise", "reason"],
53
50
  "lane heartbeat": ["note", "waiting-on"],
54
- "lane waits": ["machine"],
51
+ "lane waits": ["machine", "person"],
52
+ // O3 items 9 and 12 (DEC-0569, MW1-115): --text and --scratch are the new flags.
53
+ "ruling file": ["text"],
54
+ "steward register": ["focus", "repos", "side", "key", "scratch"],
55
55
  "lane resume": ["override", "reason", "host-lost", "min-free-gb", "stagger-seconds", "profile", "class", "if-changed", "ungated"],
56
56
  "lane transfer": ["reason", "to-agent"],
57
57
  "inbox ack": ["note"],
@@ -69,6 +69,8 @@ export const COMMAND_FLAGS = {
69
69
  "operator step-up": ["revoke"],
70
70
  "lane land": [],
71
71
  "lane verify": ["dev-check", "checks"],
72
+ // O3 item 4: the weekly page takes only --json.
73
+ "harness week": [],
72
74
  "repo policy": ["root"],
73
75
  "test affected": ["base", "max-light", "run"],
74
76
  "repo lint": ["root"],
package/dist/harness.js CHANGED
@@ -573,10 +573,113 @@ export async function harnessCommand(action, flags, { request = devRequest, cont
573
573
  // current dispatcher (its lane-free nudges included), with no sudo.
574
574
  const refreshed = claudeBundle ? [] : await refreshManaged(managedHome ? { home: managedHome } : {}).catch(() => []);
575
575
  const refreshText = refreshed.length ? `\nRefreshed the managed hook dispatcher in ${refreshed.join(", ")}.` : "";
576
- const managedCliText = !managedCli ? ""
576
+ const managedCliText = (!managedCli ? ""
577
577
  : managedCli.error ? `\nwarning: the managed nodii-dev was not updated: ${managedCli.error}`
578
578
  : managedCli.current ? `\nThe managed nodii-dev is at the latest release, ${managedCli.version}.`
579
- : `\nInstalled the managed nodii-dev ${managedCli.version}${managedCli.previous ? ` over ${managedCli.previous}` : ""} at ${managedCli.cliPath}.`;
579
+ : `\nInstalled the managed nodii-dev ${managedCli.version}${managedCli.previous ? ` over ${managedCli.previous}` : ""} at ${managedCli.cliPath}.`)
580
+ + (managedCli?.movedFrom ? `\nMoved the managed nodii-dev from ${managedCli.movedFrom}, a prefix this user cannot write, to ${managedCli.cliPath}; no root was used. Put ${managedCli.cliPath.replace(/\/lib\/node_modules\/@nodii\/dev\/bin\/nodii-dev$/, "/bin")} first on PATH so \`command -v nodii-dev\` names it.` : "");
580
581
  const claudeData = claudePlan ? { claudeManagedDir: claudeBundle.dir, claudeManaged: { state: claudePlan.state, target: claudePlan.target, systemCommands: claudePlan.commands } } : {};
581
582
  return { payload: { data: { ...summary, applied: true, ...(systemCommands.length ? { systemCommands: [...systemCommands, ...(claudePlan?.commands ?? [])], managedDir: managedBundle.dir } : {}), ...claudeData, ...(refreshed.length ? { managedDispatchRefreshed: refreshed } : {}), ...(managedCli ? { managedCli } : {}) } }, human: `${lines.join("\n")}\n${machineOnly ? "No harness in this directory: refreshed this machine's managed hooks only, and wrote no repository files." : plan.changes.length ? `${action === "install" ? "Installed" : "Updated"}: ${plan.changes.length} change${plan.changes.length === 1 ? "" : "s"}.` : "Harness already current."}${systemText}${refreshText}${managedCliText}` };
582
583
  }
584
+
585
+ // ─── harness week (O3 item 4, MW5-8.1, DEC-0569) ────────────────────────────
586
+ // The weekly page for someone who does not build: Dev computes every number
587
+ // (GET /harness/week) and this prints them as plain text, in a fixed order, so
588
+ // the same answer always reads the same. --json prints Dev's payload.
589
+
590
+ export const WEEK_USAGE = "harness week [--json]";
591
+
592
+ /** 3d 4h, 2h 5m, 4m 10s, 9s. */
593
+ export function weekDuration(seconds) {
594
+ const s = Math.max(0, Math.round(Number(seconds) || 0));
595
+ const d = Math.floor(s / 86_400), h = Math.floor((s % 86_400) / 3600), m = Math.floor((s % 3600) / 60);
596
+ if (d) return `${d}d ${h}h`;
597
+ if (h) return `${h}h ${m}m`;
598
+ if (m) return `${m}m ${s % 60}s`;
599
+ return `${s}s`;
600
+ }
601
+
602
+ const dash = (value) => (value === null || value === undefined || value === "" ? "-" : String(value));
603
+ const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
604
+ const tokensText = (n) => (typeof n === "number" ? `${n} tokens` : "tokens not recorded");
605
+
606
+ /** Rows as columns padded to their widest cell; the last column is not padded. */
607
+ function columns(rows, indent = " ") {
608
+ const widths = rows[0]?.map((_, i) => Math.max(...rows.map((r) => String(r[i]).length))) ?? [];
609
+ return rows.map((r) => indent + r.map((cell, i) => (i === r.length - 1 ? String(cell) : String(cell).padEnd(widths[i]))).join(" ").trimEnd());
610
+ }
611
+
612
+ const meanText = (c) => (c?.n ? `${Math.round(((c.meanMs ?? c.ms / c.n) || 0) * 10) / 10} ms` : "-");
613
+ const costCell = (c) => `${c?.n ?? 0} calls, ${Math.round((c?.ms ?? 0) * 10) / 10} ms, mean ${meanText(c)}`;
614
+
615
+ export function renderWeek(week) {
616
+ const w = week ?? {};
617
+ const machineNames = new Map((w.versions?.machines ?? []).map((m) => [m.machineId, m.name]));
618
+ for (const m of w.runs?.perMachine ?? []) if (m.machineId && m.name) machineNames.set(m.machineId, m.name);
619
+ const machineName = (id) => (id ? machineNames.get(id) ?? id : "no machine");
620
+ const out = [`The week from ${dash(w.window?.since)} to ${dash(w.window?.until)}`];
621
+ const section = (title, lines) => out.push("", title, ...(lines.length ? lines : [" none"]));
622
+
623
+ section("Run-hours that pushed nothing, by how the run ended", columns((w.classes ?? []).map((c) =>
624
+ [c.class, count(c.runs, "run"), `${c.runHours} h`, tokensText(c.tokens)])));
625
+
626
+ const waits = w.waits;
627
+ section("Waits, as of now", waits ? [
628
+ ` unknown: ${count(waits.unknown.lanes, "lane")} waiting on ${count(waits.unknown.targets, "PR or release", "PRs or releases")} Dev traced to no lane`,
629
+ ` claimed: ${count(waits.claimed.lanes, "lane")} (on lanes ${waits.claimed.onLanes}, operator questions ${waits.claimed.operatorQuestions}, decisions ${waits.claimed.decisions}, launch day ${waits.claimed.launchDay}, roles ${waits.claimed.persons})`,
630
+ ] : []);
631
+
632
+ const r = w.refusals;
633
+ const top = (label, list, name = dash) => ` by ${label}: ${(list ?? []).length ? list.map((x) => `${name(x.key)} ${x.count}`).join(", ") : "none"}`;
634
+ section(`Refusals: ${r?.total ?? 0}`, r && r.total ? [top("code", r.byCode), top("route", r.byRoute), top("caller", r.byCaller), top("machine", r.byMachine, machineName)] : []);
635
+
636
+ section("Hours main was red, per repository", [
637
+ ...columns((w.red?.repos ?? []).map((x) => [x.repo, `${x.hoursRed} h`, x.redNow ? "red now" : ""])),
638
+ ...(w.red?.source ? [` (${w.red.source})`] : []),
639
+ ]);
640
+
641
+ section("Lanes by state, as of now", columns((w.states ?? []).map((s) => [s.state, s.count, `oldest ${weekDuration(s.oldestAgeSeconds)}`])));
642
+
643
+ const b = w.baselines;
644
+ const baselineRows = (list) => columns((list ?? []).map((x) => [x.repo, String(x.mergeBase).slice(0, 12), x.measuredAt,
645
+ `${count(x.counts?.files ?? 0, "file")}, ${x.counts?.red ?? 0} red${x.red?.length ? `: ${x.red.join(", ")}` : ""}`]));
646
+ section("Test baselines at main's merge base", !b ? [` ${w.baselinesReason ?? "not reported"}`] : [
647
+ ...baselineRows(b.repos),
648
+ ...(b.scratch?.length ? [" scratch (a local path, in no total):", ...baselineRows(b.scratch).map((l) => ` ${l}`)] : []),
649
+ ...(b.totals ? [` total: ${count(b.totals.baselines, "baseline")}, ${b.totals.withRed} with red, ${count(b.totals.redFiles, "red file")}`] : []),
650
+ ]);
651
+
652
+ const cost = w.callCost;
653
+ section("Dev calls per machine", !cost ? [` ${w.callCostReason ?? "not reported"}`] : [
654
+ ...columns([["machine", "since", "hook", "gather", "command"], ...(cost.machines ?? []).map((m) => [m.name, m.since, costCell(m.hook), costCell(m.gather), costCell(m.command)])]),
655
+ ...(cost.basis ? [` (${cost.basis})`] : []),
656
+ ]);
657
+
658
+ const v = w.versions ?? {};
659
+ section("CLI versions", [
660
+ ` target ${dash(v.target)}, floor ${dash(v.floor)}`,
661
+ ...columns((v.machines ?? []).map((m) => [m.name, m.cliVersion ?? "no version", m.needsRoot === true ? "needs root" : ""])),
662
+ ` needs root: ${(v.needRoot ?? []).length ? v.needRoot.join(", ") : "none"}`,
663
+ ]);
664
+
665
+ section("Runs per machine", columns((w.runs?.perMachine ?? []).map((m) => [m.name ?? machineName(m.machineId), count(m.runs, "run"), `${m.scratchRuns} scratch`])));
666
+
667
+ if (w.rulings) section("Rulings", [` filed: ${w.rulings.filed}`]);
668
+
669
+ const list = w.runs?.list ?? [];
670
+ section(`Runs (${list.length}${w.runs?.truncated ? ", more not shown" : ""})`, list.length ? columns([
671
+ ["lane", "step", "started because", "tokens", "duration", "ended", "machine"],
672
+ ...list.map((x) => [
673
+ `${x.laneKey ?? `(${x.kind})`}${x.scratch ? " [scratch]" : ""}`,
674
+ dash(x.facts?.step), dash(x.facts?.startReason), dash(x.facts?.tokens), weekDuration(x.durationSeconds),
675
+ `${x.endingClass ?? "running"}${x.pushed ? ", pushed" : ""}`, x.machineName ?? machineName(x.machineId),
676
+ ]),
677
+ ]) : []);
678
+ return out.join("\n");
679
+ }
680
+
681
+ export async function harnessWeekCommand(rest, flags, { request = devRequest } = {}) {
682
+ if (rest.length) throw new CliError("USAGE", `harness week takes no arguments, got: ${rest.join(" ")}. ${WEEK_USAGE}`, 2);
683
+ const payload = await request("GET", "/api/v1/harness/week");
684
+ return { payload, human: () => renderWeek(payload?.data) };
685
+ }
package/dist/impact.js CHANGED
@@ -15,11 +15,13 @@
15
15
  // package by name. A changed file the graph cannot place (a manifest, a
16
16
  // lockfile, a test or build config, or an unreferenced data file) selects the
17
17
  // full suite: the selection fails closed, never open.
18
- import { execFile, spawn } from "node:child_process";
19
- import { readFile } from "node:fs/promises";
20
- import { join, posix } from "node:path";
18
+ import { execFile, execFileSync, spawn } from "node:child_process";
19
+ import { rmSync } from "node:fs";
20
+ import { access, lstat, mkdtemp, readFile, readdir, realpath, rm, symlink, writeFile } from "node:fs/promises";
21
+ import { tmpdir } from "node:os";
22
+ import { basename, join, posix, sep } from "node:path";
21
23
  import { promisify } from "node:util";
22
- import { CliError } from "./core.js";
24
+ import { CliError, devRequest } from "./core.js";
23
25
  import { heavySlotArgv } from "./heavy.js";
24
26
 
25
27
  const execFileAsync = promisify(execFile);
@@ -414,7 +416,7 @@ export async function affected(cwd, { base = DEFAULT_BASE, maxLight = DEFAULT_MA
414
416
  const { tests, full } = selectTests(changed, { importers, files: fileSet, sources });
415
417
  const jobs = await planJobs({ tests, full, files: fileSet, read, fullScript });
416
418
  const size = full.length || jobs.some((job) => job.full) || tests.length > maxLight ? "heavy" : "light";
417
- return { root, base, mergeBase, changed, tests, full, jobs, size, maxLight };
419
+ return { root, base, mergeBase, changed, tests, full, jobs, size, maxLight, exec: execPrefix(fileSet) };
418
420
  }
419
421
 
420
422
  // ─── command ────────────────────────────────────────────────────────────────
@@ -430,20 +432,296 @@ const human = (result) => {
430
432
  }
431
433
  for (const job of result.jobs) out.push(`run${job.dir ? ` in ${job.dir}` : ""}: ${job.command}`);
432
434
  if (result.ran) for (const ran of result.ran) out.push(`${ran.code === 0 ? "passed" : `failed (exit ${ran.code})`}: ${ran.command}`);
435
+ const baseline = result.baseline;
436
+ if (baseline) {
437
+ const at = baseline.mergeBase;
438
+ if (baseline.redOnMain.length) out.push(`red on main at ${at}: ${baseline.redOnMain.join(", ")}`);
439
+ if (baseline.branchFailures.length) out.push(`fails on this branch, not at ${at}: ${baseline.branchFailures.join(", ")}`);
440
+ for (const note of baseline.notes) out.push(note);
441
+ }
433
442
  return out.join("\n");
434
443
  };
435
444
 
436
- /** One job through the heavy-slot queue at its size, output streamed. */
437
- export function runJob(job, { root, size, spawnImpl = spawn, argv = heavySlotArgv } = {}) {
445
+ /**
446
+ * One job through the heavy-slot queue at its size, output streamed. With
447
+ * CAPTURE the output is also kept, and the result is { code, output }, so the
448
+ * baseline can read which tests failed.
449
+ */
450
+ export function runJob(job, { root, size, capture = false, spawnImpl = spawn, argv = heavySlotArgv } = {}) {
438
451
  return new Promise((resolve) => {
439
452
  const [file, args] = argv(["--size", size, "--", "/bin/sh", "-c", job.command]);
440
- const child = spawnImpl(file, args, { cwd: job.dir ? join(root, job.dir) : root, stdio: ["ignore", "inherit", "inherit"] });
441
- child.on("error", () => resolve(127));
442
- child.on("close", (code, signal) => resolve(code ?? (signal ? 128 : 1)));
453
+ const child = spawnImpl(file, args, { cwd: job.dir ? join(root, job.dir) : root, stdio: ["ignore", capture ? "pipe" : "inherit", capture ? "pipe" : "inherit"] });
454
+ let output = "";
455
+ if (capture) for (const [stream, out] of [[child.stdout, process.stdout], [child.stderr, process.stderr]]) {
456
+ stream?.on("data", (chunk) => { output += chunk; out.write(chunk); });
457
+ }
458
+ const done = (code) => resolve(capture ? { code, output } : code);
459
+ child.on("error", () => done(127));
460
+ child.on("close", (code, signal) => done(code ?? (signal ? 128 : 1)));
443
461
  });
444
462
  }
445
463
 
446
- export async function testCommand(action, rest, flags = {}, { analyse = affected, run = runJob, readPolicy } = {}) {
464
+ // ─── baseline (MW2-21, CLI-158) ─────────────────────────────────────────────
465
+ // Main's reds are a baseline. When a job fails, each of its test files runs
466
+ // alone on the branch, and each that fails runs again at the merge base, in a
467
+ // temporary detached worktree. A file counts against main only when the branch
468
+ // did not change it, it fails there too, twice the same way, and every test
469
+ // that fails on the branch also fails there (by name, where the runner's output
470
+ // names them). Anything else is the branch's. The base never runs with the
471
+ // branch's code: dependencies that differ, or workspace links into the
472
+ // checkout, leave the file unmeasured. A confirmed base result is kept once per
473
+ // repository and merge base.
474
+
475
+ /** Where a repository keeps its baseline for MERGE_BASE: shared by every worktree of it. */
476
+ export async function baselinePath(root, mergeBase) {
477
+ const common = (await git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"])).trim();
478
+ return join(common, `nodii-baseline-${mergeBase}.json`);
479
+ }
480
+
481
+ async function readBaseline(path, mergeBase) {
482
+ try {
483
+ const saved = JSON.parse(await readFile(path, "utf8"));
484
+ if (saved?.mergeBase === mergeBase && saved.files && typeof saved.files === "object")
485
+ return { files: saved.files, failed: saved.failed && typeof saved.failed === "object" ? saved.failed : {} };
486
+ } catch { /* none yet, or unreadable: measured again */ }
487
+ return { files: {}, failed: {} };
488
+ }
489
+
490
+ const exists = (path) => access(path).then(() => true, () => false);
491
+
492
+ async function packageScript(tree, dir) {
493
+ try { return JSON.parse(await readFile(join(tree, dir, "package.json"), "utf8")).scripts?.test ?? null; } catch { return null; }
494
+ }
495
+
496
+ /**
497
+ * The tests a run's output names as failed: node --test's TAP (`not ok N - name`)
498
+ * or spec (`✖ name (1ms)`) lines, or bun test's `(fail) name`. Null when the
499
+ * output names none, so the file's exit code is all there is to go on.
500
+ */
501
+ export function failingTests(output) {
502
+ if (typeof output !== "string") return null;
503
+ const names = new Set();
504
+ for (const raw of output.split("\n")) {
505
+ const line = raw.replace(/\x1b\[[0-9;]*m/g, "").trimEnd();
506
+ const tap = /^\s*not ok \d+ - (.+?)(?:\s+#\s*(SKIP|TODO)\b.*)?$/i.exec(line);
507
+ if (tap) { if (!tap[2]) names.add(tap[1].trim()); continue; }
508
+ const spec = /^\s*✖ (.+?) \(\d+(?:\.\d+)?m?s\)$/.exec(line);
509
+ if (spec) { names.add(spec[1].trim()); continue; }
510
+ const bun = /^\s*\(fail\) (.+?)(?: \[\d+(?:\.\d+)?m?s\])?$/.exec(line);
511
+ if (bun) names.add(bun[1].trim());
512
+ }
513
+ return names.size ? [...names].sort() : null;
514
+ }
515
+
516
+ /** One file alone, in TREE: { code, failed } (failed: names, or null), or null when the package's script is not one runner call. */
517
+ async function runFile(tree, dir, file, { exec, run }) {
518
+ const script = await packageScript(tree, dir);
519
+ const command = runnerCommand(script, [file], { exec });
520
+ if (!command) return null;
521
+ const ran = await run({ dir, command, tests: [file], full: false }, { root: tree, size: "light", capture: true });
522
+ const code = typeof ran === "number" ? ran : ran?.code ?? 1;
523
+ return { code, failed: code === 0 ? [] : failingTests(typeof ran === "number" ? null : ran?.output) };
524
+ }
525
+
526
+ const LOCKFILES = new Set(["package-lock.json", "npm-shrinkwrap.json", "bun.lock", "bun.lockb", "yarn.lock", "pnpm-lock.yaml"]);
527
+
528
+ /** A link in NODE_MODULES (top level or one scope deep) that resolves inside ROOT: a workspace package, the branch's own code. */
529
+ async function workspaceLink(nodeModules, root) {
530
+ const inside = (target) => target === root || target.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
531
+ const real = await realpath(root).catch(() => root);
532
+ for (const name of await readdir(nodeModules).catch(() => [])) {
533
+ const entries = name.startsWith("@") ? (await readdir(join(nodeModules, name)).catch(() => [])).map((inner) => join(name, inner)) : [name];
534
+ for (const entry of entries) {
535
+ const path = join(nodeModules, entry);
536
+ if (!(await lstat(path).catch(() => null))?.isSymbolicLink()) continue;
537
+ const target = await realpath(path).catch(() => null);
538
+ if (target && (inside(target) || target === real || target.startsWith(`${real}${sep}`))) return entry;
539
+ }
540
+ }
541
+ return null;
542
+ }
543
+
544
+ /**
545
+ * Why the base cannot share the branch's installed dependencies, or null when
546
+ * it can (or there are none to share). A lockfile or package.json that differs
547
+ * from the merge base, or a workspace link into the checkout, would run the
548
+ * base with the branch's code.
549
+ */
550
+ export async function sharedDepsRefusal(root, dirs, changed) {
551
+ const installed = [];
552
+ for (const dir of new Set(["", ...dirs])) if (await exists(join(root, dir, "node_modules"))) installed.push(dir);
553
+ if (!installed.length) return null;
554
+ const manifest = changed.find((path) => LOCKFILES.has(posix.basename(path)) || posix.basename(path) === "package.json");
555
+ if (manifest) return `dependencies differ at the merge base (${manifest} changed)`;
556
+ for (const dir of installed) {
557
+ const link = await workspaceLink(join(root, dir, "node_modules"), root);
558
+ if (link) return `workspace links: ${posix.join(dir, "node_modules", link)} points into this checkout`;
559
+ }
560
+ return null;
561
+ }
562
+
563
+ /**
564
+ * A detached worktree at MERGE_BASE. It shares the branch's installed
565
+ * dependencies only when they are the base's too (sharedDepsRefusal); else it
566
+ * throws and nothing is measured. While it exists, SIGINT or SIGTERM removes it
567
+ * before the process ends; `dispose` removes it and restores the handlers.
568
+ */
569
+ async function baseWorktree(root, mergeBase, dirs, { changed = [] } = {}) {
570
+ const refusal = await sharedDepsRefusal(root, dirs, changed);
571
+ if (refusal) throw new Error(refusal);
572
+ // A worktree left by an interrupted run is pruned before another is added.
573
+ await git(root, ["worktree", "prune"]).catch(() => {});
574
+ const tree = await mkdtemp(join(tmpdir(), "nodii-baseline-"));
575
+ const removeNow = () => {
576
+ try { execFileSync("git", ["-C", root, "worktree", "remove", "--force", tree], { stdio: "ignore" }); } catch {}
577
+ try { rmSync(tree, { recursive: true, force: true }); } catch {}
578
+ };
579
+ const onSignal = (signal) => {
580
+ removeNow();
581
+ process.off("SIGINT", onSignal);
582
+ process.off("SIGTERM", onSignal);
583
+ // Nothing else listens: end as the signal would have.
584
+ if (!process.listenerCount(signal)) process.kill(process.pid, signal);
585
+ };
586
+ process.on("SIGINT", onSignal);
587
+ process.on("SIGTERM", onSignal);
588
+ const dispose = async () => {
589
+ process.off("SIGINT", onSignal);
590
+ process.off("SIGTERM", onSignal);
591
+ await git(root, ["worktree", "remove", "--force", tree]).catch(() => {});
592
+ await rm(tree, { recursive: true, force: true }).catch(() => {});
593
+ };
594
+ try {
595
+ await git(root, ["worktree", "add", "--detach", "--force", tree, mergeBase]);
596
+ for (const dir of new Set(["", ...dirs])) {
597
+ const installed = join(root, dir, "node_modules");
598
+ const target = join(tree, dir, "node_modules");
599
+ if ((await exists(installed)) && (await exists(join(tree, dir))) && !(await exists(target))) await symlink(installed, target, "dir").catch(() => {});
600
+ }
601
+ } catch (error) { await dispose(); throw error; }
602
+ return { tree, dispose };
603
+ }
604
+
605
+ const sameFailure = (a, b) => a.code === b.code && JSON.stringify(a.failed) === JSON.stringify(b.failed);
606
+
607
+ /**
608
+ * Split a failed JOB per file. Returns { redOnMain, branchFailures, notes },
609
+ * paths relative to the repository root. The base runs only for files the
610
+ * branch fails and did not change, and only those not measured before.
611
+ */
612
+ export async function baselineJob(result, job, { run = runJob, cache, worktree = baseWorktree } = {}) {
613
+ const notes = [];
614
+ const path = (file) => (job.dir ? `${job.dir}/${file}` : file);
615
+ if (job.full || !job.tests.length) {
616
+ notes.push(`no baseline for ${job.command}: a full-suite run is not split per file.`);
617
+ return { redOnMain: [], branchFailures: [], unsplit: true, notes };
618
+ }
619
+ const failing = [];
620
+ const onBranch = new Map();
621
+ for (const file of job.tests) {
622
+ const ran = await runFile(result.root, job.dir, file, { exec: result.exec, run });
623
+ if (ran === null) {
624
+ notes.push(`no baseline for ${job.command}: its test script is not one runner call.`);
625
+ return { redOnMain: [], branchFailures: [], unsplit: true, notes };
626
+ }
627
+ if (ran.code !== 0) { failing.push(file); onBranch.set(file, ran); }
628
+ }
629
+ if (!failing.length) {
630
+ notes.push(`${job.command} failed, but each of its files passes alone.`);
631
+ return { redOnMain: [], branchFailures: [], unsplit: true, notes };
632
+ }
633
+ const changed = new Set(result.changed);
634
+ const { files, failed } = await cache.read();
635
+ const flaky = new Set();
636
+ const toMeasure = failing.filter((file) => !changed.has(path(file)) && !(path(file) in files));
637
+ if (toMeasure.length) {
638
+ let base = null;
639
+ let measured = false;
640
+ try {
641
+ for (const file of toMeasure) {
642
+ // A file the base does not have passes nothing there.
643
+ try { await git(result.root, ["cat-file", "-e", `${result.mergeBase}:${path(file)}`]); }
644
+ catch { files[path(file)] = "absent"; measured = true; continue; }
645
+ base ??= await worktree(result.root, result.mergeBase, [job.dir], { changed: result.changed });
646
+ const first = await runFile(base.tree, job.dir, file, { exec: result.exec, run });
647
+ if (first === null) { files[path(file)] = "unrun"; measured = true; continue; }
648
+ if (first.code !== 0) {
649
+ // A base failure is kept only when a second run fails the same way.
650
+ const again = await runFile(base.tree, job.dir, file, { exec: result.exec, run });
651
+ if (!again || !sameFailure(first, again)) { flaky.add(path(file)); continue; }
652
+ }
653
+ files[path(file)] = first.code;
654
+ failed[path(file)] = first.failed;
655
+ measured = true;
656
+ }
657
+ } finally {
658
+ await base?.dispose();
659
+ }
660
+ if (measured) await cache.write({ files, failed });
661
+ }
662
+ const redOnMain = [], branchFailures = [];
663
+ for (const file of failing) {
664
+ const key = path(file);
665
+ const atBase = files[key];
666
+ if (flaky.has(key)) {
667
+ notes.push(`flaky at ${result.mergeBase.slice(0, 12)}: ${key} failed there, then not the same way again; it is not counted as main's.`);
668
+ branchFailures.push(key);
669
+ continue;
670
+ }
671
+ if (changed.has(key) || typeof atBase !== "number" || atBase === 0) { branchFailures.push(key); continue; }
672
+ const branchNames = onBranch.get(file).failed;
673
+ const baseNames = failed[key];
674
+ if (Array.isArray(branchNames) && Array.isArray(baseNames) && baseNames.length) {
675
+ const atMain = new Set(baseNames);
676
+ const added = branchNames.filter((name) => !atMain.has(name));
677
+ if (added.length) {
678
+ notes.push(`${key} also fails on main, but not these tests, which fail only on this branch: ${added.join("; ")}`);
679
+ branchFailures.push(key);
680
+ } else redOnMain.push(key);
681
+ continue;
682
+ }
683
+ notes.push(`${key}: the runner's output named no failing tests, so it is judged by the file's exit code alone.`);
684
+ redOnMain.push(key);
685
+ }
686
+ return { redOnMain, branchFailures, notes };
687
+ }
688
+
689
+ /** The repository a baseline names: origin as owner/name when it is on GitHub, else the checkout's folder name (never a path). */
690
+ export function baselineRepo(root, originUrl) {
691
+ const match = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(String(originUrl ?? "").trim());
692
+ return match ? `${match[1]}/${match[2]}` : basename(root);
693
+ }
694
+
695
+ /**
696
+ * O3 item 4 (DEC-0569): Dev keeps each newly measured baseline for the weekly
697
+ * page, POST /harness/baselines. Best effort: a failed post never changes the
698
+ * test result.
699
+ */
700
+ export async function postBaseline({ root, mergeBase, files, measuredAt }, { request = devRequest } = {}) {
701
+ try {
702
+ const origin = await git(root, ["remote", "get-url", "origin"]).catch(() => "");
703
+ await request("POST", "/api/v1/harness/baselines", { repo: baselineRepo(root, origin), mergeBase, files, measuredAt });
704
+ return true;
705
+ } catch {
706
+ return false;
707
+ }
708
+ }
709
+
710
+ function baselineCache(path, mergeBase, { root, post = postBaseline, now = () => new Date() } = {}) {
711
+ let kept = null;
712
+ return {
713
+ read: async () => (kept ??= await readBaseline(path, mergeBase)),
714
+ // Written only when something was newly measured, so Dev hears of each measurement once.
715
+ // Dev keeps the exit codes; the failing test names stay on this machine.
716
+ write: async (next) => {
717
+ kept = next;
718
+ await writeFile(path, `${JSON.stringify({ mergeBase, files: next.files, failed: next.failed }, null, 2)}\n`);
719
+ await Promise.resolve().then(() => post({ root, mergeBase, files: next.files, measuredAt: now().toISOString() })).catch(() => {});
720
+ },
721
+ };
722
+ }
723
+
724
+ export async function testCommand(action, rest, flags = {}, { analyse = affected, run = runJob, readPolicy, cachePath = baselinePath, post = postBaseline } = {}) {
447
725
  if (action !== "affected") throw new CliError("USAGE", TEST_USAGE, 2);
448
726
  if (rest.length) throw new CliError("USAGE", `test affected takes no arguments, got: ${rest.join(" ")}. ${TEST_USAGE}`, 2);
449
727
  const base = flags.base && flags.base !== true ? String(flags.base) : DEFAULT_BASE;
@@ -459,10 +737,24 @@ export async function testCommand(action, rest, flags = {}, { analyse = affected
459
737
  const result = await analyse(process.cwd(), { base, maxLight, fullScript });
460
738
  if (flags.run) {
461
739
  result.ran = [];
740
+ let cache = null;
462
741
  for (const job of result.jobs) {
463
742
  const code = await run(job, { root: result.root, size: result.size });
464
743
  result.ran.push({ dir: job.dir, command: job.command, code });
465
- if (code !== 0) return { payload: result, human, exitCode: code };
744
+ if (code === 0) continue;
745
+ let found;
746
+ try {
747
+ cache ??= baselineCache(await cachePath(result.root, result.mergeBase), result.mergeBase, { root: result.root, post });
748
+ found = await baselineJob(result, job, { run, cache });
749
+ } catch (error) {
750
+ found = { redOnMain: [], branchFailures: [], unsplit: true, notes: [`no baseline for ${job.command}: ${error.message}`] };
751
+ }
752
+ result.baseline ??= { mergeBase: result.mergeBase, redOnMain: [], branchFailures: [], notes: [] };
753
+ result.baseline.redOnMain.push(...found.redOnMain);
754
+ result.baseline.branchFailures.push(...found.branchFailures);
755
+ result.baseline.notes.push(...found.notes);
756
+ // Only what the change adds fails: a job whose every failing file is red on main passes.
757
+ if (found.unsplit || found.branchFailures.length) return { payload: result, human, exitCode: code };
466
758
  }
467
759
  }
468
760
  return { payload: result, human, exitCode: 0 };