@flyingrobots/parley-emit 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,111 @@
1
+ // Where the receipt goes (spec §5, §5.2). The default is `.parley/receipts/<run>.jsonl` under the
2
+ // initial working directory, once hygiene is established; otherwise the XDG state directory keyed
3
+ // by a digest of the repository root; otherwise nothing, which is a startup failure. A location
4
+ // whose path carries a declared secret value is never chosen (§5.3: the path would print it).
5
+ import { closeSync, existsSync, linkSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { dirname, isAbsolute, join, resolve } from "node:path";
8
+ import { sha256 } from "./inv.ts";
9
+ import { carriesSecret } from "./redact.ts";
10
+
11
+ export interface Bookkeeping { op: "create" | "append" | "delete"; scope: string }
12
+ export interface Location {
13
+ readonly where: "repo" | "state";
14
+ readonly receiptDir: string;
15
+ readonly receiptPath: string;
16
+ readonly fd: number;
17
+ readonly warning?: { code: string; problem: string; remedy: string };
18
+ }
19
+ export interface LocationFailure { readonly code: "startup.receipt_unwritable" | "startup.secret_in_path"; readonly problem: string; readonly remedy: string }
20
+
21
+ export function repoRoot(cwd: string): string {
22
+ let dir = resolve(cwd);
23
+ for (;;) {
24
+ if (existsSync(join(dir, ".git"))) return dir;
25
+ const parent = dirname(dir);
26
+ if (parent === dir) return resolve(cwd);
27
+ dir = parent;
28
+ }
29
+ }
30
+
31
+ export function stateBase(env: Record<string, string | undefined>, home = homedir()): string {
32
+ const x = env.XDG_STATE_HOME;
33
+ return x && isAbsolute(x) ? x : join(home, ".local", "state");
34
+ }
35
+
36
+ function stateReceiptDir(cwd: string, env: Record<string, string | undefined>, home?: string): string {
37
+ const key = sha256(realpathSafe(repoRoot(cwd))).slice(0, 16);
38
+ return join(stateBase(env, home), "parley", key, "receipts");
39
+ }
40
+
41
+ /** The bookkeeping a run may perform, declared ahead of time in the command line (§4.3). */
42
+ export function bookkeepingFor(cwd: string, env: Record<string, string | undefined>, home?: string): Bookkeeping[] {
43
+ const repo = join(resolve(cwd), ".parley");
44
+ const state = stateReceiptDir(cwd, env, home);
45
+ return [
46
+ { op: "create", scope: `${join(repo, "receipts")}/` },
47
+ { op: "create", scope: join(repo, ".gitignore") },
48
+ { op: "delete", scope: `${join(repo, "receipts")}/` },
49
+ { op: "create", scope: `${state}/` },
50
+ { op: "delete", scope: `${state}/` },
51
+ ];
52
+ }
53
+
54
+ /**
55
+ * §5.2: `.parley/.gitignore` containing `*`, create-if-absent and never overwrite. The file is
56
+ * written whole to a temporary name and linked into place, so no process can read it empty.
57
+ */
58
+ function hygiene(parleyDir: string, nonce: string): "ok" | "users_file" {
59
+ mkdirSync(parleyDir, { recursive: true });
60
+ const file = join(parleyDir, ".gitignore");
61
+ if (!existsSync(file)) {
62
+ const tmp = join(parleyDir, `.gitignore.${nonce}.tmp`);
63
+ const fd = openSync(tmp, "wx");
64
+ try { writeSync(fd, "*\n"); } finally { closeSync(fd); }
65
+ try { linkSync(tmp, file); } catch (e) { if ((e as NodeJS.ErrnoException).code !== "EEXIST") { unlinkSafe(tmp); throw e; } } finally { unlinkSafe(tmp); }
66
+ }
67
+ const lines = readFileSync(file, "utf8").split(/\r?\n/);
68
+ return lines.includes("*") ? "ok" : "users_file";
69
+ }
70
+
71
+ function reserve(receiptDir: string, run: string): { receiptPath: string; fd: number } {
72
+ mkdirSync(receiptDir, { recursive: true });
73
+ const receiptPath = join(receiptDir, `${run}.jsonl`);
74
+ return { receiptPath, fd: openSync(receiptPath, "wx") };
75
+ }
76
+
77
+ export function chooseLocation(opts: { cwd: string; run: string; env: Record<string, string | undefined>; home?: string; secrets?: ReadonlySet<string> }): Location | LocationFailure {
78
+ const cwd = resolve(opts.cwd);
79
+ const secrets = opts.secrets ?? new Set<string>();
80
+ let warning: Location["warning"];
81
+ const repoDir = join(cwd, ".parley", "receipts");
82
+ if (carriesSecret(join(repoDir, `${opts.run}.jsonl`), secrets)) {
83
+ warning = { code: "receipt.relocated", problem: "the receipt path under the working directory would carry a declared secret value, so the receipt went to the state directory", remedy: "run from a directory whose path does not contain the secret, or leave the receipt where it went" };
84
+ } else {
85
+ try {
86
+ if (hygiene(join(cwd, ".parley"), opts.run) === "ok") return { where: "repo", receiptDir: repoDir, ...reserve(repoDir, opts.run) };
87
+ warning = { code: "receipt.relocated", problem: `${join(cwd, ".parley", ".gitignore")} exists without a line consisting of *, so it is a user's file and was left alone; the receipt went to the state directory`, remedy: "add a line consisting of * to .parley/.gitignore, or leave the receipt where it went" };
88
+ } catch {
89
+ // The working directory is not usable; fall back silently (the bootstrap line says where).
90
+ }
91
+ }
92
+ let stateDir: string;
93
+ try { stateDir = stateReceiptDir(cwd, opts.env, opts.home); } catch { return unwritable(cwd); }
94
+ if (carriesSecret(join(stateDir, `${opts.run}.jsonl`), secrets)) {
95
+ return { code: "startup.secret_in_path", problem: "every receipt location this writer can choose has a path carrying a declared secret value; no receipt path can be printed without disclosing it", remedy: "set XDG_STATE_HOME to an absolute path that does not contain the secret, or do not pass that value as a declared secret" };
96
+ }
97
+ try {
98
+ return { where: "state", receiptDir: stateDir, ...reserve(stateDir, opts.run), ...(warning ? { warning } : {}) };
99
+ } catch {
100
+ return unwritable(cwd);
101
+ }
102
+ }
103
+
104
+ function unwritable(cwd: string): LocationFailure {
105
+ return { code: "startup.receipt_unwritable", problem: `No writable receipt location: ${join(cwd, ".parley")} is not usable and the state directory is not writable`, remedy: "make .parley writable or set XDG_STATE_HOME to a writable absolute path" };
106
+ }
107
+
108
+ export function isLocationFailure(l: Location | LocationFailure): l is LocationFailure { return "code" in l; }
109
+
110
+ function realpathSafe(p: string): string { try { return realpathSync(p); } catch { return p; } }
111
+ function unlinkSafe(p: string): void { try { unlinkSync(p); } catch { /* already gone */ } }
package/src/redact.ts ADDED
@@ -0,0 +1,108 @@
1
+ // Redaction (spec §5.3). Declared secrets are named in the command description: an argument by
2
+ // its flag, a variable by its name, a credential source by a logical name. Their values are
3
+ // replaced with the literal `[redacted]` in a record's payload before any copy leaves the
4
+ // process, and the head records where. The envelope and the writer's own identifiers are never
5
+ // scrubbed: the writer refuses, at startup, to choose a run id or receipt path that carries a
6
+ // secret (location.ts, tool.ts), so there is nothing in them to replace.
7
+ export const REDACTED = "[redacted]";
8
+
9
+ export interface SecretNames { readonly flags: string[]; readonly env: string[]; readonly sources: string[] }
10
+
11
+ /** A name starting with `-` is a flag; an upper-case identifier is an environment variable; anything else is a logical source. */
12
+ export function classifySecrets(secrets: readonly string[]): SecretNames {
13
+ const flags: string[] = [], env: string[] = [], sources: string[] = [];
14
+ for (const s of new Set(secrets)) {
15
+ if (s.startsWith("-")) flags.push(s);
16
+ else if (/^[A-Z_][A-Z0-9_]*$/.test(s)) env.push(s);
17
+ else sources.push(s);
18
+ }
19
+ return { flags, env, sources };
20
+ }
21
+
22
+ /** The secret values an invocation carries: declared flag values from argv and declared variables from the environment. Empty values are supplied but carry nothing to replace. */
23
+ export function collectSecretValues(argv: readonly string[], names: SecretNames, env: Record<string, string | undefined>): Set<string> {
24
+ const values = new Set<string>();
25
+ for (let i = 0; i < argv.length; i++) {
26
+ const a = argv[i]!;
27
+ for (const flag of names.flags) {
28
+ if (a === flag && i + 1 < argv.length) values.add(argv[i + 1]!);
29
+ else if (a.startsWith(flag + "=")) values.add(a.slice(flag.length + 1));
30
+ }
31
+ }
32
+ for (const name of names.env) { const v = env[name]; if (v !== undefined) values.add(v); }
33
+ values.delete("");
34
+ return values;
35
+ }
36
+
37
+ /** Longest value first, so a secret that contains another is replaced whole rather than leaving its tail behind. */
38
+ function ordered(values: ReadonlySet<string>): string[] { return [...values].sort((a, b) => b.length - a.length); }
39
+
40
+ export function replaceSecrets(s: string, values: ReadonlySet<string>): string {
41
+ let out = s;
42
+ for (const v of ordered(values)) if (out.includes(v)) out = out.split(v).join(REDACTED);
43
+ return out;
44
+ }
45
+
46
+ /** True when any secret value occurs inside `s`, which disqualifies `s` as a writer-chosen identifier. */
47
+ export function carriesSecret(s: string, values: ReadonlySet<string>): boolean {
48
+ for (const v of values) if (s.includes(v)) return true;
49
+ return false;
50
+ }
51
+
52
+ /**
53
+ * The raw argv after §5.3: the element after a declared flag becomes `[redacted]` even when
54
+ * empty (it was supplied), `--name=value` keeps its flag, and a secret inside any other element
55
+ * is replaced within it.
56
+ */
57
+ export function redactArgv(argv: readonly string[], values: ReadonlySet<string>, flags: readonly string[] = []): { argv: string[]; indexes: number[] } {
58
+ const out = argv.map((a) => replaceSecrets(a, values));
59
+ const changed = new Set<number>();
60
+ out.forEach((a, i) => { if (a !== argv[i]) changed.add(i); });
61
+ for (let i = 0; i < argv.length; i++) {
62
+ for (const flag of flags) {
63
+ if (argv[i] === flag && i + 1 < argv.length) { out[i + 1] = REDACTED; changed.add(i + 1); }
64
+ else if (argv[i]!.startsWith(flag + "=")) { out[i] = flag + "=" + REDACTED; changed.add(i); }
65
+ }
66
+ }
67
+ return { argv: out, indexes: [...changed].sort((a, b) => a - b) };
68
+ }
69
+
70
+ function escapePointer(key: string): string { return key.replace(/~/g, "~0").replace(/\//g, "~1"); }
71
+
72
+ export interface ScrubOptions {
73
+ /** Keys whose string values are never scrubbed: writer digests, which a secret cannot occur in except by coincidence of hex. */
74
+ readonly skipKeys?: ReadonlySet<string>;
75
+ /** Scrub numbers, booleans and bigints whose decimal form is a secret (default true). A writer-built record passes false: its scalars (`status`, `dry_run`, `network`, `in`) are the writer's own and never a secret. */
76
+ readonly scalars?: boolean;
77
+ }
78
+
79
+ /**
80
+ * A deep copy of `value` with every secret replaced, and the RFC 6901 pointer of each place that
81
+ * changed. Strings are replaced within; a number, boolean or bigint whose decimal form is a
82
+ * secret becomes the string `[redacted]` (a PIN parsed to a number is still the PIN); an object
83
+ * key that carries a secret is renamed, and the pointer recorded is the renamed key's.
84
+ */
85
+ export function scrub(value: unknown, values: ReadonlySet<string>, pointer = "", found: string[] = [], opts: ScrubOptions = {}): unknown {
86
+ if (values.size === 0) return value;
87
+ if (typeof value === "string") {
88
+ const r = replaceSecrets(value, values);
89
+ if (r !== value) found.push(pointer || "/");
90
+ return r;
91
+ }
92
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
93
+ if (opts.scalars !== false && values.has(String(value))) { found.push(pointer || "/"); return REDACTED; }
94
+ return value;
95
+ }
96
+ if (Array.isArray(value)) return value.map((v, i) => scrub(v, values, `${pointer}/${i}`, found, opts));
97
+ if (value && typeof value === "object") {
98
+ const out: Record<string, unknown> = {};
99
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
100
+ const key = replaceSecrets(k, values);
101
+ const p = `${pointer}/${escapePointer(key)}`;
102
+ if (key !== k) found.push(p);
103
+ out[key] = opts.skipKeys?.has(k) && typeof v === "string" ? v : scrub(v, values, p, found, opts);
104
+ }
105
+ return out;
106
+ }
107
+ return value;
108
+ }
package/src/run.ts ADDED
@@ -0,0 +1,304 @@
1
+ // One run (spec §3): a single sequence across stdout, stderr and the receipt; the bootstrap line
2
+ // first, the head next, the `end` event last and immutable; every record's payload scrubbed of
3
+ // declared secrets before any copy leaves the process. The envelope is applied after scrubbing
4
+ // and is never scrubbed: the run id and the receipt path were chosen secret-free at startup.
5
+ import { closeSync, mkdirSync, openSync, writeSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { computeInv, digestInput, sha256, type InputDecl, type InputDescriptor } from "./inv.ts";
8
+ import { scrub } from "./redact.ts";
9
+
10
+ export interface Sink { write(line: string): void }
11
+ export const SIDECAR_THRESHOLD = 65_536;
12
+ export const CODE = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
13
+ const ENVELOPE_KEYS = ["t", "seq", "run", "_schema"] as const;
14
+ /**
15
+ * Writer-owned string fields never scrubbed in a writer-built record: digests (a secret cannot
16
+ * occur in one except by hex coincidence, and replacing it would corrupt the digest) and public
17
+ * identity the tool declared and every discovery line prints regardless: the tool's name and
18
+ * version, a command's name, a schema's id and version. Tool-supplied values that reach a
19
+ * writer-built record (`resolved`, input descriptors) are scrubbed in full before it is built.
20
+ */
21
+ const DIGEST_KEYS = new Set(["sha256", "inv", "tool", "v", "name", "id", "version"]);
22
+
23
+ export const SCHEMA_IDS = {
24
+ bootstrap: { id: "parley.run.bootstrap", version: "1.1.1" },
25
+ head: { id: "parley.receipt.head", version: "2.0.0" },
26
+ step: { id: "parley.receipt.step", version: "1.0.0" },
27
+ inputs: { id: "parley.receipt.inputs", version: "1.0.0" },
28
+ error: { id: "parley.error", version: "2.0.0" },
29
+ warning: { id: "parley.warning", version: "1.0.0" },
30
+ end: { id: "parley.end", version: "1.0.0" },
31
+ startupFailed: { id: "parley.startup.failed", version: "1.0.0" },
32
+ sidecar: { id: "parley.sidecar", version: "1.0.0" },
33
+ redaction: { id: "parley.redaction", version: "1.0.0" },
34
+ command: { id: "parley.command", version: "1.0.0" },
35
+ schema: { id: "parley.schema", version: "1.0.0" },
36
+ page: { id: "parley.page", version: "1.0.0" },
37
+ } as const;
38
+
39
+ export type SchemaRef = { readonly id: string; readonly version: string };
40
+ export type Record_ = Record<string, unknown>;
41
+
42
+ export interface Diagnostic {
43
+ code: string; problem: string; remedy?: string; remedy_target?: string;
44
+ measured?: number; limit?: number; retryable?: boolean; detail?: unknown;
45
+ }
46
+
47
+ export class ParleyClosed extends Error {
48
+ constructor() { super("the run has ended; nothing may follow end (spec §3.3)"); this.name = "ParleyClosed"; }
49
+ }
50
+
51
+ export interface RunInit {
52
+ tool: string; v: string; id: string; session?: string; dryRun: boolean;
53
+ stdout: Sink; stderr: Sink; receiptFd: number; receiptPath: string; receiptDir: string;
54
+ secretValues: Set<string>; now: () => number; cwd: string;
55
+ command: string; resolved: unknown; inputs: InputDecl[];
56
+ headRedacted: boolean; human?: (line: Record_) => string | null;
57
+ }
58
+
59
+ type SinkName = "stdout" | "stderr" | "receipt";
60
+ interface Emit { to: { stdout?: boolean; stderr?: boolean; receipt?: boolean }; writer?: boolean; noSidecar?: boolean; deferFailures?: boolean }
61
+
62
+ export class Run {
63
+ readonly id: string; readonly tool: string; readonly v: string; readonly session?: string;
64
+ readonly dryRun: boolean; readonly receiptPath: string; readonly receiptDir: string; readonly cwd: string;
65
+ private seq = -1;
66
+ private closed = false;
67
+ private receiptOpen = true;
68
+ private errorReported = false;
69
+ private redactedAny: boolean;
70
+ private failedSinks = new Set<SinkName>();
71
+ private sidecarFailed = false;
72
+ private deferred: { sink: SinkName; error: unknown }[] = [];
73
+ private inputsSettled = false;
74
+ private supplied = new Map<string, Uint8Array>();
75
+ private finalStatus: number | null = null;
76
+ private readonly init: RunInit;
77
+
78
+ constructor(init: RunInit) {
79
+ this.init = init;
80
+ this.id = init.id; this.tool = init.tool; this.v = init.v; this.session = init.session;
81
+ this.dryRun = init.dryRun; this.receiptPath = init.receiptPath; this.receiptDir = init.receiptDir; this.cwd = init.cwd;
82
+ this.redactedAny = init.headRedacted;
83
+ }
84
+
85
+ /** True once `end` has been emitted. */
86
+ get ended(): boolean { return this.closed; }
87
+ /** The exit status `end` carried, once ended. */
88
+ get status(): number | null { return this.finalStatus; }
89
+ /** True when any stream, the receipt or a sidecar could not be written: the run closes with 4. */
90
+ get sinkFailed(): boolean { return this.failedSinks.size > 0 || this.sidecarFailed; }
91
+
92
+ // ---- emission -------------------------------------------------------------------------
93
+
94
+ private next(): { seq: number; t: number } { this.seq += 1; return { seq: this.seq, t: this.init.now() }; }
95
+
96
+ private envelope(payload: Record_, schema: SchemaRef, at: { seq: number; t: number }): Record_ {
97
+ const { event, ...rest } = payload;
98
+ return { event, t: at.t, seq: at.seq, run: this.id, ...rest, _schema: { id: schema.id, version: schema.version } };
99
+ }
100
+
101
+ private refuseEnvelopeKeys(obj: Record_ | undefined, what: string): void {
102
+ if (!obj) return;
103
+ for (const k of ENVELOPE_KEYS) if (k in obj) throw new TypeError(`${what} must not carry ${k}; the writer owns the envelope (spec §1.3)`);
104
+ }
105
+
106
+ private write(sink: SinkName, text: string, defer = false): boolean {
107
+ if (this.failedSinks.has(sink)) return false;
108
+ try {
109
+ if (sink === "receipt") { if (!this.receiptOpen) return false; writeSync(this.init.receiptFd, text); }
110
+ else this.init[sink].write(text);
111
+ return true;
112
+ } catch (e) {
113
+ this.failedSinks.add(sink);
114
+ if (defer) this.deferred.push({ sink, error: e });
115
+ else if (!this.closed) this.reportSinkFailure(sink, e);
116
+ return false;
117
+ }
118
+ }
119
+
120
+ /** An empty prose rendering means "say nothing here"; a write of nothing is not a sink failure. */
121
+ private writeOrSkip(sink: "stdout" | "stderr", text: string, defer = false): boolean { return text === "" ? true : this.write(sink, text, defer); }
122
+
123
+ private reportSinkFailure(sink: string, e: unknown) {
124
+ const msg = e instanceof Error ? e.message : String(e);
125
+ this.emit({ to: { stderr: sink !== "stderr", receipt: sink !== "receipt" }, writer: true }, { event: "error", code: sink === "sidecar" ? "sink.sidecar_failed" : "sink.write_failed", problem: `writing to ${sink} failed: ${msg}`, remedy: "the run will close with status 4; whatever other sinks received is preserved" }, SCHEMA_IDS.error);
126
+ }
127
+
128
+ /** Internal: report sink failures held back during the bootstrap write, now that the head is in place (§5: the head is the receipt's first line). */
129
+ flushDeferredFailures(): void {
130
+ const held = this.deferred; this.deferred = [];
131
+ for (const { sink, error } of held) if (!this.closed) this.reportSinkFailure(sink, error);
132
+ }
133
+
134
+ private line(obj: Record_): string { return JSON.stringify(obj) + "\n"; }
135
+
136
+ private rendererFailed = false;
137
+
138
+ private prose(obj: Record_): string {
139
+ let custom: string | null = null;
140
+ try { custom = this.init.human?.(obj) ?? null; } catch (e) {
141
+ custom = null;
142
+ if (!this.rendererFailed && !this.closed) {
143
+ this.rendererFailed = true;
144
+ const msg = e instanceof Error ? e.message : String(e);
145
+ queueMicrotask(() => { try { if (!this.closed) this.warning({ code: "human.renderer_failed", problem: `the tool's --human renderer threw: ${msg}; the default rendering is used for the rest of the run`, remedy: "fix the renderer; the receipt is complete regardless" }); } catch { /* the run ended first */ } });
146
+ }
147
+ }
148
+ if (typeof custom === "string") return custom.endsWith("\n") ? custom : custom + "\n";
149
+ switch (obj.event) {
150
+ // Prose is for a person or a pipe into something like a pull-request comment; the bootstrap
151
+ // line and a successful end say nothing there, so the tool's rendering stands alone. The
152
+ // receipt still carries both.
153
+ case "run": return "";
154
+ case "end": return obj.status === 0 ? "" : `end: status ${String(obj.status)}${obj.redacted ? ", receipt redacted" : ""}; receipt at ${String(obj.receipt)}\n`;
155
+ case "error": case "warning": return `${String(obj.event)} ${String(obj.code)}: ${String(obj.problem)}${obj.remedy ? ` (${String(obj.remedy)})` : ""}\n`;
156
+ default: return `${String(obj.event)}: ${JSON.stringify(obj)}\n`;
157
+ }
158
+ }
159
+
160
+ /** Scrub a payload's values; `event` is envelope, named by the writer or the tool's schema, and is never a secret. */
161
+ private scrubPayload(payload: Record_, found: string[], writer: boolean): Record_ {
162
+ const { event, ...rest } = payload;
163
+ const scrubbed = scrub(rest, this.init.secretValues, "", found, writer ? { skipKeys: DIGEST_KEYS, scalars: false } : {}) as Record_;
164
+ return event === undefined ? scrubbed : { event, ...scrubbed };
165
+ }
166
+
167
+ /**
168
+ * Emit one event to the named streams as copies sharing seq, t and event. The receipt copy may
169
+ * carry `receiptExtra` fields the stream copy omits (§1.3). Returns the event's seq.
170
+ */
171
+ private emit(how: Emit, payload: Record_, schema: SchemaRef, receiptExtra?: Record_): number {
172
+ if (this.closed) throw new ParleyClosed();
173
+ this.refuseEnvelopeKeys(payload, "a record"); this.refuseEnvelopeKeys(receiptExtra, "receiptExtra");
174
+ const found: string[] = [];
175
+ const scrubbed = this.scrubPayload(payload, found, how.writer === true);
176
+ const extraFound: string[] = [];
177
+ const extra = receiptExtra ? this.scrubPayload(receiptExtra, extraFound, how.writer === true) : undefined;
178
+ const at = this.next();
179
+ const rec = this.envelope(scrubbed, schema, at);
180
+ const human = this.init.human !== undefined;
181
+ if (how.to.stdout) this.writeOrSkip("stdout", human ? this.prose(rec) : this.line(rec), how.deferFailures);
182
+ if (how.to.stderr) this.writeOrSkip("stderr", human ? this.prose(rec) : this.line(rec), how.deferFailures);
183
+ if (how.to.receipt) {
184
+ const full = extra ? this.envelope({ ...scrubbed, ...extra, event: scrubbed.event }, schema, at) : rec;
185
+ const text = JSON.stringify(full);
186
+ if (!how.noSidecar && Buffer.byteLength(text, "utf8") > SIDECAR_THRESHOLD) this.sidecar(at.seq, text);
187
+ else this.write("receipt", text + "\n");
188
+ }
189
+ for (const at_ of [...found, ...extraFound]) this.redaction(at.seq, at_);
190
+ return at.seq;
191
+ }
192
+
193
+ private sidecar(source: number, text: string) {
194
+ const rel = `${this.id}/${source}.json`;
195
+ const bytes = Buffer.from(text, "utf8");
196
+ try {
197
+ mkdirSync(join(this.receiptDir, this.id), { recursive: true });
198
+ const fd = openSync(join(this.receiptDir, rel), "wx");
199
+ try { writeSync(fd, bytes); } finally { closeSync(fd); }
200
+ } catch (e) {
201
+ // The receipt file itself is fine: keep the record inline so the bundle stays complete (§5),
202
+ // then say what failed; the run still closes with 4 because a write failed (§5.4).
203
+ this.sidecarFailed = true;
204
+ this.write("receipt", text + "\n");
205
+ this.reportSinkFailure("sidecar", e);
206
+ return;
207
+ }
208
+ const at = this.next();
209
+ this.write("receipt", this.line(this.envelope({ event: "sidecar", source, path: rel, bytes: bytes.length, sha256: sha256(bytes) }, SCHEMA_IDS.sidecar, at)));
210
+ }
211
+
212
+ private redaction(inSeq: number, at: string) {
213
+ this.redactedAny = true;
214
+ const a = this.next();
215
+ this.write("receipt", this.line(this.envelope({ event: "redaction", in: inSeq, at }, SCHEMA_IDS.redaction, a)));
216
+ }
217
+
218
+ // ---- the public surface --------------------------------------------------------------
219
+
220
+ /** Internal: the bootstrap line, stdout only, seq 0 (§3.1). A stdout failure here is reported after the head. */
221
+ bootstrap(inv: string | undefined): void {
222
+ const rec: Record_ = { event: "run", tool: this.tool, v: this.v, ...(inv ? { inv } : {}), ...(this.session ? { session: this.session } : {}), paths: { receipt: this.receiptPath }, ...(this.dryRun ? { dry_run: true } : {}) };
223
+ this.emit({ to: { stdout: true }, writer: true, deferFailures: true }, rec, SCHEMA_IDS.bootstrap);
224
+ }
225
+
226
+ /** Internal: the receipt head, receipt only, never a sidecar (§5). */
227
+ head(fields: Record_): void { this.emit({ to: { receipt: true }, writer: true, noSidecar: true }, { event: "receipt.head", ...fields }, SCHEMA_IDS.head); }
228
+
229
+ /** Internal: a discovery line (§4.1), a writer-built record describing public identity. */
230
+ describe(record: Record_, schema: SchemaRef): number { return this.emit({ to: { stdout: true, receipt: true }, writer: true }, record, schema); }
231
+
232
+ /** A result: to stdout and the receipt. `receiptExtra` goes to the receipt copy only. */
233
+ result(record: Record_, schema: SchemaRef, receiptExtra?: Record_): number {
234
+ if (typeof record.event !== "string" || !record.event) throw new TypeError("a result needs an event name");
235
+ return this.emit({ to: { stdout: true, receipt: true } }, record, schema, receiptExtra);
236
+ }
237
+
238
+ /** One page of unbounded output (§7.2); rows belong in `receiptExtra` or in the stream copy as the tool documents. */
239
+ page(cursor: string | null, hasMore: boolean, record: Record_ = {}, receiptExtra?: Record_): number {
240
+ if (hasMore && !cursor) throw new TypeError("a page with has_more needs a cursor (spec §7.2)");
241
+ return this.emit({ to: { stdout: true, receipt: true } }, { event: "page", ...record, ...(cursor ? { cursor } : {}), has_more: hasMore }, SCHEMA_IDS.page, receiptExtra);
242
+ }
243
+
244
+ /** One decision and why, receipt only (§5). */
245
+ step(decision: string, because: string, detail?: unknown): number {
246
+ return this.emit({ to: { receipt: true } }, { event: "receipt.step", decision, because, ...(detail === undefined ? {} : { detail }) }, SCHEMA_IDS.step);
247
+ }
248
+
249
+ warning(d: Diagnostic): number { return this.emit({ to: { stderr: true, receipt: true } }, { event: "warning", ...this.diagnostic(d) }, SCHEMA_IDS.warning); }
250
+
251
+ /** A structured error (§6). The run then closes with status 2 unless `end` is given another non-zero status. `receiptExtra` goes to the receipt copy only. */
252
+ error(d: Diagnostic, receiptExtra?: Record_): number {
253
+ this.errorReported = true;
254
+ return this.emit({ to: { stderr: true, receipt: true } }, { event: "error", ...this.diagnostic(d) }, SCHEMA_IDS.error, receiptExtra);
255
+ }
256
+
257
+ private diagnostic(d: Diagnostic): Record_ {
258
+ if (!CODE.test(d.code)) throw new TypeError(`code ${JSON.stringify(d.code)} is not two or more dot-separated lowercase segments (spec §6)`);
259
+ if (!d.problem) throw new TypeError("problem is never empty (spec §6)");
260
+ const out: Record_ = { code: d.code, problem: d.problem };
261
+ for (const k of ["remedy", "remedy_target", "measured", "limit", "retryable", "detail"] as const) if (d[k] !== undefined) out[k] = d[k];
262
+ return out;
263
+ }
264
+
265
+ /** Supply the bytes of a declared input the writer cannot read itself, such as stdin. */
266
+ input(path: string, bytes: Uint8Array | string): void {
267
+ this.supplied.set(path, typeof bytes === "string" ? Buffer.from(bytes, "utf8") : bytes);
268
+ }
269
+
270
+ /** Digest the declared inputs and emit `receipt.inputs` with `inv` once settled (§2.2). Idempotent; `end` calls it. */
271
+ finaliseInputs(): InputDescriptor[] {
272
+ if (this.inputsSettled || this.init.inputs.length === 0) { this.inputsSettled = true; return []; }
273
+ this.inputsSettled = true;
274
+ const raw = this.init.inputs.map((i) => digestInput(this.cwd, i, this.supplied.get(i.path)));
275
+ // The preimage and the record both take the redacted descriptors (§2.2: no secret value in inv).
276
+ const inputs = scrub(raw, this.init.secretValues, "", [], { skipKeys: DIGEST_KEYS, scalars: false }) as InputDescriptor[];
277
+ const inv = computeInv({ tool: this.tool, v: this.v, command: this.init.command, resolved: this.init.resolved, inputs });
278
+ this.emit({ to: { receipt: true }, writer: true }, { event: "receipt.inputs", inputs, ...(inv ? { inv } : {}) }, SCHEMA_IDS.inputs);
279
+ return inputs;
280
+ }
281
+
282
+ /**
283
+ * Close the run (§3.3). Status defaults to 2 when an error was reported, else 0; a sink failure
284
+ * forces 4. Returns the exit status the process should exit with.
285
+ */
286
+ end(status?: number): number {
287
+ if (this.closed) return this.finalStatus ?? 4;
288
+ if (status !== undefined && (!Number.isInteger(status) || status < 0 || status > 255 || status === 3)) throw new TypeError("end status is an integer 0-255 other than 3 (spec §3.4)");
289
+ if (status === 0 && this.errorReported) throw new TypeError("a run that reported an error cannot end with status 0 (spec §3.4); a recovered condition is a warning");
290
+ try { this.finaliseInputs(); } catch { /* an unreadable input is already recorded; nothing else can fail here */ }
291
+ let s = status ?? (this.errorReported ? 2 : 0);
292
+ if (this.sinkFailed) s = 4;
293
+ const at = this.next();
294
+ const rec = this.envelope(this.scrubPayload({ event: "end", status: s, receipt: this.receiptPath, redacted: this.redactedAny }, [], true), SCHEMA_IDS.end, at);
295
+ this.closed = true;
296
+ const okOut = this.writeOrSkip("stdout", this.init.human ? this.prose(rec) : this.line(rec));
297
+ const okRec = this.write("receipt", this.line(rec));
298
+ this.receiptOpen = false;
299
+ let closeOk = true;
300
+ try { closeSync(this.init.receiptFd); } catch { closeOk = false; }
301
+ this.finalStatus = okOut && okRec && closeOk ? s : 4;
302
+ return this.finalStatus;
303
+ }
304
+ }