@staix/vault-mem 0.9.0 → 0.10.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +19 -6
  3. package/bin/vmem.js +2 -2
  4. package/package.json +2 -2
  5. package/src/analysis-commands.ts +24 -14
  6. package/src/analysis-input.ts +12 -0
  7. package/src/analysis-types.ts +5 -1
  8. package/src/assert-command.ts +48 -0
  9. package/src/assertion-exposure.ts +367 -0
  10. package/src/assertion-index.ts +86 -0
  11. package/src/assertion-policy.ts +63 -0
  12. package/src/assertion-read.ts +170 -0
  13. package/src/assertions-command.ts +123 -0
  14. package/src/assertions.ts +1013 -0
  15. package/src/cli-output.ts +9 -3
  16. package/src/cli.ts +44 -23
  17. package/src/commands-table.ts +16 -2
  18. package/src/evidence.ts +222 -0
  19. package/src/graph-evidence.ts +169 -0
  20. package/src/index.ts +14 -0
  21. package/src/links.ts +18 -0
  22. package/src/log-commands.ts +7 -7
  23. package/src/mcp-spec.ts +11 -11
  24. package/src/mcp-vault.ts +105 -6
  25. package/src/mcp.ts +4 -0
  26. package/src/org-commands.ts +5 -5
  27. package/src/org-promote.ts +9 -0
  28. package/src/promote-command.ts +6 -6
  29. package/src/proposal-commands.ts +100 -0
  30. package/src/proposal-provider.ts +335 -0
  31. package/src/proposal-storage.ts +334 -0
  32. package/src/proposals.ts +170 -0
  33. package/src/read-commands.ts +44 -12
  34. package/src/read-output.ts +42 -14
  35. package/src/skills-mine.ts +12 -7
  36. package/src/source-age.ts +131 -0
  37. package/src/spec-output.ts +14 -13
  38. package/src/sync.ts +14 -7
  39. package/src/text-output.ts +86 -21
  40. package/src/vault-brief.ts +8 -4
  41. package/src/vault-graph.ts +12 -3
  42. package/src/vault-history.ts +662 -0
  43. package/src/vault-index.ts +2 -0
  44. package/src/vault-lint.ts +15 -4
  45. package/src/write-commands.ts +18 -17
  46. package/src/write-output.ts +6 -6
  47. package/src/write-types.ts +1 -0
  48. package/src/write-validation.ts +3 -1
  49. package/src/writer.ts +257 -11
@@ -0,0 +1,334 @@
1
+ /** Internal bounded storage for proposal records and binding metadata. */
2
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, realpathSync, writeFileSync, type Stats } from "node:fs";
3
+ import { randomUUID } from "node:crypto";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { LOCK_FILE, syncDirectory } from "./registry.ts";
6
+ import { capturePublicationPath, cleanupOwnedFile, publishFile } from "./write-files.ts";
7
+ import { isDenied } from "./platform.ts";
8
+ import { decodeProposalEvidence, decodeProposalReason, decodeProposalRecord, encodeProposalEvidence, encodeProposalReason, encodeProposalRecord, MAX_PROPOSAL_RECORD_BYTES, proposalRecordDigest, type ProposalExecutionEvidence, type ProposalReason, type ProposalRecord } from "./proposals.ts";
9
+ import type { WriteIssue } from "./write-types.ts";
10
+
11
+ const DIGEST = /^[a-f0-9]{64}$/;
12
+ const ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
13
+ const MAX_BINDINGS = 256, MAX_BINDING_BYTES = 4096;
14
+ function leftover(name: string): WriteIssue {
15
+ const display = /^[A-Za-z0-9._-]{1,100}$/.test(name) && !/(?:secret|token|password|credential)/i.test(name) ? name : "name withheld";
16
+ return { code: "PROPOSAL_LEFTOVER", severity: "warning", message: `proposal store skipped unexpected entry ${display}; inspect the proposal store and retry after concurrent writes finish` };
17
+ }
18
+ function requireAllowed(denyPaths: string[], ...paths: string[]): void {
19
+ if (paths.some(path => isDenied(path, denyPaths))) throw new Error("proposal: storage path is denied by current policy; inspect the configured deny paths");
20
+ }
21
+ function storeRoot(home: string, denyPaths: string[]): string {
22
+ const configured = resolve(home); requireAllowed(denyPaths, configured);
23
+ let root: string;
24
+ try { root = realpathSync(configured); } catch { throw new Error("proposal: configured home is unavailable; set VMEM_HOME to an existing home or restore it from backup"); }
25
+ requireAllowed(denyPaths, root);
26
+ if (!lstatSync(root).isDirectory()) throw new Error("proposal: configured home is not a directory; set VMEM_HOME to an existing home");
27
+ return root;
28
+ }
29
+ function validateDirectory(path: string): void {
30
+ const info = lstatSync(path);
31
+ if (!info.isDirectory() || info.isSymbolicLink() || (info.mode & 0o077) !== 0 || (typeof process.getuid === "function" && info.uid !== process.getuid()))
32
+ throw new Error("proposal: store directory is linked or not private; inspect the configured home");
33
+ }
34
+ /** The binding is derived internally by the caller, never accepted from a CLI or MCP request. */
35
+ function directory(home: string, binding: string, create: boolean, denyPaths: string[] = []): string {
36
+ if (!DIGEST.test(binding)) throw new Error("proposal: invalid internal vault binding; inspect the registered vault");
37
+ const root = storeRoot(home, denyPaths);
38
+ requireAllowed(denyPaths, root, join(root, "proposals"), join(root, "proposals", binding));
39
+ let current = root;
40
+ for (const part of ["proposals", binding]) {
41
+ current = join(current, part);
42
+ if (create) {
43
+ let made = false;
44
+ try { mkdirSync(current, { mode: 0o700 }); made = true; }
45
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
46
+ if (made) syncDirectory(dirname(current));
47
+ }
48
+ validateDirectory(current);
49
+ }
50
+ return current;
51
+ }
52
+ function recordFile(home: string, binding: string, id: string, create: boolean, denyPaths: string[] = []): { root: string; file: string } {
53
+ if (!ID.test(id)) throw new Error("proposal: invalid proposal id; use an id from proposal list");
54
+ const root = storeRoot(home, denyPaths), file = join(root, "proposals", binding, `${id}.json`);
55
+ requireAllowed(denyPaths, file);
56
+ directory(root, binding, create, denyPaths);
57
+ return { root, file };
58
+ }
59
+ function validRecordFile(info: Stats): void {
60
+ if (info.nlink !== 1) throw new Error("proposal: record is linked or publication is in progress; retry after concurrent writes finish, then inspect the proposal store");
61
+ if (!info.isFile() || (info.mode & 0o077) !== 0 || (typeof process.getuid === "function" && info.uid !== process.getuid()))
62
+ throw new Error("proposal: record is linked or not private; inspect the proposal store");
63
+ if (info.size > MAX_PROPOSAL_RECORD_BYTES) throw new Error("proposal: stored record exceeds 32 KiB; inspect the proposal store");
64
+ }
65
+ /** Binding metadata contains no note or proposal body. Each read is bounded before allocation. */
66
+ function readBinding(home: string, binding: string, denyPaths: string[] = []): { vault: string; bindingDigest: string } {
67
+ const root = storeRoot(home, denyPaths), file = join(root, "proposals", binding, "binding.json");
68
+ requireAllowed(denyPaths, file);
69
+ directory(root, binding, false, denyPaths);
70
+ const captured = capturePublicationPath(root, file);
71
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
72
+ try {
73
+ const before = fstatSync(fd); validRecordFile(before);
74
+ if (before.size > MAX_BINDING_BYTES) throw new Error("proposal: binding metadata exceeds its bound; inspect the proposal store");
75
+ const bytes = Buffer.alloc(MAX_BINDING_BYTES + 1); let length = 0, n = 0;
76
+ while (length < bytes.length && (n = readSync(fd, bytes, length, bytes.length - length, null)) > 0) length += n;
77
+ const after = fstatSync(fd), named = lstatSync(file), parents = capturePublicationPath(root, file);
78
+ validRecordFile(after); validRecordFile(named);
79
+ if (length > MAX_BINDING_BYTES || length !== after.size || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || after.dev !== named.dev || after.ino !== named.ino || JSON.stringify(captured.parents) !== JSON.stringify(parents.parents))
80
+ throw new Error("proposal: binding metadata changed while reading; inspect the proposal store");
81
+ const data = bytes.subarray(0, length), text = data.toString("utf8");
82
+ if (!Buffer.from(text, "utf8").equals(data)) throw new Error("proposal: binding metadata is not UTF-8; inspect the proposal store");
83
+ let parsed: unknown;
84
+ try { parsed = JSON.parse(text); } catch { throw new Error("proposal: binding metadata is not JSON; inspect the proposal store"); }
85
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || JSON.stringify(parsed) !== text) throw new Error("proposal: binding metadata is corrupt; inspect the proposal store");
86
+ const value = parsed as Record<string, unknown>;
87
+ if (Object.keys(value).sort().join(",") !== "bindingDigest,schemaVersion,vault" || value.schemaVersion !== 1 || typeof value.vault !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.vault) || value.bindingDigest !== binding)
88
+ throw new Error("proposal: binding metadata is invalid; inspect the proposal store");
89
+ return { vault: value.vault, bindingDigest: binding };
90
+ } finally { closeSync(fd); }
91
+ }
92
+
93
+ /** Bounded lookup prevents a re-registered vault id from silently choosing another store. */
94
+ export function checkStoredBinding(home: string, vault: string, expected: string, denyPaths: string[] = [], issues: WriteIssue[] = []): boolean {
95
+ if (!DIGEST.test(expected) || !/^[a-z][a-z0-9-]{0,63}$/.test(vault)) throw new Error("proposal: invalid internal vault binding; inspect the registered vault");
96
+ const root = storeRoot(home, denyPaths), base = join(root, "proposals");
97
+ requireAllowed(denyPaths, root, base);
98
+ try { validateDirectory(base); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; }
99
+ const parent = capturePublicationPath(root, join(base, ".scan")), dir = opendirSync(base); let count = 0, found = false;
100
+ try {
101
+ let entry;
102
+ while ((entry = dir.readSync()) !== null) {
103
+ if (entry.name === ".binding.lock") { issues.push(leftover(entry.name)); continue; }
104
+ if (++count > MAX_BINDINGS) throw new Error("proposal: too many vault bindings to inspect; inspect the proposal store");
105
+ if (!DIGEST.test(entry.name)) { issues.push(leftover(entry.name)); continue; }
106
+ let binding: { vault: string; bindingDigest: string };
107
+ try { binding = readBinding(root, entry.name, denyPaths); }
108
+ catch (error) {
109
+ if (error instanceof Error && /denied by current policy/.test(error.message)) throw error;
110
+ issues.push({ code: "PROPOSAL_BINDING_UNREADABLE", severity: "warning", message: `proposal binding ${entry.name}: metadata is incomplete, linked or corrupt; inspect the proposal store and retry after concurrent writes finish` });
111
+ continue;
112
+ }
113
+ if (binding.vault === vault && binding.bindingDigest !== expected) issues.push({ code: "PROPOSAL_ORPHANED_BINDING", severity: "warning", message: "vault root identity changed; old proposals remain bound to the previous root; restore that root or inspect the proposal store" });
114
+ if (binding.vault === vault && binding.bindingDigest === expected) found = true;
115
+ }
116
+ } finally { dir.closeSync(); }
117
+ if (JSON.stringify(parent.parents) !== JSON.stringify(capturePublicationPath(root, join(base, ".scan")).parents)) throw new Error("proposal: store path changed during binding lookup; inspect the configured home");
118
+ return found;
119
+ }
120
+
121
+ function publishNew(root: string, dir: string, file: string, bytes: Uint8Array, denyPaths: string[] = []): void {
122
+ const captured = capturePublicationPath(root, file), temporary = join(dir, `.proposal-${randomUUID()}.tmp`);
123
+ requireAllowed(denyPaths, file, temporary);
124
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
125
+ try {
126
+ writeFileSync(fd, bytes); fsyncSync(fd);
127
+ publishFile(captured, { kind: "link", temp: temporary }, () => {});
128
+ syncDirectory(dir);
129
+ } finally { try { cleanupOwnedFile(temporary, fd); } finally { closeSync(fd); } }
130
+ }
131
+ /** Reads at most 32 KiB and rejects a rebound filename or changed descriptor. */
132
+ export function readStoredProposal(home: string, binding: string, id: string, denyPaths: string[] = []): ProposalRecord {
133
+ const { root, file } = recordFile(home, binding, id, false, denyPaths), captured = capturePublicationPath(root, file);
134
+ let fd: number;
135
+ try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW); }
136
+ catch (error) {
137
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") throw Object.assign(new Error("proposal: id not found; use proposal list to find an existing id"), { code: "ENOENT" });
138
+ throw new Error("proposal: record is linked or unreadable; inspect the proposal store before retrying", { cause: error });
139
+ }
140
+ try {
141
+ const before = fstatSync(fd); validRecordFile(before);
142
+ const bytes = Buffer.alloc(MAX_PROPOSAL_RECORD_BYTES + 1);
143
+ let size = 0, read = 0;
144
+ while (size < bytes.length && (read = readSync(fd, bytes, size, bytes.length - size, null)) > 0) size += read;
145
+ const after = fstatSync(fd), named = lstatSync(file);
146
+ validRecordFile(after); validRecordFile(named);
147
+ if (size > MAX_PROPOSAL_RECORD_BYTES || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || after.dev !== named.dev || after.ino !== named.ino || size !== after.size)
148
+ throw new Error("proposal: stored record changed while reading; retry after concurrent writes stop");
149
+ const parents = capturePublicationPath(root, file);
150
+ if (JSON.stringify(captured.parents) !== JSON.stringify(parents.parents)) throw new Error("proposal: store path changed while reading; inspect the configured home");
151
+ const record = decodeProposalRecord(bytes.subarray(0, size));
152
+ if (record.id !== id || record.bindingDigest !== binding) throw new Error("proposal: stored record binding differs from its path; inspect the proposal store");
153
+ return record;
154
+ } finally { closeSync(fd); }
155
+ }
156
+ /** Enumerate only generated record names, with bounded directory traversal and parent identity checks. */
157
+ export function listStoredProposalIds(home: string, binding: string, denyPaths: string[] = [], issues: WriteIssue[] = []): string[] {
158
+ const root = storeRoot(home, denyPaths), dir = directory(root, binding, false, denyPaths), target = join(dir, ".scan"), captured = capturePublicationPath(root, target);
159
+ const fd = openSync(dir, constants.O_RDONLY | constants.O_NOFOLLOW), before = fstatSync(fd);
160
+ let entries;
161
+ try { entries = opendirSync(dir); } catch (error) { closeSync(fd); throw error; }
162
+ const ids: string[] = [];
163
+ try {
164
+ let item, count = 0;
165
+ while ((item = entries.readSync()) !== null) {
166
+ if (++count > 10001) throw new Error("proposal: store exceeds the listing bound; inspect the proposal store");
167
+ if (item.name === "binding.json") continue;
168
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.[a-f0-9]{64}\.receipt\.json$/.test(item.name)) continue;
169
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.[a-f0-9]{64}\.reason\.json$/.test(item.name)) continue;
170
+ const id = item.name.endsWith(".json") ? item.name.slice(0, -5) : "";
171
+ if (!ID.test(id)) { issues.push(leftover(item.name)); continue; }
172
+ ids.push(id);
173
+ }
174
+ const after = fstatSync(fd), named = lstatSync(dir), parents = capturePublicationPath(root, target);
175
+ validateDirectory(dir);
176
+ if (!named.isDirectory() || named.isSymbolicLink() || before.dev !== after.dev || before.ino !== after.ino || after.dev !== named.dev || after.ino !== named.ino || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || JSON.stringify(captured.parents) !== JSON.stringify(parents.parents))
177
+ throw new Error("proposal: store changed during listing; retry after concurrent writes stop");
178
+ } finally { try { entries.closeSync(); } finally { closeSync(fd); } }
179
+ return ids.sort();
180
+ }
181
+ /** Store mutations require the caller's owned registry lock; no second, unrecoverable store lock is created. */
182
+ function withStoreLock<T>(home: string, create: boolean, work: (root: string) => T, denyPaths: string[], registryFd: number): T {
183
+ const root = storeRoot(home, denyPaths), base = join(root, "proposals"), lock = join(root, LOCK_FILE);
184
+ requireAllowed(denyPaths, root, base, lock);
185
+ const owned = fstatSync(registryFd), named = lstatSync(lock);
186
+ validRecordFile(owned); validRecordFile(named);
187
+ if (owned.dev !== named.dev || owned.ino !== named.ino) throw new Error("proposal: registry lock ownership changed; inspect the lock before retrying");
188
+ if (create) {
189
+ let made = false;
190
+ try { mkdirSync(base, { mode: 0o700 }); made = true; } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
191
+ if (made) syncDirectory(root);
192
+ }
193
+ validateDirectory(base);
194
+ const result = work(root), after = lstatSync(lock), held = fstatSync(registryFd);
195
+ validRecordFile(after); validRecordFile(held);
196
+ if (after.dev !== held.dev || after.ino !== held.ino) throw new Error("proposal: registry lock ownership changed during storage; inspect the proposal before retrying");
197
+ return result;
198
+ }
199
+ function evidenceFile(home: string, binding: string, id: string, fingerprint: string, denyPaths: string[]): { root: string; dir: string; file: string } {
200
+ if (!DIGEST.test(fingerprint) || !ID.test(id)) throw new Error("proposal: invalid evidence identifier; inspect the proposal");
201
+ const root = storeRoot(home, denyPaths), dir = directory(root, binding, false, denyPaths), file = join(dir, `${id}.${fingerprint}.receipt.json`);
202
+ requireAllowed(denyPaths, file);
203
+ return { root, dir, file };
204
+ }
205
+ /** A missing sidecar is not evidence that publication did or did not occur. */
206
+ export function readStoredEvidence(home: string, binding: string, id: string, fingerprint: string, denyPaths: string[] = []): ProposalExecutionEvidence | null {
207
+ const { root, file } = evidenceFile(home, binding, id, fingerprint, denyPaths), captured = capturePublicationPath(root, file);
208
+ let fd: number;
209
+ try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW); }
210
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw new Error("proposal: execution evidence is linked or unreadable; inspect the proposal store", { cause: error }); }
211
+ try {
212
+ const before = fstatSync(fd); validRecordFile(before);
213
+ if (before.size > 4096) throw new Error("proposal: execution evidence exceeds its bound; inspect the proposal store");
214
+ const bytes = Buffer.alloc(4097); let length = 0, n = 0;
215
+ while (length < bytes.length && (n = readSync(fd, bytes, length, bytes.length - length, null)) > 0) length += n;
216
+ const after = fstatSync(fd), named = lstatSync(file), parents = capturePublicationPath(root, file);
217
+ validRecordFile(after); validRecordFile(named);
218
+ if (length > 4096 || length !== after.size || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || after.dev !== named.dev || after.ino !== named.ino || JSON.stringify(captured.parents) !== JSON.stringify(parents.parents)) throw new Error("proposal: execution evidence changed during reading; inspect the proposal store");
219
+ const evidence = decodeProposalEvidence(bytes.subarray(0, length));
220
+ if (evidence.id !== id || evidence.bindingDigest !== binding || evidence.fingerprint !== fingerprint) throw new Error("proposal: execution evidence binding differs; inspect the proposal store");
221
+ // A prior publication may have reported a directory flush failure. Re-flush the existing name before using it as durable evidence.
222
+ if (!syncDirectory(dirname(file))) throw new Error("proposal: execution evidence cannot be durably verified on this platform; inspect the proposal store");
223
+ const flushed = lstatSync(file), finalParents = capturePublicationPath(root, file);
224
+ validRecordFile(flushed);
225
+ if (flushed.dev !== after.dev || flushed.ino !== after.ino || JSON.stringify(captured.parents) !== JSON.stringify(finalParents.parents)) throw new Error("proposal: execution evidence changed while flushing; inspect the proposal store");
226
+ return evidence;
227
+ } finally { closeSync(fd); }
228
+ }
229
+ /** Record a writer-observed outcome under the owned registry lock, never from a caller. */
230
+ export function createStoredEvidence(home: string, evidence: ProposalExecutionEvidence, denyPaths: string[], registryFd: number): void {
231
+ const bytes = encodeProposalEvidence(evidence);
232
+ withStoreLock(home, false, root => {
233
+ const record = readStoredProposal(root, evidence.bindingDigest, evidence.id, denyPaths);
234
+ if (record.state !== "apply_unknown" || record.intent?.fingerprint !== evidence.fingerprint || record.intent.beforeSha !== evidence.beforeSha || record.intent.afterSha !== evidence.afterSha)
235
+ throw new Error("proposal: execution evidence does not match the recorded intent; inspect the proposal store");
236
+ const { dir, file } = evidenceFile(root, evidence.bindingDigest, evidence.id, evidence.fingerprint, denyPaths);
237
+ try { publishNew(root, dir, file, bytes, denyPaths); }
238
+ catch (error) {
239
+ const cause = error instanceof Error ? error.cause as NodeJS.ErrnoException | undefined : undefined;
240
+ if (cause?.code !== "EEXIST") throw error;
241
+ const existing = readStoredEvidence(root, evidence.bindingDigest, evidence.id, evidence.fingerprint, denyPaths);
242
+ if (!existing || JSON.stringify(existing) !== JSON.stringify(evidence)) throw error;
243
+ }
244
+ }, denyPaths, registryFd);
245
+ }
246
+ function reasonFile(home: string, binding: string, id: string, digest: string, denyPaths: string[]): { root: string; dir: string; file: string } {
247
+ if (!DIGEST.test(digest) || !ID.test(id)) throw new Error("proposal: invalid reason identifier; inspect the proposal");
248
+ const root = storeRoot(home, denyPaths), dir = directory(root, binding, false, denyPaths), file = join(dir, `${id}.${digest}.reason.json`);
249
+ requireAllowed(denyPaths, file);
250
+ return { root, dir, file };
251
+ }
252
+ export function readStoredReason(home: string, binding: string, id: string, digest: string, denyPaths: string[] = []): string {
253
+ const { root, file } = reasonFile(home, binding, id, digest, denyPaths), captured = capturePublicationPath(root, file);
254
+ let fd: number;
255
+ try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW); }
256
+ catch (error) { throw new Error("proposal: rejection reason record is missing, linked or unreadable; inspect the proposal store", { cause: error }); }
257
+ try {
258
+ const before = fstatSync(fd); validRecordFile(before);
259
+ const bytes = Buffer.alloc(MAX_PROPOSAL_RECORD_BYTES + 1); let length = 0, n = 0;
260
+ while (length < bytes.length && (n = readSync(fd, bytes, length, bytes.length - length, null)) > 0) length += n;
261
+ const after = fstatSync(fd), named = lstatSync(file), parents = capturePublicationPath(root, file);
262
+ validRecordFile(after); validRecordFile(named);
263
+ if (length > MAX_PROPOSAL_RECORD_BYTES || length !== after.size || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || after.dev !== named.dev || after.ino !== named.ino || JSON.stringify(captured.parents) !== JSON.stringify(parents.parents)) throw new Error("proposal: rejection reason changed while reading; inspect the proposal store");
264
+ const reason = decodeProposalReason(bytes.subarray(0, length));
265
+ if (reason.id !== id || reason.bindingDigest !== binding || reason.digest !== digest) throw new Error("proposal: rejection reason binding differs; inspect the proposal store");
266
+ if (!syncDirectory(dirname(file))) throw new Error("proposal: rejection reason cannot be durably verified on this platform; inspect the proposal store");
267
+ const flushed = lstatSync(file), finalParents = capturePublicationPath(root, file);
268
+ validRecordFile(flushed);
269
+ if (flushed.dev !== after.dev || flushed.ino !== after.ino || JSON.stringify(captured.parents) !== JSON.stringify(finalParents.parents)) throw new Error("proposal: rejection reason changed while flushing; inspect the proposal store");
270
+ return reason.reason;
271
+ } finally { closeSync(fd); }
272
+ }
273
+ /** Store the screened overflow reason before atomically replacing the proposal record. */
274
+ export function createStoredReason(home: string, reason: ProposalReason, recordDigest: string, denyPaths: string[], registryFd: number): void {
275
+ const bytes = encodeProposalReason(reason);
276
+ withStoreLock(home, false, root => {
277
+ const current = readStoredProposal(root, reason.bindingDigest, reason.id, denyPaths);
278
+ if (current.state !== "pending" || proposalRecordDigest(current) !== recordDigest) throw new Error("proposal: record changed before rejection; request a new preview");
279
+ const { dir, file } = reasonFile(root, reason.bindingDigest, reason.id, reason.digest, denyPaths);
280
+ try { publishNew(root, dir, file, bytes, denyPaths); }
281
+ catch (error) {
282
+ const cause = error instanceof Error ? error.cause as NodeJS.ErrnoException | undefined : undefined;
283
+ if (cause?.code !== "EEXIST" || readStoredReason(root, reason.bindingDigest, reason.id, reason.digest, denyPaths) !== reason.reason) throw error;
284
+ }
285
+ }, denyPaths, registryFd);
286
+ }
287
+ /** Publishes a new record atomically without overwriting any existing proposal. */
288
+ export function createStoredProposal(home: string, record: ProposalRecord, denyPaths: string[], registryFd: number): void {
289
+ const bytes = encodeProposalRecord(record);
290
+ withStoreLock(home, true, root => {
291
+ const found = checkStoredBinding(root, record.vault, record.bindingDigest, denyPaths);
292
+ const { file } = recordFile(root, record.bindingDigest, record.id, true, denyPaths), dir = directory(root, record.bindingDigest, false, denyPaths);
293
+ if (!found) publishNew(root, dir, join(dir, "binding.json"), Buffer.from(JSON.stringify({ schemaVersion: 1, vault: record.vault, bindingDigest: record.bindingDigest }), "utf8"), denyPaths);
294
+ publishNew(root, dir, file, bytes, denyPaths);
295
+ }, denyPaths, registryFd);
296
+ }
297
+
298
+ /** Compare-and-replace a record while retaining the proposal payload and vault identity. */
299
+ export function replaceStoredProposal(home: string, binding: string, id: string, expectedDigest: string, next: ProposalRecord, denyPaths: string[], registryFd: number): void {
300
+ if (!DIGEST.test(expectedDigest)) throw new Error("proposal: invalid record fingerprint; request a new preview");
301
+ const bytes = encodeProposalRecord(next);
302
+ let published = false;
303
+ try { withStoreLock(home, false, root => {
304
+ const { file } = recordFile(root, binding, id, false, denyPaths), dir = directory(root, binding, false, denyPaths);
305
+ const sourceFd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
306
+ try {
307
+ const before = fstatSync(sourceFd); validRecordFile(before);
308
+ const current = readStoredProposal(root, binding, id, denyPaths);
309
+ if (proposalRecordDigest(current) !== expectedDigest) throw new Error("proposal: record changed since preview; request a new preview");
310
+ if (current.id !== next.id || current.vault !== next.vault || current.bindingDigest !== next.bindingDigest || current.createdAt !== next.createdAt || current.payloadDigest !== next.payloadDigest || current.agentLabel !== next.agentLabel)
311
+ throw new Error("proposal: decision cannot change immutable record fields; request a new preview");
312
+ if (!checkStoredBinding(root, current.vault, binding, denyPaths)) throw new Error("proposal: vault binding is missing; inspect the proposal store");
313
+ const path = capturePublicationPath(root, file), temporary = join(dir, `.proposal-${randomUUID()}.tmp`);
314
+ requireAllowed(denyPaths, temporary);
315
+ const tempFd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
316
+ try {
317
+ writeFileSync(tempFd, bytes); fsyncSync(tempFd);
318
+ const named = lstatSync(file), held = fstatSync(sourceFd); validRecordFile(named); validRecordFile(held);
319
+ if (before.dev !== held.dev || before.ino !== held.ino || before.size !== held.size || before.mtimeMs !== held.mtimeMs || before.ctimeMs !== held.ctimeMs || named.dev !== held.dev || named.ino !== held.ino)
320
+ throw new Error("proposal: record changed during decision; request a new preview");
321
+ publishFile(path, { kind: "rename", temp: temporary }, () => { published = true; });
322
+ syncDirectory(dir);
323
+ } catch (error) {
324
+ if (published) throw new Error("proposal: record update was published but durability or path verification failed; inspect the proposal store before retrying", { cause: error });
325
+ throw error;
326
+ } finally {
327
+ try { if (!published) cleanupOwnedFile(temporary, tempFd); } finally { closeSync(tempFd); }
328
+ }
329
+ } finally { closeSync(sourceFd); }
330
+ }, denyPaths, registryFd); } catch (error) {
331
+ if (published) throw new Error("proposal: record update was published but finalization failed; inspect the proposal store before retrying", { cause: error });
332
+ throw error;
333
+ }
334
+ }
@@ -0,0 +1,170 @@
1
+ /** Proposal payload and durable record contracts. */
2
+ import { createHash } from "node:crypto";
3
+ import { notePath } from "./write-operations.ts";
4
+ import type { PatchEdit, WriteOp } from "./write-types.ts";
5
+
6
+ export const MAX_PROPOSAL_RECORD_BYTES = 32 * 1024;
7
+ export const MAX_PROPOSAL_RPC_BYTES = 48 * 1024;
8
+ export const MAX_PROPOSAL_EDITS = 32;
9
+ export type ProposalOperation = Extract<WriteOp, { op: "create" | "patch" }>;
10
+
11
+ function object(value: unknown): value is Record<string, unknown> {
12
+ return value !== null && typeof value === "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
13
+ }
14
+ function exactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
15
+ return Object.keys(value).every(key => keys.includes(key));
16
+ }
17
+ function jsonBytes(value: unknown): number {
18
+ let text: string | undefined;
19
+ try { text = JSON.stringify(value); } catch { throw new Error("proposal: input is not JSON serializable"); }
20
+ if (text === undefined) throw new Error("proposal: input is not JSON serializable");
21
+ return Buffer.byteLength(text, "utf8");
22
+ }
23
+ /** Measures the complete JSON-RPC frame, including escaping, envelope, and its terminating newline. */
24
+ export function proposalRpcBytes(request: unknown): number { return jsonBytes(request) + 1; }
25
+ export function checkProposalRpcSize(request: unknown): void {
26
+ if (proposalRpcBytes(request) > MAX_PROPOSAL_RPC_BYTES) throw new Error("proposal: encoded JSON-RPC request exceeds 48 KiB; shorten the proposal");
27
+ }
28
+ /** Only create and exact-replacement patch operations are admissible, with one canonical flat note target. */
29
+ export function parseProposalOperation(value: unknown): ProposalOperation {
30
+ if (!object(value) || typeof value.path !== "string") throw new Error("proposal: expected one create or patch operation and note target");
31
+ if (jsonBytes(value) > MAX_PROPOSAL_RECORD_BYTES) throw new Error("proposal: operation exceeds the 32 KiB record limit; shorten the payload");
32
+ const path = notePath(value.path);
33
+ if (value.op === "create") {
34
+ if (!exactKeys(value, ["op", "path", "frontmatter", "body"]) || !object(value.frontmatter) || (value.body !== undefined && typeof value.body !== "string"))
35
+ throw new Error("proposal: create requires frontmatter and an optional text body; remove unsupported fields");
36
+ return { op: "create", path, frontmatter: value.frontmatter, ...(typeof value.body === "string" ? { body: value.body } : {}) };
37
+ }
38
+ if (value.op === "patch") {
39
+ if (!exactKeys(value, ["op", "path", "edits", "expectedSha"]) || typeof value.expectedSha !== "string" || !/^[a-f0-9]{64}$/.test(value.expectedSha) || !Array.isArray(value.edits) || value.edits.length < 1 || value.edits.length > MAX_PROPOSAL_EDITS)
40
+ throw new Error("proposal: patch requires a base SHA and 1..32 exact edits; correct the patch");
41
+ const edits: PatchEdit[] = value.edits.map(edit => {
42
+ if (!object(edit) || !exactKeys(edit, ["oldString", "newString"]) || typeof edit.oldString !== "string" || !edit.oldString || typeof edit.newString !== "string")
43
+ throw new Error("proposal: each edit needs nonempty oldString and a text newString; correct the patch");
44
+ return { oldString: edit.oldString, newString: edit.newString };
45
+ });
46
+ return { op: "patch", path, edits, expectedSha: value.expectedSha };
47
+ }
48
+ throw new Error("proposal: unsupported operation; choose create or patch");
49
+ }
50
+
51
+ /** Durable record schema: version 1 is local state, not an index or a note. */
52
+ export interface ProposalRecord {
53
+ schemaVersion: 1;
54
+ id: string;
55
+ vault: string;
56
+ bindingDigest: string;
57
+ state: "pending" | "applied" | "rejected" | "apply_unknown";
58
+ createdAt: string;
59
+ updatedAt: string;
60
+ operation: ProposalOperation;
61
+ payloadDigest: string;
62
+ agentLabel?: string;
63
+ decisionReason?: string;
64
+ decisionReasonRef?: string;
65
+ intent?: { fingerprint: string; beforeSha: string | null; afterSha: string | null };
66
+ receipt?: { applied: true; logged: boolean | null; beforeSha: string | null; afterSha: string | null };
67
+ }
68
+ /** Written by the locked writer after an apply attempt; it is never accepted from a caller. */
69
+ export interface ProposalExecutionEvidence {
70
+ schemaVersion: 1; id: string; bindingDigest: string; fingerprint: string;
71
+ beforeSha: string | null; afterSha: string | null; applied: boolean; publicationStarted: boolean; logged: boolean | null;
72
+ }
73
+ export interface ProposalReason { schemaVersion: 1; id: string; bindingDigest: string; digest: string; reason: string }
74
+
75
+ /** A digest of the exact normalized operation, never a claim about who authored it. */
76
+ export function proposalPayloadDigest(operation: ProposalOperation): string {
77
+ return createHash("sha256").update(JSON.stringify(operation), "utf8").digest("hex");
78
+ }
79
+ const digest = (value: unknown): value is string => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
80
+ const date = (value: unknown): value is string => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
81
+ /** Parse bounded bytes and reject unknown fields, malformed states and payload drift. */
82
+ export function decodeProposalRecord(bytes: Uint8Array): ProposalRecord {
83
+ if (bytes.byteLength > MAX_PROPOSAL_RECORD_BYTES) throw new Error("proposal: stored record exceeds 32 KiB; inspect the proposal store");
84
+ const text = Buffer.from(bytes).toString("utf8");
85
+ if (!Buffer.from(text, "utf8").equals(Buffer.from(bytes))) throw new Error("proposal: stored record is not UTF-8; inspect the proposal store");
86
+ let parsed: unknown;
87
+ try { parsed = JSON.parse(text); } catch { throw new Error("proposal: stored record is not JSON; inspect the proposal store"); }
88
+ if (JSON.stringify(parsed) !== text) throw new Error("proposal: stored record is not in canonical JSON form; inspect the proposal store");
89
+ if (!object(parsed) || !exactKeys(parsed, ["schemaVersion", "id", "vault", "bindingDigest", "state", "createdAt", "updatedAt", "operation", "payloadDigest", "agentLabel", "decisionReason", "decisionReasonRef", "intent", "receipt"]) || parsed.schemaVersion !== 1 || typeof parsed.id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(parsed.id) || typeof parsed.vault !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(parsed.vault) || !digest(parsed.bindingDigest) || !["pending", "applied", "rejected", "apply_unknown"].includes(String(parsed.state)) || !date(parsed.createdAt) || !date(parsed.updatedAt) || !digest(parsed.payloadDigest))
90
+ throw new Error("proposal: stored record has invalid metadata; inspect the proposal store");
91
+ if ((parsed.agentLabel !== undefined && (typeof parsed.agentLabel !== "string" || Buffer.byteLength(parsed.agentLabel) > 256)) || (parsed.decisionReason !== undefined && (typeof parsed.decisionReason !== "string" || !parsed.decisionReason.isWellFormed() || Buffer.byteLength(parsed.decisionReason) > 4096)))
92
+ throw new Error("proposal: stored record has invalid optional fields; inspect the proposal store");
93
+ if (parsed.decisionReasonRef !== undefined && !digest(parsed.decisionReasonRef)) throw new Error("proposal: stored reason reference is invalid; inspect the proposal store");
94
+ if (parsed.intent !== undefined && (!object(parsed.intent) || !exactKeys(parsed.intent, ["fingerprint", "beforeSha", "afterSha"]) || !digest(parsed.intent.fingerprint) || (parsed.intent.beforeSha !== null && !digest(parsed.intent.beforeSha)) || (parsed.intent.afterSha !== null && !digest(parsed.intent.afterSha))))
95
+ throw new Error("proposal: stored record has invalid apply intent; inspect the proposal store");
96
+ if (parsed.state === "apply_unknown" && parsed.intent === undefined) throw new Error("proposal: uncertain apply has no recorded intent; inspect the proposal store");
97
+ if (parsed.state === "applied" && parsed.intent === undefined) throw new Error("proposal: applied record has no recorded intent; inspect the proposal store");
98
+ if (parsed.receipt !== undefined && (!object(parsed.receipt) || !exactKeys(parsed.receipt, ["applied", "logged", "beforeSha", "afterSha"]) || parsed.receipt.applied !== true || (typeof parsed.receipt.logged !== "boolean" && parsed.receipt.logged !== null) || (parsed.receipt.beforeSha !== null && !digest(parsed.receipt.beforeSha)) || (parsed.receipt.afterSha !== null && !digest(parsed.receipt.afterSha))))
99
+ throw new Error("proposal: stored receipt is invalid; inspect the proposal store");
100
+ if (parsed.state === "applied" && parsed.receipt === undefined) throw new Error("proposal: applied record has no durable receipt; inspect the proposal store");
101
+ if (parsed.receipt !== undefined && (!object(parsed.receipt) || parsed.state !== "applied" || !object(parsed.intent) || parsed.receipt.beforeSha !== parsed.intent.beforeSha || parsed.receipt.afterSha !== parsed.intent.afterSha))
102
+ throw new Error("proposal: stored receipt does not match its apply intent; inspect the proposal store");
103
+ if (parsed.state === "pending" && parsed.intent !== undefined) throw new Error("proposal: pending record has an apply intent; inspect the proposal store");
104
+ if (parsed.state === "rejected" && ((typeof parsed.decisionReason !== "string" || !parsed.decisionReason.trim()) === (parsed.decisionReasonRef === undefined))) throw new Error("proposal: rejected record must have exactly one reason or reason reference; inspect the proposal store");
105
+ if (parsed.state !== "rejected" && (parsed.decisionReason !== undefined || parsed.decisionReasonRef !== undefined)) throw new Error("proposal: non-rejected record has a rejection reason; inspect the proposal store");
106
+ const operation = parseProposalOperation(parsed.operation);
107
+ if (proposalPayloadDigest(operation) !== parsed.payloadDigest) throw new Error("proposal: stored payload digest differs; inspect the proposal store");
108
+ return { ...parsed, operation } as unknown as ProposalRecord;
109
+ }
110
+ export function encodeProposalRecord(record: ProposalRecord): Uint8Array {
111
+ const bytes = Buffer.from(JSON.stringify(record), "utf8");
112
+ decodeProposalRecord(bytes);
113
+ return bytes;
114
+ }
115
+ /** Digest the complete canonical record so decisions can bind both payload and state. */
116
+ export function proposalRecordDigest(record: ProposalRecord): string {
117
+ return createHash("sha256").update(encodeProposalRecord(record)).digest("hex");
118
+ }
119
+ export function encodeProposalEvidence(value: ProposalExecutionEvidence): Uint8Array {
120
+ const bytes = Buffer.from(JSON.stringify(value), "utf8");
121
+ decodeProposalEvidence(bytes);
122
+ return bytes;
123
+ }
124
+ export function decodeProposalEvidence(bytes: Uint8Array): ProposalExecutionEvidence {
125
+ if (bytes.byteLength > 4096) throw new Error("proposal: execution evidence exceeds its bound; inspect the proposal store");
126
+ const text = Buffer.from(bytes).toString("utf8");
127
+ if (!Buffer.from(text, "utf8").equals(Buffer.from(bytes))) throw new Error("proposal: execution evidence is not UTF-8; inspect the proposal store");
128
+ let value: unknown;
129
+ try { value = JSON.parse(text); } catch { throw new Error("proposal: execution evidence is not JSON; inspect the proposal store"); }
130
+ if (!object(value) || JSON.stringify(value) !== text || !exactKeys(value, ["schemaVersion", "id", "bindingDigest", "fingerprint", "beforeSha", "afterSha", "applied", "publicationStarted", "logged"]) || value.schemaVersion !== 1 || typeof value.id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.id) || !digest(value.bindingDigest) || !digest(value.fingerprint) || (value.beforeSha !== null && !digest(value.beforeSha)) || (value.afterSha !== null && !digest(value.afterSha)) || typeof value.applied !== "boolean" || typeof value.publicationStarted !== "boolean" || (value.logged !== null && typeof value.logged !== "boolean") || (value.applied && !value.publicationStarted))
131
+ throw new Error("proposal: execution evidence has invalid fields; inspect the proposal store");
132
+ return value as unknown as ProposalExecutionEvidence;
133
+ }
134
+ export function proposalEvidenceDigest(value: ProposalExecutionEvidence): string { return createHash("sha256").update(encodeProposalEvidence(value)).digest("hex"); }
135
+ export function proposalReasonDigest(reason: string): string { return createHash("sha256").update(reason, "utf8").digest("hex"); }
136
+ export function encodeProposalReason(value: ProposalReason): Uint8Array {
137
+ const bytes = Buffer.from(JSON.stringify(value), "utf8"); decodeProposalReason(bytes); return bytes;
138
+ }
139
+ export function decodeProposalReason(bytes: Uint8Array): ProposalReason {
140
+ if (bytes.byteLength > MAX_PROPOSAL_RECORD_BYTES) throw new Error("proposal: rejection reason record exceeds its bound; inspect the proposal store");
141
+ const text = Buffer.from(bytes).toString("utf8");
142
+ if (!Buffer.from(text, "utf8").equals(Buffer.from(bytes))) throw new Error("proposal: rejection reason record is not UTF-8; inspect the proposal store");
143
+ let value: unknown;
144
+ try { value = JSON.parse(text); } catch { throw new Error("proposal: rejection reason record is not JSON; inspect the proposal store"); }
145
+ if (!object(value) || JSON.stringify(value) !== text || !exactKeys(value, ["schemaVersion", "id", "bindingDigest", "digest", "reason"]) || value.schemaVersion !== 1 || typeof value.id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.id) || !digest(value.bindingDigest) || !digest(value.digest) || typeof value.reason !== "string" || !value.reason.trim() || !value.reason.isWellFormed() || Buffer.byteLength(value.reason, "utf8") > 4096 || proposalReasonDigest(value.reason) !== value.digest)
146
+ throw new Error("proposal: rejection reason record is invalid; inspect the proposal store");
147
+ return value as unknown as ProposalReason;
148
+ }
149
+ /** Keep a near-limit proposal rejectable without making its primary record exceed 32 KiB. */
150
+ export function prepareRejectedProposal(record: ProposalRecord, reason: string, updatedAt: string): { record: ProposalRecord; reasonRecord?: ProposalReason } {
151
+ if (!reason.trim() || !reason.isWellFormed() || Buffer.byteLength(reason, "utf8") > 4096) throw new Error("proposal: rejection requires a well-formed nonempty reason of at most 4096 bytes; provide a reason and preview again");
152
+ const inline: ProposalRecord = { ...record, state: "rejected", updatedAt, decisionReason: reason };
153
+ if (Buffer.byteLength(JSON.stringify(inline), "utf8") <= MAX_PROPOSAL_RECORD_BYTES) { encodeProposalRecord(inline); return { record: inline }; }
154
+ const ref = proposalReasonDigest(reason), compact: ProposalRecord = { ...record, state: "rejected", updatedAt, decisionReasonRef: ref };
155
+ const reasonRecord: ProposalReason = { schemaVersion: 1, id: record.id, bindingDigest: record.bindingDigest, digest: ref, reason };
156
+ encodeProposalRecord(compact); encodeProposalReason(reasonRecord);
157
+ return { record: compact, reasonRecord };
158
+ }
159
+ export function proposalReconcileFingerprint(recordDigest: string, evidenceDigest: string, plan: string, state: "pending" | "applied"): string {
160
+ if (!digest(recordDigest) || !digest(evidenceDigest) || !digest(plan) || (state !== "pending" && state !== "applied")) throw new Error("proposal: invalid reconciliation inputs; request a new preview");
161
+ return createHash("sha256").update(JSON.stringify(["vmem-proposal-reconcile", 1, recordDigest, evidenceDigest, plan, state]), "utf8").digest("hex");
162
+ }
163
+ /** Bind the exact prior record and writer plan, including the rejection reason when present. */
164
+ export function proposalDecisionFingerprint(recordDigest: string, writerFingerprint: string, decision: "apply" | "reject", reason?: string): string {
165
+ if (!digest(recordDigest) || !digest(writerFingerprint) || (decision !== "apply" && decision !== "reject")) throw new Error("proposal: invalid decision inputs; request a new preview");
166
+ if (decision === "reject" && (typeof reason !== "string" || !reason.trim() || Buffer.byteLength(reason, "utf8") > 4096))
167
+ throw new Error("proposal: rejection needs a nonempty reason of at most 4096 bytes; provide a reason and preview again");
168
+ if (decision === "apply" && reason !== undefined) throw new Error("proposal: an apply decision cannot carry a rejection reason; request a new preview");
169
+ return createHash("sha256").update(JSON.stringify(["vmem-proposal-decision", 1, decision, recordDigest, writerFingerprint, reason ?? null]), "utf8").digest("hex");
170
+ }
@@ -1,37 +1,69 @@
1
1
  import { loadRegistry } from "./registry.ts";
2
2
  import { VaultIndex, MAX_NOTE_BYTES } from "./vault-index.ts";
3
- import { PLAIN, type TextOptions } from "./text-output.ts";
3
+ import { PLAIN, UsageError, type TextOptions } from "./text-output.ts";
4
4
  import { linksText, rebuildText, searchText, showText } from "./read-output.ts";
5
+ import { CHANGES_PAGE_LIMIT, HISTORY_PAGE_LIMIT, changesText, historyText, readChanges, readHistory, readRevision, revisionText } from "./vault-history.ts";
5
6
  import type { NoteReadResult, SearchResult } from "./vault-index.ts";
6
- const READ_COMMANDS = new Set(["rebuild", "search", "show", "links"]);
7
+ import { evidenceReport } from "./evidence.ts";
8
+ import { evidenceText } from "./read-output.ts";
9
+ const READ_COMMANDS = new Set(["rebuild", "search", "show", "links", "evidence", "history", "changes"]);
7
10
  export function isReadCommand(command: string): boolean { return READ_COMMANDS.has(command); }
8
11
  export function runReadCommand(command: string, args: string[], home: string, text: TextOptions = PLAIN): { text: string; code: number } {
9
12
  const options: Record<string, string | boolean> = {}, positional: string[] = [];
10
- const allowed = command === "search" ? ["--limit", "--type", "--domain"] : command === "show" ? ["--max-bytes", "--section", "--offset"] : command === "links" ? ["--limit"] : [];
13
+ const allowed = command === "search" ? ["--limit", "--type", "--domain"] : command === "show" ? ["--max-bytes", "--section", "--offset", "--revision"]
14
+ : command === "links" ? ["--limit"] : command === "history" ? ["--limit", "--cursor"] : command === "changes" ? ["--from", "--to", "--limit", "--cursor"] : [];
11
15
  for (let i = 0; i < args.length; i++) {
12
16
  const arg = args[i]!;
13
17
  if (!arg.startsWith("-")) { positional.push(arg); continue; }
14
- if (Object.hasOwn(options, arg) || (arg !== "--json" && !allowed.includes(arg))) throw new Error(`${command}: unknown or repeated option ${arg}`);
18
+ if (Object.hasOwn(options, arg) || (arg !== "--json" && !allowed.includes(arg))) throw new UsageError(`${command}: unknown or repeated option ${arg}`);
15
19
  if (arg === "--json") { options[arg] = true; continue; }
16
20
  const value = args[++i];
17
- if (!value || value.startsWith("--")) throw new Error(`${arg}: value required`);
21
+ if (!value || value.startsWith("--")) throw new UsageError(`${arg}: value required`);
18
22
  options[arg] = value;
19
23
  }
20
- if (positional.length !== (command === "rebuild" ? 1 : 2)) throw new Error(`${command}: requires vault id${command === "rebuild" ? "" : " and query/target"}`);
24
+ const expected = command === "rebuild" || command === "changes" ? 1 : 2;
25
+ if (positional.length !== expected) throw new UsageError(`${command}: requires vault id${command === "rebuild" ? "" : command === "changes" ? " and --from/--to" : " and query/target"}`);
21
26
  const registry = loadRegistry(home), vault = registry.vaults.find(v => v.id === positional[0]);
22
27
  if (!vault) throw new Error(`${command}: unknown vault id`);
28
+ // Evidence reads the note and its sources directly: no index cache, lock or write.
29
+ if (command === "evidence") {
30
+ const report = evidenceReport(vault, positional[1]!, registry.denyPaths ?? []);
31
+ return { text: options["--json"] ? JSON.stringify(report) : evidenceText(report, text), code: 0 };
32
+ }
23
33
  const number = (name: string): number | undefined => {
24
34
  if (options[name] === undefined) return undefined;
25
- if (!/^[0-9]+$/.test(String(options[name]))) throw new Error(`${name}: expected integer`);
35
+ if (!/^[0-9]+$/.test(String(options[name]))) throw new UsageError(`${name}: expected integer`);
26
36
  return Number(options[name]);
27
37
  };
28
38
  const limit = number("--limit"), maxBytes = number("--max-bytes"), offset = number("--offset");
29
39
  // Validate bounds before opening or updating a derived cache.
30
- if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)) throw new Error("limit: expected integer 1..500");
31
- if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 65536)) throw new Error("max-bytes: expected integer 1..65536");
32
- if (offset !== undefined && (!Number.isSafeInteger(offset) || offset < 0 || offset > MAX_NOTE_BYTES)) throw new Error(`offset: expected integer 0..${MAX_NOTE_BYTES}`);
40
+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)) throw new UsageError("limit: expected integer 1..500");
41
+ if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 65536)) throw new UsageError("max-bytes: expected integer 1..65536");
42
+ if (offset !== undefined && (!Number.isSafeInteger(offset) || offset < 0 || offset > MAX_NOTE_BYTES)) throw new UsageError(`offset: expected integer 0..${MAX_NOTE_BYTES}`);
33
43
  const section = options["--section"] as string | undefined;
34
- if (section !== undefined && (!section.trim() || /[\r\n]/.test(section) || Buffer.byteLength(section) > 1024)) throw new Error("section: expected one exact H2 heading <=1024 bytes");
44
+ if (section !== undefined && (!section.trim() || /[\r\n]/.test(section) || Buffer.byteLength(section) > 1024)) throw new UsageError("section: expected one exact H2 heading <=1024 bytes");
45
+ const cursor = options["--cursor"] as string | undefined, revision = options["--revision"] as string | undefined;
46
+ const denyPaths = registry.denyPaths ?? [];
47
+ if (command === "history") {
48
+ if (limit !== undefined && limit > HISTORY_PAGE_LIMIT) throw new UsageError(`limit: expected integer 1..${HISTORY_PAGE_LIMIT} for history`);
49
+ const result = readHistory({ vault, home, denyPaths, note: positional[1]!, ...(limit !== undefined ? { limit } : {}), ...(cursor !== undefined ? { cursor } : {}) });
50
+ if (options["--json"]) return { text: JSON.stringify(result), code: 0 };
51
+ return { text: historyText(result, text, { vault: vault.id, note: positional[1]!, ...(limit !== undefined ? { limit } : {}), ...(cursor !== undefined ? { cursor } : {}) }), code: 0 };
52
+ }
53
+ if (command === "changes") {
54
+ const from = options["--from"], to = options["--to"];
55
+ if (typeof from !== "string" || typeof to !== "string") throw new UsageError("changes: requires one vault id plus --from and --to, e.g. vmem changes demo --from <oid> --to <oid>");
56
+ if (limit !== undefined && limit > CHANGES_PAGE_LIMIT) throw new UsageError(`limit: expected integer 1..${CHANGES_PAGE_LIMIT} for changes`);
57
+ const result = readChanges({ vault, home, denyPaths, from, to, ...(limit !== undefined ? { limit } : {}), ...(cursor !== undefined ? { cursor } : {}) });
58
+ if (options["--json"]) return { text: JSON.stringify(result), code: 0 };
59
+ return { text: changesText(result, text, { vault: vault.id, from, to, ...(limit !== undefined ? { limit } : {}) }), code: 0 };
60
+ }
61
+ if (command === "show" && revision !== undefined) {
62
+ const result = readRevision({ vault, home, denyPaths, note: positional[1]!, revision,
63
+ ...(maxBytes !== undefined ? { maxBytes } : {}), ...(offset !== undefined ? { offset } : {}), ...(section !== undefined ? { section } : {}) });
64
+ if (options["--json"]) return { text: JSON.stringify(result), code: 0 };
65
+ return { text: revisionText(result, text, { vault: vault.id, note: positional[1]!, revision, ...(maxBytes !== undefined ? { maxBytes } : {}) }), code: 0 };
66
+ }
35
67
  const index = new VaultIndex(home, vault, registry.vaults.map(v => v.path));
36
68
  let result: unknown;
37
69
  try {
@@ -40,7 +72,7 @@ export function runReadCommand(command: string, args: string[], home: string, te
40
72
  else if (command === "search") result = index.search(positional[1]!, { limit, type: options["--type"] as string | undefined, domain: options["--domain"] as string | undefined });
41
73
  else if (command === "show") result = index.show(positional[1]!, maxBytes, section, offset);
42
74
  else if (command === "links") result = index.links(positional[1]!, limit);
43
- else throw new Error("unknown read command");
75
+ else throw new UsageError("unknown read command");
44
76
  } finally { index.close(); }
45
77
  if (options["--json"]) return { text: JSON.stringify(result), code: 0 };
46
78
  const vaultId = vault.id, target = positional[1]!;