@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
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Text renderers for the registry, health, setup and manifest commands (#114). Each is a pure function of the
3
+ * command's JSON result; `--json` never comes through here, and the text shows no more than that JSON carries.
4
+ */
5
+ import { effectiveDomains, PII_SURFACES, type SpecSourceSpec, type VaultSpec } from "./config.ts";
6
+ import type { ResolvedHome } from "./home.ts";
7
+ import type { PiiMatrix, PiiRow } from "./pii.ts";
8
+ import { effectivePii, type RecoveryReport } from "./registry.ts";
9
+ import type { SetupReport } from "./setup.ts";
10
+ import { blocks, clean, fields, heading, issueTable, nextCommand, paint, paragraph, plural, shellWord, table, tone, type CellInput, type TextOptions } from "./text-output.ts";
11
+ import type { VaultStats } from "./vault-stats.ts";
12
+
13
+ type Check = { ok: boolean; issue?: string };
14
+ export type VaultRow = Omit<VaultSpec, "pii"> & { pii: string; healthy?: boolean; issue?: string; checks?: Record<string, Check>;
15
+ tidy?: { pending: Record<string, number>; notes: number; unparsable: string[]; hint: string } };
16
+ export type SpecRow = SpecSourceSpec & { healthy?: boolean; issue?: string };
17
+ export interface StatusResult extends ResolvedHome { version: string; healthy: boolean; vaults: VaultRow[]; specs?: SpecRow[] }
18
+ export interface Manifest { name: string; version: string; configVersion: number; mcp: { server: string; tools: (string | { name: string; readOnly: boolean })[] }; commands: string[] }
19
+
20
+ const OK = tone("ok", "ok"), WARN = tone("warn", "warn"), FAIL = tone("fail", "fail");
21
+ const homeLine = (r: StatusResult, o: TextOptions) => `${heading(`vmem ${r.version}`, o)} home ${clean(r.home)} (${r.source})`;
22
+ const NO_VAULTS = "no vaults registered; add one with vmem vaults add <id> <absolute-path> --kind personal|org --write mcp|cli|none";
23
+
24
+ export function renderStatus(r: StatusResult, o: TextOptions): string {
25
+ const title = `${homeLine(r, o)} ${r.healthy ? paint("healthy", "ok", o) : paint("unhealthy", "fail", o)}`;
26
+ const vaults = r.vaults.length ? table(["VAULT", "KIND", "WRITE", "PII", "HEALTH", "PATH"], r.vaults.map(v => [v.id, v.kind, v.write, v.pii, v.healthy ? OK : FAIL, v.path]), o) : paragraph(NO_VAULTS, o);
27
+ const issues = r.vaults.filter(v => v.issue).map(v => paragraph(`${v.id}: ${v.issue}`, o, "fail")).join("\n");
28
+ const specs = r.specs?.length ? table(["SOURCE", "WRITE", "PII", "PATH"], r.specs.map(s => [s.id, s.write, s.pii, s.path]), o) : undefined;
29
+ return blocks(title, issues ? `${vaults}\n${issues}` : vaults, specs);
30
+ }
31
+
32
+ function tidyFinding(t: NonNullable<VaultRow["tidy"]>): string {
33
+ const pending = Object.entries(t.pending).filter(([, n]) => n > 0).map(([rule, n]) => `${rule} ${n}`).join(", ");
34
+ return [`${plural(t.notes, "note")} to migrate${pending ? ` (${pending})` : ""}`, t.unparsable.length ? `${plural(t.unparsable.length, "unparsable note")} skipped` : ""].filter(Boolean).join("; ");
35
+ }
36
+ export function renderDoctor(r: StatusResult, o: TextOptions): string {
37
+ let failed = 0;
38
+ const vaults = r.vaults.map(v => {
39
+ const rows: CellInput[][] = [[v.healthy ? OK : FAIL, "path", v.healthy ? v.path : `${v.path}: ${v.issue ?? "unavailable"}`]];
40
+ if (!v.healthy) failed++;
41
+ for (const [name, check] of Object.entries(v.checks ?? {})) {
42
+ if (!check.ok) failed++;
43
+ rows.push([check.ok ? OK : FAIL, name, check.ok ? (name === "remote" ? v.remote : name === "registry" ? v.registry : "ok") : check.issue]);
44
+ }
45
+ if (v.tidy) rows.push([WARN, "tidy", tidyFinding(v.tidy)]);
46
+ const next = v.tidy ? `\n${nextCommand("next", `vmem tidy ${shellWord(v.id)} --all`, o)}, then confirm its fingerprint to apply the migration` : "";
47
+ return `${heading(`Vault ${v.id}`, o)}\n${table(["LEVEL", "CHECK", "FINDING"], rows, o)}${next}`;
48
+ });
49
+ const specs = (r.specs ?? []).map(s => {
50
+ if (s.healthy === false) failed++;
51
+ return `${heading(`Spec source ${s.id}`, o)}\n${table(["LEVEL", "CHECK", "FINDING"], [[s.healthy === false ? FAIL : OK, "root", s.healthy === false ? s.issue : s.path]], o)}`;
52
+ });
53
+ const checked = [plural(r.vaults.length, "vault"), ...(r.specs ? [plural(r.specs.length, "spec source")] : [])].join(" and ");
54
+ const verdict = r.healthy ? paragraph(`healthy: ${checked} checked`, o, "ok")
55
+ : paragraph(`unhealthy: ${plural(failed, "failed check")}; fix the findings above, then run vmem doctor again`, o, "fail");
56
+ return blocks(homeLine(r, o), r.vaults.length ? undefined : paragraph(NO_VAULTS, o), ...vaults, ...specs, verdict);
57
+ }
58
+
59
+ export function renderStats(r: VaultStats, o: TextOptions): string {
60
+ const counts = (record: Record<string, number>) => fields(Object.entries(record).sort(([a, x], [b, y]) => y - x || a.localeCompare(b)), o);
61
+ const block = (name: string, body: string) => body ? `${heading(name, o)}\n${body}` : undefined;
62
+ const log = r.log.total === null ? paragraph("unreadable; see the issues below", o, "fail", " ")
63
+ : fields([["total", r.log.total], ...Object.entries(r.log.byType ?? {}).filter(([, n]) => n > 0).sort(([a, x], [b, y]) => y - x || a.localeCompare(b))], o);
64
+ return blocks(`${heading(r.vault, o)} ${plural(r.notes.total, "note")} as of ${r.asOf}`,
65
+ block("Notes by type", counts(r.notes.byType)), block("Notes by domain", counts(r.notes.byDomain)), block("Notes by status", counts(r.notes.byStatus)),
66
+ block("Modified", fields([["last 7 days", r.modified.last7Days], ["last 30 days", r.modified.last30Days]], o)),
67
+ block(`Log since ${r.log.since} (${plural(r.log.days, "day")})`, log),
68
+ r.log.warnings.map(w => paragraph(`warning: ${w}`, o, "warn")).join("\n"), issueTable(r.log.issues, o));
69
+ }
70
+
71
+ export function renderRecover(r: RecoveryReport, o: TextOptions): string {
72
+ const owner = r.lock.owner ? `pid ${r.lock.owner.pid} on ${r.lock.owner.host} since ${r.lock.owner.created}` : undefined;
73
+ const detail = fields([["lock", r.lock.path], ["state", r.lock.state], ["owner", owner], ["temporary files", r.temporaryFiles.join(", ")]], o);
74
+ if (r.blocked) return blocks(paragraph(`recovery blocked: ${r.blocked}`, o, "fail"), detail);
75
+ if (r.applied) {
76
+ const done = [r.lock.removed ? "the stale registry lock" : "", r.removedTemporaryFiles.length ? plural(r.removedTemporaryFiles.length, "temporary config file") : ""].filter(Boolean);
77
+ return paragraph(done.length ? `recovered: removed ${done.join(" and ")}` : "nothing to recover: no stale lock and no temporary config files", o, done.length ? "ok" : undefined);
78
+ }
79
+ const work = [r.lock.state === "stale" ? "the stale registry lock" : "", r.temporaryFiles.length ? plural(r.temporaryFiles.length, "temporary config file") : ""].filter(Boolean);
80
+ if (!work.length) return paragraph("nothing to recover: no stale lock and no temporary config files", o);
81
+ return blocks(paragraph(`dry run: would remove ${work.join(" and ")}`, o), detail, nextCommand("confirm", "vmem recover --confirm", o));
82
+ }
83
+
84
+ export function renderVaultsList(vaults: VaultRow[], o: TextOptions): string {
85
+ return vaults.length ? table(["VAULT", "KIND", "WRITE", "PII", "DOMAINS", "PATH"], vaults.map(v => [v.id, v.kind, v.write, v.pii, effectiveDomains(v).join(", "), v.path]), o) : paragraph(NO_VAULTS, o);
86
+ }
87
+ export function renderVaultAdd(r: { vault: VaultSpec }, o: TextOptions): string {
88
+ const v = r.vault;
89
+ return paragraph(`registered vault ${v.id}: ${v.kind}, write ${v.write}, PII ${effectivePii(v)}, at ${v.path}`, o, "ok");
90
+ }
91
+ export function renderSpecsList(specs: SpecSourceSpec[], o: TextOptions): string {
92
+ return specs.length ? table(["SOURCE", "WRITE", "PII", "PATH"], specs.map(s => [s.id, s.write, s.pii, s.path]), o)
93
+ : paragraph("no spec sources registered; add one with vmem specs add <id> <absolute-path>", o);
94
+ }
95
+ export function renderSpecAdd(r: { spec: SpecSourceSpec }, o: TextOptions): string {
96
+ return paragraph(`registered spec source ${r.spec.id}: write ${r.spec.write}, PII ${r.spec.pii}, at ${r.spec.path}`, o, "ok");
97
+ }
98
+ /** `vaults remove` and `specs remove`: unregistering only, so the files are always said to stay. */
99
+ export function renderRemove(group: "vaults" | "specs", r: { applied: boolean; vault?: { id: string; path: string }; spec?: { id: string; path: string } }, o: TextOptions): string {
100
+ const entry = (r.vault ?? r.spec)!, what = `${group === "vaults" ? "vault" : "spec source"} ${entry.id} at ${entry.path}`;
101
+ const stays = group === "vaults" ? "its files stay on disk" : "the repository stays on disk";
102
+ if (r.applied) return paragraph(`unregistered ${what}; ${stays}`, o, "ok");
103
+ return blocks(paragraph(`dry run: would unregister ${what}; ${stays}`, o), nextCommand("confirm", `vmem ${group} remove ${shellWord(entry.id)} --confirm`, o));
104
+ }
105
+
106
+ export interface PiiResult { vault: string; pii: string; piiPolicy: PiiMatrix; applied?: boolean; changed?: boolean; loosened?: string[]; preview?: true }
107
+ /** `confirm` is the exact command that applies a preview; the result itself does not carry the `--set` value. */
108
+ export function renderVaultPii(r: PiiResult, o: TextOptions, confirm?: string): string {
109
+ const row = (name: string, cells: PiiRow): CellInput[] => [name, ...PII_SURFACES.map(surface => cells[surface])];
110
+ const matrix = table(["CATEGORY", "NOTES", "LOG", "PROMOTION"], [row("email", r.piiPolicy.email), row("phone", r.piiPolicy.phone), row("custom", r.piiPolicy.custom),
111
+ ...r.piiPolicy.patterns.map(p => row(`pattern ${p.name}`, p.action))], o);
112
+ const allow = r.piiPolicy.allow.length ? paragraph(`allow list: ${plural(r.piiPolicy.allow.length, "entry", "entries")} (shown with --json)`, o) : undefined;
113
+ const title = r.changed === undefined ? `Vault ${r.vault} PII policy: ${r.pii}`
114
+ : !r.changed ? `unchanged: vault ${r.vault} already has this PII policy (${r.pii})`
115
+ : r.applied ? `set the PII policy of vault ${r.vault} to ${r.pii}` : `dry run: would set the PII policy of vault ${r.vault} to ${r.pii}`;
116
+ const loosened = r.loosened?.length ? r.loosened.map(cell => paragraph(`loosens ${cell}`, o, "warn")).join("\n") : undefined;
117
+ const next = r.preview && r.changed && confirm ? nextCommand("confirm", confirm, o) : undefined;
118
+ return blocks(paragraph(title, o, r.applied ? "ok" : undefined), matrix, allow, loosened, next);
119
+ }
120
+
121
+ export function renderManifest(m: Manifest, o: TextOptions): string {
122
+ const tools = m.mcp.tools.map(t => typeof t === "string" ? [t, "may write"] : [t.name, tone("read-only", "muted")]);
123
+ return blocks(`${heading(`${m.name} ${m.version}`, o)} config format ${m.configVersion}`,
124
+ `${heading(`MCP server ${m.mcp.server}`, o)}: ${plural(tools.length, "tool")}\n${table(["TOOL", "ACCESS"], tools, o)}`,
125
+ `${heading("Commands", o)}: ${m.commands.length}\n${paragraph(m.commands.join(", "), o, undefined, " ")}`);
126
+ }
127
+
128
+ /** `apply` is the exact command that applies a dry run. */
129
+ export function renderSetup(r: SetupReport, o: TextOptions, apply?: string): string {
130
+ const rows = [...r.actions.map(a => ({ host: a.target, ...a })), ...(r.console ? [{ host: "console", ...r.console }] : [])];
131
+ const reasons = rows.some(a => a.reason), refused = rows.filter(a => a.change === "refused").length, pending = rows.some(a => !["none", "unchanged", "refused"].includes(a.change));
132
+ const title = r.mode === "dry-run" ? "dry run: nothing written" : r.applied ? (r.mode === "apply" ? "setup applied" : "setup undone") : "unchanged: nothing to do";
133
+ const changeTone = (change: string) => change === "refused" ? "fail" : ["none", "unchanged"].includes(change) ? "muted" : "info";
134
+ return blocks(paragraph(title, o, r.applied ? "ok" : undefined),
135
+ fields([["server", [r.entry.command, ...r.entry.args].map(shellWord).join(" ")], ["root", r.root ? `${r.root.path} (${r.root.version})` : undefined]], o),
136
+ rows.length ? table(["HOST", "CHANGE", "PATH", ...(reasons ? ["REASON"] : [])], rows.map(a => [a.host, tone(a.change, changeTone(a.change)), a.file, a.reason]), o) : undefined,
137
+ r.notes.map(note => paragraph(note, o)).join("\n"),
138
+ refused ? paragraph(`${plural(refused, "host")} refused; see REASON.`, o, "fail") : undefined,
139
+ r.mode === "dry-run" && pending && apply ? nextCommand("apply", apply, o) : undefined);
140
+ }
package/src/cli.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { runSpecCommand } from "./mcp-spec.ts";
1
+ import { runSpecCommand, specTools } from "./mcp-spec.ts";
2
2
  import { tidyVault, TIDY_RULES } from "./tidy.ts";
3
3
  import { originCheck } from "./sync.ts";
4
4
  import { registryIds } from "./vault-log.ts";
@@ -8,13 +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";
12
- import { VMEM_TOOL_NAMES } from "./mcp-vault.ts";
13
- import { CONFIG_VERSION } from "./config.ts";
11
+ import { COMMANDS, commandUsage, completionScript, help } from "./commands-table.ts";
12
+ import { VMEM_TOOL_NAMES, vaultTools } from "./mcp-vault.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
+ 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";
18
21
  function parse(args: string[], allowed: string[], values: string[]) {
19
22
  const flags: Record<string, string | boolean> = {}, positional: string[] = [];
20
23
  for (let i = 0; i < args.length; i++) {
@@ -29,49 +32,66 @@ function parse(args: string[], allowed: string[], values: string[]) {
29
32
  }
30
33
  return { flags, positional };
31
34
  }
32
- 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
+ }
33
43
  if (args.includes("--")) return undefined;
34
44
  if (!["--help", "-h"].includes(args.at(-1) ?? "")) return undefined;
35
45
  const name = args.slice(0, -1).join(" ");
36
46
  if (!name) return undefined;
37
- const commands = COMMANDS.filter(command => command.name === name || command.name.startsWith(name + " "));
38
- 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));
39
55
  }
40
- export function run(args: string[], env: NodeJS.ProcessEnv = process.env): { text: string; code: number } {
41
- if (!args.length || (args.length === 1 && ["--help", "-h", "help"].includes(args[0]!))) return { text: help(), code: 0 };
42
- 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);
43
59
  if (usage) return { text: usage, code: 0 };
44
60
  if (args.length === 1 && args[0] === "--version") return { text: version, code: 0 };
45
61
  if (args[0] === "manifest") {
46
62
  const { flags, positional } = parse(args.slice(1), ["--json"], []);
47
63
  if (positional.length) throw new Error("manifest: unexpected arguments");
48
- const manifest = { name: "@staix/vault-mem", version, configVersion: CONFIG_VERSION, mcp: { server: "vmem", tools: [...VMEM_TOOL_NAMES] }, commands: COMMANDS.map(c => c.name) };
49
- return { text: JSON.stringify(manifest, null, flags["--json"] ? undefined : 2), code: 0 };
64
+ // Read-only tools are published as { name, readOnly: true } so installers can approve them without a hard-coded list.
65
+ const readOnly = new Set([...vaultTools([]), ...specTools()].filter(t => t.annotations.readOnlyHint).map(t => t.name));
66
+ const tools = VMEM_TOOL_NAMES.map(name => readOnly.has(name) ? { name, readOnly: true } : name);
67
+ const manifest = { name: "@staix/vault-mem", version, configVersion: CONFIG_VERSION, mcp: { server: "vmem", tools }, commands: COMMANDS.map(c => c.name) };
68
+ return { text: flags["--json"] ? JSON.stringify(manifest) : renderManifest(manifest, text), code: 0 };
50
69
  }
51
70
  if (args[0] === "setup") {
52
71
  const { flags, positional } = parse(args.slice(1), ["--apply", "--undo", "--json", "--root"], ["--root"]);
53
72
  if (positional.length !== 1 || (flags["--apply"] && flags["--undo"])) throw new Error("setup: requires one target and at most one of --apply/--undo");
54
73
  const mode: SetupMode = flags["--apply"] ? "apply" : flags["--undo"] ? "undo" : "dry-run";
55
74
  const report = runSetup(positional[0]!, mode, { home: resolveHome(env).home, env, ...(typeof flags["--root"] === "string" ? { root: flags["--root"] } : {}) });
56
- 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 };
57
77
  }
58
78
  if (args[0] === "completion") {
59
79
  if (args.length !== 2) throw new Error("completion: requires bash, zsh or fish");
60
80
  return { text: completionScript(args[1]!).trimEnd(), code: 0 };
61
81
  }
62
- if (args[0] === "spec") return runSpecCommand(args.slice(1), env);
63
- if (args[0] === "lint" || args[0] === "graph") return runAnalysisCommand(args[0],args.slice(1),resolveHome(env).home,env);
64
- if (args[0] === "promote" || args[0] === "sync") return runOrgCommand(args[0], args.slice(1), resolveHome(env).home, env);
65
- if (args[0] === "log") return runLogCommand(args.slice(1), resolveHome(env).home, env);
66
- if (isWriteCommand(args[0]!)) return runWriteCommand(args[0]!, args.slice(1), resolveHome(env).home, env);
67
- 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);
68
88
  const group = args[0] === "vaults" || args[0] === "specs";
69
89
  const command = group ? `${args[0]} ${args[1] ?? ""}` : args[0];
70
90
  const tail = args.slice(group ? 2 : 1);
71
- const options = command === "vaults add" ? ["--kind", "--write", "--pii", "--remote", "--registry"] : command === "vaults pii" ? ["--set"] : command === "specs add" ? ["--write", "--pii"] : [];
91
+ const options = command === "vaults add" ? ["--kind", "--write", "--pii", "--remote", "--registry"] : command === "vaults pii" ? ["--set"] : command === "specs add" ? ["--write", "--pii"] : command === "stats" ? ["--days"] : [];
72
92
  const { flags, positional } = parse(tail, ["--json", ...options, ...(command === "vaults remove" || command === "specs remove" || command === "vaults pii" || command === "recover" ? ["--confirm"] : [])], options);
73
93
  const home = resolveHome(env);
74
- let result: unknown, code = 0;
94
+ let result: unknown, code = 0, render: () => string;
75
95
  switch (command) {
76
96
  case "status": case "doctor": {
77
97
  if (positional.length) throw new Error(`${command}: unexpected arguments`);
@@ -81,7 +101,7 @@ export function run(args: string[], env: NodeJS.ProcessEnv = process.env): { tex
81
101
  const checks: Record<string, { ok: boolean; issue?: string }> = {};
82
102
  if (vault.remote) {
83
103
  try {
84
- const checked = originCheck(vault.path, vault.remote, env);
104
+ const checked = originCheck(vault.path, vault.remote, env, "doctor");
85
105
  checks.remote = { ok: checked.ok, ...(checked.issue ? { issue: checked.issue } : {}) };
86
106
  } catch (error) { checks.remote = { ok: false, issue: error instanceof Error ? error.message : "git failed" }; }
87
107
  }
@@ -105,39 +125,60 @@ export function run(args: string[], env: NodeJS.ProcessEnv = process.env): { tex
105
125
  });
106
126
  const sources = command === "doctor" && config.specs !== undefined ? specStatus(home.home, env) : undefined;
107
127
  const healthy = vaults.every(v => v.healthy && (!v.checks || Object.values(v.checks).every(check => check.ok))) && (!sources || sources.every(source => source.healthy));
108
- result = { ...home, version, stage: "foundation", 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);
109
131
  if (command === "doctor" && !healthy) code = 1;
110
132
  break;
111
133
  }
112
- case "recover":
134
+ case "stats": {
135
+ if (positional.length !== 1) throw new Error("stats: requires one vault id; use vmem stats <vault> [--days 1..3650]");
136
+ const days = flags["--days"];
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");
138
+ const stats = vaultStats(home.home, positional[0]!, days === undefined ? {} : { days: Number(days) });
139
+ result = stats; render = () => renderStats(stats, text);
140
+ if (stats.log.issues.length) code = 1;
141
+ break;
142
+ }
143
+ case "recover": {
113
144
  if (positional.length) throw new Error("recover: unexpected arguments");
114
- result = recoverRegistry(home.home, flags["--confirm"] === true);
115
- 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;
116
148
  break;
117
- case "specs list":
149
+ }
150
+ case "specs list": {
118
151
  if (positional.length) throw new Error("specs list: unexpected targets; use vmem specs list [--json]");
119
- result = loadRegistry(home.home).specs ?? [];
152
+ const specs = loadRegistry(home.home).specs ?? [];
153
+ result = specs; render = () => renderSpecsList(specs, text);
120
154
  break;
155
+ }
121
156
  case "specs add": {
122
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]");
123
158
  const value: Record<string, unknown> = { id: positional[0], path: positional[1] };
124
159
  for (const option of options) if (flags[option] !== undefined) value[option.slice(2)] = flags[option];
125
- 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);
126
162
  break;
127
163
  }
128
- case "specs remove":
164
+ case "specs remove": {
129
165
  if (positional.length !== 1) throw new Error("specs remove: requires one id; use vmem specs list, then vmem specs remove <id> [--confirm]");
130
- 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);
131
168
  break;
132
- case "vaults list":
169
+ }
170
+ case "vaults list": {
133
171
  if (positional.length) throw new Error("vaults list: unexpected arguments");
134
- 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);
135
174
  break;
175
+ }
136
176
  case "vaults add": {
137
177
  if (positional.length !== 2) throw new Error("vaults add: requires id and absolute path");
138
178
  const value: Record<string, unknown> = { id: positional[0], path: positional[1] };
139
179
  for (const option of options) if (flags[option] !== undefined) value[option.slice(2)] = flags[option];
140
- 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);
141
182
  break;
142
183
  }
143
184
  case "vaults pii": {
@@ -146,16 +187,20 @@ export function run(args: string[], env: NodeJS.ProcessEnv = process.env): { tex
146
187
  if (raw === undefined && flags["--confirm"] === true) throw new Error("vaults pii: --confirm requires --set");
147
188
  let value: unknown;
148
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"); } } }
149
- 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);
150
193
  break;
151
194
  }
152
- case "vaults remove":
195
+ case "vaults remove": {
153
196
  if (positional.length !== 1) throw new Error("vaults remove: requires id");
154
- 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);
155
199
  break;
200
+ }
156
201
  default: throw new Error(`unknown command: ${command}; use --help`);
157
202
  }
158
- return { text: JSON.stringify(result, null, flags["--json"] ? undefined : 2), code };
203
+ return { text: flags["--json"] ? JSON.stringify(result) : render(), code };
159
204
  }
160
205
  /**
161
206
  * `vmem mcp`: the vault set is fixed now; stdout carries protocol frames only. Every module a tool handler
@@ -170,22 +215,23 @@ export async function runMcp(env: NodeJS.ProcessEnv = process.env): Promise<void
170
215
  await serveMcp({ tools: server.tools, handlers: server.handlers, name: "vmem", version });
171
216
  }
172
217
  /** Async commands. Only `promote-from-amem` and `skills mine` load the agent-mem seam, and only when they run. */
173
- export async function runAsync(args: string[], env: NodeJS.ProcessEnv = process.env, io: { stdinIsTTY?: boolean } = {}): Promise<{ text: string; code: number }> {
174
- 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);
175
221
  if (usage) return { text: usage, code: 0 };
176
222
  if (args[0] === "skills") {
177
223
  const { runSkillsCommand } = await import("./skills-mine.ts");
178
- return runSkillsCommand(args.slice(1), resolveHome(env).home, env);
224
+ return runSkillsCommand(args.slice(1), resolveHome(env).home, env, text);
179
225
  }
180
- if (args[0] !== "promote-from-amem") return run(args, env);
226
+ if (args[0] !== "promote-from-amem") return runWith(args, env, text);
181
227
  const { runPromoteCommand } = await import("./promote-command.ts");
182
- return runPromoteCommand(args.slice(1), resolveHome(env).home, env, io);
228
+ return runPromoteCommand(args.slice(1), resolveHome(env).home, env, io, text);
183
229
  }
184
230
  export async function mainAsync(args: string[]): Promise<number> {
185
- 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; }
186
232
  catch (error) { console.error(`vmem: ${error instanceof Error ? error.message : "operation failed"}`); return 1; }
187
233
  }
188
234
  export function main(args: string[]): number {
189
- 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; }
190
236
  catch (error) { console.error(`vmem: ${error instanceof Error ? error.message : "operation failed"}`); return 1; }
191
237
  }
@@ -1,46 +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] [--dry-run] [--json]", mutates: true },
23
- { name: "patch", usage: "patch <vault> <note> --old TEXT --new TEXT [--expected-sha SHA] [--dry-run] [--json]", mutates: true },
24
- { name: "append", usage: "append <vault> <note> --section SECTION --markdown TEXT [--expected-sha SHA] [--dry-run] [--json]", mutates: true },
25
- { name: "frontmatter", usage: "frontmatter <vault> <note> [--set JSON] [--unset key,key] [--expected-sha SHA] [--dry-run] [--json]", mutates: true },
26
- { name: "link", usage: "link <vault> <from> <to> --relation R [--context TEXT] [--one-way] [--dry-run] [--json]", mutates: true },
27
- { name: "supersede", usage: "supersede <vault> <old> <next> [--dry-run] [--json]", mutates: true },
28
- { name: "move", usage: "move <vault> <from> <to> [--confirm --fingerprint SHA] [--dry-run] [--json]", mutates: "confirm" },
29
- { name: "delete", usage: "delete <vault> <note> [--confirm --fingerprint SHA] [--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|- [--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
- ] 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[];
44
57
  const RELATIONS = ["supports", "contradicts", "extends", "applies-to", "context-for"] as const;
45
58
  const LOG_EVENT_TYPES = ["INGEST", "ROUTE", "EXTRACT", "CONNECT", "DIGEST", "LEARN", "LINT", "TASK", "GRAPH", "SYNC", "RETHINK", "SOURCE"] as const;
46
59
  const VALUE = /^--[a-z-]+ (?!\.\.\.)([A-Z]|[a-z0-9.|,-]+|file\|-|JSON|SHA|URL|PATH|TEXT)/;
@@ -93,4 +106,33 @@ ${cases.join("\n")}
93
106
  `;
94
107
  return shell === "zsh" ? `autoload -U +X bashcompinit && bashcompinit\n${fn}complete -F _vmem vmem\n` : `${fn}complete -F _vmem vmem\n`;
95
108
  }
96
- 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. */