@staix/vault-mem 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +19 -6
  3. package/bin/vmem.js +2 -2
  4. package/package.json +2 -2
  5. package/src/analysis-commands.ts +24 -14
  6. package/src/analysis-input.ts +12 -0
  7. package/src/analysis-types.ts +5 -1
  8. package/src/assert-command.ts +48 -0
  9. package/src/assertion-exposure.ts +367 -0
  10. package/src/assertion-index.ts +86 -0
  11. package/src/assertion-policy.ts +63 -0
  12. package/src/assertion-read.ts +170 -0
  13. package/src/assertions-command.ts +123 -0
  14. package/src/assertions.ts +1013 -0
  15. package/src/cli-output.ts +9 -3
  16. package/src/cli.ts +44 -23
  17. package/src/commands-table.ts +16 -2
  18. package/src/evidence.ts +222 -0
  19. package/src/graph-evidence.ts +169 -0
  20. package/src/index.ts +14 -0
  21. package/src/links.ts +18 -0
  22. package/src/log-commands.ts +7 -7
  23. package/src/mcp-spec.ts +11 -11
  24. package/src/mcp-vault.ts +105 -6
  25. package/src/mcp.ts +4 -0
  26. package/src/org-commands.ts +5 -5
  27. package/src/org-promote.ts +9 -0
  28. package/src/promote-command.ts +6 -6
  29. package/src/proposal-commands.ts +100 -0
  30. package/src/proposal-provider.ts +335 -0
  31. package/src/proposal-storage.ts +334 -0
  32. package/src/proposals.ts +170 -0
  33. package/src/read-commands.ts +44 -12
  34. package/src/read-output.ts +42 -14
  35. package/src/skills-mine.ts +12 -7
  36. package/src/source-age.ts +131 -0
  37. package/src/spec-output.ts +14 -13
  38. package/src/sync.ts +14 -7
  39. package/src/text-output.ts +86 -21
  40. package/src/vault-brief.ts +8 -4
  41. package/src/vault-graph.ts +12 -3
  42. package/src/vault-history.ts +662 -0
  43. package/src/vault-index.ts +2 -0
  44. package/src/vault-lint.ts +15 -4
  45. package/src/write-commands.ts +18 -17
  46. package/src/write-output.ts +6 -6
  47. package/src/write-types.ts +1 -0
  48. package/src/write-validation.ts +3 -1
  49. package/src/writer.ts +257 -11
@@ -0,0 +1,169 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { AnalysisSnapshot } from "./analysis-types.ts";
3
+ import { authoredLinkOffsets, noteKey } from "./links.ts";
4
+ import { buildGraph, codePointCompare, graphBody, graphPath, legacyTarget, linkRelation, LEGACY_LINK, type GraphEdge, type GraphPathOptions } from "./vault-graph.ts";
5
+
6
+ /** Occurrences kept per hop, and the bound on the complete encoded result (envelope and escaping included). */
7
+ export const EXPLAIN_OCCURRENCES_PER_HOP = 20, EXPLAIN_MAX_BYTES = 48 * 1024;
8
+ const MAX_TEXT_BYTES = 512;
9
+ /** Identifies the path selection the snapshot hash covers; bump it if graphPath's selection ever changes. */
10
+ const ALGORITHM = "graph-path-bfs-codepoint-v1";
11
+
12
+ export interface GraphOccurrence {
13
+ /**
14
+ * `legacy_graph_match`: the body match `buildGraph` turned into this hop's edge. `annotation`: a heading/block-anchored
15
+ * or frontmatter reference between the same notes; it explains context but never adds a traversable edge.
16
+ */
17
+ kind: "legacy_graph_match" | "annotation";
18
+ /** True when `extractLinks` also accepts it as an authored link (visible, not escaped, not in code). */
19
+ authored: boolean;
20
+ origin: { path: string; sha256: string };
21
+ /** One-based line in the whole note file, and the zero-based UTF-8 byte range of the link text in the file. */
22
+ line: number;
23
+ bytes: { start: number; end: number };
24
+ /** `body` or `frontmatter`, with the frontmatter key in `field`. */
25
+ source: "body" | "frontmatter";
26
+ field?: string;
27
+ /** The declared `(relation)` of a typed list link, else `wiki_link`. */
28
+ relation: string;
29
+ /** As written: the note that contains the link, and the note it names. */
30
+ authoredFrom: string;
31
+ authoredTo: string;
32
+ /** `forward` when the path walks from the authoring note to the named note; `reverse` when it walks against the link. */
33
+ traversal: "forward" | "reverse";
34
+ anchor?: { heading?: string; block?: string };
35
+ embed?: true;
36
+ /** The literal link text, at most 512 bytes. */
37
+ text: string;
38
+ }
39
+ export interface GraphHop {
40
+ index: number;
41
+ from: string;
42
+ to: string;
43
+ /** The deduplicated graph edge this hop used: structural metadata only, never a quote or a probability. */
44
+ edge: { kind: "structural"; relation: GraphEdge["relation"]; rel?: string; field: "body" };
45
+ occurrences: GraphOccurrence[];
46
+ /** Occurrences found for this pair that the per-hop or byte bound left out. */
47
+ omitted: number;
48
+ }
49
+ export interface GraphExplanation {
50
+ schemaVersion: 1;
51
+ /** sha256 over sorted note paths with their content hashes and the path options: a content identity, not a signature. */
52
+ snapshotHash: string;
53
+ path: { from: string; to: string; found: boolean; length: number; nodes: string[]; options: { maxHops: number; relation: string | null; viaHubs: boolean } };
54
+ hops: GraphHop[];
55
+ structuralOnly: true;
56
+ truncated: boolean;
57
+ limits: { occurrencesPerHop: number; maxBytes: number };
58
+ }
59
+
60
+ const sha = (text: string) => createHash("sha256").update(text).digest("hex");
61
+ const bytes = (text: string) => Buffer.byteLength(text);
62
+ const stemOf = (path: string) => path.replace(/^notes\//, "").slice(0, -3);
63
+ function bounded(text: string): string {
64
+ if (bytes(text) <= MAX_TEXT_BYTES) return text;
65
+ let out = "";
66
+ for (const character of text) { if (bytes(out + character) > MAX_TEXT_BYTES - 3) break; out += character; }
67
+ return out + "...";
68
+ }
69
+
70
+ /** A match found by the cheap pass: its position and fields, before any line or byte location is computed. */
71
+ interface Candidate { self: string; other: string; at: number; length: number; fields: Omit<GraphOccurrence, "origin" | "authoredFrom" | "authoredTo" | "traversal" | "line" | "bytes"> }
72
+ /** True when an annotation address names `other`: by the navigation note key (`b.md`, `notes/b`) or the legacy stem rule. */
73
+ const names = (address: string, other: string) => noteKey(address) === noteKey(other) || legacyTarget(address) === other;
74
+ /**
75
+ * Every body match and annotation between `a` and `b` in the notes `a` and `b`, sorted (forward author first, then
76
+ * note, then file position). Only positions are collected here; locations are computed later for the kept ones.
77
+ */
78
+ function candidates(notes: Map<string, { source: string; sha256: string }>, a: string, b: string, from: string): Candidate[] {
79
+ const out: Candidate[] = [];
80
+ for (const [self, other] of [[a, b], [b, a]] as const) {
81
+ const note = notes.get(self);
82
+ if (!note) continue;
83
+ const { body, offset } = graphBody(note.source), authored = authoredLinkOffsets(body), legacy = new Set<number>();
84
+ for (const match of body.matchAll(LEGACY_LINK)) {
85
+ if (legacyTarget(match[1]!) !== other) continue;
86
+ legacy.add(match.index);
87
+ const link = authored.get(match.index), rel = linkRelation(body, match.index, match[0].length);
88
+ out.push({ self, other, at: offset + match.index, length: match[0].length,
89
+ fields: { kind: "legacy_graph_match", authored: link !== undefined, source: "body", relation: rel ?? "wiki_link", ...(link?.embed ? { embed: true } : {}), text: bounded(match[0]) } });
90
+ }
91
+ // Authored anchored links never become legacy edges ("x#h" is not a stem), so they annotate only.
92
+ for (const [index, link] of authored) {
93
+ if (legacy.has(index) || (!link.heading && !link.block) || !names(link.target, other)) continue;
94
+ const end = body.indexOf("]]", index) + 2;
95
+ out.push({ self, other, at: offset + index, length: end - index, fields: { kind: "annotation", authored: true, source: "body", relation: linkRelation(body, index, end - index) ?? "wiki_link",
96
+ anchor: { ...(link.heading ? { heading: link.heading } : {}), ...(link.block ? { block: link.block } : {}) }, ...(link.embed ? { embed: true } : {}), text: bounded(body.slice(index, end)) } });
97
+ }
98
+ // Frontmatter references annotate the pair; the legacy graph never makes edges from them.
99
+ let field: string | undefined, lineStart = 0;
100
+ for (const line of note.source.slice(0, offset).split("\n")) {
101
+ const key = /^([A-Za-z_][\w-]*)\s*:/.exec(line);
102
+ if (key) field = key[1];
103
+ for (const match of line.matchAll(/\[\[([^\]|#\n]+)(?:[#|][^\]\n]*)?\]\]/g)) if (field && names(match[1]!.trim(), other))
104
+ out.push({ self, other, at: lineStart + match.index, length: match[0].length, fields: { kind: "annotation", authored: false, source: "frontmatter", field, relation: "wiki_link", text: bounded(match[0]) } });
105
+ lineStart += line.length + 1;
106
+ }
107
+ }
108
+ const rank = (c: Candidate) => c.self === from ? 0 : 1;
109
+ return out.sort((x, y) => rank(x) - rank(y) || codePointCompare(x.self, y.self) || x.at - y.at);
110
+ }
111
+ /** Locations for the kept candidates only: one forward walk per note over the sorted positions, so the cost is linear. */
112
+ function locate(notes: Map<string, { source: string; sha256: string }>, kept: Candidate[], from: string): GraphOccurrence[] {
113
+ const located = new Map<Candidate, { line: number; start: number; end: number }>();
114
+ for (const self of new Set(kept.map(c => c.self))) {
115
+ const source = notes.get(self)!.source, mine = kept.filter(c => c.self === self).sort((x, y) => x.at - y.at);
116
+ let at = 0, line = 1, byte = 0;
117
+ for (const c of mine) {
118
+ for (let i = source.indexOf("\n", at); i !== -1 && i < c.at; i = source.indexOf("\n", i + 1)) line++;
119
+ byte += bytes(source.slice(at, c.at)); at = c.at;
120
+ located.set(c, { line, start: byte, end: byte + bytes(source.slice(c.at, c.at + c.length)) });
121
+ }
122
+ }
123
+ return kept.map(c => {
124
+ const where = located.get(c)!, note = notes.get(c.self)!;
125
+ return { ...c.fields, origin: { path: `notes/${c.self}.md`, sha256: note.sha256 }, line: where.line, bytes: { start: where.start, end: where.end },
126
+ authoredFrom: c.self, authoredTo: c.other, traversal: c.self === from ? "forward" : "reverse" } as GraphOccurrence;
127
+ });
128
+ }
129
+ /**
130
+ * Bytes of the largest encoding a caller receives: the MCP JSON-RPC response wrapping the result as text content (a
131
+ * superset of the CLI `--json` line), with room for a request id of up to ENVELOPE_ID_BYTES.
132
+ */
133
+ const ENVELOPE_ID_BYTES = 128;
134
+ export function encodedBytes(result: GraphExplanation): number {
135
+ return bytes(JSON.stringify({ jsonrpc: "2.0", id: "x".repeat(ENVELOPE_ID_BYTES), result: { content: [{ type: "text", text: JSON.stringify(result) }] } })) + 1;
136
+ }
137
+
138
+ /**
139
+ * Explain `graphPath`'s selected path from the same snapshot: the path is chosen by `graphPath` itself, then each hop
140
+ * lists the source occurrences behind its edge. Pure and deterministic: the same snapshot and options give
141
+ * byte-identical JSON. Reads nothing beyond the snapshot and writes nothing.
142
+ */
143
+ export function explainGraphPath(snapshot: AnalysisSnapshot, from: string, to: string, options: GraphPathOptions = {}): GraphExplanation {
144
+ const maxHops = options.maxHops ?? 6, relation = options.relation ?? null, viaHubs = options.viaHubs === true;
145
+ const graph = buildGraph(snapshot), path = graphPath(graph, from, to, options);
146
+ // Snapshot paths are relative to notes/ ("stem.md"), as buildGraph reads them.
147
+ const notes = new Map(snapshot.notes.map(note => [stemOf(note.path), { source: note.source, sha256: sha(note.source) }]));
148
+ const identity = [...notes].sort(([a], [b]) => codePointCompare(a, b)).map(([stem, note]) => [stem, note.sha256]);
149
+ const snapshotHash = sha(JSON.stringify({ algorithm: ALGORITHM, notes: identity, options: { maxHops, relation, viaHubs } }));
150
+ const hops: GraphHop[] = path.edges.map((edge, index) => {
151
+ const found = candidates(notes, edge.source, edge.target, edge.source);
152
+ return { index, from: edge.source, to: edge.target, edge: { kind: "structural", relation: edge.relation, ...(edge.rel ? { rel: edge.rel } : {}), field: "body" },
153
+ occurrences: locate(notes, found.slice(0, EXPLAIN_OCCURRENCES_PER_HOP), edge.source), omitted: Math.max(0, found.length - EXPLAIN_OCCURRENCES_PER_HOP) };
154
+ });
155
+ const result: GraphExplanation = { schemaVersion: 1, snapshotHash,
156
+ path: { from: path.from, to: path.to, found: path.found, length: path.length, nodes: path.nodes.map(node => node.id), options: { maxHops, relation, viaHubs } },
157
+ hops, structuralOnly: true, truncated: hops.some(hop => hop.omitted > 0), limits: { occurrencesPerHop: EXPLAIN_OCCURRENCES_PER_HOP, maxBytes: EXPLAIN_MAX_BYTES } };
158
+ // Byte bound on the complete encoded output (envelope and escaping): drop occurrences from the last hop backwards
159
+ // until it fits; every drop is counted. Setting `truncated` first keeps the measured size an upper bound.
160
+ if (encodedBytes(result) > EXPLAIN_MAX_BYTES) {
161
+ result.truncated = true;
162
+ for (let i = hops.length - 1; i >= 0 && encodedBytes(result) > EXPLAIN_MAX_BYTES; i--) {
163
+ const hop = hops[i]!;
164
+ while (hop.occurrences.length && encodedBytes(result) > EXPLAIN_MAX_BYTES) { hop.occurrences.pop(); hop.omitted++; }
165
+ }
166
+ if (encodedBytes(result) > EXPLAIN_MAX_BYTES) throw Object.assign(new Error(`graph explain: path metadata alone exceeds ${EXPLAIN_MAX_BYTES} bytes; lower --max-hops`), { code: "V09" });
167
+ }
168
+ return result;
169
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export { readAssertions, ASSERTIONS_PAGE_LIMIT } from "./assertion-read.ts";
2
+ export type { AssertionsReadRequest, AssertionsReadResult, AssertionsReadOptions } from "./assertion-read.ts";
1
3
  export { resolveHome } from "./home.ts";
2
4
  export { parseConfig, parseVault, parseSpec, readConfig, CONFIG_FILE, MAX_CONFIG_BYTES } from "./config.ts";
3
5
  export type { VaultSpec, SpecSourceSpec, VmemConfig } from "./config.ts";
@@ -9,7 +11,15 @@ export { extractLinks, resolveLinks, normalizeTarget } from "./links.ts";
9
11
  export type { Link, LinkNote, ResolvedLink } from "./links.ts";
10
12
  export { VaultIndex, MAX_NOTE_BYTES, MAX_RESULTS, MAX_READ_BYTES } from "./vault-index.ts";
11
13
  export type { IndexedNote, SearchOptions, SearchResult } from "./vault-index.ts";
14
+ export { readHistory, readRevision, readChanges, historyText, revisionText, changesText, HISTORY_PAGE_LIMIT, HISTORY_SCAN_LIMIT, CHANGES_PAGE_LIMIT, SNAPSHOT_TRANSPORT_BYTES } from "./vault-history.ts";
15
+ export type { HistoryRequest, RevisionRequest, ChangesRequest, HistoryResult, RevisionResult, ChangesResult, SnapshotCoverage, SnapshotCapability } from "./vault-history.ts";
16
+ export { readJournal, verifySegment, evaluateAssertions, asOfCutoff, appendAssertions, purgeAssertions, assertFrameBytes, ASSERTIONS_DIR, ASSERTIONS_LOCK, ASSERTION_SCHEMA_VERSION, ASSERT_FRAME_BYTES, MAX_BATCH_OPS, PURGE_LIST_LIMIT } from "./assertions.ts";
17
+ export type { AssertRequest, AssertReceipt, AssertOp, AssertionAnswerSet, AssertionItem, AssertionQuery, Answer, JournalEntry, SegmentReport, VerifiedJournal, PurgeRequest, PurgeReceipt } from "./assertions.ts";
18
+ export { scanAssertionExposure, writeReplaceFile, EXPOSURE_COMMIT_BUDGET, EXPOSURE_BLOB_BYTES, EXPOSURE_COMMIT_BYTES, EXPOSURE_FRAME_BYTES } from "./assertion-exposure.ts";
19
+ export type { ExposureRequest, ExposureReceipt, ExposureRow, ExposureScan, ExposureLine, ExposureCommits, ReplaceFileReceipt } from "./assertion-exposure.ts";
12
20
  export { applyWrite, sha256, MUTATION_LOCK, MAX_WRITE_BYTES } from "./writer.ts";
21
+ export { submitProposal, listProposals, showProposal, previewProposalApply, applyProposal, previewProposalReject, rejectProposal, reconcileProposal, confirmProposalReconciliation } from "./proposal-provider.ts";
22
+ export type { ProposalSubmitRequest, ProposalContext, ProposalSubmitted, ProposalListRequest, ProposalPage, ProposalShowRequest, ProposalView, ProposalApplyPreview, ProposalApplyResult, ProposalRejectPreview, ProposalReconciliation } from "./proposal-provider.ts";
13
23
  export { validateWrite, screenContent } from "./write-validation.ts";
14
24
  export type { WriteOp, WriteRequest, WriteReceipt, WriteIssue, PlannedChange, ValidationContext, ChangeReceipt } from "./write-types.ts";
15
25
  export { appendLog, readLog, LOG_LOCK, MAX_LOG_READ_BYTES, MAX_LOG_RESULT_BYTES, LARGE_LOG_LINES } from "./vault-log.ts";
@@ -30,6 +40,8 @@ export type { AmemSeam, AmemCandidate, AmemOptions } from "./amem/seam.ts";
30
40
  export { lintVault } from "./vault-lint.ts";
31
41
  export { buildGraph, graphNeighbors, graphPath, graphReport } from "./vault-graph.ts";
32
42
  export type { VaultGraph, GraphNeighborhood } from "./vault-graph.ts";
43
+ export { explainGraphPath, EXPLAIN_OCCURRENCES_PER_HOP, EXPLAIN_MAX_BYTES } from "./graph-evidence.ts";
44
+ export type { GraphExplanation, GraphHop, GraphOccurrence } from "./graph-evidence.ts";
33
45
  export type { AnalysisSnapshot, LintCode, LintReport } from "./analysis-types.ts";
34
46
  export { writeAnalysisReports } from "./analysis-reports.ts";
35
47
  export type { AnalysisRequest } from "./analysis-reports.ts";
@@ -39,6 +51,8 @@ export { syncVault, sameRemote } from "./sync.ts";
39
51
  export type { SyncResult } from "./sync.ts";
40
52
 
41
53
  export { normalizeSource, sourceReferences } from "./source.ts";
54
+ export { evidenceReport, verifyNoteEvidence, verifyEvidenceEntry, parseEvidence, evidenceProblem, screenEvidenceForTarget, EVIDENCE_SCHEMA_VERSION } from "./evidence.ts";
55
+ export type { EvidenceEntry, EvidenceResult, EvidenceReport, EvidenceStatus, EvidenceReason } from "./evidence.ts";
42
56
  export type { SourceValue, SourceReference } from "./source.ts";
43
57
  export { tidyVault, parseTidyMap, TIDY_RULES } from "./tidy.ts";
44
58
  export type { TidyRequest, TidyResult, TidyRule, TidyMap } from "./tidy.ts";
package/src/links.ts CHANGED
@@ -90,6 +90,24 @@ export function extractLinks(body: string): Link[] {
90
90
  }
91
91
  return links;
92
92
  }
93
+ /**
94
+ * Body UTF-16 offsets of the `[[` of every link `extractLinks` accepts (visible, unescaped), with its parsed address.
95
+ * Offsets are in the original body, CRLF included, so a caller can compare them with raw regex matches.
96
+ */
97
+ export function authoredLinkOffsets(body: string): Map<number, Link> {
98
+ const masked = maskInlineCode(proseLines(body).join("\n")).split("\n"), raw = body.match(/[^\n]*\n|[^\n]+$/g) ?? [];
99
+ const out = new Map<number, Link>(), links = extractLinks(body);
100
+ let start = 0, cursor = 0;
101
+ for (const [index, line] of masked.entries()) {
102
+ for (const match of line.matchAll(/(!?)\[\[([^\]\n]+)\]\]/g)) {
103
+ if (escapedAt(line, match.index!)) continue;
104
+ const link = links[cursor++];
105
+ if (link) out.set(start + match.index! + match[1]!.length, link);
106
+ }
107
+ start += raw[index]?.length ?? 0;
108
+ }
109
+ return out;
110
+ }
93
111
  /** Rewrite only visible wiki-link note targets; retain aliases, anchors, embeds and code verbatim. */
94
112
  export function rewriteLinkTargets(body: string, replace: (target: string) => string | undefined): string {
95
113
  const masked = maskInlineCode(proseLines(body).join("\n")).split("\n");
@@ -1,33 +1,33 @@
1
1
  import { appendLog, readLog } from "./vault-log.ts";
2
2
  import type { LogEvent } from "./log-types.ts";
3
- import { PLAIN, type TextOptions } from "./text-output.ts";
3
+ import { PLAIN, UsageError, type TextOptions } from "./text-output.ts";
4
4
  import { logAppendText, logReadText } from "./read-output.ts";
5
5
  export function runLogCommand(args: string[], home: string, env: NodeJS.ProcessEnv = process.env, text: TextOptions = PLAIN): { text: string; code: number } {
6
6
  const command = args[0];
7
- if (!["tail", "grep", "append"].includes(command ?? "")) throw new Error("log: use tail, grep or append");
7
+ if (!["tail", "grep", "append"].includes(command ?? "")) throw new UsageError("log: use tail, grep or append");
8
8
  const positional: string[] = [], flags: Record<string, string | boolean> = {};
9
9
  const values = command === "append" ? ["--dest"] : ["--limit", "--type"];
10
10
  for (let i = 1; i < args.length; i++) {
11
11
  const word = args[i]!;
12
12
  if (!word.startsWith("--")) { positional.push(word); continue; }
13
- if (Object.hasOwn(flags, word) || (word !== "--json" && !values.includes(word))) throw new Error(`log ${command}: unknown or repeated option: ${word}`);
13
+ if (Object.hasOwn(flags, word) || (word !== "--json" && !values.includes(word))) throw new UsageError(`log ${command}: unknown or repeated option: ${word}`);
14
14
  if (word === "--json") flags[word] = true;
15
15
  else {
16
- const value = args[++i]; if (value === undefined || value.startsWith("--")) throw new Error("log: option value required");
16
+ const value = args[++i]; if (value === undefined || value.startsWith("--")) throw new UsageError("log: option value required");
17
17
  flags[word] = value;
18
18
  }
19
19
  }
20
20
  let result, out: (o: TextOptions) => string;
21
21
  if (command === "append") {
22
- if (positional.length !== 5) throw new Error("log append: requires vault, TYPE, project, source and note");
22
+ if (positional.length !== 5) throw new UsageError("log append: requires vault, TYPE, project, source and note");
23
23
  const [vault, type, project, source, note] = positional as [string, string, string, string, string];
24
24
  const event: LogEvent = { type, project, source, note, ...(typeof flags["--dest"] === "string" ? { dest: flags["--dest"] } : {}) };
25
25
  const receipt = result = appendLog(home, { vault, event, channel: "cli" }, { env });
26
26
  out = o => logAppendText(receipt, o, { vault, type });
27
27
  } else {
28
- if (positional.length !== (command === "grep" ? 2 : 1)) throw new Error(`log ${command}: requires vault${command === "grep" ? " and pattern" : ""}`);
28
+ if (positional.length !== (command === "grep" ? 2 : 1)) throw new UsageError(`log ${command}: requires vault${command === "grep" ? " and pattern" : ""}`);
29
29
  const value = flags["--limit"];
30
- if (value !== undefined && (typeof value !== "string" || !/^[0-9]+$/.test(value))) throw new Error("log limit: expected integer 1..200");
30
+ if (value !== undefined && (typeof value !== "string" || !/^[0-9]+$/.test(value))) throw new UsageError("log limit: expected integer 1..200");
31
31
  const read = result = readLog(home, { vault: positional[0]!, ...(value !== undefined ? { limit: Number(value) } : {}), ...(command === "grep" ? { grep: positional[1] } : {}), ...(typeof flags["--type"] === "string" ? { type: flags["--type"] } : {}) });
32
32
  const type = typeof flags["--type"] === "string" ? flags["--type"] : undefined;
33
33
  out = o => logReadText(read, o, { command: command as "tail" | "grep", vault: positional[0]!, ...(command === "grep" ? { pattern: positional[1]! } : {}), limit: value !== undefined ? Number(value) : 50, ...(type ? { type } : {}) });
package/src/mcp-spec.ts CHANGED
@@ -4,7 +4,7 @@ import { executeSpecCommand } from "./spec-commands.ts";
4
4
  import { validateSpecRepo } from "./spec-validate.ts";
5
5
  import { resolveHome } from "./home.ts";
6
6
  import { loadRegistry } from "./registry.ts";
7
- import { PLAIN, type TextOptions } from "./text-output.ts";
7
+ import { PLAIN, UsageError, type TextOptions } from "./text-output.ts";
8
8
  import { renderSpec } from "./spec-output.ts";
9
9
  import type { SpecWriteResult } from "./spec-write.ts";
10
10
 
@@ -34,7 +34,7 @@ export function createSpecMcp(home: string, env: NodeJS.ProcessEnv = process.env
34
34
  /** Parse with the same bounded field schemas as MCP. --repo deliberately bypasses home resolution. */
35
35
  export function runSpecCommand(args: string[], env: NodeJS.ProcessEnv = process.env, text: TextOptions = PLAIN): { text: string; code: number } {
36
36
  const item = SPEC_COMMANDS.find(entry => entry.command === args[0]);
37
- if (!item) throw new Error("spec: unknown command; use vmem spec --help");
37
+ if (!item) throw new UsageError("spec: unknown command; use vmem spec --help");
38
38
  const values: Record<string, unknown> = {}, positional: string[] = [];
39
39
  const properties = item.inputSchema.properties as Record<string, { type: string }>;
40
40
  const takesId = item.command === "get" || item.command === "graph" || item.command === "update" || item.command === "delete";
@@ -45,32 +45,32 @@ export function runSpecCommand(args: string[], env: NodeJS.ProcessEnv = process.
45
45
  const flag = args[i]!;
46
46
  if (positionalOnly || !flag.startsWith("-")) { positional.push(flag); continue; }
47
47
  if (flag === "--") { positionalOnly = true; continue; }
48
- if (seen.has(flag)) throw new Error(`spec ${item.command}: repeated option ${flag}; supply it once (vmem spec ${item.command} --help)`);
48
+ if (seen.has(flag)) throw new UsageError(`spec ${item.command}: repeated option ${flag}; supply it once (vmem spec ${item.command} --help)`);
49
49
  seen.add(flag);
50
50
  if (flag === "--json") { json = true; continue; }
51
51
  const key = flags.get(flag);
52
- if (!key && !(flag === "--repo" && item.command === "validate")) throw new Error(`spec ${item.command}: unknown option ${flag}; see vmem spec ${item.command} --help`);
52
+ if (!key && !(flag === "--repo" && item.command === "validate")) throw new UsageError(`spec ${item.command}: unknown option ${flag}; see vmem spec ${item.command} --help`);
53
53
  if (key && properties[key]!.type === "boolean") { values[key] = true; continue; }
54
54
  const value = args[++i];
55
- if (value === undefined || value.startsWith("--")) throw new Error(`${flag}: value required; see vmem spec ${item.command} --help`);
55
+ if (value === undefined || value.startsWith("--")) throw new UsageError(`${flag}: value required; see vmem spec ${item.command} --help`);
56
56
  if (flag === "--repo") {
57
57
  const invalidPath = argumentError(value, { type: "string", minLength: 1, maxLength: 4096 }, "repo");
58
- if (invalidPath) throw new Error(`${invalidPath}; supply a checkout path with vmem spec validate --repo PATH`);
58
+ if (invalidPath) throw new UsageError(`${invalidPath}; supply a checkout path with vmem spec validate --repo PATH`);
59
59
  repo = value; continue;
60
60
  }
61
61
  if (properties[key!]!.type === "integer") {
62
- if (!/^[0-9]+$/.test(value)) throw new Error(`${flag}: expected integer; see vmem spec ${item.command} --help for its bounds`);
62
+ if (!/^[0-9]+$/.test(value)) throw new UsageError(`${flag}: expected integer; see vmem spec ${item.command} --help for its bounds`);
63
63
  values[key!] = Number(value);
64
64
  } else if (properties[key!]!.type === "object" || properties[key!]!.type === "array") {
65
65
  try { values[key!] = JSON.parse(value); }
66
- catch { throw new Error(`${flag}: invalid JSON; supply a JSON ${properties[key!]!.type} as shown by vmem spec ${item.command} --help`); }
66
+ catch { throw new UsageError(`${flag}: invalid JSON; supply a JSON ${properties[key!]!.type} as shown by vmem spec ${item.command} --help`); }
67
67
  } else values[key!] = value;
68
68
  }
69
- if (positional.length > (item.command === "validate" ? 0 : 1) || ((takesId || item.command === "create") && positional.length !== 1)) throw new Error(`spec ${item.command}: unexpected targets; use vmem ${item.usage}`);
69
+ if (positional.length > (item.command === "validate" ? 0 : 1) || ((takesId || item.command === "create") && positional.length !== 1)) throw new UsageError(`spec ${item.command}: unexpected targets; use vmem ${item.usage}`);
70
70
  if (positional[0] !== undefined && positionalKey !== undefined) values[positionalKey] = positional[0];
71
71
  const invalid = argumentError(values, item.inputSchema);
72
- if (invalid) throw new Error(`${invalid}; see vmem spec ${item.command} --help to correct the arguments`);
73
- if (repo !== undefined && (values.source !== undefined || values.worktree !== undefined)) throw new Error("--repo cannot be combined with --source or --worktree; choose registry-free or registered validation");
72
+ if (invalid) throw new UsageError(`${invalid}; see vmem spec ${item.command} --help to correct the arguments`);
73
+ if (repo !== undefined && (values.source !== undefined || values.worktree !== undefined)) throw new UsageError("--repo cannot be combined with --source or --worktree; choose registry-free or registered validation");
74
74
  const result = repo !== undefined
75
75
  ? validateSpecRepo(repo, { requireFresh: values.requireFresh as boolean | undefined, limit: values.limit as number | undefined, env }).report
76
76
  : executeSpecCommand(resolveHome(env).home, item.command, values, env);
package/src/mcp-vault.ts CHANGED
@@ -1,4 +1,10 @@
1
+ import { readAssertions, ASSERTIONS_PAGE_LIMIT } from "./assertion-read.ts";
1
2
  import { vaultBrief } from "./vault-brief.ts";
3
+ import { applyProposal, confirmProposalReconciliation, listProposals, previewProposalApply, previewProposalReject, reconcileProposal, rejectProposal, showProposal, submitProposal, type ProposalContext } from "./proposal-provider.ts";
4
+ import { evidenceReport } from "./evidence.ts";
5
+ import { appendAssertions, assertFrameBytes, ASSERT_FRAME_BYTES, purgeAssertions, type AssertReceipt, type PurgeReceipt } from "./assertions.ts";
6
+ import { scanAssertionExposure, type ExposureReceipt } from "./assertion-exposure.ts";
7
+ import { explainGraphPath } from "./graph-evidence.ts";
2
8
  import { createSpecMcp } from "./mcp-spec.ts";
3
9
  import { SPEC_COMMANDS } from "./spec-command-table.ts";
4
10
  import { analysisInput } from "./analysis-input.ts";
@@ -9,8 +15,9 @@ import { parseFrontmatter } from "./frontmatter.ts";
9
15
  import type { VaultSpec } from "./config.ts";
10
16
  import { loadRegistry, registryStatus } from "./registry.ts";
11
17
  import { VaultIndex, MAX_NOTE_BYTES } from "./vault-index.ts";
18
+ import { CHANGES_PAGE_LIMIT, HISTORY_PAGE_LIMIT, SNAPSHOT_CURSOR_CHARS, readChanges, readHistory, readRevision } from "./vault-history.ts";
12
19
  import { listVaultFiles, readVaultFile } from "./vault-files.ts";
13
- import { appendLog, readLog } from "./vault-log.ts";
20
+ import { appendLog, logBinding, readLog } from "./vault-log.ts";
14
21
  import { STATS_MAX_DAYS, vaultStats } from "./vault-stats.ts";
15
22
  import { applyWrite } from "./writer.ts";
16
23
  import { notePath } from "./write-operations.ts";
@@ -28,13 +35,24 @@ const tool = (name: string, description: string, inputSchema: Record<string, unk
28
35
  const RELATIONS = ["supports", "contradicts", "extends", "applies-to", "context-for"];
29
36
  const LOG_TYPES = ["INGEST", "ROUTE", "EXTRACT", "CONNECT", "DIGEST", "LEARN", "LINT", "TASK", "GRAPH", "SYNC", "RETHINK", "SOURCE"];
30
37
  const note = string(1024), sha = { type: "string", minLength: 64, maxLength: 64 };
38
+ const evidenceItem = object({ source: string(512), sha256: sha, quote: string(2048), section: string(1024) }, ["source", "sha256", "quote"]);
39
+ const dateValue = string(10);
40
+ /** One assertion operation; the closed op-specific checks follow in `appendAssertions`. */
41
+ const ASSERT_OP = object({ op: { type: "string", enum: ["declare", "relink", "assert", "revise", "retract"] }, subject: string(66), label: string(200), note: string(1024), relation: string(64), value: string(1024),
42
+ kind: { type: "string", enum: ["state", "event"] }, from: dateValue, to: dateValue, held_on: dateValue, on: dateValue, id: string(40),
43
+ expected_heads: { type: "array", minItems: 1, maxItems: 32, items: sha }, reason: { type: "string", enum: ["recorded_in_error", "evidence_withdrawn", "other"] },
44
+ evidence: { type: "array", minItems: 1, maxItems: 16, items: evidenceItem }, source: { type: "array", minItems: 1, maxItems: 32, items: string(512) } }, ["op"]);
45
+ const oid = { type: "string", minLength: 40, maxLength: 64, pattern: "^(?:[0-9a-f]{40}|[0-9a-f]{64})$" };
31
46
  const logEvent = LOG_EVENT_SCHEMA;
32
47
  const scalar = { type: ["string", "number", "boolean", "null", "array"], maxLength: 4096, maxItems: 64, items: { type: ["string", "number", "boolean"], maxLength: 1024 } };
33
48
  const metadata = { type: "object", maxProperties: 32, properties: { authors: { type: "array", minItems: 1, maxItems: 100, items: string(1024) } }, additionalProperties: scalar };
49
+ const proposalMetadata = { ...metadata, properties: { ...metadata.properties, evidence: { type: "array", maxItems: 16, items: object({ source: string(512), sha256: sha, quote: string(2048), section: string(1024) }, ["source", "sha256", "quote"]) } } };
50
+ const proposalOperation = object({ op: { type: "string", enum: ["create", "patch"] }, path: string(200), frontmatter: proposalMetadata, body: string(32768, 0), expectedSha: sha,
51
+ edits: { type: "array", minItems: 1, maxItems: 32, items: object({ oldString: string(8192), newString: string(8192, 0) }, ["oldString", "newString"]) } }, ["op", "path"]);
34
52
 
35
53
  /** Tool names for the implemented read, write, log, analysis and promotion providers. */
36
- export const VMEM_TOOL_NAMES = ["vmem_status", "vmem_search", "vmem_brief", "vmem_read", "vmem_read_many", "vmem_list", "vmem_links", "vmem_mocs", "vmem_check", "vmem_log_tail",
37
- "vmem_create", "vmem_patch", "vmem_append", "vmem_set_frontmatter", "vmem_link", "vmem_supersede", "vmem_log_append", "vmem_move", "vmem_merge", "vmem_delete", "vmem_promote_from_amem", "vmem_lint", "vmem_graph_build", "vmem_graph_neighbors", "vmem_graph_path", "vmem_promote", "vmem_skills_mine", "vmem_read_file", "vmem_list_files", "vmem_report", "vmem_stats", ...SPEC_COMMANDS.map(item => item.name)] as const;
54
+ export const VMEM_TOOL_NAMES = ["vmem_status", "vmem_search", "vmem_brief", "vmem_read", "vmem_read_many", "vmem_list", "vmem_links", "vmem_history", "vmem_changes", "vmem_mocs", "vmem_check", "vmem_log_tail",
55
+ "vmem_create", "vmem_patch", "vmem_append", "vmem_set_frontmatter", "vmem_link", "vmem_supersede", "vmem_log_append", "vmem_move", "vmem_merge", "vmem_delete", "vmem_promote_from_amem", "vmem_lint", "vmem_graph_build", "vmem_graph_neighbors", "vmem_graph_path", "vmem_graph_explain", "vmem_promote", "vmem_skills_mine", "vmem_read_file", "vmem_list_files", "vmem_report", "vmem_evidence", "vmem_stats", "vmem_proposal_submit", "vmem_proposal_list", "vmem_proposal_show", "vmem_proposal_apply", "vmem_proposal_reject", "vmem_proposal_reconcile", "vmem_assert", "vmem_assertions", "vmem_assertions_purge", "vmem_assertions_exposure", ...SPEC_COMMANDS.map(item => item.name)] as const;
38
56
 
39
57
  /** Server `initialize` instructions: purpose, navigation order and the write contract. Pinned by a test, under 400 bytes. */
40
58
  export const VMEM_INSTRUCTIONS = "vmem is a vault of durable, linked knowledge: notes with frontmatter, wiki-links and an append-only log. Search first with vmem_search, then read the best match with vmem_read, using section for one H2. Writes are validated and receipted: a refusal lists issues, and a failure after publication can leave changes behind, so read the receipt and its issues before retrying.";
@@ -48,10 +66,12 @@ export function vaultTools(ids: readonly string[], orgIds: readonly string[] = [
48
66
  tool("vmem_status", "Registered vaults with health, write policy, effective pii and the piiPolicy matrix (read-only).", object({})),
49
67
  tool("vmem_search", "Full-text (BM25) search over indexed notes. Literal AND terms.", object({ query: string(1000), vault, limit: integer(1, 50), type: string(64), domain: string(64) }, ["query"])),
50
68
  tool("vmem_brief", "Intent-ranked note pointers and one-hop neighbors, with metadata PII/deny screening and whole-line byte cap including the result JSON. No note bodies; read a selected pointer with vmem_read.", object({ vault, intent: string(1024), paths: { type: "array", maxItems: 16, items: string(1024) }, bytes: integer(256, 4096) }, ["intent"])),
51
- tool("vmem_read", "Read one note by stem, alias or notes/ path: frontmatter, body, sha256. Bounded by maxBytes; section selects an exact H2, offset pages UTF-8 byte ranges, and truncated reads list H2 headings/nextOffset.", object({ path: note, vault, maxBytes: integer(1, 65536), section: string(1024), offset: integer(0, MAX_NOTE_BYTES) }, ["path"])),
69
+ tool("vmem_read", "Read one note by stem, alias or notes/ path: frontmatter, body, sha256. Bounded by maxBytes; section selects an exact H2, offset pages UTF-8 byte ranges, and truncated reads list H2 headings/nextOffset. With revision, read that full commit id's blob for the path instead: the result carries revision, blob and content sha256 plus basis git_snapshot, within the 48 KiB transport bound.", object({ path: note, vault, maxBytes: integer(1, 65536), section: string(1024), offset: integer(0, MAX_NOTE_BYTES), revision: oid }, ["path"])),
52
70
  tool("vmem_read_many", "Read up to 20 notes (8 KiB each).", object({ paths: { type: "array", minItems: 1, maxItems: 20, items: note }, vault }, ["paths"])),
53
71
  tool("vmem_list", "List indexed notes under notes/ in path order, optionally by stem prefix, with each note's mtime and the filtered total. Pass the returned nextCursor as cursor for the next page.", object({ vault, prefix: string(256, 0), limit: integer(1, 500), cursor: string(1024) })),
54
72
  tool("vmem_links", "Outgoing links (with resolution) and/or incoming backlinks of a note. Each dead link carries at most one suggested existing target from the title search, with its score; it is a hint and the link is never rewritten.", object({ path: note, vault, direction: { type: "string", enum: ["out", "in", "both"] }, limit: integer(1, 200) }, ["path"])),
73
+ tool("vmem_history", "Read-only Git snapshot history of one note path, newest first: full commit ids reachable from the vault HEAD, blob ids, sizes and Git commit metadata (never assertion time). Pinned to the HEAD the first page saw; pass the returned continuation as cursor. First-parent only, exact path only, at most 1000 commits traversed. Non-repositories, shallow history, unavailable Git, unreachable or pruned objects, revision expressions, symlinked and denied paths are reported or refused explicitly, never replaced with current content.", object({ vault, path: note, limit: integer(1, HISTORY_PAGE_LIMIT), cursor: string(SNAPSHOT_CURSOR_CHARS) }, ["path"])),
74
+ tool("vmem_changes", "Compare two pinned commits over notes/ only: path, status and before/after blob ids, never a content diff. Both ids must be full commits reachable from the vault HEAD. At most 500 paths per page with a continuation cursor; denied and symlinked entries stay out.", object({ vault, from: oid, to: oid, limit: integer(1, CHANGES_PAGE_LIMIT), cursor: string(SNAPSHOT_CURSOR_CHARS) }, ["from", "to"])),
55
75
  tool("vmem_mocs", "MOC notes with incoming link counts.", object({ vault })),
56
76
  tool("vmem_check", "Validate a prospective note text without writing.", object({ vault, path: string(200), text: string(262144, 0) }, ["text"])),
57
77
  tool("vmem_log_tail", "Read the newest vault log lines, optionally filtered.", object({ vault, n: integer(1, 200), type: { type: "string", enum: LOG_TYPES }, grep: string(256) })),
@@ -71,6 +91,7 @@ export function vaultTools(ids: readonly string[], orgIds: readonly string[] = [
71
91
  tool("vmem_graph_build", "Build a deterministic graph and screened reports; dryRun changes nothing.", object({ vault, dryRun: { type: "boolean" }, workspace: { type: "boolean" } }), "write"),
72
92
  tool("vmem_graph_neighbors", "Read a bounded graph neighborhood.", object({ vault, path: note, hops: integer(1,2), limit: integer(1,500), relation: { type: "string", enum: ["wiki_link", ...LINK_RELATIONS] } }, ["path"])),
73
93
  tool("vmem_graph_path", "Read the shortest undirected link path between two notes (BFS, code-point tie order). MOC/bu hubs are not intermediates unless viaHubs. found=false when no path within maxHops (default 6).", object({ vault, from: note, to: note, maxHops: integer(1,6), relation: { type: "string", enum: ["wiki_link", ...LINK_RELATIONS] }, viaHubs: { type: "boolean" } }, ["from", "to"])),
94
+ tool("vmem_graph_explain", "Explain the vmem_graph_path selection hop by hop from the same snapshot: each hop lists the link occurrences behind its edge (origin note path and sha256, line, UTF-8 byte range, body or frontmatter field, declared relation, authored from/to and forward/reverse traversal). legacy_graph_match marks the matches the graph used, with authored=true when also a validated link; anchored and frontmatter references are annotations that add no edge. structuralOnly=true: no quote proves a link and nothing is a probability. 20 occurrences per hop and 48 KiB total, with omitted counts. Writes nothing.", object({ vault, from: note, to: note, maxHops: integer(1,6), relation: { type: "string", enum: ["wiki_link", ...LINK_RELATIONS] }, viaHubs: { type: "boolean" } }, ["from", "to"])),
74
95
  tool("vmem_promote", "Two-step promotion of a personal note into a local org vault clone (never pushes): without confirm returns the full transformed text, dropped links, screen result and fingerprint; confirm=true with that fingerprint writes the org note, source provenance and SYNC log lines. Configured target-vault canonTables add advisory canonical row matches and link-existing choices; personal rows are never included and matches do not affect the fingerprint or block confirm. Publishing is the separate `vmem sync` CLI.",
75
96
  object({ path: note, to: orgVault, topics: { type: "array", maxItems: 32, items: string(200) }, again: { type: "boolean" }, ...twoStep }, ["path", "to"]), "confirm"),
76
97
  tool("vmem_skills_mine", "Read-only skill-candidate mining over amem curated entries, amem capture rows and vault notes: dictionary matching, deterministic communities and novelty scoring. Returns counts, masked candidates and a markdown report; writes nothing.",
@@ -78,19 +99,71 @@ export function vaultTools(ids: readonly string[], orgIds: readonly string[] = [
78
99
  tool("vmem_read_file", "Read one UTF-8 file outside notes/: ops/, reports/, self/, templates/, AGENTS.md or README.md. Same bounds and paging as vmem_read (maxBytes, offset, nextOffset); notes/ use vmem_read, the log vmem_log_tail. Never locks or writes.", object({ vault, path: string(1024), maxBytes: integer(1, 65536), offset: integer(0, MAX_NOTE_BYTES) }, ["path"])),
79
100
  tool("vmem_list_files", "List one directory level under ops/, reports/, self/ or templates/ (up to 500 entries; dot, linked and denied entries omitted). Never locks or writes.", object({ vault, dir: string(1024) }, ["dir"])),
80
101
  tool("vmem_report", "Write a screened report file under reports/ or ops/ (the MCP form of `vmem report`): same path rules, screening, write policy (write=mcp), receipt and EXTRACT log event; log overrides it, for example a LINT or GRAPH event. dryRun changes nothing.", object({ vault, path: string(200), body: string(65536, 0), dryRun: { type: "boolean" }, log: logEvent }, ["path", "body"]), "write"),
102
+ tool("vmem_evidence", "Verify a note's version-1 evidence entries (source, sha256, quote, optional section): flat notes/*.md sources in the same vault are re-read on every call and reported verified, stale, missing, ambiguous or unsupported with UTF-8 byte offsets; other references are unverified_external without I/O. Proves that quoted bytes occur in a source version, not that a claim is true. Writes nothing, takes no lock, keeps no cache.", object({ vault, path: note }, ["path"])),
81
103
  tool("vmem_stats", "Read-only vault statistics: note counts by type, domain and status, note bytes and words in total and by type and domain, and the note-to-source byte ratio (median, p90 and the largest notes) over the workspace files the notes cite. A source counts at its own byte size on disk, so a decoded byte count never inflates a file that is not UTF-8; non-file, unreadable and over-cap sources are skipped and counted, and `truncatedNotes` counts the sourced notes the ratio's 10000-note cap left out. Also notes modified in the last 7 and 30 days, and log event counts by type over the last `days` (default 30). Writes no vault file or log and takes no vault or log lock.", object({ vault, days: integer(1, STATS_MAX_DAYS) })),
104
+ tool("vmem_proposal_submit", "Screen and save one create or exact-patch proposal without modifying vault notes or the log. Agent labels are unverified.", object({ vault, operation: proposalOperation, agentLabel: string(256) }, ["operation"]), "write"),
105
+ tool("vmem_proposal_list", "List screened proposal summaries, pending by default; pass nextCursor as after.", object({ vault, state: { type: "string", enum: ["pending", "applied", "rejected", "apply_unknown"] }, limit: integer(1, 100), after: string(36) })),
106
+ tool("vmem_proposal_show", "Read a screened proposal operation in UTF-8 pages, with the complete encoded response bounded to 48 KiB.", object({ vault, id: string(36), offset: integer(0, 32768), maxBytes: integer(1, 16384) }, ["id"])),
107
+ tool("vmem_proposal_apply", "Preview an apply, then confirm with its fingerprint. An interrupted apply remains apply_unknown and is never replayed automatically.", object({ vault, id: string(36), ...twoStep }, ["id"]), "confirm"),
108
+ tool("vmem_proposal_reject", "Preview rejection with a reason, then confirm with the returned fingerprint; rejection does not change vault notes or log.", object({ vault, id: string(36), reason: string(4096), ...twoStep }, ["id", "reason"]), "confirm"),
109
+ tool("vmem_proposal_reconcile", "Preview an uncertain apply using the target and durable writer receipt; confirm only with the preview fingerprint. Matching content alone does not prove attribution.", object({ vault, id: string(36), ...twoStep }, ["id"]), "confirm"),
110
+ tool("vmem_assert", "Append one all-or-nothing batch of 1..32 temporal assertion operations (declare, relink, assert, revise, retract) to the vault's append-only assertions/ journal; the MCP form of `vmem assert`. Relink changes a declared subject's note while retaining its identity and label. vmem assigns ids, rev, recorded_at and hashes. Each assert or revise needs evidence (path sources verified at append) or source references; revise and retract need expected_heads equal to the current head set. Writes no note; a log line only with log. dryRun validates without lock or append. Requires write=mcp. Request and reply stay within 48 KiB.",
111
+ object({ vault, ops: { type: "array", minItems: 1, maxItems: 32, items: ASSERT_OP }, dryRun: { type: "boolean" }, log: logEvent }, ["ops"]), "write"),
112
+ tool("vmem_assertions", "Read verified temporal assertions with current policy and bounded pages. The journal is the source of truth; results include a verified pin and coverage. Pass continuation as cursor.", object({ vault, subject: string(66), relation: string(64), at: string(10), asOf: string(20), history: { type: "boolean" }, limit: integer(1, ASSERTIONS_PAGE_LIMIT), cursor: string(512) })),
113
+ tool("vmem_assertions_purge", "Two-step purge of one assertion's payloads from the append-only journal: without confirm it returns the affected entries, segment counts and a fingerprint and writes nothing. confirm=true with that fingerprint rewrites each affected segment through a temporary file and a rename under assertions.lock, removes payload, keeps payload_sha256 and every hashed field, and adds purged {at, reason}, so the chain still verifies; reads then show the assertion as unavailable and count it in coverage.purged. The reason stays in the journal. Bytes in Git history, other clones or remotes need a history rewrite outside vmem. Requires write=mcp.", object({ vault, id: string(40), reason: string(200), ...twoStep }, ["id", "reason"]), "confirm"),
114
+ tool("vmem_assertions_exposure", "Read-only exposure report for purged assertion payloads: does a commit reachable from local branches, tags or remote-tracking refs still hold a purged entry's line with a payload, matched by seg, seq and hash with the payload's SHA-256 equal to payload_sha256? Reads only assertions/*.jsonl blobs and reports position, hash, commit count and refs per entry, the scanned counts, clean and truncated. It never prints payload text. Bounded per blob (8 MiB), per commit (64 MiB) and overall (100000 commits); crossing a bound sets truncated and is never clean. A vault that is not a Git repository reports clean: null. The scan covers this local repository only. The history rewrite, the force push, reflog expire and gc stay with the person: vmem never runs them. Replies stay within 48 KiB by dropping refs first, then rows with an omitted count.", object({ vault, assertion: string(40) })),
82
115
  ];
83
116
  }
84
117
  type Issue = { code: string; severity: "error"; message: string };
85
118
  const refusal = (code: string, message: string) => ({ refused: true as const, issues: [{ code, severity: "error", message } as Issue] });
119
+ /** Keep a `vmem_assert` reply inside the 48 KiB frame bound without hiding a batch that was already applied. */
120
+ export function assertReply(reply: AssertReceipt & { refused?: true }): unknown {
121
+ if (assertFrameBytes(reply, "result") <= ASSERT_FRAME_BYTES) return reply;
122
+ const count = reply.entries.length;
123
+ const note: Issue = { code: "LIMIT", severity: "error", message: `the reply exceeds ${ASSERT_FRAME_BYTES} bytes as an encoded JSON-RPC frame; ${count} ${count === 1 ? "row was" : "rows were"} ${reply.applied ? `appended to segment ${reply.segment} and the rows are omitted` : "not appended and the rows are omitted"}. Read the journal for their ids, and send smaller batches` };
124
+ const trimmed = [{ ...reply, entries: [], issues: [...reply.issues.slice(0, 4), note] }, { ...reply, entries: [], issues: [note] },
125
+ { ok: reply.ok, applied: reply.applied, dryRun: reply.dryRun, segment: reply.segment, ...(reply.recordedAt ? { recordedAt: reply.recordedAt } : {}), ...(reply.refused ? { refused: reply.refused } : {}), entries: [], recovery: [], indexUpdated: false as const, issues: [note] }];
126
+ return trimmed.find(candidate => assertFrameBytes(candidate, "result") <= ASSERT_FRAME_BYTES) ?? trimmed[trimmed.length - 1];
127
+ }
128
+ /** Keep a `vmem_assertions_purge` reply inside the 48 KiB frame bound without hiding what was rewritten. */
129
+ export function purgeReply(reply: PurgeReceipt & { refused?: true }): unknown {
130
+ if (assertFrameBytes(reply, "result") <= ASSERT_FRAME_BYTES) return reply;
131
+ const entries = reply.entries.length, segments = reply.segments.length;
132
+ const note: Issue = { code: "LIMIT", severity: "error", message: `the reply exceeds ${ASSERT_FRAME_BYTES} bytes as an encoded JSON-RPC frame; ${entries} ${entries === 1 ? "entry" : "entries"} in ${segments} ${segments === 1 ? "segment" : "segments"} are omitted and ${reply.applied ? "those segments were rewritten by this confirm" : "the preview wrote nothing"}. Read vmem_assertions --history for the ids, and purge fewer entries at a time` };
133
+ const trimmed = [{ ...reply, recovery: [], issues: [...reply.issues.slice(0, 4), note] },
134
+ { ...reply, entries: [], recovery: [], issues: [note] },
135
+ { ok: reply.ok, applied: reply.applied, preview: reply.preview, vault: reply.vault, assertion: reply.assertion, reason: reply.reason, ...(reply.at ? { at: reply.at } : {}), fingerprint: reply.fingerprint, entries: [], segments: reply.segments, alreadyPurged: reply.alreadyPurged, omitted: reply.omitted, recovery: [], ...(reply.refused ? { refused: reply.refused } : {}), issues: [note] },
136
+ { ok: reply.ok, applied: reply.applied, preview: reply.preview, vault: reply.vault, assertion: reply.assertion, reason: reply.reason, ...(reply.at ? { at: reply.at } : {}), fingerprint: reply.fingerprint, entries: [], segments: [], alreadyPurged: reply.alreadyPurged, omitted: reply.omitted, recovery: [], ...(reply.refused ? { refused: reply.refused } : {}), issues: [note] }];
137
+ return trimmed.find(candidate => assertFrameBytes(candidate, "result") <= ASSERT_FRAME_BYTES) ?? trimmed[trimmed.length - 1];
138
+ }
86
139
  const str = (value: unknown): string | undefined => typeof value === "string" ? value : undefined;
87
140
 
141
+ /** Keep a `vmem_assertions_exposure` reply inside the 48 KiB frame bound: refs first, then rows with an omitted count. */
142
+ export function exposureReply(reply: ExposureReceipt & { refused?: true }): unknown {
143
+ const fits = (value: unknown) => assertFrameBytes(value, "result") <= ASSERT_FRAME_BYTES;
144
+ if (fits(reply)) return reply;
145
+ const rows = reply.exposed.map(row => ({ ...row, refs: [] }));
146
+ const stripped = { ...reply, exposed: rows, refsOmitted: true as const };
147
+ if (fits(stripped)) return stripped;
148
+ const keep = (count: number) => ({ ...stripped, exposed: rows.slice(0, count), omitted: reply.exposed.length - count });
149
+ if (!fits(keep(0))) return { ...reply, exposed: [], refsOmitted: true as const, omitted: reply.exposed.length };
150
+ // A longer prefix is never smaller, so the longest one that fits is found by halving: about a dozen serializations
151
+ // for a few thousand rows instead of one per row.
152
+ let low = 0, high = rows.length;
153
+ while (high - low > 1) {
154
+ const middle = Math.floor((low + high) / 2);
155
+ if (fits(keep(middle))) low = middle; else high = middle;
156
+ }
157
+ return keep(low);
158
+ }
159
+
88
160
  /**
89
161
  * Handlers over the shared providers (VaultIndex, applyWrite, appendLog/readLog). The vault set and
90
162
  * the default (first personal) are fixed when the server starts; later registry changes need a restart.
91
163
  */
92
164
  export function createVaultMcp(home: string, env: NodeJS.ProcessEnv = process.env): { tools: McpTool[]; handlers: Record<string, McpHandler>; vaults: VaultSpec[]; defaultVault: string | undefined; instructions: string } {
93
- const vaults = loadRegistry(home).vaults, ids = vaults.map(v => v.id);
165
+ const startup = loadRegistry(home), vaults = startup.vaults, ids = vaults.map(v => v.id);
166
+ const proposalBindings = new Map(vaults.map(v => { try { return [v.id, logBinding(v, startup)] as const; } catch { return [v.id, null] as const; } }));
94
167
  const defaultVault = (vaults.find(v => v.kind === "personal") ?? vaults[0])?.id;
95
168
  const pick = (args: Record<string, unknown>): VaultSpec => {
96
169
  const id = str(args.vault) ?? defaultVault;
@@ -115,6 +188,12 @@ export function createVaultMcp(home: string, env: NodeJS.ProcessEnv = process.en
115
188
  return { path, sha256: hash, truncated, frontmatter: parsed.data, body: parsed.body };
116
189
  };
117
190
  const handlers: Record<string, McpHandler> = {
191
+ vmem_proposal_submit: args => { const spec = pick(args), context: ProposalContext = { channel: "mcp", env, expectedVault: spec, expectedBinding: proposalBindings.get(spec.id) ?? null }; return submitProposal(home, { vault: spec.id, operation: args.operation, ...(str(args.agentLabel) !== undefined ? { agentLabel: str(args.agentLabel)! } : {}) }, context); },
192
+ vmem_proposal_list: args => { const spec = pick(args), context: ProposalContext = { channel: "mcp", env, expectedVault: spec, expectedBinding: proposalBindings.get(spec.id) ?? null }; return listProposals(home, { vault: spec.id, ...(str(args.state) ? { state: str(args.state) as "pending" | "applied" | "rejected" | "apply_unknown" } : {}), ...(typeof args.limit === "number" ? { limit: args.limit } : {}), ...(str(args.after) ? { after: str(args.after) } : {}) }, context); },
193
+ vmem_proposal_show: args => { const spec = pick(args), context: ProposalContext = { channel: "mcp", env, expectedVault: spec, expectedBinding: proposalBindings.get(spec.id) ?? null }; return showProposal(home, { vault: spec.id, id: str(args.id)!, ...(typeof args.offset === "number" ? { offset: args.offset } : {}), ...(typeof args.maxBytes === "number" ? { maxBytes: args.maxBytes } : {}) }, context); },
194
+ vmem_proposal_apply: args => { const spec = pick(args), context: ProposalContext = { channel: "mcp", env, expectedVault: spec, expectedBinding: proposalBindings.get(spec.id) ?? null }; if (args.confirm === true && !str(args.fingerprint)) throw new Error("proposal apply: confirm requires a fingerprint; request a new preview"); if (args.confirm !== true && args.fingerprint !== undefined) throw new Error("proposal apply: fingerprint requires confirm; request a new preview"); if (args.confirm !== true) return previewProposalApply(home, { vault: spec.id, id: str(args.id)! }, context); const result = applyProposal(home, { vault: spec.id, id: str(args.id)!, fingerprint: str(args.fingerprint)! }, context); return result.ok || result.applied !== false || result.state === "apply_unknown" ? result : { ...result, refused: true }; },
195
+ vmem_proposal_reject: args => { const spec = pick(args), context: ProposalContext = { channel: "mcp", env, expectedVault: spec, expectedBinding: proposalBindings.get(spec.id) ?? null }; if (args.confirm === true && !str(args.fingerprint)) throw new Error("proposal reject: confirm requires a fingerprint; request a new preview"); if (args.confirm !== true && args.fingerprint !== undefined) throw new Error("proposal reject: fingerprint requires confirm; request a new preview"); if (args.confirm !== true) return previewProposalReject(home, { vault: spec.id, id: str(args.id)!, reason: str(args.reason)! }, context); const result = rejectProposal(home, { vault: spec.id, id: str(args.id)!, reason: str(args.reason)!, fingerprint: str(args.fingerprint)! }, context); return result.ok || result.rejected ? result : { ...result, refused: true }; },
196
+ vmem_proposal_reconcile: args => { const spec = pick(args), context: ProposalContext = { channel: "mcp", env, expectedVault: spec, expectedBinding: proposalBindings.get(spec.id) ?? null }; if (args.confirm === true && !str(args.fingerprint)) throw new Error("proposal reconcile: confirm requires a fingerprint; request a new preview"); if (args.confirm !== true && args.fingerprint !== undefined) throw new Error("proposal reconcile: fingerprint requires confirm; request a new preview"); if (args.confirm !== true) return reconcileProposal(home, { vault: spec.id, id: str(args.id)! }, context); const result = confirmProposalReconciliation(home, { vault: spec.id, id: str(args.id)!, fingerprint: str(args.fingerprint)! }, context); return result.ok || result.resolved ? result : { ...result, refused: true }; },
118
197
  vmem_brief: args => vaultBrief(home, { vault: pick(args).id, intent: args.intent as string, paths: args.paths as string[] | undefined, bytes: args.bytes as number | undefined }, pick(args)),
119
198
  vmem_promote: async args => {
120
199
  const { promoteToOrg } = await import("./org-promote.ts");
@@ -145,20 +224,40 @@ export function createVaultMcp(home: string, env: NodeJS.ProcessEnv = process.en
145
224
  vmem_graph_build: args => writeAnalysisReports(home,{vault:pick(args).id,kind:"graph",workspace:args.workspace === true,channel:"mcp",expectedVault:pick(args),dryRun:args.dryRun === true},env),
146
225
  vmem_graph_neighbors: args => graphNeighbors(buildGraph(analysisInput(home,pick(args).id,{expectedVault:pick(args)}).snapshot),str(args.path)!, (args.hops as 1|2|undefined) ?? 1, (args.limit as number|undefined) ?? 50, str(args.relation)),
147
226
  vmem_graph_path: args => graphPath(buildGraph(analysisInput(home,pick(args).id,{expectedVault:pick(args)}).snapshot),str(args.from)!,str(args.to)!,{maxHops:(args.maxHops as number|undefined) ?? 6,viaHubs:args.viaHubs === true,...(str(args.relation) === undefined ? {} : {relation:str(args.relation)!})}),
227
+ vmem_graph_explain: args => explainGraphPath(analysisInput(home,pick(args).id,{expectedVault:pick(args)}).snapshot,str(args.from)!,str(args.to)!,{maxHops:(args.maxHops as number|undefined) ?? 6,viaHubs:args.viaHubs === true,...(str(args.relation) === undefined ? {} : {relation:str(args.relation)!})}),
148
228
  vmem_status: () => ({ defaultVault: defaultVault ?? null, vaults: registryStatus(home).filter(v => ids.includes(v.id)) }),
149
229
  vmem_search: args => read(args, index => ({ hits: index.search(str(args.query)!, { limit: (args.limit as number | undefined) ?? 20, type: str(args.type), domain: str(args.domain) }) })),
150
- vmem_read: args => read(args, index => { const r = index.show(str(args.path)!, (args.maxBytes as number | undefined) ?? 16384, str(args.section), args.offset as number | undefined); return document(r); }),
230
+ vmem_read: args => str(args.revision) === undefined
231
+ ? read(args, index => { const r = index.show(str(args.path)!, (args.maxBytes as number | undefined) ?? 16384, str(args.section), args.offset as number | undefined); return document(r); })
232
+ : readRevision({ vault: pick(args), home, env, denyPaths: loadRegistry(home).denyPaths ?? [], note: str(args.path)!, revision: str(args.revision)!,
233
+ ...(typeof args.maxBytes === "number" ? { maxBytes: args.maxBytes } : {}), ...(typeof args.offset === "number" ? { offset: args.offset } : {}), ...(str(args.section) ? { section: str(args.section)! } : {}) }),
151
234
  vmem_read_many: args => read(args, index => ({ notes: (args.paths as string[]).map(path => {
152
235
  try { const r = index.show(path, 8192); return document(r); }
153
236
  catch (error) { return { path, ...refusal("V04", error instanceof Error ? error.message : "unreadable") }; }
154
237
  }) })),
155
238
  vmem_list: args => read(args, index => index.list(str(args.prefix) ?? "", (args.limit as number | undefined) ?? 100, str(args.cursor))),
239
+ // Registry is reloaded per call so the source root is rebound on every verification.
240
+ vmem_assertions: args => readAssertions(home, { vault: pick(args).id, ...(str(args.subject) ? { subject: str(args.subject)! } : {}), ...(str(args.relation) ? { relation: str(args.relation)! } : {}), ...(str(args.at) ? { at: str(args.at)! } : {}), ...(str(args.asOf) ? { asOf: str(args.asOf)! } : {}), ...(args.history === true ? { history: true } : {}), ...(typeof args.limit === "number" ? { limit: args.limit } : {}), ...(str(args.cursor) ? { cursor: str(args.cursor)! } : {}) }, { env }),
241
+ vmem_assertions_purge: args => {
242
+ const receipt = purgeAssertions(home, { vault: pick(args).id, id: str(args.id)!, reason: str(args.reason)!, channel: "mcp", ...twoStep(args) }, { env });
243
+ return purgeReply(receipt.ok || receipt.applied ? receipt : { ...receipt, refused: true });
244
+ },
245
+ vmem_assertions_exposure: args => exposureReply(scanAssertionExposure(home, { vault: pick(args).id, ...(str(args.assertion) ? { assertion: str(args.assertion)! } : {}) }, { env }).receipt),
246
+ vmem_evidence: args => { const registry = loadRegistry(home), spec = registry.vaults.find(v => v.id === pick(args).id); if (!spec) throw Object.assign(new Error("unknown vault id; list registered vaults with vmem status"), { code: "V04" }); return evidenceReport(spec, str(args.path)!, registry.denyPaths ?? []); },
247
+ vmem_assert: args => {
248
+ const receipt = appendAssertions(home, { vault: pick(args).id, ops: args.ops, channel: "mcp", dryRun: args.dryRun === true, ...(args.log ? { log: args.log as LogEvent } : {}) }, { env });
249
+ return assertReply(receipt.ok || receipt.applied ? receipt : { ...receipt, refused: true });
250
+ },
156
251
  vmem_stats: args => vaultStats(home, pick(args).id, { expectedVault: pick(args), ...(typeof args.days === "number" ? { days: args.days } : {}) }),
157
252
  vmem_links: args => read(args, index => {
158
253
  const direction = str(args.direction) ?? "both", limit = (args.limit as number | undefined) ?? 50;
159
254
  const out = direction === "in" ? [] : index.links(str(args.path)!, limit);
160
255
  return { out: out.filter(l => l.resolved), dead: out.filter(l => !l.resolved), in: direction === "out" ? [] : index.backlinks(str(args.path)!, limit) };
161
256
  }),
257
+ vmem_history: args => readHistory({ vault: pick(args), home, env, denyPaths: loadRegistry(home).denyPaths ?? [], note: str(args.path)!,
258
+ ...(typeof args.limit === "number" ? { limit: args.limit } : {}), ...(str(args.cursor) ? { cursor: str(args.cursor)! } : {}) }),
259
+ vmem_changes: args => readChanges({ vault: pick(args), home, env, denyPaths: loadRegistry(home).denyPaths ?? [], from: str(args.from)!, to: str(args.to)!,
260
+ ...(typeof args.limit === "number" ? { limit: args.limit } : {}), ...(str(args.cursor) ? { cursor: str(args.cursor)! } : {}) }),
162
261
  vmem_mocs: args => read(args, index => ({ mocs: index.mocs() })),
163
262
  vmem_check: args => write(args, { op: "check", path: notePath(str(args.path) ?? "checked-note"), text: str(args.text)! }),
164
263
  vmem_log_tail: args => readLog(home, { vault: pick(args).id, limit: (args.n as number | undefined) ?? 50, ...(str(args.type) ? { type: str(args.type) } : {}), ...(str(args.grep) ? { grep: str(args.grep) } : {}) }),
package/src/mcp.ts CHANGED
@@ -3,6 +3,9 @@ import type { Readable, Writable } from "node:stream";
3
3
 
4
4
  /** Newline-delimited JSON-RPC stdio transport (MCP basic + tools). Sequential, bounded, no timers. */
5
5
  export const FRAME_BYTES = 65_536, RESULT_BYTES = 262_144;
6
+ /** Tools whose complete request is bounded to 48 KiB as the raw frame the client sent, escapes included. */
7
+ export const TOOL_FRAME_BYTES = 48 * 1024;
8
+ const narrowedFrame = (name: string) => name.startsWith("vmem_proposal_") || ["vmem_assert", "vmem_assertions", "vmem_assertions_purge", "vmem_assertions_exposure"].includes(name);
6
9
  export interface McpTool { name: string; description: string; inputSchema: Record<string, unknown>; annotations: Record<string, boolean> }
7
10
  export type McpHandler = (args: Record<string, unknown>) => unknown | Promise<unknown>;
8
11
  export interface McpServerOptions { tools: readonly McpTool[]; handlers: Record<string, McpHandler>; input?: Readable; output?: Writable; name?: string; version?: string; instructions?: string }
@@ -93,6 +96,7 @@ export async function serveMcp(options: McpServerOptions): Promise<void> {
93
96
  if (msg.method !== "tools/call") { await error(id, -32601, "Method not found"); return; }
94
97
  const params = msg.params;
95
98
  if (!plain(params) || Object.keys(params).some(k => !["name", "arguments", "_meta"].includes(k)) || typeof params.name !== "string") { await error(id, -32602, "Invalid tool call"); return; }
99
+ if (narrowedFrame(params.name) && Buffer.byteLength(line, "utf8") + 1 > TOOL_FRAME_BYTES) { await error(id, -32600, `${params.name} request exceeds 48 KiB as the frame it was sent in; shorten the request or split the batch`); return; }
96
100
  const definition = options.tools.find(t => t.name === params.name), args = params.arguments ?? {};
97
101
  const handler = definition && options.handlers[definition.name];
98
102
  if (!definition || !handler) { await error(id, -32602, `unknown tool: ${params.name.slice(0, 200)}`); return; }