@nodii/dev 0.6.208 → 0.6.209

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.
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 };
package/dist/lane-asks.js CHANGED
@@ -1,33 +1,26 @@
1
- import { CliError, devRequest, encode, query, requireFlag } from "./core.js";
1
+ import { CliError, devRequest, encode, requireFlag } from "./core.js";
2
2
 
3
3
  /**
4
- * hub-525 (MW1-12.9, MW1-37.2): a lane's questions to its machine
5
- * coordinator. The answer is delivered as an amendment the lane acknowledges
6
- * with a Delta gather; an issue comment alone is not delivery.
4
+ * hub-525 (MW1-37.2): the coordinator puts a leeway off.
7
5
  *
8
- * lane ask <key> --question TEXT [--options a,b]
9
- * lane ask withdraw <ask id>
10
- * lane answer <ask id> --text TEXT
11
- * lane defer <ask or leeway id> --reason TEXT [--minutes N] [--leeway]
12
- * lane asks [--machine M] [--state S] [--lane KEY] [--cursor C] [--limit N]
6
+ * lane defer <leeway id> --reason TEXT [--minutes N]
7
+ *
8
+ * DEV-PROCESS-5, row 29b (one in, one out): the lane-ask family (`lane ask`,
9
+ * `lane ask withdraw`, `lane answer`, `lane asks`, the NODII_DEV_LANE_ASKS
10
+ * switch) is retired. It shipped off by default since 18 Nov (MW1-37.2) and is
11
+ * replaced by role waits. Typing one is refused USAGE with what replaced it.
13
12
  */
14
13
 
15
- /**
16
- * MW1-37.2 (DEC-0503): lane asks ship off by default; NODII_DEV_LANE_ASKS=1
17
- * turns them on. Dev's rulebook holds no clause yet for a lane's question and
18
- * its answer. Off, no command here calls Dev's lane-ask routes (Dev's answer
19
- * route, which delivers the amendment, is then unreachable from the CLI), and
20
- * the coordinator's count, list and gate leave questions out: a question
21
- * cannot be cleared without the answer route.
22
- */
23
- export const laneAsksOn = (env = process.env) => env?.NODII_DEV_LANE_ASKS === "1";
24
- const assertAsksOn = (name, env) => {
25
- if (!laneAsksOn(env))
26
- throw new CliError("LANE_ASKS_OFF", `${name} is off: lane asks ship off by default (MW1-37.2). A lane writes its question as an issue comment or a heartbeat note, as before; NODII_DEV_LANE_ASKS=1 turns the commands on.`, 1);
27
- };
14
+ export const RETIRED_LANE_ASK_ACTIONS = new Set(["ask", "asks", "answer"]);
15
+ export const LANE_ASKS_RETIRED =
16
+ "lane ask, lane asks and lane answer were retired in 0.6.209 (DEV-PROCESS-5, row 29b). A lane waiting on a person records `nodii-dev lane heartbeat <key> --waiting-on person:ROLE`; the role reads them with `nodii-dev lane waits --person ROLE`.";
17
+
18
+ /** `nodii-dev lane ask|asks|answer ...`: refused before anything runs or reaches Dev. */
19
+ export function refuseRetiredLaneAsk(argv) {
20
+ if (argv[0] === "lane" && RETIRED_LANE_ASK_ACTIONS.has(argv[1])) throw new CliError("USAGE", LANE_ASKS_RETIRED, 2);
21
+ }
28
22
 
29
23
  const via = { via: "nodii-dev" };
30
- const ASK_USAGE = "lane ask <key> --question TEXT [--options a,b] | lane ask withdraw <ask id>";
31
24
  const DEFER_MAX_MINUTES = 240;
32
25
 
33
26
  function onlyFlags(name, flags, allowed) {
@@ -36,44 +29,12 @@ function onlyFlags(name, flags, allowed) {
36
29
  throw new CliError("USAGE", `${name} does not take ${extra.map((flag) => `--${flag}`).join(", ")}; its flags: ${allowed.length ? allowed.map((flag) => `--${flag}`).join(", ") : "none"} (and --json).`, 2);
37
30
  }
38
31
 
39
- export async function laneAskCommand(args, flags, { request = devRequest, env = process.env } = {}) {
40
- assertAsksOn("lane ask", env);
41
- const [first, second, ...more] = args;
42
- if (first === "withdraw") {
43
- if (!second || more.length) throw new CliError("USAGE", "lane ask withdraw needs the ask id.", 2);
44
- onlyFlags("lane ask withdraw", flags, []);
45
- const payload = await request("POST", `/api/v1/lane-asks/${encode(second)}/withdraw`, { ...via });
46
- return { payload, human: `Withdrawn (${payload.data?.id ?? second}): ${payload.data?.laneKey ?? "the lane"} no longer asks.` };
47
- }
48
- if (!first || args.length > 1) throw new CliError("USAGE", ASK_USAGE, 2);
49
- onlyFlags("lane ask", flags, ["question", "options"]);
50
- const question = String(requireFlag(flags, "question"));
51
- const options = flags.options === undefined ? undefined : String(requireFlag(flags, "options")).split(",").map((option) => option.trim()).filter(Boolean);
52
- const payload = await request("POST", `/api/v1/lanes/${encode(first)}/asks`, { question, ...(options?.length ? { options } : {}), ...via });
53
- const key = payload.data?.laneKey ?? first;
54
- return { payload, human: `Asked (${payload.data?.id}): the coordinator's answer reaches ${key} as an amendment; acknowledge it with nodii-dev lane gather ${key} --delta. Keep working what is not blocked.` };
55
- }
56
-
57
- export async function laneAnswerCommand(args, flags, { request = devRequest, env = process.env } = {}) {
58
- assertAsksOn("lane answer", env);
59
- if (!args[0] || args.length > 1) throw new CliError("USAGE", "lane answer <ask id> --text TEXT", 2);
60
- onlyFlags("lane answer", flags, ["text"]);
61
- const text = String(requireFlag(flags, "text"));
62
- const payload = await request("POST", `/api/v1/lane-asks/${encode(args[0])}/answer`, { text, ...via });
63
- const { ask, amendment } = payload.data ?? {};
64
- const key = ask?.laneKey ?? "the lane";
65
- return { payload, human: `Answered (${ask?.id ?? args[0]}): ${key} gets it as amendment ${amendment?.version ?? "?"} and acknowledges it with nodii-dev lane gather ${key} --delta.` };
66
- }
67
-
68
- // Dev has no such ask: the id may be a leeway's.
69
- const notFound = (error) => error instanceof CliError && (/NOT_FOUND$/.test(error.code ?? "") || error.code === "HTTP_404");
70
-
71
32
  /**
72
- * `lane defer <id>`: the id is tried as an ask; when Dev has no such ask it
73
- * is tried as a leeway. `--leeway` goes straight to the leeway.
33
+ * `lane defer <leeway id>`: the id is a leeway's. `--leeway` is still accepted
34
+ * (it once skipped the ask) and changes nothing.
74
35
  */
75
- export async function laneDeferCommand(args, flags, { request = devRequest, env = process.env } = {}) {
76
- if (!args[0] || args.length > 1) throw new CliError("USAGE", "lane defer <ask or leeway id> --reason TEXT [--minutes N] [--leeway]", 2);
36
+ export async function laneDeferCommand(args, flags, { request = devRequest } = {}) {
37
+ if (!args[0] || args.length > 1) throw new CliError("USAGE", "lane defer <leeway id> --reason TEXT [--minutes N]", 2);
77
38
  onlyFlags("lane defer", flags, ["reason", "minutes", "leeway"]);
78
39
  const reason = String(requireFlag(flags, "reason"));
79
40
  let minutes;
@@ -83,33 +44,7 @@ export async function laneDeferCommand(args, flags, { request = devRequest, env
83
44
  throw new CliError("USAGE", `--minutes is a whole number from 1 to ${DEFER_MAX_MINUTES} (default 60).`, 2);
84
45
  }
85
46
  const body = { reason, ...(minutes === undefined ? {} : { minutes }), ...via };
86
- const id = encode(args[0]);
87
- let payload;
88
- // With questions off the id can only be a leeway's.
89
- let kind = flags.leeway || !laneAsksOn(env) ? "leeway" : "ask";
90
- if (kind === "ask") {
91
- try {
92
- payload = await request("POST", `/api/v1/lane-asks/${id}/defer`, body);
93
- } catch (error) {
94
- if (!notFound(error)) throw error;
95
- kind = "leeway";
96
- }
97
- }
98
- if (kind === "leeway") payload = await request("POST", `/api/v1/lane-leeway/${id}/defer`, body);
47
+ const payload = await request("POST", `/api/v1/lane-leeway/${encode(args[0])}/defer`, body);
99
48
  const item = payload.data ?? {};
100
- const what = kind === "ask" ? `${item.laneKey ?? "the lane"}'s question` : `${item.laneKey ?? "the lane"}'s leeway for ${item.blockerIssueKey ?? "its blocker"}`;
101
- return { payload, human: `Deferred (${item.id ?? args[0]}) until ${item.deferUntil ?? "?"}: ${reason}. ${what} counts again after that.` };
102
- }
103
-
104
- const askLine = (ask) => [ask.id, ask.laneKey, ask.state === "deferred" && ask.deferUntil ? `deferred until ${ask.deferUntil}` : ask.state, ask.createdAt, String(ask.question ?? "").replace(/\s+/g, " ").trim().slice(0, 100)].join("\t");
105
-
106
- export async function laneAsksCommand(args, flags, { request = devRequest, env = process.env } = {}) {
107
- assertAsksOn("lane asks", env);
108
- const filters = ["machine", "state", "lane", "cursor", "limit"];
109
- if (args.length) throw new CliError("USAGE", `lane asks ${filters.map((flag) => `[--${flag} X]`).join(" ")}`, 2);
110
- onlyFlags("lane asks", flags, filters);
111
- const payload = await request("GET", `/api/v1/lane-asks${query(Object.fromEntries(filters.filter((flag) => flags[flag] !== undefined).map((flag) => [flag, String(requireFlag(flags, flag))])))}`);
112
- const rows = payload.data ?? [];
113
- const more = payload.nextCursor ? `\nMore: nodii-dev lane asks --cursor ${payload.nextCursor}` : "";
114
- return { payload, human: rows.length ? `${rows.map(askLine).join("\n")}${more}` : "No lane asks." };
49
+ return { payload, human: `Deferred (${item.id ?? args[0]}) until ${item.deferUntil ?? "?"}: ${reason}. ${item.laneKey ?? "the lane"}'s leeway for ${item.blockerIssueKey ?? "its blocker"} counts again after that.` };
115
50
  }
@@ -1,4 +1,4 @@
1
- import { randomBytes } from "node:crypto";
1
+ import { createHash, randomBytes } from "node:crypto";
2
2
  import { existsSync } from "node:fs";
3
3
  import { appendFile, mkdir, open, readFile, rename, stat, writeFile } from "node:fs/promises";
4
4
  import { basename, dirname, join } from "node:path";
@@ -168,6 +168,54 @@ export async function inboxStopGate(payload, context, { dir, env = process.env }
168
168
  return takeInboxDelivery(key, { dir: dir ?? envInboxDir(process.env) });
169
169
  }
170
170
 
171
+ /**
172
+ * O3 item 8 (DEC-0569, MW1-36.5): the role a steward answers for, the person
173
+ * in `person:ROLE`. Dev delivers a role's waits to a steward keyed ROLE or
174
+ * steward-ROLE, so the key without its `steward-` prefix. Null when that is
175
+ * no role Dev accepts.
176
+ */
177
+ export function stewardRole(key) {
178
+ const role = String(key ?? "").replace(/^steward-/, "");
179
+ return /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(role) && role.length <= 48 ? role : null;
180
+ }
181
+
182
+ const deliveryId = (ref) => createHash("sha256").update(ref).digest("hex").slice(0, 8);
183
+
184
+ /**
185
+ * O3 item 8: a role's waits and READYs (Dev's `GET /lanes/waits?person=ROLE`
186
+ * board) as inbox entries for its steward, in the shape `lane message` writes,
187
+ * leaving out what `delivered` already holds. A scratch steward has no issue,
188
+ * so Dev's lane message never reaches it; the watchdog sweep writes these to
189
+ * its local inbox file instead. `delivered` comes back holding only refs still
190
+ * on the board, so a wait recorded again later is delivered again.
191
+ */
192
+ export function roleWaitDeliveries(key, board, delivered = [], { now = () => new Date() } = {}) {
193
+ const role = stewardRole(key);
194
+ const seen = new Set(Array.isArray(delivered) ? delivered : []);
195
+ const current = [];
196
+ const entries = [];
197
+ const persons = Array.isArray(board?.persons) ? board.persons : [];
198
+ for (const person of persons.filter((item) => item?.targetKind === "person" && item.targetRef === role)) {
199
+ const ready = new Map((Array.isArray(person.ready) ? person.ready : []).filter((item) => item?.lane && item.readyAt).map((item) => [item.lane, new Date(item.readyAt).toISOString()]));
200
+ for (const lane of Array.isArray(person.laneKeys) ? person.laneKeys : []) {
201
+ const waitRef = `wait:${role}:${lane}`;
202
+ current.push(waitRef);
203
+ if (!seen.has(waitRef))
204
+ entries.push({ id: deliveryId(waitRef), from: lane, to: key, at: now().toISOString(), body: `Lane ${lane} waits on person:${role} (MW1-36.5). It clears the wait itself once it has what it needs.`, issueKey: null, commentRef: null });
205
+ const readyAt = ready.get(lane);
206
+ if (!readyAt) continue;
207
+ const readyRef = `ready:${role}:${lane}:${readyAt}`;
208
+ current.push(readyRef);
209
+ if (!seen.has(readyRef))
210
+ entries.push({ id: deliveryId(readyRef), from: lane, to: key, at: readyAt, body: `Lane ${lane}, waiting on person:${role}, posted READY at ${readyAt} (MW1-36.5).`, issueKey: null, commentRef: null });
211
+ }
212
+ }
213
+ return { role, entries, delivered: current };
214
+ }
215
+
216
+ /** Append entries to a key's local inbox file (0600, dir 0700). */
217
+ export const appendInbox = (key, entries, { dir = inboxDir() } = {}) => append(key, dir, entries);
218
+
171
219
  /** nudge-pre: the lane's unread messages as hook context, from the inbox file alone (no Dev call). Null on any failure. */
172
220
  export async function inboxHookContext({ env = process.env, dir } = {}) {
173
221
  if (!laneSwitchOn("laneMessages", env)) return null;
@@ -178,6 +226,20 @@ export async function inboxHookContext({ env = process.env, dir } = {}) {
178
226
  }
179
227
  }
180
228
 
229
+ /**
230
+ * O3 item 8: a steward session's unread messages (its inbox key is its
231
+ * steward lane key), for the prompt hook's next turn. The local inbox file
232
+ * alone, no Dev call; null on any failure.
233
+ */
234
+ export async function stewardInboxContext(key, { env = process.env, dir } = {}) {
235
+ if (!key || !laneSwitchOn("laneMessages", env)) return null;
236
+ try {
237
+ return await takeInboxDelivery(key, { dir: dir ?? envInboxDir(env) });
238
+ } catch {
239
+ return null;
240
+ }
241
+ }
242
+
181
243
  /** The supervisor's continuation: the lane's unread messages, read from its runtime's config dir. */
182
244
  export const inboxForContinuation = async (laneKey, invocation, { env = process.env } = {}) =>
183
245
  !laneSwitchOn("laneMessages", env) ? null : takeInboxDelivery(laneKey, { dir: inboxDir(invocation?.env?.NODII_DEV_CONFIG_PATH ?? configPath()) });
@@ -10,7 +10,7 @@ import { CliError } from "./core.js";
10
10
  *
11
11
  * A switch outside RATIFIED_LANE_SWITCHES (none today) is off by default, on
12
12
  * only when its variable is exactly "1" (the coordinator's instruction of 18 Nov
13
- * 01:55Z, done as NODII_DEV_LANE_ASKS was).
13
+ * 01:55Z).
14
14
  */
15
15
  export const LANE_SWITCHES = Object.freeze({
16
16
  // "BLOCKED is not an exit": only a typed human gate ends a run early.