@nodii/dev 0.6.71 → 0.6.73

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
@@ -89,6 +89,23 @@ checks the local stack.
89
89
  Every command accepts `--json`; without it, output is formatted for humans.
90
90
  Dev failures print Dev's error code to stderr and exit non-zero.
91
91
 
92
+ ## Receipts
93
+
94
+ A gate that lets work move writes a signed receipt (STD-22, K04-27, S06-53 to S06-56). `lane check` and `lane review` write and attach a `review` receipt listing the `--gate` commands and the review checks, and stop if they cannot. A `test` receipt needs what those commands cannot see (scope, stack, auth posture), so it comes from `receipt write` or the stack tool's `test --receipt`. A receipt must name the lane it is attached to. Anything else uses:
95
+
96
+ ```bash
97
+ # Keep details.json outside the worktree: an untracked file there makes the receipt name a tree hash, not the commit.
98
+ nodii-dev receipt write --kind test --run 'bun test' --from-file /tmp/details.json --lane KEY
99
+ nodii-dev lane evidence KEY --file RECEIPT.json
100
+ nodii-dev receipt verify RECEIPT.json --commit SHA
101
+ ```
102
+
103
+ - **Kinds:** `test`, `review`, `down_merge`, `release`, `built_ack`, `stack_reset`. Each must carry what its rule requires, or it is refused. `--from-file` holds those details; for a `test`, `authPosture` and `scope`.
104
+ - **Signature:** Ed25519, from the machine's key at `~/.config/nodii-dev/receipt-signing-key.pem`. Dev pins the key to the lane's machine the first time it sees it and refuses any other (`RECEIPT_KEY_MISMATCH`).
105
+ - **Commands:** a receipt goes to Dev, so each command keeps its shape and loses its values (`NAME=value`, `--flag=value`, a secret-sounding flag's value, URL user info, auth headers, anything token-shaped). That is a net, not a licence: a gate command must not carry a secret (MW1-65).
106
+ - **What it proves:** that this machine's tool wrote the receipt and that nothing changed since. It does not prove the run was honest: an agent on that machine can read the key. It is never verification on dev (S06-56).
107
+ - **Dev down (MW1-64):** only a Dev fix lane may land, with a `down_merge` receipt. `lane evidence` keeps what Dev cannot take in `~/.config/nodii-dev/pending-records`, `lane done-check` and `lane land` refuse until `nodii-dev sync pending` has sent it (`--discard FILE --reason TEXT` drops one Dev refuses for good, with a note on the lane), and Dev refuses a `down_merge` receipt on any other lane kind.
108
+
92
109
  ## Commands
93
110
 
94
111
  ```text
@@ -517,6 +534,8 @@ nodii-dev docs parked [CODE] [--status pending|acknowledged]
517
534
  nodii-dev harness install [--include-drafts] [--adopt PATH,...] [--dry-run] [--system]
518
535
  nodii-dev harness update [--include-drafts] [--adopt PATH,...] [--dry-run] [--system]
519
536
  nodii-dev harness check [--json] # 0 current, 1 differs from Dev, 2 no harness
537
+ nodii-dev repo policy [--json] # print this repository's nodii.repo.yaml facts (STD-11)
538
+ nodii-dev repo lint [--json] # 0 clean, 1 findings
520
539
  nodii-dev harness update --check # the same check
521
540
  nodii-dev watchdog install [--interval SECONDS] # install/update com.nodii.watchdog in ~/Library/LaunchAgents
522
541
  nodii-dev watchdog sweep # launchd entrypoint; normally not run by hand
package/dist/cli.js CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  import { FIGMA_HOOK_DENIALS, heartbeatCurrentLane, postHook, postHookFailure, preHook, sessionStartContext, settingsSnippet, workflowSuggestion } from "./hooks.js";
25
25
  import { setupCommand } from "./setup.js";
26
26
  import { harnessCommand } from "./harness.js";
27
+ import { repoCommand } from "./repo-policy.js";
27
28
  import { hookRuntime, recordHookFire, safetyContext, safetyPostHook, safetyPreHook } from "./safety.js";
28
29
  import { SUBMIT_CHECK_FLAGS, changedPaths, nudgeCandidate, nudgePre, nudgeStop, recordGathered, recordGuidelineRead, recordSubmitChecks } from "./nudges.js";
29
30
  import { doctorCommand } from "./doctor.js";
@@ -68,6 +69,9 @@ import { designCheck, designCheckChangeSet, designCheckText, designRoles, design
68
69
  import { assertKnownFlags } from "./flags.js";
69
70
  import { installWatchdog, watchdogCommand } from "./watchdog.js";
70
71
  import { machineCapacityCommand } from "./accounts.js";
72
+ import { prepareGate, receiptCommand, syncCommand } from "./receipt.js";
73
+
74
+ const gateSigner = (ref, kind, { details, commit, cwd }) => prepareGate(ref, kind, details, { commit, cwd });
71
75
  import {
72
76
  ALIASES,
73
77
  GROUPS,
@@ -189,6 +193,9 @@ Usage: nodii-dev <command> [options] [--json]
189
193
  # --system stages managed hooks and only prints operator-reviewed sudo commands
190
194
  harness check # 0 current, 1 differs from Dev, 2 not installed
191
195
  harness update --check # the same check
196
+ repo policy # print this repository's nodii.repo.yaml facts (STD-11)
197
+ repo lint # 0 clean, 1 findings: policy file missing or invalid, stray root
198
+ # files, docs layout, scratch not gitignored, test scripts
192
199
  watchdog install [--interval SECONDS] # install/update the per-Mac launchd liveness sweep (default 60s)
193
200
  watchdog sweep # launchd entrypoint: report dead runs, stale sockets, unpushed worktrees,
194
201
  # and re-report account usage every 5 min
@@ -269,7 +276,16 @@ Usage: nodii-dev <command> [options] [--json]
269
276
  # records the review (as lane review) first, then marks the step done
270
277
  lane step <key> --side SIDE --not-applicable gather --reason-code pre_harness_lane [--note TEXT]
271
278
  # coordinator only: Gather never applied (pre-Gather lane); never "done"
272
- lane evidence <key> --pr|--commit|--figma|--deploy|--dev-check REF
279
+ lane evidence <key> --pr|--commit|--figma|--deploy|--dev-check REF | --file RECEIPT.json
280
+ # --file attaches a signed receipt (K04-27); when Dev is unreachable the
281
+ # record waits on this machine and blocks done-check and land (MW1-64)
282
+ receipt write --kind test|review|down_merge|release|built_ack|stack_reset [--lane KEY] [--commit SHA]
283
+ [--run CMD ...] [--from-file DETAILS.json] [--out FILE]
284
+ # one signed receipt (STD-22); --run gates stop at the first failure and exit 1
285
+ receipt verify <file> [--commit SHA] # the signature, and that it names this commit (S06-55)
286
+ sync pending [--discard FILE --reason TEXT]
287
+ # send the lane records queued while Dev was down (MW1-64); --discard drops
288
+ # one Dev refuses for good, with a note on its lane
273
289
  lane done-check <key> --evidence TEXT|URL # the done check is met; a launched run that exits after it ends finished
274
290
  lane subagent-quota <key> <n> # coordinator assigns 0-100 subagent slots
275
291
  lane heartbeat|resume|land|verify|prioritize|deprioritize|stop <key>
@@ -745,6 +761,7 @@ export async function main(argv = process.argv.slice(2)) {
745
761
  if (rest.length) throw new CliError("USAGE", `harness ${action} takes no arguments, got: ${rest.join(" ")}. Write a flag value as --include-drafts=false.`, 2);
746
762
  return emitCommand(await harnessCommand(action, f));
747
763
  }
764
+ if (command === "repo" && ["policy", "lint"].includes(action)) return emitCommand(await repoCommand(action, rest, f));
748
765
  if (command === "watchdog") {
749
766
  if (rest.length) throw new CliError("USAGE", `watchdog ${action ?? ""} takes no arguments, got: ${rest.join(" ")}.`, 2);
750
767
  return emitCommand(await watchdogCommand(action, f));
@@ -813,16 +830,18 @@ export async function main(argv = process.argv.slice(2)) {
813
830
  }
814
831
  if (command === "lane" && action === "check") {
815
832
  // The Delta gather goes through lane gather's own path (amendments included).
816
- const result = await laneCommand("check", rest, f, { check: { deltaGather: (key, paths) => gatherLaneCommand(key, { delta: true, paths: paths.join(",") }) } });
833
+ const result = await laneCommand("check", rest, f, { signReceipt: gateSigner, check: { deltaGather: (key, paths) => gatherLaneCommand(key, { delta: true, paths: paths.join(",") }) } });
817
834
  emit(result.payload, json, result.human);
818
835
  if (result.exitCode) process.exitCode = result.exitCode;
819
836
  return;
820
837
  }
821
838
  if (command === "lane" && action === "freeze")
822
839
  return emitCommand(await freezeCommand(rest[0], rest.slice(1), f));
823
- if (command === "lane") return emitCommand(await laneCommand(action, rest, f));
840
+ if (command === "lane") return emitCommand(await laneCommand(action, rest, f, action === "review" || action === "step" ? { signReceipt: gateSigner } : {}));
824
841
  if (command === "next") return emitCommand(await nextCommand(action, f));
825
842
  if (command === "built") return emitCommand(await builtCommand(action, rest, f));
843
+ if (command === "receipt") return emitCommand(await receiptCommand(action, rest, f));
844
+ if (command === "sync") return emitCommand(await syncCommand(action, f));
826
845
  if (command === "machine" && ["accounts", "usage"].includes(action))
827
846
  return emitCommand(await machineCapacityCommand(action, rest[0], f));
828
847
  if (command === "machine") return emitCommand(await machineCommand(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.71";
7
+ export const VERSION = "0.6.73";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
package/dist/flags.js CHANGED
@@ -30,13 +30,18 @@ export const COMMAND_FLAGS = {
30
30
  "lane amend": ["objective", "scope", "rules", "reason"],
31
31
  "lane start": ["key", "issue", "title", "kind", "side", "repo", "branch", "worktree", "step-limit"],
32
32
  "lane step": ["side", "start", "done", "block", "not-applicable", "reason", "reason-code", "note", "review", "delta"],
33
- "lane evidence": ["pr", "commit", "figma", "deploy", "dev-check"],
33
+ "lane evidence": ["pr", "commit", "figma", "deploy", "dev-check", "file"],
34
+ "receipt write": ["kind", "lane", "commit", "run", "from-file", "out"],
35
+ "receipt verify": ["commit"],
36
+ "sync pending": ["discard", "reason"],
34
37
  "lane done-check": ["evidence"],
35
38
  "lane heartbeat": ["note"],
36
39
  "lane resume": ["override", "reason", "host-lost", "min-free-gb", "stagger-seconds", "profile", "class"],
37
40
  "lane transfer": ["reason", "to-agent"],
38
41
  "lane stop": ["reason"],
39
42
  "lane land": [],
43
+ "repo policy": ["root"],
44
+ "repo lint": ["root"],
40
45
  "lane review": ["file", "not-required", "decision", "question", "quote", "at"],
41
46
  "lane non-issue": ["reason", "reroute", "evidence", "commits", "branch"],
42
47
  "drift file": ["service", "severity", "summary", ...BODY, "related-artifact-type", "related-artifact-id"],
package/dist/lanes.js CHANGED
@@ -10,10 +10,11 @@ import { GATHER_TIMEOUT_MS, PICKER_FIRST_PICK_TIMEOUT_MS, PICKER_MODEL, agentFal
10
10
  import { storeGatherFreeze } from "./freeze.js";
11
11
  import { doneCheckRecorded } from "./lane-supervisor.js";
12
12
  import { availableMemoryBytes } from "./host.js";
13
+ import { assertNothingPending, devDown, queuePending, receiptEvidenceBody, signedBuiltAck } from "./receipt.js";
13
14
  import { SWAP_BOUNDARIES, componentsForScope, guidelineLookup, laneFigmaScope, loadDsCatalog } from "./figma-scope.js";
14
15
  import { designCheck } from "./design.js";
15
16
  import { LANE_ENV_FIX, laneEnvProblem, laneEnvReport } from "./lane-env.js";
16
- import { REVIEW_FILE, checkLines, checkReviewChecks, diffDigest, laneDiff, privateStore, repoGeneratedPaths, runLaneCheck, runOutcome, worktreeCommitted } from "./review.js";
17
+ import { GATES_RECEIPT, REVIEW_FILE, checkLines, checkReviewChecks, diffDigest, laneDiff, privateStore, repoGeneratedPaths, runLaneCheck, runOutcome, worktreeCommitted } from "./review.js";
17
18
 
18
19
  const execFileAsync = promisify(execFile);
19
20
  const via = { via: "nodii-dev" };
@@ -387,7 +388,7 @@ async function resumeHostLost(flags, deps, { request, config }) {
387
388
  }
388
389
 
389
390
  export async function laneCommand(action, args, flags, deps = {}) {
390
- const { request = devRequest, config = readConfig, refreshAccounts = refreshMoveAccounts, 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, rebind = rebindLaneConfig, catalog = loadDsCatalog, pickLock = withPickLock, check: checkDeps = {} } = deps;
391
+ const { request = devRequest, config = readConfig, refreshAccounts = refreshMoveAccounts, 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, rebind = rebindLaneConfig, catalog = loadDsCatalog, pickLock = withPickLock, check: checkDeps = {}, signReceipt = null } = deps;
391
392
  if (action === "resume" && flags["host-lost"]) {
392
393
  if (args[0]) throw new CliError("USAGE", "lane resume --host-lost takes no <key>: it resumes every host_lost lane on this machine.", 2);
393
394
  return resumeHostLost(flags, deps, { request, config });
@@ -637,7 +638,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
637
638
  }
638
639
  // MW2-45: `lane review` and a step's `--done --review` record through one path.
639
640
  // `lane check` hands its own body over, already shaped.
640
- const recordReview = async (reviewFlags = flags, prepared = null) => {
641
+ const recordReview = async (reviewFlags = flags, prepared = null, ranGates = [], cwd = null) => {
641
642
  // The input is checked before git is read, so a bad call never touches the worktree.
642
643
  const notRequired = !prepared && reviewFlags["not-required"] ? notRequiredCitation(reviewFlags) : null;
643
644
  const filed = prepared ?? (notRequired ? null : await reviewBody(reviewFlags, read));
@@ -649,6 +650,18 @@ export async function laneCommand(action, args, flags, deps = {}) {
649
650
  `The review file covers base ${body.base ?? "(missing)"} and head ${body.head ?? "(missing)"}, but this worktree is base ${current.base} and head ${current.commit}. Review the current diff and write a new receipt.`,
650
651
  2,
651
652
  );
653
+ // Signed and attached first: no proof on Dev, no passed review on Dev (S06-53).
654
+ // Only gates this tool saw pass for this head: lane check hands over its gates receipt's commands.
655
+ // A --gate flag on lane review is a claim, not a run, so it signs nothing. Their scope, stack and
656
+ // auth posture are unknown to this tool, so a test receipt comes from receipt write or the stack tool.
657
+ const gatesRun = ranGates.map((command) => ({ command, exitCode: 0 }));
658
+ const attachReceipt = await signReceipt?.(ref, "review", { commit: body.head, ...(cwd ? { cwd } : {}), details: {
659
+ checks: [...gatesRun, ...(body.checks?.length
660
+ ? body.checks.map((check) => ({ name: check.check, outcome: check.outcome, exitCode: runOutcome([check]) === "CLEAN" ? 0 : 1 }))
661
+ : [{ name: "review", outcome: body.exitReason, exitCode: ["CLEAN", "NOT_REQUIRED"].includes(body.exitReason) ? 0 : 1 }])],
662
+ review: { exitReason: body.exitReason, base: body.base, head: body.head, findings: body.findings?.length ?? 0 },
663
+ } });
664
+ await attachReceipt?.();
652
665
  const payload = await request("POST", `/api/v1/lanes/${encode(id)}/review`, body);
653
666
  try { await reviewReceipt(); }
654
667
  catch (error) {
@@ -710,7 +723,9 @@ export async function laneCommand(action, args, flags, deps = {}) {
710
723
  if (!committed || diffDigest((await diff(context.worktree)).text) !== run.digest)
711
724
  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);
712
725
  const file = await store.write(REVIEW_FILE, run.body);
713
- const payload = await recordReview(flags, run.body);
726
+ const gates = await store.read(GATES_RECEIPT).catch(() => null);
727
+ const ranGates = gates?.commit === run.body.head && gates?.base === run.body.base && Array.isArray(gates.commands) ? gates.commands : [];
728
+ const payload = await recordReview(flags, run.body, ranGates, context.worktree);
714
729
  await run.saveLoop();
715
730
  const outcome = runOutcome(run.body.checks);
716
731
  return {
@@ -783,11 +798,20 @@ export async function laneCommand(action, args, flags, deps = {}) {
783
798
  return { payload: reason ? { ...payload, reason } : payload, human: `${ref}: ${side}/${step.stepKey} ${selected[0]}${reason ? `: ${reason}` : ""}` };
784
799
  }
785
800
  if (action === "evidence") {
786
- const body = evidence(flags);
787
- const payload = await request("POST", `/api/v1/lanes/${encode(id)}/evidence`, body);
788
- return { payload, human: `${ref}: recorded ${body.kind} evidence.` };
801
+ const body = flags.file !== undefined ? await receiptEvidenceBody(requireFlag(flags, "file"), ref) : evidence(flags);
802
+ const path = `/api/v1/lanes/${encode(id)}/evidence`;
803
+ try {
804
+ const payload = await request("POST", path, body);
805
+ return { payload, human: `${ref}: recorded ${body.kind} evidence.` };
806
+ } catch (error) {
807
+ if (!devDown(error)) throw error;
808
+ // MW1-64: Dev is down, so the record waits here and blocks the lane's close.
809
+ const file = await queuePending(path, body, { lane: ref });
810
+ return { payload: { data: { queued: true, file } }, human: `${ref}: Dev is unreachable; ${body.kind} evidence is waiting at ${file}. Run nodii-dev sync pending before the lane closes (MW1-64).` };
811
+ }
789
812
  }
790
813
  if (action === "done-check") {
814
+ await assertNothingPending(ref);
791
815
  // NODII-DEV-CLI-4: the agent met the lane's done check. A launched run that
792
816
  // exits after this ends finished instead of orphaned (lane-supervisor.js).
793
817
  const value = typeof flags.evidence === "string" ? flags.evidence.trim() : "";
@@ -911,6 +935,7 @@ export async function laneCommand(action, args, flags, deps = {}) {
911
935
  },
912
936
  };
913
937
  }
938
+ if (action === "land") await assertNothingPending(ref);
914
939
  if (action === "land") return { payload: await request("POST", `/api/v1/lanes/${encode(id)}/land`, via), human: `${ref}: recorded on main.` };
915
940
  if (action === "review") return { payload: await recordReview(), human: (p) => `${ref}: ${reviewSummary(p)}.` };
916
941
  if (action === "reviews") {
@@ -1016,14 +1041,19 @@ export async function nextCommand(ref, flags, { request = devRequest, changedPat
1016
1041
  return { payload: { data, ...(rules ? { rules } : {}) }, human };
1017
1042
  }
1018
1043
 
1019
- export async function builtCommand(action, args, flags, { request = devRequest } = {}) {
1044
+ export async function builtCommand(action, args, flags, { request = devRequest, signAck = signedBuiltAck } = {}) {
1020
1045
  if (action === "list") {
1021
1046
  const payload = await request("GET", `/api/v1/built${query({ cursor: flags.cursor, limit: flags.limit, includeAcknowledged: flags["include-acknowledged"] })}`);
1022
1047
  return { payload, human: (p) => p.data.map(laneLine).join("\n") || "No built lanes awaiting acknowledgement." };
1023
1048
  }
1024
1049
  if (action === "ack") {
1025
1050
  if (!args.length) throw new CliError("USAGE", "built ack needs one or more lane keys", 2);
1026
- const results = await Promise.all(args.map((ref) => request("POST", `/api/v1/built/${encode(ref)}/acknowledge`, { ...(flags.note !== undefined ? { note: flags.note } : {}), ...via })));
1051
+ const results = await Promise.all(args.map(async (ref) => {
1052
+ // STD-22: the acknowledgement is signed and linked to what contributed; it is never verification.
1053
+ const lane = (await request("GET", `/api/v1/lanes/${encode(ref)}`)).data;
1054
+ const receipt = await signAck(ref, lane);
1055
+ return request("POST", `/api/v1/built/${encode(ref)}/acknowledge`, { ...(flags.note !== undefined ? { note: flags.note } : {}), receipt, ...via });
1056
+ }));
1027
1057
  return { payload: args.length === 1 ? results[0] : { data: results.map((x) => x.data) }, human: `Acknowledged ${args.join(", ")}.` };
1028
1058
  }
1029
1059
  throw new CliError("USAGE", `Unknown built action: ${action}`, 2);
@@ -0,0 +1,365 @@
1
+ // STD-22 / K04-27 / S06-53 to S06-56: the one writer and signer of gate
2
+ // receipts. A receipt names the commit, the checks run and their result, and is
3
+ // signed by the machine's own Ed25519 key. It proves that a gate ran and what it
4
+ // found; it is never verification on dev (S06-56) and acknowledgement is never
5
+ // testing. Dev pins the key to the lane's machine on first sight, so a signature
6
+ // shows which machine's tool wrote the receipt and that nothing changed since.
7
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomUUID, sign, verify } from "node:crypto";
8
+ import { execFile } from "node:child_process";
9
+ import { link, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
10
+ import { homedir, hostname } from "node:os";
11
+ import { basename, dirname, join } from "node:path";
12
+ import { promisify } from "node:util";
13
+ import { CliError, devRequest, encode, readConfig } from "./core.js";
14
+ import { runGate } from "./review.js";
15
+ import { gitPrivatePath } from "./safety.js";
16
+
17
+ const execFileAsync = promisify(execFile);
18
+ export const RECEIPT_SCHEMA = "nodii.receipt/1";
19
+ export const RECEIPT_KINDS = ["test", "review", "down_merge", "release", "built_ack", "stack_reset"];
20
+ const AUTH_POSTURES = ["real-stack", "component"];
21
+ const RECEIPT_DIR = "nodii-receipts";
22
+ const via = { via: "nodii-dev" };
23
+ // What this tool works out for itself. From a details file, each would be a claim it never checked.
24
+ // The gates that must name a real commit and the checks run (DEV-DEL-23). A test or reset may name a dirty tree (S06-54).
25
+ const NEEDS_COMMIT = ["review", "down_merge", "release", "built_ack"];
26
+ // A release records what it ships and an acknowledgement what a person saw; neither runs a check itself.
27
+ const NO_CHECKS = ["release", "built_ack"];
28
+ const OWN_FIELDS = ["schema", "commit", "worktreeHash", "baseCommit", "repo", "result", "machine", "actor", "endedAt", "signature"];
29
+
30
+ /** Dev gave no answer: the record may wait. A timeout may have landed, and Dev takes a resent receipt once. */
31
+ export const devDown = (error) => error?.code === "DEV_UNREACHABLE" || error?.code === "DEV_TIMEOUT";
32
+
33
+ /** Machine-wide, not per worktree: the close check must see a record from wherever it runs (MW1-64). */
34
+ export const pendingDirPath = (env = process.env) =>
35
+ env.NODII_DEV_PENDING_DIR ?? join(homedir(), ".config/nodii-dev/pending-records");
36
+
37
+ export const receiptKeyPath = (env = process.env) =>
38
+ env.NODII_DEV_RECEIPT_KEY_PATH ?? join(homedir(), ".config/nodii-dev/receipt-signing-key.pem");
39
+
40
+ /** Sorted keys at every level, so Dev recomputes the same bytes. Dev holds the twin of this function. */
41
+ export function canonicalJson(value) {
42
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
43
+ if (value && typeof value === "object")
44
+ return `{${Object.keys(value).filter((key) => value[key] !== undefined).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
45
+ if (value === undefined) throw new CliError("RECEIPT_INVALID", "A receipt value cannot be undefined.", 2);
46
+ return JSON.stringify(value);
47
+ }
48
+
49
+ const signedBytes = ({ signature: _signature, ...body }) => Buffer.from(canonicalJson(body));
50
+ const publicKeyBase64 = (key) => createPublicKey(key).export({ type: "spki", format: "der" }).toString("base64");
51
+ export const keyIdOf = (publicKey) => createHash("sha256").update(Buffer.from(publicKey, "base64")).digest("hex").slice(0, 32);
52
+
53
+ /** The machine's signing key, made on first use. The private half never leaves this file. */
54
+ export async function loadSigningKey(path = receiptKeyPath()) {
55
+ let pem;
56
+ try {
57
+ pem = await readFile(path, "utf8");
58
+ } catch (error) {
59
+ if (error.code !== "ENOENT") throw error;
60
+ const { privateKey } = generateKeyPairSync("ed25519");
61
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
62
+ // A whole file or none: link fails on a racing first use, and the winner's key is the key.
63
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
64
+ await writeFile(temporary, privateKey.export({ type: "pkcs8", format: "pem" }), { mode: 0o600 });
65
+ await link(temporary, path).catch((raced) => { if (raced.code !== "EEXIST") throw raced; });
66
+ await rm(temporary, { force: true });
67
+ pem = await readFile(path, "utf8");
68
+ }
69
+ return createPrivateKey(pem);
70
+ }
71
+
72
+ export function signReceipt(body, key) {
73
+ const publicKey = publicKeyBase64(key);
74
+ return { ...body, signature: { alg: "ed25519", keyId: keyIdOf(publicKey), publicKey, value: sign(null, signedBytes(body), key).toString("base64") } };
75
+ }
76
+
77
+ /** The signature over the receipt's own bytes. Returns the reason it fails, or null. */
78
+ export function receiptSignatureError(receipt) {
79
+ const signature = receipt?.signature;
80
+ if (receipt?.schema !== RECEIPT_SCHEMA) return `schema is not ${RECEIPT_SCHEMA}`;
81
+ if (signature?.alg !== "ed25519" || !signature.publicKey || !signature.value) return "no ed25519 signature";
82
+ if (keyIdOf(signature.publicKey) !== signature.keyId) return "the key id does not match the public key";
83
+ try {
84
+ const key = createPublicKey({ key: Buffer.from(signature.publicKey, "base64"), format: "der", type: "spki" });
85
+ if (key.asymmetricKeyType !== "ed25519") return "the key is not ed25519";
86
+ return verify(null, signedBytes(receipt), key, Buffer.from(signature.value, "base64")) ? null : "the signature does not match the receipt";
87
+ } catch (error) {
88
+ return `the signature cannot be read: ${error.message}`;
89
+ }
90
+ }
91
+
92
+ const refuse = (message) => { throw new CliError("RECEIPT_INVALID", message, 2); };
93
+
94
+ /** What each kind must carry (S06-54, K05-33, MW1-64, DEV-DEL-23). */
95
+ export function assertReceiptShape(body) {
96
+ if (!RECEIPT_KINDS.includes(body.kind)) refuse(`--kind must be one of ${RECEIPT_KINDS.join(", ")}.`);
97
+ if (!body.commit && !body.worktreeHash) refuse("A receipt must name a commit or a working-tree hash (S06-54).");
98
+ if (!Array.isArray(body.checks)) refuse("A receipt's checks must be a list.");
99
+ if (NEEDS_COMMIT.includes(body.kind) && !body.commit) refuse(`A ${body.kind} receipt must name a commit, not a dirty tree (DEV-DEL-23). Commit first.`);
100
+ if (!NO_CHECKS.includes(body.kind) && !body.checks.length) refuse(`A ${body.kind} receipt must name the checks run (DEV-DEL-23).`);
101
+ if (body.kind === "test") {
102
+ if (!body.checks.length) refuse("A test receipt needs at least one check: pass --run CMD or checks in --from-file (S06-54).");
103
+ if (!AUTH_POSTURES.includes(body.authPosture)) refuse(`A test receipt needs authPosture ${AUTH_POSTURES.join(" or ")} (S06-47, S06-54).`);
104
+ if (!body.scope || !Array.isArray(body.scope.files) || !(Number.isInteger(body.scope.testCount) || body.scope.testCount === null)) refuse("A test receipt needs scope.files and scope.testCount, null when the runner reported no count (S06-54).");
105
+ }
106
+ if (body.kind === "review" && !body.review?.exitReason) refuse("A review receipt needs review.exitReason.");
107
+ if (body.kind === "down_merge" && (!body.lane || !body.downMerge?.pr || !body.downMerge?.mergeCommit || !Array.isArray(body.downMerge?.records))) refuse("A down_merge receipt needs --lane, downMerge.pr, downMerge.mergeCommit and downMerge.records (MW1-64).");
108
+ if (body.kind === "release") {
109
+ const filled = (value) => Boolean(value) && typeof value === "object" && Object.keys(value).length > 0;
110
+ if (!body.release?.sourceCommit || !filled(body.release?.manifest) || !filled(body.release?.digests)) refuse("A release receipt needs release.sourceCommit, and a release.manifest and release.digests that are not empty (K05-33).");
111
+ if (body.release.sourceCommit !== body.commit) refuse(`A release receipt's commit ${body.commit} must be its source commit ${body.release.sourceCommit} (K05-33).`);
112
+ }
113
+ if (body.kind === "built_ack" && (!body.lane || !Array.isArray(body.ack?.changes))) refuse("A built_ack receipt needs --lane and ack.changes (STD-22).");
114
+ if (body.kind === "stack_reset" && !body.stack?.composeProject) refuse("A stack_reset receipt needs stack.composeProject.");
115
+ return body;
116
+ }
117
+
118
+ async function gitIdentity(cwd) {
119
+ const git = async (...args) => (await execFileAsync("git", args, { cwd, maxBuffer: 256 * 1024 * 1024 })).stdout;
120
+ try {
121
+ const commit = (await git("rev-parse", "HEAD")).trim();
122
+ const dirty = (await git("status", "--porcelain")).trim();
123
+ const repo = basename((await git("rev-parse", "--show-toplevel")).trim());
124
+ if (!dirty) return { commit, repo };
125
+ const hash = createHash("sha256").update(await git("diff", "HEAD", "--binary"));
126
+ const root = (await git("rev-parse", "--show-toplevel")).trim();
127
+ const untracked = (await execFileAsync("git", ["ls-files", "-o", "--exclude-standard", "-z"], { cwd: root, maxBuffer: 256 * 1024 * 1024 })).stdout;
128
+ for (const name of untracked.split("\0").filter(Boolean).sort()) {
129
+ hash.update(name).update("\0").update(await readFile(join(root, name)));
130
+ }
131
+ return { worktreeHash: hash.digest("hex"), baseCommit: commit, repo };
132
+ } catch {
133
+ return {};
134
+ }
135
+ }
136
+
137
+ /**
138
+ * MW1-65: a receipt goes to Dev, so a command keeps its shape and loses its values. Every
139
+ * NAME=value and --flag=value goes, whatever the name; so does the value after a flag that
140
+ * sounds secret, a URL's user info, an auth header and anything token-shaped. This is a
141
+ * net, not a licence: a gate command must not carry a secret in the first place.
142
+ */
143
+ const SHELL_VALUE = String.raw`('[^']*'|"[^"]*"|\S+)`;
144
+ const ANY_ASSIGNMENT = new RegExp(String.raw`(^|\s)(-{0,2}[A-Za-z_][\w.-]*)=${SHELL_VALUE}`, "g");
145
+ const SECRET_FLAG = new RegExp(String.raw`(^|\s)(--?[\w-]*(?:token|secret|pass|pwd|credential|key|auth|cookie|user)[\w-]*|-[upH])\s+${SHELL_VALUE}`, "gi");
146
+ const URL_USER_INFO = /(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s:@]*(?::[^/\s@]*)?@/gi;
147
+ const AUTH_SCHEME = /\b(bearer|basic|token)\s+[A-Za-z0-9._~+/=-]{8,}/gi;
148
+ const TOKEN_SHAPED = /\b(?:gh[pousr]_[A-Za-z0-9]{10,}|github_pat_\w{10,}|sk-[\w-]{10,}|xox[abprs]-[\w-]{10,}|AKIA[0-9A-Z]{12,}|eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]*|[A-Fa-f0-9]{32,}|[A-Za-z0-9+/_-]{40,}={0,2})\b/g;
149
+ export const redactCommand = (command) => String(command)
150
+ .replace(URL_USER_INFO, "$1<redacted>@")
151
+ .replace(SECRET_FLAG, "$1$2 <redacted>")
152
+ .replace(ANY_ASSIGNMENT, "$1$2=<redacted>")
153
+ .replace(AUTH_SCHEME, "$1 <redacted>")
154
+ .replace(TOKEN_SHAPED, "<redacted>");
155
+
156
+ const many = (value) => (value === undefined ? [] : [value].flat().map(String));
157
+ const ranAt = () => new Date().toISOString();
158
+
159
+ /** Build, sign and store one receipt. Gates run in order and stop at the first failure (MW2-15, MW2-16). */
160
+ export async function writeReceipt(flags, { cwd = process.cwd(), run = runGate, config = readConfig, keyPath = receiptKeyPath(), now = ranAt } = {}) {
161
+ let details = flags.details ?? {};
162
+ if (flags["from-file"]) {
163
+ try {
164
+ details = JSON.parse(await readFile(String(flags["from-file"]), "utf8"));
165
+ } catch (error) {
166
+ refuse(`Cannot read receipt details from ${flags["from-file"]}: ${error.message}`);
167
+ }
168
+ if (!details || typeof details !== "object" || Array.isArray(details)) refuse("--from-file must hold one JSON object.");
169
+ }
170
+ details = Object.fromEntries(Object.entries(details).filter(([key]) => !OWN_FIELDS.includes(key)));
171
+ const commands = many(flags.run);
172
+ if (flags.commit && commands.length) refuse("--commit names work this tool did not run, so it cannot go with --run: the receipt names what is checked out (S06-55).");
173
+ const before = flags.commit ? null : await gitIdentity(cwd);
174
+ const startedAt = details.startedAt ?? now();
175
+ const checks = (details.checks ?? []).map((check) => (check.command ? { ...check, command: redactCommand(check.command) } : check));
176
+ for (const command of commands) {
177
+ const { code } = await run(command, cwd);
178
+ checks.push({ command: redactCommand(command), exitCode: code });
179
+ if (code !== 0) break;
180
+ }
181
+ const failed = checks.some((check) => check.exitCode !== 0);
182
+ const identity = flags.commit ? { commit: String(flags.commit), repo: (await gitIdentity(cwd)).repo } : await gitIdentity(cwd);
183
+ if (before && canonicalJson(before) !== canonicalJson(identity)) throw new CliError("RECEIPT_TREE_CHANGED", "The worktree changed while the gates ran, so no one commit or tree is what they tested; nothing was signed (MW2-19).", 1);
184
+ const c = await config().catch(() => ({}));
185
+ const body = assertReceiptShape({
186
+ ...details,
187
+ schema: RECEIPT_SCHEMA,
188
+ kind: flags.kind ?? details.kind,
189
+ ...(flags.lane ? { lane: String(flags.lane) } : {}),
190
+ ...identity,
191
+ checks,
192
+ result: failed ? "fail" : checks.length ? "pass" : "recorded",
193
+ machine: hostname(),
194
+ actor: c.agentId ?? "unknown",
195
+ startedAt,
196
+ endedAt: now(),
197
+ });
198
+ const receipt = signReceipt(body, await loadSigningKey(keyPath));
199
+ const out = flags.out ? String(flags.out) : await gitPrivatePath(cwd, `${RECEIPT_DIR}/${body.kind}-${(body.commit ?? body.worktreeHash).slice(0, 12)}-${Date.now()}.json`);
200
+ await mkdir(dirname(out), { recursive: true });
201
+ await writeFile(out, `${JSON.stringify(receipt, null, 2)}\n`, { mode: 0o600 });
202
+ return { receipt, path: out, failed };
203
+ }
204
+
205
+ /** STD-22: what the operator acknowledged, linked to every change and release that contributed. */
206
+ export async function signedBuiltAck(ref, lane, { keyPath = receiptKeyPath(), config = readConfig, now = ranAt } = {}) {
207
+ const contributing = (lane.events ?? []).filter((event) => event.type === "evidence" && ["pr", "commit", "deploy"].includes(event.metadata?.kind));
208
+ const at = now();
209
+ const c = await config().catch(() => ({}));
210
+ const commit = lane.mergeCommit ?? contributing.findLast((item) => item.metadata.kind === "commit")?.metadata.ref;
211
+ if (!commit) throw new CliError("RECEIPT_NO_COMMIT", `${ref} names no merge or commit, so its acknowledgement has nothing to sign. The lane needs its landing recorded first.`, 1);
212
+ const body = assertReceiptShape({
213
+ schema: RECEIPT_SCHEMA, kind: "built_ack", lane: ref, commit,
214
+ checks: [], result: "recorded",
215
+ ack: { changes: contributing.map((item) => ({ kind: item.metadata.kind, ref: item.metadata.url ?? item.metadata.ref })), releases: lane.releases ?? [] },
216
+ machine: hostname(), actor: c.agentId ?? "unknown", startedAt: at, endedAt: at,
217
+ });
218
+ return signReceipt(body, await loadSigningKey(keyPath));
219
+ }
220
+
221
+ /**
222
+ * `lane check` and `lane review` sign what they did (STD-22, S06-53), before the gate
223
+ * is recorded, so a signing failure leaves nothing half-applied. Returns the step that
224
+ * attaches it: only an unreachable Dev waits, and that blocks the close (MW1-64).
225
+ */
226
+ export async function prepareGate(ref, kind, details, { cwd = process.cwd(), request = devRequest, commit } = {}) {
227
+ let body;
228
+ try {
229
+ const { path } = await writeReceipt({ kind, lane: ref, details, ...(commit ? { commit } : {}) }, { cwd });
230
+ body = await receiptEvidenceBody(path, ref);
231
+ } catch (error) {
232
+ throw new CliError("RECEIPT_NOT_WRITTEN", `${ref}: the ${kind} gate left no signed receipt (${error?.code ?? "ERROR"}: ${error?.message ?? error}). Fix that and rerun it (S06-53).`, 1);
233
+ }
234
+ const url = `/api/v1/lanes/${encode(ref)}/evidence`;
235
+ return async () => {
236
+ try {
237
+ await request("POST", url, body);
238
+ } catch (error) {
239
+ if (devDown(error)) return queuePending(url, body, { lane: ref });
240
+ throw new CliError("RECEIPT_NOT_ATTACHED", `${ref}: Dev refused the ${kind} receipt (${error?.code ?? "ERROR"}: ${error?.message ?? error}). It is at nodii-receipts in this worktree's git dir; attach it with lane evidence --file (K04-27).`, 1);
241
+ }
242
+ };
243
+ }
244
+
245
+ export const signGate = async (ref, kind, details, options) => (await prepareGate(ref, kind, details, options))();
246
+
247
+ export async function readReceiptFile(path) {
248
+ try {
249
+ return JSON.parse(await readFile(path, "utf8"));
250
+ } catch (error) {
251
+ throw new CliError("RECEIPT_FILE_INVALID", `Cannot read a receipt from ${path}: ${error.message}`, 2);
252
+ }
253
+ }
254
+
255
+ /** The lane evidence body for a receipt, refused locally when its signature fails. */
256
+ export async function receiptEvidenceBody(path, ref) {
257
+ const receipt = await readReceiptFile(path);
258
+ const error = receiptSignatureError(receipt);
259
+ if (error) throw new CliError("RECEIPT_SIGNATURE_INVALID", `${path}: ${error}.`, 1);
260
+ if (receipt.lane !== ref) throw new CliError("RECEIPT_LANE_MISMATCH", `${path} names lane ${receipt.lane ?? "(none)"}, not ${ref}: write it with --lane ${ref}.`, 2);
261
+ return { kind: "receipt", ref: receipt.commit ?? receipt.worktreeHash, receipt, ...via };
262
+ }
263
+
264
+ /** MW1-64: a lane record Dev could not take waits here until `sync pending`. */
265
+ export async function queuePending(path, body, { lane, dir = pendingDirPath(), now = ranAt, config = readConfig } = {}) {
266
+ const agentId = (await config().catch(() => ({}))).agentId ?? null;
267
+ await mkdir(dir, { recursive: true, mode: 0o700 });
268
+ const file = join(dir, `${Date.now()}-${process.pid}-${Math.random().toString(36).slice(2, 8)}.json`);
269
+ await writeFile(`${file}.tmp`, JSON.stringify({ lane, agentId, path, body, queuedAt: now() }), { mode: 0o600 });
270
+ await rename(`${file}.tmp`, file);
271
+ return file;
272
+ }
273
+
274
+ export async function listPending({ dir = pendingDirPath() } = {}) {
275
+ let names;
276
+ try {
277
+ names = (await readdir(dir)).filter((name) => name.endsWith(".json")).sort();
278
+ } catch (error) {
279
+ if (error.code === "ENOENT") return [];
280
+ throw error;
281
+ }
282
+ const items = await Promise.all(names.map(async (name) => {
283
+ try {
284
+ return { file: join(dir, name), ...JSON.parse(await readFile(join(dir, name), "utf8")) };
285
+ } catch (error) {
286
+ // Only this one record was sent meanwhile; the rest of the queue still counts (MW1-64).
287
+ if (error.code === "ENOENT") return null;
288
+ throw error;
289
+ }
290
+ }));
291
+ return items.filter(Boolean);
292
+ }
293
+
294
+ /** A lane does not close while a record it owes Dev is still on this machine (MW1-64, MW3-31). */
295
+ export async function assertNothingPending(ref, deps = {}) {
296
+ const owed = (await listPending(deps)).filter((item) => item.lane === ref);
297
+ if (owed.length)
298
+ throw new CliError("LANE_RECORDS_PENDING", `${ref} still owes Dev ${owed.length} record(s) written while Dev was down. Run nodii-dev sync pending first (MW1-64).`, 1, { pending: owed.length });
299
+ }
300
+
301
+ /**
302
+ * Send this agent's waiting records, oldest first, so none reaches Dev under another
303
+ * agent's identity. An unreachable Dev stops the run; a refusal stays queued and is reported.
304
+ */
305
+ export async function syncPending({ dir = pendingDirPath(), request = devRequest, config = readConfig } = {}) {
306
+ const sent = [];
307
+ const refused = [];
308
+ const skipped = [];
309
+ const agentId = (await config().catch(() => ({}))).agentId ?? null;
310
+ for (const item of await listPending({ dir })) {
311
+ if (item.agentId !== agentId) {
312
+ skipped.push({ file: item.file, lane: item.lane, agentId: item.agentId });
313
+ continue;
314
+ }
315
+ try {
316
+ await request("POST", item.path, item.body);
317
+ await rm(item.file, { force: true });
318
+ sent.push(item.path);
319
+ } catch (error) {
320
+ if (devDown(error)) throw error;
321
+ refused.push({ file: item.file, lane: item.lane, path: item.path, code: error.code ?? "ERROR", message: error.message });
322
+ }
323
+ }
324
+ return { sent, refused, skipped };
325
+ }
326
+
327
+ /**
328
+ * A record Dev will never take would block its lane for good. Dropping one is explicit and
329
+ * leaves a note on the lane; Dev decides who may write that note, so Dev decides who may drop it.
330
+ */
331
+ export async function discardPending(file, reason, { dir = pendingDirPath(), request = devRequest } = {}) {
332
+ const item = (await listPending({ dir })).find((entry) => entry.file === file || basename(entry.file) === file);
333
+ if (!item) throw new CliError("PENDING_NOT_FOUND", `No waiting record ${file}.`, 2);
334
+ await request("POST", `/api/v1/lanes/${encode(item.lane)}/heartbeat`, { note: `Discarded a record owed since ${item.queuedAt} (${item.body?.kind}): ${reason}`.slice(0, 500), ...via });
335
+ await rm(item.file, { force: true });
336
+ return item;
337
+ }
338
+
339
+ export async function receiptCommand(action, args, flags) {
340
+ if (action === "write") {
341
+ const { receipt, path, failed } = await writeReceipt(flags);
342
+ return { payload: { data: { path, receipt } }, human: `${receipt.kind} receipt ${receipt.result} for ${receipt.commit ?? receipt.worktreeHash}: ${path}`, exitCode: failed ? 1 : 0 };
343
+ }
344
+ if (action === "verify") {
345
+ if (!args[0]) throw new CliError("USAGE", "receipt verify needs <file>", 2);
346
+ const receipt = await readReceiptFile(args[0]);
347
+ const signature = receiptSignatureError(receipt);
348
+ const commit = flags.commit && receipt.commit !== flags.commit ? `it names ${receipt.commit ?? receipt.worktreeHash}, not ${flags.commit} (S06-55)` : null;
349
+ const reason = signature ?? commit;
350
+ return { payload: { data: { valid: !reason, reason, keyId: receipt?.signature?.keyId ?? null, kind: receipt?.kind ?? null, commit: receipt?.commit ?? null, result: receipt?.result ?? null } }, human: reason ? `INVALID: ${reason}` : `Signature holds for ${receipt.kind} receipt (${receipt.result}) on ${receipt.commit ?? receipt.worktreeHash}, by key ${receipt.signature.keyId}. Whether that key is the signer's own is Dev's pin, not this check.`, exitCode: reason ? 1 : 0 };
351
+ }
352
+ throw new CliError("USAGE", `Unknown receipt action: ${action}. Use write or verify.`, 2);
353
+ }
354
+
355
+ export async function syncCommand(action, flags = {}) {
356
+ if (action !== "pending") throw new CliError("USAGE", "sync takes one action: sync pending", 2);
357
+ if (flags.discard !== undefined) {
358
+ if (typeof flags.reason !== "string" || !flags.reason.trim()) throw new CliError("USAGE", "sync pending --discard FILE needs --reason TEXT", 2);
359
+ const item = await discardPending(String(flags.discard), flags.reason);
360
+ return { payload: { data: { discarded: item.file } }, human: `Discarded ${item.file}; noted on ${item.lane}.` };
361
+ }
362
+ const { sent, refused, skipped } = await syncPending();
363
+ const human = [`Sent ${sent.length} waiting record(s).`, ...refused.map((item) => `REFUSED ${item.file}: ${item.code}: ${item.message}`), ...skipped.map((item) => `LEFT ${item.file}: lane ${item.lane}'s, written by another agent, which must send it.`)].join("\n");
364
+ return { payload: { data: { sent, refused, skipped } }, human, exitCode: refused.length ? 1 : 0 };
365
+ }
@@ -0,0 +1,315 @@
1
+ // `nodii-dev repo policy|lint`: the repository policy file (STD-11; MW5-3).
2
+ // The file holds facts about one repository: merge mode, CI cadence, review
3
+ // engine, test tiers and docs layout. It holds no rules; those are in Dev.
4
+ //
5
+ // The CLI has no runtime dependencies, so it reads a strict subset of YAML: block
6
+ // maps, block lists, flow lists of scalars, quoted scalars and comments. Anything
7
+ // else (anchors, block text, several documents) is refused, never guessed at.
8
+ import { execFile } from "node:child_process";
9
+ import { readFile, stat } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { promisify } from "node:util";
12
+ import { CliError } from "./core.js";
13
+
14
+ const execFileAsync = promisify(execFile);
15
+
16
+ export const POLICY_FILE = "nodii.repo.yaml";
17
+ export const SCHEMA_VERSION = 1;
18
+ export const DOCS_LAYOUTS = ["standard", "drive", "existing"];
19
+ export const CI_PR_MODES = ["none", "affected", "full"];
20
+ export const CI_FULL_TRIGGERS = ["weekly", "dispatch", "pr", "push", "release", "label"];
21
+ // MW4-31.1. pre-launch.md is optional, so it is not listed.
22
+ export const STANDARD_DOCS = ["docs/README.md", "docs/open.md", "docs/answered.md", "docs/architecture/", "docs/runbooks/", "docs/reports/", "docs/archive/"];
23
+
24
+ // ─── parser ─────────────────────────────────────────────────────────────────
25
+ const invalid = (message) => new CliError("POLICY_INVALID", `${POLICY_FILE}: ${message}`, 1);
26
+
27
+ /** Text before an unquoted ` #`, trailing space removed. */
28
+ function stripComment(line) {
29
+ let quote = null;
30
+ for (let i = 0; i < line.length; i++) {
31
+ const c = line[i];
32
+ if (quote) { if (c === quote) quote = null; continue; }
33
+ if (c === '"' || c === "'") quote = c;
34
+ else if (c === "#" && (i === 0 || /\s/.test(line[i - 1]))) return line.slice(0, i).trimEnd();
35
+ }
36
+ if (quote) throw invalid(`unterminated quote in: ${line.trim()}`);
37
+ return line.trimEnd();
38
+ }
39
+
40
+ function scalar(raw, where) {
41
+ const text = raw.trim();
42
+ if (/^".*"$/.test(text) || /^'.*'$/.test(text)) return text.slice(1, -1);
43
+ if (/^[&*!|>%@`]/.test(text) || text === "---" || text === "...") throw invalid(`${where}: "${text}" uses YAML this reader does not model; write a plain or quoted value`);
44
+ if (/^[{[]/.test(text)) throw invalid(`${where}: nested collections are not allowed in a flow list`);
45
+ if (text === "true") return true;
46
+ if (text === "false") return false;
47
+ if (text === "null" || text === "~") return null;
48
+ if (/^-?\d+$/.test(text)) return Number(text);
49
+ return text;
50
+ }
51
+
52
+ function flowList(raw, where) {
53
+ if (!raw.endsWith("]")) throw invalid(`${where}: unterminated list`);
54
+ const items = [];
55
+ let current = "";
56
+ let quote = null;
57
+ for (const c of raw.slice(1, -1)) {
58
+ if (quote) { current += c; if (c === quote) quote = null; continue; }
59
+ if (c === '"' || c === "'") quote = c;
60
+ if (c === ",") { items.push(current); current = ""; } else current += c;
61
+ }
62
+ if (current.trim()) items.push(current);
63
+ return items.map((item) => scalar(item, where));
64
+ }
65
+
66
+ const value = (raw, where) => (raw.startsWith("[") ? flowList(raw, where) : scalar(raw, where));
67
+
68
+ /** Parse the policy file's YAML subset. Throws POLICY_INVALID on anything outside it. */
69
+ export function parsePolicyYaml(text) {
70
+ const lines = [];
71
+ for (const [index, line] of String(text).split(/\r?\n/).entries()) {
72
+ if (/^\s*\t/.test(line)) throw invalid(`line ${index + 1}: tabs are not allowed in indentation`);
73
+ const clean = stripComment(line);
74
+ if (!clean.trim()) continue;
75
+ if (clean.trim() === "---" || clean.trim() === "...") throw invalid(`line ${index + 1}: write one document, without "---"`);
76
+ lines.push({ number: index + 1, indent: clean.length - clean.trimStart().length, text: clean.trim() });
77
+ }
78
+ let at = 0;
79
+ function block(indent) {
80
+ return lines[at].text.startsWith("- ") || lines[at].text === "-" ? list(indent) : map(indent);
81
+ }
82
+ function list(indent) {
83
+ const out = [];
84
+ while (at < lines.length && lines[at].indent === indent && (lines[at].text.startsWith("- ") || lines[at].text === "-")) {
85
+ const { number, text: item } = lines[at];
86
+ if (item === "-") throw invalid(`line ${number}: a list item needs a value`);
87
+ out.push(value(item.slice(2).trim(), `line ${number}`));
88
+ at++;
89
+ }
90
+ return out;
91
+ }
92
+ function map(indent) {
93
+ const out = {};
94
+ while (at < lines.length && lines[at].indent === indent) {
95
+ const { number, text: entry } = lines[at];
96
+ const match = /^([A-Za-z_][\w-]*):(?:\s+(.*))?$/.exec(entry);
97
+ if (!match) throw invalid(`line ${number}: expected "key: value", got "${entry}"`);
98
+ const [, key, raw] = match;
99
+ if (Object.hasOwn(out, key)) throw invalid(`line ${number}: duplicate key "${key}"`);
100
+ at++;
101
+ if (raw !== undefined && raw !== "") { out[key] = value(raw, `line ${number}`); continue; }
102
+ // A list may sit at its key's own indent, as in common YAML style.
103
+ const next = lines[at];
104
+ const nestedList = next && next.indent === indent && next.text.startsWith("- ");
105
+ if (!next || (next.indent <= indent && !nestedList)) { out[key] = null; continue; }
106
+ out[key] = block(next.indent);
107
+ }
108
+ return out;
109
+ }
110
+ if (!lines.length) throw invalid("the file is empty");
111
+ const root = block(lines[0].indent);
112
+ if (at < lines.length) throw invalid(`line ${lines[at].number}: unexpected indentation`);
113
+ return root;
114
+ }
115
+
116
+ // ─── schema ─────────────────────────────────────────────────────────────────
117
+ const isObject = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
118
+ const isStringList = (x) => Array.isArray(x) && x.every((item) => typeof item === "string" && item);
119
+ const isText = (x) => typeof x === "string" && x.trim().length > 0;
120
+ const ALLOWED_KEYS = {
121
+ "": ["schema", "service", "merge", "ci", "review", "tests", "docs"],
122
+ merge: ["mode"],
123
+ ci: ["pr", "full", "required", "reporting"],
124
+ review: ["engine", "command", "severities"],
125
+ tests: ["full", "tiers"],
126
+ docs: ["layout", "open", "scratch", "rootAllow"],
127
+ };
128
+ // MW4-31.1 names these as what must not sit at the root; a repo cannot declare them away.
129
+ const STRAY_KIND = /\.(md|mdx|markdown|png|jpe?g|gif|webp|bmp|tiff?|heic|svg|log)$/i;
130
+ const safeRelativePath = (path) => isText(path) && !path.startsWith("/") && !path.split("/").includes("..");
131
+
132
+ /** Every way the parsed file breaks the schema, as sentences. Empty means valid. */
133
+ export function validatePolicy(policy) {
134
+ if (!isObject(policy)) return ["the file must be a map of keys"];
135
+ const errors = [];
136
+ for (const [section, keys] of Object.entries(ALLOWED_KEYS)) {
137
+ const target = section ? policy[section] : policy;
138
+ if (section && !isObject(target)) { errors.push(`${section}: required, and must be a map`); continue; }
139
+ for (const key of Object.keys(target)) if (!keys.includes(key)) errors.push(`${section ? `${section}.` : ""}${key}: unknown key; allowed: ${keys.join(", ")}`);
140
+ }
141
+ if (policy.schema !== SCHEMA_VERSION) errors.push(`schema: must be ${SCHEMA_VERSION}`);
142
+ if (!isText(policy.service)) errors.push("service: required, the repository's service id or name");
143
+ if (isObject(policy.merge) && policy.merge.mode !== "squash") errors.push("merge.mode: must be squash (MW3-9)");
144
+
145
+ if (isObject(policy.ci)) {
146
+ const { pr, full, required, reporting } = policy.ci;
147
+ if (!CI_PR_MODES.includes(pr)) errors.push(`ci.pr: must be one of ${CI_PR_MODES.join(", ")}`);
148
+ const fullOk = isStringList(full) && full.length > 0 && full.every((item) => CI_FULL_TRIGGERS.includes(item));
149
+ if (!fullOk) errors.push(`ci.full: must list when the full suite runs, from ${CI_FULL_TRIGGERS.join(", ")}`);
150
+ for (const [key, list] of [["required", required], ["reporting", reporting]]) if (list !== undefined && !isStringList(list)) errors.push(`ci.${key}: must be a list of check names`);
151
+ const named = [...(required ?? []), ...(reporting ?? [])];
152
+ const perPush = pr !== "none" || (fullOk && (full.includes("pr") || full.includes("push")));
153
+ if (perPush && !named.length) errors.push("ci.required / ci.reporting: a repository that runs PR or push CI must name which checks are required and which only report (MW3-22)");
154
+ if (Array.isArray(required) && Array.isArray(reporting)) for (const name of required) if (reporting.includes(name)) errors.push(`ci: "${name}" is both required and reporting (MW3-22)`);
155
+ if (pr === "none" && fullOk && !perPush && !(full.includes("weekly") && full.includes("dispatch"))) errors.push("ci.full: a weekly repository must run its full suite on weekly and dispatch (MW3-15)");
156
+ }
157
+
158
+ if (isObject(policy.review)) {
159
+ if (!isText(policy.review.engine)) errors.push("review.engine: required");
160
+ if (!isText(policy.review.command)) errors.push("review.command: required");
161
+ if (!isStringList(policy.review.severities) || !policy.review.severities.length) errors.push("review.severities: must list the severities the review reports");
162
+ }
163
+
164
+ if (isObject(policy.tests)) {
165
+ if (!isText(policy.tests.full)) errors.push("tests.full: required, the script that runs the full suite (S06-52)");
166
+ if (!isStringList(policy.tests.tiers)) errors.push("tests.tiers: must be a list of tier names, each with a test:<tier> script (S06-52)");
167
+ else for (const tier of policy.tests.tiers) {
168
+ if (/^(tier[-_]?)?[123][ab]?$/i.test(tier)) errors.push(`tests.tiers: "${tier}" is a cluster tier; the canonical suite owns it, so it is not declared here (S06-52)`);
169
+ else if (!/^[a-z][a-z0-9-]*$/.test(tier)) errors.push(`tests.tiers: "${tier}" must be lowercase letters, digits and hyphens`);
170
+ }
171
+ }
172
+
173
+ if (isObject(policy.docs)) {
174
+ const { layout, open, scratch, rootAllow } = policy.docs;
175
+ if (!DOCS_LAYOUTS.includes(layout)) errors.push(`docs.layout: must be one of ${DOCS_LAYOUTS.join(", ")}`);
176
+ if (layout === "standard" && open !== "docs/open.md") errors.push("docs.open: the standard layout keeps it at docs/open.md (MW4-31.1)");
177
+ if (layout === "drive" && !(safeRelativePath(open) && open.endsWith("/open.md"))) errors.push("docs.open: a drive repository names its drive's open.md path (MW4-31)");
178
+ if (open !== undefined && !safeRelativePath(open)) errors.push("docs.open: must be a path inside the repository");
179
+ if (scratch !== undefined && !(isStringList(scratch) && scratch.every(safeRelativePath))) errors.push("docs.scratch: must be a list of paths inside the repository");
180
+ if (rootAllow !== undefined) {
181
+ if (!isStringList(rootAllow)) errors.push("docs.rootAllow: must be a list of root file names");
182
+ else for (const name of rootAllow) if (STRAY_KIND.test(name) || name.includes("/")) errors.push(`docs.rootAllow: "${name}" cannot be allowed; markdown, screenshots and logs never sit at the root (MW4-31.1)`);
183
+ }
184
+ }
185
+ return errors;
186
+ }
187
+
188
+ // ─── reader ─────────────────────────────────────────────────────────────────
189
+ async function gitLines(root, args) {
190
+ const { stdout } = await execFileAsync("git", ["-C", root, ...args], { maxBuffer: 64 * 1024 * 1024 });
191
+ return stdout.split("\n").filter(Boolean);
192
+ }
193
+
194
+ async function repoRoot(flags = {}) {
195
+ if (flags.root && flags.root !== true) return String(flags.root);
196
+ try {
197
+ const [root] = await gitLines(process.cwd(), ["rev-parse", "--show-toplevel"]);
198
+ return root;
199
+ } catch { throw new CliError("USAGE", "Run this inside a git repository.", 2); }
200
+ }
201
+
202
+ async function exists(path) {
203
+ try { await stat(path); return true; } catch (error) { if (error.code === "ENOENT") return false; throw error; }
204
+ }
205
+
206
+ /** The repository's parsed, validated policy. Throws POLICY_MISSING or POLICY_INVALID. */
207
+ export async function readPolicy(root) {
208
+ let text;
209
+ try { text = await readFile(join(root, POLICY_FILE), "utf8"); } catch (error) {
210
+ if (error.code !== "ENOENT") throw error;
211
+ throw new CliError("POLICY_MISSING", `${root} has no ${POLICY_FILE} (STD-11).`, 1);
212
+ }
213
+ const policy = parsePolicyYaml(text);
214
+ const errors = validatePolicy(policy);
215
+ if (errors.length) throw new CliError("POLICY_INVALID", `${POLICY_FILE}: ${errors.join("; ")}`, 1, { errors });
216
+ return policy;
217
+ }
218
+
219
+ // ─── lint ───────────────────────────────────────────────────────────────────
220
+ // Configuration by name. A root file outside these, and outside docs.rootAllow, is stray.
221
+ const ROOT_NAMES = new Set([POLICY_FILE, "makefile", "justfile", "procfile", "dockerfile", "go.mod", "go.sum", "pipfile", "gemfile"]);
222
+ const ROOT_PATTERNS = [
223
+ /^readme(\.[a-z]+)?$/i,
224
+ /^\.[^/]+$/, // dotfiles
225
+ /\.(json|jsonc|ya?ml|toml|lock|ini|cfg|conf)$/i,
226
+ /\.config\.[cm]?[jt]s$/i,
227
+ /^dockerfile\./i,
228
+ /^requirements[\w.-]*\.txt$/i,
229
+ /^setup\.py$/i,
230
+ ];
231
+ const ROOT_MARKDOWN = new Set(["readme.md", "claude.md", "agents.md"]);
232
+
233
+ /** Is this root file allowed? README, CLAUDE.md, the harness's AGENTS.md and config are (MW4-31.1). */
234
+ function allowedAtRoot(name, extras) {
235
+ if (ROOT_MARKDOWN.has(name.toLowerCase())) return true;
236
+ if (STRAY_KIND.test(name)) return false;
237
+ return extras.includes(name) || ROOT_NAMES.has(name.toLowerCase()) || ROOT_PATTERNS.some((pattern) => pattern.test(name));
238
+ }
239
+
240
+ /** Files at the repository root that git tracks or would track; ignored scratch does not count. */
241
+ async function rootFiles(root) {
242
+ const all = await gitLines(root, ["ls-files", "--cached", "--others", "--exclude-standard", "--deduplicate"]);
243
+ return all.filter((path) => !path.includes("/"));
244
+ }
245
+
246
+ async function isIgnored(root, path) {
247
+ try { await execFileAsync("git", ["-C", root, "check-ignore", "-q", "--no-index", path]); return true; } catch (error) {
248
+ if (error.code === 1) return false;
249
+ throw error;
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Check one repository against its policy file. A missing or invalid file fails
255
+ * every repository. `layout: existing` marks a repository that predates MW4-31.1:
256
+ * it is not required to migrate (operator, 2 Nov 2026), so the root and layout
257
+ * checks skip it.
258
+ */
259
+ export async function lintRepo(root) {
260
+ let policy;
261
+ try { policy = await readPolicy(root); } catch (error) {
262
+ if (error.code !== "POLICY_MISSING" && error.code !== "POLICY_INVALID") throw error;
263
+ return { root, policy: null, findings: [{ code: error.code, path: POLICY_FILE, message: error.message }] };
264
+ }
265
+ const findings = [];
266
+ const add = (code, path, message) => findings.push({ code, path, message });
267
+ const { layout, open, scratch = [], rootAllow = [] } = policy.docs;
268
+
269
+ if (layout !== "existing") {
270
+ for (const name of await rootFiles(root)) {
271
+ if (!allowedAtRoot(name, rootAllow)) add("STRAY_ROOT_FILE", name, `${name} may not sit at the repository root (MW4-31.1): move it under docs/, gitignore it if it is scratch, or list a configuration file in docs.rootAllow.`);
272
+ }
273
+ }
274
+ if (layout === "standard") {
275
+ for (const path of STANDARD_DOCS) if (!(await exists(join(root, path)))) add("DOCS_LAYOUT_MISSING", path, `The standard layout needs ${path} (MW4-31.1).`);
276
+ } else if (open && layout === "drive" && !(await exists(join(root, open)))) {
277
+ add("DOCS_LAYOUT_MISSING", open, `docs.open names ${open}, which does not exist (MW4-31).`);
278
+ }
279
+ for (const path of scratch) if (!(await isIgnored(root, path))) add("SCRATCH_NOT_IGNORED", path, `The scratch path ${path} is not gitignored (MW4-31.1).`);
280
+
281
+ // Tier scripts are checked where the repository declares scripts in package.json.
282
+ let scripts = null;
283
+ try { scripts = JSON.parse(await readFile(join(root, "package.json"), "utf8")).scripts ?? {}; } catch (error) {
284
+ if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
285
+ }
286
+ if (scripts) {
287
+ const declared = [policy.tests.full, ...policy.tests.tiers.map((tier) => `test:${tier}`)];
288
+ for (const script of declared) if (!Object.hasOwn(scripts, script)) add("TEST_SCRIPT_MISSING", script, `The policy file declares the script ${script}, which package.json does not have (S06-52).`);
289
+ }
290
+ return { root, policy, findings };
291
+ }
292
+
293
+ // ─── command ────────────────────────────────────────────────────────────────
294
+ const humanPolicy = ({ root, policy: p }) => [
295
+ `${root}/${POLICY_FILE} · ${p.service}`,
296
+ `merge: ${p.merge.mode}`,
297
+ `ci: PR runs ${p.ci.pr}; full suite on ${p.ci.full.join(", ")}; required ${p.ci.required?.join(", ") || "none"}; reporting ${p.ci.reporting?.join(", ") || "none"}`,
298
+ `review: ${p.review.engine} · ${p.review.command} · ${p.review.severities.join(", ")}`,
299
+ `tests: ${p.tests.full}${p.tests.tiers.length ? `; tiers ${p.tests.tiers.join(", ")}` : ""}`,
300
+ `docs: ${p.docs.layout}${p.docs.open ? ` · ${p.docs.open}` : ""}`,
301
+ ].join("\n");
302
+
303
+ const humanLint = ({ root, findings }) => (findings.length
304
+ ? [`${root}: ${findings.length} policy finding(s).`, ...findings.map((f) => ` ${f.code} ${f.path}: ${f.message}`)].join("\n")
305
+ : `${root}: policy file and checks pass.`);
306
+
307
+ export async function repoCommand(action, rest, flags = {}) {
308
+ if (!["policy", "lint"].includes(action)) throw new CliError("USAGE", "repo policy|lint", 2);
309
+ if (rest.length) throw new CliError("USAGE", `repo ${action} takes no arguments, got: ${rest.join(" ")}`, 2);
310
+ const root = await repoRoot(flags);
311
+ if (action === "policy") return { payload: { root, policy: await readPolicy(root) }, human: humanPolicy };
312
+ const result = await lintRepo(root);
313
+ const payload = { root, passed: result.findings.length === 0, findings: result.findings };
314
+ return { payload, human: humanLint, exitCode: result.findings.length ? 1 : 0 };
315
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.71",
3
+ "version": "0.6.73",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {