@nodii/dev 0.6.117 → 0.6.119

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/cli.js CHANGED
@@ -60,6 +60,8 @@ import {
60
60
  readLaneReads,
61
61
  figmaWithdrawItemsText,
62
62
  WITHDRAW_ITEMS_USAGE,
63
+ removedNodesFrom,
64
+ removedNodesInReads,
63
65
  withdrawItemsFrom,
64
66
  checkSubmitPayload,
65
67
  assertContext,
@@ -70,7 +72,7 @@ import {
70
72
  scopesFrom,
71
73
  conformanceLines,
72
74
  } from "./figma.js";
73
- export { figmaLock, figmaWithdrawItems, figmaWithdrawItemsText, submitMode, withdrawItemsFrom } from "./figma.js";
75
+ export { figmaLock, figmaWithdrawItems, figmaWithdrawItemsText, removedNodesFrom, removedNodesInReads, submitMode, withdrawItemsFrom } from "./figma.js";
74
76
  import { tuneCommand } from "./tune.js";
75
77
  import { TUNING_MODELS, pickerModelName, pickerPin, measurePickerLatency, pickTimingStats, pickTimingText, pickTimingsPath, readPickTimings } from "./gather.js";
76
78
  import { docsCommand, rulebookCommand, rulesCommand } from "./upload.js";
@@ -231,12 +233,15 @@ Usage: nodii-dev <command> [options] [--json]
231
233
  # lane's agent, even from a stopped lane. The target can hold no other lock on
232
234
  # the file (TARGET_HOLDS_FILE_LOCK)
233
235
  figma withdraw CHANGE_SET # holder takes back a submit: in_review -> editing (or a re-submit -> applying)
234
- figma withdraw CHANGE_SET --items ID[,ID] --reason TEXT [--lane-reads FILE]
236
+ figma withdraw CHANGE_SET --items ID[,ID] --reason TEXT [--lane-reads FILE [--removed-nodes NODE[,NODE]]]
235
237
  # holder, coordinator or operator: take rejected items (item or node ids)
236
238
  # out of an applying set so apply takes the approved ones. Each item's nodes
237
239
  # must be back at the set's base version first (CHANGE_ITEM_NOT_AT_BASE lists
238
240
  # the ones that differ); a withdrawn item never publishes, and the scopes only
239
- # it sat in are released
241
+ # it sat in are released. --removed-nodes: nodes you deleted (sent as
242
+ # removedNodeIds); Dev takes each as gone when your reads list it in gone and
243
+ # its /nodes entry is null or the empty ghost Figma answers for a deleted
244
+ # component or variant
240
245
  figma resubmit CHANGE_SET PAYLOAD.json [--sync] [--dry-run] [--lane-reads FILE]
241
246
  # holder re-submits every rejected item: applying -> in_review, round + 1;
242
247
  # each item needs context, each variant name and context; writeUp optional
@@ -409,6 +414,13 @@ Usage: nodii-dev <command> [options] [--json]
409
414
  lane review <key> --file REVIEW.json # base/head, outcome and clause-cited findings
410
415
  lane review <key> --not-required --decision DEC-nnnn|--question ID|--quote TEXT --at ISO-TIME
411
416
  # no review needed for this diff: cites the ruling Dev validates (hub-58)
417
+ lane review <key> --treat FINDING_ID=declined --ruling DEC-nnnn
418
+ lane review <key> --treat FINDING_ID=deferred --ruling ISSUE-KEY
419
+ # P-21 treatment of a finding the last lane check round printed (f-xxxxxxxx),
420
+ # repeatable, for that round of this commit only (MW2-44): declined cites the
421
+ # locked decision that settles it (MW4-27), deferred an open issue. Records the
422
+ # round once nothing blocks; Dev checks each citation and refuses code-check
423
+ # findings, blockers, and security, tenancy, PII and money findings (MW2-41)
412
424
  lane check <key> [--gate CMD ...] [--critical] [--max-iterations N]
413
425
  # from the lane's worktree: the rules, Figma and code checks over the
414
426
  # diff against origin/main (DEV-REV); --gate runs gates 1-5 in order
@@ -1453,8 +1465,19 @@ export async function main(argv = process.argv.slice(2)) {
1453
1465
  }
1454
1466
  if (action === "withdraw") {
1455
1467
  if (rest.length > 1) throw new CliError("USAGE", `figma withdraw CHANGE_SET | ${WITHDRAW_ITEMS_USAGE}`, 2);
1456
- if (f.items !== undefined)
1457
- return emit(await figmaWithdrawItems(rest[0], withdrawItemsFrom(f), f.reason === true ? "" : f.reason, f["lane-reads"] ? { laneReads: await readLaneReads(f["lane-reads"]) } : {}).catch((error) => { throw laneReadsRefusal(error); }), json, (p) => figmaWithdrawItemsText(rest[0], p.data));
1468
+ if (f.items !== undefined) {
1469
+ const items = withdrawItemsFrom(f);
1470
+ const removedNodeIds = removedNodesFrom(f);
1471
+ const laneReads = f["lane-reads"] ? await readLaneReads(f["lane-reads"]) : undefined;
1472
+ if (removedNodeIds) removedNodesInReads(removedNodeIds, laneReads);
1473
+ return emit(
1474
+ await figmaWithdrawItems(rest[0], items, f.reason === true ? "" : f.reason, { laneReads, removedNodeIds }).catch((error) => { throw laneReadsRefusal(error); }),
1475
+ json,
1476
+ (p) => figmaWithdrawItemsText(rest[0], p.data),
1477
+ );
1478
+ }
1479
+ if (f["removed-nodes"] !== undefined)
1480
+ throw new CliError("USAGE", `--removed-nodes goes with --items: ${WITHDRAW_ITEMS_USAGE}`, 2);
1458
1481
  if (f.reason !== undefined)
1459
1482
  throw new CliError("USAGE", `--reason goes with --items: ${WITHDRAW_ITEMS_USAGE} (a whole submit is withdrawn with: figma withdraw CHANGE_SET)`, 2);
1460
1483
  return emit(await figmaWithdraw(rest[0]), json, (p) => `Withdrew ${rest[0]}; it is back in ${p.data?.state ?? "editing"}.`);
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.117";
7
+ export const VERSION = "0.6.119";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
package/dist/figma.js CHANGED
@@ -952,7 +952,7 @@ export function figmaPublishPlanText(plan) {
952
952
  ].join("\n");
953
953
  }
954
954
 
955
- export const WITHDRAW_ITEMS_USAGE = "figma withdraw CHANGE_SET --items ID[,ID] --reason TEXT";
955
+ export const WITHDRAW_ITEMS_USAGE = "figma withdraw CHANGE_SET --items ID[,ID] --reason TEXT [--lane-reads FILE [--removed-nodes NODE[,NODE]]]";
956
956
 
957
957
  /** `--items A,B --items C` → ["A", "B", "C"], each an item id or a Figma node id. */
958
958
  export function withdrawItemsFrom(flags) {
@@ -963,6 +963,32 @@ export function withdrawItemsFrom(flags) {
963
963
  return items;
964
964
  }
965
965
 
966
+ /**
967
+ * `--removed-nodes 47:9554,47-9501` → the Figma node ids the lane deleted
968
+ * (a figma.com link's 47-9501 is 47:9501), sent as removedNodeIds (hub-312).
969
+ * Dev takes each as absent only with the lane's reads: in their `gone`, with a
970
+ * /nodes entry at the version read that is null or the empty ghost Figma
971
+ * answers for a deleted component or variant. So it goes with --lane-reads.
972
+ */
973
+ export function removedNodesFrom(flags) {
974
+ if (flags["removed-nodes"] === undefined) return undefined;
975
+ const ids = [...new Set([flags["removed-nodes"]].flat().flatMap(nodeIdList).map(nodeId))];
976
+ if (!ids.length) throw new CliError("USAGE", `--removed-nodes needs Figma node ids: ${WITHDRAW_ITEMS_USAGE}`, 2);
977
+ const bad = ids.filter((x) => !BARE_NODE_ID.test(x));
978
+ if (bad.length) throw new CliError("USAGE", `--removed-nodes takes Figma node ids (like 47:9554), not: ${bad.join(", ")}`, 2);
979
+ if (!flags["lane-reads"] || flags["lane-reads"] === true)
980
+ throw new CliError("USAGE", `--removed-nodes goes with --lane-reads FILE: Dev takes a node as deleted only when your reads show it gone. ${WITHDRAW_ITEMS_USAGE}`, 2);
981
+ return ids;
982
+ }
983
+
984
+ /** Each removed node must be in the reads' `gone`, or Dev refuses it; say so before calling Dev. */
985
+ export function removedNodesInReads(ids, reads) {
986
+ const gone = new Set(Array.isArray(reads?.gone) ? reads.gone : []);
987
+ const missing = ids.filter((x) => !gone.has(x));
988
+ if (missing.length)
989
+ throw new CliError("USAGE", `--removed-nodes ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} not in your lane reads' gone list. Read ${missing.length === 1 ? "it" : "them"} through the Figma MCP and list ${missing.length === 1 ? "it" : "them"} in gone if deleted, then run this again. Nothing was sent.`, 2);
990
+ }
991
+
966
992
  const indented = (ids) => ids.map((x) => ` ${x}`);
967
993
 
968
994
  // Dev's refusals of withdrawDesignChangeItems, said in terms of what to do next.
@@ -972,13 +998,22 @@ const WITHDRAW_ITEMS_REFUSALS = {
972
998
  INVALID_CHANGE_SET_STATE: (id, message) => `${message}\nItems are withdrawn only while ${id} is applying (decided, with rejected items). Check it with: nodii-dev figma changeset show ${id}`,
973
999
  CHANGE_SET_HAS_NO_BASE_VERSION: (id, message) => `${message}\nDev can't tell whether the items' nodes are back at base, so it can't withdraw them.`,
974
1000
  CHANGE_SET_CHANGED: (id, message) => `${message}\n${id} changed while withdrawing; read it with nodii-dev figma changeset show ${id} and run this again.`,
975
- CHANGE_ITEM_NOT_AT_BASE: (id, message, d) => {
976
- const nodes = d?.nodeIds ?? [];
977
- if (!nodes.length) return message;
1001
+ CHANGE_ITEM_NOT_AT_BASE: (id, message, d, removed = []) => {
1002
+ const all = d?.nodeIds ?? [];
1003
+ if (!all.length) return message;
1004
+ // A node named in --removed-nodes that Dev still finds: Dev's own words say
1005
+ // why (not in the reads' gone, or still in the file). The rest differ from base.
1006
+ const named = all.filter((n) => removed.includes(n));
1007
+ const nodes = all.filter((n) => !removed.includes(n));
978
1008
  return [
979
- `${nodes.length} node(s) of ${d?.changeSetId ?? id} still differ from its base version${d?.baseVersion ? ` (${d.baseVersion})` : ""}:`,
980
- ...indented(nodes),
981
- "Put each back as it was at base (remove it if the set added it), then run this again. Nothing was withdrawn.",
1009
+ ...(named.length ? [message] : []),
1010
+ ...(nodes.length
1011
+ ? [
1012
+ `${nodes.length} node(s) of ${d?.changeSetId ?? id} still differ from its base version${d?.baseVersion ? ` (${d.baseVersion})` : ""}:`,
1013
+ ...indented(nodes),
1014
+ "Put each back as it was at base (remove it if the set added it), then run this again. Nothing was withdrawn.",
1015
+ ]
1016
+ : ["Nothing was withdrawn."]),
982
1017
  ].join("\n");
983
1018
  },
984
1019
  CHANGE_ITEM_NOT_REJECTED: (id, message, d) => {
@@ -1004,14 +1039,20 @@ const WITHDRAW_ITEMS_REFUSALS = {
1004
1039
  * must already be back at the set's base version; apply then takes the
1005
1040
  * approved items alone, and the scopes only those items sat in are released.
1006
1041
  */
1007
- export async function figmaWithdrawItems(id, items, reason, { request = devRequest, laneReads } = {}) {
1042
+ export async function figmaWithdrawItems(id, items, reason, { request = devRequest, laneReads, removedNodeIds } = {}) {
1008
1043
  if (!id || !items?.length) throw new CliError("USAGE", WITHDRAW_ITEMS_USAGE, 2);
1009
1044
  if (typeof reason !== "string" || !reason.trim()) throw new CliError("USAGE", `--reason needs a reason: ${WITHDRAW_ITEMS_USAGE}`, 2);
1045
+ const removed = removedNodeIds?.length ? removedNodeIds : null;
1010
1046
  try {
1011
- return await request("POST", `/api/v1/design/change-sets/${encode(id)}/withdraw-items`, { items, reason: reason.trim(), ...(laneReads ? { laneReads } : {}) });
1047
+ return await request("POST", `/api/v1/design/change-sets/${encode(id)}/withdraw-items`, {
1048
+ items,
1049
+ reason: reason.trim(),
1050
+ ...(removed ? { removedNodeIds: removed } : {}),
1051
+ ...(laneReads ? { laneReads } : {}),
1052
+ });
1012
1053
  } catch (error) {
1013
1054
  const say = WITHDRAW_ITEMS_REFUSALS[error?.code];
1014
- if (say) throw new CliError(error.code, say(id, error.message, error.details), error.exitCode ?? 1, error.details);
1055
+ if (say) throw new CliError(error.code, say(id, error.message, error.details, removed ?? []), error.exitCode ?? 1, error.details);
1015
1056
  throw scopeRefusal(error, id) ?? error;
1016
1057
  }
1017
1058
  }
package/dist/flags.js CHANGED
@@ -56,7 +56,7 @@ export const COMMAND_FLAGS = {
56
56
  "lane verify": ["dev-check", "checks"],
57
57
  "repo policy": ["root"],
58
58
  "repo lint": ["root"],
59
- "lane review": ["file", "not-required", "decision", "question", "quote", "at"],
59
+ "lane review": ["file", "not-required", "decision", "question", "quote", "at", "treat", "ruling"],
60
60
  "lane non-issue": ["reason", "reroute", "evidence", "commits", "branch"],
61
61
  "drift file": ["service", "severity", "summary", ...BODY, "related-artifact-type", "related-artifact-id"],
62
62
  "drift accept": ["reason", "decision", "resolution-md", "related-decision-id"],
@@ -67,7 +67,7 @@ export const COMMAND_FLAGS = {
67
67
  "docs ratify": ["domain", "decision", ...WAIT],
68
68
  "figma submit": ["file", "figma-version", ...SUBMIT_MODE, "dry-run", "lane-reads"],
69
69
  "figma resubmit": [...SUBMIT_MODE, "dry-run", "lane-reads"],
70
- "figma withdraw": ["items", "reason", "lane-reads"],
70
+ "figma withdraw": ["items", "reason", "lane-reads", "removed-nodes"],
71
71
  "figma lane-reads-script": ["nodes"],
72
72
  "figma abandon": ["file"],
73
73
  // hub-260: list takes these; show takes none.
package/dist/lanes.js CHANGED
@@ -18,7 +18,7 @@ import { SWAP_BOUNDARIES, componentsForScope, guidelineLookup, laneFigmaScope, l
18
18
  import { designCheck } from "./design.js";
19
19
  import { LANE_ENV_FIX, laneEnvProblem, laneEnvReport } from "./lane-env.js";
20
20
  import { closeoutLane } from "./closeout.js";
21
- import { GATES_RECEIPT, REVIEW_FILE, checkLines, checkReviewChecks, diffDigest, laneDiff, privateStore, repoGeneratedPaths, runLaneCheck, runOutcome, worktreeCommitted } from "./review.js";
21
+ import { GATES_RECEIPT, REVIEW_FILE, REVIEW_LAST, REVIEW_LOOP, checkLines, checkReviewChecks, citationText, diffDigest, findingId, laneDiff, privateStore, repoGeneratedPaths, runBody, runLaneCheck, runOutcome, treatChecks, treatable, worktreeCommitted } from "./review.js";
22
22
 
23
23
  const execFileAsync = promisify(execFile);
24
24
  const via = { via: "nodii-dev" };
@@ -241,6 +241,28 @@ export async function reviewBody(flags, read = (path) => readFile(path, "utf8"))
241
241
  return { ...body, ...via };
242
242
  }
243
243
 
244
+ /**
245
+ * NODII-DEV-CLI-74 (P-21): --treat FINDING_ID=declined|deferred, repeatable,
246
+ * with one --ruling. declined cites the locked decision that settles the
247
+ * finding (DEC-nnnn; MW4-27: a ruling binds only once it is a decision);
248
+ * deferred cites an open issue (ISSUE-KEY). Dev validates the citation.
249
+ */
250
+ export function treatmentFlags(flags) {
251
+ const usage = "--treat FINDING_ID=declined|deferred (the f-xxxxxxxx id lane check prints) with --ruling DEC-nnnn (the locked decision that settles it) for declined, or --ruling ISSUE-KEY (an open issue) for deferred.";
252
+ const items = [flags.treat].flat().map((value) => {
253
+ const match = typeof value === "string" ? /^(f-[0-9a-f]{8})=(declined|deferred)$/.exec(value.trim()) : null;
254
+ if (!match) throw new CliError("USAGE", usage, 2);
255
+ return { id: match[1], disposition: match[2] };
256
+ });
257
+ const dispositions = [...new Set(items.map((x) => x.disposition))];
258
+ if (dispositions.length !== 1) throw new CliError("USAGE", `One call treats findings one way, with one citation: run declined and deferred separately. ${usage}`, 2);
259
+ const [disposition] = dispositions;
260
+ if (["quote", "at", "question", "decision"].some((key) => flags[key] !== undefined)) throw new CliError("USAGE", `A treatment cites only --ruling: a quote or a question binds only once it is a decision (MW4-27). ${usage}`, 2);
261
+ const ruling = typeof flags.ruling === "string" ? flags.ruling.trim() : "";
262
+ if (!ruling) throw new CliError("USAGE", usage, 2);
263
+ return items.map((x) => ({ ...x, treatment: disposition === "deferred" ? { issue: ruling } : { decision: ruling } }));
264
+ }
265
+
244
266
  /**
245
267
  * hub-58 (30 Oct): a NOT-REQUIRED record cites exactly one ruling Dev can
246
268
  * check: --decision ID, --question ID, or --quote TEXT with --at ISO-TIME.
@@ -789,6 +811,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
789
811
  const diff = (cwd) => (checkDeps.diff ?? laneDiff)(cwd, { generatedPaths });
790
812
  const run = await runLaneCheck(ref, flags, {
791
813
  request, lane, freeze, current, cwd: context.worktree, store,
814
+ ...(checkDeps.exceptions ? { exceptions: checkDeps.exceptions } : {}),
792
815
  diff,
793
816
  deltaGather: checkDeps.deltaGather ?? ((key, paths, pick) => laneCommand("gather", [key], deltaGatherFlags(paths, pick), deps)),
794
817
  catalog: checkDeps.catalog ?? catalog,
@@ -802,13 +825,19 @@ export async function laneCommand(action, args, flags, deps = {}) {
802
825
  // hooks. Reported, never blocking: the check itself cannot fix a process.
803
826
  const env = await laneEnvReport([{ key: lane.key ?? ref, worktrees }], checkDeps.processes ? { processes: checkDeps.processes } : {}).catch((error) => ({ error: error?.message ?? String(error) }));
804
827
  const lines = [...checkLines(run.checks, run.maxIterations), ...laneEnvLines(env)];
828
+ // NODII-DEV-CLI-74: the round is kept so a P-21 treatment can be applied to it.
829
+ const last = (await store.read(REVIEW_LAST).catch(() => null)) ?? {};
830
+ await store.write(REVIEW_LAST, { ...last, [ref]: { branch: current.branch, base: current.base, head: current.commit, digest: run.digest, maxIterations: run.maxIterations, checks: run.checks } });
831
+ const treatHint = run.checks.some((x) => x.blocking?.length)
832
+ ? [`A major finding (not a code-check finding or a blocker) that a locked decision already settles, or that an open issue carries: nodii-dev lane review ${ref} --treat FINDING_ID=declined --ruling DEC-nnnn (or =deferred --ruling ISSUE-KEY), for this round only. Dev checks the citation (P-21).`]
833
+ : [];
805
834
  // A check still looping records nothing: the agent fixes and reruns (MW2-41).
806
835
  if (!run.body) {
807
836
  await run.saveLoop();
808
837
  const open = run.checks.filter((x) => x.outcome === null).map((x) => x.check);
809
838
  return {
810
839
  payload: { data: { recorded: false, outcome: "NOT_CLEAN", checks: run.checks, laneEnv: env } },
811
- 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"),
840
+ human: [...lines, `run: NOT CLEAN, nothing recorded. Fix the blocking ${open.join(" and ")} finding(s), commit, and rerun nodii-dev lane check ${ref}.`, ...treatHint].join("\n"),
812
841
  exitCode: 1,
813
842
  };
814
843
  }
@@ -825,7 +854,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
825
854
  const outcome = runOutcome(run.body.checks);
826
855
  return {
827
856
  payload: { ...payload, reviewFile: file, laneEnv: env },
828
- human: [...lines, `run: ${outcome === "CLEAN" ? "CLEAN" : "NOT CLEAN"}, recorded on ${ref} (${file})`].join("\n"),
857
+ human: [...lines, `run: ${outcome === "CLEAN" ? "CLEAN" : "NOT CLEAN"}, recorded on ${ref} (${file})`, ...(outcome === "CLEAN" ? [] : treatHint)].join("\n"),
829
858
  exitCode: outcome === "CLEAN" ? 0 : 1,
830
859
  };
831
860
  }
@@ -1059,6 +1088,61 @@ export async function laneCommand(action, args, flags, deps = {}) {
1059
1088
  }
1060
1089
  if (action === "land") await assertNothingPending(ref);
1061
1090
  if (action === "land") return { payload: await request("POST", `/api/v1/lanes/${encode(id)}/land`, via), human: `${ref}: recorded on main.` };
1091
+ if (action === "review" && flags.treat !== undefined) {
1092
+ if (flags.file !== undefined || flags["not-required"] !== undefined) throw new CliError("USAGE", "--treat goes alone: not with --file or --not-required.", 2);
1093
+ const items = treatmentFlags(flags);
1094
+ const context = await gitContext();
1095
+ const current = { ...(await reviewContext()), branch: context.branch };
1096
+ const store = checkDeps.store ?? privateStore(context.worktree);
1097
+ const lastAll = (await store.read(REVIEW_LAST).catch(() => null)) ?? {};
1098
+ const last = lastAll[ref];
1099
+ // MW2-44: a treatment counts only for the round it was given on, which
1100
+ // must be this exact commit; it is never carried to another round.
1101
+ const rerun = (why) => new CliError("REVIEW_ROUND_STALE", `${ref}: ${why}, so nothing was treated. Run nodii-dev lane check ${ref}, then treat its findings by the ids it prints.`, 1);
1102
+ if (!last || last.branch !== current.branch || last.head !== current.commit || last.base !== current.base) throw rerun("the last lane check round is not for this commit");
1103
+ const found = new Map(last.checks.flatMap((check) => check.findings.map((finding) => [findingId(finding), finding])));
1104
+ const missing = items.filter((x) => !found.has(x.id));
1105
+ if (missing.length) throw new CliError("REVIEW_FINDING_NOT_FOUND", `${ref}: the last lane check round (head ${last.head}) has no finding ${missing.map((x) => x.id).join(", ")}; nothing was treated.`, 1);
1106
+ // MW2-41: Dev refuses these too; saying so here saves a round trip.
1107
+ const fixOnly = items.filter((x) => !treatable(found.get(x.id)));
1108
+ if (fixOnly.length) throw new CliError("REVIEW_TREATMENT_FORBIDDEN", `${ref}: ${fixOnly.map((x) => x.id).join(", ")} ${fixOnly.length === 1 ? "is a code-check finding or a blocker" : "are code-check findings or blockers"}, which may only be fixed (MW2-41); nothing was treated.`, 1);
1109
+ const generatedPaths = await repoGeneratedPaths(request, context.repo);
1110
+ const committed = await (checkDeps.committed ?? worktreeCommitted)(context.worktree);
1111
+ const digest = diffDigest((await (checkDeps.diff ?? laneDiff)(context.worktree, { generatedPaths })).text);
1112
+ if (!committed || digest !== last.digest) throw rerun("the worktree changed since that round");
1113
+ const treatments = Object.fromEntries(items.map((x) => [x.id, { disposition: x.disposition, treatment: x.treatment }]));
1114
+ const checks = treatChecks(last.checks, treatments);
1115
+ const lines = checkLines(checks, last.maxIterations);
1116
+ const named = items.map((x) => `${x.id} ${x.disposition}: ${citationText(x.treatment)}`).join(", ");
1117
+ if (checks.some((x) => x.outcome === null)) {
1118
+ // Kept on this round only, so the other findings can be treated next.
1119
+ await store.write(REVIEW_LAST, { ...lastAll, [ref]: { ...last, checks } });
1120
+ return {
1121
+ payload: { data: { recorded: false, outcome: "NOT_CLEAN", checks } },
1122
+ human: [...lines, `run: NOT CLEAN, nothing recorded. ${named} is set on this round, but ${checks.filter((x) => x.outcome === null).map((x) => x.check).join(" and ")} still has a blocking finding that is not treated: treat it too, or fix it, commit, and rerun nodii-dev lane check ${ref}.`].join("\n"),
1123
+ exitCode: 1,
1124
+ };
1125
+ }
1126
+ const body = runBody(checks, current);
1127
+ const gates = await store.read(GATES_RECEIPT).catch(() => null);
1128
+ const ranGates = gates?.commit === body.head && gates?.base === body.base && Array.isArray(gates.commands) ? gates.commands : [];
1129
+ // Dev checks every citation; nothing is written here unless it records the run.
1130
+ const payload = await recordReview(flags, body, ranGates, context.worktree);
1131
+ const file = await store.write(REVIEW_FILE, body);
1132
+ // A check the treatment made CLEAN starts a new loop, as any CLEAN does.
1133
+ const loop = (await store.read(REVIEW_LOOP).catch(() => null)) ?? {};
1134
+ if (loop[ref]?.branch === current.branch) {
1135
+ const made = checks.filter((x, i) => x.outcome === "CLEAN" && last.checks[i].outcome !== "CLEAN").map((x) => x.check);
1136
+ await store.write(REVIEW_LOOP, { ...loop, [ref]: { ...loop[ref], checks: { ...loop[ref].checks, ...Object.fromEntries(made.map((check) => [check, { rounds: [] }])) } } });
1137
+ }
1138
+ await store.write(REVIEW_LAST, { ...lastAll, [ref]: { ...last, checks } });
1139
+ const outcome = runOutcome(body.checks);
1140
+ return {
1141
+ payload: { ...payload, reviewFile: file },
1142
+ human: [...lines, `run: ${outcome === "CLEAN" ? "CLEAN" : "NOT CLEAN"}, recorded on ${ref} with ${named} (${file})`].join("\n"),
1143
+ exitCode: outcome === "CLEAN" ? 0 : 1,
1144
+ };
1145
+ }
1062
1146
  if (action === "review") return { payload: await recordReview(), human: (p) => `${ref}: ${reviewSummary(p)}.` };
1063
1147
  if (action === "reviews") {
1064
1148
  const payload = await request("GET", `/api/v1/lanes/${encode(id)}`);
@@ -1076,7 +1160,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
1076
1160
  ...(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)` : ""}`),
1077
1161
  ...run.findings.map(
1078
1162
  (finding) =>
1079
- ` ${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}` : ""}`,
1163
+ ` ${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}` : ""}${finding.treatmentKind ? ` (${finding.treatmentKind} ${finding.treatmentRef}, by ${finding.treatedByLabel})` : ""}`,
1080
1164
  ),
1081
1165
  ].join("\n");
1082
1166
  })
package/dist/review.js CHANGED
@@ -7,7 +7,7 @@ import { REVIEW_SESSION_ENV } from "./review-session.js";
7
7
  import { createHash } from "node:crypto";
8
8
  import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
9
9
  import { tmpdir } from "node:os";
10
- import { dirname, join } from "node:path";
10
+ import { basename, dirname, join } from "node:path";
11
11
  import { promisify } from "node:util";
12
12
  import { CliError, encode } from "./core.js";
13
13
  import { pickerPrompt } from "./gather.js";
@@ -21,6 +21,10 @@ export const SEVERITIES = ["blocker", "major", "minor"];
21
21
  export const GATES_RECEIPT = "nodii-gates-receipt.json";
22
22
  export const REVIEW_LOOP = "nodii-review-loop.json";
23
23
  export const REVIEW_FILE = "REVIEW.json";
24
+ /** The last round of lane check, so a treatment can be applied to it without another round. */
25
+ export const REVIEW_LAST = "nodii-review-last.json";
26
+ /** P-21 SETTLED (an operator ruling) and BUG or PARK (an open issue). */
27
+ export const TREATED = ["declined", "deferred"];
24
28
  export const REVIEWER_TIMEOUT_MS = 600_000;
25
29
  export const MAX_ITERATIONS = 5;
26
30
  // About 150k tokens: a diff past this is reviewed by nobody, never in part.
@@ -192,7 +196,7 @@ const clauseText = (clauses) => clauses.map((clause) => [
192
196
  ].join("\n")).join("\n\n");
193
197
 
194
198
  /** The reviewer's whole input: instructions, the clauses, the diff. */
195
- export function reviewerPrompt(check, { diff, clauses = [], generated = [] }) {
199
+ export function reviewerPrompt(check, { diff, clauses = [], generated = [], exceptions = [] }) {
196
200
  const ask = check === "rules"
197
201
  ? [
198
202
  "You are the rules check of a lane review (DEV-REV). You have no tools: judge only the diff and the clauses below.",
@@ -215,9 +219,61 @@ export function reviewerPrompt(check, { diff, clauses = [], generated = [] }) {
215
219
  diff,
216
220
  "```",
217
221
  ...(generated.length ? ["", `## Generated files changed, left out of the diff (A-037: built from source, not reviewed by reading) (${generated.length})`, ...generated] : []),
222
+ ...(exceptions.length ? [
223
+ "",
224
+ `## Exception and leave-out entries on main that name a changed file (${exceptions.length} file(s); the lines around each match)`,
225
+ "These are the files as they are on main, before this diff; the diff above shows any change the lane makes to them. An entry is not a ruling by itself (P-22). When an entry cites a decision (DEC-nnnn) that answers a breach you would report, still report the breach, and name that decision in its detail, so the lane can decline it citing the decision (P-21 SETTLED).",
226
+ ...exceptions.map((x) => `### ${x.path}\n\`\`\`\n${x.excerpt}\n\`\`\``),
227
+ ] : []),
218
228
  ].join("\n");
219
229
  }
220
230
 
231
+ const EXCEPTION_FILE = /(^|\/)[^/]*(exception|leave[-_]?out)[^/]*\.(json|ya?ml|md)$/i;
232
+ const GENERIC_SEGMENTS = new Set(["src", "lib", "test", "tests", "docs", "packages", "components", "component", "index", "utils", "types", "frontend", "backend", "apps", "shared", "common", "styles", "stories", "public", "assets", "scripts", "config", "fixtures"]);
233
+ const squash = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, "");
234
+ const EXCEPTION_CONTEXT = 3;
235
+ const EXCEPTION_MAX_CHARS = 60_000;
236
+
237
+ /**
238
+ * NODII-DEV-CLI-74: the exception and leave-out files as they are on main
239
+ * (the diff's merge base, never the lane's own edits, which the diff shows)
240
+ * whose entries name a changed file (by a path segment, ignoring case,
241
+ * hyphens and underscores), as excerpts around each match. The reviewer
242
+ * otherwise sees only the diff, so an exception already on main is invisible
243
+ * to it. A file that cannot be read is left out; this never fails the check.
244
+ */
245
+ export async function exceptionFiles(cwd, paths, { base = "origin/main", exec = execFileAsync, read } = {}) {
246
+ const git = (args) => exec("git", ["-C", cwd, ...args], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
247
+ const show = read ?? (async (path) => (await git(["show", `${base}:${path}`])).stdout);
248
+ let listed;
249
+ try { listed = (await git(["ls-tree", "-r", "--name-only", base])).stdout.split("\n").filter((path) => EXCEPTION_FILE.test(path)); }
250
+ catch { return []; }
251
+ const needles = [...new Set(paths.flatMap((path) => path.split("/").map((segment, i, all) => squash(i === all.length - 1 ? segment.replace(/\.[^.]+$/, "") : segment))))]
252
+ .filter((needle) => needle.length >= 5 && !GENERIC_SEGMENTS.has(needle));
253
+ if (!needles.length) return [];
254
+ const out = [];
255
+ let total = 0;
256
+ for (const path of listed.slice(0, 200)) {
257
+ let text;
258
+ try { text = await show(path); } catch { continue; }
259
+ const lines = text.split("\n");
260
+ const hits = lines.flatMap((line, i) => (needles.some((needle) => squash(line).includes(needle)) ? [i] : []));
261
+ if (!hits.length) continue;
262
+ const keep = new Set(hits.flatMap((i) => Array.from({ length: EXCEPTION_CONTEXT * 2 + 1 }, (_, k) => i - EXCEPTION_CONTEXT + k)).filter((i) => i >= 0 && i < lines.length));
263
+ let excerpt = "";
264
+ let last = -2;
265
+ for (const i of [...keep].sort((a, b) => a - b)) {
266
+ excerpt += `${i !== last + 1 && last >= 0 ? "...\n" : ""}${i + 1}: ${lines[i]}\n`;
267
+ last = i;
268
+ }
269
+ excerpt = excerpt.trimEnd();
270
+ if (total + excerpt.length > EXCEPTION_MAX_CHARS) break;
271
+ total += excerpt.length;
272
+ out.push({ path, excerpt });
273
+ }
274
+ return out;
275
+ }
276
+
221
277
  /** The headless, tool-less reviewer command for the lane's runtime. */
222
278
  export function reviewerInvocation({ runtime, model, profile, schema, workdir, schemaFile, outFile }) {
223
279
  if (runtime === "codex") return {
@@ -604,8 +660,22 @@ export async function figmaFindings(figma, { catalog, check, changeSets = {}, sw
604
660
  // A finding's identity across rounds uses only fields a reviewer states the same
605
661
  // way each time: the clause (and frame and state) it cites, or for code the file.
606
662
  // Never the wording, which changes between rounds.
607
- const findingKey = (finding) => (finding.perspective === "code" ? ["code", finding.path ?? ""] : [finding.perspective, finding.clauseId ?? "", finding.frameUrl ?? "", finding.state ?? ""]).join("|");
663
+ export const findingKey = (finding) => (finding.perspective === "code" ? ["code", finding.path ?? ""] : [finding.perspective, finding.clauseId ?? "", finding.frameUrl ?? "", finding.state ?? ""]).join("|");
608
664
  const blockingOf = (findings) => findings.filter((finding) => finding.severity !== "minor");
665
+ /**
666
+ * NODII-DEV-CLI-74: the id lane check prints for a finding, the same in every
667
+ * round. Finer than the loop's key: the clause (or frame and state) and the
668
+ * file, so a treatment covers that finding, not every finding on its clause.
669
+ */
670
+ export const findingId = (finding) => `f-${createHash("sha256").update(`${findingKey(finding)}|${finding.path ?? ""}`).digest("hex").slice(0, 8)}`;
671
+ /** MW2-41: a code-check finding and a blocker are only ever fixed (Dev refuses the same). */
672
+ export const treatable = (finding) => finding.perspective !== "code" && finding.severity !== "blocker";
673
+ /** A finding with a P-21 treatment applied when one names it and it may be treated; else as it was. */
674
+ export function treatFinding(finding, treatments = {}) {
675
+ const treated = treatments[findingId(finding)];
676
+ if (!treated || finding.disposition === "fixed" || !treatable(finding)) return finding;
677
+ return { ...finding, disposition: treated.disposition, treatment: treated.treatment };
678
+ }
609
679
 
610
680
  /**
611
681
  * MW2-41 to MW2-43 across invocations: one round per run of lane check. CLEAN
@@ -629,6 +699,35 @@ export function loopRound(previous, findings, { head, maxIterations }) {
629
699
  return { outcome, iterationCount, findings: recorded, blocking, state: { rounds: [...rounds, { head, keys, findings: blocking }] } };
630
700
  }
631
701
 
702
+ const LOOPING = [null, "STUCK", "ITERATION_CAP"];
703
+ /**
704
+ * NODII-DEV-CLI-74: treatments applied to the last round of this commit (a
705
+ * treatment is never carried to another round or commit; MW2-44). A check
706
+ * that was still looping, STUCK or at its cap is CLEAN once none of its
707
+ * blocker or major findings is left untreated; nothing else changes.
708
+ */
709
+ export function treatChecks(checks, treatments) {
710
+ return checks.map((x) => {
711
+ const findings = x.findings.map((finding) => treatFinding(finding, treatments));
712
+ const blocking = blockingOf(findings.filter((finding) => finding.disposition === "unresolved"));
713
+ return { ...x, findings, blocking, outcome: LOOPING.includes(x.outcome) && x.iterationCount > 0 && !blocking.length ? "CLEAN" : x.outcome };
714
+ });
715
+ }
716
+
717
+ /** Dev's review body for checks that all have an outcome (POST /lanes/:id/review). */
718
+ export function runBody(checks, current) {
719
+ return {
720
+ base: current.base,
721
+ head: current.commit,
722
+ appliedPatches: [],
723
+ unresolvedProposals: [],
724
+ reviewerErrors: checks.flatMap((x) => x.reviewerErrors),
725
+ findings: checks.flatMap((x) => x.findings).slice(0, 500),
726
+ checks: checks.map(({ check, outcome, iterationCount, reviewerErrors: errors, inputs, notRequired }) => ({ check, outcome, iterationCount, reviewerErrors: errors, inputs, ...(notRequired ? { notRequired } : {}) })),
727
+ via: "nodii-dev",
728
+ };
729
+ }
730
+
632
731
  const errorCheck = (check, error, iterationCount, inputs) => ({ check, outcome: error.outcome, iterationCount, reviewerErrors: [`${check}: ${error.message}`.slice(0, 2000)], inputs, findings: [] });
633
732
 
634
733
  /**
@@ -638,7 +737,7 @@ const errorCheck = (check, error, iterationCount, inputs) => ({ check, outcome:
638
737
  * caller saves the round (saveLoop) once it is kept: still looping, or
639
738
  * recorded; a run that records nothing leaves the loop where it was.
640
739
  */
641
- export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, picker = pickByAgent, now }) {
740
+ export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, picker = pickByAgent, now, exceptions = exceptionFiles }) {
642
741
  const critical = flags.critical === true;
643
742
  const maxIterations = flags["max-iterations"] === undefined ? MAX_ITERATIONS : Number(flags["max-iterations"]);
644
743
  if (!Number.isInteger(maxIterations) || maxIterations < 1 || maxIterations > 100)
@@ -679,7 +778,9 @@ export async function runLaneCheck(ref, flags, { request, lane, freeze, current,
679
778
  if (!rules) {
680
779
  const inputs = { clauseIds: gathered.clauseIds, clauseMapGatherId: gathered.clauseMapGatherId, deltaGatherId: gathered.deltaGatherId, runtime, diffDigest: diffDigest(changed.text), ...excluded };
681
780
  try {
682
- const findings = await reviewer("rules", { ...runner, prompt: reviewerPrompt("rules", { diff: reviewed, clauses: gathered.clauses, generated }), clauseIds: gathered.clauseIds });
781
+ const excerpts = await exceptions(cwd, changed.paths, { base: changed.mergeBase ?? current.base }).catch(() => []);
782
+ if (excerpts.length) inputs.exceptionFiles = excerpts.map((x) => x.path);
783
+ const findings = await reviewer("rules", { ...runner, prompt: reviewerPrompt("rules", { diff: reviewed, clauses: gathered.clauses, generated, exceptions: excerpts }), clauseIds: gathered.clauseIds });
683
784
  rules = round("rules", findings, inputs);
684
785
  } catch (error) {
685
786
  if (!(error instanceof ReviewerError)) throw error;
@@ -740,18 +841,7 @@ export async function runLaneCheck(ref, flags, { request, lane, freeze, current,
740
841
  const saveLoop = () => store.write(REVIEW_LOOP, { ...loop, [ref]: { branch: current.branch, checks: nextLoop } });
741
842
  const digest = diffDigest(changed.text);
742
843
  if (checks.some((x) => x.outcome === null)) return { checks, body: null, maxIterations, saveLoop, digest };
743
- const reviewerErrors = checks.flatMap((x) => x.reviewerErrors);
744
- const body = {
745
- base: current.base,
746
- head: current.commit,
747
- appliedPatches: [],
748
- unresolvedProposals: [],
749
- reviewerErrors,
750
- findings: checks.flatMap((x) => x.findings).slice(0, 500),
751
- checks: checks.map(({ check, outcome, iterationCount, reviewerErrors: errors, inputs, notRequired }) => ({ check, outcome, iterationCount, reviewerErrors: errors, inputs, ...(notRequired ? { notRequired } : {}) })),
752
- via: "nodii-dev",
753
- };
754
- return { checks, body, maxIterations, saveLoop, digest };
844
+ return { checks, body: runBody(checks, current), maxIterations, saveLoop, digest };
755
845
  }
756
846
 
757
847
  /** A REVIEW.json carrying checks is Dev's check contract: exactly the three, each well formed. */
@@ -773,10 +863,12 @@ export function checkReviewChecks(body) {
773
863
  }
774
864
 
775
865
  const counts = (findings) => {
776
- const n = (severity) => findings.filter((x) => x.severity === severity && x.disposition !== "fixed").length;
866
+ const n = (severity) => findings.filter((x) => x.severity === severity && x.disposition === "unresolved").length;
777
867
  return `${n("blocker")} blocker, ${n("major")} major, ${n("minor")} minor`;
778
868
  };
779
- 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}`;
869
+ /** A treatment's citation as one phrase: DEC-0085 or issue KEY. */
870
+ export const citationText = (cite) => (!cite ? "-" : cite.decision ?? `issue ${cite.issue}`);
871
+ 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}\t${findingId(x)}${TREATED.includes(x.disposition) ? `\t${x.disposition}: ${citationText(x.treatment)}` : ""}`;
780
872
 
781
873
  /** One line per check, then its open findings. */
782
874
  export function checkLines(checks, maxIterations) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.117",
3
+ "version": "0.6.119",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {