@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
package/src/links.ts CHANGED
@@ -1,3 +1,5 @@
1
+ /** Relations `vmem link --relation` writes as `- [[x]] (relation): context`. */
2
+ export const LINK_RELATIONS = ["supports", "contradicts", "extends", "applies-to", "context-for"] as const;
1
3
  export interface Link {
2
4
  target: string;
3
5
  label: string | null;
@@ -1,6 +1,8 @@
1
1
  import { appendLog, readLog } from "./vault-log.ts";
2
2
  import type { LogEvent } from "./log-types.ts";
3
- export function runLogCommand(args: string[], home: string, env: NodeJS.ProcessEnv = process.env): { text: string; code: number } {
3
+ import { PLAIN, type TextOptions } from "./text-output.ts";
4
+ import { logAppendText, logReadText } from "./read-output.ts";
5
+ export function runLogCommand(args: string[], home: string, env: NodeJS.ProcessEnv = process.env, text: TextOptions = PLAIN): { text: string; code: number } {
4
6
  const command = args[0];
5
7
  if (!["tail", "grep", "append"].includes(command ?? "")) throw new Error("log: use tail, grep or append");
6
8
  const positional: string[] = [], flags: Record<string, string | boolean> = {};
@@ -15,17 +17,20 @@ export function runLogCommand(args: string[], home: string, env: NodeJS.ProcessE
15
17
  flags[word] = value;
16
18
  }
17
19
  }
18
- let result;
20
+ let result, out: (o: TextOptions) => string;
19
21
  if (command === "append") {
20
22
  if (positional.length !== 5) throw new Error("log append: requires vault, TYPE, project, source and note");
21
23
  const [vault, type, project, source, note] = positional as [string, string, string, string, string];
22
24
  const event: LogEvent = { type, project, source, note, ...(typeof flags["--dest"] === "string" ? { dest: flags["--dest"] } : {}) };
23
- result = appendLog(home, { vault, event, channel: "cli" }, { env });
25
+ const receipt = result = appendLog(home, { vault, event, channel: "cli" }, { env });
26
+ out = o => logAppendText(receipt, o, { vault, type });
24
27
  } else {
25
28
  if (positional.length !== (command === "grep" ? 2 : 1)) throw new Error(`log ${command}: requires vault${command === "grep" ? " and pattern" : ""}`);
26
29
  const value = flags["--limit"];
27
30
  if (value !== undefined && (typeof value !== "string" || !/^[0-9]+$/.test(value))) throw new Error("log limit: expected integer 1..200");
28
- result = readLog(home, { vault: positional[0]!, ...(value !== undefined ? { limit: Number(value) } : {}), ...(command === "grep" ? { grep: positional[1] } : {}), ...(typeof flags["--type"] === "string" ? { type: flags["--type"] } : {}) });
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
+ const type = typeof flags["--type"] === "string" ? flags["--type"] : undefined;
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 } : {}) });
29
34
  }
30
- return { text: JSON.stringify(result, null, flags["--json"] ? undefined : 2), code: result.ok ? 0 : 1 };
35
+ return { text: flags["--json"] ? JSON.stringify(result) : out(text), code: result.ok ? 0 : 1 };
31
36
  }
package/src/log-format.ts CHANGED
@@ -7,6 +7,9 @@ import type { LogContext, LogEvent } from "./log-types.ts";
7
7
  import type { WriteIssue } from "./write-types.ts";
8
8
 
9
9
  export const LOG_TYPES = ["INGEST", "ROUTE", "EXTRACT", "CONNECT", "DIGEST", "LEARN", "LINT", "TASK", "GRAPH", "SYNC", "RETHINK", "SOURCE"] as const;
10
+ const bounded = (maxLength: number) => ({ type: "string", minLength: 1, maxLength });
11
+ /** Closed schema of a write's log event, shared by the MCP write tools and CLI `--log JSON`. */
12
+ export const LOG_EVENT_SCHEMA = { type: "object", properties: { type: { type: "string", enum: [...LOG_TYPES] }, project: bounded(64), source: bounded(512), dest: bounded(512), note: bounded(500) }, required: ["type", "project", "source", "note"], additionalProperties: false };
10
13
  export const AGENT_MARKERS = ["AGENTHUB_PEER_ID", "CLAUDECODE", "CLAUDE_CODE_SESSION_ID", "CODEX_THREAD_ID", "PI_SESSION_ID"] as const;
11
14
  const EVENT_KEYS = new Set(["type", "project", "source", "dest", "note"]);
12
15
  const CONTEXT_KEYS = new Set(["vault", "config", "channel", "env", "now", "projectIds"]);
package/src/log-types.ts CHANGED
@@ -4,7 +4,11 @@ export interface LogEvent { type: string; project: string; source: string; dest?
4
4
  export interface LogRequest { vault: string; event: LogEvent; channel?: "cli" | "mcp" }
5
5
  export interface LogContext { vault: VaultSpec; config: VmemConfig; channel?: "cli" | "mcp"; env?: NodeJS.ProcessEnv; now?: Date; projectIds?: ReadonlySet<string> }
6
6
  export interface LogReceipt { ok: boolean; appended: boolean | null; synced: boolean; bytesWritten: number | null; issues: WriteIssue[]; rolledBack?: boolean }
7
- export interface LogReadOptions { vault: string; limit?: number; grep?: string; type?: string }
7
+ export interface LogReadOptions {
8
+ vault: string; limit?: number; grep?: string; type?: string;
9
+ /** In-process callers only (never CLI/MCP input): called with every complete data line, before the type and grep filters. */
10
+ visit?: (line: string) => void;
11
+ }
8
12
  export interface LogReadResult { ok: boolean; lines: string[]; dataLines: number | null; warnings: string[]; issues: WriteIssue[] }
9
13
 
10
14
  export interface LogBinding { vault: VaultSpec; denyPaths: string[]; piiPatterns: string[]; dev: number; ino: number }
package/src/mcp-spec.ts CHANGED
@@ -4,11 +4,16 @@ 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";
8
+ import { renderSpec } from "./spec-output.ts";
9
+
10
+ /** Spec tool definitions; every spec tool is read-only. */
11
+ export const specTools = (): McpTool[] => SPEC_COMMANDS.map(item => ({ name: item.name, description: item.description, inputSchema: item.inputSchema,
12
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } }));
7
13
 
8
14
  export function createSpecMcp(home: string, env: NodeJS.ProcessEnv = process.env): { tools: McpTool[]; handlers: Record<string, McpHandler> } {
9
15
  const registered = loadRegistry(home).specs ?? [];
10
- const tools: McpTool[] = SPEC_COMMANDS.map(item => ({ name: item.name, description: item.description, inputSchema: item.inputSchema,
11
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } }));
16
+ const tools = specTools();
12
17
  const handlers: Record<string, McpHandler> = {};
13
18
  for (const item of SPEC_COMMANDS) handlers[item.name] = args => {
14
19
  const invalid = argumentError(args, item.inputSchema);
@@ -23,7 +28,7 @@ export function createSpecMcp(home: string, env: NodeJS.ProcessEnv = process.env
23
28
  }
24
29
 
25
30
  /** Parse with the same bounded field schemas as MCP. --repo deliberately bypasses home resolution. */
26
- export function runSpecCommand(args: string[], env: NodeJS.ProcessEnv = process.env): { text: string; code: number } {
31
+ export function runSpecCommand(args: string[], env: NodeJS.ProcessEnv = process.env, text: TextOptions = PLAIN): { text: string; code: number } {
27
32
  const item = SPEC_COMMANDS.find(entry => entry.command === args[0]);
28
33
  if (!item) throw new Error("spec: unknown command; use vmem spec --help");
29
34
  const values: Record<string, unknown> = {}, positional: string[] = [];
@@ -61,5 +66,6 @@ export function runSpecCommand(args: string[], env: NodeJS.ProcessEnv = process.
61
66
  const result = repo !== undefined
62
67
  ? validateSpecRepo(repo, { requireFresh: values.requireFresh as boolean | undefined, limit: values.limit as number | undefined, env }).report
63
68
  : executeSpecCommand(resolveHome(env).home, item.command, values, env);
64
- return { text: JSON.stringify(result, null, json ? undefined : 2), code: item.command === "validate" && !(result as { ok: boolean }).ok ? 1 : 0 };
69
+ const code = item.command === "validate" && !(result as { ok: boolean }).ok ? 1 : 0;
70
+ return { text: json ? JSON.stringify(result) : renderSpec(item.command, result, text, { args, values, ...(repo !== undefined ? { repo } : {}) }), code };
65
71
  }
package/src/mcp-vault.ts CHANGED
@@ -1,18 +1,21 @@
1
1
  import { createSpecMcp } from "./mcp-spec.ts";
2
2
  import { SPEC_COMMANDS } from "./spec-command-table.ts";
3
3
  import { analysisInput } from "./analysis-input.ts";
4
- import { buildGraph, graphNeighbors } from "./vault-graph.ts";
4
+ import { buildGraph, graphNeighbors, LINK_RELATIONS } from "./vault-graph.ts";
5
5
  import { lintVault } from "./vault-lint.ts";
6
6
  import { writeAnalysisReports } from "./analysis-reports.ts";
7
7
  import { parseFrontmatter } from "./frontmatter.ts";
8
8
  import type { VaultSpec } from "./config.ts";
9
9
  import { loadRegistry, registryStatus } from "./registry.ts";
10
10
  import { VaultIndex, MAX_NOTE_BYTES } from "./vault-index.ts";
11
+ import { listVaultFiles, readVaultFile } from "./vault-files.ts";
11
12
  import { appendLog, readLog } from "./vault-log.ts";
13
+ import { STATS_MAX_DAYS, vaultStats } from "./vault-stats.ts";
12
14
  import { applyWrite } from "./writer.ts";
13
15
  import { notePath } from "./write-operations.ts";
14
16
  import type { LogEvent } from "./log-types.ts";
15
- import type { WriteOp, WriteReceipt, WriteRequest } from "./write-types.ts";
17
+ import { LOG_EVENT_SCHEMA } from "./log-format.ts";
18
+ import type { PatchEdit, WriteOp, WriteReceipt, WriteRequest } from "./write-types.ts";
16
19
  import type { McpHandler, McpTool } from "./mcp.ts";
17
20
 
18
21
  const string = (maxLength: number, minLength = 1) => ({ type: "string", minLength, maxLength });
@@ -24,12 +27,13 @@ const tool = (name: string, description: string, inputSchema: Record<string, unk
24
27
  const RELATIONS = ["supports", "contradicts", "extends", "applies-to", "context-for"];
25
28
  const LOG_TYPES = ["INGEST", "ROUTE", "EXTRACT", "CONNECT", "DIGEST", "LEARN", "LINT", "TASK", "GRAPH", "SYNC", "RETHINK", "SOURCE"];
26
29
  const note = string(1024), sha = { type: "string", minLength: 64, maxLength: 64 };
27
- const logEvent = object({ type: { type: "string", enum: LOG_TYPES }, project: string(64), source: string(512), dest: string(512), note: string(500) }, ["type", "project", "source", "note"]);
30
+ const logEvent = LOG_EVENT_SCHEMA;
28
31
  const scalar = { type: ["string", "number", "boolean", "null", "array"], maxLength: 4096, maxItems: 64, items: { type: ["string", "number", "boolean"], maxLength: 1024 } };
32
+ const metadata = { type: "object", maxProperties: 32, properties: { authors: { type: "array", minItems: 1, maxItems: 100, items: string(1024) } }, additionalProperties: scalar };
29
33
 
30
34
  /** Tool names for the implemented read, write, log, analysis and promotion providers. */
31
35
  export const VMEM_TOOL_NAMES = ["vmem_status", "vmem_search", "vmem_read", "vmem_read_many", "vmem_list", "vmem_links", "vmem_mocs", "vmem_check", "vmem_log_tail",
32
- "vmem_create", "vmem_patch", "vmem_append", "vmem_set_frontmatter", "vmem_link", "vmem_supersede", "vmem_log_append", "vmem_move", "vmem_delete", "vmem_promote_from_amem", "vmem_lint", "vmem_graph_build", "vmem_graph_neighbors", "vmem_promote", "vmem_skills_mine", ...SPEC_COMMANDS.map(item => item.name)] as const;
36
+ "vmem_create", "vmem_patch", "vmem_append", "vmem_set_frontmatter", "vmem_link", "vmem_supersede", "vmem_log_append", "vmem_move", "vmem_delete", "vmem_promote_from_amem", "vmem_lint", "vmem_graph_build", "vmem_graph_neighbors", "vmem_promote", "vmem_skills_mine", "vmem_read_file", "vmem_list_files", "vmem_report", "vmem_stats", ...SPEC_COMMANDS.map(item => item.name)] as const;
33
37
 
34
38
  /** Tool definitions for a fixed vault set: `vault` is an enum of the registered ids. */
35
39
  export function vaultTools(ids: readonly string[], orgIds: readonly string[] = []): McpTool[] {
@@ -41,29 +45,33 @@ export function vaultTools(ids: readonly string[], orgIds: readonly string[] = [
41
45
  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"])),
42
46
  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"])),
43
47
  tool("vmem_read_many", "Read up to 20 notes (8 KiB each).", object({ paths: { type: "array", minItems: 1, maxItems: 20, items: note }, vault }, ["paths"])),
44
- tool("vmem_list", "List indexed notes under notes/, optionally by stem prefix.", object({ vault, prefix: string(256, 0), limit: integer(1, 500) })),
48
+ 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) })),
45
49
  tool("vmem_links", "Outgoing links (with resolution) and/or incoming backlinks of a note.", object({ path: note, vault, direction: { type: "string", enum: ["out", "in", "both"] }, limit: integer(1, 200) }, ["path"])),
46
50
  tool("vmem_mocs", "MOC notes with incoming link counts.", object({ vault })),
47
51
  tool("vmem_check", "Validate a prospective note text without writing.", object({ vault, path: string(200), text: string(262144, 0) }, ["text"])),
48
52
  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) })),
49
- tool("vmem_create", "Create a validated note. Requires a vault with write=mcp.", object({ vault, stem: string(200), type: string(64), domain: string(64), topics: { type: "array", maxItems: 32, items: string(200) }, description: string(1000), title: string(300), body: string(65536, 0), source: { type: ["string", "array"], minLength: 1, maxLength: 512, minItems: 1, maxItems: 32, items: string(512) }, confidence: string(32), status: string(32), created: string(32, 0), extra: { type: "object", maxProperties: 32, additionalProperties: scalar }, log: logEvent }, ["stem", "type", "domain", "description"]), "write"),
50
- tool("vmem_patch", "Replace one exact string in a note.", object({ vault, path: note, oldString: string(8192), newString: string(8192, 0), expectedSha: sha }, ["path", "oldString", "newString"]), "write"),
51
- tool("vmem_append", "Append markdown to a section of a note.", object({ vault, path: note, section: string(120), markdown: string(16384), expectedSha: sha }, ["path", "section", "markdown"]), "write"),
52
- tool("vmem_set_frontmatter", "Set or unset frontmatter keys of a note.", object({ vault, path: note, set: { type: "object", maxProperties: 32, additionalProperties: scalar }, unset: { type: "array", maxItems: 32, items: string(64) }, expectedSha: sha }, ["path"]), "write"),
53
+ tool("vmem_create", "Create a validated note. Requires a vault with write=mcp.", object({ vault, stem: string(200), type: string(64), domain: string(64), topics: { type: "array", maxItems: 32, items: string(200) }, description: string(1000), title: string(300), body: string(65536, 0), source: { type: ["string", "array"], minLength: 1, maxLength: 512, minItems: 1, maxItems: 32, items: string(512) }, confidence: string(32), status: string(32), created: string(32, 0), extra: metadata, log: logEvent }, ["stem", "type", "domain", "description"]), "write"),
54
+ tool("vmem_patch", "Replace exact strings in a note: one oldString/newString pair, or edits (1..32 pairs, each matching once in the original text, non-overlapping) applied all-or-nothing with one receipt and one log event.", object({ vault, path: note, oldString: string(8192), newString: string(8192, 0), edits: { type: "array", minItems: 1, maxItems: 32, items: object({ oldString: string(8192), newString: string(8192, 0) }, ["oldString", "newString"]) }, expectedSha: sha, log: logEvent }, ["path"]), "write"),
55
+ tool("vmem_append", "Append markdown to a section of a note.", object({ vault, path: note, section: string(120), markdown: string(16384), expectedSha: sha, log: logEvent }, ["path", "section", "markdown"]), "write"),
56
+ tool("vmem_set_frontmatter", "Set or unset frontmatter keys of a note.", object({ vault, path: note, set: metadata, unset: { type: "array", maxItems: 32, items: string(64) }, expectedSha: sha, log: logEvent }, ["path"]), "write"),
53
57
  tool("vmem_link", "Add a typed relation link between two notes (bidirectional by default).", object({ vault, from: note, to: note, relation: { type: "string", enum: RELATIONS }, context: string(500), bidirectional: { type: "boolean" }, log: logEvent }, ["from", "to", "relation"]), "write"),
54
58
  tool("vmem_supersede", "Mark a note superseded by another.", object({ vault, old: note, next: note, log: logEvent }, ["old", "next"]), "write"),
55
59
  tool("vmem_log_append", "Append one validated event line to the vault log.", object({ vault, type: { type: "string", enum: LOG_TYPES }, project: string(64), source: string(512), dest: string(512), note: string(500) }, ["type", "project", "source", "note"]), "write"),
56
- tool("vmem_move", "Two-step rename with link rewrites: without confirm returns preview and fingerprint; then confirm=true with that fingerprint.", object({ vault, from: note, to: note, ...twoStep }, ["from", "to"]), "confirm"),
57
- tool("vmem_delete", "Two-step delete: without confirm returns preview (or refusal), backlinks and fingerprint; then confirm=true with that fingerprint.", object({ vault, path: note, ...twoStep }, ["path"]), "confirm"),
60
+ tool("vmem_move", "Two-step rename with link rewrites: without confirm returns preview and fingerprint; then confirm=true with that fingerprint (pass log on the confirm call).", object({ vault, from: note, to: note, ...twoStep, log: logEvent }, ["from", "to"]), "confirm"),
61
+ tool("vmem_delete", "Two-step delete: without confirm returns preview (or refusal), backlinks and fingerprint; then confirm=true with that fingerprint (pass log on the confirm call).", object({ vault, path: note, ...twoStep, log: logEvent }, ["path"]), "confirm"),
58
62
  tool("vmem_promote_from_amem", "Two-step promotion of one durable agent-mem entry (id from amem_vault_candidates) into a vault note: without confirm returns the full note text, possible duplicates and fingerprint; confirm=true with that fingerprint creates the note, logs LEARN and records the agent-mem vault link. linkTo links an existing note instead.",
59
63
  object({ vault, id: { type: "string", minLength: 32, maxLength: 36 }, stem: string(120), type: string(64), domain: string(64), topics: { type: "array", maxItems: 32, items: string(200) }, description: string(1000), title: string(300), body: string(65536, 0), linkTo: note, project: string(400), ...twoStep }, ["id"]), "confirm"),
60
64
  tool("vmem_lint", "Lint a private derived snapshot; write=true writes a screened report.", object({ vault, write: { type: "boolean" }, dryRun: { type: "boolean" } }), "write"),
61
65
  tool("vmem_graph_build", "Build a deterministic graph and screened reports; dryRun changes nothing.", object({ vault, dryRun: { type: "boolean" }, workspace: { type: "boolean" } }), "write"),
62
- tool("vmem_graph_neighbors", "Read a bounded graph neighborhood.", object({ vault, path: note, hops: integer(1,2), limit: integer(1,500) }, ["path"])),
66
+ 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"])),
63
67
  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. Publishing is the separate `vmem sync` CLI.",
64
68
  object({ path: note, to: orgVault, topics: { type: "array", maxItems: 32, items: string(200) }, again: { type: "boolean" }, ...twoStep }, ["path", "to"]), "confirm"),
65
69
  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.",
66
70
  object({ vault, days: integer(1, 3650), project: string(400), allProjects: { type: "boolean" }, vocab: string(4096), skills: { type: "array", maxItems: 16, items: string(4096) }, minSize: integer(1, 10000), minNovelty: { type: "number", minimum: 0, maximum: 1 } })),
71
+ 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"])),
72
+ 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"])),
73
+ 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"),
74
+ tool("vmem_stats", "Read-only vault statistics: note counts by type, domain and status, 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) })),
67
75
  ];
68
76
  }
69
77
  type Issue = { code: string; severity: "error"; message: string };
@@ -122,9 +130,12 @@ export function createVaultMcp(home: string, env: NodeJS.ProcessEnv = process.en
122
130
  ...(Array.isArray(args.skills) ? { skills: args.skills as string[] } : {}), ...(typeof args.days === "number" ? { days: args.days } : {}),
123
131
  ...(typeof args.minSize === "number" ? { minSize: args.minSize } : {}), ...(typeof args.minNovelty === "number" ? { minNovelty: args.minNovelty } : {}) });
124
132
  },
133
+ vmem_read_file: args => readVaultFile(pick(args), loadRegistry(home).denyPaths ?? [], str(args.path)!, (args.maxBytes as number | undefined) ?? 16384, args.offset as number | undefined),
134
+ vmem_list_files: args => listVaultFiles(pick(args), loadRegistry(home).denyPaths ?? [], str(args.dir)!),
135
+ vmem_report: args => write(args, { op: "report", path: str(args.path)!, text: str(args.body)! }, args.dryRun === true ? { dryRun: true } : {}),
125
136
  vmem_lint: args => args.write === true ? writeAnalysisReports(home,{vault:pick(args).id,kind:"lint",channel:"mcp",expectedVault:pick(args),dryRun:args.dryRun === true},env) : lintVault(analysisInput(home,pick(args).id,{expectedVault:pick(args)}).snapshot),
126
137
  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),
127
- 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),
138
+ 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)),
128
139
  vmem_status: () => ({ defaultVault: defaultVault ?? null, vaults: registryStatus(home).filter(v => ids.includes(v.id)) }),
129
140
  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) }) })),
130
141
  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); }),
@@ -132,7 +143,8 @@ export function createVaultMcp(home: string, env: NodeJS.ProcessEnv = process.en
132
143
  try { const r = index.show(path, 8192); return document(r); }
133
144
  catch (error) { return { path, ...refusal("V04", error instanceof Error ? error.message : "unreadable") }; }
134
145
  }) })),
135
- vmem_list: args => read(args, index => ({ notes: index.list(str(args.prefix) ?? "", (args.limit as number | undefined) ?? 100) })),
146
+ vmem_list: args => read(args, index => index.list(str(args.prefix) ?? "", (args.limit as number | undefined) ?? 100, str(args.cursor))),
147
+ vmem_stats: args => vaultStats(home, pick(args).id, { expectedVault: pick(args), ...(typeof args.days === "number" ? { days: args.days } : {}) }),
136
148
  vmem_links: args => read(args, index => {
137
149
  const direction = str(args.direction) ?? "both", limit = (args.limit as number | undefined) ?? 50;
138
150
  const out = direction === "in" ? [] : index.links(str(args.path)!, limit);
@@ -152,7 +164,7 @@ export function createVaultMcp(home: string, env: NodeJS.ProcessEnv = process.en
152
164
  if (Array.isArray(args.topics)) frontmatter.topics = (args.topics as string[]).map(v => v.startsWith("[[") ? v : `[[${v}]]`);
153
165
  return write(args, { op: "create", path: str(args.stem)!, frontmatter, ...(str(args.body) !== undefined ? { body: str(args.body) } : {}) });
154
166
  },
155
- vmem_patch: args => write(args, { op: "patch", path: str(args.path)!, oldString: str(args.oldString)!, newString: str(args.newString)!, expectedSha: str(args.expectedSha) }),
167
+ vmem_patch: args => write(args, { op: "patch", path: str(args.path)!, ...(args.oldString !== undefined ? { oldString: str(args.oldString) } : {}), ...(args.newString !== undefined ? { newString: str(args.newString) } : {}), ...(args.edits !== undefined ? { edits: args.edits as PatchEdit[] } : {}), expectedSha: str(args.expectedSha) }),
156
168
  vmem_append: args => write(args, { op: "append", path: str(args.path)!, section: str(args.section)!, markdown: str(args.markdown)!, expectedSha: str(args.expectedSha) }),
157
169
  vmem_set_frontmatter: args => write(args, { op: "frontmatter", path: str(args.path)!, set: (args.set as Record<string, unknown> | undefined) ?? {}, ...(args.unset ? { unset: args.unset as string[] } : {}), expectedSha: str(args.expectedSha) }),
158
170
  vmem_link: args => write(args, { op: "link", from: str(args.from)!, to: str(args.to)!, relation: args.relation as Extract<WriteOp, { op: "link" }>["relation"], ...(str(args.context) ? { context: str(args.context) } : {}), bidirectional: args.bidirectional !== false }),
@@ -1,5 +1,7 @@
1
1
  import { promoteToOrg } from "./org-promote.ts";
2
2
  import { syncVault } from "./sync.ts";
3
+ import { PLAIN, type TextOptions } from "./text-output.ts";
4
+ import { renderOrgPromote, renderSync } from "./write-output.ts";
3
5
 
4
6
  function parse(command: string, args: string[], values: string[], booleans: string[]) {
5
7
  const flags: Record<string, string | boolean> = {}, positional: string[] = [];
@@ -15,17 +17,17 @@ function parse(command: string, args: string[], values: string[], booleans: stri
15
17
  return { flags, positional, value: (name: string) => typeof flags[name] === "string" ? flags[name] as string : undefined };
16
18
  }
17
19
  /** `vmem promote <vault> <note> --to <org>` and `vmem sync <vault>`: both preview unless `--confirm --fingerprint`. */
18
- export function runOrgCommand(command: string, args: string[], home: string, env: NodeJS.ProcessEnv): { text: string; code: number } {
20
+ export function runOrgCommand(command: string, args: string[], home: string, env: NodeJS.ProcessEnv, text: TextOptions = PLAIN): { text: string; code: number } {
19
21
  if (command === "promote") {
20
22
  const { flags, positional, value } = parse(command, args, ["--to", "--topics", "--fingerprint", "--log-project"], ["--again", "--confirm", "--json"]);
21
23
  if (positional.length !== 2 || !value("--to")) throw new Error("promote: requires personal vault id, note and --to <org vault>");
22
24
  const result = promoteToOrg(home, { from: positional[0]!, note: positional[1]!, to: value("--to")!, again: flags["--again"] === true, confirm: flags["--confirm"] === true,
23
25
  ...(value("--topics") ? { topics: value("--topics")!.split(",").map(t => t.trim()).filter(Boolean) } : {}),
24
26
  ...(value("--fingerprint") ? { fingerprint: value("--fingerprint") } : {}), ...(value("--log-project") ? { logProject: value("--log-project") } : {}), channel: "cli" }, { env });
25
- return { text: JSON.stringify(result, null, flags["--json"] ? undefined : 2), code: result.ok ? 0 : 1 };
27
+ return { text: flags["--json"] ? JSON.stringify(result) : renderOrgPromote(result, text, { argv: [command, ...args], positional }), code: result.ok ? 0 : 1 };
26
28
  }
27
29
  const { flags, positional, value } = parse(command, args, ["--fingerprint", "--message"], ["--confirm", "--json"]);
28
30
  if (positional.length !== 1) throw new Error("sync: requires vault id");
29
31
  const result = syncVault(home, { vault: positional[0]!, confirm: flags["--confirm"] === true, ...(value("--fingerprint") ? { fingerprint: value("--fingerprint") } : {}), ...(value("--message") ? { message: value("--message") } : {}) }, { env });
30
- return { text: JSON.stringify(result, null, flags["--json"] ? undefined : 2), code: result.ok ? 0 : 1 };
32
+ return { text: flags["--json"] ? JSON.stringify(result) : renderSync(result, text, { argv: [command, ...args], positional }), code: result.ok ? 0 : 1 };
31
33
  }
@@ -1,3 +1,4 @@
1
+ import { domainProblem } from "./config.ts";
1
2
  import { localDate } from "./local-date.ts";
2
3
  import { createHash } from "node:crypto";
3
4
  import { closeSync, constants, fstatSync, openSync, readSync, realpathSync } from "node:fs";
@@ -183,6 +184,8 @@ export function promoteToOrg(home: string, request: OrgPromoteRequest, options:
183
184
  const original = readSource(source, path);
184
185
  let parsed;
185
186
  try { parsed = parseFrontmatter(original); } catch { return fail(issue("V01", "source frontmatter is not parseable", path)); }
187
+ const domain = parsed.data.type === "moc" && parsed.data.domain === undefined ? undefined : domainProblem(parsed.data.domain, target);
188
+ if (domain) return fail(issue("V01", domain, path));
186
189
  const promotedTo = `${target.id}:${path}`;
187
190
  const prior = strings(parsed.data.promoted_to);
188
191
  if (prior.length && !request.again) return fail(issue("AGAIN", `already promoted to ${prior.join(", ")}; pass --again to promote again`, path));
@@ -6,6 +6,8 @@ import { loadRegistry } from "./registry.ts";
6
6
  import { canonicalPath, isDenied } from "./platform.ts";
7
7
  import { MAX_WRITE_BYTES } from "./writer.ts";
8
8
  import { listPromotionCandidates, promoteFromAmem, type PromoteRequest } from "./promote.ts";
9
+ import { PLAIN, type TextOptions } from "./text-output.ts";
10
+ import { renderCandidates, renderPromote } from "./write-output.ts";
9
11
 
10
12
  const VALUES = ["--project", "--limit", "--stem", "--type", "--domain", "--topics", "--description", "--title", "--body", "--link-to", "--log-project", "--fingerprint"];
11
13
  const BOOLEANS = ["--all-projects", "--edit", "--confirm", "--json"];
@@ -35,7 +37,7 @@ function editBody(draft: string, env: NodeJS.ProcessEnv, stdinIsTTY: boolean): s
35
37
  } finally { rmSync(dir, { recursive: true, force: true }); }
36
38
  }
37
39
  /** `vmem promote-from-amem <vault> [<mem-id>] ...`: lists candidates, previews, or confirms one promotion. */
38
- export async function runPromoteCommand(args: string[], home: string, env: NodeJS.ProcessEnv, io: { stdinIsTTY?: boolean } = {}): Promise<{ text: string; code: number }> {
40
+ export async function runPromoteCommand(args: string[], home: string, env: NodeJS.ProcessEnv, io: { stdinIsTTY?: boolean } = {}, text: TextOptions = PLAIN): Promise<{ text: string; code: number }> {
39
41
  const flags: Record<string, string | boolean> = {}, positional: string[] = [];
40
42
  for (let i = 0; i < args.length; i++) {
41
43
  const arg = args[i]!;
@@ -47,7 +49,7 @@ export async function runPromoteCommand(args: string[], home: string, env: NodeJ
47
49
  flags[arg] = value;
48
50
  }
49
51
  const value = (name: string) => typeof flags[name] === "string" ? flags[name] as string : undefined;
50
- const format = (result: unknown) => JSON.stringify(result, null, flags["--json"] ? undefined : 2);
52
+ const json = flags["--json"] === true, ctx = { argv: ["promote-from-amem", ...args], positional };
51
53
  if (positional.length < 1 || positional.length > 2) throw new Error("promote-from-amem: requires vault id and optional mem id");
52
54
  const [vault, rawId] = positional as [string, string | undefined];
53
55
  if (!loadRegistry(home).vaults.some(v => v.id === vault)) throw new Error("promote-from-amem: unknown vault id");
@@ -55,7 +57,7 @@ export async function runPromoteCommand(args: string[], home: string, env: NodeJ
55
57
  if (flags["--all-projects"] && value("--project")) throw new Error("choose either --all-projects or --project");
56
58
  const limit = value("--limit") === undefined ? undefined : /^[0-9]+$/.test(value("--limit")!) ? Number(value("--limit")) : NaN;
57
59
  const list = await listPromotionCandidates({ env, allProjects: flags["--all-projects"] === true, ...(value("--project") ? { project: value("--project") } : {}), ...(limit !== undefined ? { limit } : {}), piiPatterns: loadRegistry(home).piiPatterns });
58
- return { text: format(list), code: 0 };
60
+ return { text: json ? JSON.stringify(list) : renderCandidates(list, text, ctx), code: 0 };
59
61
  }
60
62
  if (flags["--all-projects"]) throw new Error("--all-projects lists candidates only");
61
63
  const request: PromoteRequest = { vault, id: rawId.replace(/^mem:/, ""), channel: "cli", confirm: flags["--confirm"] === true };
@@ -73,5 +75,5 @@ export async function runPromoteCommand(args: string[], home: string, env: NodeJ
73
75
  }
74
76
  const result = await promoteFromAmem(home, request, options);
75
77
  const edited = flags["--edit"] && request.body !== undefined && value("--body") === undefined;
76
- return { text: format(edited ? { ...result, hint: "edited text is only previewed: save it and confirm with --body <file> and this fingerprint" } : result), code: result.ok ? 0 : 1 };
78
+ return { text: json ? JSON.stringify(edited ? { ...result, hint: "edited text is only previewed: save it and confirm with --body <file> and this fingerprint" } : result) : renderPromote(result, text, ctx, !!edited), code: result.ok ? 0 : 1 };
77
79
  }
@@ -1,8 +1,12 @@
1
1
  import { loadRegistry } from "./registry.ts";
2
2
  import { VaultIndex, MAX_NOTE_BYTES } from "./vault-index.ts";
3
+ import { PLAIN, type TextOptions } from "./text-output.ts";
4
+ import { linksText, rebuildText, searchText, showText } from "./read-output.ts";
5
+ import type { NoteReadResult, SearchResult } from "./vault-index.ts";
6
+ import type { ResolvedLink } from "./links.ts";
3
7
  const READ_COMMANDS = new Set(["rebuild", "search", "show", "links"]);
4
8
  export function isReadCommand(command: string): boolean { return READ_COMMANDS.has(command); }
5
- export function runReadCommand(command: string, args: string[], home: string): { text: string; code: number } {
9
+ export function runReadCommand(command: string, args: string[], home: string, text: TextOptions = PLAIN): { text: string; code: number } {
6
10
  const options: Record<string, string | boolean> = {}, positional: string[] = [];
7
11
  const allowed = command === "search" ? ["--limit", "--type", "--domain"] : command === "show" ? ["--max-bytes", "--section", "--offset"] : command === "links" ? ["--limit"] : [];
8
12
  for (let i = 0; i < args.length; i++) {
@@ -39,5 +43,11 @@ export function runReadCommand(command: string, args: string[], home: string): {
39
43
  else if (command === "links") result = index.links(positional[1]!, limit);
40
44
  else throw new Error("unknown read command");
41
45
  } finally { index.close(); }
42
- return { text: JSON.stringify(result, null, options["--json"] ? undefined : 2), code: 0 };
46
+ if (options["--json"]) return { text: JSON.stringify(result), code: 0 };
47
+ const vaultId = vault.id, target = positional[1]!;
48
+ const out = command === "rebuild" ? rebuildText(result as Parameters<typeof rebuildText>[0], text)
49
+ : command === "search" ? searchText(result as SearchResult[], text, { vault: vaultId, query: target, limit: limit ?? 50, type: options["--type"] as string | undefined, domain: options["--domain"] as string | undefined })
50
+ : command === "show" ? showText(result as NoteReadResult, text, { vault: vaultId, target, maxBytes })
51
+ : linksText(result as ResolvedLink[], text, { vault: vaultId, target, limit: limit ?? 50 });
52
+ return { text: out, code: 0 };
43
53
  }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Text views for the read, log and analysis commands (#114). Each renderer is pure, takes the same result the
3
+ * command prints with `--json`, and never shows more than that result carries.
4
+ */
5
+ import type { SearchResult, NoteReadResult } from "./vault-index.ts";
6
+ import type { ResolvedLink } from "./links.ts";
7
+ import type { LogReadResult, LogReceipt } from "./log-types.ts";
8
+ import type { LintCode, LintReport } from "./analysis-types.ts";
9
+ import type { GraphNeighborhood } from "./vault-graph.ts";
10
+ import type { WriteIssue, WriteReceipt } from "./write-types.ts";
11
+ import { blocks, clean, fields, heading, issueTable, nextCommand, paint, paragraph, plural, shellWord, table, tone, type TextOptions, stripTerminal } from "./text-output.ts";
12
+
13
+ const command = (...words: string[]) => ["vmem", ...words].map(shellWord).join(" ");
14
+
15
+ export function searchText(hits: SearchResult[], o: TextOptions, c: { vault: string; query: string; limit: number; type?: string; domain?: string }): string {
16
+ const count = `${plural(hits.length, "result")} for ${JSON.stringify(clean(c.query))}`;
17
+ if (!hits.length) return count;
18
+ // Rows stay on one line so each snippet sits under its own hit.
19
+ const rows = table(["PATH", "TITLE", "TYPE"], hits.map(h => [h.path, h.title, h.type]), { ...o, columns: undefined }).split("\n");
20
+ const list = [rows[0]!, ...hits.flatMap((h, i) => [rows[i + 1]!, ...(stripTerminal(h.snippet).trim() ? [paragraph(stripTerminal(h.snippet).trim(), o, "muted", " ")] : [])])].join("\n");
21
+ const filters = [...(c.type ? ["--type", c.type] : []), ...(c.domain ? ["--domain", c.domain] : [])];
22
+ const more = hits.length >= c.limit && c.limit < 500 ? nextCommand("next", command("search", c.vault, c.query, ...filters, "--limit", String(Math.min(500, c.limit * 2))), o) : undefined;
23
+ return blocks(list, [count, more].filter(Boolean).join("\n"));
24
+ }
25
+
26
+ export function showText(r: NoteReadResult, o: TextOptions, c: { vault: string; target: string; maxBytes?: number }): string {
27
+ const head = [heading(r.path, o), fields([["section", r.section], ["sha256", r.hash.slice(0, 12)], ["bytes", Buffer.byteLength(r.content)], ["offset", r.offset]], o)].join("\n");
28
+ if (!r.truncated) return blocks(head, stripTerminal(r.content).replace(/\n+$/, ""));
29
+ const words = ["show", c.vault, c.target, ...(r.section ? ["--section", r.section] : []), ...(c.maxBytes !== undefined ? ["--max-bytes", String(c.maxBytes)] : []), "--offset", String(r.nextOffset)];
30
+ const tail = [paint("truncated", "warn", o), ...(r.nextOffset !== undefined ? [nextCommand("next", command(...words), o)] : [])];
31
+ const headings = r.headings?.length ? ["H2 headings (read one with --section):", ...r.headings.map(h => ` ${clean(h)}`), ...(r.headingsTruncated ? [paint(" ... more headings", "muted", o)] : [])].join("\n") : undefined;
32
+ return blocks(head, stripTerminal(r.content).replace(/\n+$/, ""), tail.join("\n"), headings);
33
+ }
34
+
35
+ export function linksText(links: ResolvedLink[], o: TextOptions, c: { vault: string; target: string; limit: number }): string {
36
+ const from = links[0]?.source ?? c.target;
37
+ const count = `${plural(links.length, "link")} from ${clean(from)}`;
38
+ if (!links.length) return count;
39
+ const target = (l: ResolvedLink) => l.target + (l.heading !== null ? `#${l.heading}` : "") + (l.block !== null ? `#^${l.block}` : "");
40
+ const rows = links.map(l => [target(l), l.resolved ?? tone(l.reason ?? "unresolved", "warn"), l.line]);
41
+ const more = links.length >= c.limit && c.limit < 500 ? nextCommand("next", command("links", c.vault, c.target, "--limit", String(Math.min(500, c.limit * 2))), o) : undefined;
42
+ return blocks(heading("OUT", o) + "\n" + table(["TARGET", "RESOLVED", "LINE"], rows, o), [count, more].filter(Boolean).join("\n"));
43
+ }
44
+
45
+ export function rebuildText(r: { vault: string; notes: number; changed: number; removed: number; skipped?: string[] }, _o: TextOptions): string {
46
+ return `rebuilt ${clean(r.vault)}: ${plural(r.notes, "note")}, ${r.changed} changed, ${r.removed} removed${r.skipped?.length ? `, ${r.skipped.length} skipped` : ""}`;
47
+ }
48
+
49
+ const warnings = (list: string[], o: TextOptions) => list.length ? list.map(w => paint(`warning: ${clean(w)}`, "warn", o)).join("\n") : undefined;
50
+ export function logReadText(r: LogReadResult, o: TextOptions, c: { command: "tail" | "grep"; vault: string; pattern?: string; limit: number; type?: string }): string {
51
+ if (!r.ok) return blocks(paint(`log ${c.command}: not read`, "fail", o), issueTable(r.issues, o), warnings(r.warnings, o));
52
+ const count = `${plural(r.lines.length, "line")}${r.dataLines !== null ? ` (log has ${r.dataLines})` : ""}`;
53
+ const words = ["log", c.command, c.vault, ...(c.pattern !== undefined ? [c.pattern] : []), ...(c.type ? ["--type", c.type] : []), "--limit", String(Math.min(200, c.limit * 2))];
54
+ const more = r.lines.length >= c.limit && c.limit < 200 ? nextCommand("next", command(...words), o) : undefined;
55
+ return blocks(r.lines.length ? r.lines.map(clean).join("\n") : undefined, [count, more].filter(Boolean).join("\n"), warnings(r.warnings, o), issueTable(r.issues, o));
56
+ }
57
+ export function logAppendText(r: LogReceipt, o: TextOptions, c: { vault: string; type: string }): string {
58
+ const line = r.ok && r.appended ? paint(`appended ${clean(c.type)} to the ${clean(c.vault)} log${r.bytesWritten ? ` (${plural(r.bytesWritten, "byte")})` : ""}`, "ok", o)
59
+ : paint(`log append: ${clean(c.type)} not appended${r.rolledBack ? " (rolled back)" : ""}`, "fail", o);
60
+ return blocks(line, issueTable(r.issues, o));
61
+ }
62
+
63
+ const LEVELS: Record<LintCode, "error" | "warn"> = { L01: "error", L02: "error", L03: "warn", L09: "warn", L10: "warn", L11: "warn", L12: "warn", L13: "error", L14: "warn" };
64
+ const verdict = (r: { errors: number; warnings: number; summary: string }, o: TextOptions) => paint(clean(r.summary), r.errors ? "fail" : r.warnings ? "warn" : "ok", o);
65
+ export function lintText(d: { report: LintReport; notes: number; titles: Record<LintCode, string>; info: Partial<Record<LintCode, string>> }, o: TextOptions, c: { vault: string; note?: string }): string {
66
+ const rows = (Object.keys(d.report.findings) as LintCode[]).flatMap(code => {
67
+ const check = d.titles[code].replace(" — ", " "), found = d.report.findings[code];
68
+ return [...(found.length ? found.map(f => [tone(LEVELS[code], LEVELS[code] === "error" ? "fail" : "warn"), check, f]) : [[tone("ok", "ok"), check, "위반 없음"]]),
69
+ ...(d.info[code] ? [[tone("info", "muted"), check, d.info[code]]] : [])];
70
+ });
71
+ return blocks(heading(`lint ${c.vault}${c.note ? ` ${c.note}` : ""}: ${plural(d.notes, "note")}`, o), table(["LEVEL", "CHECK", "FINDING"], rows, o), verdict(d.report, o));
72
+ }
73
+
74
+ /** `lint --write` and `graph build`: what was written or would be, then issues and the log event. */
75
+ export function analysisWriteText(r: { ok: boolean; applied: boolean; summary: unknown; paths: string[]; receipts: WriteReceipt[]; log?: LogReceipt }, o: TextOptions, c: { kind: "lint" | "graph"; dryRun: boolean }): string {
76
+ const verb = c.dryRun && r.ok ? "would write" : r.applied ? "wrote" : "did not write";
77
+ const line = paint(`${c.kind === "lint" ? "lint" : "graph build"}: ${verb} ${plural(r.paths.length, "report")}`, r.ok ? "ok" : "fail", o);
78
+ const s = (r.summary ?? {}) as Record<string, unknown>;
79
+ const counts = c.kind === "lint" ? verdict(s as { errors: number; warnings: number; summary: string }, o)
80
+ : fields((["nodes", "edges", "communities", "work_docs"] as const).map(k => [k.replace("_", " "), typeof s[k] === "number" ? s[k] : undefined]), o);
81
+ const issues: WriteIssue[] = [...r.receipts.flatMap(x => x.issues), ...(r.log?.issues ?? [])];
82
+ const logged = r.log ? (r.log.ok ? `logged ${c.kind === "lint" ? "LINT" : "GRAPH"} event` : paint("log event not appended", "fail", o)) : undefined;
83
+ return blocks(line, r.paths.map(p => ` ${clean(p)}`).join("\n"), counts, issueTable(issues, o), logged);
84
+ }
85
+
86
+ export function neighborsText(r: GraphNeighborhood, o: TextOptions, c: { vault: string; limit: number; relation?: string }): string {
87
+ // Hops and relations follow from the returned edges: every selected node's nearer neighbour is selected too.
88
+ const hops = new Map([[r.start, 0]]), queue = [r.start];
89
+ for (let i = 0; i < queue.length; i++) for (const e of r.edges) {
90
+ const other = e.source === queue[i] ? e.target : e.target === queue[i] ? e.source : undefined;
91
+ if (other !== undefined && !hops.has(other)) { hops.set(other, hops.get(queue[i]!)! + 1); queue.push(other); }
92
+ }
93
+ const relation = (id: string) => [...new Set(r.edges.filter(e => (e.source === id && hops.get(e.target) === hops.get(id)! - 1) || (e.target === id && hops.get(e.source) === hops.get(id)! - 1)).map(e => e.relation === "wiki_link" ? e.rel ?? e.relation : e.relation))].join(",");
94
+ const nodes = r.nodes.filter(n => n.id !== r.start).sort((a, b) => (hops.get(a.id) ?? 9) - (hops.get(b.id) ?? 9));
95
+ const count = `${plural(nodes.length, "neighbour")} of ${clean(r.start)} within ${plural(r.hops, "hop")}`;
96
+ const more = r.truncated && c.limit < 500 ? nextCommand("next", command("graph", "neighbors", c.vault, r.start, "--hops", String(r.hops), "--limit", String(Math.min(500, c.limit * 2)), ...(c.relation ? ["--relation", c.relation] : [])), o) : undefined;
97
+ if (!nodes.length) return [count, more].filter(Boolean).join("\n");
98
+ return blocks(table(["NOTE", "HOPS", "RELATION", "TITLE"], nodes.map(n => [n.id, hops.get(n.id), relation(n.id), n.label]), o), [count, more].filter(Boolean).join("\n"));
99
+ }
package/src/registry.ts CHANGED
@@ -4,7 +4,7 @@ import { realPath, memoryGitArgv, memoryGitEnv } from "./platform.ts";
4
4
  import { hostname } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { randomUUID } from "node:crypto";
7
- import { CONFIG_FILE, MAX_CONFIG_BYTES, parseConfig, parsePii, parseVault, parseSpec, piiExtensions, readConfig, type VaultSpec, type SpecSourceSpec, type VmemConfig } from "./config.ts";
7
+ import { CONFIG_FILE, MAX_CONFIG_BYTES, effectiveDomains, parseConfig, parsePii, parseVault, parseSpec, piiExtensions, readConfig, type VaultSpec, type SpecSourceSpec, type VmemConfig } from "./config.ts";
8
8
  import { loosenedCells, piiPolicy, piiShorthand } from "./pii.ts";
9
9
  export const LOCK_FILE = "config.lock";
10
10
  const TEMP = /^\.config-[0-9a-f-]{36}\.tmp$/;
@@ -44,6 +44,7 @@ function mutate<T>(home: string, update: (config: VmemConfig) => T): T {
44
44
  writeFileSync(lockFd, JSON.stringify(owner) + "\n");
45
45
  const config = loadRegistry(home), result = update(config);
46
46
  if (config.specs !== undefined) config.version = Math.max(config.version ?? 1, 2);
47
+ if (config.vaults.some(vault => vault.domains !== undefined)) config.version = Math.max(config.version ?? 1, 3);
47
48
  parseConfig(config);
48
49
  const text = JSON.stringify(config, null, 2) + "\n";
49
50
  if (Buffer.byteLength(text) > MAX_CONFIG_BYTES) throw new Error(`${join(home, CONFIG_FILE)}: serialized config exceeds 64 KiB`);
@@ -194,7 +195,7 @@ export function setVaultPii(home: string, id: string, value: unknown, confirm =
194
195
  export function registryStatus(home: string) {
195
196
  const config = loadRegistry(home);
196
197
  return config.vaults.map(vault => {
197
- const base = { ...vault, pii: effectivePii(vault), piiPolicy: piiPolicy(vault) };
198
+ const base = { ...vault, domains: effectiveDomains(vault), pii: effectivePii(vault), piiPolicy: piiPolicy(vault) };
198
199
  try {
199
200
  const root = realpathSync(vault.path), notes = join(root, "notes");
200
201
  if (root !== vault.path || realpathSync(notes) !== notes || !statSync(notes).isDirectory()) throw new Error("changed");