@staix/vault-mem 0.3.3 → 0.5.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 (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +45 -20
  3. package/bin/vmem.js +9 -3
  4. package/package.json +2 -2
  5. package/src/analysis-commands.ts +22 -13
  6. package/src/analysis-input.ts +2 -2
  7. package/src/analysis-types.ts +2 -0
  8. package/src/cli-output.ts +140 -0
  9. package/src/cli.ts +91 -45
  10. package/src/commands-table.ts +85 -43
  11. package/src/config.ts +22 -3
  12. package/src/links.ts +2 -0
  13. package/src/log-commands.ts +10 -5
  14. package/src/log-format.ts +3 -0
  15. package/src/log-types.ts +5 -1
  16. package/src/mcp-spec.ts +10 -4
  17. package/src/mcp-vault.ts +27 -15
  18. package/src/org-commands.ts +5 -3
  19. package/src/org-promote.ts +3 -0
  20. package/src/promote-command.ts +6 -4
  21. package/src/read-commands.ts +12 -2
  22. package/src/read-output.ts +99 -0
  23. package/src/registry.ts +3 -2
  24. package/src/setup.ts +58 -12
  25. package/src/skills-mine.ts +3 -2
  26. package/src/spec-git.ts +7 -4
  27. package/src/spec-output.ts +119 -0
  28. package/src/sync.ts +62 -18
  29. package/src/text-output.ts +120 -0
  30. package/src/ui/panel.css +1 -5
  31. package/src/ui/panel.js +60 -70
  32. package/src/ui/plugin.ts +33 -2
  33. package/src/vault-files.ts +74 -0
  34. package/src/vault-graph.ts +21 -2
  35. package/src/vault-index.ts +121 -19
  36. package/src/vault-lint.ts +8 -2
  37. package/src/vault-log.ts +109 -1
  38. package/src/vault-stats.ts +50 -0
  39. package/src/workspace-graph.ts +9 -1
  40. package/src/write-commands.ts +32 -9
  41. package/src/write-operations.ts +48 -8
  42. package/src/write-output.ts +151 -0
  43. package/src/write-types.ts +3 -1
  44. package/src/write-validation.ts +30 -8
  45. package/src/writer.ts +19 -7
@@ -16,7 +16,40 @@ export const MAX_RESULTS = 500;
16
16
  * share the unversioned `<digest>.sqlite`; the first run of a newer version builds its own file once.
17
17
  */
18
18
  export const LINK_RESOLUTION = 2;
19
- const indexName = (root: string) => `${digest(root)}-links${LINK_RESOLUTION}.sqlite`;
19
+ /** Bump when tables or FTS columns change. Named per value like LINK_RESOLUTION. 2 = CJK bigram table; 3 = reference identifiers in FTS. */
20
+ export const INDEX_SCHEMA = 3;
21
+ const indexName = (root: string) => `${digest(root)}-links${LINK_RESOLUTION}-schema${INDEX_SCHEMA}.sqlite`;
22
+ /**
23
+ * unicode61 keeps each Hangul/CJK run as one token, so `사업단` misses `사업단은`. A side table holds the
24
+ * overlapping bigrams of every CJK run of 2+ characters, runs split by a `0` token; a CJK query term then matches
25
+ * one bigram (2 characters) or a phrase of consecutive bigrams, which is exact substring matching. A separate
26
+ * table keeps bm25 of the unicode61 table, whose document length spans all columns, unchanged for Latin queries.
27
+ */
28
+ export const GRAMS_COLUMNS = "path UNINDEXED, title, description, body";
29
+ const CJK = "\\p{sc=Hangul}\\p{sc=Han}\\p{sc=Hiragana}\\p{sc=Katakana}";
30
+ const CJK_RUN = new RegExp(`[${CJK}]{2,}`, "gu"), CJK_TERM = new RegExp(`^[${CJK}]{2,}$`, "u");
31
+ function bigrams(run: string): string[] {
32
+ const chars = [...run];
33
+ return chars.slice(1).map((char, i) => chars[i]! + char);
34
+ }
35
+ export function grams(text: string): string {
36
+ return [...text.normalize("NFC").matchAll(CJK_RUN)].map(([run]) => `${bigrams(run).join(" ")} 0`).join(" ");
37
+ }
38
+ export const gramPhrase = (run: string) => `"${bigrams(run).join(" ")}"`;
39
+ /**
40
+ * Literal AND terms: users cannot inject FTS operators, columns or SQL. A term whose letters and digits form one
41
+ * CJK run of 2+ characters (`runs`) matches as a substring through the bigram table; any other term (`tokens`,
42
+ * quoted) keeps unicode61 token matching.
43
+ */
44
+ export function splitTerms(words: string[]): { tokens: string[]; runs: string[] } {
45
+ const tokens: string[] = [], runs: string[] = [];
46
+ for (const term of words) {
47
+ const letters = term.normalize("NFC").match(/[\p{L}\p{N}]+/gu);
48
+ if (letters?.length === 1 && CJK_TERM.test(letters[0]!)) runs.push(letters[0]!);
49
+ else tokens.push(`"${term.replaceAll('"', '""')}"`);
50
+ }
51
+ return { tokens, runs };
52
+ }
20
53
  export const MAX_READ_BYTES = 64 * 1024;
21
54
  export interface IndexedNote extends LinkNote { hash: string; description: string; type: string; domain: string }
22
55
  export interface NoteReadResult {
@@ -62,6 +95,11 @@ function aliases(value: unknown): string[] {
62
95
  function metadata(stat: NonNullable<ReturnType<typeof lstatSync>>): string {
63
96
  return [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(":");
64
97
  }
98
+ /** The mtime (epoch ms) stored in a `metadata()` stamp, or null when the stamp has another shape. */
99
+ function stampMtime(stamp: string): number | null {
100
+ const value = Number(stamp.split(":")[3]);
101
+ return stamp.split(":").length === 5 && Number.isFinite(value) ? value : null;
102
+ }
65
103
  /** Adapter file I/O gets path-specific guidance without rewriting unrelated Git or binding errors. */
66
104
  function specFileIO<T>(path: string, action: string, operation: () => T): T {
67
105
  try { return operation(); }
@@ -78,7 +116,7 @@ function boundedText(value: string, bytes: number): { content: string; truncated
78
116
  while (end > 0 && (buffer[end]! & 0xc0) === 0x80) end--;
79
117
  return { content: buffer.subarray(0, end).toString("utf8"), truncated: true };
80
118
  }
81
- function readPage(prefix: Buffer, maxBytes: number, offset: number, totalBytes: number): Pick<NoteReadResult, "content" | "truncated" | "nextOffset"> {
119
+ export function readPage(prefix: Buffer, maxBytes: number, offset: number, totalBytes: number): Pick<NoteReadResult, "content" | "truncated" | "nextOffset"> {
82
120
  if (offset > totalBytes) throw new Error("offset: exceeds requested note or section");
83
121
  if (prefix.length && (prefix[0]! & 0xc0) === 0x80) throw new Error("offset: must be a UTF-8 character boundary");
84
122
  let end = Math.min(maxBytes, prefix.length);
@@ -165,6 +203,7 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
165
203
  title TEXT NOT NULL, description TEXT NOT NULL, body TEXT NOT NULL,
166
204
  type TEXT NOT NULL, domain TEXT NOT NULL, aliases TEXT NOT NULL, source TEXT NOT NULL);
167
205
  CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(path UNINDEXED, title, description, body, tokenize='unicode61');
206
+ CREATE VIRTUAL TABLE IF NOT EXISTS grams USING fts5(${GRAMS_COLUMNS}, tokenize='unicode61');
168
207
  CREATE TABLE IF NOT EXISTS analysis_notes (path TEXT PRIMARY KEY, source TEXT NOT NULL, hash TEXT NOT NULL, metadata TEXT NOT NULL);
169
208
  CREATE TABLE IF NOT EXISTS links (source TEXT NOT NULL, ordinal INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY(source, ordinal));`);
170
209
  // Dry runs reuse the derived cache via a readonly connection, then refresh only changed notes in memory.
@@ -182,7 +221,7 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
182
221
  if (size.count > 10000 || size.bytes > 64 * 1024 * 1024) throw new Error("analysis: cached snapshot exceeds bound");
183
222
  for (const row of disk.query<Omit<StoredNote,"aliases"> & {aliases:string}, []>("SELECT * FROM notes").all()) {
184
223
  this.db.query("INSERT INTO notes VALUES (?,?,?,?,?,?,?,?,?,?)").run(row.path,row.hash,row.metadata,row.title,row.description,row.body,row.type,row.domain,row.aliases,row.source);
185
- this.db.query("INSERT INTO fts VALUES (?,?,?,?)").run(row.path,row.title,row.description,row.body);
224
+ this.indexText(row.path, row.title, row.description, !this.adapter && row.type === "reference" ? this.searchBody(row.body, parseFrontmatter(row.source).data) : row.body);
186
225
  }
187
226
  for (const row of disk.query<{source:string;ordinal:number;data:string}, []>("SELECT * FROM links").all()) this.db.query("INSERT INTO links VALUES (?,?,?)").run(row.source,row.ordinal,row.data);
188
227
  this.db.run(`PRAGMA user_version = ${Number(disk.query<{ user_version: number }, []>("PRAGMA user_version").get()?.user_version ?? 0)}`);
@@ -202,6 +241,21 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
202
241
  }
203
242
  }
204
243
  close(): void { this.db.close(); }
244
+ // ponytail: grams stores its bigram text (about 2.3x the CJK bytes); contentless with stable rowids would save it.
245
+ /** Keep the stored body and link/analysis input unchanged; identifiers join only the FTS text. */
246
+ private searchBody(body: string, data: Record<string, unknown>): string {
247
+ if (this.adapter || data.type !== "reference") return body;
248
+ const identifiers = [text(data.doi), text(data.citekey)].filter(Boolean);
249
+ return identifiers.length ? body + "\n" + identifiers.join("\n") : body;
250
+ }
251
+ private indexText(path: string, title: string, description: string, body: string): void {
252
+ this.db.query("INSERT INTO fts VALUES (?,?,?,?)").run(path, title, description, body);
253
+ this.db.query("INSERT INTO grams VALUES (?,?,?,?)").run(path, grams(title), grams(description), grams(body));
254
+ }
255
+ private unindex(path: string): void {
256
+ this.db.query("DELETE FROM fts WHERE path=?").run(path);
257
+ this.db.query("DELETE FROM grams WHERE path=?").run(path);
258
+ }
205
259
  private stored(): LinkNote[] {
206
260
  return this.db.query<Omit<LinkNote, "aliases"> & { aliases: string }, []>("SELECT path,title,aliases,body FROM notes ORDER BY path").all().map(row => ({ ...row, aliases: JSON.parse(row.aliases) as string[] }));
207
261
  }
@@ -215,7 +269,7 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
215
269
  if (!this.adapter && (realpathSync(this.root) !== this.root || realpathSync(notesDir) !== notesDir || !lstatSync(notesDir).isDirectory())) throw new Error(`vault ${this.vault.id}: path or notes directory changed`);
216
270
  const indexed = this.adapter ? new Set(this.db.query<{path:string}, []>("SELECT path FROM notes").all().map(row => row.path)) : undefined;
217
271
  const previous = new Map(this.db.query<{ path: string; hash: string; metadata: string }, []>(this.adapter ? "SELECT path,hash,metadata FROM analysis_notes" : options.captureInvalidFrontmatter ? "SELECT path,hash,metadata FROM notes UNION SELECT path,hash,metadata FROM analysis_notes" : "SELECT path,hash,metadata FROM notes").all().map(note => [note.path, note]));
218
- if (rebuild) this.db.run("DELETE FROM fts");
272
+ if (rebuild) this.db.run("DELETE FROM fts; DELETE FROM grams;");
219
273
  const live = new Set<string>(), present = new Set<string>();
220
274
  let changed = 0, analysisBytes = 0;
221
275
  const skipped: string[] = [], touched = new Set<string>(), keys = new Set<string>();
@@ -298,15 +352,16 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
298
352
  }
299
353
  const { data, body } = document;
300
354
  touch(path);
355
+ const title = text(data.title) || path.slice(0, -3), description = text(data.description);
301
356
  this.db.query("INSERT OR REPLACE INTO notes VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(path, hash, stamp,
302
- text(data.title) || path.slice(0, -3), text(data.description), body, text(data.type), text(data.domain), JSON.stringify(aliases(data.aliases ?? data.alias)), source);
303
- this.db.query("DELETE FROM fts WHERE path=?").run(path);
304
- this.db.query("INSERT INTO fts(path,title,description,body) SELECT path,title,description,body FROM notes WHERE path=?").run(path);
357
+ title, description, body, text(data.type), text(data.domain), JSON.stringify(aliases(data.aliases ?? data.alias)), source);
358
+ this.unindex(path);
359
+ this.indexText(path, title, description, this.searchBody(body, data));
305
360
  changed++;
306
361
  }
307
362
  for (const row of this.db.query<{path:string}, []>("SELECT path FROM analysis_notes").all()) if (!present.has(row.path)) this.db.query("DELETE FROM analysis_notes WHERE path=?").run(row.path);
308
363
  let removed = 0;
309
- for (const path of indexed ?? previous.keys()) if (!live.has(path)) { touch(path); this.db.query("DELETE FROM notes WHERE path=?").run(path); this.db.query("DELETE FROM fts WHERE path=?").run(path); removed++; }
364
+ for (const path of indexed ?? previous.keys()) if (!live.has(path)) { touch(path); this.db.query("DELETE FROM notes WHERE path=?").run(path); this.unindex(path); removed++; }
310
365
  if (this.adapter) {
311
366
  // Spec links are resolved by frontmatter id in buildSpecGraph, never by vault paths.
312
367
  this.db.run("DELETE FROM links");
@@ -345,13 +400,22 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
345
400
  search(query: string, options: SearchOptions = {}, snapshot?: ReadonlyMap<string, string>, snapshotOffset = 0, allSnapshotRows = false): SearchResult[] {
346
401
  const limit = resultLimit(options.limit);
347
402
  if (!query.trim() || Buffer.byteLength(query) > 1024) throw new Error("search: query must contain 1..1024 bytes");
348
- // Literal AND terms: users cannot inject FTS operators, columns or SQL.
349
- const terms = query.trim().split(/\s+/).map(term => `"${term.replaceAll('"', '""')}"`).join(" AND ");
403
+ const { tokens, runs } = splitTerms(query.trim().split(/\s+/));
350
404
  const hashColumn = snapshot ? ",n.hash AS sourceHash" : "";
351
- return this.db.query<SearchResult & { sourceHash?: string }, [string, string | null, string | null, string | null, string | null, number]>(`SELECT n.path, n.title, substr(n.description,1,512) AS description, n.type, n.domain,
405
+ const filters = [options.type ?? null, options.type ?? null, options.domain ?? null, options.domain ?? null, snapshot ? 10000 : limit];
406
+ // Latin-only queries run the unicode61 query unchanged. With a CJK term the bigram table drives the match, and a
407
+ // note where every CJK term is a standalone word or sits in the title/description ranks before substring-only hits.
408
+ const strong = runs.map(() => "(n.path IN (SELECT path FROM fts WHERE fts MATCH ?) OR n.path IN (SELECT path FROM grams WHERE grams MATCH ?))").join(" AND ");
409
+ const rows = !runs.length
410
+ ? this.db.query<SearchResult & { sourceHash?: string }, (string | number | null)[]>(`SELECT n.path, n.title, substr(n.description,1,512) AS description, n.type, n.domain,
352
411
  bm25(fts,0,5,2,1) AS score, snippet(fts,3,'','',' ... ',32) AS snippet${hashColumn} FROM fts JOIN notes n ON n.path=fts.path
353
- WHERE fts MATCH ? AND (? IS NULL OR n.type=?) AND (? IS NULL OR n.domain=?) ORDER BY score,n.path LIMIT ?`).all(terms, options.type ?? null, options.type ?? null, options.domain ?? null, options.domain ?? null, snapshot ? 10000 : limit)
354
- .filter(row => !snapshot || snapshot.get(row.path) === row.sourceHash)
412
+ WHERE fts MATCH ? AND (? IS NULL OR n.type=?) AND (? IS NULL OR n.domain=?) ORDER BY score,n.path LIMIT ?`).all(tokens.join(" AND "), ...filters)
413
+ : this.db.query<SearchResult & { sourceHash?: string }, (string | number | null)[]>(`SELECT n.path, n.title, substr(n.description,1,512) AS description, n.type, n.domain,
414
+ bm25(grams,0,5,2,1) AS score, substr(n.body, max(1, instr(n.body, ?) - 48), 160) AS snippet${hashColumn} FROM grams JOIN notes n ON n.path=grams.path
415
+ WHERE grams MATCH ? ${tokens.length ? "AND n.path IN (SELECT path FROM fts WHERE fts MATCH ?)" : ""} AND (? IS NULL OR n.type=?) AND (? IS NULL OR n.domain=?)
416
+ ORDER BY NOT (${strong}),score,n.path LIMIT ?`).all(runs[0]!, runs.map(gramPhrase).join(" AND "), ...(tokens.length ? [tokens.join(" AND ")] : []), ...filters.slice(0, 4),
417
+ ...runs.flatMap(run => [`"${run}"`, `{title description} : ${gramPhrase(run)}`]), filters[4]!);
418
+ return rows.filter(row => !snapshot || snapshot.get(row.path) === row.sourceHash)
355
419
  .slice(snapshot ? snapshotOffset : 0, (snapshot ? snapshotOffset : 0) + (snapshot && allSnapshotRows ? 10000 : limit))
356
420
  .map(({ sourceHash: _, ...row }) => ({ ...row, title: boundedText(row.title, 512).content, snippet: boundedText(row.snippet, 1024).content, type: boundedText(row.type, 256).content, domain: boundedText(row.domain, 256).content }));
357
421
  }
@@ -397,13 +461,51 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
397
461
  }
398
462
  return { path, hash: note.hash, ...readPage(Buffer.from(note.prefix), maxBytes, start, note.bytes), ...metadata, ...headingMetadata(sections) };
399
463
  }
400
- /** Indexed notes (paths relative to notes/) ordered by path, optionally filtered by a literal stem prefix. */
401
- list(prefix = "", limit = 50): { path: string; title: string; type: string; domain: string; description: string }[] {
464
+ /**
465
+ * Indexed notes (paths relative to notes/) ordered by path, optionally filtered by a literal stem prefix.
466
+ * `cursor` is the previous page's `nextCursor` (its last path, exclusive); `total` counts the filtered set.
467
+ */
468
+ list(prefix = "", limit = 50, cursor?: string): { notes: { path: string; title: string; type: string; domain: string; description: string; mtime: string | null }[]; total: number; nextCursor?: string } {
402
469
  if (Buffer.byteLength(prefix) > 1024) throw new Error("prefix: expected <=1024 bytes");
403
- const key = prefix.replace(/^notes\//i, "");
404
- return this.db.query<{ path: string; title: string; type: string; domain: string; description: string }, [number, string, number]>(
405
- "SELECT path,title,type,domain,substr(description,1,512) AS description FROM notes WHERE substr(path,1,?)=? ORDER BY path LIMIT ?"
406
- ).all(key.length, key, resultLimit(limit)).map(row => ({ ...row, title: boundedText(row.title, 512).content, type: boundedText(row.type, 256).content, domain: boundedText(row.domain, 256).content, description: boundedText(row.description, 512).content }));
470
+ const key = prefix.replace(/^notes\//i, ""), max = resultLimit(limit);
471
+ if (cursor !== undefined && (!cursor || Buffer.byteLength(cursor) > 1024 || !cursor.startsWith(key))) throw new Error("cursor: expected the nextCursor of a previous page listed with the same prefix; list again without cursor to restart");
472
+ const rows = this.db.query<{ path: string; title: string; type: string; domain: string; description: string; metadata: string }, [number, string, string, number]>(
473
+ "SELECT path,title,type,domain,substr(description,1,512) AS description,metadata FROM notes WHERE substr(path,1,?)=? AND path>? ORDER BY path LIMIT ?"
474
+ ).all(key.length, key, cursor ?? "", max + 1);
475
+ const total = this.db.query<{ count: number }, [number, string]>("SELECT count(*) AS count FROM notes WHERE substr(path,1,?)=?").get(key.length, key)!.count;
476
+ const notes = rows.slice(0, max).map(({ metadata: stamp, ...row }) => {
477
+ const mtime = stampMtime(stamp);
478
+ return { ...row, title: boundedText(row.title, 512).content, type: boundedText(row.type, 256).content, domain: boundedText(row.domain, 256).content, description: boundedText(row.description, 512).content, mtime: mtime === null ? null : new Date(mtime).toISOString() };
479
+ });
480
+ return { notes, total, ...(rows.length > max ? { nextCursor: notes.at(-1)!.path } : {}) };
481
+ }
482
+ /**
483
+ * Note counts by type, domain and frontmatter `status` ("(none)" when empty), and how many notes have an mtime at or
484
+ * after each cutoff (epoch ms). Streams rows; returns no note text.
485
+ */
486
+ noteStats(cutoffs: readonly number[]): { total: number; byType: Record<string, number>; byDomain: Record<string, number>; byStatus: Record<string, number>; modified: number[] } {
487
+ const add = (map: Map<string, number>, value: string, count = 1) => { const key = value ? boundedText(value, 256).content : "(none)"; map.set(key, (map.get(key) ?? 0) + count); };
488
+ const sorted = (map: Map<string, number>) => Object.fromEntries([...map].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
489
+ const grouped = (column: "type" | "domain") => {
490
+ const map = new Map<string, number>();
491
+ for (const row of this.db.query<{ value: string; count: number }, []>(`SELECT ${column} AS value, count(*) AS count FROM notes GROUP BY ${column}`).all()) add(map, row.value, row.count);
492
+ return sorted(map);
493
+ };
494
+ // Status is not a column: stream each stored source once, parsing only its frontmatter.
495
+ const byStatus = new Map<string, number>(), modified = cutoffs.map(() => 0);
496
+ let total = 0;
497
+ const rows = this.db.prepare<{ metadata: string; source: string }, []>("SELECT metadata,source FROM notes");
498
+ try {
499
+ for (const row of rows.iterate()) {
500
+ total++;
501
+ let status: unknown;
502
+ try { status = parseFrontmatter(row.source).data.status; } catch { /* counted as (none) */ }
503
+ add(byStatus, text(status));
504
+ const mtime = stampMtime(row.metadata);
505
+ cutoffs.forEach((cutoff, i) => { if (mtime !== null && mtime >= cutoff) modified[i]!++; });
506
+ }
507
+ } finally { rows.finalize(); }
508
+ return { total, byType: grouped("type"), byDomain: grouped("domain"), byStatus: sorted(byStatus), modified };
407
509
  }
408
510
  /** Links that resolve to the target note, ordered by source. */
409
511
  backlinks(target: string, limit = 50): ResolvedLink[] {
package/src/vault-lint.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { BUILTIN_DOMAINS } from "./config.ts";
1
2
  import { parseAnalysisYaml, scalarText, yamlTruthy, AnalysisYamlUnsupported } from "./analysis-yaml.ts";
2
3
  import type { AnalysisSnapshot, LintCode, LintReport } from "./analysis-types.ts";
3
4
  const TYPES = ["decision", "insight", "method", "moc", "observation", "person", "project", "reference"];
@@ -70,7 +71,9 @@ function graphChecks(snapshot: AnalysisSnapshot): { l11: string[]; l12: string[]
70
71
  singles.sort();
71
72
  return { l11, l12, info: `nodes ${graph.nodes?.length ?? 0} / edges ${edges.length} / communities ${communities.size}; singleton ${singles.length}개${singles.length ? ": " + singles.slice(0,10).map(s => `\`${s}\``).join(", ") : ""}` };
72
73
  }
73
- export function lintVault(snapshot: AnalysisSnapshot, only?: string): LintReport {
74
+ export function lintVault(snapshot: AnalysisSnapshot, only?: string): LintReport { return lintDetails(snapshot, only).report; }
75
+ /** The report plus what only its markdown carries: the note count, check titles and per-check info lines, for the CLI text view. */
76
+ export function lintDetails(snapshot: AnalysisSnapshot, only?: string): { report: LintReport; notes: number; titles: Record<LintCode, string>; info: Partial<Record<LintCode, string>> } {
74
77
  const findings: Record<LintCode,string[]> = {L01:[],L02:[],L03:[],L09:[],L10:[],L11:[],L12:[],L13:[],L14:[]};
75
78
  const notes = [...snapshot.notes].sort((a,b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).map(n => ({...n,...legacyDocument(n.source),stem: n.path.replace(/^notes\//, "").slice(0,-3)}));
76
79
  const stems = new Set(notes.map(n => n.stem)), inlinks = new Map(notes.map(n => [n.stem,0]));
@@ -88,6 +91,9 @@ export function lintVault(snapshot: AnalysisSnapshot, only?: string): LintReport
88
91
  if (fm === null) { findings.L02.push(prefix + "frontmatter 없음/파싱 실패"); continue; }
89
92
  if (fm.status === "superseded") superseded++;
90
93
  if (!TYPES.includes(String(fm.type))) findings.L02.push(prefix + `\`type: ${py(fm.type)}\` 허용값 아님 (${TYPES.join(" | ")})`);
94
+ if (fm.domain !== undefined && (typeof fm.domain !== "string" || !(snapshot.domains ?? BUILTIN_DOMAINS).includes(fm.domain))) {
95
+ findings.L02.push(prefix + `\`domain: ${py(fm.domain)}\` 허용값 아님 (${(snapshot.domains ?? BUILTIN_DOMAINS).join(" | ")}); vmem.config.json의 이 vault \`domains\`에 id 추가 가능`);
96
+ }
91
97
  if (fm.type === "moc") { if (!truth(fm.description)) findings.L02.push(prefix + "`type: moc` 노트는 `description` 필수"); }
92
98
  else if (!truth(fm.topics)) findings.L02.push(prefix + "`topics` 없음/빈 배열");
93
99
  for (const [key,allowed] of [["confidence",CONFIDENCE],["status",STATUS]] as const) if (fm[key] !== undefined && fm[key] !== null && !allowed.includes(py(fm[key]))) findings.L02.push(prefix + `\`${key}: ${py(fm[key])}\` 허용값 아님 (${allowed.join(" | ")})${key === "status" ? " (status는 노트 생애주기이지 사업 진행 상태가 아님 — 작업 상태는 본문에)" : ""}`);
@@ -131,5 +137,5 @@ export function lintVault(snapshot: AnalysisSnapshot, only?: string): LintReport
131
137
  if (extra[code]) lines.push("",extra[code]!);
132
138
  lines.push("");
133
139
  }
134
- return { findings, errors, warnings, markdown: lines.join("\n"), summary };
140
+ return { report: { findings, errors, warnings, markdown: lines.join("\n"), summary }, notes: notes.length, titles: CODE_TITLES, info: extra };
135
141
  }
package/src/vault-log.ts CHANGED
@@ -2,6 +2,7 @@ import { compileLogFilter } from "./log-filter.ts";
2
2
  import { closeSync, constants, fstatSync, fsyncSync, ftruncateSync, lstatSync, openSync, readSync, realpathSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { hostname } from "node:os";
5
+ import { createHash } from "node:crypto";
5
6
  import { loadRegistry, syncDirectory } from "./registry.ts";
6
7
  import { canonicalPath, isDenied } from "./platform.ts";
7
8
  import { formatLogEvent, LOG_TYPES } from "./log-format.ts";
@@ -67,6 +68,16 @@ function context(home: string, id: string, channel: "cli" | "mcp" | undefined, w
67
68
  if (isDenied(join(vault.path, "log"), config.denyPaths)) refuse("V06", "log path is denied");
68
69
  return { vault, config, channel, ...(write && vault.registry ? { projectIds: registryIds(vault.registry, config.denyPaths) } : {}) };
69
70
  }
71
+ /** Validate and screen an event exactly as `appendLog` would, writing nothing. Returns the blocking issues (empty when valid). */
72
+ export function checkLogEvent(home: string, request: LogRequest, env: NodeJS.ProcessEnv = process.env): WriteIssue[] {
73
+ try {
74
+ const ctx = context(home, request.vault, request.channel, true);
75
+ return formatLogEvent(request.event, { ...ctx, env }).issues.filter(issue => issue.severity === "error");
76
+ } catch (caught) {
77
+ if (caught instanceof LogRefused) return caught.issues;
78
+ throw caught;
79
+ }
80
+ }
70
81
  /** One O_APPEND write per event. A separate cooperative lock permits safe short-write rollback. */
71
82
  /** Bind a later append to the vault spec, path policy and root identity resolved now (refused with LOG_DRIFT if they change). */
72
83
  export function logBinding(vault: VaultSpec, config: VmemConfig): LogBinding {
@@ -189,7 +200,7 @@ export function readLog(home: string, options: LogReadOptions): LogReadResult {
189
200
  const result: LogReadResult = { ok: false, lines: [], dataLines: null, warnings: [], issues: [] };
190
201
  let fd: number | undefined;
191
202
  try {
192
- if (!options || typeof options !== "object" || typeof options.vault !== "string" || Object.keys(options).some(key => !["vault", "limit", "grep", "type"].includes(key))) refuse("L09", "invalid log read options");
203
+ if (!options || typeof options !== "object" || typeof options.vault !== "string" || Object.keys(options).some(key => !["vault", "limit", "grep", "type", "visit"].includes(key)) || (options.visit !== undefined && typeof options.visit !== "function")) refuse("L09", "invalid log read options");
193
204
  const limit = options.limit ?? 50;
194
205
  if (!Number.isInteger(limit) || limit < 1 || limit > 200) refuse("L09", "log limit must be an integer 1..200");
195
206
  if (options.type !== undefined && !(LOG_TYPES as readonly string[]).includes(options.type)) refuse("L09", "unknown log type filter");
@@ -222,6 +233,7 @@ export function readLog(home: string, options: LogReadOptions): LogReadResult {
222
233
  } else {
223
234
  const line = pending.endsWith("\r") ? pending.slice(0, -1) : pending;
224
235
  const type = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}\s+(\S+)/.exec(line)?.[1];
236
+ options.visit?.(line);
225
237
  if ((!options.type || options.type === type) && (!filter || filter(line))) {
226
238
  result.lines.push(line); resultBytes += Buffer.byteLength(JSON.stringify(line)) + 1;
227
239
  while (result.lines.length > limit || resultBytes > MAX_LOG_RESULT_BYTES) resultBytes -= Buffer.byteLength(JSON.stringify(result.lines.shift()!)) + 1;
@@ -251,3 +263,99 @@ export function readLog(home: string, options: LogReadOptions): LogReadResult {
251
263
  }
252
264
  return result;
253
265
  }
266
+
267
+ /** Bytes a cursor poll may read forward; a larger gap answers with the latest rows and `reset: true`. */
268
+ export const MAX_LOG_CURSOR_GAP = 1024 * 1024;
269
+ /** Bytes read from the end of the log for a first call or a reset. */
270
+ const LOG_TAIL_WINDOW = 256 * 1024;
271
+ const CURSOR_ANCHOR = 256;
272
+ export interface LogSinceResult { ok: boolean; lines: string[]; cursor: string; reset: boolean; more: boolean; warnings: string[]; issues: WriteIssue[] }
273
+ /**
274
+ * Incremental tail for pollers. The cursor is opaque: base64url of `v1.<offset>.<sha256 of up to 256 bytes before offset>`,
275
+ * where offset is the end of the last complete line read. Rows come from the byte range after it, so identical lines
276
+ * are kept apart; a cursor past the end, with a different anchor (rewritten or truncated log) or more than
277
+ * MAX_LOG_CURSOR_GAP behind answers with the latest rows and `reset: true`. Every call reads a bounded range.
278
+ */
279
+ export function readLogSince(home: string, options: { vault: string; after?: string; type?: string; limit?: number }): LogSinceResult {
280
+ const result: LogSinceResult = { ok: false, lines: [], cursor: "", reset: false, more: false, warnings: [], issues: [] };
281
+ let fd: number | undefined;
282
+ try {
283
+ const limit = options.limit ?? 100;
284
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) refuse("L09", "log limit must be an integer 1..200");
285
+ if (options.type !== undefined && !(LOG_TYPES as readonly string[]).includes(options.type)) refuse("L09", "unknown log type filter");
286
+ if (options.after !== undefined && (typeof options.after !== "string" || options.after.length > 256)) refuse("L09", "invalid log cursor");
287
+ const ctx = context(home, options.vault, undefined, false), file = join(ctx.vault.path, "log");
288
+ try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
289
+ catch (caught) { if ((caught as NodeJS.ErrnoException).code === "ENOENT") { result.ok = true; result.cursor = encodeCursor(0, Buffer.alloc(0)); result.reset = options.after !== undefined && options.after !== result.cursor; return result; } throw caught; }
290
+ const stat = fstatSync(fd);
291
+ if (!stat.isFile()) refuse("L09", "log must be a plain file");
292
+ const size = stat.size, read = (start: number, end: number) => {
293
+ const out = Buffer.alloc(end - start);
294
+ for (let done = 0; done < out.length;) { const n = readSync(fd!, out, done, out.length - done, start + done); if (!n) refuse("LOG_READ", "log changed while reading"); done += n; }
295
+ return out;
296
+ };
297
+ const anchor = (offset: number) => read(Math.max(0, offset - CURSOR_ANCHOR), offset);
298
+ let start: number | undefined;
299
+ if (options.after !== undefined) {
300
+ const at = decodeCursor(options.after);
301
+ if (at && at.offset <= size && size - at.offset <= MAX_LOG_CURSOR_GAP && hashOf(anchor(at.offset)) === at.hash) start = at.offset;
302
+ else result.reset = true;
303
+ }
304
+ let skipFirst = false;
305
+ if (start === undefined) { start = Math.max(0, size - LOG_TAIL_WINDOW); skipFirst = start > 0 && read(start - 1, start)[0] !== 0x0a; }
306
+ const bytes = read(start, size);
307
+ let from = 0;
308
+ if (skipFirst) {
309
+ const nl = bytes.indexOf(0x0a);
310
+ if (nl < 0) {
311
+ // The whole window is inside one line: point the cursor at the newline before it (scanning back at most
312
+ // MAX_LOG_CURSOR_GAP), or at offset 0, which is a line start and, that far behind, always answers with a reset.
313
+ let boundary = 0;
314
+ for (let at = start; at > 0 && start - at < MAX_LOG_CURSOR_GAP;) {
315
+ const chunk = read(Math.max(0, at - 64 * 1024), at), i = chunk.lastIndexOf(0x0a);
316
+ if (i >= 0) { boundary = at - chunk.length + i + 1; break; }
317
+ at -= chunk.length;
318
+ }
319
+ result.warnings.push("historical log line over 4096 bytes omitted");
320
+ result.cursor = encodeCursor(boundary, anchor(boundary));
321
+ result.ok = true;
322
+ return result;
323
+ }
324
+ from = nl + 1;
325
+ }
326
+ const lastNl = bytes.lastIndexOf(0x0a), end = lastNl >= from ? lastNl + 1 : from;
327
+ if (end < bytes.length) result.warnings.push("incomplete final log line not yet read");
328
+ const decoder = new TextDecoder("utf-8", { fatal: true });
329
+ // A poll from a valid cursor delivers the oldest `limit` new rows and stops its cursor after the last one, so the
330
+ // next poll continues there; a first call or a reset shows the newest rows and moves the cursor to the end.
331
+ const incremental = options.after !== undefined && !result.reset;
332
+ let cursorAt = start + end;
333
+ for (let at = from; at < end;) {
334
+ const nl = bytes.indexOf(0x0a, at), next = nl + 1;
335
+ const raw = decoder.decode(bytes.subarray(at, nl)), line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
336
+ at = next;
337
+ if (!line.trim() || line.trimStart().startsWith("#")) continue;
338
+ if (Buffer.byteLength(line) > MAX_READ_LINE_BYTES) { if (!result.warnings.includes("historical log line over 4096 bytes omitted")) result.warnings.push("historical log line over 4096 bytes omitted"); continue; }
339
+ const type = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}\s+(\S+)/.exec(line)?.[1];
340
+ if (options.type && options.type !== type) continue;
341
+ if (incremental && result.lines.length === limit) { cursorAt = start + bytes.lastIndexOf(0x0a, at - 2) + 1; result.more = true; result.warnings.push(`more rows follow; poll again with the returned cursor`); break; }
342
+ result.lines.push(line);
343
+ }
344
+ if (result.lines.length > limit) { result.lines = result.lines.slice(-limit); result.warnings.push(`only the newest ${limit} rows returned`); }
345
+ result.cursor = encodeCursor(cursorAt, anchor(cursorAt));
346
+ result.ok = true;
347
+ } catch (caught) {
348
+ result.lines = [];
349
+ if (caught instanceof LogRefused) result.issues.push(...caught.issues);
350
+ else result.issues.push({ code: "LOG_READ", severity: "error", message: "cannot read plain UTF-8 log" });
351
+ } finally {
352
+ if (fd !== undefined) { try { closeSync(fd); } catch { result.ok = false; result.issues.push({ code: "LOG_CLOSE", severity: "error", message: "log descriptor close failed" }); } }
353
+ }
354
+ return result;
355
+ }
356
+ const hashOf = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
357
+ function encodeCursor(offset: number, before: Buffer): string { return Buffer.from(`v1.${offset}.${hashOf(before)}`).toString("base64url"); }
358
+ function decodeCursor(cursor: string): { offset: number; hash: string } | undefined {
359
+ const m = /^v1\.(\d{1,15})\.([0-9a-f]{64})$/.exec(Buffer.from(cursor, "base64url").toString("latin1"));
360
+ return m ? { offset: Number(m[1]), hash: m[2]! } : undefined;
361
+ }
@@ -0,0 +1,50 @@
1
+ import { localDate } from "./local-date.ts";
2
+ import { LOG_TYPES } from "./log-format.ts";
3
+ import { loadRegistry } from "./registry.ts";
4
+ import { VaultIndex } from "./vault-index.ts";
5
+ import { readLog } from "./vault-log.ts";
6
+ import type { WriteIssue } from "./write-types.ts";
7
+ import type { VaultSpec } from "./config.ts";
8
+
9
+ export const STATS_DEFAULT_DAYS = 30;
10
+ export const STATS_MAX_DAYS = 3650;
11
+ export interface VaultStats {
12
+ vault: string;
13
+ /** Local calendar date the windows end on (today included). */
14
+ asOf: string;
15
+ notes: { total: number; byType: Record<string, number>; byDomain: Record<string, number>; byStatus: Record<string, number> };
16
+ /** Notes whose indexed mtime falls within the last 7 and 30 local calendar days, today included. */
17
+ modified: { last7Days: number; last30Days: number };
18
+ /** Log events dated on or after `since` (local date), by type; types outside the known set count as "(other)". */
19
+ log: { days: number; since: string; total: number | null; byType: Record<string, number> | null; warnings: string[]; issues: WriteIssue[] };
20
+ }
21
+ /**
22
+ * Read-only vault statistics over the derived index (refreshed like every read tool) and the log streamed by `readLog`:
23
+ * no vault file or log is written and no vault or log lock is taken.
24
+ */
25
+ export function vaultStats(home: string, id: string, options: { days?: number; now?: Date; expectedVault?: VaultSpec } = {}): VaultStats {
26
+ const days = options.days ?? STATS_DEFAULT_DAYS, now = options.now ?? new Date();
27
+ if (!Number.isInteger(days) || days < 1 || days > STATS_MAX_DAYS) throw new Error(`stats: days must be an integer 1..${STATS_MAX_DAYS}; omit it for the ${STATS_DEFAULT_DAYS}-day default`);
28
+ const registry = loadRegistry(home), vault = registry.vaults.find(v => v.id === id);
29
+ if (!vault) throw Object.assign(new Error("stats: unknown vault id; run vmem vaults list for the registered ids"), { code: "V04" });
30
+ // An MCP server reads the vault set fixed at startup; a re-registered id would otherwise count a different vault.
31
+ if (options.expectedVault && JSON.stringify(options.expectedVault) !== JSON.stringify(vault)) throw new Error("stats: the vault registration changed since the MCP server started; restart the MCP server");
32
+ // Local midnight that opens a window of n calendar days ending today.
33
+ const start = (n: number) => new Date(now.getFullYear(), now.getMonth(), now.getDate() - (n - 1));
34
+ const index = new VaultIndex(home, vault, registry.vaults.map(v => v.path));
35
+ let notes: ReturnType<VaultIndex["noteStats"]>;
36
+ try { index.scan(); notes = index.noteStats([start(7).getTime(), start(30).getTime()]); } finally { index.close(); }
37
+ const since = localDate(start(days)), byType: Record<string, number> = Object.fromEntries(LOG_TYPES.map(type => [type, 0]));
38
+ let total = 0;
39
+ const log = readLog(home, { vault: vault.id, limit: 1, visit: line => {
40
+ const match = /^(\d{4}-\d{2}-\d{2}) \d{2}:\d{2}\s+(\S+)/.exec(line);
41
+ if (!match || match[1]! < since) return;
42
+ const type = (LOG_TYPES as readonly string[]).includes(match[2]!) ? match[2]! : "(other)";
43
+ total++; byType[type] = (byType[type] ?? 0) + 1;
44
+ } });
45
+ const { modified: [last7Days = 0, last30Days = 0], ...counts } = notes;
46
+ return {
47
+ vault: vault.id, asOf: localDate(now), notes: counts, modified: { last7Days, last30Days },
48
+ log: { days, since, total: log.ok ? total : null, byType: log.ok ? byType : null, warnings: log.warnings, issues: log.issues },
49
+ };
50
+ }
@@ -16,6 +16,13 @@ const FRONTMATTER = /^---\s*\n([\s\S]*?)\n---\s*\n/;
16
16
  const WIKI = /\[\[([^\]|]+?)(?:\|[^\]]+?)?\]\]/g;
17
17
  const PRIORITY = { wiki_link: 0, fm_ref: 1, bu_member: 2, source_ref: 3, related: 4, supersedes: 5 };
18
18
  export type WorkCounters = Record<"work_docs" | "yaml_fail" | "template_skip" | "related_unresolved" | "related_ambiguous" | "related_dir_skip" | "related_root_escape" | "related_home_escape" | "source_stub" | "source_dead" | "source_nonmd" | "source_skiproot" | "collisions" | "dup_edges", number>;
19
+ /**
20
+ * Edge attributes `scripts/workspace-parity.ts` compares with `build-graph.py --work-root`. The Python reference puts no
21
+ * `rel` on wiki_link edges; vmem keeps the `vmem link --relation` type there, so that `rel` is outside parity.
22
+ */
23
+ export function workspaceParityEdgeKey(e: Record<string, unknown>): string {
24
+ return (["relation", "field", "rel"] as const).map(a => e[a] === undefined || (a === "rel" && e.relation === "wiki_link") ? "" : String(e[a])).join("|");
25
+ }
19
26
  export function workSkipped(path: string, roots: string[]): boolean {
20
27
  const normalized = path.normalize("NFC").replace(/^\/+|\/+$/g, "");
21
28
  return roots.some(root => normalized === root || normalized.startsWith(root + "/"));
@@ -129,7 +136,8 @@ export function buildWorkspaceGraph(snapshot: AnalysisSnapshot, work: WorkspaceS
129
136
  if (!current || PRIORITY[edge.relation] > PRIORITY[current.relation]) best.set(key, edge);
130
137
  }
131
138
  const edges = new Map(graph.edges.map(edge => [pair(edge), edge]));
132
- for (const [key, edge] of best) edges.set(key, { ...edges.get(key), ...edge });
139
+ // A vault wiki link's `rel` belongs to that relation only: a higher-priority work edge on the pair drops it.
140
+ for (const [key, edge] of best) { const prior = edges.get(key); edges.set(key, prior && prior.relation === edge.relation ? { ...prior, ...edge } : edge); }
133
141
  graph.edges = [...edges.values()];
134
142
  if (graph.nodes.length > 20000 || graph.edges.length > 100000) throw new Error("workspace graph: node or edge bound exceeded");
135
143
  finalizeGraph(graph);
@@ -5,8 +5,13 @@ import { loadRegistry } from "./registry.ts";
5
5
  import { basename } from "node:path";
6
6
  import { applyWrite, MAX_WRITE_BYTES } from "./writer.ts";
7
7
  import { notePath } from "./write-operations.ts";
8
- import type { WriteOp, WriteRequest } from "./write-types.ts";
8
+ import type { PatchEdit, WriteOp, WriteRequest } from "./write-types.ts";
9
+ import type { LogEvent } from "./log-types.ts";
10
+ import { LOG_EVENT_SCHEMA } from "./log-format.ts";
11
+ import { argumentError } from "./mcp.ts";
9
12
  import { parseTidyMap, tidyVault, TIDY_RULES } from "./tidy.ts";
13
+ import { PLAIN, type TextOptions } from "./text-output.ts";
14
+ import { renderTidy, renderWriteReceipt } from "./write-output.ts";
10
15
  const COMMANDS = new Set(["new", "patch", "append", "frontmatter", "link", "supersede", "move", "delete", "tidy", "report", "check"]);
11
16
  export function isWriteCommand(command: string): boolean { return COMMANDS.has(command); }
12
17
  function object(text: string, label: string): Record<string, unknown> {
@@ -29,15 +34,24 @@ function input(file: string, home: string): string {
29
34
  return text;
30
35
  } finally { if (file !== "-") closeSync(fd); }
31
36
  }
32
- export function runWriteCommand(command: string, args: string[], home: string, env: NodeJS.ProcessEnv = process.env): { text: string; code: number } {
37
+ /** `--log JSON` checked against the same closed schema as the MCP `log` argument; registry and screening checks follow in applyWrite. */
38
+ function logOption(text: string | undefined): { log?: LogEvent } {
39
+ if (text === undefined) return {};
40
+ let value: unknown;
41
+ try { value = JSON.parse(text); } catch { throw new Error("--log: invalid JSON; expected {\"type\", \"project\", \"source\", \"note\"[, \"dest\"]}"); }
42
+ const error = argumentError(value, LOG_EVENT_SCHEMA, "--log");
43
+ if (error) throw new Error(`${error}; expected {"type", "project", "source", "note"[, "dest"]} as for log append`);
44
+ return { log: value as LogEvent };
45
+ }
46
+ export function runWriteCommand(command: string, args: string[], home: string, env: NodeJS.ProcessEnv = process.env, text: TextOptions = PLAIN): { text: string; code: number } {
33
47
  const valueOptions: Record<string, string[]> = {
34
48
  new: ["--type", "--domain", "--topics", "--description", "--title", "--source", "--confidence", "--status", "--extra", "--body"],
35
- patch: ["--old", "--new", "--expected-sha"], append: ["--section", "--markdown", "--expected-sha"],
49
+ patch: ["--old", "--new", "--edits", "--expected-sha"], append: ["--section", "--markdown", "--expected-sha"],
36
50
  frontmatter: ["--set", "--unset", "--expected-sha"], link: ["--relation", "--context"],
37
51
  move: ["--fingerprint"], delete: ["--fingerprint"], tidy: ["--fingerprint", "--map"], report: ["--body"], check: ["--path"], supersede: [],
38
52
  };
39
- // For tidy, --log selects the log-redaction rule; tidy always writes its own LINT event.
40
- const values = valueOptions[command] ? [...valueOptions[command]!, ...(command === "tidy" ? [] : ["--log"])] : undefined;
53
+ // For tidy, --log selects the log-redaction rule; tidy always writes its own LINT event. Check never appends an event.
54
+ const values = valueOptions[command] ? [...valueOptions[command]!, ...(["tidy", "check"].includes(command) ? [] : ["--log"])] : undefined;
41
55
  if (!values) throw new Error("unknown writer command");
42
56
  const twoStep = ["move", "delete", "tidy"].includes(command);
43
57
  const booleans = ["--json", "--dry-run", ...(twoStep ? ["--confirm"] : []), ...(command === "link" ? ["--one-way"] : []), ...(command === "tidy" ? TIDY_RULES.map(rule => `--${rule}`).concat("--all") : [])];
@@ -69,7 +83,7 @@ export function runWriteCommand(command: string, args: string[], home: string, e
69
83
  if (flags["--dry-run"] && flags["--confirm"]) throw new Error("tidy: --dry-run and --confirm are exclusive");
70
84
  const mapText = optional("--map") !== undefined ? input(required("--map"), home) : undefined;
71
85
  const result = tidyVault(home, { vault, rules, ...(mapText !== undefined ? { map: parseTidyMap(mapText), mapText } : {}), confirm: flags["--confirm"] === true && !flags["--dry-run"], fingerprint: optional("--fingerprint"), channel: "cli" }, { env });
72
- return { text: JSON.stringify(result, null, flags["--json"] ? undefined : 2), code: result.ok ? 0 : 1 };
86
+ return { text: flags["--json"] ? JSON.stringify(result) : renderTidy(result, text, { argv: [command, ...args], positional }), code: result.ok ? 0 : 1 };
73
87
  }
74
88
  let operation: WriteOp;
75
89
  switch (command) {
@@ -80,7 +94,16 @@ export function runWriteCommand(command: string, args: string[], home: string, e
80
94
  if (optional("--topics") !== undefined) frontmatter.topics = required("--topics").split(",").filter(Boolean).map(value => value.startsWith("[[") ? value : `[[${value}]]`);
81
95
  operation = { op: "create", path: target, frontmatter, ...(optional("--body") ? { body: input(required("--body"), home) } : {}) }; break;
82
96
  }
83
- case "patch": operation = { op: "patch", path: target, oldString: required("--old"), newString: required("--new"), expectedSha: optional("--expected-sha") }; break;
97
+ case "patch": {
98
+ // --edits takes the same JSON array as the MCP `edits` argument.
99
+ if (optional("--edits") === undefined) { operation = { op: "patch", path: target, oldString: required("--old"), newString: required("--new"), expectedSha: optional("--expected-sha") }; break; }
100
+ if (optional("--old") !== undefined || optional("--new") !== undefined) throw new Error("patch: use --old/--new or --edits, not both");
101
+ const text = input(required("--edits"), home);
102
+ let edits: unknown;
103
+ try { edits = JSON.parse(text); } catch { throw new Error("--edits: invalid JSON; expected an array of {oldString, newString}"); }
104
+ if (!Array.isArray(edits)) throw new Error("--edits: expected a JSON array of {oldString, newString}");
105
+ operation = { op: "patch", path: target, edits: edits as PatchEdit[], expectedSha: optional("--expected-sha") }; break;
106
+ }
84
107
  case "append": operation = { op: "append", path: target, section: required("--section"), markdown: required("--markdown"), expectedSha: optional("--expected-sha") }; break;
85
108
  case "frontmatter": operation = { op: "frontmatter", path: target, set: optional("--set") ? object(required("--set"), "set") : {}, unset: optional("--unset")?.split(","), expectedSha: optional("--expected-sha") }; break;
86
109
  case "link": operation = { op: "link", from: target, to: positional[2]!, relation: required("--relation") as Extract<WriteOp, { op: "link" }>["relation"], context: optional("--context"), bidirectional: !flags["--one-way"] }; break;
@@ -92,7 +115,7 @@ export function runWriteCommand(command: string, args: string[], home: string, e
92
115
  case "check": operation = { op: "check", path: notePath(optional("--path") ?? (target === "-" ? "checked-note" : basename(target))), text: input(target, home) }; break;
93
116
  default: throw new Error("unknown writer command");
94
117
  }
95
- const request: WriteRequest = { vault, operation, channel: "cli", dryRun: flags["--dry-run"] === true, confirm: flags["--confirm"] === true, fingerprint: optional("--fingerprint"), ...(optional("--log") ? { log: object(required("--log"), "log") as unknown as import("./log-types.ts").LogEvent } : {}) };
118
+ const request: WriteRequest = { vault, operation, channel: "cli", dryRun: flags["--dry-run"] === true, confirm: flags["--confirm"] === true, fingerprint: optional("--fingerprint"), ...logOption(optional("--log")) };
96
119
  const result = applyWrite(home, request, { env });
97
- return { text: JSON.stringify(result, null, flags["--json"] ? undefined : 2), code: result.ok && result.log?.ok !== false ? 0 : 1 };
120
+ return { text: flags["--json"] ? JSON.stringify(result) : renderWriteReceipt(result, text, { argv: [command, ...args], positional }), code: result.ok && result.log?.ok !== false ? 0 : 1 };
98
121
  }