@staix/agent-mem 0.30.0 → 0.31.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,442 @@
1
+ /**
2
+ * #326: the memory correctness audit. Whether a stored note is still right cannot be measured by ranking, so this samples curated notes, records where each
3
+ * note's own anchors stand today, and leaves two empty judge columns for a person (or an agent in another session) to fill. `score` then turns those labels
4
+ * into content-free counts and Cohen's kappa.
5
+ *
6
+ * amem makes no model and no network call here: `git log` over the anchors is the only outside read, and it is read-only. Judging happens outside amem, so a
7
+ * judgement never depends on a model this package vendors or on a key it would have to hold.
8
+ */
9
+ import { createHash } from "node:crypto";
10
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readlinkSync, readSync, writeFileSync } from "node:fs";
11
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
12
+ import {
13
+ AUDIT_AGE_BUCKETS, AUDIT_ANCHOR_STATUSES, AUDIT_KINDS, AUDIT_LABELS, AUDIT_RUBRIC, AUDIT_SCHEMA, MAX_AUDIT_ANCHORS, MAX_AUDIT_NOTES, MAX_AUDIT_SHEET_BYTES,
14
+ auditAge, cohenKappa, foldAnchorStatus, type AuditAgeBucket, type AuditAnchorStatus, type AuditLabel,
15
+ } from "./eval.ts";
16
+ import { memoryGitEnv, memoryGitSync, realPath } from "./platform.ts";
17
+ import type { MemoryStore, View } from "./store.ts";
18
+
19
+ export interface AuditAnchor { path: string; status: Exclude<AuditAnchorStatus, "none"> }
20
+ export interface AuditNote {
21
+ id: string; kind: string; at: string; age: AuditAgeBucket;
22
+ /** The spec's per-note verdict over every path anchor this note names; `none` when it names none. */
23
+ anchor: AuditAnchorStatus; anchors: AuditAnchor[];
24
+ title?: string; text: string;
25
+ /** Empty until a judge fills it; the sheet's only free cells, and only ever a closed label. */
26
+ judge_a: "" | AuditLabel; judge_b: "" | AuditLabel;
27
+ }
28
+ export interface AuditSheet {
29
+ schema: typeof AUDIT_SCHEMA; project: string; seed: string;
30
+ /**
31
+ * The instant the age buckets were measured at - `--as-of` when it was given, this run's clock otherwise - recorded so the same store, seed and as-of draw the
32
+ * same sample instead of reaching the wall clock silently.
33
+ */
34
+ asOf: string;
35
+ /** The git work tree the anchors were checked in; anchors are repository-relative, so the sheet is only re-scoreable, never re-checkable, elsewhere. */
36
+ root: string; frame: number; drawn: number;
37
+ /** True when the store's listing bound cut the frame, so `frame` is a floor rather than the project's live note count. */
38
+ truncated: boolean;
39
+ /** Frame members the configured policy refused, so they never entered the sheet: a count, because the sheet stays free of what was withheld. */
40
+ withheld: number;
41
+ rubric: Record<AuditLabel, string>;
42
+ notes: AuditNote[];
43
+ }
44
+ export interface AuditSampleOptions {
45
+ store: MemoryStore; project: string; n: number; seed: string; root: string;
46
+ /** The instant the age buckets are measured at; the CLI passes `--as-of` or its own clock, and the sheet records whichever it was. */
47
+ asOf?: number;
48
+ /**
49
+ * Screens one frame member before it can enter the sheet; `false` withholds it. The CLI passes the configured standalone policy over the complete `View`, not
50
+ * the fields the sheet copies, so a denied pattern in `task`, `peer` or `source` withholds the note just as one in its text does.
51
+ */
52
+ screen?: (view: View) => boolean;
53
+ }
54
+
55
+ /** One frame member before the draw: the view plus the bucket the sheet will name. */
56
+ interface Candidate { view: View; age: AuditAgeBucket }
57
+
58
+ /**
59
+ * The bound on the one listing the frame is read from. A project with more live notes than this has its frame cut, and the sheet says `truncated` rather than
60
+ * reporting the bound as if it were the whole frame.
61
+ * ponytail: one bounded listing instead of a windowed walk; upgrade to a cursor over the store's ordering when a frame this size is real.
62
+ */
63
+ const AUDIT_LIST_CAP = MAX_AUDIT_NOTES * 100;
64
+
65
+ const fail = (message: string): never => { throw new Error(`invalid audit sheet: ${message}`); };
66
+ const object = (value: unknown, what: string): Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : fail(`${what} must be an object`);
67
+ function exact(row: Record<string, unknown>, allowed: readonly string[], what: string): void {
68
+ for (const key of Object.keys(row)) if (!allowed.includes(key)) fail(`${what} has an unknown key "${key.slice(0, 40)}": the score is content-free, so a free-text field is refused rather than read`);
69
+ }
70
+ const string = (value: unknown, what: string, max: number): string => typeof value === "string" && value.length <= max && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value) ? value : fail(`${what} must be a string of at most ${max} characters without control characters`);
71
+ const oneOf = <T extends string>(value: unknown, vocabulary: readonly T[], what: string): T => vocabulary.includes(value as T) ? value as T : fail(`${what} must be one of ${vocabulary.join(", ")}`);
72
+ const seedValue = (value: unknown): string => typeof value === "string" && /^[A-Za-z0-9._-]{1,64}$/.test(value) ? value : fail("seed must be 1 to 64 letters, digits, '.', '_' or '-', the alphabet `sample` draws with");
73
+ /** A canonical UTC instant - the one clock value a sheet and its score carry - so a hand-edited sheet cannot park free text in it. */
74
+ const stamp = (value: unknown): string => {
75
+ const at = typeof value === "string" && /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$/.test(value) ? Date.parse(value) : Number.NaN;
76
+ return Number.isFinite(at) && new Date(at).toISOString() === value ? value as string : fail("asOf must be a canonical UTC instant such as 2026-02-01T00:00:00.000Z, the one the age buckets were measured at");
77
+ };
78
+ const bool = (value: unknown, what: string): boolean => typeof value === "boolean" ? value : fail(`${what} must be true or false`);
79
+
80
+ /** SHA-256 of the seed with a stratum and its ordinal, so one seed gives one order on every machine and runtime (no `Math.random`, no clock). */
81
+ function seededOrder(seed: string, key: string, size: number): number[] {
82
+ let state = 0;
83
+ for (const byte of createHash("sha256").update(`${seed}\n${key}`).digest()) state = (state * 257 + byte) % 0x1_0000_0000;
84
+ const at = Array.from({ length: size }, (_, index) => index);
85
+ for (let i = size - 1; i > 0; i--) {
86
+ state = (state * 1_664_525 + 1_013_904_223) % 0x1_0000_0000;
87
+ const j = state % (i + 1);
88
+ [at[i], at[j]] = [at[j]!, at[i]!];
89
+ }
90
+ return at;
91
+ }
92
+
93
+ /**
94
+ * Stratified draw by kind and age bucket. Every non-empty cell is represented before any cell gets a second note, then the remainder goes to the cells with
95
+ * the most members left to offer, and ties break on the stratum name - so the same frame, `n` and seed always give the same notes in the same order.
96
+ */
97
+ function draw(candidates: readonly Candidate[], n: number, seed: string): Candidate[] {
98
+ const cells = new Map<string, Candidate[]>();
99
+ for (const candidate of candidates) {
100
+ const key = `${candidate.view.kind}\n${candidate.age}`;
101
+ const list = cells.get(key); if (list) list.push(candidate); else cells.set(key, [candidate]);
102
+ }
103
+ // The cells are drawn in seeded order too, so a different seed reaches different strata instead of always the lexicographically first ones.
104
+ const names = [...cells.keys()].sort(), keys = seededOrder(seed, "cells", names.length).map(index => names[index]!);
105
+ const size = (key: string) => cells.get(key)!.length, total = Math.min(n, candidates.length);
106
+ const quota = new Map(keys.map(key => [key, 0]));
107
+ let left = total;
108
+ for (const key of keys) { if (left <= 0) break; quota.set(key, 1); left--; }
109
+ while (left > 0) {
110
+ const roomy = keys.filter(key => quota.get(key)! < size(key)).sort((a, b) => (size(b) - quota.get(b)!) - (size(a) - quota.get(a)!) || a.localeCompare(b));
111
+ const next = roomy[0];
112
+ if (next === undefined) break;
113
+ quota.set(next, quota.get(next)! + 1); left--;
114
+ }
115
+ const drawn: Candidate[] = [];
116
+ for (const key of keys) {
117
+ const list = [...cells.get(key)!].sort((a, b) => a.view.id.localeCompare(b.view.id)), order = seededOrder(seed, key, list.length);
118
+ for (const index of order.slice(0, quota.get(key)!)) drawn.push(list[index]!);
119
+ }
120
+ return drawn;
121
+ }
122
+
123
+ /** The path anchors a note names, deduplicated, bounded, and never outside the work tree (a `..` segment is dropped rather than read). */
124
+ export function auditAnchorPaths(view: View): string[] {
125
+ const paths = new Set<string>();
126
+ for (const node of view.about) {
127
+ if (!node.startsWith("path:") || paths.size >= MAX_AUDIT_ANCHORS) continue;
128
+ const path = node.slice(5).replace(/^\.\//, "");
129
+ if (!path || path.startsWith("/") || path.split("/").includes("..")) continue;
130
+ paths.add(path);
131
+ }
132
+ return [...paths];
133
+ }
134
+
135
+ /** The statuses an anchor path can have: every one but `none`, which describes a note rather than a path. */
136
+ const PATH_STATUSES = AUDIT_ANCHOR_STATUSES.filter((status): status is Exclude<AuditAnchorStatus, "none"> => status !== "none");
137
+
138
+ /**
139
+ * Where an anchor path lands without ever reading outside the work tree. Each component is `lstat`ed, which does not follow a link, and a link is resolved by
140
+ * `readlink` plus a lexical join - so an escaping anchor is recognised before anything at its target is stat'ed, and an external target's existence can never
141
+ * show up in the status. `absent` means the walk stayed inside the tree and found no such entry; `outside` means the anchor leaves the tree, loops, or cannot be
142
+ * resolved without a read the audit is not allowed to make.
143
+ */
144
+ export function resolveAnchor(root: string, path: string): { kind: "inside"; path: string } | { kind: "absent" } | { kind: "outside" } {
145
+ let walk = path;
146
+ for (let hops = 0; hops <= 40; hops++) {
147
+ const parts = walk.split("/").filter(part => part !== "" && part !== ".");
148
+ let at = root, restart: string | undefined;
149
+ for (const [index, part] of parts.entries()) {
150
+ const next = join(at, part);
151
+ let info;
152
+ try { info = lstatSync(next); } catch (error) {
153
+ const code = (error as NodeJS.ErrnoException).code;
154
+ return code === "ENOENT" || code === "ENOTDIR" ? { kind: "absent" } : { kind: "outside" };
155
+ }
156
+ if (!info.isSymbolicLink()) { at = next; continue; }
157
+ let target: string;
158
+ try { target = readlinkSync(next); } catch { return { kind: "outside" }; }
159
+ const resolved = resolve(dirname(next), target);
160
+ if (resolved !== root && !resolved.startsWith(`${root}${sep}`)) return { kind: "outside" };
161
+ // The link's target is inside the tree, so the walk continues there: a link may lead to another link, and a hop bound stops a cycle.
162
+ restart = [relative(root, resolved), ...parts.slice(index + 1)].filter(Boolean).join("/");
163
+ break;
164
+ }
165
+ if (restart === undefined) return { kind: "inside", path: at };
166
+ walk = restart;
167
+ }
168
+ return { kind: "outside" };
169
+ }
170
+
171
+ /**
172
+ * Where one anchor stands today. A path that is gone is `missing`; one with a commit touching it since the note was written is `changed since note time`;
173
+ * anything else is `present`. Two shapes are `unavailable` instead, because claiming `present` would say "no commit touched it" about a check that never ran:
174
+ * a path that resolves outside the work tree (a symlink inside the repository can point anywhere, and the audit reads only this repository), and a history
175
+ * read that fails or times out. The read itself runs through the hardened runner: read-only diagnostics, no lazy fetch.
176
+ */
177
+ function anchorStatus(root: string, at: string, path: string): AuditAnchor["status"] {
178
+ const found = resolveAnchor(root, path);
179
+ if (found.kind === "outside") return "unavailable";
180
+ if (found.kind === "absent") return "missing";
181
+ const log = memoryGitSync(["-C", root, "log", "-n", "1", "--format=%H", "--since", at, "--", path], {
182
+ encoding: "utf8", env: memoryGitEnv(process.env, { readOnlyDiagnostic: true }), timeout: 8_000, maxBuffer: 64 * 1024,
183
+ });
184
+ if (log.error !== undefined || log.status !== 0) return "unavailable";
185
+ return log.stdout.trim() === "" ? "present" : "changed";
186
+ }
187
+
188
+ /** The git work tree a cwd belongs to, or a refusal naming the next step: anchors are repository-relative, so an audit needs the tree they name. */
189
+ export function auditRoot(cwd: string): string {
190
+ const top = memoryGitSync(["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8", env: memoryGitEnv(process.env, { readOnlyDiagnostic: true }), timeout: 8_000, maxBuffer: 64 * 1024 });
191
+ const root = top.status === 0 ? top.stdout.trim() : "";
192
+ if (!root) throw new Error(`the audit checks note anchors against a git work tree, and ${cwd} is not inside one; run it from the project the notes describe`);
193
+ return realPath(root);
194
+ }
195
+
196
+ /**
197
+ * The instant `--as-of` names, normalized to one canonical UTC stamp: a date alone is midnight UTC of that day, and anything else must already be canonical.
198
+ * A future instant is refused, because it would measure ages that have not happened and quietly drop notes out of every bucket.
199
+ */
200
+ export function auditAsOf(value: string, present: number): number {
201
+ const iso = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(value) ? `${value}T00:00:00.000Z` : value, at = Date.parse(iso);
202
+ if (!Number.isFinite(at) || new Date(at).toISOString() !== iso) {
203
+ throw new Error(`--as-of must be a canonical UTC date or timestamp (2026-01-31 or 2026-01-31T00:00:00.000Z), and "${value.slice(0, 40)}" is not; it is the instant the notes' ages are measured at, and the sheet records it so the same seed draws the same sample again`);
204
+ }
205
+ if (at > present) throw new Error(`--as-of ${iso} is in the future, and the audit measures how old the notes are at that instant; pass today or an earlier date`);
206
+ return at;
207
+ }
208
+
209
+ /** Draw the sample and describe it. Nothing is written here: the caller chooses the private path. */
210
+ export function auditSample(opts: AuditSampleOptions): AuditSheet {
211
+ if (!Number.isInteger(opts.n) || opts.n < 1 || opts.n > MAX_AUDIT_NOTES) throw new Error(`the audit draws 1 to ${MAX_AUDIT_NOTES} notes, not ${opts.n}`);
212
+ if (!/^[A-Za-z0-9._-]{1,64}$/.test(opts.seed)) throw new Error("the audit seed is 1 to 64 letters, digits, '.', '_' or '-', so the same seed and store draw the same sample");
213
+ const asOf = opts.asOf ?? Date.now(), kinds = new Set<string>(AUDIT_KINDS), candidates: Candidate[] = [];
214
+ const listed = opts.store.list({ project: opts.project, limit: AUDIT_LIST_CAP });
215
+ let withheld = 0;
216
+ for (const view of listed) {
217
+ if (!kinds.has(view.kind)) continue;
218
+ const age = auditAge(view.at, asOf);
219
+ if (age === undefined) continue;
220
+ // The policy runs over the whole view before anything is written: a note it refuses is not copied into the sheet, and the sheet only reports the count.
221
+ if (opts.screen && !opts.screen(view)) { withheld++; continue; }
222
+ candidates.push({ view, age });
223
+ }
224
+ const drawn = draw(candidates, opts.n, opts.seed);
225
+ // A sheet with no notes cannot be judged and its own parser refuses it, so an empty frame is a refusal with the cause and the next step, not a file.
226
+ if (!drawn.length) throw new Error(withheld
227
+ ? `the audit drew no notes: the configured policy withheld all ${withheld} candidate note(s), so nothing could be sampled; adjust the policy or sample from the project that holds the notes`
228
+ : `the audit drew no notes: ${opts.project} has no live decision, finding, contract or fail note in the frame this work tree covers; record curated notes and sample again`);
229
+ const notes = drawn.map(({ view, age }): AuditNote => {
230
+ const anchors = auditAnchorPaths(view).map(path => ({ path, status: anchorStatus(opts.root, view.at, path) }));
231
+ return {
232
+ id: view.id, kind: view.kind, at: view.at, age, anchor: foldAnchorStatus(anchors.map(anchor => anchor.status)), anchors,
233
+ ...(view.title === null ? {} : { title: view.title }), text: view.text, judge_a: "", judge_b: "",
234
+ };
235
+ });
236
+ return {
237
+ schema: AUDIT_SCHEMA, project: opts.project, seed: opts.seed, asOf: new Date(asOf).toISOString(), root: opts.root,
238
+ frame: candidates.length, drawn: notes.length, truncated: listed.length >= AUDIT_LIST_CAP, withheld, rubric: { ...AUDIT_RUBRIC }, notes,
239
+ };
240
+ }
241
+
242
+ /** The sheet's own file: pretty JSON, because a person fills `judge_a` and `judge_b` in it by hand. Never overwritten (flag `wx`), always 0600. */
243
+ export function writeAuditSheet(path: string, sheet: AuditSheet): string {
244
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
245
+ const file = join(realPath(dirname(path)), basename(path));
246
+ try {
247
+ writeFileSync(file, JSON.stringify(sheet, null, 2) + "\n", { mode: 0o600, flag: "wx" });
248
+ } catch (error) {
249
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
250
+ throw new Error(`an audit sheet is never overwritten and ${file} exists; keep it and pass \`--out <another path>\`, or sample again with a new --seed`);
251
+ }
252
+ return file;
253
+ }
254
+
255
+ /** A bounded read of an untrusted file: a regular file within the sheet bound, with the size and the bytes read bound together. */
256
+ export function readAuditSheet(path: string): AuditSheet {
257
+ const tooBig = () => new Error(`invalid audit sheet: ${path} is not a regular file within ${MAX_AUDIT_SHEET_BYTES} bytes; score the sheet \`amem eval audit sample\` wrote instead of a directory or a larger file`);
258
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
259
+ let bytes: Buffer;
260
+ try {
261
+ const before = fstatSync(fd);
262
+ if (!before.isFile() || before.size > MAX_AUDIT_SHEET_BYTES) throw tooBig();
263
+ const buffer = Buffer.alloc(MAX_AUDIT_SHEET_BYTES + 1);
264
+ let length = 0;
265
+ while (length < buffer.length) {
266
+ const read = readSync(fd, buffer, length, buffer.length - length, length);
267
+ if (read === 0) break;
268
+ length += read;
269
+ }
270
+ const after = fstatSync(fd);
271
+ if (length > MAX_AUDIT_SHEET_BYTES || after.size !== before.size || length !== before.size) throw tooBig();
272
+ bytes = buffer.subarray(0, length);
273
+ } finally { closeSync(fd); }
274
+ let raw: unknown;
275
+ try { raw = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); }
276
+ catch { throw new Error(`invalid audit sheet: ${path} is not valid JSON; re-open the sheet \`amem eval audit sample\` wrote, fill only judge_a and judge_b, and save it whole`); }
277
+ return parseAuditSheet(raw);
278
+ }
279
+
280
+ /**
281
+ * Strict parse of a filled sheet. Unknown keys are refused rather than ignored: the sheet holds note text, and a key the score does not know is exactly how
282
+ * free text would reach the content-free output. A judge cell holds one of the four labels or stays empty, a kind is one of the audit's four, the as-of instant
283
+ * is a canonical UTC stamp, and the seed is the alphabet `sample` accepts - every value the score copies or turns into a bucket name is a closed set, not a
284
+ * string from the file.
285
+ */
286
+ export function parseAuditSheet(raw: unknown): AuditSheet {
287
+ const root = object(raw, "the sheet");
288
+ exact(root, ["schema", "project", "seed", "asOf", "root", "frame", "drawn", "truncated", "withheld", "rubric", "notes"], "the sheet");
289
+ if (root.schema !== AUDIT_SCHEMA) fail(`schema must be "${AUDIT_SCHEMA}"`);
290
+ if (!Array.isArray(root.notes) || !root.notes.length || root.notes.length > MAX_AUDIT_NOTES) fail(`notes must hold 1 to ${MAX_AUDIT_NOTES} items, and \`amem eval audit sample\` writes a sheet of at least one note`);
291
+ const notes = (root.notes as unknown[]).map((item, index): AuditNote => {
292
+ const row = object(item, `notes[${index}]`), what = `notes[${index}]`;
293
+ exact(row, ["id", "kind", "at", "age", "anchor", "anchors", "title", "text", "judge_a", "judge_b"], what);
294
+ const id = typeof row.id === "string" && /^[0-9a-f]{32}$/.test(row.id) ? row.id : fail(`${what}.id must be a 32-character lowercase hex entry id`);
295
+ const judge = (cell: unknown, name: string): "" | AuditLabel => cell === "" ? "" : oneOf(cell, AUDIT_LABELS, `${what}.${name}`);
296
+ if (!Array.isArray(row.anchors) || row.anchors.length > MAX_AUDIT_ANCHORS) fail(`${what}.anchors must hold at most ${MAX_AUDIT_ANCHORS} items`);
297
+ const anchors = (row.anchors as unknown[]).map((anchor, at): AuditAnchor => {
298
+ const entry = object(anchor, `${what}.anchors[${at}]`);
299
+ exact(entry, ["path", "status"], `${what}.anchors[${at}]`);
300
+ return { path: string(entry.path, `${what}.anchors[${at}].path`, 400), status: oneOf(entry.status, PATH_STATUSES, `${what}.anchors[${at}].status`) };
301
+ });
302
+ return {
303
+ id, kind: oneOf(row.kind, AUDIT_KINDS, `${what}.kind`), at: string(row.at, `${what}.at`, 40), age: oneOf(row.age, AUDIT_AGE_BUCKETS, `${what}.age`),
304
+ anchor: oneOf(row.anchor, AUDIT_ANCHOR_STATUSES, `${what}.anchor`), anchors,
305
+ ...(row.title === undefined ? {} : { title: string(row.title, `${what}.title`, 200) }),
306
+ text: string(row.text, `${what}.text`, 4_000), judge_a: judge(row.judge_a, "judge_a"), judge_b: judge(row.judge_b, "judge_b"),
307
+ };
308
+ });
309
+ const rubric = object(root.rubric, "the sheet's rubric");
310
+ return {
311
+ schema: AUDIT_SCHEMA, project: string(root.project, "project", 200), seed: seedValue(root.seed),
312
+ asOf: stamp(root.asOf), root: string(root.root, "root", 1_000),
313
+ frame: typeof root.frame === "number" && Number.isInteger(root.frame) && root.frame >= 0 ? root.frame : fail("frame must be a non-negative integer"),
314
+ drawn: typeof root.drawn === "number" && Number.isInteger(root.drawn) && root.drawn >= 0 ? root.drawn : fail("drawn must be a non-negative integer"),
315
+ truncated: bool(root.truncated, "truncated"),
316
+ withheld: typeof root.withheld === "number" && Number.isInteger(root.withheld) && root.withheld >= 0 ? root.withheld : fail("withheld must be a non-negative integer"),
317
+ rubric: Object.fromEntries(AUDIT_LABELS.map(label => [label, string(rubric[label] ?? AUDIT_RUBRIC[label], `rubric.${label}`, 400)])) as Record<AuditLabel, string>,
318
+ notes,
319
+ };
320
+ }
321
+
322
+ /** One non-zero cell of the joint cross-tab: a label against a kind, an age bucket and an anchor status together. */
323
+ export interface AuditCell { kind: string; age: AuditAgeBucket; anchor: AuditAnchorStatus; label: AuditLabel; count: number }
324
+
325
+ export interface AuditScore {
326
+ schema: "amem.audit.score/v1";
327
+ /** A SHA-256 prefix of the sheet's project key, never the key: a key can be derived from a local checkout path, and the score is the part meant to be shared. */
328
+ project: string;
329
+ /** The instant the age buckets were measured at, so a shared coefficient travels with the buckets that produced it. */
330
+ asOf: string;
331
+ /** Echoed verbatim: the seed is the person's own input in the closed sample alphabet, not note content (owner ruling 2026-11-20). */
332
+ seed: string;
333
+ frame: number; drawn: number; truncated: boolean; withheld: number;
334
+ labelled: number; unlabelled: number;
335
+ byLabel: Record<AuditLabel, number>;
336
+ /** The spec's joint cross-tab (label x kind x age bucket x anchor status) as its non-zero cells, sorted; the marginals below cannot rebuild it. */
337
+ cells: AuditCell[];
338
+ byKind: Record<string, Partial<Record<AuditLabel, number>>>;
339
+ byAge: Record<string, Partial<Record<AuditLabel, number>>>;
340
+ byAnchor: Record<string, Partial<Record<AuditLabel, number>>>;
341
+ agreement: { pairs: number; agreed: number; kappa: number | null };
342
+ }
343
+
344
+ /** So two scores name the same project without carrying a key, which can be built from the person's own checkout path. */
345
+ function projectDigest(project: string): string {
346
+ return `sha256:${createHash("sha256").update(project).digest("hex").slice(0, 16)}`;
347
+ }
348
+
349
+ /**
350
+ * The score is content-free because no note field is copied into it: the project becomes a digest, the clock becomes the canonical stamp the sheet recorded, and
351
+ * every other string it emits is a schema or field literal, a member of the four closed vocabularies, or the seed. The seed is echoed verbatim - the person
352
+ * chose it in the closed alphabet `sample` draws with, and it is not note content, so a note whose text happens to equal the seed is not a leak (owner ruling
353
+ * 2026-11-20, docs/bench/audit.md). This check makes the rest true for a sheet handed in directly rather than through the strict parse: a kind, age bucket or
354
+ * anchor status outside its vocabulary would become a key in `byKind`, `byAge`, `byAnchor` or `cells`, a judge cell outside the four labels would become a key in
355
+ * the tallies, and a seed outside the alphabet would be copied verbatim, so all of them refuse the score instead. Note text, title and anchor paths are never
356
+ * read by the score at all.
357
+ */
358
+ function assertClosedInputs(sheet: AuditSheet): void {
359
+ stamp(sheet.asOf);
360
+ if (!/^[A-Za-z0-9._-]{1,64}$/.test(sheet.seed)) throw new Error("the audit score echoes the seed verbatim, so it must stay in the alphabet `sample` draws with; a seed outside it is refused, because the score carries only closed strings besides note-free literals");
361
+ for (const note of sheet.notes) {
362
+ if (!AUDIT_KINDS.includes(note.kind) || !AUDIT_AGE_BUCKETS.includes(note.age) || !AUDIT_ANCHOR_STATUSES.includes(note.anchor)) {
363
+ throw new Error("the audit score would carry a kind, age bucket or anchor status outside its closed vocabulary; it is refused, because the score is content-free by contract");
364
+ }
365
+ for (const judge of [note.judge_a, note.judge_b]) {
366
+ if (judge !== "" && !AUDIT_LABELS.includes(judge)) {
367
+ throw new Error("the audit score would carry a judge cell outside the four labels; it is refused, because the score is content-free by contract");
368
+ }
369
+ }
370
+ }
371
+ }
372
+
373
+ const tally = (rows: readonly AuditNote[], key: (note: AuditNote) => string): Record<string, Partial<Record<AuditLabel, number>>> => {
374
+ const out: Record<string, Partial<Record<AuditLabel, number>>> = {};
375
+ for (const note of rows) {
376
+ if (note.judge_a === "") continue;
377
+ const bucket = out[key(note)] ??= {};
378
+ bucket[note.judge_a] = (bucket[note.judge_a] ?? 0) + 1;
379
+ }
380
+ return Object.fromEntries(Object.entries(out).sort(([a], [b]) => a.localeCompare(b)));
381
+ };
382
+
383
+ /**
384
+ * Counts by label against kind, age bucket and anchor status - separately and jointly - plus Cohen's kappa over the notes both judges labelled. The result is
385
+ * content-free by the check above and by construction: the project key is replaced by a digest, and no note field is read into the output.
386
+ */
387
+ export function auditScore(sheet: AuditSheet): AuditScore {
388
+ assertClosedInputs(sheet);
389
+ const labelled = sheet.notes.filter(note => note.judge_a !== "");
390
+ const pairs = sheet.notes.filter(note => note.judge_a !== "" && note.judge_b !== "").map(note => [note.judge_a, note.judge_b] as const);
391
+ const joint = new Map<string, AuditCell>();
392
+ for (const note of labelled) {
393
+ const label = note.judge_a as AuditLabel, key = `${note.kind}\u0000${note.age}\u0000${note.anchor}\u0000${label}`, cell = joint.get(key);
394
+ if (cell) cell.count++;
395
+ else joint.set(key, { kind: note.kind, age: note.age, anchor: note.anchor, label, count: 1 });
396
+ }
397
+ const score: AuditScore = {
398
+ schema: "amem.audit.score/v1", project: projectDigest(sheet.project), asOf: sheet.asOf, seed: sheet.seed, frame: sheet.frame, drawn: sheet.drawn,
399
+ truncated: sheet.truncated, withheld: sheet.withheld, labelled: labelled.length, unlabelled: sheet.notes.length - labelled.length,
400
+ byLabel: Object.fromEntries(AUDIT_LABELS.map(label => [label, labelled.filter(note => note.judge_a === label).length])) as Record<AuditLabel, number>,
401
+ cells: [...joint.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, cell]) => cell),
402
+ byKind: tally(sheet.notes, note => note.kind), byAge: tally(sheet.notes, note => note.age), byAnchor: tally(sheet.notes, note => note.anchor),
403
+ agreement: { pairs: pairs.length, agreed: pairs.filter(([a, b]) => a === b).length, kappa: cohenKappa(pairs, AUDIT_LABELS) },
404
+ };
405
+ return score;
406
+ }
407
+
408
+ /** Human text for `amem eval audit sample`: where the sheet is, and what filling it costs. Content-free, like the score. */
409
+ export function auditSheetText(sheet: AuditSheet, file: string): string {
410
+ const cells = new Set(sheet.notes.map(note => `${note.kind}/${note.age}`));
411
+ const frame = `${sheet.frame}${sheet.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
412
+ return [
413
+ `audit sample: ${sheet.drawn} of ${frame} ${sheet.project} notes, seed "${sheet.seed}" as of ${sheet.asOf}, ${cells.size} kind/age cells, anchors checked in ${sheet.root}${sheet.withheld ? `, ${sheet.withheld} withheld by the configured policy` : ""}`,
414
+ `sheet: ${file} (0600, local only; never synced and never committed)`,
415
+ `fill judge_a and judge_b with ${AUDIT_LABELS.join(", ")} (rubric in the sheet header), then run \`amem eval audit score ${file}\``,
416
+ ].join("\n");
417
+ }
418
+
419
+ /** Human text for `amem eval audit score`; the JSON is the machine form. */
420
+ export function auditScoreText(score: AuditScore): string {
421
+ const row = (label: string, counts: Partial<Record<AuditLabel, number>>) => `${label.padEnd(10)} ${AUDIT_LABELS.map(name => String(counts[name] ?? 0).padStart(4)).join(" ")}`;
422
+ const frame = `${score.frame}${score.truncated ? "+ (the store listing hit its cap, so the frame is a floor)" : ""}`;
423
+ const withheld = score.withheld ? `, ${score.withheld} withheld by the configured policy` : "";
424
+ const head = `audit score: project ${score.project}, ${score.drawn} of ${frame} notes, seed "${score.seed}" as of ${score.asOf}, ${score.labelled} labelled, ${score.unlabelled} not${withheld}`;
425
+ // The joint cells are printed as one line per kind/age/anchor stratum, so a reader sees which label fills each intersection instead of three marginals.
426
+ const strata = new Map<string, Partial<Record<AuditLabel, number>>>();
427
+ for (const cell of score.cells) {
428
+ const key = `${cell.kind}/${cell.age}/${cell.anchor}`, counts = strata.get(key) ?? {};
429
+ counts[cell.label] = cell.count;
430
+ strata.set(key, counts);
431
+ }
432
+ return [
433
+ head,
434
+ `${"".padEnd(10)} ${AUDIT_LABELS.map(name => name.slice(0, 4).padStart(4)).join(" ")}`,
435
+ row("all", score.byLabel),
436
+ ...Object.entries(score.byKind).map(([kind, counts]) => row(`kind ${kind}`, counts)),
437
+ ...Object.entries(score.byAge).map(([age, counts]) => row(`age ${age}`, counts)),
438
+ ...Object.entries(score.byAnchor).map(([anchor, counts]) => row(`anchor ${anchor}`, counts)),
439
+ ...strata.entries().map(([key, counts]) => row(`cross ${key}`, counts)),
440
+ `kappa ${score.agreement.kappa === null ? "n/a (needs both judge columns, and more than one label between them)" : score.agreement.kappa.toFixed(3)} over ${score.agreement.pairs} doubly labelled note(s)`,
441
+ ].join("\n");
442
+ }
@@ -12,6 +12,33 @@ export const MAX_QUESTIONS = 500, MAX_ENTRIES = 200, MAX_QUESTION_CHARS = 500, M
12
12
  export const DEFAULT_KS: readonly number[] = [1, 5, 10];
13
13
 
14
14
  export const EVAL_KINDS = ["decision", "finding", "contract", "fail"] as const;
15
+
16
+ /**
17
+ * #326: the correctness audit's closed vocabulary. A label is a judge's verdict on one sampled note, never a number: `unverifiable` says no source was
18
+ * available, which is a different thing from `wrong`. The rubric travels with the sheet so the person filling it and the score agree on each word.
19
+ */
20
+ export const AUDIT_SCHEMA = "amem.audit/v1";
21
+ export const AUDIT_LABELS = ["correct", "stale", "wrong", "unverifiable"] as const;
22
+ export type AuditLabel = (typeof AUDIT_LABELS)[number];
23
+ /** The spec's <30, 30-90 and >90 day buckets, named so a sheet and its score agree without keeping the clock that made them. */
24
+ export const AUDIT_AGE_BUCKETS = ["lt30", "d30to90", "gt90"] as const;
25
+ export type AuditAgeBucket = (typeof AUDIT_AGE_BUCKETS)[number];
26
+ /**
27
+ * `unavailable` is an anchor the audit could not check - the history read failed, or the path resolves outside the work tree through a symlink - so it claims
28
+ * neither "untouched" nor "gone". `none` is a note that names no path anchor, so no anchor check applies to it.
29
+ */
30
+ export const AUDIT_ANCHOR_STATUSES = ["present", "changed", "missing", "unavailable", "none"] as const;
31
+ export type AuditAnchorStatus = (typeof AUDIT_ANCHOR_STATUSES)[number];
32
+ export const MAX_AUDIT_NOTES = 200, MAX_AUDIT_ANCHORS = 8, MAX_AUDIT_SHEET_BYTES = 4 * 1024 * 1024;
33
+ /**
34
+ * The audit's kind frame, written out rather than aliased to `EVAL_KINDS`: widening the eval-set schema must not silently widen what gets audited, and adding
35
+ * `preference` here is the one-line change that samples it (docs/bench/audit.md records why it stays out today).
36
+ */
37
+ export const AUDIT_KINDS: readonly string[] = ["decision", "finding", "contract", "fail"];
38
+ export const AUDIT_RUBRIC: Readonly<Record<AuditLabel, string>> = {
39
+ correct: "true now, and true when it was written", stale: "once true, no longer true", wrong: "never true", unverifiable: "no source available",
40
+ };
41
+ const AUDIT_DAY = 86400_000;
15
42
  export interface EvalEntry { key: string; title?: string; text: string; kind?: (typeof EVAL_KINDS)[number]; tier?: "short" | "long"; about?: string[]; /** Explicit seed date; absent keeps the legacy positional day. */ at?: string }
16
43
  /** `tag` is an optional label for what a question probes (a test counts them); it never changes the scoring. */
17
44
  export interface EvalQuestion { q: string; expect: string[]; tag?: string }
@@ -79,6 +106,45 @@ export function parseKs(value: string | undefined): number[] {
79
106
  return [...new Set(ks)].sort((a, b) => a - b);
80
107
  }
81
108
 
109
+ /**
110
+ * The spec's age bucket for one note: <30 days, 30-90 days, >90 days, measured from `now` to the note's own timestamp. A note written after `now` did not
111
+ * exist at that instant and has no age, so it is outside the frame rather than in `<30`.
112
+ */
113
+ export function auditAge(at: string, now: number): AuditAgeBucket | undefined {
114
+ const written = Date.parse(at);
115
+ if (!Number.isFinite(written) || written > now) return undefined;
116
+ const days = Math.floor((now - written) / AUDIT_DAY);
117
+ return days < 30 ? "lt30" : days <= 90 ? "d30to90" : "gt90";
118
+ }
119
+
120
+ /**
121
+ * One note's anchor verdict from its per-path values: a missing path outranks a changed one, a changed one outranks an uncheckable one, and no anchor at all
122
+ * is `none`.
123
+ */
124
+ export function foldAnchorStatus(statuses: readonly Exclude<AuditAnchorStatus, "none">[]): AuditAnchorStatus {
125
+ if (!statuses.length) return "none";
126
+ if (statuses.includes("missing")) return "missing";
127
+ return statuses.includes("changed") ? "changed" : statuses.includes("unavailable") ? "unavailable" : "present";
128
+ }
129
+
130
+ /**
131
+ * Cohen's kappa for two judges over the closed label set: the observed agreement corrected for what chance alone would give. Null, never 0, when there
132
+ * is nothing to measure - no pair at all, or both judges used one single label throughout, where the chance term is 1 and kappa is undefined.
133
+ */
134
+ export function cohenKappa(pairs: readonly (readonly [string, string])[], vocabulary: readonly string[]): number | null {
135
+ const total = pairs.length;
136
+ if (!total) return null;
137
+ const left = new Map<string, number>(), right = new Map<string, number>();
138
+ let agreed = 0;
139
+ for (const [a, b] of pairs) {
140
+ left.set(a, (left.get(a) ?? 0) + 1); right.set(b, (right.get(b) ?? 0) + 1);
141
+ if (a === b) agreed++;
142
+ }
143
+ const chance = vocabulary.reduce((sum, label) => sum + (left.get(label) ?? 0) * (right.get(label) ?? 0), 0) / (total * total);
144
+ if (chance >= 1) return null;
145
+ return Math.round(((agreed / total) - chance) / (1 - chance) * 10_000) / 10_000;
146
+ }
147
+
82
148
  export interface EvalQuestionResult {
83
149
  q: string;
84
150
  /** True when at least one expected entry exists in the searched store. Only those can be recalled. */
@@ -0,0 +1,28 @@
1
+ import { lstatSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join, relative, sep } from "node:path";
4
+ import { ownedUnwritableDirectory, realPath } from "./platform.ts";
5
+
6
+ export type NativeRootKind = "sessions" | "archived_sessions";
7
+ export type NativeRootStatus = { state: "ready"; path: string } | { state: "unsafe" | "unavailable" };
8
+
9
+ /** Only a symlink at the named root receives this exception; callers still refuse links beneath it. */
10
+ export function inspectNativeRoot(folder: string, home = process.env.HOME?.trim() || homedir()): NativeRootStatus {
11
+ let link = false;
12
+ try {
13
+ link = lstatSync(folder).isSymbolicLink();
14
+ const physical = realPath(folder);
15
+ if (link) {
16
+ const root = realPath(home), rel = relative(root, physical);
17
+ if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel) || !ownedUnwritableDirectory(physical)) return { state: "unsafe" };
18
+ }
19
+ return { state: "ready", path: physical };
20
+ } catch { return { state: link ? "unsafe" : "unavailable" }; }
21
+ }
22
+
23
+ export function nativeRoots(kind: "codex" | "kimi" | "pi", env: NodeJS.ProcessEnv = process.env, home = env.HOME?.trim() || homedir()): { kind: NativeRootKind; folder: string }[] {
24
+ const root = kind === "codex" ? env.CODEX_HOME?.trim() || join(home, ".codex")
25
+ : kind === "kimi" ? env.KIMI_CODE_HOME?.trim() || join(home, ".kimi-code")
26
+ : env.PI_CODING_AGENT_DIR?.trim() || join(home, ".pi", "agent");
27
+ return [{ kind: "sessions", folder: join(root, "sessions") }, ...(kind === "codex" ? [{ kind: "archived_sessions" as const, folder: join(root, "archived_sessions") }] : [])];
28
+ }
@@ -1,5 +1,5 @@
1
1
  // Single-source platform helpers. Hub, local and Pi modules re-export these functions unchanged.
2
- import { realpathSync } from "node:fs";
2
+ import { lstatSync, realpathSync } from "node:fs";
3
3
  import { basename, dirname, join, resolve, sep } from "node:path";
4
4
  import type { SpawnSyncOptions, SpawnSyncOptionsWithBufferEncoding, SpawnSyncOptionsWithStringEncoding, SpawnSyncReturns } from "node:child_process";
5
5
  import { createRequire } from "node:module";
@@ -47,6 +47,14 @@ export function realPath(path: string): string {
47
47
  return r.stdout.slice(0, -1);
48
48
  }
49
49
 
50
+ /** An existing physical directory must belong to this user and resist group/world writes. */
51
+ export function ownedUnwritableDirectory(path: string): boolean {
52
+ try {
53
+ const stat = lstatSync(path), uid = process.getuid?.();
54
+ return uid !== undefined && stat.isDirectory() && !stat.isSymbolicLink() && stat.uid === uid && (stat.mode & 0o022) === 0;
55
+ } catch { return false; }
56
+ }
57
+
50
58
  /** One denylist for core extraction, hub path guards, sandbox rules and capture. */
51
59
  // `.agenthub/archive` holds reset state directories, including task text and PII.
52
60
  export const DENY_SEGMENTS = [".maru/secrets", ".agenthub/state", ".agenthub/archive"];
@@ -0,0 +1,69 @@
1
+ import type { View } from "./store.ts";
2
+ import type { MemoryUseSummary } from "./use-telemetry.ts";
3
+ import type { Counter } from "./candidates.ts";
4
+ import { summarizeMemoryUse } from "./use-telemetry.ts";
5
+ import { Database } from "bun:sqlite";
6
+ import { lstatSync } from "node:fs";
7
+ import { join } from "node:path";
8
+
9
+ export type ReviewReason = "stale" | "rendered" | "volatile";
10
+ export interface ReviewTarget { id: string; reason: ReviewReason; ageDays: number; counts: MemoryUseSummary }
11
+ export interface ReviewTargetOptions {
12
+ now: number; recheckDays: number; limit: number;
13
+ stale: (view: View) => boolean | undefined;
14
+ use: (view: View) => MemoryUseSummary;
15
+ /** False when a retained decided candidate was created inside the window. */
16
+ eligibleForRecheck: (view: View, cutoff: number) => boolean;
17
+ }
18
+
19
+ export const REVIEW_DEFAULTS = { recheck_days: 30, unused_rendered: 20, unused_days: 30 } as const;
20
+ export interface ReviewSnapshot { counters: Counter[]; decided: { at: number; targets: string[] }[] }
21
+ /** Read the sidecar without opening the writer, pruning, or altering the schema. */
22
+ export function readReviewSnapshot(home: string, projects: readonly string[]): ReviewSnapshot {
23
+ const file = join(home, "candidates.db"), stat = lstatSync(file, { throwIfNoEntry: false });
24
+ if (!stat) return { counters: [], decided: [] };
25
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) throw Error("review history unavailable: candidate database is not a private regular file; inspect the memory home before retrying");
26
+ const db = new Database(file, { readonly: true });
27
+ try {
28
+ db.run("PRAGMA busy_timeout = 0");
29
+ const scope = JSON.stringify(projects);
30
+ const counters = (db.query("SELECT id,payload,at,rendered,delivered,cited FROM counters WHERE project IN (SELECT value FROM json_each(?)) ORDER BY id").all(scope) as { id: string; payload: string; at: number; rendered: number | null; delivered: number | null; cited: number | null }[])
31
+ .map(row => ({ id: row.id, key: JSON.parse(row.payload), createdAt: new Date(row.at).toISOString(), rendered: row.rendered, delivered: row.delivered, cited: row.cited }));
32
+ const decided = (db.query("SELECT at,payload FROM candidates WHERE project IN (SELECT value FROM json_each(?)) AND status IN ('accepted','rejected') ORDER BY at,id").all(scope) as { at: number; payload: string }[]).map(row => {
33
+ const input = JSON.parse(row.payload) as { target?: { id?: string }; targets?: { id?: string }[] };
34
+ return { at: row.at, targets: [input.target?.id, ...(input.targets ?? []).map(target => target.id)].filter((id): id is string => typeof id === "string") };
35
+ });
36
+ return { counters, decided };
37
+ } finally { db.close(); }
38
+ }
39
+
40
+ export function reviewUse(snapshot: ReviewSnapshot, project: readonly string[], id: string, since = -Infinity): MemoryUseSummary {
41
+ return summarizeMemoryUse(snapshot.counters.filter(row => project.includes(row.key.project) && row.key.entryId === id && Date.parse(row.createdAt) >= since));
42
+ }
43
+
44
+ /** ponytail: candidate creation time approximates decision time; add a decision timestamp if over-listing proves material. */
45
+ export function noRecentReview(snapshot: ReviewSnapshot, id: string, cutoff: number): boolean {
46
+ return !snapshot.decided.some(row => row.at >= cutoff && row.targets.includes(id));
47
+ }
48
+
49
+ /** Pure selection over a caller-supplied snapshot. The caller supplies policy-screened views and read-only telemetry. */
50
+ export function reviewTargets(views: readonly View[], options: ReviewTargetOptions): ReviewTarget[] {
51
+ const { now, recheckDays, limit } = options;
52
+ if (!Number.isFinite(now) || !Number.isSafeInteger(recheckDays) || recheckDays < 1 || !Number.isSafeInteger(limit) || limit < 1 || limit > 500)
53
+ throw Error("invalid review target window or limit; use a positive recheck window and a limit from 1 to 500");
54
+ const cutoff = now - recheckDays * 86400_000;
55
+ const rows: ReviewTarget[] = [];
56
+ for (const view of views) {
57
+ const at = Date.parse(view.at);
58
+ if (!Number.isFinite(at) || at > now || view.supersededBy) continue;
59
+ const counts = options.use(view), ageDays = Math.floor((now - at) / 86400_000);
60
+ const reason: ReviewReason | undefined = options.stale(view) === true ? "stale"
61
+ : counts.rendered !== null && counts.rendered > 0 && options.eligibleForRecheck(view, cutoff) ? "rendered"
62
+ : (view.kind === "decision" || view.kind === "contract") && at < cutoff ? "volatile" : undefined;
63
+ if (reason) rows.push({ id: view.id, reason, ageDays, counts });
64
+ }
65
+ const rank: Record<ReviewReason, number> = { stale: 0, rendered: 1, volatile: 2 };
66
+ return rows.sort((a, b) => rank[a.reason] - rank[b.reason]
67
+ || (a.reason === "rendered" ? (b.counts.rendered ?? 0) - (a.counts.rendered ?? 0) : b.ageDays - a.ageDays)
68
+ || a.id.localeCompare(b.id)).slice(0, limit);
69
+ }