@staix/agent-mem 0.3.1 → 0.4.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,40 @@
1
+ import { validVaultPath } from "./generation.ts";
2
+ import { createStandalonePolicy, type MemoryPolicy } from "./policy.ts";
3
+ import type { MemoryStore, View, VaultEntry } from "./store.ts";
4
+
5
+ export interface VaultSelection { project: string; policy: MemoryPolicy; limit?: number }
6
+ export type { VaultEntry } from "./store.ts";
7
+ export { vaultLinkId, validVaultPath, validateVaultLinkRow, type VaultLinkRow, type VaultLink } from "./generation.ts";
8
+ const invalid = (): never => { throw new Error("invalid vault link or unavailable exact entry"); };
9
+
10
+ function selection(options: VaultSelection): MemoryPolicy {
11
+ if (!options || typeof options.project !== "string" || !options.project.trim() || options.project.length > 400
12
+ || !options.policy || typeof options.policy.screen !== "function" || options.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit < 1 || options.limit > 200)) throw new Error("invalid startup-bound vault selection");
13
+ return createStandalonePolicy({ host: options.policy });
14
+ }
15
+ function durable(view: View): boolean {
16
+ if (view.tier !== "long" || view.local || view.expiresAt !== null || view.supersededBy || !["decision", "finding", "contract", "fail"].includes(view.kind)) return false;
17
+ const text = `${view.title ?? ""}\n${view.text}`.normalize("NFKC");
18
+ // ponytail: deterministic suggestions can omit durable lessons phrased as status; a separately measured classifier
19
+ // may improve recall later, but candidate selection never calls a model or imports capture into curated evidence.
20
+ return !/(?:\b(?:task|ticket)\s*#?\d+\b[^\n]*(?:completed|done|in.progress|blocked|checkpoint)|\b(?:review|ci|checks?|pipeline|build)\s*(?::|-)?\s*(?:is\s+)?(?:approved|passed|green|failed|pending|rejected)|\b(?:pr|pull request)\s*#?\d+\b[^\n]*(?:merged|closed|approved|opened|ready)|\b(?:task progress|review verdict|pr status|ci status|working on|progress checkpoint)\b)/i.test(text);
21
+ }
22
+
23
+ /** Policy runs over every startup-project value before durable selection, ordering, limit or returned counts. */
24
+ export async function vaultCandidates(store: MemoryStore, options: VaultSelection): Promise<View[]> {
25
+ const policy = selection(options), visible: VaultEntry[] = [];
26
+ for (const entry of store.vaultEntries(options.project)) if (await policy.screen(entry.view)) visible.push(entry);
27
+ const linked = new Set(store.vaultLinks(options.project).map(row => `${row.target}:${row.rowHash}`));
28
+ return visible.filter(entry => durable(entry.view) && !linked.has(`${entry.view.id}:${entry.rowHash}`)).map(entry => entry.view)
29
+ .sort((a, b) => b.at.localeCompare(a.at) || a.id.localeCompare(b.id)).slice(0, options.limit ?? 50);
30
+ }
31
+
32
+ /** Person-facing hosts authenticate intent before calling; no MCP vault-link tool is provided. */
33
+ export async function recordVaultLink(store: MemoryStore, id: string, path: string, options: VaultSelection): Promise<string> {
34
+ const policy = selection(options);
35
+ if (store.profile.kind !== "generation") throw new Error("vault links require a generation profile; shared-v1 is unchanged");
36
+ if (!/^[a-f0-9]{32}$/.test(id) || !validVaultPath(path)) return invalid();
37
+ const entry = store.vaultEntries(options.project).find(row => row.view.id === id);
38
+ if (!entry || !await policy.screen({ entry: entry.view, path }) || !durable(entry.view)) return invalid();
39
+ return store.recordVaultLink(id, path, options.project, entry.rowHash);
40
+ }
@@ -0,0 +1,243 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { appendFileSync, chmodSync, closeSync, lstatSync, mkdirSync, openSync, readSync, readdirSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { StringDecoder } from "node:string_decoder";
6
+ import { canonicalJSON, hashJSON } from "./generation.ts";
7
+ import { mutationDatabase } from "./mutation.ts";
8
+ import { canonicalPath } from "./platform.ts";
9
+ import { looksSecret } from "./screen.ts";
10
+ import { ensureShardDescriptor, resolveAlias, shardDir } from "./shard.ts";
11
+ import { machineId } from "./store.ts";
12
+
13
+ const SCHEMA = "agent-mem.work-list/v1", ROW_BYTES = 16_384;
14
+ const READ_ROW_CEILING = 5000;
15
+ export type WorkListFields = Record<string, string | number | boolean | null>;
16
+ export type WorkListPolicy = (row: unknown) => boolean | Promise<boolean>;
17
+ export interface WorkListSource { source: string; id: string; machine?: string; at?: number }
18
+ export interface WorkListView { list: string; fields: WorkListFields; items: { task: string; fields: WorkListFields }[]; closed: boolean }
19
+ interface WorkRow { schema: typeof SCHEMA; project: string; machine: string; at: number; nonce: string; list: string; fields: WorkListFields; source?: WorkListSource; id: string }
20
+ interface IndexedRow { row: WorkRow; position: number }
21
+ interface Head { file: string; bytes: number; hash: string }
22
+ const forbidden = new Set(["__proto__", "constructor", "prototype"]);
23
+ const bounded = (value: unknown, max: number): value is string => typeof value === "string" && value.trim().length > 0 && value.length <= max && !/[\x00-\x1f\x7f]/.test(value);
24
+ const invalid = (): never => { throw new Error("invalid work-list input"); };
25
+ function regular(path: string, directory = false): void {
26
+ try {
27
+ const stat = lstatSync(path);
28
+ if (stat.isSymbolicLink() || !(directory ? stat.isDirectory() : stat.isFile())) throw new Error("work log path is invalid");
29
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
30
+ }
31
+ function fieldsOf(input: unknown): WorkListFields {
32
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).length > 64 || Object.keys(input).length === 0) return invalid();
33
+ const out: WorkListFields = {};
34
+ for (const [key, value] of Object.entries(input)) {
35
+ if (!bounded(key, 100) || forbidden.has(key) || !(value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || typeof value === "string" && value.length <= 8000 && !value.includes("\0"))) return invalid();
36
+ out[key] = value;
37
+ }
38
+ if (Object.hasOwn(out, "task") && !bounded(out.task, 300)) return invalid();
39
+ if (typeof out.task === "string" && Object.hasOwn(out, "status") && out.status !== null && !["todo", "doing", "done", "dropped"].includes(String(out.status))) return invalid();
40
+ return out;
41
+ }
42
+ function sourceOf(input: unknown): WorkListSource | undefined {
43
+ if (input === undefined) return undefined;
44
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => !["source", "id", "machine", "at"].includes(key))) return invalid();
45
+ const source = input as WorkListSource;
46
+ if (!bounded(source.source, 500) || !bounded(source.id, 500) || source.machine !== undefined && !bounded(source.machine, 300) || source.at !== undefined && (!Number.isSafeInteger(source.at) || source.at < 0)) return invalid();
47
+ return { source: source.source, id: source.id, ...(source.machine === undefined ? {} : { machine: source.machine }), ...(source.at === undefined ? {} : { at: source.at }) };
48
+ }
49
+ const receipt = (row: Pick<WorkRow, "source">): string | null => row.source ? hashJSON({ source: row.source.source, id: row.source.id, machine: row.source.machine ?? null }) : null;
50
+ const importPayload = (row: Pick<WorkRow, "list" | "fields" | "source">): string => hashJSON({ list: row.list, fields: row.fields, source: row.source });
51
+ const lexical = (a: string, b: string): number => a < b ? -1 : a > b ? 1 : 0;
52
+ /** Source row ids retain their numeric sequence, including ids such as work-9 and work-10. */
53
+ function sourceOrder(a: string, b: string): number {
54
+ const left = a.match(/\d+|\D+/g) ?? [], right = b.match(/\d+|\D+/g) ?? [];
55
+ for (let i = 0; i < Math.min(left.length, right.length); i++) {
56
+ const x = left[i]!, y = right[i]!;
57
+ if (/^\d+$/.test(x) && /^\d+$/.test(y)) {
58
+ const n = BigInt(x), m = BigInt(y); if (n !== m) return n < m ? -1 : 1;
59
+ } else { const order = lexical(x, y); if (order) return order; }
60
+ }
61
+ return left.length - right.length || lexical(a, b);
62
+ }
63
+ /**
64
+ * Equal epochs have no causal order across origins: imports sort before authored rows, then by source device and
65
+ * source identity (lexically). Within one import origin, source ids use numeric order. Authored same-machine ties
66
+ * retain physical append position. Position is derived, never added to or changed inside the screened/hash row.
67
+ */
68
+ function replayOrder(a: IndexedRow, b: IndexedRow): number {
69
+ const x = a.row, y = b.row;
70
+ if (x.at !== y.at) return x.at - y.at;
71
+ const groupX = x.source ? ["import", x.source.machine ?? "", x.source.source] : ["native", x.machine, ""];
72
+ const groupY = y.source ? ["import", y.source.machine ?? "", y.source.source] : ["native", y.machine, ""];
73
+ for (let i = 0; i < groupX.length; i++) { const order = lexical(groupX[i]!, groupY[i]!); if (order) return order; }
74
+ if (x.source && y.source) { const order = sourceOrder(x.source.id, y.source.id); if (order) return order; }
75
+ return lexical(x.machine, y.machine) || a.position - b.position || lexical(x.id, y.id);
76
+ }
77
+
78
+ /** Stream log bytes with bounded carry; neither a long history nor an invalid oversized row is loaded at once. */
79
+ function scan(path: string, consume?: (text: string, end: number) => void, prefixBytes = 0): { bytes: number; hash: string; prefix: string } {
80
+ const stat = lstatSync(path);
81
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("work log is not a regular file");
82
+ const fd = openSync(path, "r"), buffer = Buffer.alloc(64 * 1024), full = createHash("sha256"), prefix = createHash("sha256"), decoder = new StringDecoder("utf8");
83
+ let bytes = 0, text = "", lineEnd = 0;
84
+ try {
85
+ for (;;) {
86
+ const n = readSync(fd, buffer, 0, buffer.length, null); if (!n) break;
87
+ const chunk = buffer.subarray(0, n); full.update(chunk);
88
+ if (bytes < prefixBytes) prefix.update(chunk.subarray(0, Math.min(n, prefixBytes - bytes)));
89
+ bytes += n;
90
+ if (consume) {
91
+ text += decoder.write(chunk);
92
+ let end: number;
93
+ while ((end = text.indexOf("\n")) >= 0) {
94
+ const line = text.slice(0, end); lineEnd += Buffer.byteLength(line + "\n"); text = text.slice(end + 1);
95
+ if (!line || Buffer.byteLength(line) > ROW_BYTES) throw new Error("work log contains an invalid row");
96
+ consume(line, lineEnd);
97
+ }
98
+ if (Buffer.byteLength(text) > ROW_BYTES) throw new Error("work log contains an oversized row");
99
+ }
100
+ }
101
+ if (consume && (text + decoder.end()).length) throw new Error("work log has an incomplete row");
102
+ return { bytes, hash: full.digest("hex"), prefix: prefix.digest("hex") };
103
+ } finally { closeSync(fd); }
104
+ }
105
+
106
+ /** Project-scoped append truth; the index and writer lock are independent of generations and capture eviction. */
107
+ export class WorkListStore {
108
+ readonly dir: string;
109
+ readonly project: string;
110
+ private readonly db: Database;
111
+ private readonly mutation: Database;
112
+ private readonly machine: string;
113
+ private readonly policy: WorkListPolicy;
114
+ private readonly now: () => number;
115
+ private closed = false;
116
+
117
+ constructor(options: { base: string; project: string; policy: WorkListPolicy; now?: () => number }) {
118
+ if (!bounded(options.project, 1000) || typeof options.policy !== "function") throw new Error("invalid work-list input");
119
+ const base = canonicalPath(options.base);
120
+ this.project = resolveAlias(base, options.project);
121
+ regular(join(base, "projects"), true); regular(shardDir(base, this.project), true);
122
+ ensureShardDescriptor(base, this.project);
123
+ this.dir = join(shardDir(base, this.project), "work");
124
+ regular(this.dir, true); regular(join(this.dir, "log"), true);
125
+ mkdirSync(this.dir, { recursive: true, mode: 0o700 }); chmodSync(this.dir, 0o700);
126
+ mkdirSync(join(this.dir, "log"), { recursive: true, mode: 0o700 });
127
+ if (lstatSync(this.dir).isSymbolicLink() || lstatSync(join(this.dir, "log")).isSymbolicLink()) throw new Error("work log directory is invalid");
128
+ this.machine = machineId(base).id;
129
+ this.policy = options.policy; this.now = options.now ?? Date.now;
130
+ for (const name of ["mutation-lock.db", "index.db", "index.db-wal", "index.db-shm"]) regular(join(this.dir, name));
131
+ this.mutation = mutationDatabase(this.dir);
132
+ this.db = new Database(join(this.dir, "index.db"), { create: true }); chmodSync(join(this.dir, "index.db"), 0o600);
133
+ this.db.run("PRAGMA busy_timeout = 3000"); this.db.run("PRAGMA journal_mode = WAL");
134
+ // The index is disposable. An older derived schema is replayed without changing a log row.
135
+ const columns = this.db.query("PRAGMA table_info(work_ops)").all() as { name: string }[];
136
+ if (columns.length && !columns.some(column => column.name === "position")) { this.db.run("DROP TABLE work_ops"); this.db.run("DROP TABLE IF EXISTS work_heads"); }
137
+ this.db.run("CREATE TABLE IF NOT EXISTS work_ops (id TEXT PRIMARY KEY, at INTEGER NOT NULL, machine TEXT NOT NULL, payload TEXT NOT NULL, receipt TEXT, position INTEGER NOT NULL)");
138
+ this.db.run("CREATE INDEX IF NOT EXISTS work_receipts ON work_ops(receipt)");
139
+ this.db.run("CREATE TABLE IF NOT EXISTS work_heads (file TEXT PRIMARY KEY, bytes INTEGER NOT NULL, hash TEXT NOT NULL)");
140
+ }
141
+
142
+ close(): void { if (!this.closed) { this.closed = true; this.db.close(); this.mutation.close(); } }
143
+ private locked<T>(run: () => T): T {
144
+ if (this.closed) throw new Error("work-list store is closed");
145
+ return this.mutation.transaction(run).immediate();
146
+ }
147
+ private decode(text: string): WorkRow {
148
+ try {
149
+ const row = JSON.parse(text) as WorkRow;
150
+ if (!row || row.schema !== SCHEMA || row.project !== this.project || !/^[a-f0-9]{16}$/.test(row.machine) || !Number.isSafeInteger(row.at) || row.at < 0 || !/^[a-f0-9]{32}$/.test(row.nonce) || !bounded(row.list, 300) || !/^[a-f0-9]{64}$/.test(row.id) || Object.keys(row).some(key => !["schema", "project", "machine", "at", "nonce", "list", "fields", "source", "id"].includes(key))) throw new Error();
151
+ fieldsOf(row.fields); sourceOf(row.source);
152
+ const { id, ...body } = row;
153
+ if (hashJSON(body) !== id || Buffer.byteLength(text) > ROW_BYTES) throw new Error();
154
+ return row;
155
+ } catch { throw new Error("work log contains an invalid hashed row"); }
156
+ }
157
+ private index(row: WorkRow, position: number): void {
158
+ const key = receipt(row);
159
+ if (key) for (const prior of this.db.query("SELECT payload FROM work_ops WHERE receipt = ?").all(key) as { payload: string }[]) {
160
+ if (importPayload(this.decode(prior.payload)) !== importPayload(row)) throw new Error("work log contains conflicting source receipts");
161
+ }
162
+ this.db.query("INSERT OR IGNORE INTO work_ops (id, at, machine, payload, receipt, position) VALUES (?, ?, ?, ?, ?, ?)").run(row.id, row.at, row.machine, canonicalJSON(row), key, position);
163
+ }
164
+ private refresh(force = false): void {
165
+ const files = readdirSync(join(this.dir, "log")).sort();
166
+ if (files.some(file => !/^[a-f0-9]{16}\.jsonl$/.test(file))) throw new Error("work log has an invalid segment name");
167
+ const heads = new Map((this.db.query("SELECT file, bytes, hash FROM work_heads").all() as Head[]).map(head => [head.file, head]));
168
+ const scans = new Map(files.map(file => [file, scan(join(this.dir, "log", file), undefined, heads.get(file)?.bytes ?? 0)]));
169
+ const reset = force || [...heads].some(([file, head]) => !scans.has(file) || scans.get(file)!.bytes < head.bytes || scans.get(file)!.prefix !== head.hash);
170
+ this.db.transaction(() => {
171
+ if (reset) { this.db.run("DELETE FROM work_ops"); this.db.run("DELETE FROM work_heads"); }
172
+ for (const file of files) {
173
+ const old = reset ? 0 : heads.get(file)?.bytes ?? 0, current = scans.get(file)!;
174
+ if (old !== current.bytes) scan(join(this.dir, "log", file), (line, end) => { if (end > old) this.index(this.decode(line), end); });
175
+ this.db.query("INSERT OR REPLACE INTO work_heads (file, bytes, hash) VALUES (?, ?, ?)").run(file, current.bytes, current.hash);
176
+ }
177
+ }).immediate();
178
+ }
179
+ rebuild(): void { this.locked(() => this.refresh(true)); }
180
+ private async permitted(row: WorkRow): Promise<boolean> {
181
+ if (looksSecret(canonicalJSON(row))) return false;
182
+ const copy = structuredClone(row); Object.freeze(copy.fields); if (copy.source) Object.freeze(copy.source); Object.freeze(copy);
183
+ try { return await this.policy(copy) === true; } catch { return false; }
184
+ }
185
+
186
+ async write(list: string, input: WorkListFields, source?: WorkListSource): Promise<{ id: string; already: boolean }> {
187
+ if (!bounded(list, 300)) return invalid();
188
+ const fields = fieldsOf(input), origin = sourceOf(source);
189
+ const at = origin?.at ?? this.locked(() => {
190
+ this.refresh();
191
+ const previous = this.db.query("SELECT max(at) AS at FROM work_ops WHERE machine = ?").get(this.machine) as { at: number | null };
192
+ return Math.max(this.now(), (previous.at ?? -1) + 1);
193
+ });
194
+ if (!Number.isSafeInteger(at) || at < 0) return invalid();
195
+ const body: Omit<WorkRow, "id"> = { schema: SCHEMA, project: this.project, machine: this.machine, at, nonce: randomBytes(16).toString("hex"), list, fields, ...(origin ? { source: origin } : {}) };
196
+ const row: WorkRow = { ...body, id: hashJSON(body) };
197
+ if (Buffer.byteLength(canonicalJSON(row)) > ROW_BYTES) return invalid();
198
+ if (!await this.permitted(row)) throw new Error("work-list privacy policy refused the write");
199
+ return this.locked(() => {
200
+ this.refresh();
201
+ const key = receipt(row);
202
+ if (key) {
203
+ const found = this.db.query("SELECT payload FROM work_ops WHERE receipt = ? ORDER BY id LIMIT 1").get(key) as { payload: string } | null;
204
+ if (found) {
205
+ const prior = this.decode(found.payload);
206
+ if (importPayload(prior) !== importPayload(row)) throw new Error("work-list source receipt conflicts with an earlier import");
207
+ return { id: prior.id, already: true };
208
+ }
209
+ }
210
+ // No metadata changes after screening: the derived index records same-machine append order.
211
+ regular(join(this.dir, "log", `${this.machine}.jsonl`));
212
+ appendFileSync(join(this.dir, "log", `${this.machine}.jsonl`), canonicalJSON(row) + "\n", { mode: 0o600 });
213
+ this.refresh();
214
+ return { id: row.id, already: false };
215
+ });
216
+ }
217
+
218
+ async read(list?: string, includeClosed = false): Promise<WorkListView[]> {
219
+ if (list !== undefined && !bounded(list, 300) || typeof includeClosed !== "boolean") return invalid();
220
+ const rows = this.locked(() => {
221
+ this.refresh();
222
+ // ponytail: 5000 persisted operations per project read, including named-list reads. Refuse before payload
223
+ // materialization; append truth is never truncated. Upgrade to bounded streaming reduction for longer histories.
224
+ const count = this.db.query("SELECT count(*) AS count FROM work_ops").get() as { count: number };
225
+ if (count.count > READ_ROW_CEILING) throw new Error("work-list read exceeds 5000-row ceiling");
226
+ return (this.db.query("SELECT payload, position FROM work_ops").all() as { payload: string; position: number }[]).map(row => ({ row: this.decode(row.payload), position: row.position })).sort(replayOrder);
227
+ });
228
+ const views = new Map<string, { fields: WorkListFields; items: Map<string, WorkListFields> }>();
229
+ for (const { row } of rows) {
230
+ if (!await this.permitted(row)) continue;
231
+ if (list !== undefined && row.list !== list) continue;
232
+ let view = views.get(row.list); if (!view) { view = { fields: {}, items: new Map() }; views.set(row.list, view); }
233
+ const task = row.fields.task;
234
+ const target = typeof task === "string" ? view.items.get(task) ?? {} : view.fields;
235
+ if (typeof task === "string") view.items.set(task, target);
236
+ for (const [key, value] of Object.entries(row.fields)) if (key !== "task") { if (value === null) delete target[key]; else target[key] = value; }
237
+ }
238
+ return [...views].sort(([a], [b]) => a.localeCompare(b)).flatMap(([name, view]) => {
239
+ const closed = view.fields.status === "done";
240
+ return closed && !includeClosed ? [] : [{ list: name, fields: view.fields, items: [...view.items].sort(([a], [b]) => a.localeCompare(b)).map(([task, fields]) => ({ task, fields })), closed }];
241
+ });
242
+ }
243
+ }