@nodii/dev 0.6.72 → 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
package/dist/cli.js CHANGED
@@ -69,6 +69,9 @@ import { designCheck, designCheckChangeSet, designCheckText, designRoles, design
69
69
  import { assertKnownFlags } from "./flags.js";
70
70
  import { installWatchdog, watchdogCommand } from "./watchdog.js";
71
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 });
72
75
  import {
73
76
  ALIASES,
74
77
  GROUPS,
@@ -273,7 +276,16 @@ Usage: nodii-dev <command> [options] [--json]
273
276
  # records the review (as lane review) first, then marks the step done
274
277
  lane step <key> --side SIDE --not-applicable gather --reason-code pre_harness_lane [--note TEXT]
275
278
  # coordinator only: Gather never applied (pre-Gather lane); never "done"
276
- 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
277
289
  lane done-check <key> --evidence TEXT|URL # the done check is met; a launched run that exits after it ends finished
278
290
  lane subagent-quota <key> <n> # coordinator assigns 0-100 subagent slots
279
291
  lane heartbeat|resume|land|verify|prioritize|deprioritize|stop <key>
@@ -818,16 +830,18 @@ export async function main(argv = process.argv.slice(2)) {
818
830
  }
819
831
  if (command === "lane" && action === "check") {
820
832
  // The Delta gather goes through lane gather's own path (amendments included).
821
- 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(",") }) } });
822
834
  emit(result.payload, json, result.human);
823
835
  if (result.exitCode) process.exitCode = result.exitCode;
824
836
  return;
825
837
  }
826
838
  if (command === "lane" && action === "freeze")
827
839
  return emitCommand(await freezeCommand(rest[0], rest.slice(1), f));
828
- 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 } : {}));
829
841
  if (command === "next") return emitCommand(await nextCommand(action, f));
830
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));
831
845
  if (command === "machine" && ["accounts", "usage"].includes(action))
832
846
  return emitCommand(await machineCapacityCommand(action, rest[0], f));
833
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.72";
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,7 +30,10 @@ 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"],
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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.72",
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": {