@flyingrobots/parley-emit 0.0.0-stage → 0.2.4

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/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@flyingrobots/parley-emit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.4",
4
+ "description": "A writer for the Parley output protocol: bootstrap, receipt, sequence, redaction, end, exit status.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./src/index.ts",
8
+ "types": "./src/index.ts",
9
+ "exports": {
10
+ ".": "./src/index.ts"
11
+ },
12
+ "files": [
13
+ "src",
14
+ "README.md",
15
+ "CHANGELOG.md",
16
+ "LICENSE",
17
+ "NOTICE"
18
+ ],
19
+ "scripts": {
20
+ "test": "bun test",
21
+ "sync-schemas": "bun run scripts/sync-schemas.ts"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/flyingrobots/parley.git",
26
+ "directory": "packages/parley-emit"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public",
30
+ "registry": "https://registry.npmjs.org/"
31
+ },
32
+ "author": "James Ross",
33
+ "engines": {
34
+ "bun": ">=1.2"
35
+ }
36
+ }
package/src/check.ts ADDED
@@ -0,0 +1,198 @@
1
+ // A bounded JSON Schema (draft 2020-12) checker, written for exactly one job: re-validating the
2
+ // record a history transform returned against the schema for its exact advertised pair (§4.5),
3
+ // inside a package that has no runtime dependencies. It is not a general validator and does not
4
+ // pretend to be one.
5
+ //
6
+ // The honest part is the boundary. It implements the constructs the protocol's own schemas use
7
+ // and **says so** when a schema uses one it does not, rather than ignoring the keyword and
8
+ // reporting a line as checked that was not. A caller that cannot verify a line can then refuse
9
+ // it. `test/parley-emit.test.ts` asserts every schema this package ships is inside the subset,
10
+ // so a new draft that reaches for `$ref` fails a test here rather than silently going unchecked.
11
+
12
+ /** The keywords that carry no assertion; present for readers and ignored here. */
13
+ const ANNOTATIONS = new Set(["$schema", "$id", "$anchor", "$comment", "title", "description", "examples", "default", "deprecated", "readOnly", "writeOnly"]);
14
+ /** Everything this checker understands. A keyword outside it is reported, never ignored. */
15
+ const SUPPORTED = new Set([
16
+ ...ANNOTATIONS,
17
+ "type", "const", "enum", "required", "properties", "additionalProperties", "items",
18
+ "minItems", "maxItems", "minLength", "maxLength", "minimum", "maximum",
19
+ "exclusiveMinimum", "exclusiveMaximum", "minProperties", "maxProperties",
20
+ "pattern", "format", "not", "anyOf", "allOf", "oneOf", "if", "then", "else",
21
+ ]);
22
+ /** The formats this checker asserts. Any other is reported as unsupported, not waved through. */
23
+ const FORMATS: Record<string, RegExp> = {
24
+ // RFC 6901, as ajv-formats asserts it: empty, or one or more escaped segments.
25
+ "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/u,
26
+ };
27
+
28
+ /**
29
+ * The first construct in `schema` this checker does not implement, or `null` when the whole
30
+ * document is inside the subset. This is a property of the schema and not of any one record, so
31
+ * it is checked **before** a value is walked: a keyword nested under a property the record does
32
+ * not happen to carry would otherwise go unnoticed, and "we checked the parts we understood" is
33
+ * exactly the claim this file exists not to make. Memoised per document.
34
+ */
35
+ export function schemaSubsetGap(schema: unknown): string | null {
36
+ if (typeof schema !== "object" || schema === null) return walkSchema(schema);
37
+ const cached = gaps.get(schema as object);
38
+ if (cached !== undefined) return cached;
39
+ const gap = walkSchema(schema);
40
+ gaps.set(schema as object, gap);
41
+ return gap;
42
+ }
43
+ const gaps = new WeakMap<object, string | null>();
44
+
45
+ const SUBSCHEMA = ["items", "not", "if", "then", "else", "additionalProperties"] as const;
46
+ const SUBSCHEMA_LISTS = ["anyOf", "allOf", "oneOf"] as const;
47
+
48
+ function walkSchema(node: unknown): string | null {
49
+ if (node === true || node === false || node === undefined) return null;
50
+ if (typeof node !== "object" || node === null || Array.isArray(node)) return "a schema that is not an object or a boolean";
51
+ const s = node as Record<string, unknown>;
52
+ for (const k of Object.keys(s)) {
53
+ if (!SUPPORTED.has(k)) return k;
54
+ if (k === "format" && !Object.hasOwn(FORMATS, String(s[k]))) return `format ${String(s[k])}`;
55
+ }
56
+ if (Array.isArray(s.items)) return "items as a tuple";
57
+ for (const k of SUBSCHEMA) { const gap = walkSchema(s[k]); if (gap !== null) return gap; }
58
+ for (const k of SUBSCHEMA_LISTS) {
59
+ if (!Array.isArray(s[k])) continue;
60
+ for (const sub of s[k] as unknown[]) { const gap = walkSchema(sub); if (gap !== null) return gap; }
61
+ }
62
+ if (s.properties !== null && typeof s.properties === "object" && !Array.isArray(s.properties)) {
63
+ for (const sub of Object.values(s.properties as Record<string, unknown>)) { const gap = walkSchema(sub); if (gap !== null) return gap; }
64
+ }
65
+ return null;
66
+ }
67
+
68
+ export type CheckResult =
69
+ /** The record satisfies the schema. */
70
+ | { readonly ok: true }
71
+ /** The record does not satisfy it; `errors` names where, shortest path first. */
72
+ | { readonly ok: false; readonly errors: readonly string[] }
73
+ /** The schema uses a construct this checker does not implement, so nothing was established. */
74
+ | { readonly ok: false; readonly errors: readonly string[]; readonly unsupported: string };
75
+
76
+ /** The same refusal, raised from inside the walk of a value as a guard of last resort. */
77
+ class Unsupported extends Error {
78
+ constructor(readonly keyword: string) { super(`the schema uses ${keyword}, which this checker does not implement`); }
79
+ }
80
+
81
+ /**
82
+ * Check `value` against `schema`. Returns `ok` when it satisfies it, an error list when it does
83
+ * not, and an `unsupported` keyword when the schema is outside the subset — in which case the
84
+ * result establishes nothing either way, and a caller that must not guess should refuse.
85
+ */
86
+ export function checkRecord(value: unknown, schema: unknown): CheckResult {
87
+ const gap = schemaSubsetGap(schema);
88
+ if (gap !== null) return { ok: false, errors: [`the schema uses ${gap}, which this checker does not implement`], unsupported: gap };
89
+ const errors: string[] = [];
90
+ try { validate(schema, value, "", errors); }
91
+ catch (e) {
92
+ if (e instanceof Unsupported) return { ok: false, errors: [e.message], unsupported: e.keyword };
93
+ throw e;
94
+ }
95
+ return errors.length === 0 ? { ok: true } : { ok: false, errors };
96
+ }
97
+
98
+ function at(path: string): string { return path === "" ? "/" : path; }
99
+
100
+ function kindOf(v: unknown): string {
101
+ if (v === null) return "null";
102
+ if (Array.isArray(v)) return "array";
103
+ const t = typeof v;
104
+ return t === "number" ? (Number.isInteger(v as number) ? "integer" : "number") : t;
105
+ }
106
+
107
+ function isType(v: unknown, t: string): boolean {
108
+ if (t === "number") return typeof v === "number" && Number.isFinite(v);
109
+ if (t === "integer") return typeof v === "number" && Number.isInteger(v);
110
+ return kindOf(v) === t;
111
+ }
112
+
113
+ function same(a: unknown, b: unknown): boolean {
114
+ if (a === b) return true;
115
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => same(x, b[i]));
116
+ if (a && b && typeof a === "object" && typeof b === "object" && !Array.isArray(a) && !Array.isArray(b)) {
117
+ const ka = Object.keys(a as object), kb = Object.keys(b as object);
118
+ return ka.length === kb.length && ka.every((k) => Object.hasOwn(b as object, k) && same((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]));
119
+ }
120
+ return false;
121
+ }
122
+
123
+ function satisfies(schema: unknown, value: unknown): boolean {
124
+ const scratch: string[] = [];
125
+ validate(schema, value, "", scratch);
126
+ return scratch.length === 0;
127
+ }
128
+
129
+ function regex(pattern: string): RegExp {
130
+ try { return new RegExp(pattern, "u"); } catch { return new RegExp(pattern); }
131
+ }
132
+
133
+ function validate(schema: unknown, value: unknown, path: string, errors: string[]): void {
134
+ if (schema === true || schema === undefined) return;
135
+ if (schema === false) { errors.push(`${at(path)} is not allowed here`); return; }
136
+ if (typeof schema !== "object" || Array.isArray(schema)) throw new Unsupported("a schema that is not an object or a boolean");
137
+ const s = schema as Record<string, unknown>;
138
+ for (const k of Object.keys(s)) if (!SUPPORTED.has(k)) throw new Unsupported(k);
139
+
140
+ if (s.type !== undefined) {
141
+ const types = Array.isArray(s.type) ? (s.type as string[]) : [s.type as string];
142
+ if (!types.some((t) => isType(value, t))) errors.push(`${at(path)} is ${kindOf(value)}, not ${types.join(" or ")}`);
143
+ }
144
+ if (s.const !== undefined && !same(value, s.const)) errors.push(`${at(path)} must be ${JSON.stringify(s.const)}`);
145
+ if (s.enum !== undefined) {
146
+ const options = s.enum as unknown[];
147
+ if (!options.some((o) => same(value, o))) errors.push(`${at(path)} must be one of ${JSON.stringify(options)}`);
148
+ }
149
+ if (s.not !== undefined && satisfies(s.not, value)) errors.push(`${at(path)} must not match the excluded shape`);
150
+ if (s.allOf !== undefined) for (const sub of s.allOf as unknown[]) validate(sub, value, path, errors);
151
+ if (s.anyOf !== undefined && !(s.anyOf as unknown[]).some((sub) => satisfies(sub, value))) errors.push(`${at(path)} matches none of the allowed shapes`);
152
+ if (s.oneOf !== undefined && (s.oneOf as unknown[]).filter((sub) => satisfies(sub, value)).length !== 1) errors.push(`${at(path)} must match exactly one of the allowed shapes`);
153
+ if (s.if !== undefined) {
154
+ const branch = satisfies(s.if, value) ? s.then : s.else;
155
+ if (branch !== undefined) validate(branch, value, path, errors);
156
+ }
157
+
158
+ if (typeof value === "string") {
159
+ if (typeof s.minLength === "number" && [...value].length < s.minLength) errors.push(`${at(path)} is shorter than ${s.minLength}`);
160
+ if (typeof s.maxLength === "number" && [...value].length > s.maxLength) errors.push(`${at(path)} is longer than ${s.maxLength}`);
161
+ if (typeof s.pattern === "string" && !regex(s.pattern).test(value)) errors.push(`${at(path)} does not match ${s.pattern}`);
162
+ if (typeof s.format === "string") {
163
+ const f = FORMATS[s.format];
164
+ if (f === undefined) throw new Unsupported(`format ${s.format}`);
165
+ if (!f.test(value)) errors.push(`${at(path)} is not a ${s.format}`);
166
+ }
167
+ }
168
+
169
+ if (typeof value === "number") {
170
+ if (typeof s.minimum === "number" && value < s.minimum) errors.push(`${at(path)} is below ${s.minimum}`);
171
+ if (typeof s.maximum === "number" && value > s.maximum) errors.push(`${at(path)} is above ${s.maximum}`);
172
+ if (typeof s.exclusiveMinimum === "number" && value <= s.exclusiveMinimum) errors.push(`${at(path)} is not above ${s.exclusiveMinimum}`);
173
+ if (typeof s.exclusiveMaximum === "number" && value >= s.exclusiveMaximum) errors.push(`${at(path)} is not below ${s.exclusiveMaximum}`);
174
+ }
175
+
176
+ if (Array.isArray(value)) {
177
+ if (typeof s.minItems === "number" && value.length < s.minItems) errors.push(`${at(path)} has fewer than ${s.minItems} items`);
178
+ if (typeof s.maxItems === "number" && value.length > s.maxItems) errors.push(`${at(path)} has more than ${s.maxItems} items`);
179
+ if (s.items !== undefined) {
180
+ if (Array.isArray(s.items)) throw new Unsupported("items as a tuple");
181
+ value.forEach((item, i) => validate(s.items, item, `${path}/${i}`, errors));
182
+ }
183
+ }
184
+
185
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
186
+ const obj = value as Record<string, unknown>;
187
+ const keys = Object.keys(obj);
188
+ if (Array.isArray(s.required)) for (const k of s.required as string[]) if (!Object.hasOwn(obj, k)) errors.push(`${at(path)} is missing ${k}`);
189
+ if (typeof s.minProperties === "number" && keys.length < s.minProperties) errors.push(`${at(path)} has fewer than ${s.minProperties} properties`);
190
+ if (typeof s.maxProperties === "number" && keys.length > s.maxProperties) errors.push(`${at(path)} has more than ${s.maxProperties} properties`);
191
+ const properties = (s.properties ?? {}) as Record<string, unknown>;
192
+ for (const k of keys) {
193
+ if (Object.hasOwn(properties, k)) { validate(properties[k], obj[k], `${path}/${k}`, errors); continue; }
194
+ if (s.additionalProperties === false) errors.push(`${at(path)} must not carry ${k}`);
195
+ else if (s.additionalProperties !== undefined && s.additionalProperties !== true) validate(s.additionalProperties, obj[k], `${path}/${k}`, errors);
196
+ }
197
+ }
198
+ }
package/src/history.ts ADDED
@@ -0,0 +1,229 @@
1
+ // The shared history stream (spec §8, informative). An opt-in second sink that receives the
2
+ // bytes of the local receipt, so a caller gets one timeline across tools, repositories, agents
3
+ // and people. The dependency runs one way: the stream consumes the format and the format never
4
+ // requires the stream, so nothing here can change what a run with no stream configured emits,
5
+ // and a stream that cannot be written is a warning rather than a failure.
6
+ //
7
+ // Scope and expiry (the decision flyingrobots/parley#3 left open): one stream per user per
8
+ // machine, written as dated daily segments, keeping `days` of them. Expiry deletes whole
9
+ // segments, because the stream is append-only with concurrent writers and rewriting a live
10
+ // append-only file to expire a record is the one operation that cannot be made safe. With
11
+ // `days >= 1` today's segment is never a candidate and the newest deletable one is already
12
+ // `days` days old, so no run is holding it open.
13
+ //
14
+ // Redaction (the other decision): none of its own. The sink is handed the same string the
15
+ // receipt was handed, after §5.3 has replaced every declared secret, so a credential cannot
16
+ // reach the stream unless it reached the receipt first. What is left to protect is reach rather
17
+ // than content, so the directory is owner-only, segments are owner-only, a record stored as a
18
+ // sidecar reaches the stream as its `sidecar` event and never as its stored bytes, and nothing
19
+ // is sent anywhere.
20
+ import { closeSync, mkdirSync, openSync, readdirSync, statSync, unlinkSync, writeSync } from "node:fs";
21
+ import { isAbsolute, join } from "node:path";
22
+ import { sha256 } from "./inv.ts";
23
+ import { stateBase } from "./location.ts";
24
+ import { carriesSecret } from "./redact.ts";
25
+ import type { HistoryRefusal } from "./refusal.ts";
26
+
27
+ /** The directory the stream lives in, or an off switch. Absolute when it names a directory. */
28
+ export const HISTORY_ENV = "PARLEY_HISTORY";
29
+ /** How many daily segments to keep, today's included. */
30
+ export const HISTORY_DAYS_ENV = "PARLEY_HISTORY_DAYS";
31
+ export const HISTORY_DEFAULT_DAYS = 14;
32
+ /** A century of daily segments. Beyond this the window's own start date stops being representable. */
33
+ export const HISTORY_MAX_DAYS = 36_500;
34
+ const DIR_MODE = 0o700;
35
+ const FILE_MODE = 0o600;
36
+ const OFF = new Set(["0", "off", "false", "no", "none"]);
37
+ const SEGMENT = /^\d{4}-\d{2}-\d{2}\.jsonl$/;
38
+ const DAY_MS = 86_400_000;
39
+
40
+ export interface HistoryPlan {
41
+ readonly dir: string;
42
+ readonly path: string;
43
+ readonly days: number;
44
+ /** `env` when `PARLEY_HISTORY` named the directory, `state` when the known state path exists. */
45
+ readonly source: "env" | "state";
46
+ }
47
+
48
+ export interface HistorySink {
49
+ readonly dir: string;
50
+ readonly path: string;
51
+ /**
52
+ * Append one whole line, newline included, in a single write. Throws the first time the append
53
+ * does not land; the sink is then closed and every later append is a no-op, so one failure is
54
+ * reported once and the run carries on.
55
+ */
56
+ append(line: string): void;
57
+ close(): void;
58
+ }
59
+
60
+ /**
61
+ * A user-defined projection of one record for the stream copy (flyingrobots#57). It is handed the
62
+ * parsed record the receipt already holds, after §5.3 has replaced every declared secret, and
63
+ * returns a record to put on the stream, nothing to withhold the line, or a `refuse(...)` to
64
+ * withhold it under a code of its own (flyingrobots#60). The envelope is not its to change: the
65
+ * writer reattaches `event`, `t`, `seq`, `run` and `_schema` afterwards and re-validates the
66
+ * returned body against the schema for that exact pair.
67
+ */
68
+ export type HistoryTransform = (record: Record<string, unknown>) => Record<string, unknown> | HistoryRefusal | undefined | null | void;
69
+
70
+ /** `MainOptions.history` in its long form: the sink, the transform, and what to call it. */
71
+ export interface HistoryConfig {
72
+ /** A sink to use instead of resolving one from the environment; `null` is no stream at all. */
73
+ readonly sink?: HistorySink | null;
74
+ /** The projection applied to the stream copy, and to nothing else. */
75
+ readonly transform?: HistoryTransform;
76
+ /** What the transform is called on the stream; its function name by default. */
77
+ readonly name?: string;
78
+ }
79
+
80
+ /** What the stream copy's opening line says about the projection that wrote it. */
81
+ export interface HistoryProjection {
82
+ readonly name: string;
83
+ readonly sha256: string;
84
+ readonly fn: HistoryTransform;
85
+ /** Schema documents by `id@version`: this package's drafts and the tool's own declared types. */
86
+ readonly schemas: ReadonlyMap<string, Record<string, unknown>>;
87
+ }
88
+
89
+ /**
90
+ * The digest the stream names a projection by: SHA-256, hex, of the transform's source text as
91
+ * the runtime renders it (`fn.toString()`). That is honestly what it is — a digest of rendered
92
+ * source, not of a build — and it is enough to tell two projections apart and to pin which one
93
+ * wrote a copy. A function closing over different values has the same source and the same digest;
94
+ * name the configuration, not only the function, when that distinction matters.
95
+ */
96
+ export function transformDigest(fn: HistoryTransform): string { return sha256(fn.toString()); }
97
+
98
+ /** The transform's name: what the configuration called it, else the function's own name. */
99
+ export function transformName(fn: HistoryTransform, given?: string): string {
100
+ const n = (given ?? fn.name ?? "").trim();
101
+ return n === "" ? "anonymous" : n;
102
+ }
103
+
104
+ export function historyProjection(cfg: { transform: HistoryTransform; name?: string }, schemas: ReadonlyMap<string, Record<string, unknown>>): HistoryProjection {
105
+ return { name: transformName(cfg.transform, cfg.name), sha256: transformDigest(cfg.transform), fn: cfg.transform, schemas };
106
+ }
107
+
108
+ /** Whether `MainOptions.history` was given a sink or the long form. */
109
+ export function isHistorySink(h: HistorySink | HistoryConfig): h is HistorySink {
110
+ return typeof (h as HistorySink).append === "function";
111
+ }
112
+
113
+ export interface HistoryFailure { readonly code: "history.unavailable"; readonly problem: string; readonly remedy: string }
114
+
115
+ export function isHistoryFailure(h: HistorySink | HistoryFailure): h is HistoryFailure { return "code" in h; }
116
+
117
+ /** The segment a run started at `t` writes to: the UTC date, so one day is one file everywhere. */
118
+ export function segmentName(t: number): string { return `${new Date(t).toISOString().slice(0, 10)}.jsonl`; }
119
+
120
+ /**
121
+ * `PARLEY_HISTORY_DAYS` as an integer from 1 to `HISTORY_MAX_DAYS`; anything else, including a
122
+ * window so wide that the date it names is not a date, is the default. A retention window is not
123
+ * worth failing a run over, and an unrepresentable one would throw where nothing can catch it.
124
+ */
125
+ export function historyDays(env: Record<string, string | undefined>): number {
126
+ const raw = env[HISTORY_DAYS_ENV];
127
+ if (raw === undefined) return HISTORY_DEFAULT_DAYS;
128
+ const n = Number(raw.trim());
129
+ return Number.isInteger(n) && n >= 1 && n <= HISTORY_MAX_DAYS ? n : HISTORY_DEFAULT_DAYS;
130
+ }
131
+
132
+ /**
133
+ * Where the stream is, or `null` when none is configured. `PARLEY_HISTORY` names the directory
134
+ * and is created if absent; an off value (`0`, `off`, `false`, `no`, `none`, empty) switches the
135
+ * stream off even when the state directory exists. With the variable unset, the known state path
136
+ * `$XDG_STATE_HOME/parley/history` is used when it already exists, so the stream is opted into by
137
+ * creating that directory once and never by surprise.
138
+ */
139
+ export function resolveHistory(env: Record<string, string | undefined>, home: string | undefined, t: number): HistoryPlan | null {
140
+ const days = historyDays(env);
141
+ const raw = env[HISTORY_ENV];
142
+ if (raw !== undefined) {
143
+ const trimmed = raw.trim();
144
+ if (trimmed === "" || OFF.has(trimmed.toLowerCase())) return null;
145
+ return { dir: trimmed, path: join(trimmed, segmentName(t)), days, source: "env" };
146
+ }
147
+ let dir: string;
148
+ try { dir = join(stateBase(env, home), "parley", "history"); } catch { return null; }
149
+ try { if (!statSync(dir).isDirectory()) return null; } catch { return null; }
150
+ return { dir, path: join(dir, segmentName(t)), days, source: "state" };
151
+ }
152
+
153
+ /**
154
+ * Open the segment for appending, creating the directory owner-only when the environment named
155
+ * it. A failure is described rather than thrown: the caller warns and the run proceeds without a
156
+ * stream (§8 is informative and opt-in; nothing may depend on it).
157
+ */
158
+ export function openHistory(plan: HistoryPlan, secrets: ReadonlySet<string> = new Set()): HistorySink | HistoryFailure {
159
+ // §5.3, as for the receipt path: a path the bootstrap line cannot print without disclosing a
160
+ // declared secret is never chosen. The receipt has nowhere else to go and fails startup; the
161
+ // stream is optional, so it yields and the run carries on without one. The field name is
162
+ // checked too, since a secret that is a substring of it would rename the key the line prints.
163
+ if (carriesSecret(plan.path, secrets) || carriesSecret("history", secrets)) {
164
+ return { code: "history.unavailable", problem: `the shared history stream's path or field name would carry a declared secret value, so no stream was used; the receipt is unaffected`, remedy: `point ${HISTORY_ENV} at a path that does not contain the secret, or do not pass that value as a declared secret` };
165
+ }
166
+ if (!isAbsolute(plan.dir)) {
167
+ return { code: "history.unavailable", problem: `${HISTORY_ENV} is ${JSON.stringify(plan.dir)}, which is not an absolute path, so no shared history stream was written`, remedy: `set ${HISTORY_ENV} to an absolute directory path, or unset it to use $XDG_STATE_HOME/parley/history` };
168
+ }
169
+ let fd: number;
170
+ try {
171
+ if (plan.source === "env") mkdirSync(plan.dir, { recursive: true, mode: DIR_MODE });
172
+ fd = openSync(plan.path, "a", FILE_MODE);
173
+ } catch (e) {
174
+ const msg = e instanceof Error ? e.message : String(e);
175
+ return { code: "history.unavailable", problem: `the shared history stream at ${plan.path} could not be opened: ${msg}; this run wrote its receipt and nothing else`, remedy: `make the directory writable, point ${HISTORY_ENV} somewhere writable, or set ${HISTORY_ENV}=off` };
176
+ }
177
+ let open = true;
178
+ return {
179
+ dir: plan.dir,
180
+ path: plan.path,
181
+ append(line) {
182
+ if (!open) return;
183
+ try { writeWholeLine(fd, line); }
184
+ catch (e) { open = false; try { closeSync(fd); } catch { /* already gone */ } throw e; }
185
+ },
186
+ close() { if (!open) return; open = false; try { closeSync(fd); } catch { /* already gone */ } },
187
+ };
188
+ }
189
+
190
+ /**
191
+ * One line, one write. The file is opened `O_APPEND`, so a single write of a whole line is
192
+ * ordered against every other writer's whole-line write and the line cannot be split by them.
193
+ * A write that reports fewer bytes is abandoned rather than continued: continuing would let
194
+ * another writer's append land in the middle of this line, which is the failure mode worth
195
+ * designing out. The caller then reports one failure and stops using the stream.
196
+ */
197
+ export function writeWholeLine(fd: number, line: string, write: (fd: number, b: Uint8Array) => number = writeSync): number {
198
+ const buf = Buffer.from(line, "utf8");
199
+ const n = write(fd, buf);
200
+ if (n !== buf.length) throw new Error(`the append was truncated at ${n} of ${buf.length} bytes and was not continued, because continuing would interleave with another writer`);
201
+ return n;
202
+ }
203
+
204
+ /**
205
+ * §5.1 for the stream: keep `days` daily segments, today's included, and delete the rest whole.
206
+ * Files that are not dated segments are left alone. Returns the names deleted, or the names that
207
+ * would be deleted when `dryRun`.
208
+ */
209
+ export function retainHistory(dir: string, days: number, now: number, dryRun = false): string[] {
210
+ const keepFrom = segmentName(now - (Math.max(1, days) - 1) * DAY_MS);
211
+ let names: string[];
212
+ try { names = readdirSync(dir).filter((n) => SEGMENT.test(n)); } catch { return []; }
213
+ const stale = names.filter((n) => n < keepFrom).sort();
214
+ if (dryRun) return stale;
215
+ const gone: string[] = [];
216
+ for (const n of stale) {
217
+ try { unlinkSync(join(dir, n)); gone.push(n); } catch { /* another run deleted it first */ }
218
+ }
219
+ return gone;
220
+ }
221
+
222
+ /** The bookkeeping a run with a stream declares, beside the receipt's (§4.3). */
223
+ export function historyBookkeeping(sink: Pick<HistorySink, "dir" | "path">): { op: "create" | "append" | "delete"; scope: string }[] {
224
+ return [
225
+ { op: "create", scope: `${sink.dir}/` },
226
+ { op: "append", scope: sink.path },
227
+ { op: "delete", scope: `${sink.dir}/` },
228
+ ];
229
+ }
package/src/index.ts ADDED
@@ -0,0 +1,14 @@
1
+ export { defineTool, main, type CommandSpec, type Effects, type EmittedType, type Handler, type InputDecl, type MainOptions, type ToolSpec } from "./tool.ts";
2
+ export { DIGEST_KEYS, Run, ParleyClosed, SCHEMA_IDS, SIDECAR_THRESHOLD, type Diagnostic, type SchemaRef, type Sink } from "./run.ts";
3
+ export { checkRecord, schemaSubsetGap, type CheckResult } from "./check.ts";
4
+ export { REDACTED } from "./redact.ts";
5
+ export { SCHEMAS, SCHEMA_SOURCE } from "./schemas.ts";
6
+ export { ulid } from "./ulid.ts";
7
+ export { canonical, computeInv, digestTree, sha256, type InputDescriptor } from "./inv.ts";
8
+ export { chooseLocation, isLocationFailure, repoRoot, stateBase, bookkeepingFor } from "./location.ts";
9
+ export { HISTORY_DAYS_ENV, HISTORY_DEFAULT_DAYS, HISTORY_ENV, HISTORY_MAX_DAYS, historyBookkeeping, historyDays, historyProjection, isHistoryFailure, isHistorySink, openHistory, resolveHistory, retainHistory, segmentName, transformDigest, transformName, writeWholeLine, type HistoryConfig, type HistoryFailure, type HistoryPlan, type HistoryProjection, type HistorySink, type HistoryTransform } from "./history.ts";
10
+ export { carriesSecret, classifySecrets, collectSecretValues, redactArgv, scrub } from "./redact.ts";
11
+ export { declaredProjection } from "./transforms/declared.ts";
12
+ export { isHistoryRefusal, refuse, type HistoryRefusal } from "./refusal.ts";
13
+ export { SECRET_PATTERNS, type SecretPattern } from "./transforms/secret-patterns.ts";
14
+ export { findSuspectedSecret, refuseSuspectedSecrets, SUSPECTED_SECRET_CODE, type SuspectedSecret } from "./transforms/secrets.ts";
package/src/inv.ts ADDED
@@ -0,0 +1,72 @@
1
+ // `inv` (spec §2.2): the identity of a question. This package's derivation, which the spec asks
2
+ // every supplier to document:
3
+ //
4
+ // inv = SHA-256 over the canonical JSON (keys sorted, no whitespace, UTF-8) of
5
+ // { tool, v, command, resolved, inputs: [{ path, role?, sha256 }] }
6
+ //
7
+ // `resolved` is the interpretation after defaults, with every declared secret already replaced by
8
+ // `[redacted]`, so the fact of supply enters by name and the value never does; the input
9
+ // descriptors in the preimage are the redacted ones for the same reason. Input digests are over
10
+ // bytes, never paths alone; a `tree` input digests its regular files in sorted path order,
11
+ // skipping every `.parley` directory and every path under the declaration's `exclude` list. The
12
+ // working directory, the run id, the receipt path, the session and the clock are not in the
13
+ // preimage. If any declared input could not be read, there is no `inv`.
14
+ import { createHash } from "node:crypto";
15
+ import { readdirSync, readFileSync, statSync } from "node:fs";
16
+ import { join, resolve } from "node:path";
17
+
18
+ export function canonical(v: unknown): string {
19
+ if (Array.isArray(v)) return "[" + v.map(canonical).join(",") + "]";
20
+ if (v && typeof v === "object") {
21
+ const o = v as Record<string, unknown>;
22
+ return "{" + Object.keys(o).sort().filter((k) => o[k] !== undefined).map((k) => JSON.stringify(k) + ":" + canonical(o[k])).join(",") + "}";
23
+ }
24
+ return JSON.stringify(v) ?? "null";
25
+ }
26
+
27
+ export function sha256(bytes: Uint8Array | string): string { return createHash("sha256").update(bytes).digest("hex"); }
28
+
29
+ export interface InputDecl { path: string; role?: string; /** Relative paths under a `tree` input to leave out of its digest, such as a credential file. */ exclude?: readonly string[] }
30
+ export interface InputDescriptor { path: string; role?: string; sha256?: string; error?: string }
31
+
32
+ export function computeInv(pre: { tool: string; v: string; command: string; resolved: unknown; inputs: InputDescriptor[] }): string | undefined {
33
+ if (pre.inputs.some((i) => i.sha256 === undefined)) return undefined;
34
+ return sha256(canonical({ tool: pre.tool, v: pre.v, command: pre.command, resolved: pre.resolved, inputs: pre.inputs.map((i) => ({ path: i.path, role: i.role, sha256: i.sha256 })) }));
35
+ }
36
+
37
+ function excluded(rel: string, exclude: readonly string[]): boolean {
38
+ return exclude.some((e) => { const x = e.replace(/\/+$/, ""); return rel === x || rel.startsWith(x + "/"); });
39
+ }
40
+
41
+ /** Digest of a directory: SHA-256 over `relative-path NUL file-digest LF` for every regular file, sorted by path, skipping `.parley` directories and excluded paths. */
42
+ export function digestTree(root: string, exclude: readonly string[] = []): string {
43
+ const files: string[] = [];
44
+ const walk = (dir: string, rel: string) => {
45
+ for (const name of readdirSync(dir).sort()) {
46
+ if (name === ".parley") continue;
47
+ const p = join(dir, name), r = rel ? `${rel}/${name}` : name;
48
+ if (excluded(r, exclude)) continue;
49
+ const st = statSync(p);
50
+ if (st.isDirectory()) walk(p, r); else if (st.isFile()) files.push(r);
51
+ }
52
+ };
53
+ walk(root, "");
54
+ const h = createHash("sha256");
55
+ for (const r of files) h.update(r + "\0" + sha256(readFileSync(join(root, r))) + "\n");
56
+ return h.digest("hex");
57
+ }
58
+
59
+ /** Digest a declared input by role; an unreadable input yields an `error` code and no digest. A relative path is resolved against `cwd`; an absolute one stands. */
60
+ export function digestInput(cwd: string, input: InputDecl, supplied?: Uint8Array): InputDescriptor {
61
+ const base: InputDescriptor = { path: input.path, ...(input.role ? { role: input.role } : {}) };
62
+ try {
63
+ if (input.role === "stdin") return supplied ? { ...base, sha256: sha256(supplied) } : { ...base, error: "input.unread" };
64
+ if (supplied) return { ...base, sha256: sha256(supplied) };
65
+ const p = resolve(cwd, input.path);
66
+ const st = statSync(p);
67
+ if (st.isDirectory() || input.role === "tree") return { ...base, sha256: digestTree(p, input.exclude ?? []) };
68
+ return { ...base, sha256: sha256(readFileSync(p)) };
69
+ } catch {
70
+ return { ...base, error: "input.unreadable" };
71
+ }
72
+ }