@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
package/src/writer.ts CHANGED
@@ -8,21 +8,36 @@ import { createHash, randomUUID } from "node:crypto";
8
8
  import { dirname, join } from "node:path";
9
9
  import { hostname } from "node:os";
10
10
  import { Database } from "bun:sqlite";
11
- import { loadRegistry, syncDirectory } from "./registry.ts";
11
+ import { loadRegistry, LOCK_FILE, syncDirectory } from "./registry.ts";
12
12
  import { VaultIndex, MAX_NOTE_BYTES, GRAMS_COLUMNS, gramPhrase, grams, splitTerms } from "./vault-index.ts";
13
13
  import { parseFrontmatter } from "./frontmatter.ts";
14
14
  import { canonicalPath, isDenied } from "./platform.ts";
15
15
  import { moveSourcePath, notePath, planOperation, planMerge, stampContentChanges, refuse, WriteRefusal } from "./write-operations.ts";
16
- import { MAX_REPORT_BYTES, createWriteValidator } from "./write-validation.ts";
16
+ import { MAX_REPORT_BYTES, createWriteValidator, screenMetadata } from "./write-validation.ts";
17
17
  import type { PiiSurface } from "./config.ts";
18
18
  import { unenforceablePii, mutationVault } from "./config.ts";
19
19
  import type { LogBinding } from "./log-types.ts";
20
20
  import type { MergePreview, ChangeReceipt, PlannedChange, WriteIssue, WriteReceipt, WriteRequest } from "./write-types.ts";
21
+ import { createStoredEvidence, createStoredReason, readStoredEvidence, readStoredProposal, replaceStoredProposal } from "./proposal-storage.ts";
22
+ import { prepareRejectedProposal, proposalDecisionFingerprint, proposalEvidenceDigest, proposalReconcileFingerprint, proposalRecordDigest, type ProposalRecord } from "./proposals.ts";
23
+ import { readJournal, relinkSubjects, subjectsAtNote } from "./assertions.ts";
21
24
  export const MUTATION_LOCK = "mutation.lock";
22
25
  export { MAX_WRITE_BYTES } from "./write-types.ts";
23
26
  const MAX_MERGE_ACK_BYTES = 224 * 1024;
27
+ /** Preserve publication state when a post-publication relink list outgrows the MCP result budget. */
28
+ export function boundMcpWriteReceipt(receipt: WriteReceipt): WriteReceipt {
29
+ if (!receipt.applied || !receipt.assertions || Buffer.byteLength(JSON.stringify(receipt)) <= MAX_MERGE_ACK_BYTES) return receipt;
30
+ const count = receipt.assertions.relinked.length;
31
+ const reduced: WriteReceipt = { ...receipt, assertions: { ...receipt.assertions, relinked: [], relinkedCount: count, omitted: count } };
32
+ if (Buffer.byteLength(JSON.stringify(reduced)) <= MAX_MERGE_ACK_BYTES) return reduced;
33
+ return { ok: receipt.ok, applied: true, indexUpdated: receipt.indexUpdated, changes: [],
34
+ issues: [{ code: "LIMIT", severity: "warning", message: "the applied receipt was too large; change details and diagnostics were omitted. Inspect the vault and assertion journal before retrying" }],
35
+ ...(receipt.logged !== undefined ? { logged: receipt.logged } : {}),
36
+ assertions: { relinked: [], relinkedCount: count, omitted: count, ...(receipt.assertions.issue ? { issue: { code: "ASSERTIONS", severity: "warning", message: receipt.assertions.issue.message.slice(0, 16384) } } : {}) } };
37
+ }
24
38
  export function sha256(text: string): string { return createHash("sha256").update(text).digest("hex"); }
25
- function canonical(value: unknown): string {
39
+ /** Canonical JSON: sorted keys, undefined members dropped. The assertion journal hashes and stores this form. */
40
+ export function canonical(value: unknown): string {
26
41
  if (value === undefined) return "null";
27
42
  if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
28
43
  if (value && typeof value === "object") return `{${Object.entries(value).filter(([, item]) => item !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
@@ -67,6 +82,27 @@ function readPlain(root: string, path: string, maximum = MAX_NOTE_BYTES): string
67
82
  return text;
68
83
  } finally { closeSync(fd); }
69
84
  }
85
+ /** Read one approved note for proposal reconciliation without opening the index or taking a write lock. */
86
+ function readProposalTarget(home: string, vaultId: string, target: string, binding: LogBinding): string | null {
87
+ const config = loadRegistry(home), vault = config.vaults.find(item => item.id === vaultId);
88
+ if (!vault || !matchesBinding(config, vaultId, binding)) throw new Error("proposal: vault binding or policy changed; inspect the registered vault before reconciliation");
89
+ const path = notePath(target), root = realpathSync(vault.path);
90
+ if (root !== vault.path || isDenied(root, config.denyPaths ?? []) || isDenied(join(root, path), config.denyPaths ?? []))
91
+ throw new Error("proposal: reconciliation target is denied or changed; inspect the vault policy and path");
92
+ const text = readPlain(root, path);
93
+ if (!matchesBinding(loadRegistry(home), vaultId, binding)) throw new Error("proposal: vault binding or policy changed during reconciliation; retry with the current policy");
94
+ return text;
95
+ }
96
+ export function proposalTargetDigest(home: string, vaultId: string, target: string, binding: LogBinding): string | null {
97
+ const text = readProposalTarget(home, vaultId, target, binding);
98
+ return text === null ? null : sha256(text);
99
+ }
100
+ /** Read only a bound target's frontmatter for evidence validation; no index is opened. */
101
+ export function proposalTargetFrontmatter(home: string, vaultId: string, target: string, binding: LogBinding): Record<string, unknown> {
102
+ const text = readProposalTarget(home, vaultId, target, binding);
103
+ if (text === null) throw new Error("proposal: patch target is missing; inspect the note and submit a new proposal");
104
+ try { return parseFrontmatter(text).data; } catch { throw new Error("proposal: patch target frontmatter is invalid; repair the note before retrying"); }
105
+ }
70
106
  /** Flat `notes/*.md` snapshot used by every mutation (other directories such as templates/ and self/ are never read). */
71
107
  export function snapshot(root: string, denyPaths: string[] = []): Map<string, string> {
72
108
  const dir = join(root, "notes");
@@ -83,6 +119,20 @@ export function snapshot(root: string, denyPaths: string[] = []): Map<string, st
83
119
  }
84
120
  return notes;
85
121
  }
122
+ /** Bind rejection to the current vault identity, policy and target without reading denied paths. */
123
+ export function proposalRejectionPlan(home: string, vaultId: string, channel: "cli" | "mcp", binding: LogBinding, target: string): string {
124
+ const config = loadRegistry(home), vault = config.vaults.find(item => item.id === vaultId);
125
+ if (!vault || !matchesBinding(config, vaultId, binding)) throw new Error("proposal: vault binding or policy changed; request a new rejection preview");
126
+ if (vault.write === "none" || (channel === "mcp" && vault.write !== "mcp")) throw new Error("proposal: vault write policy refuses this channel; choose an authorized vault or channel");
127
+ if (unenforceablePii(vault)) throw new Error("proposal: vault PII policy cannot be enforced; inspect the vault policy");
128
+ const root = realpathSync(vault.path), homePath = canonicalPath(home);
129
+ if (root !== vault.path || isDenied(root, config.denyPaths ?? []) || config.vaults.some(item => homePath === item.path || homePath.startsWith(`${item.path}/`)))
130
+ throw new Error("proposal: vault root or configured home is denied or unsafe; inspect the vault registration and home");
131
+ const path = notePath(target), denied = isDenied(join(root, path), config.denyPaths ?? []);
132
+ const text = denied ? null : readPlain(root, path);
133
+ if (!matchesBinding(loadRegistry(home), vaultId, binding)) throw new Error("proposal: vault binding or policy changed during review; request a new rejection preview");
134
+ return sha256(canonical({ action: "reject", vault: mutationVault(vault), policy: { denyPaths: config.denyPaths ?? [], piiPatterns: config.piiPatterns ?? [] }, root, identity: [binding.dev, binding.ino], target: path, targetState: denied ? "denied" : text === null ? "missing" : sha256(text) }));
135
+ }
86
136
  function receipts(changes: PlannedChange[]): ChangeReceipt[] {
87
137
  return changes.map(change => ({ path: change.path, beforeSha: change.before === null ? null : sha256(change.before), sha256: change.after === null ? null : sha256(change.after), bytes: Buffer.byteLength(change.after ?? "") }));
88
138
  }
@@ -143,10 +193,135 @@ function duplicateWarnings(request: WriteRequest, notes: Map<string, string>, ch
143
193
  return hits.filter(hit => hit.score <= -0.000001).map(hit => ({ code: "V08", severity: "warning", path: hit.path, message: "possible duplicate: FTS title terms match an existing note" }));
144
194
  } finally { db.close(); }
145
195
  }
196
+ interface WriteOptions { env?: NodeJS.ProcessEnv; piiSurface?: PiiSurface; binding?: LogBinding; now?: Date }
197
+ /** Internal approval binding; public CLI/MCP callers never supply store paths. */
198
+ export interface ProposalWriteDecision { id: string; bindingDigest: string; recordDigest: string; fingerprint: string }
199
+ export interface ProposalRejectDecision extends ProposalWriteDecision { reason: string }
200
+ export interface ProposalRejectReceipt { ok: boolean; rejected: boolean; issues: WriteIssue[] }
201
+ export interface ProposalWriteReceipt extends WriteReceipt { proposalState: "pending" | "apply_unknown" | "applied"; proposalPublicationStarted: boolean }
202
+ export interface ProposalReconcileReceipt { ok: boolean; resolved: boolean; state: "pending" | "applied" | "apply_unknown"; issues: WriteIssue[] }
146
203
  /** Single mutation entry point. Preview/dry-run perform no writes, including locks and caches. */
147
- /** `options.binding` (internal callers composing several writes) refuses with VAULT_DRIFT unless the registry still matches it. */
148
- export function applyWrite(home: string, request: WriteRequest, options: { env?: NodeJS.ProcessEnv; piiSurface?: PiiSurface; binding?: LogBinding; now?: Date } = {}): WriteReceipt {
204
+ export function applyWrite(home: string, request: WriteRequest, options: WriteOptions = {}): WriteReceipt {
205
+ return runWrite(home, request, options);
206
+ }
207
+ /** Proposal-only seam: the normal writer owns the lock, validation, publication and receipt. */
208
+ export function applyProposalWrite(home: string, request: WriteRequest, options: WriteOptions & { binding: LogBinding; proposal: ProposalWriteDecision }): ProposalWriteReceipt {
209
+ if (!options || !options.binding || !options.proposal) return { ok: false, applied: false, proposalState: "pending", proposalPublicationStarted: false, issues: [{ code: "V01", severity: "error", message: "proposal decision and vault binding are required; request a new proposal preview" }], changes: [], indexUpdated: false };
210
+ return runWrite(home, request, options) as ProposalWriteReceipt;
211
+ }
212
+ /** Reject under the same vault mutation lock, without publishing a note or opening the index. */
213
+ export function rejectProposalWrite(home: string, vaultId: string, channel: "cli" | "mcp", binding: LogBinding, decision: ProposalRejectDecision, now = new Date()): ProposalRejectReceipt {
214
+ let fd: number | undefined, file: string | undefined, registryFd: number | undefined, rejected = false;
215
+ const result: ProposalRejectReceipt = { ok: false, rejected: false, issues: [] };
216
+ try {
217
+ if (channel !== "cli" && channel !== "mcp") throw new Error("invalid write channel; use CLI or MCP");
218
+ const initial = loadRegistry(home), vault = initial.vaults.find(item => item.id === vaultId);
219
+ if (!vault || !matchesBinding(initial, vaultId, binding)) throw new Error("vault binding or policy changed; request a new rejection preview");
220
+ if (isDenied(join(home, LOCK_FILE), initial.denyPaths ?? [])) throw new Error("registry lock path is denied; inspect the configured deny paths");
221
+ const root = realpathSync(vault.path);
222
+ if (root !== vault.path) throw new Error("vault root changed or is linked; inspect the registered vault");
223
+ file = join(root, MUTATION_LOCK);
224
+ try { fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
225
+ catch { file = undefined; throw new Error("vault mutation lock is unavailable; stop concurrent writers and inspect the lock"); }
226
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, host: hostname(), token: randomUUID(), created: new Date().toISOString() }) + "\n"); fsyncSync(fd);
227
+ try { registryFd = openSync(join(home, LOCK_FILE), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
228
+ catch { throw new Error("registry lock is unavailable; stop concurrent registry updates and inspect the lock"); }
229
+ writeFileSync(registryFd, JSON.stringify({ pid: process.pid, host: hostname(), created: new Date().toISOString() }) + "\n"); fsyncSync(registryFd);
230
+ const config = loadRegistry(home), currentVault = config.vaults.find(item => item.id === vaultId);
231
+ if (!currentVault || !matchesBinding(config, vaultId, binding)) throw new Error("vault binding or policy changed; request a new rejection preview");
232
+ const record = readStoredProposal(home, decision.bindingDigest, decision.id, config.denyPaths ?? []), recordDigest = proposalRecordDigest(record);
233
+ if (record.state !== "pending" || record.vault !== vaultId || recordDigest !== decision.recordDigest)
234
+ throw new Error("proposal, target or policy changed; request a new rejection preview");
235
+ const issues = screenMetadata({ reason: decision.reason }, { vault: currentVault, config }, record.operation.path);
236
+ if (issues.some(issue => issue.severity === "error")) throw new Error("current disclosure policy refuses the reason; inspect the vault policy");
237
+ const plan = proposalRejectionPlan(home, vaultId, channel, binding, record.operation.path);
238
+ if (proposalDecisionFingerprint(recordDigest, plan, "reject", decision.reason) !== decision.fingerprint) throw new Error("rejection fingerprint changed; request a new rejection preview");
239
+ if (!matchesBinding(loadRegistry(home), vaultId, binding)) throw new Error("vault binding or policy changed; request a new rejection preview");
240
+ const prepared = prepareRejectedProposal(record, decision.reason, now.toISOString()), next = prepared.record;
241
+ if (prepared.reasonRecord) createStoredReason(home, prepared.reasonRecord, recordDigest, config.denyPaths ?? [], registryFd);
242
+ try { replaceStoredProposal(home, decision.bindingDigest, record.id, recordDigest, next, config.denyPaths ?? [], registryFd); }
243
+ catch (error) {
244
+ try { if (proposalRecordDigest(readStoredProposal(home, decision.bindingDigest, record.id, config.denyPaths ?? [])) === proposalRecordDigest(next)) { rejected = true; result.rejected = true; } } catch { /* A failed read cannot establish the decision state. */ }
245
+ throw error;
246
+ }
247
+ rejected = true; result.ok = true; result.rejected = true;
248
+ result.issues.push(...issues.filter(issue => issue.severity === "warning"));
249
+ } catch (error) {
250
+ result.issues.push({ code: "PROPOSAL_REJECT", severity: "error", message: `proposal rejection ${rejected ? "was recorded but finalization failed" : "failed"}: ${error instanceof Error ? error.message : "unknown failure"}; inspect the proposal before retrying` });
251
+ } finally {
252
+ if (registryFd !== undefined) {
253
+ try { cleanupOwnedFile(join(home, LOCK_FILE), registryFd); }
254
+ catch { result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: `proposal rejection ${rejected ? "was recorded but " : ""}registry lock cleanup failed; inspect the lock before retrying` }); }
255
+ finally { try { closeSync(registryFd); } catch { result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: "registry lock descriptor close failed; inspect the lock before retrying" }); } }
256
+ }
257
+ if (fd !== undefined) {
258
+ try { cleanupOwnedFile(file!, fd); }
259
+ catch { result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: `proposal rejection ${rejected ? "was recorded but " : ""}mutation lock cleanup failed; inspect the lock before retrying` }); }
260
+ finally { try { closeSync(fd); } catch { result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: "mutation lock descriptor close failed; inspect the lock before retrying" }); } }
261
+ }
262
+ }
263
+ return result;
264
+ }
265
+ /** Confirm receipt-backed reconciliation under the same vault and registry locks as an apply. */
266
+ export function reconcileProposalWrite(home: string, vaultId: string, channel: "cli" | "mcp", binding: LogBinding, decision: ProposalWriteDecision, now = new Date()): ProposalReconcileReceipt {
267
+ let fd: number | undefined, file: string | undefined, registryFd: number | undefined;
268
+ const result: ProposalReconcileReceipt = { ok: false, resolved: false, state: "apply_unknown", issues: [] };
269
+ try {
270
+ if (channel !== "cli" && channel !== "mcp") throw new Error("invalid write channel; use CLI or MCP");
271
+ const initial = loadRegistry(home), vault = initial.vaults.find(item => item.id === vaultId);
272
+ if (!vault || !matchesBinding(initial, vaultId, binding)) throw new Error("vault binding or policy changed; request a new reconciliation preview");
273
+ if (isDenied(join(home, LOCK_FILE), initial.denyPaths ?? [])) throw new Error("registry lock path is denied; inspect the configured deny paths");
274
+ const root = realpathSync(vault.path);
275
+ if (root !== vault.path) throw new Error("vault root changed or is linked; inspect the registered vault");
276
+ file = join(root, MUTATION_LOCK);
277
+ try { fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
278
+ catch { file = undefined; throw new Error("vault mutation lock is unavailable; stop concurrent writers and inspect the lock"); }
279
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, host: hostname(), token: randomUUID(), created: new Date().toISOString() }) + "\n"); fsyncSync(fd);
280
+ try { registryFd = openSync(join(home, LOCK_FILE), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
281
+ catch { throw new Error("registry lock is unavailable; stop concurrent registry updates and inspect the lock"); }
282
+ writeFileSync(registryFd, JSON.stringify({ pid: process.pid, host: hostname(), created: new Date().toISOString() }) + "\n"); fsyncSync(registryFd);
283
+ const config = loadRegistry(home), currentVault = config.vaults.find(item => item.id === vaultId);
284
+ if (!currentVault || !matchesBinding(config, vaultId, binding)) throw new Error("vault binding or policy changed; request a new reconciliation preview");
285
+ const record = readStoredProposal(home, decision.bindingDigest, decision.id, config.denyPaths ?? []), recordDigest = proposalRecordDigest(record);
286
+ if (record.state !== "apply_unknown" || !record.intent || record.vault !== vaultId || recordDigest !== decision.recordDigest || isDenied(join(root, record.operation.path), config.denyPaths ?? [])) throw new Error("proposal or target changed; request a new reconciliation preview");
287
+ const screened = screenMetadata({ operation: record.operation, agentLabel: record.agentLabel, reason: record.decisionReason }, { vault: currentVault, config }, record.operation.path);
288
+ if (screened.some(issue => issue.severity === "error")) throw new Error("current disclosure policy refuses the proposal; inspect the vault policy");
289
+ const evidence = readStoredEvidence(home, decision.bindingDigest, record.id, record.intent.fingerprint, config.denyPaths ?? []);
290
+ if (!evidence || evidence.beforeSha !== record.intent.beforeSha || evidence.afterSha !== record.intent.afterSha) throw new Error("matching writer receipt evidence is unavailable; inspect the proposal before retrying");
291
+ const plan = proposalRejectionPlan(home, vaultId, channel, binding, record.operation.path), observed = proposalTargetDigest(home, vaultId, record.operation.path, binding);
292
+ const state = evidence.applied && evidence.publicationStarted && observed === evidence.afterSha ? "applied" : !evidence.applied && !evidence.publicationStarted && observed === evidence.beforeSha ? "pending" : undefined;
293
+ if (!state || proposalReconcileFingerprint(recordDigest, proposalEvidenceDigest(evidence), plan, state) !== decision.fingerprint || proposalRejectionPlan(home, vaultId, channel, binding, record.operation.path) !== plan)
294
+ throw new Error("reconciliation evidence or target changed; request a new preview");
295
+ const { intent: _intent, receipt: _receipt, ...base } = record;
296
+ const next: ProposalRecord = state === "applied" ? { ...record, state, updatedAt: now.toISOString(), receipt: { applied: true as const, logged: evidence.logged, beforeSha: evidence.beforeSha, afterSha: evidence.afterSha } }
297
+ : { ...base, state, updatedAt: now.toISOString() };
298
+ try { replaceStoredProposal(home, decision.bindingDigest, record.id, recordDigest, next, config.denyPaths ?? [], registryFd); result.resolved = true; result.state = state; result.ok = true; }
299
+ catch (error) {
300
+ try { if (proposalRecordDigest(readStoredProposal(home, decision.bindingDigest, record.id, config.denyPaths ?? [])) === proposalRecordDigest(next)) { result.resolved = true; result.state = state; } } catch { /* A failed read cannot establish the decision state. */ }
301
+ throw error;
302
+ }
303
+ result.issues.push(...screened.filter(issue => issue.severity === "warning"));
304
+ } catch (error) {
305
+ result.issues.push({ code: "PROPOSAL_RECONCILE", severity: "error", message: `proposal reconciliation ${result.resolved ? "was recorded but finalization failed" : "failed"}: ${error instanceof Error ? error.message : "unknown failure"}; inspect the proposal before retrying` });
306
+ } finally {
307
+ if (registryFd !== undefined) {
308
+ try { cleanupOwnedFile(join(home, LOCK_FILE), registryFd); } catch { result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: "registry lock cleanup failed; inspect the lock before retrying" }); }
309
+ finally { try { closeSync(registryFd); } catch { result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: "registry lock descriptor close failed; inspect the lock before retrying" }); } }
310
+ }
311
+ if (fd !== undefined) {
312
+ try { cleanupOwnedFile(file!, fd); } catch { result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: "mutation lock cleanup failed; inspect the lock before retrying" }); }
313
+ finally { try { closeSync(fd); } catch { result.ok = false; result.issues.push({ code: "CLEANUP", severity: "error", message: "mutation lock descriptor close failed; inspect the lock before retrying" }); } }
314
+ }
315
+ }
316
+ return result;
317
+ }
318
+ function runWrite(home: string, request: WriteRequest, options: WriteOptions & { proposal?: ProposalWriteDecision }): WriteReceipt {
149
319
  let lockFd: number | undefined, lockFile: string | undefined;
320
+ let proposalRegistryFd: number | undefined;
321
+ let proposalState: ProposalWriteReceipt["proposalState"] = "pending";
322
+ let proposalPublicationStarted = false;
323
+ const currentProposalState = (): ProposalWriteReceipt["proposalState"] => proposalState;
324
+ let proposalDenyPaths: string[] = [];
150
325
  let index: VaultIndex | undefined;
151
326
  const temps = new Map<string, { fd: number; remove: boolean }>(), publicationPaths = new Map<string, PublicationPath>(), createdDirs: string[] = [], committed: PlannedChange[] = [];
152
327
  let changes: PlannedChange[] = [], issues: WriteIssue[] = [], fingerprint: string | undefined, root = "", applied = false, indexUpdated = false;
@@ -163,6 +338,7 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
163
338
  ? { ...change, applied: appliedPaths.has(change.path) } : change);
164
339
  const dateWarnings: WriteIssue[] = [];
165
340
  let mergePreview: MergePreview | undefined, mergeCopiedBody = "";
341
+ let relinkPlan: { from: string; to: string; subjects: string[]; issue?: WriteIssue } | undefined;
166
342
  const recordError = (code: string, message: string, path?: string) => issues.push({ code, severity: "error", message, ...(path ? { path } : {}) });
167
343
  try {
168
344
  if (!request || typeof request !== "object" || !request.operation || typeof request.operation !== "object" || typeof request.vault !== "string") refuse("V01", "invalid write request");
@@ -170,6 +346,7 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
170
346
  if (request.expectedShas !== undefined && (!request.expectedShas || typeof request.expectedShas !== "object" || Array.isArray(request.expectedShas))) refuse("V09", "expectedShas must be a mapping");
171
347
  if (request.channel !== undefined && !["cli", "mcp"].includes(request.channel)) refuse("POLICY", "unknown write channel");
172
348
  const config = loadRegistry(home), vault = config.vaults.find(value => value.id === request.vault);
349
+ if (options.proposal) proposalDenyPaths = config.denyPaths ?? [];
173
350
  if (options.binding && !matchesBinding(config, request.vault, options.binding)) refuse("VAULT_DRIFT", "vault identity or policy changed since the run started; nothing written");
174
351
  if (!vault) refuse("V04", "unknown vault id");
175
352
  const unenforceable = unenforceablePii(vault);
@@ -185,6 +362,7 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
185
362
  }
186
363
  const twoStep = ["move", "delete", "tidy", "merge"].includes(request.operation.op);
187
364
  const preview = request.operation.op === "check" || request.dryRun === true || (twoStep && request.confirm !== true);
365
+ if (options.proposal && (preview || !options.binding || !["create", "patch"].includes(request.operation.op))) refuse("V01", "proposal confirmation requires one create or patch and a bound vault; request a new preview");
188
366
  if (!preview) {
189
367
  lockFile = join(root, MUTATION_LOCK);
190
368
  try { lockFd = openSync(lockFile, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
@@ -192,6 +370,13 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
192
370
  writeFileSync(lockFd, JSON.stringify({ pid: process.pid, host: hostname(), token: randomUUID(), created: new Date().toISOString() }) + "\n");
193
371
  fsyncSync(lockFd);
194
372
  }
373
+ if (options.proposal) {
374
+ if (isDenied(join(home, LOCK_FILE), config.denyPaths ?? [])) refuse("V06", "proposal registry lock path is denied; inspect the configured deny paths");
375
+ try { proposalRegistryFd = openSync(join(home, LOCK_FILE), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
376
+ catch { refuse("LOCKED", "registry lock unavailable; stop concurrent registry updates and inspect the lock"); }
377
+ writeFileSync(proposalRegistryFd, JSON.stringify({ pid: process.pid, host: hostname(), created: new Date().toISOString() }) + "\n"); fsyncSync(proposalRegistryFd);
378
+ if (!options.binding || !matchesBinding(loadRegistry(home), request.vault, options.binding)) refuse("VAULT_DRIFT", "vault binding or policy changed after preview; request a new proposal preview");
379
+ }
195
380
  const notes = snapshot(root, config.denyPaths);
196
381
  checkExpected(request, notes);
197
382
  let reportBefore: string | null | undefined;
@@ -204,6 +389,19 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
204
389
  if (request.operation.op === "merge") {
205
390
  const plan = planMerge(request.operation, notes); changes = plan.changes; mergePreview = plan.preview; mergeCopiedBody = plan.copiedBody;
206
391
  } else changes = planOperation(request.operation, notes, reportBefore);
392
+ if (request.operation.op === "move" || request.operation.op === "merge") {
393
+ const from = request.operation.op === "move" ? moveSourcePath(request.operation.from, notes) : notePath(request.operation.absorb);
394
+ const to = request.operation.op === "move" ? notePath(request.operation.to) : notePath(request.operation.keep);
395
+ try {
396
+ lstatSync(join(root, "assertions"));
397
+ try {
398
+ const journal = readJournal(root, config.denyPaths ?? []);
399
+ if (journal.present) relinkPlan = { from, to, subjects: subjectsAtNote(journal, from) };
400
+ } catch {
401
+ relinkPlan = { from, to, subjects: [], issue: { code: "ASSERTIONS", severity: "warning", message: "assertion journal cannot be inspected; check its path and policy before relinking subjects" } };
402
+ }
403
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
404
+ }
207
405
  for (const change of changes) if (isDenied(join(root, change.path), config.denyPaths)) refuse("V06", "planned mutation path is denied", change.path);
208
406
  const validation = { vault, config, notes, operation: request.operation, ...(options.piiSurface ? { piiSurface: options.piiSurface } : {}) };
209
407
  // Validate the caller's candidate first: replacing `updated` must not hide a
@@ -228,15 +426,15 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
228
426
  const identity = lstatSync(root);
229
427
  // The identity every later commit check uses must still be the bound root, not a directory swapped in meanwhile.
230
428
  if (options.binding && (Number(identity.dev) !== options.binding.dev || Number(identity.ino) !== options.binding.ino)) refuse("VAULT_DRIFT", "vault root changed since the run started; nothing written");
231
- fingerprint = sha256(canonical({ input, vault: mutationVault(vault), policy: { denyPaths: config.denyPaths ?? [], piiPatterns: config.piiPatterns ?? [], piiSurface: options.piiSurface ?? "notes" }, root, identity: [identity.dev, identity.ino], files: [...notes].map(([path, text]) => [path, sha256(text)]), changes: receipts(changes) }));
429
+ fingerprint = sha256(canonical({ input, vault: mutationVault(vault), policy: { denyPaths: config.denyPaths ?? [], piiPatterns: config.piiPatterns ?? [], piiSurface: options.piiSurface ?? "notes" }, root, identity: [identity.dev, identity.ino], files: [...notes].map(([path, text]) => [path, sha256(text)]), changes: receipts(changes), ...(relinkPlan ? { assertions: relinkPlan } : {}) }));
232
430
  if (twoStep && request.confirm === true && (typeof request.fingerprint !== "string" || request.fingerprint !== fingerprint)) refuse("V09", request.operation.op === "merge" ? "stale or missing merge fingerprint; request a fresh merge preview and confirm with that fingerprint" : "stale or missing preview fingerprint");
233
- if (mergePreview && request.channel === "mcp" && !issues.some(issue => issue.severity === "error") && Buffer.byteLength(JSON.stringify({ merge: mergePreview, issues, changes: receipts(changes), fingerprint })) > MAX_MERGE_ACK_BYTES) {
234
- // The complete plan must be reviewable before a merge can publish. Keep the refusal compact too.
431
+ if (twoStep && (request.operation.op === "move" || request.operation.op === "merge") && request.channel === "mcp" && !issues.some(issue => issue.severity === "error") && Buffer.byteLength(JSON.stringify({ merge: mergePreview, issues, changes: receipts(changes), fingerprint, ...(relinkPlan ? { assertions: { relinked: relinkPlan.subjects, ...(relinkPlan.issue ? { issue: relinkPlan.issue } : {}) } } : {}) })) > MAX_MERGE_ACK_BYTES) {
432
+ // The complete plan must be reviewable before a move or merge can publish.
235
433
  changes = []; mergePreview = undefined; issues = [];
236
- refuse("V09", "merge preview exceeds the bounded MCP acknowledgement size; use CLI --json for both preview and confirm, or reduce the notes and inbound links before requesting a fresh preview");
434
+ refuse("V09", `${request.operation.op} preview exceeds the bounded MCP acknowledgement size; use CLI --json for both preview and confirm, or reduce the notes, inbound links or subject relinks before requesting a fresh preview`);
237
435
  }
238
436
  if (issues.some(issue => issue.severity === "error")) return result = { ok: false, applied: false, issues, changes: receipts(changes), fingerprint, indexUpdated: false };
239
- if (preview) return result = { ok: true, applied: false, preview: true, ...(request.operation.op === "link" && !changes.length ? {unchanged:true} : {}), issues, changes: receipts(changes), fingerprint, indexUpdated: false };
437
+ if (preview) return result = { ok: true, applied: false, preview: true, ...(request.operation.op === "link" && !changes.length ? {unchanged:true} : {}), issues, changes: receipts(changes), fingerprint, indexUpdated: false, ...(relinkPlan ? { assertions: { relinked: relinkPlan.subjects, ...(relinkPlan.issue ? { issue: relinkPlan.issue } : {}) } } : {}) };
240
438
  if (!changes.length) return result = { ok: true, applied: false, ...(request.operation.op === "link" ? {unchanged:true} : {}), issues, changes: [], fingerprint, indexUpdated: false };
241
439
  index = new VaultIndex(home, vault, config.vaults.map(value => value.path));
242
440
  const staged = new Map<string, string>();
@@ -270,10 +468,32 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
270
468
  // Full content recheck: shared mmap writes can change bytes without moving any stat field.
271
469
  const current = snapshot(root, config.denyPaths);
272
470
  if (current.size !== notes.size || [...current].some(([path, text]) => notes.get(path) !== text)) refuse("V09", "vault changed while staging");
471
+ if (options.proposal) {
472
+ const decision = options.proposal;
473
+ if (!options.binding || !matchesBinding(loadRegistry(home), request.vault, options.binding)) refuse("VAULT_DRIFT", "vault binding or policy changed after preview; request a new proposal preview");
474
+ const record = readStoredProposal(home, decision.bindingDigest, decision.id, config.denyPaths ?? []);
475
+ const recordDigest = proposalRecordDigest(record);
476
+ if (record.state !== "pending" || record.vault !== request.vault || recordDigest !== decision.recordDigest || canonical(record.operation) !== canonical(request.operation))
477
+ refuse("V09", "proposal or operation changed since preview; request a new proposal preview");
478
+ const expected = proposalDecisionFingerprint(recordDigest, fingerprint!, "apply");
479
+ if (decision.fingerprint !== expected) refuse("V09", "proposal decision fingerprint changed; request a new proposal preview");
480
+ const planned = receipts(changes);
481
+ if (planned.length !== 1) refuse("V09", "proposal plan is not a single note change; request a new proposal preview");
482
+ const change = planned[0]!;
483
+ const intent = { ...record, state: "apply_unknown" as const, updatedAt: (options.now ?? new Date()).toISOString(), intent: { fingerprint: expected, beforeSha: change.beforeSha, afterSha: change.sha256 } };
484
+ proposalState = "apply_unknown";
485
+ try { replaceStoredProposal(home, decision.bindingDigest, decision.id, recordDigest, intent, config.denyPaths ?? [], proposalRegistryFd!); proposalState = "apply_unknown"; }
486
+ catch (error) {
487
+ try { if (proposalRecordDigest(readStoredProposal(home, decision.bindingDigest, decision.id, config.denyPaths ?? [])) === recordDigest) proposalState = "pending"; } catch { /* An unreadable record cannot prove whether intent was published. */ }
488
+ throw error;
489
+ }
490
+ if (!matchesBinding(loadRegistry(home), request.vault, options.binding)) refuse("VAULT_DRIFT", "proposal intent was recorded but the vault binding or policy changed; inspect the proposal before retrying");
491
+ }
273
492
  for (const change of changes) {
274
493
  const file = safePath(root, change.path);
275
494
  if (readPlain(root, change.path, request.operation.op === "report" ? MAX_REPORT_BYTES : MAX_NOTE_BYTES) !== change.before) refuse("V09", "file changed while staging", change.path);
276
495
  const temp = staged.get(change.path);
496
+ if (options.proposal) proposalPublicationStarted = true;
277
497
  publishFile(publicationPaths.get(change.path)!, change.after === null ? { kind: "unlink" } : { kind: "rename", temp: temp! }, () => {
278
498
  committed.push(change);
279
499
  if (temp) temps.get(temp)!.remove = false;
@@ -329,6 +549,7 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
329
549
  throw error;
330
550
  }
331
551
  result = { ok: true, applied, issues, changes: receipts(changes), fingerprint, indexUpdated };
552
+ if (applied && relinkPlan) result.assertions = relinkSubjects(home, { vault: request.vault, from: relinkPlan.from, to: relinkPlan.to, channel: request.channel ?? "cli", planned: relinkPlan.subjects }, { env: options.env, now: options.now });
332
553
  if (request.log !== false) {
333
554
  const op = request.operation;
334
555
  const type = op.op === "link" ? "CONNECT" : op.op === "move" ? "ROUTE" : ["supersede", "tidy", "merge"].includes(op.op) ? "RETHINK" : "EXTRACT";
@@ -350,6 +571,25 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
350
571
  }
351
572
  result = { ok: false, applied, issues, changes: reportedChanges(), ...(fingerprint ? { fingerprint } : {}), indexUpdated };
352
573
  } finally {
574
+ if (options.proposal && result && proposalState === "apply_unknown" && proposalRegistryFd !== undefined) {
575
+ const decision = options.proposal, logged = result.logged === true ? true : result.logged === false ? false : null;
576
+ try {
577
+ if (!options.binding || !matchesBinding(loadRegistry(home), request.vault, options.binding)) throw new Error("vault policy changed");
578
+ const current = readStoredProposal(home, decision.bindingDigest, decision.id, proposalDenyPaths), change = result.changes.find(item => item.path === (request.operation as { path: string }).path);
579
+ if (current.state !== "apply_unknown" || current.intent?.fingerprint !== decision.fingerprint || !change || current.intent.beforeSha !== change.beforeSha || current.intent.afterSha !== change.sha256) throw new Error("intent or receipt does not match");
580
+ createStoredEvidence(home, { schemaVersion: 1, id: current.id, bindingDigest: decision.bindingDigest, fingerprint: decision.fingerprint, beforeSha: change.beforeSha, afterSha: change.sha256, applied: result.applied, publicationStarted: proposalPublicationStarted, logged }, proposalDenyPaths, proposalRegistryFd);
581
+ if (result.applied) {
582
+ const next = { ...current, state: "applied" as const, updatedAt: (options.now ?? new Date()).toISOString(), receipt: { applied: true as const, logged, beforeSha: change.beforeSha, afterSha: change.sha256 } };
583
+ try { replaceStoredProposal(home, decision.bindingDigest, decision.id, proposalRecordDigest(current), next, proposalDenyPaths, proposalRegistryFd); proposalState = "applied"; }
584
+ catch (error) {
585
+ try { if (proposalRecordDigest(readStoredProposal(home, decision.bindingDigest, decision.id, proposalDenyPaths)) === proposalRecordDigest(next)) proposalState = "applied"; } catch { /* An unreadable record cannot prove the receipt was published. */ }
586
+ throw error;
587
+ }
588
+ }
589
+ } catch {
590
+ recordError("PROPOSAL_RECEIPT", currentProposalState() === "applied" ? "note and proposal receipt were recorded but finalization failed; inspect the proposal store before retrying" : result.applied ? "note was applied but proposal receipt could not be recorded; inspect and reconcile the proposal before retrying" : "writer stopped after intent but execution evidence could not be recorded; inspect and reconcile the proposal before retrying");
591
+ }
592
+ }
353
593
  try { index?.close(); } catch { recordError("INDEX", "derived index close failed"); }
354
594
  for (const [temp, owned] of temps) {
355
595
  try { if (owned.remove) cleanupOwnedFile(temp, owned.fd); }
@@ -365,12 +605,18 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
365
605
  }
366
606
  // Only empty directories created by this invocation are eligible for removal on failure.
367
607
  if (!applied) for (const dir of createdDirs.reverse()) { try { rmdirSync(dir); } catch { recordError("CLEANUP", "owned empty directory cleanup failed"); } }
608
+ if (proposalRegistryFd !== undefined) {
609
+ try { cleanupOwnedFile(join(home, LOCK_FILE), proposalRegistryFd); }
610
+ catch (error) { recordError("CLEANUP", `proposal registry lock retained; inspect ownership before manual recovery: ${error instanceof Error ? error.message : String(error)}`); }
611
+ finally { try { closeSync(proposalRegistryFd); } catch { recordError("CLEANUP", "proposal registry lock descriptor close failed; inspect retained locks"); } }
612
+ }
368
613
  if (lockFd !== undefined) {
369
614
  try { cleanupOwnedFile(lockFile!, lockFd); }
370
615
  catch (error) { recordError("CLEANUP", `mutation lock retained; inspect ownership before manual recovery: ${error instanceof Error ? error.message : String(error)}`); }
371
616
  finally { try { closeSync(lockFd); } catch { recordError("CLEANUP", "mutation lock descriptor close failed"); } }
372
617
  }
373
618
  if (result) {
619
+ if (options.proposal) { (result as ProposalWriteReceipt).proposalState = proposalState; (result as ProposalWriteReceipt).proposalPublicationStarted = proposalPublicationStarted; }
374
620
  if (retainedBackups.size) result.retainedBackups = [...retainedBackups];
375
621
  const possibleDuplicates = issues.filter(issue => issue.code === "V08" && issue.severity === "warning" && issue.path).map(issue => issue.path!);
376
622
  if (possibleDuplicates.length) result.possibleDuplicates = possibleDuplicates;
@@ -379,5 +625,5 @@ export function applyWrite(home: string, request: WriteRequest, options: { env?:
379
625
  if (result.ok && mergePreview) result.merge = mergePreview;
380
626
  }
381
627
  }
382
- return result!;
628
+ return request?.channel === "mcp" ? boundMcpWriteReceipt(result!) : result!;
383
629
  }