@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
@@ -1,6 +1,6 @@
1
1
  import { promoteToOrg } from "./org-promote.ts";
2
2
  import { syncVault } from "./sync.ts";
3
- import { PLAIN, type TextOptions } from "./text-output.ts";
3
+ import { PLAIN, UsageError, type TextOptions } from "./text-output.ts";
4
4
  import { renderOrgPromote, renderSync } from "./write-output.ts";
5
5
 
6
6
  function parse(command: string, args: string[], values: string[], booleans: string[]) {
@@ -8,10 +8,10 @@ function parse(command: string, args: string[], values: string[], booleans: stri
8
8
  for (let i = 0; i < args.length; i++) {
9
9
  const arg = args[i]!;
10
10
  if (!arg.startsWith("--")) { positional.push(arg); continue; }
11
- if (Object.hasOwn(flags, arg) || (!values.includes(arg) && !booleans.includes(arg))) throw new Error(`${command}: unknown or repeated option ${arg}`);
11
+ if (Object.hasOwn(flags, arg) || (!values.includes(arg) && !booleans.includes(arg))) throw new UsageError(`${command}: unknown or repeated option ${arg}`);
12
12
  if (booleans.includes(arg)) { flags[arg] = true; continue; }
13
13
  const value = args[++i];
14
- if (value === undefined || value.startsWith("--")) throw new Error(`${arg}: value required`);
14
+ if (value === undefined || value.startsWith("--")) throw new UsageError(`${arg}: value required`);
15
15
  flags[arg] = value;
16
16
  }
17
17
  return { flags, positional, value: (name: string) => typeof flags[name] === "string" ? flags[name] as string : undefined };
@@ -20,14 +20,14 @@ function parse(command: string, args: string[], values: string[], booleans: stri
20
20
  export function runOrgCommand(command: string, args: string[], home: string, env: NodeJS.ProcessEnv, text: TextOptions = PLAIN): { text: string; code: number } {
21
21
  if (command === "promote") {
22
22
  const { flags, positional, value } = parse(command, args, ["--to", "--topics", "--fingerprint", "--log-project"], ["--again", "--confirm", "--json"]);
23
- if (positional.length !== 2 || !value("--to")) throw new Error("promote: requires personal vault id, note and --to <org vault>");
23
+ if (positional.length !== 2 || !value("--to")) throw new UsageError("promote: requires personal vault id, note and --to <org vault>");
24
24
  const result = promoteToOrg(home, { from: positional[0]!, note: positional[1]!, to: value("--to")!, again: flags["--again"] === true, confirm: flags["--confirm"] === true,
25
25
  ...(value("--topics") ? { topics: value("--topics")!.split(",").map(t => t.trim()).filter(Boolean) } : {}),
26
26
  ...(value("--fingerprint") ? { fingerprint: value("--fingerprint") } : {}), ...(value("--log-project") ? { logProject: value("--log-project") } : {}), channel: "cli" }, { env });
27
27
  return { text: flags["--json"] ? JSON.stringify(result) : renderOrgPromote(result, text, { argv: [command, ...args], positional }), code: result.ok ? 0 : 1 };
28
28
  }
29
29
  const { flags, positional, value } = parse(command, args, ["--fingerprint", "--message"], ["--confirm", "--json"]);
30
- if (positional.length !== 1) throw new Error("sync: requires vault id");
30
+ if (positional.length !== 1) throw new UsageError("sync: requires vault id");
31
31
  const result = syncVault(home, { vault: positional[0]!, confirm: flags["--confirm"] === true, ...(value("--fingerprint") ? { fingerprint: value("--fingerprint") } : {}), ...(value("--message") ? { message: value("--message") } : {}) }, { env });
32
32
  return { text: flags["--json"] ? JSON.stringify(result) : renderSync(result, text, { argv: [command, ...args], positional }), code: result.ok ? 0 : 1 };
33
33
  }
@@ -16,6 +16,7 @@ import { appendLog, logBinding } from "./vault-log.ts";
16
16
  import type { WriteIssue, WriteReceipt } from "./write-types.ts";
17
17
  import type { LogBinding, LogReceipt } from "./log-types.ts";
18
18
  import { analysisInput } from "./analysis-input.ts";
19
+ import { screenEvidenceForTarget } from "./evidence.ts";
19
20
  import { lintVault } from "./vault-lint.ts";
20
21
  import type { AnalysisSnapshot } from "./analysis-types.ts";
21
22
 
@@ -41,6 +42,8 @@ export interface OrgPromoteResult {
41
42
  target: string | null;
42
43
  text?: string;
43
44
  droppedLinks?: string[];
45
+ /** Evidence entries removed because their source is not retained at the destination: index and reason only. */
46
+ evidenceRemoved?: { index: number; reason: string }[];
44
47
  /** Target-vault advisory data, excluded from the promotion fingerprint. */
45
48
  canonRowMatches?: CanonRowMatch[];
46
49
  canonTableWarnings?: string[];
@@ -230,6 +233,12 @@ export function promoteToOrg(home: string, request: OrgPromoteRequest, options:
230
233
  const values = strings(parsed.data[key]);
231
234
  if (values.some(value => value.includes("[[") && !targetNotes.resolved.has(linkKey(value)))) { frontmatter[key] = undefined; transformed.dropped.push(`${key}:${values.join(",")}`); }
232
235
  }
236
+ // Evidence whose source is not retained in the target vault is removed; its path and quote never reach the org note.
237
+ if (parsed.data.evidence !== undefined) {
238
+ const screened = screenEvidenceForTarget(parsed.data.evidence, parsed.data.source, target, config.denyPaths ?? []);
239
+ frontmatter.evidence = screened.kept;
240
+ if (screened.removed.length) result.evidenceRemoved = screened.removed;
241
+ }
233
242
  let text = emitFrontmatter(parseFrontmatter(parsed.source.slice(0, parsed.source.length - parsed.body.length) + body), frontmatter);
234
243
  result.target = `${target.id}:${targetPath}`; result.text = text; result.droppedLinks = transformed.dropped;
235
244
  const screen = [...screenForOrg(text, parsed.data, target, config), ...screenDroppedLinks(home, source, all, transformed.dropped.filter(link => !link.includes(":")))];
@@ -6,7 +6,7 @@ import { loadRegistry } from "./registry.ts";
6
6
  import { canonicalPath, isDenied } from "./platform.ts";
7
7
  import { MAX_WRITE_BYTES } from "./writer.ts";
8
8
  import { listPromotionCandidates, promoteFromAmem, type PromoteRequest } from "./promote.ts";
9
- import { PLAIN, type TextOptions } from "./text-output.ts";
9
+ import { PLAIN, UsageError, type TextOptions } from "./text-output.ts";
10
10
  import { renderCandidates, renderPromote } from "./write-output.ts";
11
11
 
12
12
  const VALUES = ["--project", "--limit", "--stem", "--type", "--domain", "--topics", "--description", "--title", "--body", "--link-to", "--log-project", "--fingerprint"];
@@ -42,24 +42,24 @@ export async function runPromoteCommand(args: string[], home: string, env: NodeJ
42
42
  for (let i = 0; i < args.length; i++) {
43
43
  const arg = args[i]!;
44
44
  if (!arg.startsWith("--")) { positional.push(arg); continue; }
45
- if (Object.hasOwn(flags, arg) || (!VALUES.includes(arg) && !BOOLEANS.includes(arg))) throw new Error(`promote-from-amem: unknown or repeated option ${arg}`);
45
+ if (Object.hasOwn(flags, arg) || (!VALUES.includes(arg) && !BOOLEANS.includes(arg))) throw new UsageError(`promote-from-amem: unknown or repeated option ${arg}`);
46
46
  if (BOOLEANS.includes(arg)) { flags[arg] = true; continue; }
47
47
  const value = args[++i];
48
- if (value === undefined || (value.startsWith("--") && value !== "-")) throw new Error(`${arg}: value required`);
48
+ if (value === undefined || (value.startsWith("--") && value !== "-")) throw new UsageError(`${arg}: value required`);
49
49
  flags[arg] = value;
50
50
  }
51
51
  const value = (name: string) => typeof flags[name] === "string" ? flags[name] as string : undefined;
52
52
  const json = flags["--json"] === true, ctx = { argv: ["promote-from-amem", ...args], positional };
53
- if (positional.length < 1 || positional.length > 2) throw new Error("promote-from-amem: requires vault id and optional mem id");
53
+ if (positional.length < 1 || positional.length > 2) throw new UsageError("promote-from-amem: requires vault id and optional mem id");
54
54
  const [vault, rawId] = positional as [string, string | undefined];
55
55
  if (!loadRegistry(home).vaults.some(v => v.id === vault)) throw new Error("promote-from-amem: unknown vault id");
56
56
  if (rawId === undefined) {
57
- if (flags["--all-projects"] && value("--project")) throw new Error("choose either --all-projects or --project");
57
+ if (flags["--all-projects"] && value("--project")) throw new UsageError("choose either --all-projects or --project");
58
58
  const limit = value("--limit") === undefined ? undefined : /^[0-9]+$/.test(value("--limit")!) ? Number(value("--limit")) : NaN;
59
59
  const list = await listPromotionCandidates({ env, allProjects: flags["--all-projects"] === true, ...(value("--project") ? { project: value("--project") } : {}), ...(limit !== undefined ? { limit } : {}), piiPatterns: loadRegistry(home).piiPatterns });
60
60
  return { text: json ? JSON.stringify(list) : renderCandidates(list, text, ctx), code: 0 };
61
61
  }
62
- if (flags["--all-projects"]) throw new Error("--all-projects lists candidates only");
62
+ if (flags["--all-projects"]) throw new UsageError("--all-projects lists candidates only");
63
63
  const request: PromoteRequest = { vault, id: rawId.replace(/^mem:/, ""), channel: "cli", confirm: flags["--confirm"] === true };
64
64
  for (const [flag, key] of [["--stem", "stem"], ["--type", "type"], ["--domain", "domain"], ["--description", "description"], ["--title", "title"], ["--link-to", "linkTo"], ["--log-project", "logProject"], ["--fingerprint", "fingerprint"]] as const) {
65
65
  if (value(flag) !== undefined) (request as unknown as Record<string, unknown>)[key] = value(flag);
@@ -0,0 +1,100 @@
1
+ import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
2
+ import { canonicalPath, isDenied } from "./platform.ts";
3
+ import { loadRegistry } from "./registry.ts";
4
+ import { applyProposal, confirmProposalReconciliation, listProposals, previewProposalApply, previewProposalReject, reconcileProposal, rejectProposal, showProposal, submitProposal, type ProposalContext } from "./proposal-provider.ts";
5
+ import { MAX_PROPOSAL_RECORD_BYTES } from "./proposals.ts";
6
+ import { blocks, fields, heading, issueTable, nextCommand, PLAIN, shellWord, status, stripTerminal, table, UsageError, type TextOptions } from "./text-output.ts";
7
+
8
+ const command = (...args: string[]) => ["vmem", "proposal", ...args].map(shellWord).join(" ");
9
+ function input(file: string, home: string): unknown {
10
+ if (file !== "-" && isDenied(canonicalPath(file), loadRegistry(home).denyPaths)) throw new Error("proposal: input file is denied; choose an allowed file");
11
+ const fd = file === "-" ? 0 : openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
12
+ try {
13
+ const stat = fstatSync(fd);
14
+ if (file !== "-" && (!stat.isFile() || stat.size > MAX_PROPOSAL_RECORD_BYTES)) throw new Error("proposal: input must be a regular file no larger than 32 KiB; shorten the input");
15
+ const buffer = Buffer.alloc(MAX_PROPOSAL_RECORD_BYTES + 1); let size = 0, n = 0;
16
+ while (size < buffer.length && (n = readSync(fd, buffer, size, buffer.length - size, null)) > 0) size += n;
17
+ if (size > MAX_PROPOSAL_RECORD_BYTES) throw new Error("proposal: input exceeds 32 KiB; shorten the input");
18
+ const bytes = buffer.subarray(0, size), text = bytes.toString("utf8");
19
+ if (!Buffer.from(text, "utf8").equals(bytes)) throw new Error("proposal: input is not UTF-8; save the input as UTF-8");
20
+ try { return JSON.parse(text); } catch { throw new UsageError("proposal: input is not JSON; supply a create or patch operation as JSON"); }
21
+ } finally { if (file !== "-") closeSync(fd); }
22
+ }
23
+ const number = (value: string | boolean | undefined, name: string, minimum: number, maximum: number): number | undefined => {
24
+ if (value === undefined) return undefined;
25
+ if (typeof value !== "string" || !/^[0-9]+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < minimum || Number(value) > maximum) throw new UsageError(`proposal: ${name} requires an integer ${minimum}..${maximum}`);
26
+ return Number(value);
27
+ };
28
+ /** CLI parsing and rendering; all lifecycle semantics stay in the shared provider. */
29
+ export function runProposalCommand(args: string[], home: string, env: NodeJS.ProcessEnv, text: TextOptions = PLAIN): { text: string; code: number } {
30
+ const action = args[0], valueFlags: Record<string, string[]> = { submit: ["--agent-label"], list: ["--state", "--limit", "--after"], show: ["--offset", "--max-bytes"], apply: ["--fingerprint"], reject: ["--reason", "--fingerprint"], reconcile: ["--fingerprint"] };
31
+ if (!action || !Object.hasOwn(valueFlags, action)) throw new UsageError("proposal: use submit, list, show, apply, reject or reconcile");
32
+ const flags: Record<string, string | boolean> = {}, positional: string[] = [];
33
+ let literal = false;
34
+ for (let i = 1; i < args.length; i++) {
35
+ const word = args[i]!;
36
+ if (word === "--" && !literal) { literal = true; continue; }
37
+ if (literal || !word.startsWith("--")) { positional.push(word); continue; }
38
+ if (Object.hasOwn(flags, word)) throw new UsageError(`proposal ${action}: repeated option ${word}`);
39
+ if (word === "--json" || (word === "--confirm" && ["apply", "reject", "reconcile"].includes(action))) { flags[word] = true; continue; }
40
+ if (!valueFlags[action]!.includes(word)) throw new UsageError(`proposal ${action}: unknown option ${word}`);
41
+ const value = args[++i]; if (value === undefined || value.startsWith("--")) throw new UsageError(`proposal ${action}: ${word} requires a value`);
42
+ flags[word] = value;
43
+ }
44
+ const required = action === "list" ? 1 : 2;
45
+ if (positional.length !== required) throw new UsageError(`proposal ${action}: expected ${required === 1 ? "one vault" : "a vault and target"}`);
46
+ const vault = positional[0]!, target = positional[1], ctx: ProposalContext = { channel: "cli", env }, json = flags["--json"] === true;
47
+ const value = (name: string): string | undefined => typeof flags[name] === "string" ? flags[name] as string : undefined;
48
+ if (!["submit", "list"].includes(action) && target !== undefined && !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(target)) throw new UsageError(`proposal ${action}: expected a proposal id from proposal list`);
49
+ if (action === "submit") {
50
+ const label = value("--agent-label");
51
+ if (label !== undefined && (!label.trim() || Buffer.byteLength(label) > 256 || /[\p{Cc}\p{Zl}\p{Zp}]/u.test(label))) throw new UsageError("proposal submit: --agent-label needs nonempty text without controls, at most 256 bytes");
52
+ const result = submitProposal(home, { vault, operation: input(target!, home), ...(label !== undefined ? { agentLabel: label } : {}) }, ctx);
53
+ const message = result.stored ? `submitted proposal ${result.id}${result.path ? ` for ${result.path}` : "; inspect current policy"}` : `proposal ${result.id}: ${result.stored === false ? "not stored" : "storage outcome unknown"}`;
54
+ return { text: json ? JSON.stringify(result) : blocks(status(result.ok && !result.issues.length ? "ok" : result.stored ? "warn" : result.stored === false ? "fail" : "unknown", message, text), issueTable(result.issues, text)), code: result.ok ? 0 : 1 };
55
+ }
56
+ if (action === "list") {
57
+ const state = value("--state");
58
+ if (state !== undefined && !["pending", "applied", "rejected", "apply_unknown"].includes(state)) throw new UsageError("proposal list: invalid --state");
59
+ const after = value("--after");
60
+ if (after !== undefined && !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(after)) throw new UsageError("proposal list: --after needs a returned cursor");
61
+ const result = listProposals(home, { vault, ...(state ? { state: state as "pending" | "applied" | "rejected" | "apply_unknown" } : {}), limit: number(flags["--limit"], "--limit", 1, 100), after }, ctx);
62
+ const rows = result.items.length ? result.items.map(item => blocks(status(item.state === "applied" ? "ok" : item.state === "rejected" ? "absent" : item.state === "pending" ? "pending" : "unknown", `${item.state} ${item.id}`, text), fields([["path", item.path], ["created", item.createdAt]], text))).join("\n\n") : "no proposals found";
63
+ const next = result.nextCursor ? nextCommand("next", command("list", vault, ...(state ? ["--state", state] : []), ...(flags["--limit"] ? ["--limit", String(flags["--limit"])] : []), "--after", result.nextCursor), text) : undefined;
64
+ return { text: json ? JSON.stringify(result) : blocks(rows, issueTable(result.issues, text), next), code: 0 };
65
+ }
66
+ if (action === "show") {
67
+ const result = showProposal(home, { vault, id: target!, offset: number(flags["--offset"], "--offset", 0, MAX_PROPOSAL_RECORD_BYTES), maxBytes: number(flags["--max-bytes"], "--max-bytes", 1, 16384) }, ctx);
68
+ const next = result.nextOffset !== null && nextCommand("next", command("show", vault, target!, "--offset", String(result.nextOffset), ...(flags["--max-bytes"] ? ["--max-bytes", String(flags["--max-bytes"])] : [])), text);
69
+ return { text: json ? JSON.stringify(result) : blocks(heading(`proposal ${result.id}: ${result.state}`, text), fields([["vault", result.vault], ["path", result.path], ["agent label (unverified)", result.agentLabelUnverified], ["reason", result.decisionReason]], text), issueTable(result.issues, text), stripTerminal(result.content), next), code: 0 };
70
+ }
71
+ if (action === "reconcile") {
72
+ const confirm = flags["--confirm"] === true, fingerprint = value("--fingerprint");
73
+ if ((confirm && !fingerprint) || (!confirm && fingerprint) || (fingerprint !== undefined && !/^[a-f0-9]{64}$/.test(fingerprint))) throw new UsageError("proposal reconcile: --confirm and a preview fingerprint must be supplied together");
74
+ if (confirm) {
75
+ const result = confirmProposalReconciliation(home, { vault, id: target!, fingerprint: fingerprint! }, ctx);
76
+ return { text: json ? JSON.stringify(result) : blocks(status(result.resolved ? result.ok ? "ok" : "warn" : "unknown", `proposal ${target}: ${result.state}`, text), issueTable(result.issues, text)), code: result.ok ? 0 : 1 };
77
+ }
78
+ const result = reconcileProposal(home, { vault, id: target! }, ctx);
79
+ const next = result.fingerprint ? nextCommand("confirm", command("reconcile", vault, target!, "--confirm", "--fingerprint", result.fingerprint), text) : undefined;
80
+ return { text: json ? JSON.stringify(result) : blocks(status("unknown", `proposal ${result.id}: apply outcome unknown`, text), fields([["before", result.beforeSha ?? "-"], ["after", result.afterSha ?? "-"], ["observed", result.observedSha ?? "-"], ["receipt evidence", result.receiptEvidence]], text), issueTable(result.issues, text), result.explanation, next), code: 0 };
81
+ }
82
+ const confirm = flags["--confirm"] === true, fingerprint = value("--fingerprint"), reason = value("--reason");
83
+ if ((confirm && !fingerprint) || (!confirm && fingerprint)) throw new UsageError(`proposal ${action}: --confirm and --fingerprint must be supplied together`);
84
+ if (fingerprint !== undefined && !/^[a-f0-9]{64}$/.test(fingerprint)) throw new UsageError(`proposal ${action}: --fingerprint needs the SHA from a fresh preview`);
85
+ if (action === "apply") {
86
+ if (!confirm) {
87
+ const result = previewProposalApply(home, { vault, id: target! }, ctx);
88
+ return { text: json ? JSON.stringify(result) : blocks(heading(`proposal ${result.id}: apply preview`, text), table(["PATH", "BEFORE", "AFTER", "BYTES"], result.changes.map(change => [change.path, change.beforeSha ?? "-", change.sha256 ?? "-", change.bytes]), text), issueTable(result.issues, text), nextCommand("confirm", command("apply", vault, target!, "--confirm", "--fingerprint", result.fingerprint), text)), code: 0 };
89
+ }
90
+ const result = applyProposal(home, { vault, id: target!, fingerprint: fingerprint! }, ctx);
91
+ return { text: json ? JSON.stringify(result) : blocks(status(result.state === "apply_unknown" ? "unknown" : result.applied ? result.ok && !result.issues.length ? "ok" : "warn" : "fail", `proposal ${target}: ${result.state}${result.logged === false ? "; log not recorded" : ""}`, text), issueTable(result.issues, text)), code: result.ok ? 0 : 1 };
92
+ }
93
+ if (!reason?.trim() || Buffer.byteLength(reason, "utf8") > 4096) throw new UsageError("proposal reject: --reason must be nonempty and at most 4096 bytes");
94
+ if (!confirm) {
95
+ const result = previewProposalReject(home, { vault, id: target!, reason }, ctx);
96
+ return { text: json ? JSON.stringify(result) : blocks(heading(`proposal ${result.id}: rejection preview`, text), fields([["reason", result.reason]], text), issueTable(result.issues, text), nextCommand("confirm", command("reject", vault, target!, "--reason", reason, "--confirm", "--fingerprint", result.fingerprint), text)), code: 0 };
97
+ }
98
+ const result = rejectProposal(home, { vault, id: target!, reason, fingerprint: fingerprint! }, ctx);
99
+ return { text: json ? JSON.stringify(result) : blocks(status(result.rejected ? result.ok && !result.issues.length ? "ok" : "warn" : "fail", `proposal ${target}: ${result.rejected ? "rejected" : "not rejected"}`, text), issueTable(result.issues, text)), code: result.ok ? 0 : 1 };
100
+ }
@@ -0,0 +1,335 @@
1
+ /** Shared proposal submission, review, decision and reconciliation provider. */
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { closeSync, constants, fsyncSync, openSync, realpathSync, writeFileSync } from "node:fs";
5
+ import { hostname } from "node:os";
6
+ import { join } from "node:path";
7
+ import { loadRegistry, LOCK_FILE } from "./registry.ts";
8
+ import { logBinding, matchesBinding } from "./vault-log.ts";
9
+ import { applyProposalWrite, applyWrite, proposalRejectionPlan, proposalTargetDigest, proposalTargetFrontmatter, reconcileProposalWrite, rejectProposalWrite, type ProposalReconcileReceipt, type ProposalRejectReceipt } from "./writer.ts";
10
+ import { verifyNoteEvidence } from "./evidence.ts";
11
+ import { screenMetadata } from "./write-validation.ts";
12
+ import { checkStoredBinding, createStoredProposal, listStoredProposalIds, readStoredEvidence, readStoredProposal, readStoredReason } from "./proposal-storage.ts";
13
+ import { encodeProposalRecord, parseProposalOperation, prepareRejectedProposal, proposalDecisionFingerprint, proposalEvidenceDigest, proposalPayloadDigest, proposalReconcileFingerprint, proposalRecordDigest, type ProposalRecord } from "./proposals.ts";
14
+ import type { ChangeReceipt, WriteIssue } from "./write-types.ts";
15
+ import type { LogBinding } from "./log-types.ts";
16
+ import { unenforceablePii, type VaultSpec } from "./config.ts";
17
+ import { canonicalPath, isDenied } from "./platform.ts";
18
+ import { cleanupOwnedFile } from "./write-files.ts";
19
+
20
+ export interface ProposalSubmitRequest { vault: string; operation: unknown; agentLabel?: string }
21
+ export interface ProposalContext { channel: "cli" | "mcp"; env?: NodeJS.ProcessEnv; now?: Date; expectedVault?: VaultSpec; expectedBinding?: LogBinding | null }
22
+ export interface ProposalSubmitted { ok: boolean; stored: boolean | null; id: string; vault: string; path: string | null; state: "pending" | null; createdAt: string; payloadDigest: string | null; issues: WriteIssue[] }
23
+ export interface ProposalSummary { id: string; vault: string; path: string; state: ProposalRecord["state"]; createdAt: string }
24
+ export interface ProposalListRequest { vault: string; state?: ProposalRecord["state"]; limit?: number; after?: string }
25
+ export interface ProposalPage { items: ProposalSummary[]; nextCursor: string | null; issues: WriteIssue[] }
26
+ export interface ProposalShowRequest { vault: string; id: string; offset?: number; maxBytes?: number }
27
+ export interface ProposalView { id: string; vault: string; state: ProposalRecord["state"]; path: string; createdAt: string; payloadDigest: string; agentLabelUnverified?: string; decisionReason?: string; content: string; offset: number; nextOffset: number | null; truncated: boolean; issues: WriteIssue[] }
28
+ export interface ProposalApplyPreview { id: string; vault: string; state: "pending"; fingerprint: string; changes: ChangeReceipt[]; issues: WriteIssue[] }
29
+ export interface ProposalApplyResult { ok: boolean; applied: boolean | null; state: "pending" | "applied" | "apply_unknown"; logged: boolean | null; issues: WriteIssue[] }
30
+ export interface ProposalReconciliation { id: string; vault: string; state: "apply_unknown"; beforeSha: string | null; afterSha: string | null; observedSha: string | null; matchesBefore: boolean; matchesAfter: boolean; receiptEvidence: "available" | "unavailable"; proposedState: "pending" | "applied" | null; fingerprint: string | null; explanation: string; issues: WriteIssue[] }
31
+ export interface ProposalRejectPreview { id: string; vault: string; state: "pending"; reason: string; fingerprint: string; issues: WriteIssue[] }
32
+ const MAX_SHOW_BYTES = 16 * 1024, MAX_RPC_REPLY_BYTES = 48 * 1024;
33
+
34
+ /** Conservative complete MCP reply size; MCP limits request IDs to 200 UTF-16 units (at most 1200 encoded bytes). */
35
+ export function proposalReplyBytes(result: unknown): number {
36
+ const text = JSON.stringify(result);
37
+ return Buffer.byteLength(JSON.stringify({ jsonrpc: "2.0", id: "x".repeat(1200), result: { content: [{ type: "text", text }] } }), "utf8") + 1;
38
+ }
39
+
40
+ function currentBinding(home: string, id: string, options: ProposalContext) {
41
+ const channel = options.channel;
42
+ if (channel !== "cli" && channel !== "mcp") throw new Error("proposal: invalid write channel; use CLI or MCP");
43
+ const config = loadRegistry(home), vault = config.vaults.find(item => item.id === id);
44
+ if (!vault) throw new Error("proposal: unknown vault; choose a registered vault");
45
+ if (options.expectedVault && !isDeepStrictEqual(vault, options.expectedVault)) throw new Error("proposal: vault registration changed since MCP startup; restart the MCP server");
46
+ if (options.expectedBinding === null || (options.expectedBinding && !matchesBinding(config, id, options.expectedBinding))) throw new Error("proposal: vault identity or policy changed since MCP startup; restart the MCP server");
47
+ 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");
48
+ let root: string;
49
+ try { root = realpathSync(vault.path); } catch { throw new Error("proposal: vault root is unavailable; inspect the registered vault"); }
50
+ if (root !== vault.path || isDenied(vault.path, config.denyPaths ?? [])) throw new Error("proposal: vault root is denied, changed or linked; inspect the registered vault");
51
+ if (unenforceablePii(vault)) throw new Error("proposal: vault PII policy cannot be enforced; inspect the vault policy");
52
+ const homePath = canonicalPath(home);
53
+ if (isDenied(homePath, config.denyPaths ?? []) || isDenied(join(homePath, "proposals"), config.denyPaths ?? [])) throw new Error("proposal: configured proposal storage is denied; inspect the configured deny paths");
54
+ if (config.vaults.some(item => homePath === item.path || homePath.startsWith(`${item.path}/`))) throw new Error("proposal: configured home is inside a registered vault; move the home outside vaults");
55
+ const binding = logBinding(vault, config);
56
+ const bindingDigest = createHash("sha256").update(JSON.stringify([vault.id, vault.path, binding.dev, binding.ino]), "utf8").digest("hex");
57
+ return { home, config, vault, binding, bindingDigest };
58
+ }
59
+ function warningsOf(...groups: WriteIssue[][]): WriteIssue[] {
60
+ const seen = new Set<string>(), out: WriteIssue[] = [];
61
+ for (const issue of groups.flat()) if (issue.severity === "warning" && !seen.has(`${issue.code}:${issue.message}`)) {
62
+ seen.add(`${issue.code}:${issue.message}`); out.push({ code: issue.code, severity: "warning", message: issue.message });
63
+ }
64
+ return out;
65
+ }
66
+ function evidenceWarnings(home: string, operation: ProposalRecord["operation"], context: ReturnType<typeof currentBinding>): WriteIssue[] {
67
+ const data = operation.op === "create" ? operation.frontmatter : proposalTargetFrontmatter(home, context.vault.id, operation.path, context.binding);
68
+ const results = verifyNoteEvidence(context.vault, data, context.config.denyPaths ?? [], new Map());
69
+ return results.filter(item => item.status !== "verified").map(item => ({ code: "EVIDENCE", severity: "warning", message: `proposal evidence entry ${item.index + 1}: ${item.status}${item.reason ? ` (${item.reason})` : ""}; inspect the source and refresh the evidence before applying` }));
70
+ }
71
+ function screenForRead(record: ProposalRecord, context: ReturnType<typeof currentBinding>): { issues: WriteIssue[]; reason?: string } {
72
+ if (record.vault !== context.vault.id || record.bindingDigest !== context.bindingDigest || isDenied(join(context.vault.path, record.operation.path), context.config.denyPaths ?? []))
73
+ throw new Error("proposal: stored binding or target is denied or changed; inspect the registered vault and policy");
74
+ const reason = record.decisionReasonRef ? readStoredReason(context.home, record.bindingDigest, record.id, record.decisionReasonRef, context.config.denyPaths ?? []) : record.decisionReason;
75
+ const issues = screenMetadata({ operation: record.operation, agentLabel: record.agentLabel, decisionReason: reason }, { vault: context.vault, config: context.config }, record.operation.path);
76
+ if (issues.some(issue => issue.severity === "error")) throw new Error("proposal: current disclosure policy refuses stored content; inspect the vault policy");
77
+ return { issues: warningsOf(issues), ...(reason !== undefined ? { reason } : {}) };
78
+ }
79
+ function requireCurrentStore(home: string, context: ReturnType<typeof currentBinding>): void {
80
+ const issues: WriteIssue[] = [];
81
+ if (!checkStoredBinding(home, context.vault.id, context.bindingDigest, context.config.denyPaths ?? [], issues)) {
82
+ const orphan = issues.find(issue => issue.code === "PROPOSAL_ORPHANED_BINDING");
83
+ throw new Error(orphan ? `proposal: ${orphan.message}` : "proposal: no proposal store for this vault; use proposal list to find an id");
84
+ }
85
+ }
86
+ function bindingStillCurrent(home: string, context: ReturnType<typeof currentBinding>): boolean {
87
+ try { return matchesBinding(loadRegistry(home), context.vault.id, context.binding); } catch { return false; }
88
+ }
89
+ function storageFailure(error: unknown): string {
90
+ let current = error;
91
+ for (let i = 0; i < 3 && current instanceof Error; i++) {
92
+ const code = (current as NodeJS.ErrnoException).code;
93
+ if (code === "ENOSPC") return "storage is full; free space and inspect the proposal store";
94
+ if (code === "EACCES" || code === "EPERM") return "storage permission was denied; inspect directory ownership and permissions";
95
+ if (code === "EMFILE" || code === "ENFILE") return "file descriptors are exhausted; reduce concurrent work and retry";
96
+ if (code === "EEXIST") return "a storage entry already exists; inspect the proposal store";
97
+ if (current.message.startsWith("proposal: ")) return current.message;
98
+ current = current.cause;
99
+ }
100
+ return "storage operation failed; inspect filesystem permissions and available space";
101
+ }
102
+ /** Screen and validate a proposal before any persistent record is created. */
103
+ export function submitProposal(home: string, request: ProposalSubmitRequest, options: ProposalContext): ProposalSubmitted {
104
+ if (!request || typeof request !== "object" || Object.keys(request).some(key => !["vault", "operation", "agentLabel"].includes(key)) || typeof request.vault !== "string")
105
+ throw new Error("proposal: invalid submit request; provide a vault and one operation");
106
+ if (options.channel !== "cli" && options.channel !== "mcp") throw new Error("proposal: invalid write channel; use CLI or MCP");
107
+ if (request.agentLabel !== undefined && (typeof request.agentLabel !== "string" || !request.agentLabel.trim() || Buffer.byteLength(request.agentLabel) > 256 || /[\p{Cc}\p{Zl}\p{Zp}]/u.test(request.agentLabel)))
108
+ throw new Error("proposal: agent label must be nonempty text without controls and at most 256 bytes; correct the label");
109
+ const operation = parseProposalOperation(request.operation), context = currentBinding(home, request.vault, options), { config, vault, binding, bindingDigest } = context;
110
+ const screen = screenMetadata({ operation, ...(request.agentLabel !== undefined ? { agentLabel: request.agentLabel } : {}) }, { vault, config }, operation.path);
111
+ if (screen.some(issue => issue.severity === "error")) throw new Error(`proposal: payload screening refused (${[...new Set(screen.filter(issue => issue.severity === "error").map(issue => issue.code))].join(", ")}); remove prohibited content or correct the vault policy`);
112
+ const preview = applyWrite(home, { vault: vault.id, operation, channel: options.channel, dryRun: true }, { env: options.env, binding, now: options.now });
113
+ if (!preview.ok) throw new Error(`proposal: validation refused (${[...new Set(preview.issues.filter(issue => issue.severity === "error").map(issue => issue.code))].join(", ") || "unknown"}); correct the proposal and retry`);
114
+ if (preview.changes.length !== 1 || preview.changes[0]!.beforeSha === preview.changes[0]!.sha256) throw new Error("proposal: operation produces no note change; revise the proposal before submitting");
115
+ const createdAt = (options.now ?? new Date()).toISOString();
116
+ const record: ProposalRecord = { schemaVersion: 1, id: randomUUID(), vault: vault.id, bindingDigest, state: "pending", createdAt, updatedAt: createdAt, operation, payloadDigest: proposalPayloadDigest(operation), ...(request.agentLabel !== undefined ? { agentLabel: request.agentLabel } : {}) };
117
+ encodeProposalRecord(record);
118
+ const placeholder = "0".repeat(64);
119
+ encodeProposalRecord({ ...record, state: "applied", intent: { fingerprint: placeholder, beforeSha: placeholder, afterSha: placeholder }, receipt: { applied: true, logged: false, beforeSha: placeholder, afterSha: placeholder } });
120
+ let evidence: WriteIssue[];
121
+ try { evidence = evidenceWarnings(home, operation, context); }
122
+ catch (error) {
123
+ const message = error instanceof Error ? error.message : "";
124
+ const cause = /denied/i.test(message) ? "the target or evidence path is denied; inspect the vault deny paths" : /binding|policy/i.test(message) ? "the vault binding or policy changed; inspect the registered vault" : /changed during read/i.test(message) ? "the patch target changed while being read; stop concurrent edits and inspect the target note" : /missing|unavailable/i.test(message) ? "the patch target is unavailable; restore or inspect the target note" : "the target evidence could not be read; inspect the target note";
125
+ throw new Error(`proposal submit: ${cause}, then submit again`, { cause: error });
126
+ }
127
+ const issues: WriteIssue[] = warningsOf(screen, preview.issues, evidence);
128
+ const lock = join(home, LOCK_FILE);
129
+ if (isDenied(lock, config.denyPaths ?? [])) throw new Error("proposal: registry lock path is denied; inspect the configured deny paths");
130
+ let fd: number;
131
+ try { fd = openSync(lock, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
132
+ catch { throw new Error("proposal: registry lock is unavailable; stop concurrent registry updates and inspect the lock"); }
133
+ let attempted = false, stored: boolean | null = false, primary: unknown;
134
+ try {
135
+ writeFileSync(fd, JSON.stringify({ pid: process.pid, host: hostname(), created: new Date().toISOString() }) + "\n"); fsyncSync(fd);
136
+ if (!matchesBinding(loadRegistry(home), vault.id, binding)) throw new Error("proposal: vault binding or policy changed during submit; request a new preview");
137
+ const bindingIssues: WriteIssue[] = [];
138
+ checkStoredBinding(home, vault.id, bindingDigest, config.denyPaths ?? [], bindingIssues);
139
+ issues.push(...warningsOf(bindingIssues));
140
+ attempted = true; stored = null;
141
+ try { createStoredProposal(home, record, config.denyPaths ?? [], fd); stored = true; }
142
+ catch (error) {
143
+ try { stored = proposalRecordDigest(readStoredProposal(home, bindingDigest, record.id, config.denyPaths ?? [])) === proposalRecordDigest(record); }
144
+ catch (readError) { stored = (readError as NodeJS.ErrnoException).code === "ENOENT" ? false : null; }
145
+ primary = error;
146
+ }
147
+ if (stored && !matchesBinding(loadRegistry(home), vault.id, binding)) issues.push({ code: "VAULT_DRIFT", severity: "error", message: "proposal was stored but the vault binding or policy changed; inspect the proposal store and current policy" });
148
+ } catch (error) { primary = error; }
149
+ finally {
150
+ try { cleanupOwnedFile(lock, fd); } catch { issues.push({ code: "CLEANUP", severity: "error", message: "proposal registry lock cleanup failed; inspect the lock before retrying" }); }
151
+ finally { try { closeSync(fd); } catch { issues.push({ code: "CLEANUP", severity: "error", message: "proposal registry lock descriptor close failed; inspect the lock before retrying" }); } }
152
+ }
153
+ if (!attempted && primary) throw primary;
154
+ if (primary) issues.push({ code: "PROPOSAL_STORE", severity: "error", message: stored === true ? `proposal was stored but finalization failed: ${storageFailure(primary)}` : stored === false ? `proposal was not stored: ${storageFailure(primary)}` : `proposal storage outcome is unknown: ${storageFailure(primary)}; inspect the proposal store before retrying` });
155
+ let current = false;
156
+ try { current = matchesBinding(loadRegistry(home), vault.id, binding); } catch { /* Unavailable policy cannot authorize disclosure. */ }
157
+ if (!current) issues.push({ code: "VAULT_DRIFT", severity: "error", message: "vault binding or policy changed during submission; inspect the registered vault and proposal store" });
158
+ return { ok: stored === true && issues.every(issue => issue.severity !== "error"), stored, id: record.id, vault: record.vault, path: current ? operation.path : null, state: stored ? "pending" : null, createdAt, payloadDigest: current ? record.payloadDigest : null, issues: current ? issues : issues.filter(issue => issue.severity === "error") };
159
+ }
160
+
161
+ /** Returns screened summaries, examining at most 512 records per call. The cursor is a record id, never a path. */
162
+ export function listProposals(home: string, request: ProposalListRequest, options: ProposalContext): ProposalPage {
163
+ if (!request || typeof request !== "object" || Object.keys(request).some(key => !["vault", "state", "limit", "after"].includes(key)) || typeof request.vault !== "string") throw new Error("proposal: invalid list request; provide a registered vault");
164
+ const limit = request.limit ?? 50, state = request.state ?? "pending";
165
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !["pending", "applied", "rejected", "apply_unknown"].includes(state) || (request.after !== undefined && !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(request.after)))
166
+ throw new Error("proposal: invalid list state, cursor or limit; use a returned cursor and limit 1..100");
167
+ const context = currentBinding(home, request.vault, options);
168
+ const storageIssues: WriteIssue[] = [];
169
+ if (!checkStoredBinding(home, context.vault.id, context.bindingDigest, context.config.denyPaths ?? [], storageIssues)) {
170
+ if (!matchesBinding(loadRegistry(home), context.vault.id, context.binding)) throw new Error("proposal: vault binding or policy changed during listing; retry with the current policy");
171
+ return { items: [], nextCursor: null, issues: warningsOf(storageIssues) };
172
+ }
173
+ const ids = listStoredProposalIds(home, context.bindingDigest, context.config.denyPaths ?? [], storageIssues).filter(id => request.after === undefined || id > request.after);
174
+ const items: ProposalSummary[] = [], warningGroups: WriteIssue[][] = [storageIssues]; let scanned = 0, cursor: string | null = null;
175
+ for (const id of ids) {
176
+ if (scanned >= 512 || items.length >= limit) break;
177
+ scanned++; cursor = id;
178
+ try {
179
+ const record = readStoredProposal(home, context.bindingDigest, id, context.config.denyPaths ?? []);
180
+ if (record.state !== state) continue;
181
+ warningGroups.push(screenForRead(record, context).issues);
182
+ items.push({ id: record.id, vault: record.vault, path: record.operation.path, state: record.state, createdAt: record.createdAt });
183
+ } catch (error) {
184
+ const message = error instanceof Error ? error.message : "";
185
+ const cause = /denied|policy refuses/i.test(message) ? "denied by current policy; inspect the proposal policy" : /linked/i.test(message) ? "linked or publication in progress; retry after concurrent writes finish, then inspect the proposal store" : "corrupt or unavailable; inspect the proposal store";
186
+ warningGroups.push([{ code: "PROPOSAL_SKIPPED", severity: "warning", message: `proposal ${id}: ${cause}` }]);
187
+ }
188
+ }
189
+ if (!matchesBinding(loadRegistry(home), context.vault.id, context.binding)) throw new Error("proposal: vault binding or policy changed during listing; retry with the current policy");
190
+ return { items, nextCursor: scanned < ids.length ? cursor : null, issues: warningsOf(...warningGroups) };
191
+ }
192
+
193
+ /** Pages the normalized operation as UTF-8 text without splitting a code point or exceeding the encoded MCP reply cap. */
194
+ export function showProposal(home: string, request: ProposalShowRequest, options: ProposalContext): ProposalView {
195
+ if (!request || typeof request !== "object" || Object.keys(request).some(key => !["vault", "id", "offset", "maxBytes"].includes(key)) || typeof request.vault !== "string" || typeof request.id !== "string")
196
+ throw new Error("proposal: invalid show request; provide a vault and proposal id");
197
+ const offset = request.offset ?? 0, maxBytes = request.maxBytes ?? MAX_SHOW_BYTES;
198
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_SHOW_BYTES)
199
+ throw new Error("proposal: invalid show offset or page size; use a returned offset and maxBytes 1..16384");
200
+ const context = currentBinding(home, request.vault, options);
201
+ requireCurrentStore(home, context);
202
+ const record = readStoredProposal(home, context.bindingDigest, request.id, context.config.denyPaths ?? []);
203
+ const screened = screenForRead(record, context), issues = screened.issues;
204
+ const serialized = JSON.stringify(record.operation), bytes = Buffer.from(serialized, "utf8");
205
+ if (offset > bytes.length || !Buffer.from(bytes.subarray(0, offset).toString("utf8"), "utf8").equals(bytes.subarray(0, offset)))
206
+ throw new Error("proposal: offset is outside the payload or splits a UTF-8 character; use the returned nextOffset");
207
+ const chars = Array.from(bytes.subarray(offset).toString("utf8"));
208
+ const view = (count: number): ProposalView => {
209
+ const content = chars.slice(0, count).join(""), end = offset + Buffer.byteLength(content, "utf8"), more = end < bytes.length;
210
+ return { id: record.id, vault: record.vault, state: record.state, path: record.operation.path, createdAt: record.createdAt, payloadDigest: record.payloadDigest,
211
+ ...(record.agentLabel !== undefined ? { agentLabelUnverified: record.agentLabel } : {}), ...(screened.reason !== undefined ? { decisionReason: screened.reason } : {}),
212
+ content, offset, nextOffset: more ? end : null, truncated: more, issues };
213
+ };
214
+ let low = 0, high = chars.length;
215
+ while (low < high) {
216
+ const middle = Math.ceil((low + high) / 2), candidate = view(middle);
217
+ if (Buffer.byteLength(candidate.content, "utf8") <= maxBytes && proposalReplyBytes(candidate) <= MAX_RPC_REPLY_BYTES) low = middle;
218
+ else high = middle - 1;
219
+ }
220
+ const result = view(low);
221
+ if (proposalReplyBytes(result) > MAX_RPC_REPLY_BYTES || (low === 0 && chars.length > 0)) throw new Error("proposal: page cannot fit the requested bounds; increase maxBytes or inspect the record");
222
+ if (!matchesBinding(loadRegistry(home), context.vault.id, context.binding)) throw new Error("proposal: vault binding or policy changed during read; retry with the current policy");
223
+ return result;
224
+ }
225
+
226
+ /** Produce a read-only preview whose fingerprint binds the current writer plan and exact record. */
227
+ export function previewProposalApply(home: string, request: { vault: string; id: string }, options: ProposalContext): ProposalApplyPreview {
228
+ if (!request || typeof request !== "object" || Object.keys(request).some(key => !["vault", "id"].includes(key)) || typeof request.vault !== "string" || typeof request.id !== "string")
229
+ throw new Error("proposal: invalid apply preview request; provide a vault and proposal id");
230
+ const context = currentBinding(home, request.vault, options);
231
+ requireCurrentStore(home, context);
232
+ const record = readStoredProposal(home, context.bindingDigest, request.id, context.config.denyPaths ?? []);
233
+ const warnings = screenForRead(record, context).issues;
234
+ if (record.state !== "pending") throw new Error(`proposal: ${record.state === "apply_unknown" ? "apply outcome is unknown; reconcile before another decision" : "proposal is no longer pending; inspect the proposal"}`);
235
+ const recordDigest = proposalRecordDigest(record);
236
+ const preview = applyWrite(home, { vault: record.vault, operation: record.operation, channel: options.channel, dryRun: true }, { binding: context.binding, env: options.env, now: options.now });
237
+ if (!preview.ok || !preview.fingerprint) throw new Error(`proposal: apply preview refused (${[...new Set(preview.issues.filter(issue => issue.severity === "error").map(issue => issue.code))].join(", ") || "unknown"}); correct the vault or proposal and retry`);
238
+ if (preview.changes.length !== 1) throw new Error("proposal: apply preview is not a single note change; inspect the proposal");
239
+ if (!matchesBinding(loadRegistry(home), context.vault.id, context.binding) || proposalRecordDigest(readStoredProposal(home, context.bindingDigest, record.id, context.config.denyPaths ?? [])) !== recordDigest)
240
+ throw new Error("proposal: record, vault binding or policy changed during preview; request a new preview");
241
+ return { id: record.id, vault: record.vault, state: "pending", fingerprint: proposalDecisionFingerprint(recordDigest, preview.fingerprint, "apply"), changes: preview.changes, issues: [...preview.issues, ...warningsOf(warnings, evidenceWarnings(home, record.operation, context))] };
242
+ }
243
+
244
+ /** Preview a rejection without changing the proposal, notes, graph or log. */
245
+ export function previewProposalReject(home: string, request: { vault: string; id: string; reason: string }, options: ProposalContext): ProposalRejectPreview {
246
+ if (!request || typeof request !== "object" || Object.keys(request).some(key => !["vault", "id", "reason"].includes(key)) || typeof request.vault !== "string" || typeof request.id !== "string" || typeof request.reason !== "string" || !request.reason.trim() || Buffer.byteLength(request.reason, "utf8") > 4096)
247
+ throw new Error("proposal: rejection requires a nonempty reason of at most 4096 bytes; provide a reason and preview again");
248
+ const context = currentBinding(home, request.vault, options);
249
+ requireCurrentStore(home, context);
250
+ const record = readStoredProposal(home, context.bindingDigest, request.id, context.config.denyPaths ?? []);
251
+ if (record.vault !== context.vault.id) throw new Error("proposal: stored vault binding is invalid; inspect the proposal store");
252
+ if (record.state !== "pending") throw new Error(`proposal: ${record.state === "apply_unknown" ? "apply outcome is unknown; reconcile before another decision" : "proposal is no longer pending; inspect the proposal"}`);
253
+ const reasonIssues = screenMetadata({ reason: request.reason }, { vault: context.vault, config: context.config }, record.operation.path);
254
+ if (reasonIssues.some(issue => issue.severity === "error"))
255
+ throw new Error("proposal: current policy refuses the rejection reason; remove prohibited content or inspect the vault policy");
256
+ prepareRejectedProposal(record, request.reason, (options.now ?? new Date()).toISOString());
257
+ const recordDigest = proposalRecordDigest(record), plan = proposalRejectionPlan(home, record.vault, options.channel, context.binding, record.operation.path);
258
+ if (!bindingStillCurrent(home, context) || proposalRecordDigest(readStoredProposal(home, context.bindingDigest, record.id, context.config.denyPaths ?? [])) !== recordDigest)
259
+ throw new Error("proposal: record, vault binding or policy changed during preview; request a new preview");
260
+ return { id: record.id, vault: record.vault, state: "pending", reason: request.reason, fingerprint: proposalDecisionFingerprint(recordDigest, plan, "reject", request.reason), issues: warningsOf(reasonIssues) };
261
+ }
262
+
263
+ /** Confirm a rejection using a freshly recomputed plan while holding the vault's mutation lock. */
264
+ export function rejectProposal(home: string, request: { vault: string; id: string; reason: string; fingerprint: string }, options: ProposalContext): ProposalRejectReceipt {
265
+ if (!request || typeof request !== "object" || Object.keys(request).some(key => !["vault", "id", "reason", "fingerprint"].includes(key)) || typeof request.vault !== "string" || typeof request.id !== "string" || typeof request.reason !== "string" || !request.reason.trim() || Buffer.byteLength(request.reason, "utf8") > 4096 || typeof request.fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(request.fingerprint))
266
+ throw new Error("proposal: invalid rejection confirmation; use the reason and fingerprint from a fresh preview");
267
+ const context = currentBinding(home, request.vault, options);
268
+ requireCurrentStore(home, context);
269
+ const record = readStoredProposal(home, context.bindingDigest, request.id, context.config.denyPaths ?? []);
270
+ if (record.vault !== context.vault.id) throw new Error("proposal: stored vault binding is invalid; inspect the proposal store");
271
+ if (record.state !== "pending") throw new Error(`proposal: ${record.state === "apply_unknown" ? "apply outcome is unknown; reconcile before another decision" : "proposal is no longer pending; inspect the proposal"}`);
272
+ const result = rejectProposalWrite(home, record.vault, options.channel, context.binding, { id: record.id, bindingDigest: context.bindingDigest, recordDigest: proposalRecordDigest(record), fingerprint: request.fingerprint, reason: request.reason }, options.now);
273
+ if (!bindingStillCurrent(home, context)) return { ok: false, rejected: result.rejected, issues: [{ code: "VAULT_DRIFT", severity: "error", message: `vault binding or policy changed${result.rejected ? " after rejection was recorded" : ""}; inspect the registered vault and proposal` }] };
274
+ return result;
275
+ }
276
+
277
+ /** Confirm through the existing writer; an applied note remains applied even if logging or receipt persistence fails. */
278
+ export function applyProposal(home: string, request: { vault: string; id: string; fingerprint: string }, options: ProposalContext): ProposalApplyResult {
279
+ if (!request || typeof request !== "object" || Object.keys(request).some(key => !["vault", "id", "fingerprint"].includes(key)) || typeof request.vault !== "string" || typeof request.id !== "string" || typeof request.fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(request.fingerprint))
280
+ throw new Error("proposal: invalid apply confirmation; use the fingerprint returned by a fresh preview");
281
+ const context = currentBinding(home, request.vault, options);
282
+ requireCurrentStore(home, context);
283
+ const record = readStoredProposal(home, context.bindingDigest, request.id, context.config.denyPaths ?? []);
284
+ const warnings = screenForRead(record, context).issues;
285
+ if (record.state !== "pending") throw new Error(`proposal: ${record.state === "apply_unknown" ? "apply outcome is unknown; reconcile before another decision" : "proposal is no longer pending; inspect the proposal"}`);
286
+ const receipt = applyProposalWrite(home, { vault: record.vault, operation: record.operation, channel: options.channel }, {
287
+ binding: context.binding, env: options.env, now: options.now,
288
+ proposal: { id: record.id, bindingDigest: context.bindingDigest, recordDigest: proposalRecordDigest(record), fingerprint: request.fingerprint },
289
+ });
290
+ const logged = receipt.logged === true ? true : receipt.logged === false ? false : null;
291
+ const applied = receipt.applied ? true : receipt.proposalState === "apply_unknown" && receipt.proposalPublicationStarted ? null : false;
292
+ if (!bindingStillCurrent(home, context)) return { ok: false, applied, state: receipt.proposalState === "applied" ? "applied" : "apply_unknown", logged, issues: [{ code: "VAULT_DRIFT", severity: "error", message: "vault binding or policy changed after the decision; inspect the registered vault and proposal" }] };
293
+ return { ok: receipt.ok && (!receipt.applied || logged !== false), applied, state: receipt.proposalState, logged, issues: [...receipt.issues, ...(receipt.log?.issues ?? []), ...warnings] };
294
+ }
295
+
296
+ /** Compare recorded intent to the current target without inferring attribution or changing state. */
297
+ export function reconcileProposal(home: string, request: { vault: string; id: string }, options: ProposalContext): ProposalReconciliation {
298
+ if (!request || typeof request !== "object" || Object.keys(request).some(key => !["vault", "id"].includes(key)) || typeof request.vault !== "string" || typeof request.id !== "string")
299
+ throw new Error("proposal: invalid reconciliation request; provide a vault and proposal id");
300
+ const context = currentBinding(home, request.vault, options);
301
+ requireCurrentStore(home, context);
302
+ const record = readStoredProposal(home, context.bindingDigest, request.id, context.config.denyPaths ?? []);
303
+ const warnings = screenForRead(record, context).issues;
304
+ if (record.state !== "apply_unknown" || !record.intent) throw new Error("proposal: reconciliation needs an uncertain apply; inspect the proposal state");
305
+ const recordDigest = proposalRecordDigest(record), observedSha = proposalTargetDigest(home, record.vault, record.operation.path, context.binding);
306
+ const evidence = readStoredEvidence(home, context.bindingDigest, record.id, record.intent.fingerprint, context.config.denyPaths ?? []);
307
+ if (evidence && (evidence.beforeSha !== record.intent.beforeSha || evidence.afterSha !== record.intent.afterSha)) throw new Error("proposal: execution evidence does not match the intent; inspect the proposal store");
308
+ const proposedState = evidence?.applied && evidence.publicationStarted && observedSha === record.intent.afterSha ? "applied" : evidence && !evidence.applied && !evidence.publicationStarted && observedSha === record.intent.beforeSha ? "pending" : null;
309
+ const plan = proposedState ? proposalRejectionPlan(home, record.vault, options.channel, context.binding, record.operation.path) : undefined;
310
+ const evidenceDigest = evidence ? proposalEvidenceDigest(evidence) : undefined;
311
+ if (!bindingStillCurrent(home, context) || proposalRecordDigest(readStoredProposal(home, context.bindingDigest, record.id, context.config.denyPaths ?? [])) !== recordDigest)
312
+ throw new Error("proposal: record, vault binding or policy changed during reconciliation; retry with the current policy");
313
+ if (evidenceDigest) {
314
+ const fresh = readStoredEvidence(home, context.bindingDigest, record.id, record.intent.fingerprint, context.config.denyPaths ?? []);
315
+ if (!fresh || proposalEvidenceDigest(fresh) !== evidenceDigest || proposalTargetDigest(home, record.vault, record.operation.path, context.binding) !== observedSha)
316
+ throw new Error("proposal: execution evidence or target changed during reconciliation; request a new preview");
317
+ }
318
+ return { id: record.id, vault: record.vault, state: "apply_unknown", beforeSha: record.intent.beforeSha, afterSha: record.intent.afterSha, observedSha,
319
+ matchesBefore: observedSha === record.intent.beforeSha, matchesAfter: observedSha === record.intent.afterSha, receiptEvidence: evidence ? "available" : "unavailable", proposedState,
320
+ fingerprint: proposedState && evidenceDigest && plan ? proposalReconcileFingerprint(recordDigest, evidenceDigest, plan, proposedState) : null,
321
+ explanation: proposedState ? `A durable writer receipt matches the current target; confirm the fingerprint to record ${proposedState}.` : "Matching content alone does not prove this proposal published it; inspect independent receipt evidence before any manual recovery.", issues: warnings };
322
+ }
323
+ /** Confirm only a receipt-backed reconciliation preview; matching content alone is never sufficient. */
324
+ export function confirmProposalReconciliation(home: string, request: { vault: string; id: string; fingerprint: string }, options: ProposalContext): ProposalReconcileReceipt {
325
+ if (!request || typeof request !== "object" || Object.keys(request).some(key => !["vault", "id", "fingerprint"].includes(key)) || typeof request.vault !== "string" || typeof request.id !== "string" || typeof request.fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(request.fingerprint))
326
+ throw new Error("proposal: invalid reconciliation confirmation; use the fingerprint from a fresh preview");
327
+ const preview = reconcileProposal(home, { vault: request.vault, id: request.id }, options);
328
+ if (!preview.fingerprint || preview.fingerprint !== request.fingerprint) throw new Error("proposal: reconciliation evidence is unavailable or changed; inspect the proposal and request a new preview");
329
+ const context = currentBinding(home, request.vault, options);
330
+ requireCurrentStore(home, context);
331
+ const record = readStoredProposal(home, context.bindingDigest, request.id, context.config.denyPaths ?? []);
332
+ const result = reconcileProposalWrite(home, record.vault, options.channel, context.binding, { id: record.id, bindingDigest: context.bindingDigest, recordDigest: proposalRecordDigest(record), fingerprint: request.fingerprint }, options.now);
333
+ if (!bindingStillCurrent(home, context)) return { ok: false, resolved: result.resolved, state: result.resolved ? result.state : "apply_unknown", issues: [{ code: "VAULT_DRIFT", severity: "error", message: "vault binding or policy changed during reconciliation; inspect the registered vault and proposal" }] };
334
+ return { ...result, issues: [...result.issues, ...preview.issues] };
335
+ }