@nodii/dev 0.6.72 → 0.6.74
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 +150 -7
- package/dist/cli.js +84 -16
- package/dist/core.js +2 -2
- package/dist/design.js +46 -2
- package/dist/doctor.js +17 -7
- package/dist/figma.js +44 -0
- package/dist/flags.js +5 -1
- package/dist/freeze.js +12 -0
- package/dist/gather.js +51 -23
- package/dist/harness.js +8 -4
- package/dist/hooks.js +1 -25
- package/dist/lanes.js +74 -23
- package/dist/managed-hooks.js +60 -9
- package/dist/nudges.js +166 -2
- package/dist/receipt.js +365 -0
- package/dist/review.js +76 -4
- package/dist/safety.js +8 -1
- package/dist/session-kind.js +243 -0
- package/dist/setup.js +8 -6
- package/dist/surface.js +847 -0
- package/dist/vendor/render-templates.mjs +740 -0
- package/package.json +1 -1
package/dist/receipt.js
ADDED
|
@@ -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/dist/review.js
CHANGED
|
@@ -9,6 +9,7 @@ import { tmpdir } from "node:os";
|
|
|
9
9
|
import { dirname, join } from "node:path";
|
|
10
10
|
import { promisify } from "node:util";
|
|
11
11
|
import { CliError, encode } from "./core.js";
|
|
12
|
+
import { pickerPrompt } from "./gather.js";
|
|
12
13
|
import { gitPrivatePath } from "./safety.js";
|
|
13
14
|
|
|
14
15
|
const execFileAsync = promisify(execFile);
|
|
@@ -277,6 +278,67 @@ export async function runReviewer(check, { runtime = "claude", model, profile, p
|
|
|
277
278
|
}
|
|
278
279
|
}
|
|
279
280
|
|
|
281
|
+
/** The agent pick's answer schema: one or more of the offered document codes. */
|
|
282
|
+
export function agentPickSchema(codes) {
|
|
283
|
+
return {
|
|
284
|
+
type: "object",
|
|
285
|
+
properties: { documents: { type: "array", items: { type: "string", enum: codes }, minItems: 1 } },
|
|
286
|
+
required: ["documents"],
|
|
287
|
+
additionalProperties: false,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* The Delta gather's pick by the lane's runtime when the local picker fell
|
|
293
|
+
* back (hub-58): the same prompt and shortlist the local model gets, answered
|
|
294
|
+
* headless with no tools. Forced documents are always kept; Dev adds them too.
|
|
295
|
+
*/
|
|
296
|
+
/** A pick is one short structured answer; it never needs the reviewer's budget. */
|
|
297
|
+
export const AGENT_PICK_TIMEOUT_MS = 120_000;
|
|
298
|
+
|
|
299
|
+
export async function pickByAgent({ runtime = "claude", model, profile, objective, files = [], triggers, timeoutMs = AGENT_PICK_TIMEOUT_MS, spawnImpl = spawnReviewer }) {
|
|
300
|
+
const codes = [...new Set(triggers.map((trigger) => trigger.code))];
|
|
301
|
+
const input = {
|
|
302
|
+
objective,
|
|
303
|
+
files,
|
|
304
|
+
triggers: triggers.map((trigger) => ({ code: trigger.code, trigger: trigger.sentence ?? trigger.trigger ?? trigger.title ?? "", ...(trigger.forcedBy ? { forcedBy: trigger.forcedBy } : {}) })),
|
|
305
|
+
};
|
|
306
|
+
const schema = agentPickSchema(codes);
|
|
307
|
+
const workdir = await mkdtemp(join(tmpdir(), "nodii-pick-"));
|
|
308
|
+
try {
|
|
309
|
+
const schemaFile = join(workdir, "schema.json");
|
|
310
|
+
const outFile = join(workdir, "answer.json");
|
|
311
|
+
if (runtime === "codex") await writeFile(schemaFile, JSON.stringify(schema));
|
|
312
|
+
const invocation = reviewerInvocation({ runtime, model, profile, schema, workdir, schemaFile, outFile });
|
|
313
|
+
const result = await spawnImpl({ ...invocation, cwd: workdir, input: pickerPrompt(input, schema), timeoutMs });
|
|
314
|
+
const name = invocation.command;
|
|
315
|
+
if (result.missing) throw new ReviewerError(UNAVAILABLE, `${name} is not installed or not on PATH`);
|
|
316
|
+
if (result.timedOut) throw new ReviewerError("TIMEOUT", `${name} gave no pick within ${Math.round(timeoutMs / 1000)} s`);
|
|
317
|
+
if (result.code !== 0) throw new ReviewerError("CRASH", `${name} exited ${result.code ?? "abnormally"}: ${(result.stderr || result.error || result.stdout || "").trim().slice(-500)}`);
|
|
318
|
+
let answer;
|
|
319
|
+
if (runtime === "codex") {
|
|
320
|
+
let text;
|
|
321
|
+
try { text = await readFile(outFile, "utf8"); }
|
|
322
|
+
catch { throw new ReviewerError("UNPARSABLE", "codex wrote no pick"); }
|
|
323
|
+
answer = parseJson(text, "codex's pick");
|
|
324
|
+
} else {
|
|
325
|
+
const envelope = parseJson(result.stdout, "claude's output");
|
|
326
|
+
if (envelope?.is_error) throw new ReviewerError("CRASH", `claude ended in error (${envelope.subtype ?? "unknown"}): ${String(envelope.result ?? "").slice(0, 500)}`);
|
|
327
|
+
answer = envelope?.structured_output ?? (typeof envelope?.result === "string" ? parseJson(envelope.result, "claude's pick") : null);
|
|
328
|
+
}
|
|
329
|
+
// The agent's own answer must name at least one offered document and
|
|
330
|
+
// nothing else: forced documents alone are not a pick (hub-58 integrity).
|
|
331
|
+
const answered = Array.isArray(answer?.documents) ? answer.documents : null;
|
|
332
|
+
if (!answered || !answered.length) throw new ReviewerError("UNPARSABLE", "the pick names no document from the shortlist");
|
|
333
|
+
const outside = answered.filter((code) => !codes.includes(code));
|
|
334
|
+
if (outside.length) throw new ReviewerError("UNPARSABLE", `the pick names documents Dev did not offer: ${outside.join(", ")}`);
|
|
335
|
+
const forcedCodes = input.triggers.filter((trigger) => Array.isArray(trigger.forcedBy) ? trigger.forcedBy.length : trigger.forcedBy).map((trigger) => trigger.code);
|
|
336
|
+
return [...new Set([...answered, ...forcedCodes])];
|
|
337
|
+
} finally {
|
|
338
|
+
await rm(workdir, { recursive: true, force: true });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
280
342
|
const text = (value, max) => (typeof value === "string" ? value.trim().slice(0, max) : "");
|
|
281
343
|
/** The answer as Dev's finding shape, or UNPARSABLE: no finding outside the schema reaches Dev. */
|
|
282
344
|
export function checkAnswer(check, answer, clauseIds = []) {
|
|
@@ -319,14 +381,24 @@ async function inBatches(items, size, work) {
|
|
|
319
381
|
* gather over the changed paths, each with its full text. Any gap is an
|
|
320
382
|
* error: a partial set is never reviewed.
|
|
321
383
|
*/
|
|
322
|
-
export async function ruleClauses(ref, { request, freeze, paths, deltaGather }) {
|
|
384
|
+
export async function ruleClauses(ref, { request, freeze, paths, deltaGather, agentPicker }) {
|
|
323
385
|
const mapped = [...(freeze?.clauseMap?.clauses ?? []), ...(freeze?.pinnedClauses ?? [])].map((x) => x.clauseId);
|
|
324
386
|
if (!freeze?.clauseMap) throw new ReviewerError(UNAVAILABLE, `${ref} has no Clause map: its Freeze was never written by Gather. Run nodii-dev lane gather ${ref} first.`);
|
|
325
387
|
if (paths.length > 5000) throw new ReviewerError(UNAVAILABLE, `the diff touches ${paths.length} paths; a Delta gather takes at most 5,000`);
|
|
326
388
|
let delta;
|
|
327
389
|
try { delta = await deltaGather(ref, paths); }
|
|
328
390
|
catch (error) { throw new ReviewerError(UNAVAILABLE, `the Delta gather over the changed paths failed (${error?.code ?? "ERROR"}: ${error?.message ?? error})`); }
|
|
329
|
-
|
|
391
|
+
let data = delta?.payload?.data;
|
|
392
|
+
// hub-58: no usable local picker on this Mac, so the lane's own runtime picks
|
|
393
|
+
// from the shortlist Dev offered, and Dev records the Gather as picker: agent.
|
|
394
|
+
if (data?.recorded === false && data.shortlistId && data.triggers?.length && agentPicker) {
|
|
395
|
+
let documents;
|
|
396
|
+
try { documents = await agentPicker({ objective: data.objective, files: paths, triggers: data.triggers }); }
|
|
397
|
+
catch (error) { throw new ReviewerError(UNAVAILABLE, `the local picker fell back (${data.fallback ?? "no local pick"}) and the agent pick failed (${error?.outcome ?? error?.code ?? "ERROR"}: ${error?.message ?? error})`); }
|
|
398
|
+
try { delta = await deltaGather(ref, paths, { shortlist: data.shortlistId, documents }); }
|
|
399
|
+
catch (error) { throw new ReviewerError(UNAVAILABLE, `recording the agent's Delta gather pick failed (${error?.code ?? "ERROR"}: ${error?.message ?? error})`); }
|
|
400
|
+
data = delta?.payload?.data;
|
|
401
|
+
}
|
|
330
402
|
if (data?.recorded === false || !data?.gatherId)
|
|
331
403
|
throw new ReviewerError(UNAVAILABLE, `the Delta gather over the changed paths recorded nothing${data?.fallback ? ` (${data.fallback})` : ""}; record it with nodii-dev lane gather ${ref} --delta --picker agent, then rerun lane check`);
|
|
332
404
|
const ids = [...new Set([...mapped, ...(data.clauses ?? []).map((x) => x.clauseId)])].sort();
|
|
@@ -461,7 +533,7 @@ const errorCheck = (check, error, iterationCount, inputs) => ({ check, outcome:
|
|
|
461
533
|
* caller saves the round (saveLoop) once it is kept: still looping, or
|
|
462
534
|
* recorded; a run that records nothing leaves the loop where it was.
|
|
463
535
|
*/
|
|
464
|
-
export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, now }) {
|
|
536
|
+
export async function runLaneCheck(ref, flags, { request, lane, freeze, current, cwd, store, diff, deltaGather, catalog, designCheck, gate, reviewer = runReviewer, picker = pickByAgent, now }) {
|
|
465
537
|
const critical = flags.critical === true;
|
|
466
538
|
const maxIterations = flags["max-iterations"] === undefined ? MAX_ITERATIONS : Number(flags["max-iterations"]);
|
|
467
539
|
if (!Number.isInteger(maxIterations) || maxIterations < 1 || maxIterations > 100)
|
|
@@ -494,7 +566,7 @@ export async function runLaneCheck(ref, flags, { request, lane, freeze, current,
|
|
|
494
566
|
let gathered = null;
|
|
495
567
|
try {
|
|
496
568
|
if (tooLarge) throw tooLarge;
|
|
497
|
-
gathered = await ruleClauses(ref, { request, freeze, paths: changed.paths, deltaGather });
|
|
569
|
+
gathered = await ruleClauses(ref, { request, freeze, paths: changed.paths, deltaGather, agentPicker: (input) => picker({ ...runner, ...input }) });
|
|
498
570
|
} catch (error) {
|
|
499
571
|
if (!(error instanceof ReviewerError)) throw error;
|
|
500
572
|
rules = errorCheck("rules", error, firstRound("rules"), { clauseIds: [], deltaGatherId: null, clauseMapGatherId: freeze?.clauseMap?.gatherId ?? null });
|
package/dist/safety.js
CHANGED
|
@@ -613,8 +613,15 @@ export const codexSafetyHooksSnippet = () => ({
|
|
|
613
613
|
},
|
|
614
614
|
});
|
|
615
615
|
|
|
616
|
+
// The compact entry re-grounds the Freeze; the other entry prints the session
|
|
617
|
+
// kind on every other start, and the first prompt confirms it (MW1-92). Two
|
|
618
|
+
// entries, so a repository already carrying the compact one gains only the new.
|
|
616
619
|
export const regroundingHooksSnippet = () => ({
|
|
617
620
|
hooks: {
|
|
618
|
-
SessionStart: [
|
|
621
|
+
SessionStart: [
|
|
622
|
+
{ matcher: "^compact$", hooks: [{ type: "command", command: "nodii-dev hook session-start" }] },
|
|
623
|
+
{ matcher: "^(startup|resume|clear)$", hooks: [{ type: "command", command: "nodii-dev hook session-start" }] },
|
|
624
|
+
],
|
|
625
|
+
UserPromptSubmit: [{ hooks: [{ type: "command", command: "nodii-dev hook session-kind" }] }],
|
|
619
626
|
},
|
|
620
627
|
});
|