@staix/vault-mem 0.4.0 → 0.5.1

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.
package/src/cli.ts CHANGED
@@ -8,14 +8,16 @@ import { runOrgCommand } from "./org-commands.ts";
8
8
  import { isWriteCommand, runWriteCommand } from "./write-commands.ts";
9
9
  import { isReadCommand, runReadCommand } from "./read-commands.ts";
10
10
  import { version } from "../package.json";
11
- import { COMMANDS, completionScript, help } from "./commands-table.ts";
11
+ import { COMMANDS, commandUsage, completionScript, help } from "./commands-table.ts";
12
12
  import { VMEM_TOOL_NAMES, vaultTools } from "./mcp-vault.ts";
13
- import { CONFIG_VERSION } from "./config.ts";
13
+ import { CONFIG_VERSION, effectiveDomains } from "./config.ts";
14
14
  import { runSetup, type SetupMode } from "./setup.ts";
15
15
  import { resolveHome } from "./home.ts";
16
16
  import { addVault, addSpec, removeSpec, specStatus, effectivePii, loadRegistry, recoverRegistry, registryStatus, removeVault, setVaultPii } from "./registry.ts";
17
17
  import { piiPolicy } from "./pii.ts";
18
18
  import { vaultStats } from "./vault-stats.ts";
19
+ import { PLAIN, shellWord, takeColorFlag, textOptions, type TextOptions } from "./text-output.ts";
20
+ import { renderDoctor, renderManifest, renderRecover, renderRemove, renderSetup, renderSpecAdd, renderSpecsList, renderStats, renderStatus, renderVaultAdd, renderVaultPii, renderVaultsList, type StatusResult } from "./cli-output.ts";
19
21
  function parse(args: string[], allowed: string[], values: string[]) {
20
22
  const flags: Record<string, string | boolean> = {}, positional: string[] = [];
21
23
  for (let i = 0; i < args.length; i++) {
@@ -30,17 +32,30 @@ function parse(args: string[], allowed: string[], values: string[]) {
30
32
  }
31
33
  return { flags, positional };
32
34
  }
33
- function commandHelp(args: string[]): string | undefined {
35
+ /** `vmem help <command>` and `<command> --help|-h`: that command's help entries. */
36
+ function commandHelp(args: string[], o: TextOptions): string | undefined {
37
+ if (args[0] === "help" && args.length > 1) {
38
+ const name = args.slice(1).join(" ");
39
+ const text = commandUsage(name, o);
40
+ if (!text) throw new Error(`help: unknown command ${name}; run vmem help for the command list`);
41
+ return text;
42
+ }
34
43
  if (args.includes("--")) return undefined;
35
44
  if (!["--help", "-h"].includes(args.at(-1) ?? "")) return undefined;
36
45
  const name = args.slice(0, -1).join(" ");
37
46
  if (!name) return undefined;
38
- const commands = COMMANDS.filter(command => command.name === name || command.name.startsWith(name + " "));
39
- return commands.length ? commands.map(command => `Usage: vmem ${command.usage}`).join("\n") : undefined;
47
+ return commandUsage(name, o);
48
+ }
49
+ /** Where the text goes; library callers and tests default to a non-terminal, `main` passes the real stdout. */
50
+ export interface Stdout { isTTY?: boolean; columns?: number }
51
+ /** Runs one command; `--color=auto|always|never` is taken off first and decides the text options for `stdout`. */
52
+ export function run(args: string[], env: NodeJS.ProcessEnv = process.env, stdout: Stdout = {}): { text: string; code: number } {
53
+ const taken = takeColorFlag(args);
54
+ return runWith(taken.args, env, textOptions(taken.color, env, stdout));
40
55
  }
41
- export function run(args: string[], env: NodeJS.ProcessEnv = process.env): { text: string; code: number } {
42
- if (!args.length || (args.length === 1 && ["--help", "-h", "help"].includes(args[0]!))) return { text: help(), code: 0 };
43
- const usage = commandHelp(args);
56
+ function runWith(args: string[], env: NodeJS.ProcessEnv, text: TextOptions = PLAIN): { text: string; code: number } {
57
+ if (!args.length || (args.length === 1 && ["--help", "-h", "help"].includes(args[0]!))) return { text: help(text), code: 0 };
58
+ const usage = commandHelp(args, text);
44
59
  if (usage) return { text: usage, code: 0 };
45
60
  if (args.length === 1 && args[0] === "--version") return { text: version, code: 0 };
46
61
  if (args[0] === "manifest") {
@@ -50,32 +65,33 @@ export function run(args: string[], env: NodeJS.ProcessEnv = process.env): { tex
50
65
  const readOnly = new Set([...vaultTools([]), ...specTools()].filter(t => t.annotations.readOnlyHint).map(t => t.name));
51
66
  const tools = VMEM_TOOL_NAMES.map(name => readOnly.has(name) ? { name, readOnly: true } : name);
52
67
  const manifest = { name: "@staix/vault-mem", version, configVersion: CONFIG_VERSION, mcp: { server: "vmem", tools }, commands: COMMANDS.map(c => c.name) };
53
- return { text: JSON.stringify(manifest, null, flags["--json"] ? undefined : 2), code: 0 };
68
+ return { text: flags["--json"] ? JSON.stringify(manifest) : renderManifest(manifest, text), code: 0 };
54
69
  }
55
70
  if (args[0] === "setup") {
56
71
  const { flags, positional } = parse(args.slice(1), ["--apply", "--undo", "--json", "--root"], ["--root"]);
57
72
  if (positional.length !== 1 || (flags["--apply"] && flags["--undo"])) throw new Error("setup: requires one target and at most one of --apply/--undo");
58
73
  const mode: SetupMode = flags["--apply"] ? "apply" : flags["--undo"] ? "undo" : "dry-run";
59
74
  const report = runSetup(positional[0]!, mode, { home: resolveHome(env).home, env, ...(typeof flags["--root"] === "string" ? { root: flags["--root"] } : {}) });
60
- return { text: JSON.stringify(report, null, flags["--json"] ? undefined : 2), code: [...report.actions, report.console].some(a => a?.change === "refused") ? 1 : 0 };
75
+ const apply = ["vmem", "setup", positional[0]!, "--apply", ...(typeof flags["--root"] === "string" ? ["--root", flags["--root"]] : [])].map(shellWord).join(" ");
76
+ return { text: flags["--json"] ? JSON.stringify(report) : renderSetup(report, text, apply), code: [...report.actions, report.console].some(a => a?.change === "refused") ? 1 : 0 };
61
77
  }
62
78
  if (args[0] === "completion") {
63
79
  if (args.length !== 2) throw new Error("completion: requires bash, zsh or fish");
64
80
  return { text: completionScript(args[1]!).trimEnd(), code: 0 };
65
81
  }
66
- if (args[0] === "spec") return runSpecCommand(args.slice(1), env);
67
- if (args[0] === "lint" || args[0] === "graph") return runAnalysisCommand(args[0],args.slice(1),resolveHome(env).home,env);
68
- if (args[0] === "promote" || args[0] === "sync") return runOrgCommand(args[0], args.slice(1), resolveHome(env).home, env);
69
- if (args[0] === "log") return runLogCommand(args.slice(1), resolveHome(env).home, env);
70
- if (isWriteCommand(args[0]!)) return runWriteCommand(args[0]!, args.slice(1), resolveHome(env).home, env);
71
- if (isReadCommand(args[0]!)) return runReadCommand(args[0]!, args.slice(1), resolveHome(env).home);
82
+ if (args[0] === "spec") return runSpecCommand(args.slice(1), env, text);
83
+ if (args[0] === "lint" || args[0] === "graph") return runAnalysisCommand(args[0],args.slice(1),resolveHome(env).home,env,text);
84
+ if (args[0] === "promote" || args[0] === "sync") return runOrgCommand(args[0], args.slice(1), resolveHome(env).home, env, text);
85
+ if (args[0] === "log") return runLogCommand(args.slice(1), resolveHome(env).home, env, text);
86
+ if (isWriteCommand(args[0]!)) return runWriteCommand(args[0]!, args.slice(1), resolveHome(env).home, env, text);
87
+ if (isReadCommand(args[0]!)) return runReadCommand(args[0]!, args.slice(1), resolveHome(env).home, text);
72
88
  const group = args[0] === "vaults" || args[0] === "specs";
73
89
  const command = group ? `${args[0]} ${args[1] ?? ""}` : args[0];
74
90
  const tail = args.slice(group ? 2 : 1);
75
91
  const options = command === "vaults add" ? ["--kind", "--write", "--pii", "--remote", "--registry"] : command === "vaults pii" ? ["--set"] : command === "specs add" ? ["--write", "--pii"] : command === "stats" ? ["--days"] : [];
76
92
  const { flags, positional } = parse(tail, ["--json", ...options, ...(command === "vaults remove" || command === "specs remove" || command === "vaults pii" || command === "recover" ? ["--confirm"] : [])], options);
77
93
  const home = resolveHome(env);
78
- let result: unknown, code = 0;
94
+ let result: unknown, code = 0, render: () => string;
79
95
  switch (command) {
80
96
  case "status": case "doctor": {
81
97
  if (positional.length) throw new Error(`${command}: unexpected arguments`);
@@ -85,7 +101,7 @@ export function run(args: string[], env: NodeJS.ProcessEnv = process.env): { tex
85
101
  const checks: Record<string, { ok: boolean; issue?: string }> = {};
86
102
  if (vault.remote) {
87
103
  try {
88
- const checked = originCheck(vault.path, vault.remote, env);
104
+ const checked = originCheck(vault.path, vault.remote, env, "doctor");
89
105
  checks.remote = { ok: checked.ok, ...(checked.issue ? { issue: checked.issue } : {}) };
90
106
  } catch (error) { checks.remote = { ok: false, issue: error instanceof Error ? error.message : "git failed" }; }
91
107
  }
@@ -109,7 +125,9 @@ export function run(args: string[], env: NodeJS.ProcessEnv = process.env): { tex
109
125
  });
110
126
  const sources = command === "doctor" && config.specs !== undefined ? specStatus(home.home, env) : undefined;
111
127
  const healthy = vaults.every(v => v.healthy && (!v.checks || Object.values(v.checks).every(check => check.ok))) && (!sources || sources.every(source => source.healthy));
112
- result = { ...home, version, healthy, vaults, ...(config.specs !== undefined ? { specs: sources ?? config.specs } : {}) };
128
+ const status: StatusResult = { ...home, version, healthy, vaults, ...(config.specs !== undefined ? { specs: sources ?? config.specs } : {}) };
129
+ result = status;
130
+ render = () => command === "doctor" ? renderDoctor(status, text) : renderStatus(status, text);
113
131
  if (command === "doctor" && !healthy) code = 1;
114
132
  break;
115
133
  }
@@ -118,39 +136,49 @@ export function run(args: string[], env: NodeJS.ProcessEnv = process.env): { tex
118
136
  const days = flags["--days"];
119
137
  if (days !== undefined && !/^[0-9]+$/.test(String(days))) throw new Error("stats: --days expects an integer 1..3650; omit it for the 30-day default");
120
138
  const stats = vaultStats(home.home, positional[0]!, days === undefined ? {} : { days: Number(days) });
121
- result = stats;
139
+ result = stats; render = () => renderStats(stats, text);
122
140
  if (stats.log.issues.length) code = 1;
123
141
  break;
124
142
  }
125
- case "recover":
143
+ case "recover": {
126
144
  if (positional.length) throw new Error("recover: unexpected arguments");
127
- result = recoverRegistry(home.home, flags["--confirm"] === true);
128
- if ((result as { blocked?: string }).blocked) code = 1;
145
+ const report = recoverRegistry(home.home, flags["--confirm"] === true);
146
+ result = report; render = () => renderRecover(report, text);
147
+ if (report.blocked) code = 1;
129
148
  break;
130
- case "specs list":
149
+ }
150
+ case "specs list": {
131
151
  if (positional.length) throw new Error("specs list: unexpected targets; use vmem specs list [--json]");
132
- result = loadRegistry(home.home).specs ?? [];
152
+ const specs = loadRegistry(home.home).specs ?? [];
153
+ result = specs; render = () => renderSpecsList(specs, text);
133
154
  break;
155
+ }
134
156
  case "specs add": {
135
157
  if (positional.length !== 2) throw new Error("specs add: requires id and absolute repository root; use vmem specs add <id> <absolute-path> [--write mcp|cli|none] [--pii allow|deny]");
136
158
  const value: Record<string, unknown> = { id: positional[0], path: positional[1] };
137
159
  for (const option of options) if (flags[option] !== undefined) value[option.slice(2)] = flags[option];
138
- result = { applied: true, spec: addSpec(home.home, value, env) };
160
+ const added = { applied: true, spec: addSpec(home.home, value, env) };
161
+ result = added; render = () => renderSpecAdd(added, text);
139
162
  break;
140
163
  }
141
- case "specs remove":
164
+ case "specs remove": {
142
165
  if (positional.length !== 1) throw new Error("specs remove: requires one id; use vmem specs list, then vmem specs remove <id> [--confirm]");
143
- result = removeSpec(home.home, positional[0]!, flags["--confirm"] === true);
166
+ const removed = removeSpec(home.home, positional[0]!, flags["--confirm"] === true);
167
+ result = removed; render = () => renderRemove("specs", removed, text);
144
168
  break;
145
- case "vaults list":
169
+ }
170
+ case "vaults list": {
146
171
  if (positional.length) throw new Error("vaults list: unexpected arguments");
147
- result = loadRegistry(home.home).vaults.map(v => ({ ...v, pii: effectivePii(v), piiPolicy: piiPolicy(v) }));
172
+ const vaults = loadRegistry(home.home).vaults.map(v => ({ ...v, domains: effectiveDomains(v), pii: effectivePii(v), piiPolicy: piiPolicy(v) }));
173
+ result = vaults; render = () => renderVaultsList(vaults, text);
148
174
  break;
175
+ }
149
176
  case "vaults add": {
150
177
  if (positional.length !== 2) throw new Error("vaults add: requires id and absolute path");
151
178
  const value: Record<string, unknown> = { id: positional[0], path: positional[1] };
152
179
  for (const option of options) if (flags[option] !== undefined) value[option.slice(2)] = flags[option];
153
- result = { applied: true, vault: addVault(home.home, value) };
180
+ const added = { applied: true, vault: addVault(home.home, value) };
181
+ result = added; render = () => renderVaultAdd(added, text);
154
182
  break;
155
183
  }
156
184
  case "vaults pii": {
@@ -159,16 +187,20 @@ export function run(args: string[], env: NodeJS.ProcessEnv = process.env): { tex
159
187
  if (raw === undefined && flags["--confirm"] === true) throw new Error("vaults pii: --confirm requires --set");
160
188
  let value: unknown;
161
189
  if (typeof raw === "string") { if (raw === "allow" || raw === "deny") value = raw; else { try { value = JSON.parse(raw); } catch { throw new Error("vaults pii: --set expects allow, deny or a JSON policy object"); } } }
162
- result = setVaultPii(home.home, positional[0]!, value, flags["--confirm"] === true);
190
+ const pii = setVaultPii(home.home, positional[0]!, value, flags["--confirm"] === true);
191
+ const confirm = typeof raw === "string" ? ["vmem", "vaults", "pii", positional[0]!, "--set", raw, "--confirm"].map(shellWord).join(" ") : undefined;
192
+ result = pii; render = () => renderVaultPii(pii, text, confirm);
163
193
  break;
164
194
  }
165
- case "vaults remove":
195
+ case "vaults remove": {
166
196
  if (positional.length !== 1) throw new Error("vaults remove: requires id");
167
- result = removeVault(home.home, positional[0]!, flags["--confirm"] === true);
197
+ const removed = removeVault(home.home, positional[0]!, flags["--confirm"] === true);
198
+ result = removed; render = () => renderRemove("vaults", removed, text);
168
199
  break;
200
+ }
169
201
  default: throw new Error(`unknown command: ${command}; use --help`);
170
202
  }
171
- return { text: JSON.stringify(result, null, flags["--json"] ? undefined : 2), code };
203
+ return { text: flags["--json"] ? JSON.stringify(result) : render(), code };
172
204
  }
173
205
  /**
174
206
  * `vmem mcp`: the vault set is fixed now; stdout carries protocol frames only. Every module a tool handler
@@ -183,22 +215,23 @@ export async function runMcp(env: NodeJS.ProcessEnv = process.env): Promise<void
183
215
  await serveMcp({ tools: server.tools, handlers: server.handlers, name: "vmem", version });
184
216
  }
185
217
  /** Async commands. Only `promote-from-amem` and `skills mine` load the agent-mem seam, and only when they run. */
186
- export async function runAsync(args: string[], env: NodeJS.ProcessEnv = process.env, io: { stdinIsTTY?: boolean } = {}): Promise<{ text: string; code: number }> {
187
- const usage = commandHelp(args);
218
+ export async function runAsync(argv: string[], env: NodeJS.ProcessEnv = process.env, io: { stdinIsTTY?: boolean; stdout?: Stdout } = {}): Promise<{ text: string; code: number }> {
219
+ const taken = takeColorFlag(argv), args = taken.args, text = textOptions(taken.color, env, io.stdout ?? {});
220
+ const usage = commandHelp(args, text);
188
221
  if (usage) return { text: usage, code: 0 };
189
222
  if (args[0] === "skills") {
190
223
  const { runSkillsCommand } = await import("./skills-mine.ts");
191
- return runSkillsCommand(args.slice(1), resolveHome(env).home, env);
224
+ return runSkillsCommand(args.slice(1), resolveHome(env).home, env, text);
192
225
  }
193
- if (args[0] !== "promote-from-amem") return run(args, env);
226
+ if (args[0] !== "promote-from-amem") return runWith(args, env, text);
194
227
  const { runPromoteCommand } = await import("./promote-command.ts");
195
- return runPromoteCommand(args.slice(1), resolveHome(env).home, env, io);
228
+ return runPromoteCommand(args.slice(1), resolveHome(env).home, env, io, text);
196
229
  }
197
230
  export async function mainAsync(args: string[]): Promise<number> {
198
- try { const output = await runAsync(args, process.env, { stdinIsTTY: process.stdin.isTTY === true }); console.log(output.text); return output.code; }
231
+ try { const output = await runAsync(args, process.env, { stdinIsTTY: process.stdin.isTTY === true, stdout: process.stdout }); console.log(output.text); return output.code; }
199
232
  catch (error) { console.error(`vmem: ${error instanceof Error ? error.message : "operation failed"}`); return 1; }
200
233
  }
201
234
  export function main(args: string[]): number {
202
- try { const output = run(args); console.log(output.text); return output.code; }
235
+ try { const output = run(args, process.env, process.stdout); console.log(output.text); return output.code; }
203
236
  catch (error) { console.error(`vmem: ${error instanceof Error ? error.message : "operation failed"}`); return 1; }
204
237
  }
@@ -1,47 +1,59 @@
1
- import { SPEC_COMMANDS } from "./spec-command-table.ts";
1
+ import { SPEC_COMMANDS, type SpecCommand } from "./spec-command-table.ts";
2
+ import { version } from "../package.json";
3
+ import { paint, paragraph, width, wrap, type TextOptions } from "./text-output.ts";
4
+ /** One-line help per spec command; the longer SPEC_COMMANDS descriptions are the MCP tool descriptions. */
5
+ const SPEC_HELP: Record<SpecCommand, string> = {
6
+ get: "read a spec's metadata, links and freshness; optionally page its body",
7
+ graph: "read a bounded slice of the spec graph",
8
+ grep: "search specs by terms or literal text with metadata filters",
9
+ validate: "validate specs and report errors, warnings and freshness",
10
+ };
11
+ /** Help sections in print order; every COMMANDS entry names one. */
12
+ export const HELP_SECTIONS = ["Registry", "Read", "Write", "Log", "Analysis", "Promotion and sync", "Design specs", "Setup"] as const;
13
+ interface CommandEntry { name: string; usage: string; mutates: boolean | string; section: typeof HELP_SECTIONS[number]; description: string }
2
14
  export const COMMANDS = [
3
- ...SPEC_COMMANDS.map(item => ({ name: `spec ${item.command}`, usage: item.usage, mutates: false })),
4
- { name: "lint", usage: "lint <vault> [--note PATH] [--write] [--dry-run] [--json]", mutates: "write" },
5
- { name: "graph build", usage: "graph build <vault> [--workspace] [--dry-run] [--json]", mutates: true },
6
- { name: "graph neighbors", usage: "graph neighbors <vault> <stem> [--hops 1..2] [--limit 1..500] [--json]", mutates: false },
7
- { name: "skills mine", usage: "skills mine <vault> [--days N] [--project KEY|--all-projects] [--vocab DIR] [--skills DIR] [--min-size N] [--min-novelty X] [--json]", mutates: false },
8
- { name: "rebuild", usage: "rebuild <vault> [--json]", mutates: "cache" },
9
- { name: "search", usage: "search <vault> <query> [--type TYPE] [--domain DOMAIN] [--limit 1..500] [--json]", mutates: "cache" },
10
- { name: "show", usage: "show <vault> <target> [--section TEXT] [--offset 0..2097152] [--max-bytes 1..65536] [--json]", mutates: "cache" },
11
- { name: "links", usage: "links <vault> <target> [--limit 1..500] [--json]", mutates: "cache" },
12
- { name: "status", usage: "status [--json]", mutates: false },
13
- { name: "doctor", usage: "doctor [--json]", mutates: false },
14
- { name: "recover", usage: "recover [--confirm] [--json]", mutates: "confirm" },
15
- { name: "vaults list", usage: "vaults list [--json]", mutates: false },
16
- { name: "vaults add", usage: "vaults add <id> <absolute-path> --kind personal|org --write mcp|cli|none [--pii allow|deny] [--remote URL] [--registry PATH] [--json]", mutates: true },
17
- { name: "vaults remove", usage: "vaults remove <id> [--confirm] [--json]", mutates: "confirm" },
18
- { name: "vaults pii", usage: "vaults pii <id> [--set allow|deny|JSON] [--confirm] [--json]", mutates: "confirm" },
19
- { name: "specs list", usage: "specs list [--json]", mutates: false },
20
- { name: "specs add", usage: "specs add <id> <absolute-path> [--write mcp|cli|none] [--pii allow|deny] [--json]", mutates: true },
21
- { name: "specs remove", usage: "specs remove <id> [--confirm] [--json]", mutates: "confirm" },
22
- { name: "new", usage: "new <vault> <stem> --type TYPE --domain DOMAIN --topics a,b --description TEXT [--title TEXT] [--source TEXT|JSON] [--confidence TEXT] [--status TEXT] [--body file|-] [--extra JSON] [--log JSON] [--dry-run] [--json]", mutates: true },
23
- { name: "patch", usage: "patch <vault> <note> [--old TEXT --new TEXT] [--edits file|-] [--expected-sha SHA] [--log JSON] [--dry-run] [--json]", mutates: true },
24
- { name: "append", usage: "append <vault> <note> --section SECTION --markdown TEXT [--expected-sha SHA] [--log JSON] [--dry-run] [--json]", mutates: true },
25
- { name: "frontmatter", usage: "frontmatter <vault> <note> [--set JSON] [--unset key,key] [--expected-sha SHA] [--log JSON] [--dry-run] [--json]", mutates: true },
26
- { name: "link", usage: "link <vault> <from> <to> --relation R [--context TEXT] [--one-way] [--log JSON] [--dry-run] [--json]", mutates: true },
27
- { name: "supersede", usage: "supersede <vault> <old> <next> [--log JSON] [--dry-run] [--json]", mutates: true },
28
- { name: "move", usage: "move <vault> <from> <to> [--confirm --fingerprint SHA] [--log JSON] [--dry-run] [--json]", mutates: "confirm" },
29
- { name: "delete", usage: "delete <vault> <note> [--confirm --fingerprint SHA] [--log JSON] [--dry-run] [--json]", mutates: "confirm" },
30
- { name: "tidy", usage: "tidy <vault> [--connections] [--escapes] [--enums] [--keys] [--sources] [--topics] [--secrets] [--log] [--all] [--map file] [--confirm --fingerprint SHA] [--dry-run] [--json]", mutates: "confirm" },
31
- { name: "report", usage: "report <vault> <reports/path|ops/path> --body file|- [--log JSON] [--dry-run] [--json]", mutates: true },
32
- { name: "check", usage: "check <vault> <file|-> [--path stem] [--json]", mutates: false },
33
- { name: "log tail", usage: "log tail <vault> [--limit 1..200] [--type TYPE] [--json]", mutates: false },
34
- { name: "log grep", usage: "log grep <vault> <pattern> [--limit 1..200] [--type TYPE] [--json]", mutates: false },
35
- { name: "log append", usage: "log append <vault> <TYPE> <project> <source> <note> [--dest PATH] [--json]", mutates: true },
36
- { name: "promote-from-amem", usage: "promote-from-amem <vault> [<mem-id>] [--project KEY|--all-projects] [--limit 1..200] [--stem STEM] [--type TYPE] [--domain DOMAIN] [--topics a,b] [--description TEXT] [--title TEXT] [--body file|-] [--link-to NOTE] [--log-project ID] [--edit] [--confirm --fingerprint SHA] [--json]", mutates: "confirm" },
37
- { name: "promote", usage: "promote <personal-vault> <note> --to ORG [--topics a,b] [--again] [--log-project ID] [--confirm --fingerprint SHA] [--json]", mutates: "confirm" },
38
- { name: "sync", usage: "sync <vault> [--message TEXT] [--confirm --fingerprint SHA] [--json]", mutates: "confirm" },
39
- { name: "mcp", usage: "mcp", mutates: false },
40
- { name: "setup", usage: "setup <claude|codex|kimi|pi|qwen|jcode|agy|all> [--root PATH] [--apply|--undo] [--json]", mutates: "apply" },
41
- { name: "manifest", usage: "manifest [--json]", mutates: false },
42
- { name: "completion", usage: "completion <bash|zsh|fish>", mutates: false },
43
- { name: "stats", usage: "stats <vault> [--days 1..3650] [--json]", mutates: false },
44
- ] as const;
15
+ ...SPEC_COMMANDS.map(item => ({ name: `spec ${item.command}`, usage: item.usage, mutates: false, section: "Design specs" as const, description: SPEC_HELP[item.command] })),
16
+ { name: "lint", usage: "lint <vault> [--note PATH] [--write] [--dry-run] [--json]", mutates: "write", section: "Analysis", description: "lint links, schema, filenames and the log; --write saves a screened report" },
17
+ { name: "graph build", usage: "graph build <vault> [--workspace] [--dry-run] [--json]", mutates: true, section: "Analysis", description: "build the vault graph, or the workspace graph with --workspace, under reports/" },
18
+ { name: "graph neighbors", usage: "graph neighbors <vault> <stem> [--hops 1..2] [--limit 1..500] [--relation REL] [--json]", mutates: false, section: "Analysis", description: "read a note's graph neighborhood up to two hops, optionally over one link relation" },
19
+ { name: "skills mine", usage: "skills mine <vault> [--days N] [--project KEY|--all-projects] [--vocab DIR] [--skills DIR] [--min-size N] [--min-novelty X] [--json]", mutates: false, section: "Analysis", description: "rank repeated work patterns in agent memory as new-skill candidates" },
20
+ { name: "rebuild", usage: "rebuild <vault> [--json]", mutates: "cache", section: "Read", description: "rebuild the derived search index from the vault files" },
21
+ { name: "search", usage: "search <vault> <query> [--type TYPE] [--domain DOMAIN] [--limit 1..500] [--json]", mutates: "cache", section: "Read", description: "full-text search notes, optionally by type and domain" },
22
+ { name: "show", usage: "show <vault> <target> [--section TEXT] [--offset 0..2097152] [--max-bytes 1..65536] [--json]", mutates: "cache", section: "Read", description: "print a note's fields and body, paged by section, offset and size" },
23
+ { name: "links", usage: "links <vault> <target> [--limit 1..500] [--json]", mutates: "cache", section: "Read", description: "list a note's outgoing, dead and incoming links" },
24
+ { name: "status", usage: "status [--json]", mutates: false, section: "Registry", description: "show the home, registered vaults and spec sources, and vault health" },
25
+ { name: "doctor", usage: "doctor [--json]", mutates: false, section: "Registry", description: "check vault paths, remotes, project registries, pending tidy and spec sources; exits 1 when unhealthy" },
26
+ { name: "recover", usage: "recover [--confirm] [--json]", mutates: "confirm", section: "Registry", description: "preview, then remove with --confirm, a stale registry lock and leftover temporary files" },
27
+ { name: "vaults list", usage: "vaults list [--json]", mutates: false, section: "Registry", description: "list registered vaults with kind, write policy and effective PII policy" },
28
+ { name: "vaults add", usage: "vaults add <id> <absolute-path> --kind personal|org --write mcp|cli|none [--pii allow|deny] [--remote URL] [--registry PATH] [--json]", mutates: true, section: "Registry", description: "register a vault directory that contains notes/" },
29
+ { name: "vaults remove", usage: "vaults remove <id> [--confirm] [--json]", mutates: "confirm", section: "Registry", description: "preview, then unregister with --confirm, a vault; its files stay on disk" },
30
+ { name: "vaults pii", usage: "vaults pii <id> [--set allow|deny|JSON] [--confirm] [--json]", mutates: "confirm", section: "Registry", description: "show a vault's PII policy, or preview a new one and apply it with --confirm" },
31
+ { name: "specs list", usage: "specs list [--json]", mutates: false, section: "Registry", description: "list registered spec sources" },
32
+ { name: "specs add", usage: "specs add <id> <absolute-path> [--write mcp|cli|none] [--pii allow|deny] [--json]", mutates: true, section: "Registry", description: "register a git repository root as a spec source" },
33
+ { name: "specs remove", usage: "specs remove <id> [--confirm] [--json]", mutates: "confirm", section: "Registry", description: "preview, then unregister with --confirm, a spec source; the repository stays" },
34
+ { name: "new", usage: "new <vault> <stem> --type TYPE --domain DOMAIN --topics a,b --description TEXT [--title TEXT] [--source TEXT|JSON] [--confidence TEXT] [--status TEXT] [--body file|-] [--extra JSON] [--log JSON] [--dry-run] [--json]", mutates: true, section: "Write", description: "create a validated note" },
35
+ { name: "patch", usage: "patch <vault> <note> [--old TEXT --new TEXT] [--edits file|-] [--expected-sha SHA] [--log JSON] [--dry-run] [--json]", mutates: true, section: "Write", description: "replace exact text in a note, or several replacements at once" },
36
+ { name: "append", usage: "append <vault> <note> --section SECTION --markdown TEXT [--expected-sha SHA] [--log JSON] [--dry-run] [--json]", mutates: true, section: "Write", description: "append markdown under a section of a note" },
37
+ { name: "frontmatter", usage: "frontmatter <vault> <note> [--set JSON] [--unset key,key] [--expected-sha SHA] [--log JSON] [--dry-run] [--json]", mutates: true, section: "Write", description: "set or unset frontmatter keys of a note" },
38
+ { name: "link", usage: "link <vault> <from> <to> --relation R [--context TEXT] [--one-way] [--log JSON] [--dry-run] [--json]", mutates: true, section: "Write", description: "add a typed link between two notes, both ways unless --one-way" },
39
+ { name: "supersede", usage: "supersede <vault> <old> <next> [--log JSON] [--dry-run] [--json]", mutates: true, section: "Write", description: "mark a note superseded by a newer one and link them" },
40
+ { name: "move", usage: "move <vault> <from> <to> [--confirm --fingerprint SHA] [--log JSON] [--dry-run] [--json]", mutates: "confirm", section: "Write", description: "preview, then confirm with the fingerprint, a note move that rewrites links" },
41
+ { name: "delete", usage: "delete <vault> <note> [--confirm --fingerprint SHA] [--log JSON] [--dry-run] [--json]", mutates: "confirm", section: "Write", description: "preview backlinks, then confirm with the fingerprint, a note deletion" },
42
+ { name: "tidy", usage: "tidy <vault> [--connections] [--escapes] [--enums] [--keys] [--sources] [--topics] [--secrets] [--log] [--all] [--map file] [--confirm --fingerprint SHA] [--dry-run] [--json]", mutates: "confirm", section: "Write", description: "preview, then confirm with the fingerprint, migration tidy of notes and the log" },
43
+ { name: "report", usage: "report <vault> <reports/path|ops/path> --body file|- [--log JSON] [--dry-run] [--json]", mutates: true, section: "Write", description: "write a screened file under reports/ or ops/" },
44
+ { name: "check", usage: "check <vault> <file|-> [--path stem] [--json]", mutates: false, section: "Read", description: "validate a note file or stdin without writing it" },
45
+ { name: "log tail", usage: "log tail <vault> [--limit 1..200] [--type TYPE] [--json]", mutates: false, section: "Log", description: "print the latest log events" },
46
+ { name: "log grep", usage: "log grep <vault> <pattern> [--limit 1..200] [--type TYPE] [--json]", mutates: false, section: "Log", description: "search log events by pattern" },
47
+ { name: "log append", usage: "log append <vault> <TYPE> <project> <source> <note> [--dest PATH] [--json]", mutates: true, section: "Log", description: "append one event to the vault log" },
48
+ { name: "promote-from-amem", usage: "promote-from-amem <vault> [<mem-id>] [--project KEY|--all-projects] [--limit 1..200] [--stem STEM] [--type TYPE] [--domain DOMAIN] [--topics a,b] [--description TEXT] [--title TEXT] [--body file|-] [--link-to NOTE] [--log-project ID] [--edit] [--confirm --fingerprint SHA] [--json]", mutates: "confirm", section: "Promotion and sync", description: "list agent-mem candidates, or preview and confirm one as a note" },
49
+ { name: "promote", usage: "promote <personal-vault> <note> --to ORG [--topics a,b] [--again] [--log-project ID] [--confirm --fingerprint SHA] [--json]", mutates: "confirm", section: "Promotion and sync", description: "preview, then confirm, copying a personal note into an org vault clone" },
50
+ { name: "sync", usage: "sync <vault> [--message TEXT] [--confirm --fingerprint SHA] [--json]", mutates: "confirm", section: "Promotion and sync", description: "preview, then confirm, committing and pushing a vault to its remote" },
51
+ { name: "mcp", usage: "mcp", mutates: false, section: "Setup", description: "serve the vmem MCP tools on stdio" },
52
+ { name: "setup", usage: "setup <claude|codex|kimi|pi|qwen|jcode|agy|all> [--root PATH] [--apply|--undo] [--json]", mutates: "apply", section: "Setup", description: "preview, apply or undo the vmem MCP entry in agent hosts" },
53
+ { name: "manifest", usage: "manifest [--json]", mutates: false, section: "Setup", description: "print the package version, MCP tools and command names" },
54
+ { name: "completion", usage: "completion <bash|zsh|fish>", mutates: false, section: "Setup", description: "print a shell completion script built from this table" },
55
+ { name: "stats", usage: "stats <vault> [--days 1..3650] [--json]", mutates: false, section: "Read", description: "count notes by type, domain and status, recent edits and log events" },
56
+ ] as const satisfies readonly CommandEntry[];
45
57
  const RELATIONS = ["supports", "contradicts", "extends", "applies-to", "context-for"] as const;
46
58
  const LOG_EVENT_TYPES = ["INGEST", "ROUTE", "EXTRACT", "CONNECT", "DIGEST", "LEARN", "LINT", "TASK", "GRAPH", "SYNC", "RETHINK", "SOURCE"] as const;
47
59
  const VALUE = /^--[a-z-]+ (?!\.\.\.)([A-Z]|[a-z0-9.|,-]+|file\|-|JSON|SHA|URL|PATH|TEXT)/;
@@ -94,4 +106,33 @@ ${cases.join("\n")}
94
106
  `;
95
107
  return shell === "zsh" ? `autoload -U +X bashcompinit && bashcompinit\n${fn}complete -F _vmem vmem\n` : `${fn}complete -F _vmem vmem\n`;
96
108
  }
97
- export function help(): string { return "vmem - validated knowledge vaults for agents and people\n\n" + COMMANDS.map(c => ` vmem ${c.usage}`).join("\n") + "\n\n vmem --help | --version\n"; }
109
+ const DESCRIPTION = 34;
110
+ /** Help lines that are not commands of their own, so completion and the manifest leave them out. */
111
+ const EXTRA_HELP = [
112
+ { name: "help", section: "Setup", usage: "help [command]", description: "this help, or one command's entries; also <command> --help and -h" },
113
+ { name: "--version", section: "Setup", usage: "--version", description: "print the installed version" },
114
+ ] as const;
115
+ const OUTPUT_NOTE = "Output is text for people; --json prints the compact JSON object for scripts (every command but mcp and completion). --color=auto|always|never sets color: auto colors a terminal unless NO_COLOR is set or TERM is dumb.";
116
+ /** Usage at 2 spaces and the description at column 34, wrapped to the width (at most 100); a long usage puts its description below. */
117
+ function entryLines(entry: { usage: string; description: string }, o: TextOptions): string[] {
118
+ const columns = o.columns === undefined ? undefined : Math.min(100, o.columns);
119
+ const usage = wrap(`vmem ${entry.usage}`, columns === undefined ? undefined : columns - 4);
120
+ const description = wrap(entry.description, columns === undefined ? undefined : columns - DESCRIPTION);
121
+ const lines = [` ${usage[0]}`];
122
+ if (usage.length === 1 && width(lines[0]!) + 2 <= DESCRIPTION) lines[0] += " ".repeat(DESCRIPTION - width(lines[0]!)) + description.shift();
123
+ return [...lines, ...usage.slice(1).map(line => ` ${line}`), ...description.map(line => " ".repeat(DESCRIPTION) + line)];
124
+ }
125
+ function sectionsText(entries: readonly { section: string; usage: string; description: string }[], o: TextOptions): string {
126
+ return HELP_SECTIONS.map(section => entries.filter(entry => entry.section === section)).filter(group => group.length)
127
+ .map(group => [paint(group[0]!.section, "bold", o), ...group.flatMap(entry => entryLines(entry, o))].join("\n")).join("\n\n");
128
+ }
129
+ /** `vmem help`: the tagline, then every command by section with its description. */
130
+ export function help(o: TextOptions = { color: false }): string {
131
+ return [paragraph(`vmem ${version}: validated knowledge vaults for agents and people`, o), sectionsText([...COMMANDS, ...EXTRA_HELP], o),
132
+ paint("Output", "bold", o) + "\n" + paragraph(OUTPUT_NOTE, o, undefined, " ")].join("\n\n");
133
+ }
134
+ /** `vmem help <command>` and `<command> --help`: the entries of that command or command group, or undefined when none match. */
135
+ export function commandUsage(name: string, o: TextOptions = { color: false }): string | undefined {
136
+ const entries = [...COMMANDS, ...EXTRA_HELP].filter(entry => entry.name === name || entry.name.startsWith(name + " "));
137
+ return entries.length ? sectionsText(entries, o) : undefined;
138
+ }
package/src/config.ts CHANGED
@@ -11,6 +11,19 @@ export interface VaultSpec {
11
11
  pii?: "allow" | "deny" | PiiSpec;
12
12
  remote?: string;
13
13
  registry?: string;
14
+ domains?: string[];
15
+ }
16
+ /** Canonical built-ins; vault declarations add ids without replacing these. */
17
+ export const BUILTIN_DOMAINS: readonly string[] = Object.freeze(["research", "projects", "teaching", "operations", "people", "ai-practice"]);
18
+ export function effectiveDomains(vault: Pick<VaultSpec, "domains">): string[] {
19
+ return [...new Set([...BUILTIN_DOMAINS, ...(vault.domains ?? [])])];
20
+ }
21
+ /** A named, actionable domain refusal shared by writers and promotion targets. */
22
+ export function domainProblem(value: unknown, vault: VaultSpec): string | undefined {
23
+ const domains = effectiveDomains(vault);
24
+ if (typeof value !== "string" || !/^[a-z][a-z0-9-]{0,31}(?![\s\S])/.test(value)) return `domain is missing or not a valid id for vault ${vault.id}; set domain to one of ${domains.join(", ")}`;
25
+ if (domains.includes(value)) return undefined;
26
+ return `domain ${value} is not declared for vault ${vault.id}; choose ${domains.join(", ")} or add the id to this vault's domains in ${CONFIG_FILE}`;
14
27
  }
15
28
  export type PiiAction = "allow" | "warn" | "deny";
16
29
  export const PII_SURFACES = ["notes", "log", "promotion"] as const;
@@ -23,9 +36,9 @@ export interface PiiSpec { email?: PiiCell; phone?: PiiCell; custom?: PiiCell; p
23
36
  * The config format this build writes. A build that adds a key bumps it. A config whose `version` is newer
24
37
  * than this build is read tolerantly: unknown keys are kept as they are and written back unchanged, so an
25
38
  * older vmem can share a config with a newer one. At or below this version unknown keys stay errors (typos).
26
- * An absent `version` means 1. Registry writes add format 2 only when `specs` is present; vault-only configs keep their existing version field.
39
+ * An absent `version` means 1. Registry writes add format 2 when `specs` is present and format 3 when vault `domains` is present; otherwise they keep the existing version field.
27
40
  */
28
- export const CONFIG_VERSION = 2;
41
+ export const CONFIG_VERSION = 3;
29
42
  export interface SpecSourceSpec { id: string; path: string; write: "mcp" | "cli" | "none"; pii: "allow" | "deny" }
30
43
  export interface VmemConfig { version?: number; home?: string; vaults: VaultSpec[]; specs?: SpecSourceSpec[]; denyPaths?: string[]; piiPatterns?: string[] }
31
44
  const controls = /[\x00-\x1f\x7f]/;
@@ -115,7 +128,7 @@ export function unenforceablePii(vault: VaultSpec): string | undefined {
115
128
  return members.length ? `vault ${vault.id}: PII policy has members this vmem cannot enforce (${members.slice(0, 8).join(", ")}); write with the newer vmem that wrote the policy` : undefined;
116
129
  }
117
130
  export function parseVault(value: unknown, tolerant = false): VaultSpec {
118
- const keys = ["id", "path", "kind", "write", "pii", "remote", "registry"], v = object(value, keys, "vault", tolerant);
131
+ const keys = ["id", "path", "kind", "write", "pii", "remote", "registry", "domains"], v = object(value, keys, "vault", tolerant);
119
132
  const id = string(v.id, "vault.id");
120
133
  if (!/^[a-z][a-z0-9-]{0,31}$/.test(id)) throw new Error("vault.id: invalid id");
121
134
  if (v.kind !== "personal" && v.kind !== "org") throw new Error("vault.kind: expected personal or org");
@@ -124,6 +137,12 @@ export function parseVault(value: unknown, tolerant = false): VaultSpec {
124
137
  if (v.pii !== undefined) result.pii = parsePii(v.pii, tolerant);
125
138
  if (v.remote !== undefined) result.remote = string(v.remote, "vault.remote");
126
139
  if (v.registry !== undefined) result.registry = absolute(v.registry, "vault.registry");
140
+ if (v.domains !== undefined) {
141
+ if (!Array.isArray(v.domains) || v.domains.length > 16 || v.domains.some(id => typeof id !== "string" || !/^[a-z][a-z0-9-]{0,31}(?![\s\S])/.test(id))) {
142
+ throw new Error("vault.domains: expected at most 16 ids matching [a-z][a-z0-9-]{0,31}; fix domains in vmem.config.json");
143
+ }
144
+ result.domains = [...v.domains];
145
+ }
127
146
  return result;
128
147
  }
129
148
  /** Spec sources have their own registry shape; they are not vaults. */
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/mcp-spec.ts CHANGED
@@ -4,6 +4,8 @@ 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";
7
9
 
8
10
  /** Spec tool definitions; every spec tool is read-only. */
9
11
  export const specTools = (): McpTool[] => SPEC_COMMANDS.map(item => ({ name: item.name, description: item.description, inputSchema: item.inputSchema,
@@ -26,7 +28,7 @@ export function createSpecMcp(home: string, env: NodeJS.ProcessEnv = process.env
26
28
  }
27
29
 
28
30
  /** Parse with the same bounded field schemas as MCP. --repo deliberately bypasses home resolution. */
29
- 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 } {
30
32
  const item = SPEC_COMMANDS.find(entry => entry.command === args[0]);
31
33
  if (!item) throw new Error("spec: unknown command; use vmem spec --help");
32
34
  const values: Record<string, unknown> = {}, positional: string[] = [];
@@ -64,5 +66,6 @@ export function runSpecCommand(args: string[], env: NodeJS.ProcessEnv = process.
64
66
  const result = repo !== undefined
65
67
  ? validateSpecRepo(repo, { requireFresh: values.requireFresh as boolean | undefined, limit: values.limit as number | undefined, env }).report
66
68
  : executeSpecCommand(resolveHome(env).home, item.command, values, env);
67
- 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 };
68
71
  }
package/src/mcp-vault.ts CHANGED
@@ -1,7 +1,7 @@
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";
@@ -29,6 +29,7 @@ const LOG_TYPES = ["INGEST", "ROUTE", "EXTRACT", "CONNECT", "DIGEST", "LEARN", "
29
29
  const note = string(1024), sha = { type: "string", minLength: 64, maxLength: 64 };
30
30
  const logEvent = LOG_EVENT_SCHEMA;
31
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 };
32
33
 
33
34
  /** Tool names for the implemented read, write, log, analysis and promotion providers. */
34
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",
@@ -49,10 +50,10 @@ export function vaultTools(ids: readonly string[], orgIds: readonly string[] = [
49
50
  tool("vmem_mocs", "MOC notes with incoming link counts.", object({ vault })),
50
51
  tool("vmem_check", "Validate a prospective note text without writing.", object({ vault, path: string(200), text: string(262144, 0) }, ["text"])),
51
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) })),
52
- 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"),
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"),
53
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"),
54
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"),
55
- 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, log: logEvent }, ["path"]), "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"),
56
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"),
57
58
  tool("vmem_supersede", "Mark a note superseded by another.", object({ vault, old: note, next: note, log: logEvent }, ["old", "next"]), "write"),
58
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"),
@@ -62,7 +63,7 @@ export function vaultTools(ids: readonly string[], orgIds: readonly string[] = [
62
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"),
63
64
  tool("vmem_lint", "Lint a private derived snapshot; write=true writes a screened report.", object({ vault, write: { type: "boolean" }, dryRun: { type: "boolean" } }), "write"),
64
65
  tool("vmem_graph_build", "Build a deterministic graph and screened reports; dryRun changes nothing.", object({ vault, dryRun: { type: "boolean" }, workspace: { type: "boolean" } }), "write"),
65
- 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"])),
66
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.",
67
68
  object({ path: note, to: orgVault, topics: { type: "array", maxItems: 32, items: string(200) }, again: { type: "boolean" }, ...twoStep }, ["path", "to"]), "confirm"),
68
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.",
@@ -134,7 +135,7 @@ export function createVaultMcp(home: string, env: NodeJS.ProcessEnv = process.en
134
135
  vmem_report: args => write(args, { op: "report", path: str(args.path)!, text: str(args.body)! }, args.dryRun === true ? { dryRun: true } : {}),
135
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),
136
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),
137
- 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)),
138
139
  vmem_status: () => ({ defaultVault: defaultVault ?? null, vaults: registryStatus(home).filter(v => ids.includes(v.id)) }),
139
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) }) })),
140
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); }),