@nodii/dev 0.6.52 → 0.6.54

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/README.md CHANGED
@@ -145,6 +145,7 @@ nodii-dev gather tune start --cases all|ID,ID --corpus-ref REF [--pickers P,Q] [
145
145
  nodii-dev gather tune exec RUN_ID [--pickers shortlist-only,gemma-e4b,gemma-12b,gemma-26b]
146
146
  nodii-dev gather tune trial RUN_ID --case ID --picker P --iteration N [--documents A,B]
147
147
  nodii-dev gather tune finalize RUN_ID [--supersedes RUN_ID --reason TEXT]
148
+ nodii-dev gather tune missed [--document CODE] [--since ISO]
148
149
  nodii-dev gather timings [--model M] [--last N]
149
150
 
150
151
  nodii-dev open-questions list|show|answer
@@ -421,9 +422,23 @@ nodii-dev lane resume KEY [--override --reason TEXT]
421
422
  # deaths rule stopped; Dev refuses it with
422
423
  # RESUME_OVERRIDE_NEEDS_CHANGE unless the lane was amended
423
424
  # since its last death, keeps the reason on the new run, and
424
- # restarts the death count (AGENT-HARNESS-46)
425
+ # restarts the death count (AGENT-HARNESS-46). Any resume
426
+ # is refused with LANE_PROCESS_LIVE while the lane has a
427
+ # running run or a lane-agent heartbeat since the death
428
+ # that is not yet old enough to be dead: one process per
429
+ # lane (the coordinator's own heartbeats do not count)
430
+ nodii-dev lane check KEY [--gate CMD ...] [--critical] [--max-iterations N]
431
+ # from the lane's worktree: the rules, Figma and code checks (DEV-REV) over
432
+ # the diff against origin/main, tracked and untracked; --gate runs the gates
433
+ # in order first, else a green gates receipt for this head and diff
434
+ # (uncommitted changes included) is required.
435
+ # The lane's runtime reviews headless with no tools. One round per run: fix
436
+ # the blocking findings and rerun until CLEAN, STUCK or the cap (default 5);
437
+ # then REVIEW.json is written in git's private dir and recorded as lane review.
438
+ # A run is recorded only from a committed worktree (Dev keys it to the head).
439
+ # Without --critical the code check is NOT_REQUIRED (DEC-0085).
425
440
  nodii-dev lane review KEY --file REVIEW.json
426
- nodii-dev lane reviews KEY
441
+ nodii-dev lane reviews KEY # each run with its checks and findings
427
442
  nodii-dev lane land KEY
428
443
  nodii-dev lane verify KEY --dev-check REF
429
444
  nodii-dev lane list [--kind KIND] [--status STATUS] [--machine UUID]
package/dist/cli.js CHANGED
@@ -172,6 +172,8 @@ Usage: nodii-dev <command> [options] [--json]
172
172
  rules show CLAUSE_ID # one clause in full, from the current document version
173
173
  rules cap TOKENS # operator: set the core token cap (default 3000)
174
174
  gather tune cases|runs # Gather tuning (AH-11): frozen cases; runs with per-picker scores
175
+ gather tune missed [--document CODE] [--since ISO]
176
+ # clauses a lane review cited that Gather never served (DEV-REV-18), per document
175
177
  gather tune replay <case-id> # blind replay + trigger shortlist, for the lane-agent picker
176
178
  gather tune start --cases all|ID,ID --corpus-ref REF [--pickers P,Q] [--trigger manual] [--settings JSON]
177
179
  # --pickers: the subset this run scores (default all five)
@@ -241,11 +243,21 @@ Usage: nodii-dev <command> [options] [--json]
241
243
  lane resume <key> --override --reason TEXT
242
244
  # coordinator: resume past the two-identical-deaths stop; Dev refuses
243
245
  # it (RESUME_OVERRIDE_NEEDS_CHANGE) unless the lane was amended since
244
- # its last death; the reason is kept on the new run
246
+ # its last death; the reason is kept on the new run. Any resume is
247
+ # refused (LANE_PROCESS_LIVE) while the lane has a running run or a
248
+ # fresh lane-agent heartbeat since the death: one process per lane
245
249
  lane review <key> --file REVIEW.json # base/head, outcome and clause-cited findings
246
250
  lane review <key> --not-required --decision DEC-nnnn|--question ID|--quote TEXT --at ISO-TIME
247
251
  # no review needed for this diff: cites the ruling Dev validates (hub-58)
248
- lane reviews <key> # stored review history for the lane
252
+ lane check <key> [--gate CMD ...] [--critical] [--max-iterations N]
253
+ # from the lane's worktree: the rules, Figma and code checks over the
254
+ # diff against origin/main (DEV-REV); --gate runs gates 1-5 in order
255
+ # first (else a green gates receipt for this head is required); the
256
+ # lane's runtime reviews headless with no tools; one round per run:
257
+ # fix blocking findings and rerun until CLEAN, STUCK or the cap
258
+ # (default 5); then writes REVIEW.json in git's private dir and
259
+ # records it as lane review; --critical runs the code check (MW2-38.1)
260
+ lane reviews <key> # stored review history for the lane, with each run's checks
249
261
  lane freeze add <key> --section SECTION --file ITEM.json --reason TEXT
250
262
  lane freeze drop <key> --section SECTION --item ID --reason TEXT
251
263
  lane freeze swap <key> --section SECTION [--item ID] --file VALUE.json --reason TEXT
@@ -739,6 +751,13 @@ export async function main(argv = process.argv.slice(2)) {
739
751
  await (async () => recordGathered(process.cwd(), { guidelines: asked(f.components), deltaGathered: f.delta ? (f.paths ? asked(f.paths) : await changedPaths(process.cwd())) : [] }))().catch(() => {});
740
752
  return emitCommand(result);
741
753
  }
754
+ if (command === "lane" && action === "check") {
755
+ // The Delta gather goes through lane gather's own path (amendments included).
756
+ const result = await laneCommand("check", rest, f, { check: { deltaGather: (key, paths) => gatherLaneCommand(key, { delta: true, paths: paths.join(",") }) } });
757
+ emit(result.payload, json, result.human);
758
+ if (result.exitCode) process.exitCode = result.exitCode;
759
+ return;
760
+ }
742
761
  if (command === "lane" && action === "freeze")
743
762
  return emitCommand(await freezeCommand(rest[0], rest.slice(1), f));
744
763
  if (command === "lane") return emitCommand(await laneCommand(action, rest, f));
package/dist/core.js CHANGED
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { homedir, platform } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.52";
7
+ export const VERSION = "0.6.54";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
@@ -222,7 +222,7 @@ export async function checkLogin() {
222
222
  export const encode = (value) => encodeURIComponent(value);
223
223
  // Switches never take the next token as their value, so
224
224
  // `docs upload --wait rulebook/` keeps rulebook/ as a path.
225
- const SWITCHES = new Set(["json", "wait", "pending", "dry-run", "check", "all", "fleet", "help", "yes", "mine", "no-browser", "include-drafts", "drafted", "library", "async", "sync", "force", "system", "delta", "probe", "no-probe", "not-required", "override"]);
225
+ const SWITCHES = new Set(["json", "wait", "pending", "dry-run", "check", "all", "fleet", "help", "yes", "mine", "no-browser", "include-drafts", "drafted", "library", "async", "sync", "force", "system", "delta", "probe", "no-probe", "not-required", "override", "critical"]);
226
226
  export function parseArgs(argv) {
227
227
  const flags = {};
228
228
  const args = [];
@@ -69,6 +69,10 @@ export function surfacesFrom(registry) {
69
69
  componentSetKey: figma.componentSetKey ?? null,
70
70
  pendingKey: figma.pendingKey ?? null,
71
71
  nodeIds: [figma.nodeId ?? item.figmaNodeId, ...Object.values(figma.states ?? {})].filter(Boolean),
72
+ // What lane check's Figma check reads: each named state, else the main node.
73
+ frames: Object.keys(figma.states ?? {}).length
74
+ ? Object.entries(figma.states).map(([state, nodeId]) => ({ nodeId, state }))
75
+ : [figma.nodeId ?? item.figmaNodeId].filter(Boolean).map((nodeId) => ({ nodeId, state: "default" })),
72
76
  components: [...new Set((item.registryDependencies ?? []).map(componentName).filter(Boolean))],
73
77
  };
74
78
  });
package/dist/figma.js CHANGED
@@ -149,8 +149,11 @@ const CONTEXT_REFUSALS = {
149
149
  CHANGE_SET_MIXED_COMPONENTS: (message, details) =>
150
150
  [
151
151
  message,
152
- ...(details?.items ?? []).map((i) => ` item ${i.figmaNodeId}: outside it ${(i.outside ?? []).join(", ") || "?"}`),
153
- "Each variant must be its item's node or a direct child of it at the submitted version: split unrelated components into separate items, then submit again.",
152
+ ...(details?.items ?? []).flatMap((i) => [
153
+ ...(i.outside?.length ? [` item ${i.figmaNodeId}: outside it ${i.outside.join(", ")}`] : []),
154
+ ...(i.componentSets?.length ? [` item ${i.figmaNodeId}: mixes component sets ${i.componentSets.map((s) => s.name ?? s.id).join(", ")}`] : []),
155
+ ]),
156
+ "Each variant must be its item's node or a direct child of it at the submitted version, all from one component set (DEC-0327): split unrelated components into separate items, then submit again.",
154
157
  ].join("\n"),
155
158
  FIGMA_UNAVAILABLE: (message, details) =>
156
159
  [
package/dist/lanes.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { execFile } from "node:child_process";
2
- import { readFile } from "node:fs/promises";
2
+ import { readFile, realpath } from "node:fs/promises";
3
3
  import { promisify } from "node:util";
4
4
  import { CliError, encode, devRequest, query, readConfig, requireFlag } from "./core.js";
5
5
  import { launchRecovery } from "./runtime-launcher.js";
@@ -8,6 +8,8 @@ import { GATHER_TIMEOUT_MS, PICKER_FIRST_PICK_TIMEOUT_MS, PICKER_MODEL, agentFal
8
8
  import { storeGatherFreeze } from "./freeze.js";
9
9
  import { doneCheckRecorded } from "./lane-supervisor.js";
10
10
  import { SWAP_BOUNDARIES, componentsForScope, guidelineLookup, laneFigmaScope, loadDsCatalog } from "./figma-scope.js";
11
+ import { designCheck } from "./design.js";
12
+ import { REVIEW_FILE, checkLines, checkReviewChecks, diffDigest, laneDiff, privateStore, runLaneCheck, runOutcome, worktreeCommitted } from "./review.js";
11
13
 
12
14
  const execFileAsync = promisify(execFile);
13
15
  const via = { via: "nodii-dev" };
@@ -157,6 +159,8 @@ export async function reviewBody(flags, read = (path) => readFile(path, "utf8"))
157
159
  }
158
160
  if (!body || typeof body !== "object" || Array.isArray(body))
159
161
  throw new CliError("REVIEW_FILE_INVALID", "The review file must contain one JSON object.", 2);
162
+ // DEV-REV-12: a run with checks carries the three of them.
163
+ if (body.checks !== undefined) checkReviewChecks(body);
160
164
  return { ...body, ...via };
161
165
  }
162
166
 
@@ -287,7 +291,8 @@ async function localPick(lane, warming, pick, { budgetMs, timings }) {
287
291
  return { ...picked, timing, stats };
288
292
  }
289
293
 
290
- export async function laneCommand(action, args, flags, { request = devRequest, config = readConfig, gitContext = inferGitContext, commitsOf = branchCommits, read = (path) => readFile(path, "utf8"), reviewContext = reviewCommitContext, reviewReceipt = recordReviewReceipt, picker = pickDocuments, warm = warmPicker, firstPickTimeoutMs = PICKER_FIRST_PICK_TIMEOUT_MS, timings = { record: recordPickTiming, read: readPickTimings }, changedPaths = laneChangedPaths, gatherTimeoutMs = GATHER_TIMEOUT_MS, deadline: outerDeadline, storeFreeze = storeGatherFreeze, launch = launchRecovery, catalog = loadDsCatalog, pickLock = withPickLock } = {}) {
294
+ export async function laneCommand(action, args, flags, deps = {}) {
295
+ const { request = devRequest, config = readConfig, gitContext = inferGitContext, commitsOf = branchCommits, read = (path) => readFile(path, "utf8"), reviewContext = reviewCommitContext, reviewReceipt = recordReviewReceipt, picker = pickDocuments, warm = warmPicker, firstPickTimeoutMs = PICKER_FIRST_PICK_TIMEOUT_MS, timings = { record: recordPickTiming, read: readPickTimings }, changedPaths = laneChangedPaths, gatherTimeoutMs = GATHER_TIMEOUT_MS, deadline: outerDeadline, storeFreeze = storeGatherFreeze, launch = launchRecovery, catalog = loadDsCatalog, pickLock = withPickLock, check: checkDeps = {} } = deps;
291
296
  if (action === "list") {
292
297
  const c = flags.mine ? await config() : null;
293
298
  const payload = await request("GET", `/api/v1/lanes${query({ kind: flags.kind, status: flags.status, machine: flags.machine, agent: flags.mine ? c.agentId : flags.agent, "waiting-on": flags["waiting-on"], stuck: flags.stuck, cursor: flags.cursor, limit: flags.limit })}`);
@@ -532,10 +537,11 @@ export async function laneCommand(action, args, flags, { request = devRequest, c
532
537
  }
533
538
  }
534
539
  // MW2-45: `lane review` and a step's `--done --review` record through one path.
535
- const recordReview = async (reviewFlags = flags) => {
540
+ // `lane check` hands its own body over, already shaped.
541
+ const recordReview = async (reviewFlags = flags, prepared = null) => {
536
542
  // The input is checked before git is read, so a bad call never touches the worktree.
537
- const notRequired = reviewFlags["not-required"] ? notRequiredCitation(reviewFlags) : null;
538
- const filed = notRequired ? null : await reviewBody(reviewFlags, read);
543
+ const notRequired = !prepared && reviewFlags["not-required"] ? notRequiredCitation(reviewFlags) : null;
544
+ const filed = prepared ?? (notRequired ? null : await reviewBody(reviewFlags, read));
539
545
  const current = await reviewContext();
540
546
  const body = filed ?? { base: current.base, head: current.commit, iterationCount: 0, exitReason: "NOT_REQUIRED", appliedPatches: [], unresolvedProposals: [], reviewerErrors: [], findings: [], notRequired, ...via };
541
547
  if (body.head !== current.commit || body.base !== current.base)
@@ -556,6 +562,53 @@ export async function laneCommand(action, args, flags, { request = devRequest, c
556
562
  const missed = findings.filter((finding) => finding.missedTrigger === true).length;
557
563
  return `review recorded for the current commit and origin/main (${p.data.exitReason}; ${findings.length} finding(s), ${missed} missed trigger(s))`;
558
564
  };
565
+ if (action === "check") {
566
+ const context = await gitContext();
567
+ const lane = (await request("GET", `/api/v1/lanes/${encode(id)}`)).data;
568
+ const real = (path) => realpath(path).catch(() => path);
569
+ const here = await real(context.worktree);
570
+ const worktrees = [...(lane.repositories ?? []), ...(lane.freeze?.boundaries?.repos ?? []), { worktree: lane.worktree }].map((x) => x?.worktree).filter(Boolean);
571
+ if (!(await Promise.all(worktrees.map(real))).includes(here))
572
+ throw new CliError("LANE_WORKTREE_REQUIRED", `Run lane check from ${ref}'s worktree (${worktrees.join(", ") || "none recorded"}); this is ${context.worktree}.`, 2);
573
+ const freeze = (await request("GET", `/api/v1/lanes/${encode(id)}/freeze`)).data?.freeze ?? null;
574
+ const current = { ...(await reviewContext()), branch: context.branch };
575
+ const store = checkDeps.store ?? privateStore(context.worktree);
576
+ const run = await runLaneCheck(ref, flags, {
577
+ request, lane, freeze, current, cwd: context.worktree, store,
578
+ diff: checkDeps.diff ?? laneDiff,
579
+ deltaGather: checkDeps.deltaGather ?? ((key, paths) => laneCommand("gather", [key], { delta: true, paths: paths.join(",") }, deps)),
580
+ catalog: checkDeps.catalog ?? catalog,
581
+ designCheck: checkDeps.designCheck ?? designCheck,
582
+ ...(checkDeps.gate ? { gate: checkDeps.gate } : {}),
583
+ ...(checkDeps.reviewer ? { reviewer: checkDeps.reviewer } : {}),
584
+ ...(checkDeps.now ? { now: checkDeps.now } : {}),
585
+ });
586
+ const lines = checkLines(run.checks, run.maxIterations);
587
+ // A check still looping records nothing: the agent fixes and reruns (MW2-41).
588
+ if (!run.body) {
589
+ await run.saveLoop();
590
+ const open = run.checks.filter((x) => x.outcome === null).map((x) => x.check);
591
+ return {
592
+ payload: { data: { recorded: false, outcome: "NOT_CLEAN", checks: run.checks } },
593
+ human: [...lines, `run: NOT CLEAN, nothing recorded. Fix the blocking ${open.join(" and ")} finding(s), commit, and rerun nodii-dev lane check ${ref}.`].join("\n"),
594
+ exitCode: 1,
595
+ };
596
+ }
597
+ // Dev binds a run to base and head only, so the reviewed content must be that
598
+ // commit, unchanged since the reviewers read it.
599
+ const committed = await (checkDeps.committed ?? worktreeCommitted)(context.worktree);
600
+ if (!committed || diffDigest((await (checkDeps.diff ?? laneDiff)(context.worktree)).text) !== run.digest)
601
+ throw new CliError("REVIEW_WORKTREE_DIRTY", `${[...lines, `run: nothing recorded. ${committed ? "The worktree changed while the reviewers ran" : "The reviewed diff has uncommitted or untracked changes"}, and Dev records a review for commit ${run.body.head} only. Commit them (or drop them) and rerun nodii-dev lane check ${ref}; this round does not count.`].join("\n")}`, 1);
602
+ const file = await store.write(REVIEW_FILE, run.body);
603
+ const payload = await recordReview(flags, run.body);
604
+ await run.saveLoop();
605
+ const outcome = runOutcome(run.body.checks);
606
+ return {
607
+ payload: { ...payload, reviewFile: file },
608
+ human: [...lines, `run: ${outcome === "CLEAN" ? "CLEAN" : "NOT CLEAN"}, recorded on ${ref} (${file})`].join("\n"),
609
+ exitCode: outcome === "CLEAN" ? 0 : 1,
610
+ };
611
+ }
559
612
  if (action === "step") {
560
613
  const selected = ["start", "done", "block", "not-applicable"].filter((x) => flags[x]);
561
614
  if (selected.length !== 1) throw new CliError("USAGE", "lane step needs exactly one of --start, --done, --block, or --not-applicable.", 2);
@@ -600,10 +653,14 @@ export async function laneCommand(action, args, flags, { request = devRequest, c
600
653
  try {
601
654
  payload = await request("POST", `/api/v1/lanes/${encode(id)}/steps/${encode(step.id)}/${selected[0]}`, via);
602
655
  } catch (error) {
656
+ // DEV-REV-14: Dev names each failing check.
657
+ const failed = Array.isArray(error?.details?.failedChecks) && error.details.failedChecks.length
658
+ ? ` Failing checks: ${error.details.failedChecks.map((x) => `${x.check} ${x.outcome}`).join(", ")}; fix them and rerun nodii-dev lane check ${ref}.`
659
+ : "";
603
660
  if (!review && ["REVIEW_NOT_RECORDED", "REVIEW_NOT_CLEAN"].includes(error?.code))
604
- throw new CliError(error.code, `${side}/${step.stepKey} on ${ref} needs a stored review record whose latest entry is CLEAN, or a NOT-REQUIRED record citing a ruling (hub-58). Run lane step ${ref} --side ${side} --done ${step.stepKey} --review REVIEW.json, or lane review ${ref} --not-required --decision DEC-nnnn|--question ID|--quote TEXT --at ISO-TIME first.`, 1);
661
+ throw new CliError(error.code, `${side}/${step.stepKey} on ${ref} needs a stored review record whose latest entry is CLEAN, or a NOT-REQUIRED record citing a ruling (hub-58).${failed} Run nodii-dev lane check ${ref} (or lane step ${ref} --side ${side} --done ${step.stepKey} --review REVIEW.json, or lane review ${ref} --not-required --decision DEC-nnnn|--question ID|--quote TEXT --at ISO-TIME) first.`, 1, error.details);
605
662
  if (!review) throw error;
606
- throw new CliError(error?.code ?? "STEP_DONE_FAILED", `${ref}: the review is recorded, but ${side}/${step.stepKey} was not marked done (${error?.message ?? error}). Run the same lane step --done without --review.`, 1);
663
+ throw new CliError(error?.code ?? "STEP_DONE_FAILED", `${ref}: the review is recorded, but ${side}/${step.stepKey} was not marked done (${error?.message ?? error}).${failed || " Run the same lane step --done without --review."}`, 1, error?.details);
607
664
  }
608
665
  if (review) return { payload: { ...payload, review: review.data }, human: `${ref}: ${side}/${step.stepKey} done; ${reviewSummary(review)}.` };
609
666
  if (reason) {
@@ -715,9 +772,11 @@ export async function laneCommand(action, args, flags, { request = devRequest, c
715
772
  const missed = run.findings.filter((finding) => finding.missedTrigger === true).length;
716
773
  return [
717
774
  `${run.createdAt}\t${run.head}\t${run.exitReason}\t${run.findings.length} finding(s)\t${missed} missed trigger(s)${run.notRequiredKind ? `\tcites ${run.notRequiredKind} ${run.notRequiredKind === "operator_quote" ? `"${run.notRequiredQuote}" (${run.notRequiredAt})` : run.notRequiredRef}` : ""}`,
775
+ // DEV-REV-12: a run recorded by lane check carries its three checks.
776
+ ...(run.checks ?? []).map((check) => ` check ${check.check}\t${check.outcome}\t${check.iterationCount} iteration(s)${check.reviewerErrors?.length ? `\t${check.reviewerErrors.length} reviewer error(s)` : ""}`),
718
777
  ...run.findings.map(
719
778
  (finding) =>
720
- ` ${finding.severity}\t${finding.perspective}\t${finding.clauseId ?? "-"}\t${finding.summary}${finding.missedTrigger ? "\tMISSED_TRIGGER" : ""}`,
779
+ ` ${finding.severity}\t${finding.perspective}\t${finding.perspective === "figma" ? `${finding.frameUrl ?? "-"} [${finding.state ?? "-"}]` : finding.clauseId ?? "-"}\t${finding.summary}${finding.missedTrigger ? "\tMISSED_TRIGGER" : ""}${finding.disposition && finding.disposition !== "unresolved" ? `\t${finding.disposition}` : ""}`,
721
780
  ),
722
781
  ].join("\n");
723
782
  })
package/dist/review.js ADDED
@@ -0,0 +1,520 @@
1
+ // `nodii-dev lane check` (DEV-REV-6 to DEV-REV-11): the three review checks
2
+ // over the exact diff that will be pushed. The reviewer is the lane's own
3
+ // runtime, headless and without tools (DEV-REV-2); it sees the diff and the
4
+ // clauses that judge it, nothing else.
5
+ import { execFile, spawn } from "node:child_process";
6
+ import { createHash } from "node:crypto";
7
+ import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
8
+ import { tmpdir } from "node:os";
9
+ import { dirname, join } from "node:path";
10
+ import { promisify } from "node:util";
11
+ import { CliError, encode } from "./core.js";
12
+ import { gitPrivatePath } from "./safety.js";
13
+
14
+ const execFileAsync = promisify(execFile);
15
+ export const CHECKS = ["rules", "figma", "code"];
16
+ export const CHECK_OUTCOMES = ["CLEAN", "NOT_REQUIRED", "NOT_APPLICABLE", "TIMEOUT", "CRASH", "REVIEWER_UNAVAILABLE", "UNPARSABLE", "NOTHING_TO_FIX", "STUCK", "FLIP_FLOP", "ITERATION_CAP"];
17
+ export const SEVERITIES = ["blocker", "major", "minor"];
18
+ export const GATES_RECEIPT = "nodii-gates-receipt.json";
19
+ export const REVIEW_LOOP = "nodii-review-loop.json";
20
+ export const REVIEW_FILE = "REVIEW.json";
21
+ export const REVIEWER_TIMEOUT_MS = 600_000;
22
+ export const MAX_ITERATIONS = 5;
23
+ // About 150k tokens: a diff past this is reviewed by nobody, never in part.
24
+ export const MAX_DIFF_CHARS = 600_000;
25
+ // DEV-REV-10: no --critical, no code check.
26
+ export const CODE_NOT_REQUIRED = { decision: "DEC-0085" };
27
+ const PASSING = { rules: ["CLEAN"], figma: ["CLEAN", "NOT_APPLICABLE"], code: ["CLEAN", "NOT_REQUIRED"] };
28
+ const UNAVAILABLE = "REVIEWER_UNAVAILABLE";
29
+
30
+ class ReviewerError extends Error {
31
+ constructor(outcome, message) {
32
+ super(message);
33
+ this.outcome = outcome;
34
+ }
35
+ }
36
+
37
+ /** DEV-REV-14 as Dev computes it: rules CLEAN, Figma CLEAN or not applicable, code CLEAN or not required. */
38
+ export const runOutcome = (checks) => (checks.every((x) => PASSING[x.check].includes(x.outcome)) ? "CLEAN" : "NOT_CLEAN");
39
+
40
+ /** The worktree's private files (git's own dir), never in the repository. */
41
+ export const privateStore = (cwd) => ({
42
+ path: (name) => gitPrivatePath(cwd, name),
43
+ async read(name) {
44
+ try { return JSON.parse(await readFile(await gitPrivatePath(cwd, name), "utf8")); }
45
+ catch (error) { if (error.code === "ENOENT") return null; throw error; }
46
+ },
47
+ async write(name, value) {
48
+ const path = await gitPrivatePath(cwd, name);
49
+ await mkdir(dirname(path), { recursive: true });
50
+ const temporary = `${path}.${process.pid}.tmp`;
51
+ await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
52
+ await rename(temporary, path);
53
+ return path;
54
+ },
55
+ });
56
+
57
+ /** One gate through the shell in the worktree; its output goes to stderr, its tail is kept. */
58
+ export function runGate(command, cwd) {
59
+ return new Promise((resolve) => {
60
+ let tail = "";
61
+ const child = spawn("/bin/sh", ["-c", command], { cwd, stdio: ["ignore", "pipe", "pipe"] });
62
+ const keep = (chunk) => {
63
+ process.stderr.write(chunk);
64
+ tail = (tail + chunk).slice(-4000);
65
+ };
66
+ child.stdout.on("data", keep);
67
+ child.stderr.on("data", keep);
68
+ child.on("error", (error) => resolve({ code: 127, tail: error.message }));
69
+ child.on("close", (code, signal) => resolve({ code: code ?? (signal ? 128 : 1), tail }));
70
+ });
71
+ }
72
+
73
+ /** The content a receipt and a review cover: the diff itself, so uncommitted changes count too. */
74
+ export const diffDigest = (text) => createHash("sha256").update(text).digest("hex");
75
+
76
+ /**
77
+ * MW2-14 / DEV-REV-6: gates 1 to 5 green for this head and this exact diff,
78
+ * uncommitted and untracked changes included. --gate runs them in order and
79
+ * writes the receipt; without --gate only a receipt for this head, base and
80
+ * diff counts. Returns the diff the receipt covers, which is the one reviewed.
81
+ */
82
+ export async function gatesReceipt(commands, { cwd, current, store, diff, run = runGate, now = () => new Date().toISOString() }) {
83
+ const changed = await diff(cwd);
84
+ const digest = diffDigest(changed.text);
85
+ if (commands.length) {
86
+ for (const command of commands) {
87
+ const { code, tail } = await run(command, cwd);
88
+ if (code !== 0)
89
+ throw new CliError("GATES_NOT_GREEN", `Gate \`${command}\` exited ${code}; nothing was reviewed or recorded. Make it green and rerun lane check.${tail ? `\n${tail.trimEnd().split("\n").slice(-20).join("\n")}` : ""}`, 1, { command, exitCode: code });
90
+ }
91
+ if (diffDigest((await diff(cwd)).text) !== digest)
92
+ throw new CliError("GATES_CHANGED_WORKTREE", "A gate changed the worktree, so the gates before it did not run on this content; nothing was reviewed or recorded. Keep or commit the change and rerun lane check.", 1);
93
+ await store.write(GATES_RECEIPT, { commit: current.commit, base: current.base, diff: digest, commands, at: now() });
94
+ return changed;
95
+ }
96
+ const receipt = await store.read(GATES_RECEIPT);
97
+ if (!receipt || receipt.commit !== current.commit || receipt.base !== current.base || receipt.diff !== digest)
98
+ throw new CliError("GATES_RECEIPT_MISSING", `No green gates receipt for head ${current.commit} on origin/main ${current.base} with this worktree's changes (MW2-14)${receipt ? `; the last one covers ${receipt.commit} on ${receipt.base}${receipt.commit === current.commit && receipt.base === current.base ? " with other uncommitted changes" : ""}` : ""}. Pass your gates with --gate CMD (repeatable, in order): lane check runs them first.`, 2);
99
+ return changed;
100
+ }
101
+
102
+ /** DEV-REV-6: the worktree against its origin/main merge base, tracked and untracked. */
103
+ export async function laneDiff(cwd, { exec = execFileAsync } = {}) {
104
+ const git = async (...args) => (await exec("git", ["-C", cwd, ...args], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 })).stdout;
105
+ const mergeBase = (await git("merge-base", "origin/main", "HEAD")).trim();
106
+ const tracked = await git("diff", "--no-color", "--no-ext-diff", mergeBase);
107
+ const names = (await git("diff", "--name-only", mergeBase)).split("\n");
108
+ const untracked = (await git("ls-files", "--others", "--exclude-standard", "-z")).split("\0").filter(Boolean);
109
+ const added = [];
110
+ for (const path of untracked) {
111
+ // --no-index exits 1 when the files differ, which they always do here.
112
+ try { added.push(await git("diff", "--no-color", "--no-ext-diff", "--no-index", "--", "/dev/null", path)); }
113
+ catch (error) { if (error.code === 1 && typeof error.stdout === "string") added.push(error.stdout); else throw error; }
114
+ }
115
+ const paths = [...new Set([...names, ...untracked].map((x) => x.trim()).filter(Boolean))];
116
+ return { mergeBase, text: tracked + added.join(""), paths };
117
+ }
118
+
119
+ /** True when the worktree is its commit: no uncommitted or untracked (not ignored) change. */
120
+ export async function worktreeCommitted(cwd, { exec = execFileAsync } = {}) {
121
+ return !(await exec("git", ["-C", cwd, "status", "--porcelain", "--untracked-files=normal"], { encoding: "utf8" })).stdout.trim();
122
+ }
123
+
124
+ const nullable = (type) => ({ type: [type, "null"] });
125
+ /** The answer schema; every key required (codex's strict schemas), optional ones nullable. */
126
+ export function reviewerSchema(check, clauseIds = []) {
127
+ const properties = {
128
+ severity: { type: "string", enum: SEVERITIES },
129
+ summary: { type: "string" },
130
+ detail: { type: "string" },
131
+ path: nullable("string"),
132
+ line: nullable("integer"),
133
+ ...(check === "rules" ? { clauseId: { type: "string", enum: clauseIds } } : {}),
134
+ };
135
+ return {
136
+ type: "object",
137
+ additionalProperties: false,
138
+ required: ["findings"],
139
+ properties: { findings: { type: "array", items: { type: "object", additionalProperties: false, required: Object.keys(properties), properties } } },
140
+ };
141
+ }
142
+
143
+ const SEVERITY_TEXT = "Severity: blocker = must not merge (data loss, a security hole, a MUST broken in a way that ships harm); major = has to be fixed before merge; minor = worth fixing, never blocks.";
144
+ const clauseText = (clauses) => clauses.map((clause) => [
145
+ `### ${clause.clauseId}`,
146
+ ...clause.sources.map((source) => `(${source.documentCode} v${source.documentVersion}${source.section ? `, ${source.section}` : ""})\n${source.text}`),
147
+ ].join("\n")).join("\n\n");
148
+
149
+ /** The reviewer's whole input: instructions, the clauses, the diff. */
150
+ export function reviewerPrompt(check, { diff, clauses = [] }) {
151
+ const ask = check === "rules"
152
+ ? [
153
+ "You are the rules check of a lane review (DEV-REV). You have no tools: judge only the diff and the clauses below.",
154
+ "Report one finding per breach: the diff does something a clause forbids, or leaves out something a clause requires for what the diff changes. Each finding cites exactly one clause id from the list. Do not report clauses the diff does not touch, style preferences, or anything a clause does not say.",
155
+ ]
156
+ : [
157
+ "You are the code check of a lane review (DEV-REV, MW2-38.1). You have no tools: judge only the diff below.",
158
+ "Review it for correctness, security, data safety and money safety: wrong results, unhandled failures, races, injection, leaked secrets or personal data, lost or corrupted data, wrong amounts. The governing clauses are context for what the change must do. Report one finding per real defect, with the file path and line in the new version where you can.",
159
+ ];
160
+ return [
161
+ ...ask,
162
+ SEVERITY_TEXT,
163
+ "Answer with JSON only, matching the schema. No breach means {\"findings\": []}.",
164
+ "",
165
+ `## Clauses (${clauses.length})`,
166
+ clauses.length ? clauseText(clauses) : "(none)",
167
+ "",
168
+ "## Diff (the worktree against its origin/main merge base)",
169
+ "```diff",
170
+ diff,
171
+ "```",
172
+ ].join("\n");
173
+ }
174
+
175
+ /** The headless, tool-less reviewer command for the lane's runtime. */
176
+ export function reviewerInvocation({ runtime, model, profile, schema, workdir, schemaFile, outFile }) {
177
+ if (runtime === "codex") return {
178
+ command: "codex",
179
+ args: ["exec", "--sandbox", "read-only", "--skip-git-repo-check", "--ephemeral", "--ignore-user-config", "--ignore-rules",
180
+ ...["shell_tool", "unified_exec", "apps", "plugins", "browser_use", "in_app_browser", "computer_use"].flatMap((feature) => ["--disable", feature]),
181
+ "-c", "web_search=\"disabled\"", "--cd", workdir, "--output-schema", schemaFile, "--output-last-message", outFile, ...(model ? ["--model", model] : []), "-"],
182
+ env: profile ? { CODEX_HOME: profile } : {},
183
+ };
184
+ return {
185
+ command: "claude",
186
+ args: ["-p", "--output-format", "json", "--json-schema", JSON.stringify(schema), "--tools", "", "--safe-mode", "--strict-mcp-config", "--no-session-persistence", ...(model ? ["--model", model] : [])],
187
+ env: profile ? { CLAUDE_CONFIG_DIR: profile } : {},
188
+ };
189
+ }
190
+
191
+ /** Spawn with stdin; never throws for the process's own failures, the caller maps them. */
192
+ export function spawnReviewer({ command, args, env, cwd, input, timeoutMs }) {
193
+ return new Promise((resolve) => {
194
+ let stdout = "";
195
+ let stderr = "";
196
+ let timedOut = false;
197
+ const child = spawn(command, args, { cwd, env: { ...process.env, ...env }, stdio: ["pipe", "pipe", "pipe"] });
198
+ const timer = setTimeout(() => { timedOut = true; child.kill("SIGKILL"); }, timeoutMs);
199
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
200
+ child.stderr.on("data", (chunk) => { stderr = (stderr + chunk).slice(-4000); });
201
+ child.stdin.on("error", () => {});
202
+ child.on("error", (error) => { clearTimeout(timer); resolve({ code: null, stdout, stderr, timedOut, missing: error.code === "ENOENT", error: error.message }); });
203
+ child.on("close", (code) => { clearTimeout(timer); resolve({ code, stdout, stderr, timedOut, missing: false }); });
204
+ child.stdin.end(input);
205
+ });
206
+ }
207
+
208
+ const parseJson = (text, what) => {
209
+ try { return JSON.parse(text); }
210
+ catch { throw new ReviewerError("UNPARSABLE", `${what} is not JSON: ${String(text).slice(0, 200)}`); }
211
+ };
212
+
213
+ /** One reviewer round: the answer's findings, or a ReviewerError carrying the MW2-40 exit reason. */
214
+ export async function runReviewer(check, { runtime = "claude", model, profile, prompt, clauseIds = [], timeoutMs = REVIEWER_TIMEOUT_MS, spawnImpl = spawnReviewer }) {
215
+ const schema = reviewerSchema(check, clauseIds);
216
+ // An empty directory: the reviewer reads no repository and no project settings.
217
+ const workdir = await mkdtemp(join(tmpdir(), "nodii-review-"));
218
+ try {
219
+ const schemaFile = join(workdir, "schema.json");
220
+ const outFile = join(workdir, "answer.json");
221
+ if (runtime === "codex") await writeFile(schemaFile, JSON.stringify(schema));
222
+ const invocation = reviewerInvocation({ runtime, model, profile, schema, workdir, schemaFile, outFile });
223
+ const result = await spawnImpl({ ...invocation, cwd: workdir, input: prompt, timeoutMs });
224
+ const name = invocation.command;
225
+ if (result.missing) throw new ReviewerError(UNAVAILABLE, `${name} is not installed or not on PATH`);
226
+ if (result.timedOut) throw new ReviewerError("TIMEOUT", `${name} gave no answer within ${Math.round(timeoutMs / 1000)} s`);
227
+ if (result.code !== 0) throw new ReviewerError("CRASH", `${name} exited ${result.code ?? "abnormally"}: ${(result.stderr || result.error || result.stdout || "").trim().slice(-500)}`);
228
+ let answer;
229
+ if (runtime === "codex") {
230
+ let text;
231
+ try { text = await readFile(outFile, "utf8"); }
232
+ catch { throw new ReviewerError("UNPARSABLE", "codex wrote no final answer"); }
233
+ answer = parseJson(text, "codex's answer");
234
+ } else {
235
+ const envelope = parseJson(result.stdout, "claude's output");
236
+ if (envelope?.is_error) throw new ReviewerError("CRASH", `claude ended in error (${envelope.subtype ?? "unknown"}): ${String(envelope.result ?? "").slice(0, 500)}`);
237
+ answer = envelope?.structured_output ?? (typeof envelope?.result === "string" ? parseJson(envelope.result, "claude's answer") : null);
238
+ }
239
+ return checkAnswer(check, answer, clauseIds);
240
+ } finally {
241
+ await rm(workdir, { recursive: true, force: true });
242
+ }
243
+ }
244
+
245
+ const text = (value, max) => (typeof value === "string" ? value.trim().slice(0, max) : "");
246
+ /** The answer as Dev's finding shape, or UNPARSABLE: no finding outside the schema reaches Dev. */
247
+ export function checkAnswer(check, answer, clauseIds = []) {
248
+ if (!answer || typeof answer !== "object" || !Array.isArray(answer.findings))
249
+ throw new ReviewerError("UNPARSABLE", "the answer has no findings array");
250
+ return answer.findings.map((finding, index) => {
251
+ const summary = text(finding?.summary, 500);
252
+ if (!SEVERITIES.includes(finding?.severity) || !summary)
253
+ throw new ReviewerError("UNPARSABLE", `finding ${index + 1} has no valid severity or summary`);
254
+ if (check === "rules" && !clauseIds.includes(finding.clauseId))
255
+ throw new ReviewerError("UNPARSABLE", `finding ${index + 1} cites ${finding.clauseId ?? "no clause"}, which is not a clause it was given`);
256
+ const path = text(finding.path, 1000);
257
+ return {
258
+ perspective: check,
259
+ severity: finding.severity,
260
+ summary,
261
+ detail: text(finding.detail, 10_000) || summary,
262
+ ...(path ? { path } : {}),
263
+ ...(Number.isInteger(finding.line) && finding.line > 0 ? { line: finding.line } : {}),
264
+ ...(check === "rules" ? { clauseId: finding.clauseId } : {}),
265
+ };
266
+ });
267
+ }
268
+
269
+ /** One clause's full current text in every document that holds it (DEV-REV-7). */
270
+ async function clauseSources(request, clauseId) {
271
+ const rows = (await request("GET", `/api/v1/rules/clauses/${encode(clauseId)}`)).data ?? [];
272
+ if (!rows.length) throw new Error(`Dev has no current text for ${clauseId}`);
273
+ return { clauseId, sources: rows.map((row) => ({ documentCode: row.documentCode, documentVersion: row.documentVersion, section: row.section, text: row.text })) };
274
+ }
275
+
276
+ async function inBatches(items, size, work) {
277
+ const out = [];
278
+ for (let i = 0; i < items.length; i += size) out.push(...await Promise.all(items.slice(i, i + size).map(work)));
279
+ return out;
280
+ }
281
+
282
+ /**
283
+ * The rules check's clauses: the lane's Clause map (its Freeze) and a Delta
284
+ * gather over the changed paths, each with its full text. Any gap is an
285
+ * error: a partial set is never reviewed.
286
+ */
287
+ export async function ruleClauses(ref, { request, freeze, paths, deltaGather }) {
288
+ const mapped = [...(freeze?.clauseMap?.clauses ?? []), ...(freeze?.pinnedClauses ?? [])].map((x) => x.clauseId);
289
+ if (!freeze?.clauseMap) throw new ReviewerError(UNAVAILABLE, `${ref} has no Clause map: its Freeze was never written by Gather. Run nodii-dev lane gather ${ref} first.`);
290
+ if (paths.length > 5000) throw new ReviewerError(UNAVAILABLE, `the diff touches ${paths.length} paths; a Delta gather takes at most 5,000`);
291
+ let delta;
292
+ try { delta = await deltaGather(ref, paths); }
293
+ catch (error) { throw new ReviewerError(UNAVAILABLE, `the Delta gather over the changed paths failed (${error?.code ?? "ERROR"}: ${error?.message ?? error})`); }
294
+ const data = delta?.payload?.data;
295
+ if (data?.recorded === false || !data?.gatherId)
296
+ throw new ReviewerError(UNAVAILABLE, `the Delta gather over the changed paths recorded nothing${data?.fallback ? ` (${data.fallback})` : ""}; record it with nodii-dev lane gather ${ref} --delta --picker agent, then rerun lane check`);
297
+ const ids = [...new Set([...mapped, ...(data.clauses ?? []).map((x) => x.clauseId)])].sort();
298
+ let clauses;
299
+ try { clauses = await inBatches(ids, 8, (id) => clauseSources(request, id)); }
300
+ catch (error) { throw new ReviewerError(UNAVAILABLE, `a clause's text could not be read (${error?.code ? `${error.code}: ` : ""}${error?.message ?? error})`); }
301
+ return { clauses, clauseIds: ids, clauseMapGatherId: freeze.clauseMap.gatherId ?? null, deltaGatherId: data.gatherId };
302
+ }
303
+
304
+ export const frameUrl = (fileKey, nodeId) => `https://www.figma.com/design/${fileKey}?node-id=${String(nodeId).replace(/:/g, "-")}`;
305
+
306
+ /**
307
+ * The frames in the Freeze's Figma boundary: each component set's state
308
+ * nodes from the DS catalog (its main node as "default" when it has none);
309
+ * a whole-file boundary is the whole file.
310
+ */
311
+ export function boundaryFrames(figma, surfaces) {
312
+ return figma.flatMap((file) => {
313
+ const keys = file.componentSetKeys ?? [];
314
+ if (!keys.length) return [{ fileKey: file.fileKey, nodeId: null, state: "default" }];
315
+ return keys.flatMap((key) => {
316
+ const surface = surfaces.find((x) => x.componentSetKey === key && x.fileKey === file.fileKey);
317
+ if (!surface) throw new ReviewerError("CRASH", `component set ${key} in the Freeze's Figma boundary is not a Surface in the DS catalog`);
318
+ return surface.frames.map((frame) => ({ fileKey: file.fileKey, ...frame }));
319
+ });
320
+ });
321
+ }
322
+
323
+ /** DEV-REV-9, design-check part: designCheck on every boundary frame; per-state frame comparison is Q-162. */
324
+ export async function figmaFindings(figma, { catalog, check }) {
325
+ const frames = boundaryFrames(figma, figma.some((file) => file.componentSetKeys?.length) ? await catalog() : []);
326
+ const findings = [];
327
+ const versions = new Set();
328
+ for (const frame of frames) {
329
+ const result = await check(frame.fileKey, frame.nodeId ? { nodes: frame.nodeId } : {});
330
+ const data = result.payload.data;
331
+ if (data.libraryVersion) versions.add(data.libraryVersion);
332
+ for (const finding of data.findings ?? [])
333
+ findings.push({
334
+ perspective: "figma",
335
+ severity: "major",
336
+ summary: `${finding.check} at ${finding.nodeId}`.slice(0, 500),
337
+ detail: (finding.detail || finding.check).slice(0, 10_000),
338
+ frameUrl: frameUrl(frame.fileKey, frame.nodeId ?? finding.nodeId),
339
+ state: frame.state,
340
+ });
341
+ }
342
+ return {
343
+ findings,
344
+ inputs: {
345
+ frames: frames.map((frame) => ({ fileKey: frame.fileKey, nodeId: frame.nodeId, state: frame.state, frameUrl: frame.nodeId ? frameUrl(frame.fileKey, frame.nodeId) : `https://www.figma.com/design/${frame.fileKey}` })),
346
+ libraryVersions: [...versions],
347
+ frameComparison: "not_built",
348
+ },
349
+ };
350
+ }
351
+
352
+ // A finding is the same across rounds by what it cites and where.
353
+ // A finding's identity across rounds uses only fields a reviewer states the same
354
+ // way each time: the clause (and frame and state) it cites, or for code the file.
355
+ // Never the wording, which changes between rounds.
356
+ const findingKey = (finding) => (finding.perspective === "code" ? ["code", finding.path ?? ""] : [finding.perspective, finding.clauseId ?? "", finding.frameUrl ?? "", finding.state ?? ""]).join("|");
357
+ const blockingOf = (findings) => findings.filter((finding) => finding.severity !== "minor");
358
+
359
+ /**
360
+ * MW2-41 to MW2-43 across invocations: one round per run of lane check. CLEAN
361
+ * when nothing blocks; STUCK when the blocking set is the last round's;
362
+ * ITERATION_CAP at the cap; otherwise the loop goes on (outcome null) and the
363
+ * agent fixes and reruns. Only CLEAN starts a new loop.
364
+ */
365
+ export function loopRound(previous, findings, { head, maxIterations }) {
366
+ const rounds = previous?.rounds ?? [];
367
+ const iterationCount = rounds.length + 1;
368
+ const blocking = blockingOf(findings);
369
+ const keys = [...new Set(blocking.map(findingKey))].sort();
370
+ // Fixed only when nothing at that key is left, not even a downgraded minor.
371
+ const remaining = new Set(findings.map(findingKey));
372
+ const earlier = new Map(rounds.flatMap((round) => round.findings.map((finding) => [findingKey(finding), finding])));
373
+ const fixed = [...earlier].filter(([key]) => !remaining.has(key)).map(([, finding]) => ({ ...finding, disposition: "fixed" }));
374
+ const recorded = [...findings.map((finding) => ({ ...finding, disposition: "unresolved" })), ...fixed];
375
+ if (!keys.length) return { outcome: "CLEAN", iterationCount, findings: recorded, state: { rounds: [] } };
376
+ const last = rounds.at(-1)?.keys;
377
+ const outcome = last && last.length === keys.length && last.every((key, i) => key === keys[i]) ? "STUCK" : iterationCount >= maxIterations ? "ITERATION_CAP" : null;
378
+ return { outcome, iterationCount, findings: recorded, blocking, state: { rounds: [...rounds, { head, keys, findings: blocking }] } };
379
+ }
380
+
381
+ const errorCheck = (check, error, iterationCount, inputs) => ({ check, outcome: error.outcome, iterationCount, reviewerErrors: [`${check}: ${error.message}`.slice(0, 2000)], inputs, findings: [] });
382
+
383
+ /**
384
+ * One run of lane check: gates, then one round of each check. Returns the
385
+ * checks and, once every check has an outcome, the body for Dev
386
+ * (POST /lanes/:id/review); a check still looping returns no body. The
387
+ * caller saves the round (saveLoop) once it is kept: still looping, or
388
+ * recorded; a run that records nothing leaves the loop where it was.
389
+ */
390
+ export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, now }) {
391
+ const critical = flags.critical === true;
392
+ const maxIterations = flags["max-iterations"] === undefined ? MAX_ITERATIONS : Number(flags["max-iterations"]);
393
+ if (!Number.isInteger(maxIterations) || maxIterations < 1 || maxIterations > 100)
394
+ throw new CliError("USAGE", "--max-iterations needs a whole number from 1 to 100.", 2);
395
+ const gates = [flags.gate ?? []].flat();
396
+ if (gates.some((x) => typeof x !== "string" || !x.trim())) throw new CliError("USAGE", "--gate needs a command, e.g. --gate 'npm test'.", 2);
397
+ const changed = await gatesReceipt(gates, { cwd, current, store, diff, run: gate, ...(now ? { now } : {}) });
398
+ if (!changed.text.trim()) throw new CliError("LANE_DIFF_EMPTY", `${ref}: this worktree has no change against origin/main, so there is nothing to review.`, 1);
399
+ const runtime = lane.launch?.runtime === "codex" ? "codex" : "claude";
400
+ const runner = { runtime, model: lane.launch?.model, profile: lane.launch?.profile };
401
+ const tooLarge = changed.text.length > MAX_DIFF_CHARS
402
+ ? new ReviewerError(UNAVAILABLE, `the diff is ${changed.text.length} characters; a reviewer takes at most ${MAX_DIFF_CHARS}. Split the lane.`)
403
+ : null;
404
+ const loop = (await store.read(REVIEW_LOOP)) ?? {};
405
+ const laneLoop = loop[ref]?.branch === current.branch ? loop[ref].checks ?? {} : {};
406
+ const nextLoop = { ...laneLoop };
407
+ const round = (check, findings, inputs) => {
408
+ const result = loopRound(laneLoop[check], findings, { head: current.commit, maxIterations });
409
+ nextLoop[check] = result.state;
410
+ return { check, outcome: result.outcome, iterationCount: result.iterationCount, reviewerErrors: [], inputs, findings: result.findings, blocking: result.blocking ?? [] };
411
+ };
412
+ const firstRound = (check) => (laneLoop[check]?.rounds?.length ?? 0) + 1;
413
+
414
+ // Rules (DEV-REV-7): never NOT_REQUIRED, never a partial clause set.
415
+ let rules;
416
+ let gathered = null;
417
+ try {
418
+ if (tooLarge) throw tooLarge;
419
+ gathered = await ruleClauses(ref, { request, freeze, paths: changed.paths, deltaGather });
420
+ } catch (error) {
421
+ if (!(error instanceof ReviewerError)) throw error;
422
+ rules = errorCheck("rules", error, firstRound("rules"), { clauseIds: [], deltaGatherId: null, clauseMapGatherId: freeze?.clauseMap?.gatherId ?? null });
423
+ }
424
+ if (!rules) {
425
+ const inputs = { clauseIds: gathered.clauseIds, clauseMapGatherId: gathered.clauseMapGatherId, deltaGatherId: gathered.deltaGatherId, runtime, diffDigest: diffDigest(changed.text) };
426
+ try {
427
+ const findings = await reviewer("rules", { ...runner, prompt: reviewerPrompt("rules", { diff: changed.text, clauses: gathered.clauses }), clauseIds: gathered.clauseIds });
428
+ rules = round("rules", findings, inputs);
429
+ } catch (error) {
430
+ if (!(error instanceof ReviewerError)) throw error;
431
+ rules = errorCheck("rules", error, firstRound("rules"), inputs);
432
+ }
433
+ }
434
+
435
+ // Figma (DEV-REV-9): only a lane with a frontend side.
436
+ let figma;
437
+ if (!["frontend", "both"].includes(lane.side)) figma = { check: "figma", outcome: "NOT_APPLICABLE", iterationCount: 0, reviewerErrors: [], inputs: { side: lane.side ?? null }, findings: [] };
438
+ else {
439
+ const boundary = freeze?.boundaries?.figma;
440
+ try {
441
+ if (!Array.isArray(boundary) || !boundary.length)
442
+ throw new ReviewerError("CRASH", `${ref} is a ${lane.side} lane, but its Freeze names no Figma boundary (boundaries.figma), so there is no frame to check. Set it with nodii-dev lane freeze swap ${ref} --section boundaries.`);
443
+ let checked;
444
+ try { checked = await figmaFindings(boundary, { catalog, check: designCheck }); }
445
+ catch (error) {
446
+ if (error instanceof ReviewerError) throw error;
447
+ throw new ReviewerError(["FIGMA_TOKEN_REQUIRED", "DS_CATALOG_UNAVAILABLE"].includes(error?.code) ? UNAVAILABLE : "CRASH", `design check failed (${error?.code ?? "ERROR"}: ${error?.message ?? error})`);
448
+ }
449
+ figma = round("figma", checked.findings, checked.inputs);
450
+ } catch (error) {
451
+ if (!(error instanceof ReviewerError)) throw error;
452
+ figma = errorCheck("figma", error, firstRound("figma"), { frames: [], frameComparison: "not_built" });
453
+ }
454
+ }
455
+
456
+ // Code (DEV-REV-10): only with --critical, the agent's call from the diff (MW2-47).
457
+ let code;
458
+ if (!critical) code = { check: "code", outcome: "NOT_REQUIRED", iterationCount: 0, reviewerErrors: [], inputs: { critical: false }, notRequired: CODE_NOT_REQUIRED, findings: [] };
459
+ else {
460
+ const inputs = { critical: true, clauseIds: gathered?.clauseIds ?? [], runtime, diffDigest: diffDigest(changed.text) };
461
+ try {
462
+ if (tooLarge) throw tooLarge;
463
+ const findings = await reviewer("code", { ...runner, prompt: reviewerPrompt("code", { diff: changed.text, clauses: gathered?.clauses ?? [] }) });
464
+ code = round("code", findings, inputs);
465
+ } catch (error) {
466
+ if (!(error instanceof ReviewerError)) throw error;
467
+ code = errorCheck("code", error, firstRound("code"), inputs);
468
+ }
469
+ }
470
+
471
+ const checks = [rules, figma, code];
472
+ const saveLoop = () => store.write(REVIEW_LOOP, { ...loop, [ref]: { branch: current.branch, checks: nextLoop } });
473
+ const digest = diffDigest(changed.text);
474
+ if (checks.some((x) => x.outcome === null)) return { checks, body: null, maxIterations, saveLoop, digest };
475
+ const reviewerErrors = checks.flatMap((x) => x.reviewerErrors);
476
+ const body = {
477
+ base: current.base,
478
+ head: current.commit,
479
+ appliedPatches: [],
480
+ unresolvedProposals: [],
481
+ reviewerErrors,
482
+ findings: checks.flatMap((x) => x.findings).slice(0, 500),
483
+ checks: checks.map(({ check, outcome, iterationCount, reviewerErrors: errors, inputs, notRequired }) => ({ check, outcome, iterationCount, reviewerErrors: errors, inputs, ...(notRequired ? { notRequired } : {}) })),
484
+ via: "nodii-dev",
485
+ };
486
+ return { checks, body, maxIterations, saveLoop, digest };
487
+ }
488
+
489
+ /** A REVIEW.json carrying checks is Dev's check contract: exactly the three, each well formed. */
490
+ export function checkReviewChecks(body) {
491
+ const fail = (message) => { throw new CliError("REVIEW_FILE_INVALID", `The review file's checks are invalid: ${message}`, 2); };
492
+ if (!Array.isArray(body.checks)) fail("checks must be an array");
493
+ for (const key of ["iterationCount", "exitReason", "notRequired"])
494
+ if (body[key] !== undefined) fail(`a run with checks carries no top-level ${key} (Dev computes the run outcome)`);
495
+ const names = body.checks.map((x) => x?.check);
496
+ if (names.length !== 3 || CHECKS.some((name) => names.filter((x) => x === name).length !== 1)) fail("it needs exactly one each of rules, figma and code");
497
+ for (const x of body.checks) {
498
+ if (!CHECK_OUTCOMES.includes(x.outcome)) fail(`${x.check} has outcome ${x.outcome}`);
499
+ if (!Number.isInteger(x.iterationCount) || x.iterationCount < 0) fail(`${x.check} needs a whole iterationCount`);
500
+ if (!Array.isArray(x.reviewerErrors) || !x.inputs || typeof x.inputs !== "object") fail(`${x.check} needs reviewerErrors and inputs`);
501
+ if (x.check === "rules" && ["NOT_REQUIRED", "NOT_APPLICABLE"].includes(x.outcome)) fail("the rules check is never NOT_REQUIRED or NOT_APPLICABLE");
502
+ if (x.outcome === "NOT_REQUIRED" && !x.notRequired) fail(`${x.check} NOT_REQUIRED needs a notRequired citation`);
503
+ }
504
+ return body;
505
+ }
506
+
507
+ const counts = (findings) => {
508
+ const n = (severity) => findings.filter((x) => x.severity === severity && x.disposition !== "fixed").length;
509
+ return `${n("blocker")} blocker, ${n("major")} major, ${n("minor")} minor`;
510
+ };
511
+ const findingLine = (x) => ` ${x.severity}\t${x.clauseId ?? (x.frameUrl ? `${x.frameUrl} [${x.state}]` : "-")}\t${x.path ? `${x.path}${x.line ? `:${x.line}` : ""}\t` : ""}${x.summary}`;
512
+
513
+ /** One line per check, then its open findings. */
514
+ export function checkLines(checks, maxIterations) {
515
+ return checks.flatMap((x) => [
516
+ `${x.check}\t${x.outcome ?? `NOT CLEAN, round ${x.iterationCount} of ${maxIterations}`}\t${x.iterationCount} iteration(s)\t${counts(x.findings)}`,
517
+ ...x.reviewerErrors.map((error) => ` error: ${error}`),
518
+ ...x.findings.filter((f) => f.disposition !== "fixed").map(findingLine),
519
+ ]);
520
+ }
package/dist/safety.js CHANGED
@@ -24,7 +24,7 @@ async function git(cwd, ...args) {
24
24
  return (await execFileAsync("git", args, { cwd, encoding: "utf8" })).stdout.trim();
25
25
  }
26
26
 
27
- async function gitPrivatePath(cwd, name) {
27
+ export async function gitPrivatePath(cwd, name) {
28
28
  return git(cwd, "rev-parse", "--path-format=absolute", "--git-path", name);
29
29
  }
30
30
 
package/dist/tune.js CHANGED
@@ -269,12 +269,36 @@ function summaryText(run) {
269
269
  return lines.join("\n");
270
270
  }
271
271
 
272
+ function missedText({ data }) {
273
+ if (!data.length) return "No missed triggers.";
274
+ const byDocument = new Map();
275
+ for (const item of data) byDocument.set(item.documentCode, [...(byDocument.get(item.documentCode) ?? []), item]);
276
+ return [...byDocument].sort(([a], [b]) => a.localeCompare(b)).flatMap(([code, items]) => [
277
+ `${code}: ${items.length} missed trigger${items.length === 1 ? "" : "s"}`,
278
+ ...items.map((x) => ` ${x.clauseId}\t${x.laneKey}\t${x.severity}\t${x.createdAt}\t${x.summary}\t(run ${x.reviewRunId}, finding ${x.findingId})`),
279
+ ]).join("\n");
280
+ }
281
+
272
282
  /**
273
283
  * `nodii-dev gather tune cases|replay|start|trial|exec|finalize|runs`: the
274
284
  * client for Dev's Gather tuning API (AH-11). Scoring is Dev's; the CLI only
275
285
  * runs the pickers and assembles each trial's Clause map read-only.
276
286
  */
277
287
  export async function tuneCommand(action, args, flags, { request = devRequest, pick = pickDocuments, warm = warmPicker, corpus } = {}) {
288
+ // DEV-REV-18: clauses a review cited that Gather never served the lane.
289
+ if (action === "missed") {
290
+ for (const flag of ["document", "since"])
291
+ if (flags[flag] !== undefined && (typeof flags[flag] !== "string" || !flags[flag].trim())) throw new CliError("USAGE", `--${flag} needs a value`, 2);
292
+ if (flags.since !== undefined && Number.isNaN(Date.parse(flags.since))) throw new CliError("USAGE", "--since needs an ISO time, e.g. 2026-10-01T00:00:00Z", 2);
293
+ const items = [];
294
+ let cursor;
295
+ do {
296
+ const page = await request("GET", `/api/v1/gather/missed-triggers${query({ document: flags.document, since: flags.since, cursor })}`);
297
+ items.push(...(page.data ?? []));
298
+ cursor = page.nextCursor ?? undefined;
299
+ } while (cursor);
300
+ return { payload: { data: items }, human: missedText };
301
+ }
278
302
  if (action === "cases") {
279
303
  const payload = await request("GET", "/api/v1/gather/tuning/cases");
280
304
  return { payload, human: (p) => (p.data ?? []).length
@@ -391,5 +415,5 @@ export async function tuneCommand(action, args, flags, { request = devRequest, p
391
415
  const payload = await request("POST", `/api/v1/gather/tuning/runs/${encode(runId)}/finalize`, body);
392
416
  return { payload, human: (p) => summaryText(p.data) };
393
417
  }
394
- throw new CliError("USAGE", "gather tune cases|replay <case-id>|start --cases all|ID,ID --corpus-ref REF [--pickers P,Q]|trial <run-id> --case ID --picker P --iteration N [--documents A,B]|exec <run-id> [--pickers P,Q]|finalize <run-id> [--supersedes <run-id> --reason TEXT]|runs", 2);
418
+ throw new CliError("USAGE", "gather tune missed [--document CODE] [--since ISO]|cases|replay <case-id>|start --cases all|ID,ID --corpus-ref REF [--pickers P,Q]|trial <run-id> --case ID --picker P --iteration N [--documents A,B]|exec <run-id> [--pickers P,Q]|finalize <run-id> [--supersedes <run-id> --reason TEXT]|runs", 2);
395
419
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.52",
3
+ "version": "0.6.54",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {