@staix/vault-mem 0.11.0 → 0.12.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +17 -2
  3. package/bin/vmem.js +5 -1
  4. package/package.json +2 -1
  5. package/skills/_shared/vault-adapter.md +131 -0
  6. package/skills/skill-mine/SKILL.md +52 -0
  7. package/skills/skill-mine/vocab/actions.yaml +110 -0
  8. package/skills/skill-mine/vocab/objects.yaml +123 -0
  9. package/skills/vault-connect/SKILL.md +75 -0
  10. package/skills/vault-enrich/SKILL.md +31 -0
  11. package/skills/vault-extract/README.md +20 -0
  12. package/skills/vault-extract/SKILL.md +139 -0
  13. package/skills/vault-graph/SKILL.md +120 -0
  14. package/skills/vault-learn/SKILL.md +111 -0
  15. package/skills/vault-lint/README.md +32 -0
  16. package/skills/vault-lint/SKILL.md +137 -0
  17. package/skills/vault-lint/references/lint-output.md +97 -0
  18. package/skills/vault-lint/references/vault-scope-rules.md +26 -0
  19. package/skills/vault-lint/references/work-scope-checks.md +71 -0
  20. package/skills/vault-refactor/SKILL.md +112 -0
  21. package/skills/vault-remember/SKILL.md +38 -0
  22. package/skills/vault-rethink/README.md +15 -0
  23. package/skills/vault-rethink/SKILL.md +58 -0
  24. package/skills/vault-stats/SKILL.md +49 -0
  25. package/skills/vault-sync/README.md +15 -0
  26. package/skills/vault-sync/SKILL.md +195 -0
  27. package/skills/vault-sync/references/r4-method-evidence.md +12 -0
  28. package/skills/vault-update/SKILL.md +68 -0
  29. package/skills/vmem-status/SKILL.md +30 -0
  30. package/src/amem/host-api.ts +5 -1
  31. package/src/analysis-input.ts +15 -0
  32. package/src/analysis-types.ts +3 -1
  33. package/src/assertion-policy.ts +4 -2
  34. package/src/assertions.ts +48 -8
  35. package/src/cli-output.ts +10 -3
  36. package/src/cli.ts +29 -3
  37. package/src/commands-table.ts +3 -1
  38. package/src/config.ts +21 -7
  39. package/src/enrichment-query.ts +65 -0
  40. package/src/enrichment-search.ts +69 -0
  41. package/src/enrichment-store.ts +197 -0
  42. package/src/enrichment.ts +245 -0
  43. package/src/graph-evidence.ts +2 -2
  44. package/src/index.ts +9 -0
  45. package/src/mcp-vault.ts +46 -8
  46. package/src/proposal-provider.ts +3 -2
  47. package/src/proposals.ts +10 -4
  48. package/src/read-output.ts +1 -1
  49. package/src/registry.ts +57 -2
  50. package/src/setup.ts +12 -3
  51. package/src/skills-install.ts +216 -0
  52. package/src/ui/panel-types.ts +55 -0
  53. package/src/ui/panel.js +76 -0
  54. package/src/ui/plugin.ts +95 -5
  55. package/src/vault-graph.ts +15 -7
  56. package/src/vault-index.ts +17 -0
  57. package/src/vault-lint.ts +12 -4
  58. package/src/write-operations.ts +38 -1
  59. package/src/write-types.ts +1 -0
  60. package/src/write-validation.ts +2 -1
  61. package/src/writer.ts +1 -1
package/src/setup.ts CHANGED
@@ -3,6 +3,8 @@ import { homedir } from "node:os";
3
3
  import { dirname, isAbsolute, join, resolve } from "node:path";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { isDeepStrictEqual } from "node:util";
6
+ import { shellWord } from "./text-output.ts";
7
+ import { installSkills, skillRoot, type SkillInstallReport } from "./skills-install.ts";
6
8
  import { fileURLToPath } from "node:url";
7
9
 
8
10
  /** Hosts whose MCP configuration `vmem setup` can register; `all` covers every user-level host (not agy). */
@@ -15,7 +17,7 @@ export interface McpEntry { command: string; args: string[] }
15
17
  interface HostFile { target: SetupTarget; file: string; format: "json" | "toml"; key: string }
16
18
  export interface SetupAction { target: SetupTarget; file: string; change: "add" | "replace" | "unchanged" | "restore" | "remove" | "refused" | "none"; reason?: string }
17
19
  export interface ConsoleAction { file: string; module: string; change: "add" | "replace" | "unchanged" | "remove" | "none" | "refused"; reason?: string }
18
- export interface SetupReport { mode: SetupMode; applied: boolean; entry: McpEntry; root?: InstallRoot; actions: SetupAction[]; console?: ConsoleAction; notes: string[] }
20
+ export interface SetupReport { mode: SetupMode; applied: boolean; entry: McpEntry; root?: InstallRoot; actions: SetupAction[]; console?: ConsoleAction; skills?: { target: SetupTarget; report?: SkillInstallReport; reason?: string; refused?: boolean }[]; notes: string[] }
19
21
  export interface InstallRoot { path: string; version: string }
20
22
  interface Receipt { version: 1; target: SetupTarget; file: string; existed: boolean; keyExisted?: boolean; prior: unknown; priorToml?: string[]; installed: McpEntry }
21
23
 
@@ -251,7 +253,7 @@ export function runSetup(target: string, mode: SetupMode, options: { home: strin
251
253
  if (!isAbsolute(entry.command) || entry.args.some(arg => arg.includes("\0"))) throw new Error("setup: MCP command must be absolute");
252
254
  const table = hosts(env, options.cwd ?? process.cwd());
253
255
  const targets = target === "all" ? SETUP_TARGETS.filter(t => t !== "agy") : [target as SetupTarget];
254
- const report: SetupReport = { mode, applied: false, entry, ...(root ? { root } : {}), actions: [], notes: [
256
+ const report: SetupReport = { mode, applied: false, entry, ...(root ? { root } : {}), actions: [], skills: [], notes: [
255
257
  "Registers the stdio server `vmem mcp`; restart the host session to load it.",
256
258
  "Writes the acon console plugin manifest ($AGENTHUB_HOME/console/plugins/vmem.json); re-run setup after upgrading vmem.",
257
259
  ] };
@@ -298,8 +300,15 @@ export function runSetup(target: string, mode: SetupMode, options: { home: strin
298
300
  action.change = "refused"; action.reason = error instanceof Error ? error.message : "setup failed";
299
301
  }
300
302
  }
303
+ for (const name of targets) {
304
+ try {
305
+ const path = skillRoot(name, env);
306
+ if (!path) { report.skills!.push({ target: name, reason: "skills are not installed for this host; use vmem skills export <dir>" }); continue; }
307
+ report.skills!.push({ target: name, report: installSkills(path, mode, root?.path, root?.version, ["vmem", "setup", name, ...(root ? ["--root", root.path] : []), mode === "undo" ? "--undo" : "--apply"].map(shellWord).join(" ")) });
308
+ } catch (error) { report.skills!.push({ target: name, refused: true, reason: error instanceof Error ? error.message : "skill setup failed; inspect the host configuration" }); }
309
+ }
301
310
  report.console = consoleManifest(mode, env, root?.path);
302
- report.applied = mode !== "dry-run" && [...report.actions, report.console].some(a => !["none", "unchanged", "refused"].includes(a.change));
311
+ report.applied = mode !== "dry-run" && ([...report.actions, report.console].some(a => !["none", "unchanged", "refused"].includes(a.change)) || report.skills!.some(s => s.report?.actions.some(a => ["install", "replace", "remove"].includes(a.change))));
303
312
  return report;
304
313
  }
305
314
 
@@ -0,0 +1,216 @@
1
+ /** Install package-owned skills without replacing foreign or locally modified trees. */
2
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, realpathSync, rmSync, writeFileSync, type Stats } from "node:fs";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { homedir } from "node:os";
6
+ import { fileURLToPath } from "node:url";
7
+ import { dlopen, FFIType, ptr } from "bun:ffi";
8
+ import { version } from "../package.json";
9
+ import type { SetupMode, SetupTarget } from "./setup.ts";
10
+ import { shellWord } from "./text-output.ts";
11
+
12
+ export const SKILL_NAMES = ["vault-connect", "vault-enrich", "vault-extract", "vault-graph", "vault-learn", "vault-lint", "vault-refactor", "vault-remember", "vault-rethink", "vault-stats", "vault-sync", "vault-update", "vmem-status", "skill-mine"] as const;
13
+ const PACKAGE_ROOT = fileURLToPath(new URL("..", import.meta.url));
14
+ const MARKER = ".vmem-skill.json", MAX_FILE = 2 * 1024 * 1024, MAX_BYTES = 16 * 1024 * 1024, MAX_FILES = 512;
15
+ export interface SkillAction { name: string; path: string; change: "install" | "replace" | "remove" | "unchanged" | "absent" | "modified" | "foreign" | "refused"; reason?: string }
16
+ export interface SkillInstallReport { root: string; actions: SkillAction[] }
17
+ interface Marker { tool: "vmem"; version: string; sha256: string }
18
+ type Files = Map<string, Uint8Array>;
19
+ function safePath(root: string, path: string): boolean { const rel = relative(root, path); return rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel); }
20
+ function boundedFile(file: string, remaining: number): Uint8Array {
21
+ let fd: number;
22
+ try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
23
+ catch { throw new Error("skill file is missing, unreadable or linked; inspect the skill directory"); }
24
+ try {
25
+ const before = fstatSync(fd);
26
+ if (!before.isFile() || before.size > MAX_FILE || before.size > remaining) throw new Error("skill file exceeds its read bound or is not regular; inspect the skill directory");
27
+ const bytes = Buffer.alloc(before.size + 1); let length = 0;
28
+ while (length < bytes.length) { const n = readSync(fd, bytes, length, bytes.length - length, null); if (!n) break; length += n; }
29
+ const after = fstatSync(fd), named = lstatSync(file);
30
+ if (named.isSymbolicLink() || before.dev !== after.dev || before.ino !== after.ino || after.dev !== named.dev || after.ino !== named.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || length !== before.size) throw new Error("skill file changed during inspection; stop concurrent edits and retry");
31
+ return bytes.subarray(0, length);
32
+ } finally { closeSync(fd); }
33
+ }
34
+ function walk(root: string): Files {
35
+ const files: Files = new Map(); let total = 0, count = 0;
36
+ const visit = (dir: string) => {
37
+ const stat = lstatSync(dir);
38
+ if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync(dir) !== dir) throw new Error("skill contains a linked or non-directory path; inspect the skill directory");
39
+ const entries = opendirSync(dir); let children = 0;
40
+ try {
41
+ let entry: ReturnType<typeof entries.readSync>;
42
+ while ((entry = entries.readSync()) !== null) {
43
+ if (++count > MAX_FILES) throw new Error("skill contains too many entries; inspect the skill directory");
44
+ const path = join(dir, entry.name), rel = relative(root, path).split(sep).join("/");
45
+ if (!safePath(root, path) || entry.name === "." || entry.name === "..") throw new Error("skill contains an unsafe path; inspect the skill directory");
46
+ if (rel === MARKER) continue;
47
+ children++;
48
+ if (entry.isDirectory()) visit(path);
49
+ else if (entry.isFile()) { const data = boundedFile(path, MAX_BYTES - total); total += data.length; files.set(rel, data); }
50
+ else throw new Error("skill contains a link or special file; inspect the skill directory");
51
+ }
52
+ } finally { entries.closeSync(); }
53
+ if (dir !== root && children === 0) throw new Error("skill contains an unexpected empty directory; inspect the skill directory");
54
+ const after = lstatSync(dir);
55
+ if (!identical(stat, after) || realpathSync(dir) !== dir) throw new Error("skill directory changed during inspection; stop concurrent edits and retry");
56
+ };
57
+ visit(root); return files;
58
+ }
59
+ function digest(files: Files): string {
60
+ const hash = createHash("sha256");
61
+ for (const [name, data] of [...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) { hash.update(`${Buffer.byteLength(name)}:${name}:${data.length}:`); hash.update(data); }
62
+ return hash.digest("hex");
63
+ }
64
+ function packaged(name: string, packageRoot: string): Files {
65
+ const root = join(packageRoot, "skills", name);
66
+ let files: Files, adapter: Uint8Array;
67
+ try { files = walk(root); adapter = boundedFile(join(packageRoot, "skills", "_shared", "vault-adapter.md"), MAX_FILE); }
68
+ catch (error) { throw new Error(`packaged skill ${name} is unavailable or invalid; reinstall a complete vmem package`, { cause: error }); }
69
+ if (!files.has("SKILL.md") || files.has("references/vault-adapter.md")) throw new Error("packaged skill is missing its entry or contains a conflicting adapter; reinstall vmem");
70
+ files.set("references/vault-adapter.md", adapter);
71
+ const dirs = new Set<string>(); let bytes = 0;
72
+ for (const [name, data] of files) {
73
+ bytes += data.length;
74
+ const parts = name.split("/"); for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join("/"));
75
+ }
76
+ if (bytes > MAX_BYTES || files.size + dirs.size + 1 > MAX_FILES) throw new Error("packaged skill with its adapter exceeds installation bounds; reinstall a valid vmem package");
77
+ return files;
78
+ }
79
+ function marker(path: string): Marker | undefined {
80
+ try {
81
+ const data: unknown = JSON.parse(Buffer.from(boundedFile(join(path, MARKER), 4096)).toString("utf8"));
82
+ if (!data || typeof data !== "object" || Array.isArray(data)) return undefined;
83
+ const m = data as Record<string, unknown>;
84
+ return Object.keys(m).sort().join(",") === "sha256,tool,version" && m.tool === "vmem" && typeof m.version === "string" && m.version.length <= 128 && typeof m.sha256 === "string" && /^[a-f0-9]{64}$/.test(m.sha256) ? m as unknown as Marker : undefined;
85
+ } catch { return undefined; }
86
+ }
87
+ /** Atomic no-replace and directory exchange. Unsupported kernels or filesystems are refused. */
88
+ function renameAtomic(from: string, to: string, exchange: boolean): void {
89
+ if (process.platform !== "linux" && process.platform !== "darwin") throw new Error("atomic skill rename is unsupported on this platform; use vmem skills export on a supported host");
90
+ const fromBytes = Buffer.alloc(Buffer.byteLength(from) + 1), toBytes = Buffer.alloc(Buffer.byteLength(to) + 1);
91
+ fromBytes.write(from); toBytes.write(to);
92
+ let result: number;
93
+ try {
94
+ if (process.platform === "darwin") {
95
+ const lib = dlopen("/usr/lib/libSystem.B.dylib", { renamex_np: { args: [FFIType.ptr, FFIType.ptr, FFIType.u32], returns: FFIType.i32 } });
96
+ try { result = lib.symbols.renamex_np(ptr(fromBytes), ptr(toBytes), exchange ? 2 : 4); } finally { lib.close(); }
97
+ } else {
98
+ const lib = dlopen("libc.so.6", { renameat2: { args: [FFIType.i32, FFIType.ptr, FFIType.i32, FFIType.ptr, FFIType.u32], returns: FFIType.i32 } });
99
+ try { result = lib.symbols.renameat2(-100, ptr(fromBytes), -100, ptr(toBytes), exchange ? 2 : 1); } finally { lib.close(); }
100
+ }
101
+ } catch (error) { throw new Error("atomic skill rename is unavailable; inspect platform and filesystem support before retrying", { cause: error }); }
102
+ if (result !== 0) throw new Error("atomic skill rename failed or target changed; inspect the skill root and retry on a supported filesystem");
103
+ }
104
+ function identical(a: Stats, b: Stats): boolean { return a.dev === b.dev && a.ino === b.ino && a.isDirectory() && b.isDirectory() && !a.isSymbolicLink() && !b.isSymbolicLink(); }
105
+ function stage(root: string, files: Files, digestValue: string, packageVersion: string): string {
106
+ const dir = join(root, `.vmem-skill-${randomUUID()}`); mkdirSync(dir, { mode: 0o700 });
107
+ try {
108
+ for (const [name, bytes] of files) {
109
+ const file = join(dir, name); if (!safePath(dir, file)) throw new Error("packaged skill has an unsafe path; reinstall vmem");
110
+ mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 }); writeFileSync(file, bytes, { flag: "wx", mode: 0o600 });
111
+ }
112
+ writeFileSync(join(dir, MARKER), JSON.stringify({ tool: "vmem", version: packageVersion, sha256: digestValue }) + "\n", { flag: "wx", mode: 0o600 });
113
+ return dir;
114
+ } catch (error) { rmSync(dir, { recursive: true, force: true }); throw error; }
115
+ }
116
+ function existingRoot(path: string): string | undefined {
117
+ try { const info = lstatSync(path); if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("skill root is linked or not a directory; choose a real directory"); return realpathSync(path); }
118
+ catch (error) {
119
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
120
+ if (error instanceof Error && error.message.startsWith("skill root is linked")) throw error;
121
+ throw new Error("skill root cannot be inspected; check its path and permissions", { cause: error });
122
+ }
123
+ }
124
+ /** Re-walk a moved-aside tree and delete it only while it still matches `sha`; false keeps it for inspection. */
125
+ function removeVerified(path: string, sha: string): boolean {
126
+ try { if (digest(walk(path)) !== sha) return false; rmSync(path, { recursive: true }); return true; }
127
+ catch { return false; }
128
+ }
129
+ /** Plan or install one complete skill tree per name. `root` must be an absolute target directory. */
130
+ export function installSkills(root: string, mode: SetupMode, packageRoot = PACKAGE_ROOT, packageVersion = version, retryCommand = ["vmem", "skills", "export", root].map(shellWord).join(" ")): SkillInstallReport {
131
+ if (!isAbsolute(root)) throw new Error("skills: target must be absolute; provide an absolute skill root");
132
+ if (mode !== "undo" && (typeof packageVersion !== "string" || !packageVersion.trim() || Buffer.byteLength(packageVersion) > 128 || /[\p{Cc}\p{Zl}\p{Zp}]/u.test(packageVersion))) throw new Error("skills: package version is invalid; reinstall a valid vmem package");
133
+ const requested = resolve(root), actions: SkillAction[] = [];
134
+ let actual = existingRoot(requested);
135
+ if (!actual && mode !== "dry-run" && mode !== "undo") { mkdirSync(requested, { recursive: true, mode: 0o700 }); actual = existingRoot(requested); }
136
+ if (!actual && mode === "apply") throw new Error("skills: target directory could not be created; inspect the target and retry");
137
+ for (const name of SKILL_NAMES) {
138
+ const target = join(actual ?? requested, name), action: SkillAction = { name, path: target, change: "absent" }; actions.push(action);
139
+ try {
140
+ let before: Stats | undefined;
141
+ try { before = lstatSync(target); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
142
+ if (before && (!before.isDirectory() || before.isSymbolicLink())) { action.change = "foreign"; action.reason = mode === "undo" ? `not a vmem-owned real directory; left untouched. Remove it by hand or keep it` : `not a vmem-owned real directory; left untouched. Remove or relocate it and rerun ${retryCommand} to let vmem manage it, or keep it`; continue; }
143
+ const own = before ? marker(target) : undefined;
144
+ if (before && !own) { action.change = "foreign"; action.reason = mode === "undo" ? `ownership marker missing or invalid; left untouched. Remove it by hand or keep it` : `ownership marker missing or invalid; left untouched. Remove or relocate it and rerun ${retryCommand} to let vmem manage it, or keep it`; continue; }
145
+ if (before && own) {
146
+ let current: string;
147
+ try { current = digest(walk(target)); } catch { action.change = "modified"; action.reason = mode === "undo" ? `contents cannot be safely verified; left untouched. Remove it by hand, or restore it and rerun ${retryCommand}` : `contents cannot be safely verified; left untouched. Inspect or remove it and rerun ${retryCommand}, or keep it`; continue; }
148
+ if (current !== own.sha256) { action.change = "modified"; action.reason = mode === "undo" ? `contents differ from the ownership marker; left untouched. Remove it by hand, or restore it and rerun ${retryCommand}` : `contents differ from the ownership marker; left untouched. Restore or remove it and rerun ${retryCommand}, or keep the local edit`; continue; }
149
+ }
150
+ if (mode === "undo") {
151
+ if (!before) continue;
152
+ action.change = "remove";
153
+ const moved = join(actual!, `.vmem-skill-${randomUUID()}`);
154
+ renameAtomic(target, moved, false);
155
+ let verified = false;
156
+ try { verified = identical(before, lstatSync(moved)) && digest(walk(moved)) === own!.sha256; } catch { /* Restore an unverifiable tree. */ }
157
+ if (!verified) {
158
+ try { renameAtomic(moved, target, false); }
159
+ catch { throw new Error(`skill changed during undo; inspect ${target} and ${moved} and restore the original manually`); }
160
+ throw new Error("skill changed during undo; inspect the skill root before retrying");
161
+ }
162
+ if (!removeVerified(moved, own!.sha256)) action.reason = `removed but the moved-aside tree changed before deletion or cleanup failed; inspect ${moved} before retrying`;
163
+ continue;
164
+ }
165
+ const files = packaged(name, packageRoot), sha = digest(files);
166
+ if (before && own?.sha256 === sha && own.version === packageVersion) { action.change = "unchanged"; continue; }
167
+ action.change = before ? "replace" : "install";
168
+ if (mode === "dry-run") continue;
169
+ const temp = stage(actual!, files, sha, packageVersion), staged = lstatSync(temp);
170
+ let preserve = false, published = false;
171
+ try {
172
+ if (!before) { renameAtomic(temp, target, false); published = true; }
173
+ else {
174
+ if (!identical(before, lstatSync(target))) throw new Error("skill changed before replacement; inspect it and retry");
175
+ renameAtomic(temp, target, true); published = true;
176
+ let verified = false;
177
+ try { verified = identical(before, lstatSync(temp)) && digest(walk(temp)) === own!.sha256 && identical(staged, lstatSync(target)); } catch { /* Restore an unverifiable tree. */ }
178
+ if (!verified) {
179
+ try { if (!identical(staged, lstatSync(target))) throw new Error("target changed"); renameAtomic(temp, target, true); published = false; }
180
+ catch { preserve = true; }
181
+ // The swap-back failed with the new tree published: neither tree is known good, so this is a failure.
182
+ if (published) { action.change = "refused"; action.reason = `replacement outcome needs inspection; inspect ${target} and ${temp} before retrying`; continue; }
183
+ throw new Error("skill changed during replacement; inspect it and retry");
184
+ }
185
+ }
186
+ } finally {
187
+ if (!preserve) {
188
+ // The moved-aside old tree is deleted only if it still matches its marker right before removal.
189
+ if (published && before) { if (!removeVerified(temp, own!.sha256)) action.reason = `installed, but the previous tree changed before deletion or cleanup failed; inspect ${temp}`; }
190
+ else try { rmSync(temp, { recursive: true, force: true }); }
191
+ catch (error) { if (published) action.reason = `installed but cleanup failed; inspect ${temp}`; else throw error; }
192
+ }
193
+ }
194
+ } catch (error) { action.change = "refused"; action.reason = error instanceof Error ? error.message : "skill operation failed; inspect the skill root and retry"; }
195
+ }
196
+ return { root: actual ?? requested, actions };
197
+ }
198
+ export function skillRoot(target: SetupTarget, env: NodeJS.ProcessEnv): string | undefined {
199
+ const map: Partial<Record<SetupTarget, [string, string]>> = { claude: ["CLAUDE_CONFIG_DIR", ".claude"], codex: ["CODEX_HOME", ".codex"], kimi: ["KIMI_CODE_HOME", ".kimi-code"], qwen: ["QWEN_HOME", ".qwen"] };
200
+ const spec = map[target]; if (!spec) return undefined;
201
+ const value = env[spec[0]]?.trim(), home = env.HOME?.trim() || homedir();
202
+ if (value && !isAbsolute(value)) throw new Error(`setup: ${spec[0]} must be absolute; set an absolute host configuration directory`);
203
+ return join(value ? resolve(value) : join(home, spec[1]), "skills");
204
+ }
205
+
206
+ /** Export into a dedicated directory. Unknown entries mean it is not a vmem export root. */
207
+ export function exportSkills(destination: string): SkillInstallReport {
208
+ if (typeof destination !== "string" || !destination.trim() || /[\p{Cc}\p{Zl}\p{Zp}]/u.test(destination)) throw new Error("skills export: destination is missing or invalid; choose a directory path");
209
+ const root = resolve(destination), existing = existingRoot(root);
210
+ if (existing) {
211
+ const entries = opendirSync(existing);
212
+ try { let entry: ReturnType<typeof entries.readSync>; while ((entry = entries.readSync()) !== null) if (!(SKILL_NAMES as readonly string[]).includes(entry.name)) throw new Error("skills export: destination contains foreign entries; choose an empty directory or an existing vmem export"); }
213
+ finally { entries.closeSync(); }
214
+ }
215
+ return installSkills(root, "apply");
216
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Snapshot shapes of the console panels added in vault-mem#266 increment 1b. Each panel answers with the result of the
3
+ * existing reader (proposal provider, assertion reader, Git snapshot history) unchanged, plus the selection it was asked
4
+ * for; a refusal arrives as `error`, naming its cause and next step.
5
+ */
6
+ import type { ProposalPage, ProposalView } from "../proposal-provider.ts";
7
+ import type { AssertionsReadResult } from "../assertion-read.ts";
8
+ import type { ChangesResult, HistoryResult } from "../vault-history.ts";
9
+
10
+ export type ProposalState = "pending" | "applied" | "rejected" | "apply_unknown";
11
+
12
+ /** A coverage notice for the panel: `err` when entries are left out as untrusted, `warn` for other gaps, `neutral` for information. */
13
+ export interface CoverageWarning { tone: "err" | "warn" | "neutral"; message: string }
14
+
15
+ /** `proposals` panel: params `vault`, `state` (default pending), `after` page cursor, `id` to show one proposal. */
16
+ export interface ProposalsSnapshot {
17
+ vault: string | null;
18
+ state: ProposalState;
19
+ page: ProposalPage | null;
20
+ selected: ProposalView | null;
21
+ error?: string;
22
+ }
23
+
24
+ /** Coverage notices for an assertion read: anything short of a fully verified, synced and indexed journal is named with its next step. */
25
+ export function assertionCoverageWarnings(coverage: AssertionsReadResult["coverage"] | undefined): CoverageWarning[] {
26
+ if (!coverage) return [];
27
+ const out: CoverageWarning[] = [];
28
+ if (coverage.untrusted.length) out.push({ tone: "err", message: `${coverage.untrusted.length} journal ${coverage.untrusted.length === 1 ? "entry is" : "entries are"} untrusted and left out (${coverage.untrusted.slice(0, 3).map(u => `${u.segment}#${u.seq}: ${u.reason}`).join("; ")}); run \`vmem assertions <vault> --history --json\` and inspect the journal segments` });
29
+ if (coverage.unsupported.length) out.push({ tone: "warn", message: `${coverage.unsupported.length} journal ${coverage.unsupported.length === 1 ? "entry uses" : "entries use"} an unsupported schema and ${coverage.unsupported.length === 1 ? "is" : "are"} left out; upgrade vmem to read them` });
30
+ if (coverage.tornTail.length) out.push({ tone: "warn", message: `torn journal tail in ${coverage.tornTail.join(", ")}: the incomplete last entry is ignored; the next append repairs it` });
31
+ if (coverage.partialBatch.length) out.push({ tone: "warn", message: `${coverage.partialBatch.length} ${coverage.partialBatch.length === 1 ? "entry belongs" : "entries belong"} to an incomplete batch and ${coverage.partialBatch.length === 1 ? "is" : "are"} left out; resubmit the batch` });
32
+ if (coverage.purged) out.push({ tone: "neutral", message: `${coverage.purged} purged ${coverage.purged === 1 ? "payload is" : "payloads are"} not shown` });
33
+ if (coverage.unsynced) out.push({ tone: "warn", message: `${coverage.unsynced} assertion ${coverage.unsynced === 1 ? "file is" : "files are"} not committed; run \`vmem sync\` to share them` });
34
+ if (coverage.unsynced === null) out.push({ tone: "neutral", message: "journal sync state is unknown (no Git repository or Git unavailable)" });
35
+ if (coverage.indexIssue) out.push({ tone: "warn", message: coverage.indexIssue });
36
+ return out;
37
+ }
38
+
39
+ /** `assertions` panel: params `vault`, `subject`, `relation`, `at`, `asOf`, `history`, `cursor`, as `vmem_assertions`. */
40
+ export interface AssertionsSnapshot {
41
+ vault: string | null;
42
+ result: AssertionsReadResult | null;
43
+ /** Every gap in the reported coverage (untrusted, unsupported, torn, partial, purged, unsynced, index), empty when complete. */
44
+ warnings: CoverageWarning[];
45
+ error?: string;
46
+ }
47
+
48
+ /** `history` panel: params `vault`, `path`, `cursor`, and `from` with `to` (full commit ids) for the changes between them. */
49
+ export interface HistorySnapshot {
50
+ vault: string | null;
51
+ path: string | null;
52
+ history: HistoryResult | null;
53
+ changes: ChangesResult | null;
54
+ error?: string;
55
+ }
package/src/ui/panel.js CHANGED
@@ -15,7 +15,33 @@ export default (host) => {
15
15
  input, h("button", { type: "submit", class: "btn", text: "Search" }));
16
16
  };
17
17
 
18
+ /** Journal coverage warnings computed by the provider (`warnings`); anything short of a fully verified journal shows. */
19
+ const coverageNotices = (warnings) => (warnings ?? []).map((w) => ui.notice(w.message, w.tone));
20
+ // A continuation is bound to the query that produced it, so every query param travels with it.
21
+ const assertionQuery = () => Object.fromEntries(["subject", "relation", "at", "asOf", "history", "limit"].filter((k) => params[k] !== undefined && params[k] !== "").map((k) => [k, params[k]]));
22
+
18
23
  const views = {
24
+ settings(s) {
25
+ if (s.error) return [ui.notice(s.error, "err")];
26
+ const defaultVault = h("input", { type: "text", name: "defaultVault", value: s.defaultVault ?? "", class: "vmem-input", "aria-label": "Default vault" });
27
+ const write = h("select", { name: "write", class: "vmem-input", "aria-label": "Write mode" }, ...["none", "cli", "mcp"].map(v => h("option", { value: v, text: v, ...(v === s.write ? { selected: true } : {}) })));
28
+ const patterns = h("input", { type: "text", name: "piiPatterns", value: JSON.stringify(s.piiPatterns ?? []), class: "vmem-input", "aria-label": "PII patterns as JSON array", oninput: (e) => e.target.setCustomValidity("") });
29
+ const resolution = h("input", { type: "number", name: "resolution", value: String(s.graphResolution), min: "0.01", max: "100", step: "any", class: "vmem-input", "aria-label": "Graph resolution" });
30
+ const enrichment = h("input", { type: "checkbox", name: "enrichmentEnabled", checked: s.enrichmentEnabled, "aria-label": "Enable enrichment" });
31
+ return [h("p", { text: `Settings for ${s.vault}${s.defaultVaultExplicit ? "" : " (default vault uses fallback)"}` }), h("form", { class: "vmem-bar", onsubmit: e => {
32
+ e.preventDefault();
33
+ let piiPatterns;
34
+ try { piiPatterns = JSON.parse(patterns.value); } catch { patterns.setCustomValidity("Use a JSON array of patterns"); patterns.reportValidity(); return; }
35
+ patterns.setCustomValidity("");
36
+ const changes = {};
37
+ if (defaultVault.value !== (s.defaultVault ?? "")) changes.defaultVault = defaultVault.value;
38
+ if (write.value !== s.write) changes.write = write.value;
39
+ if (JSON.stringify(piiPatterns) !== JSON.stringify(s.piiPatterns ?? [])) changes.piiPatterns = piiPatterns;
40
+ if (Number(resolution.value) !== s.graphResolution) changes.graphResolution = Number(resolution.value);
41
+ if (enrichment.checked !== s.enrichmentEnabled) changes.enrichmentEnabled = enrichment.checked;
42
+ host.action({ action: "settings", ...vaultParam(), changes });
43
+ } }, defaultVault, write, patterns, resolution, h("label", {}, enrichment, h("span", { text: "Enable enrichment" })), h("button", { type: "submit", class: "btn", text: "Review settings" }))];
44
+ },
19
45
  overview(s) {
20
46
  const vaults = s.status?.vaults ?? [];
21
47
  if (!vaults.length) return [ui.empty("No vault registered", "Run `vmem vaults add <id> <path>` to register one.")];
@@ -112,6 +138,56 @@ export default (host) => {
112
138
  ...(typeof p === "string" && p.startsWith("notes/") ? { onOpen: () => openNote(p) } : {}) });
113
139
  }) ?? ui.empty("Log is empty")];
114
140
  },
141
+ proposals(s) {
142
+ const items = s.page?.items ?? [], p = s.selected;
143
+ const stateSelect = h("select", { name: "state", class: "vmem-input", "aria-label": "Proposal state", onchange: () => go("proposals", { state: stateSelect.value }) },
144
+ ...["pending", "applied", "rejected", "apply_unknown"].map((v) => h("option", { value: v, text: v, ...(v === s.state ? { selected: true } : {}) })));
145
+ const reason = h("input", { type: "text", name: "reason", class: "vmem-input", "aria-label": "Rejection reason", placeholder: "reason for rejecting" });
146
+ const detail = p ? ui.detail({
147
+ kind: "proposal", title: p.path, state: { text: p.state, ...(p.state === "apply_unknown" ? { tone: "warn" } : {}) },
148
+ actions: p.state === "pending" ? [
149
+ ui.button("Apply…", () => host.action({ action: "proposal-apply", id: p.id, ...vaultParam() }), { tone: "primary" }),
150
+ h("form", { class: "vmem-inline", onsubmit: (e) => { e.preventDefault(); if (reason.value.trim()) host.action({ action: "proposal-reject", id: p.id, reason: reason.value.trim(), ...vaultParam() }); } },
151
+ reason, h("button", { type: "submit", class: "btn", text: "Reject…" })),
152
+ ] : [],
153
+ ...(p.decisionReason ? { summary: `reason: ${p.decisionReason}` } : {}),
154
+ sections: [{ title: "Operation", open: true, body: h("div", {}, h("pre", { class: "vmem-body", text: p.content ?? "" }), p.truncated ? ui.notice("Truncated; read the rest with `vmem proposal show`.", "warn") : null) }],
155
+ footer: [`${p.id} · ${p.createdAt}${p.agentLabelUnverified ? ` · agent ${p.agentLabelUnverified} (unverified)` : ""}`],
156
+ }) : null;
157
+ return [s.error ? ui.notice(s.error, "err") : null, h("div", { class: "vmem-bar" }, stateSelect,
158
+ ...(s.page?.nextCursor ? [ui.button("Next page", () => go("proposals", { state: s.state, page: s.page.nextCursor }))] : [])), detail,
159
+ ui.rows(items, (x) => ui.row({ title: x.path, sub: `${x.state} · ${x.createdAt}`, onOpen: () => go("proposals", { state: s.state, id: x.id }), ...(p?.id === x.id ? { chip: { text: "shown", tone: "neutral" } } : {}) }))
160
+ ?? ui.empty(`No ${s.state} proposals`, "Agents submit proposals with `vmem_proposal_submit` when the vault opts in.")];
161
+ },
162
+ assertions(s) {
163
+ const r = s.result, items = r?.items ?? [];
164
+ const subject = h("input", { type: "text", name: "subject", class: "vmem-input", "aria-label": "Subject", placeholder: "subject (optional)", value: params.subject ?? "" });
165
+ const relation = h("input", { type: "text", name: "relation", class: "vmem-input", "aria-label": "Relation", placeholder: "relation (optional)", value: params.relation ?? "" });
166
+ const filter = h("form", { class: "vmem-bar", onsubmit: (e) => { e.preventDefault(); const { subject: _s, relation: _r, ...rest } = assertionQuery(); go("assertions", { ...rest, ...(subject.value.trim() ? { subject: subject.value.trim() } : {}), ...(relation.value.trim() ? { relation: relation.value.trim() } : {}) }); } },
167
+ subject, relation, h("button", { type: "submit", class: "btn", text: "Filter" }));
168
+ return [s.error ? ui.notice(s.error, "err") : null, filter,
169
+ ...coverageNotices(s.warnings),
170
+ ui.rows(items, (a) => ui.row({ title: `${a.subject} · ${a.relation}${a.value !== undefined ? ` = ${a.value}` : ""}`, sub: [a.op, a.from && `from ${a.from}`, a.to && `to ${a.to}`, a.on && `on ${a.on}`, `recorded ${a.recordedAt}`].filter(Boolean).join(" · "),
171
+ ...(a.subjectNote?.path ? { onOpen: () => openNote(a.subjectNote.path) } : {}) }))
172
+ ?? ui.empty("No assertions", "Agents record them with `vmem_assert`."),
173
+ r?.continuation ? ui.button("Next page", () => go("assertions", { ...assertionQuery(), cursor: r.continuation })) : null];
174
+ },
175
+ history(s) {
176
+ const path = h("input", { type: "text", name: "path", class: "vmem-input", "aria-label": "Note path", placeholder: "notes/stem.md", value: s.path ?? "" });
177
+ const form = h("form", { class: "vmem-bar", onsubmit: (e) => { e.preventDefault(); if (path.value.trim()) go("history", { path: path.value.trim() }); } }, path, h("button", { type: "submit", class: "btn", text: "History" }));
178
+ const revs = s.history?.revisions ?? [], changed = s.changes?.changed ?? [];
179
+ const reason = s.history?.capability ?? s.changes?.capability;
180
+ return [s.error ? ui.notice(s.error, "err") : null, form,
181
+ reason ? ui.notice(`Git history is unavailable: ${reason}`, "warn") : null,
182
+ s.changes ? h("section", { class: "card" }, h("h2", { text: `Changes ${s.changes.from.slice(0, 10)} → ${s.changes.to.slice(0, 10)}` }),
183
+ ui.rows(changed, (c) => ui.row({ title: c.path, sub: c.status, onOpen: () => openNote(c.path) })) ?? ui.empty("No note changed"),
184
+ s.changes.continuation ? ui.button("More changes", () => go("history", { ...(s.path ? { path: s.path } : {}), ...(params.cursor ? { cursor: params.cursor } : {}), from: s.changes.from, to: s.changes.to, changesCursor: s.changes.continuation })) : null) : null,
185
+ s.path ? ui.rows(revs.map((r, i) => ({ r, prev: revs[i + 1] })), ({ r, prev }) => ui.row({ title: `${r.revision.slice(0, 10)} · ${r.committedAt}`, sub: `${r.bytes} bytes`,
186
+ ...(prev ? { verbs: [ui.button("Changes since previous", () => go("history", { path: s.path, from: prev.revision, to: r.revision }))] } : {}) }))
187
+ ?? ui.empty("No revisions", "The note has no committed history yet.") : ui.empty("No note selected", "Enter a note path to see its Git history."),
188
+ s.history?.continuation ? h("div", { class: "vmem-bar" }, ui.button("Older revisions", () => go("history", { path: s.path, cursor: s.history.continuation })), ...(params.cursor ? [ui.button("Newest", () => go("history", { path: s.path }))] : [])) : null,
189
+ s.history?.coverage && s.history.coverage.complete === false ? ui.notice(`History is incomplete${s.history.coverage.reason ? `: ${s.history.coverage.reason}` : ""}.`, "warn") : null];
190
+ },
115
191
  };
116
192
 
117
193
  let last = "", savedView = "", savedSnapshot;
package/src/ui/plugin.ts CHANGED
@@ -9,8 +9,10 @@ import { resolveHome } from "../home.ts";
9
9
  import { createVaultMcp } from "../mcp-vault.ts";
10
10
  import { validArguments } from "../mcp.ts";
11
11
  import { listPromotionCandidates } from "../promote.ts";
12
- import { loadRegistry } from "../registry.ts";
12
+ import { changeSettings, settingsSnapshot, loadRegistry } from "../registry.ts";
13
13
  import { createSnapshotRevision, createPromoteSnapshot, nextSnapshotCursor } from "./snapshot-cache.ts";
14
+ import { assertionCoverageWarnings } from "./panel-types.ts";
15
+ import type { AssertionsReadResult } from "../assertion-read.ts";
14
16
  import { createInboxSnapshot } from "./inbox.ts";
15
17
  import { lintVault } from "../vault-lint.ts";
16
18
  import { readLogSince } from "../vault-log.ts";
@@ -90,8 +92,12 @@ export const plugin: ConsolePlugin = {
90
92
  { id: "promote", title: "Promote", order: 4, maxAgeMs: REUSE_MS },
91
93
  { id: "lint", title: "Lint", order: 5, maxAgeMs: REUSE_MS },
92
94
  { id: "log", title: "Log", order: 6, maxAgeMs: REUSE_MS },
95
+ { id: "settings", title: "Settings", order: 7 },
96
+ { id: "proposals", title: "Proposals", order: 8, maxAgeMs: REUSE_MS },
97
+ { id: "assertions", title: "Assertions", order: 9 },
98
+ { id: "history", title: "History", order: 10 },
93
99
  ],
94
- capabilities: { actions: ["delete", "move", "promote", "promote-from-amem"], confirm: true, inbox: true, inboxMaxAgeMs: REUSE_MS, search: true },
100
+ capabilities: { actions: ["delete", "move", "promote", "promote-from-amem", "settings", "proposal-apply", "proposal-reject"], confirm: true, inbox: true, inboxMaxAgeMs: REUSE_MS, search: true },
95
101
  },
96
102
  async open(ctx): Promise<ConsoleProvider> {
97
103
  const home = resolveHome().home;
@@ -100,6 +106,7 @@ export const plugin: ConsolePlugin = {
100
106
  // The shell's tabs navigate without params, so the vault chosen on one panel is kept for the others.
101
107
  // ponytail: one choice per provider; fine for H0's single person, per session once H1 serves several.
102
108
  let chosen: string | undefined;
109
+ const promotionSource = mcp.vaults.find(v => v.id === mcp.defaultVault && v.kind === "personal") ?? mcp.vaults.find(v => v.kind === "personal");
103
110
  // An explicit vault must exist (undefined otherwise, like MCP's own check); only an omitted one falls back.
104
111
  const vaultOf = (args: Args) => {
105
112
  const asked = str(args.vault);
@@ -167,12 +174,31 @@ export const plugin: ConsolePlugin = {
167
174
  return confirmedOutcome(done, describe(preview).verb);
168
175
  }
169
176
 
177
+ /**
178
+ * A read panel through the MCP handler: arguments are checked against the tool schema, and a thrown refusal
179
+ * (unknown vault, invalid cursor, missing proposal) becomes the snapshot's `error` text, which names cause and next step.
180
+ */
181
+ async function readTool(tool: string, args: Args, fixed: Args = {}): Promise<{ result: Args } | { error: string }> {
182
+ const checked = forward(tool, args, fixed);
183
+ if (typeof checked === "string") return { error: `${checked}; correct the panel parameters and reload` };
184
+ try {
185
+ const result = await call(tool, checked);
186
+ return result.refused ? { error: firstIssue(result) } : { result };
187
+ } catch (error) { return { error: error instanceof Error ? error.message : String(error) }; }
188
+ }
189
+ const PROPOSAL_STATES = ["pending", "applied", "rejected", "apply_unknown"];
190
+
170
191
  return {
171
192
  async close() { await inbox.close(); },
172
193
  assets: { js: asset("./panel.js"), css: asset("./panel.css") },
173
194
  async snapshot(input) {
174
195
  const args = input as Args;
175
196
  switch (input.panel) {
197
+ case "settings": {
198
+ const vault = vaultOf(args);
199
+ if (!vault) return { error: "settings: no selected vault; select a registered vault" };
200
+ return settingsSnapshot(home, vault.id);
201
+ }
176
202
  case "inbox": {
177
203
  const result = await inbox.snapshot();
178
204
  return args.after === result.cursor ? { changed: false, cursor: result.cursor } : result;
@@ -205,8 +231,8 @@ export const plugin: ConsolePlugin = {
205
231
  const note = await call("vmem_read", { path, ...pass(args) });
206
232
  if (note.refused) return { note: null, error: firstIssue(note) };
207
233
  const links = await call("vmem_links", { path, ...pass(args) });
208
- // vmem_promote always reads from the default personal vault, so offer it only there.
209
- const promotable = vaultOf(args)?.id === mcp.defaultVault && vaultOf(args)?.kind === "personal";
234
+ // vmem_promote reads from the preferred personal vault, so offer it only there.
235
+ const promotable = vaultOf(args)?.id === promotionSource?.id && promotionSource !== undefined;
210
236
  return { note, links, orgVaults: promotable ? mcp.vaults.filter(v => v.kind === "org").map(v => v.id) : [] };
211
237
  }
212
238
  case "promote": {
@@ -237,12 +263,50 @@ export const plugin: ConsolePlugin = {
237
263
  const r = readLogSince(home, { vault: vault.id, limit: 100, ...(str(args.type) ? { type: str(args.type) } : {}), ...(str(args.since) ? { after: str(args.since) } : {}) });
238
264
  return { vault: vault.id, rows: r.lines.map(parseLogLine).reverse(), cursor: r.cursor, ...(r.reset ? { reset: true } : {}), ...(r.more ? { more: true } : {}), ...(r.ok ? {} : { error: firstIssue(r as unknown as Args) }) };
239
265
  }
266
+ case "proposals": {
267
+ const vault = vaultOf(args);
268
+ const state = PROPOSAL_STATES.includes(String(args.state)) ? String(args.state) : "pending";
269
+ if (!vault) return { vault: null, state, page: null, selected: null, ...(str(args.vault) ? { error: `unknown vault ${str(args.vault)}; pick a registered vault from Overview` } : {}) };
270
+ // The console owns the numeric `after`, so the proposal page cursor travels as `page`.
271
+ const list = await readTool("vmem_proposal_list", args, { vault: vault.id, state, after: str(args.page) });
272
+ const id = str(args.id);
273
+ const shown = id ? await readTool("vmem_proposal_show", args, { vault: vault.id, id }) : undefined;
274
+ const error = "error" in list ? list.error : shown && "error" in shown ? shown.error : undefined;
275
+ return { vault: vault.id, state, page: "result" in list ? list.result : null, selected: shown && "result" in shown ? shown.result : null, ...(error ? { error } : {}) };
276
+ }
277
+ case "assertions": {
278
+ const vault = vaultOf(args);
279
+ if (!vault) return { vault: null, result: null, warnings: [], ...(str(args.vault) ? { error: `unknown vault ${str(args.vault)}; pick a registered vault from Overview` } : {}) };
280
+ const r = await readTool("vmem_assertions", args, { vault: vault.id });
281
+ const result = "result" in r ? r.result : null;
282
+ return { vault: vault.id, result, warnings: assertionCoverageWarnings(result?.coverage as AssertionsReadResult["coverage"] | undefined), ...("error" in r ? { error: r.error } : {}) };
283
+ }
284
+ case "history": {
285
+ const vault = vaultOf(args), path = str(args.path), from = str(args.from), to = str(args.to);
286
+ if (!vault) return { vault: null, path: path ?? null, history: null, changes: null, ...(str(args.vault) ? { error: `unknown vault ${str(args.vault)}; pick a registered vault from Overview` } : {}) };
287
+ if ((from === undefined) !== (to === undefined)) return { vault: vault.id, path: path ?? null, history: null, changes: null, error: "changes need both from and to commit ids; pick two revisions from the history list" };
288
+ const history = path ? await readTool("vmem_history", args, { vault: vault.id, path }) : undefined;
289
+ const changes = from && to ? await readTool("vmem_changes", args, { vault: vault.id, from, to, cursor: str(args.changesCursor) }) : undefined;
290
+ const error = history && "error" in history ? history.error : changes && "error" in changes ? changes.error : undefined;
291
+ return { vault: vault.id, path: path ?? null, history: history && "result" in history ? history.result : null, changes: changes && "result" in changes ? changes.result : null, ...(error ? { error } : {}) };
292
+ }
240
293
  default: return { error: `unknown panel ${input.panel}` };
241
294
  }
242
295
  },
243
296
  async action(input) {
244
297
  const args = input as Args, confirmed = input.confirmed === true, fingerprint = str(input.fingerprint);
245
298
  switch (input.action) {
299
+ case "settings": {
300
+ const vault = vaultOf(args);
301
+ if (!vault) return { ok: false, error: "settings: no selected vault; select a registered vault" };
302
+ try {
303
+ const changes = args.changes as import("../registry.ts").SettingsChanges;
304
+ const preview = changeSettings(home, { vault: vault.id, changes });
305
+ if (!confirmed || fingerprint !== preview.fingerprint) return { ok: false, needsConfirm: true, fingerprint: preview.fingerprint, verb: "Change settings", preview: Object.entries(preview.changes).map(([key, value]) => `${key}: ${JSON.stringify(value)}`), changes: [{ op: "modify", target: "vmem.config.json" }] };
306
+ changeSettings(home, { vault: vault.id, changes, confirm: true, fingerprint });
307
+ return { ok: true, message: "Settings updated; restart the console and MCP server to apply the default vault and permission changes" };
308
+ } catch (error) { return { ok: false, error: error instanceof Error ? error.message : "settings: change failed; inspect the configuration and retry" }; }
309
+ }
246
310
  case "delete": {
247
311
  const path = str(args.path) ?? str(args.id);
248
312
  if (!path) return { ok: false, error: "path is required" };
@@ -260,7 +324,7 @@ export const plugin: ConsolePlugin = {
260
324
  case "promote": {
261
325
  const path = str(args.path), to = str(args.to);
262
326
  if (!path || !to) return { ok: false, error: "path and to are required" };
263
- if (vaultOf(args)?.id !== mcp.defaultVault) return { ok: false, error: `promotion to an org vault reads from ${mcp.defaultVault}; open the note there` };
327
+ if (vaultOf(args)?.id !== promotionSource?.id || !promotionSource) return { ok: false, error: promotionSource ? `promotion to an org vault reads from ${promotionSource.id}; open the note there` : "promotion needs a personal vault; register one with vmem vaults add" };
264
328
  return twoStep("vmem_promote", forward("vmem_promote", args), confirmed, fingerprint, p => {
265
329
  const screen = rec(p.screen), dropped = Array.isArray(p.droppedLinks) ? p.droppedLinks as string[] : [];
266
330
  const target = String(p.target ?? `${to}:${path}`);
@@ -296,6 +360,30 @@ export const plugin: ConsolePlugin = {
296
360
  warnings: dupes.length ? [`possible duplicates: ${dupes.slice(0, 5).join(", ")}`] : [] };
297
361
  });
298
362
  }
363
+ case "proposal-apply":
364
+ case "proposal-reject": {
365
+ const id = str(args.id), reason = str(args.reason), apply = input.action === "proposal-apply";
366
+ if (!id) return { ok: false, error: "a proposal id is required; select a proposal in the Proposals panel" };
367
+ if (!apply && !reason?.trim()) return { ok: false, error: "rejection needs a reason; enter one and reject again" };
368
+ const tool = apply ? "vmem_proposal_apply" : "vmem_proposal_reject";
369
+ const checked = forward(tool, args, { id, ...(apply ? {} : { reason }) });
370
+ if (typeof checked === "string") return { ok: false, error: `${checked}; ${apply ? "select the proposal again from the Proposals panel" : "shorten the reason to at most 4096 bytes and reject again"}` };
371
+ try {
372
+ if (apply) return await twoStep(tool, checked, confirmed, fingerprint, p => ({ verb: "Apply proposal", preview: [`apply proposal ${id}`], changes: changesOf(p), warnings: (Array.isArray(p.issues) ? p.issues as { message?: string }[] : []).map(i => String(i.message ?? "")).filter(Boolean) }));
373
+ // Rejection answers `rejected`, not `applied`, so its confirm step reads that receipt field itself.
374
+ if (typeof checked === "string") return { ok: false, error: checked };
375
+ const preview = await call(tool, checked);
376
+ if (typeof preview.fingerprint !== "string") return { ok: false, error: firstIssue(preview) };
377
+ if (!confirmed || fingerprint !== preview.fingerprint)
378
+ return { ok: false, needsConfirm: true, fingerprint: preview.fingerprint, verb: "Reject proposal", preview: [`reject proposal ${id}`, `reason: ${String(preview.reason ?? reason)}`], changes: [{ op: "modify", target: `proposal ${id}`, note: "state → rejected; no note or log changes" }] };
379
+ const done = await call(tool, { ...checked, confirm: true, fingerprint });
380
+ if (done.rejected === true) { revision.invalidate(); inbox.invalidate(); return done.ok === true ? { ok: true, message: "Reject proposal: done" } : { ok: true, message: `Reject proposal: recorded, but ${firstIssue(done)}` }; }
381
+ return { ok: false, error: firstIssue(done) };
382
+ } catch (error) {
383
+ // The provider refuses by throwing (no longer pending, apply_unknown, binding drift); its message names the next step.
384
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
385
+ }
386
+ }
299
387
  default: return { ok: false, error: `unknown action ${input.action}` };
300
388
  }
301
389
  },
@@ -304,3 +392,5 @@ export const plugin: ConsolePlugin = {
304
392
  };
305
393
 
306
394
  export default plugin;
395
+ export type { ProposalState, ProposalsSnapshot, AssertionsSnapshot, HistorySnapshot, CoverageWarning } from "./panel-types.ts";
396
+ export { assertionCoverageWarnings } from "./panel-types.ts";