@staix/vault-mem 0.3.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +45 -20
  3. package/bin/vmem.js +9 -3
  4. package/package.json +2 -2
  5. package/src/analysis-commands.ts +22 -13
  6. package/src/analysis-input.ts +2 -2
  7. package/src/analysis-types.ts +2 -0
  8. package/src/cli-output.ts +140 -0
  9. package/src/cli.ts +91 -45
  10. package/src/commands-table.ts +85 -43
  11. package/src/config.ts +22 -3
  12. package/src/links.ts +2 -0
  13. package/src/log-commands.ts +10 -5
  14. package/src/log-format.ts +3 -0
  15. package/src/log-types.ts +5 -1
  16. package/src/mcp-spec.ts +10 -4
  17. package/src/mcp-vault.ts +27 -15
  18. package/src/org-commands.ts +5 -3
  19. package/src/org-promote.ts +3 -0
  20. package/src/promote-command.ts +6 -4
  21. package/src/read-commands.ts +12 -2
  22. package/src/read-output.ts +99 -0
  23. package/src/registry.ts +3 -2
  24. package/src/setup.ts +58 -12
  25. package/src/skills-mine.ts +3 -2
  26. package/src/spec-git.ts +7 -4
  27. package/src/spec-output.ts +119 -0
  28. package/src/sync.ts +62 -18
  29. package/src/text-output.ts +120 -0
  30. package/src/ui/panel.css +1 -5
  31. package/src/ui/panel.js +60 -70
  32. package/src/ui/plugin.ts +33 -2
  33. package/src/vault-files.ts +74 -0
  34. package/src/vault-graph.ts +21 -2
  35. package/src/vault-index.ts +121 -19
  36. package/src/vault-lint.ts +8 -2
  37. package/src/vault-log.ts +109 -1
  38. package/src/vault-stats.ts +50 -0
  39. package/src/workspace-graph.ts +9 -1
  40. package/src/write-commands.ts +32 -9
  41. package/src/write-operations.ts +48 -8
  42. package/src/write-output.ts +151 -0
  43. package/src/write-types.ts +3 -1
  44. package/src/write-validation.ts +30 -8
  45. package/src/writer.ts +19 -7
package/src/ui/panel.js CHANGED
@@ -1,31 +1,13 @@
1
1
  // vmem console panels (acon api 1). Runs under the shell's strict CSP: data is rendered as text only.
2
- const h = (tag, props = {}, ...kids) => {
3
- const el = document.createElement(tag);
4
- for (const [k, v] of Object.entries(props)) {
5
- if (v === undefined || v === null || v === false) continue;
6
- if (k === "text") el.textContent = String(v);
7
- else if (k.startsWith("on")) el.addEventListener(k.slice(2), v);
8
- else el.setAttribute(k, v === true ? "" : String(v));
9
- }
10
- el.append(...kids.flat().filter((k) => k !== null && k !== undefined && k !== false));
11
- return el;
12
- };
13
- const empty = (title, hint) => h("div", { class: "empty" }, h("strong", { text: title }), hint ? h("span", { text: hint }) : null);
14
- const err = (text) => h("p", { class: "notice", role: "alert", text });
15
- const rows = (items, row) => (items.length ? h("ul", { class: "rows" }, items.map(row)) : null);
16
- const row = (title, sub, onOpen, ...verbs) => h("li", { class: "row" },
17
- h("button", { type: "button", class: "row-main", onclick: onOpen },
18
- h("span", { class: "row-text" }, h("span", { class: "row-title", text: title }), sub ? h("span", { class: "row-sub", text: sub }) : null)),
19
- verbs.length ? h("span", { class: "row-verbs" }, verbs) : null);
20
- const btn = (label, onclick, cls = "btn") => h("button", { type: "button", class: cls, onclick, text: label });
21
- const chip = (text, tone) => h("span", { class: `chip${tone ? ` ${tone}` : ""}`, text });
22
-
23
2
  export default (host) => {
3
+ // Every element comes from the console panel kit (host.ui); this file defines no DOM helper of its own.
4
+ const ui = host.ui, h = ui.h;
24
5
  const root = h("div", { class: "vmem" });
25
6
  host.mount.append(root);
26
7
  let panel = "overview", params = {};
27
8
  const go = (p, extra = {}) => host.navigate(host.tool, p, { ...(params.vault ? { vault: params.vault } : {}), ...extra });
28
9
  const openNote = (path) => go("note", { path });
10
+ const vaultParam = () => (params.vault ? { vault: params.vault } : {});
29
11
 
30
12
  const searchForm = (q) => {
31
13
  const input = h("input", { type: "search", name: "q", value: q ?? "", placeholder: "Search notes", "aria-label": "Search notes", class: "vmem-input" });
@@ -36,83 +18,91 @@ export default (host) => {
36
18
  const views = {
37
19
  overview(s) {
38
20
  const vaults = s.status?.vaults ?? [];
39
- if (!vaults.length) return [empty("No vault registered", "Run `vmem vaults add <id> <path>` to register one.")];
21
+ if (!vaults.length) return [ui.empty("No vault registered", "Run `vmem vaults add <id> <path>` to register one.")];
40
22
  return [
41
23
  searchForm(""),
42
- h("div", { class: "cards" },
24
+ h("div", { class: "vmem-cards" },
43
25
  h("section", { class: "card" }, h("h2", { text: "Vaults" }),
44
- rows(vaults, (v) => row(v.id, `${v.kind} · write ${v.write}${v.health && v.health !== "ok" ? ` · ${v.health}` : ""}`, () => go("overview", { vault: v.id }), v.id === s.vault ? chip("shown", "accent") : null))),
26
+ ui.rows(vaults, (v) => ui.row({ title: v.id, sub: `${v.kind} · write ${v.write}${v.health && v.health !== "ok" ? ` · ${v.health}` : ""}`, onOpen: () => go("overview", { vault: v.id }), ...(v.id === s.vault ? { chip: { text: "shown", tone: "neutral" } } : {}) }))),
45
27
  h("section", { class: "card" }, h("h2", { text: `${s.noteCount ?? 0}${s.noteCountCapped ? "+" : ""} notes · maps` }),
46
- rows((s.mocs ?? []).slice(0, 8), (m) => row(m.title || m.path, `${m.count} links`, () => openNote(m.path))) ?? empty("No maps yet")),
28
+ ui.rows((s.mocs ?? []).slice(0, 8), (m) => ui.row({ title: m.title || m.path, sub: `${m.count} links`, onOpen: () => openNote(m.path) })) ?? ui.empty("No maps yet")),
47
29
  h("section", { class: "card" }, h("h2", { text: "Recent log" }),
48
- rows(s.log ?? [], (r) => row(r.raw ?? `${r.type} ${r.source}${r.dest ? ` → ${r.dest}` : ""}`, r.raw ? "" : `${r.at} · ${r.project}${r.agent ? " · agent" : ""}`, () => go("log"))) ?? empty("Log is empty"))),
30
+ ui.rows(s.log ?? [], (r) => ui.row({ title: r.raw ?? `${r.type} ${r.source}${r.dest ? ` → ${r.dest}` : ""}`, ...(r.raw ? {} : { sub: `${r.at} · ${r.project}${r.agent ? " · agent" : ""}` }), onOpen: () => go("log") })) ?? ui.empty("Log is empty"))),
49
31
  ];
50
32
  },
51
33
  notes(s) {
52
34
  const list = s.notes ?? [];
53
- return [searchForm(s.q), s.error ? err(s.error) : null,
54
- rows(list, (n) => row(n.title || n.path, [n.type, n.domain, n.description].filter(Boolean).join(" · "), () => openNote(n.path)))
55
- ?? empty(s.q ? "No notes match" : "No notes", s.q ? "Try fewer words; terms are combined with AND." : null)];
35
+ return [searchForm(s.q), s.error ? ui.notice(s.error, "err") : null,
36
+ ui.rows(list, (n) => ui.row({ title: n.title || n.path, sub: [n.type, n.domain, n.description].filter(Boolean).join(" · "), onOpen: () => openNote(n.path) }))
37
+ ?? ui.empty(s.q ? "No notes match" : "No notes", s.q ? "Try fewer words; terms are combined with AND." : undefined)];
56
38
  },
57
39
  note(s) {
58
- if (s.error) return [err(s.error)];
40
+ if (s.error) return [ui.notice(s.error, "err")];
59
41
  const n = s.note;
60
- if (!n) return [empty("No note selected", "Open a note from Search or the palette.")];
42
+ if (!n) return [ui.empty("No note selected", "Open a note from Search or the palette.")];
61
43
  const fm = n.frontmatter ?? {};
62
- const title = fm.title || n.path;
63
44
  const moveInput = h("input", { type: "text", name: "to", class: "vmem-input", "aria-label": "New stem", placeholder: "new-stem" });
64
45
  const orgs = s.orgVaults ?? [];
65
- const orgSelect = orgs.length ? h("select", { name: "org", class: "vmem-input", "aria-label": "Org vault" }, orgs.map((o) => h("option", { value: o, text: o }))) : null;
46
+ const orgSelect = orgs.length ? h("select", { name: "org", class: "vmem-input", "aria-label": "Org vault" }, ...orgs.map((o) => h("option", { value: o, text: o }))) : null;
66
47
  const out = s.links?.out ?? [], back = s.links?.in ?? [], dead = s.links?.dead ?? [];
67
- return [
68
- h("header", { class: "vmem-head" }, chip(fm.type || "note"), h("h2", { text: title }), fm.status ? chip(fm.status, fm.status === "superseded" ? "warn" : null) : null),
69
- fm.description ? h("p", { class: "vmem-sub", text: fm.description }) : null,
70
- h("div", { class: "vmem-bar" },
71
- btn("Delete…", () => host.action({ action: "delete", path: n.path, ...(params.vault ? { vault: params.vault } : {}) }), "btn danger"),
72
- h("form", { class: "vmem-inline", onsubmit: (e) => { e.preventDefault(); if (moveInput.value.trim()) host.action({ action: "move", from: n.path, to: moveInput.value.trim(), ...(params.vault ? { vault: params.vault } : {}) }); } },
73
- moveInput, h("button", { type: "submit", class: "btn", text: "Move…" })),
74
- orgSelect ? (() => {
75
- const topics = h("input", { type: "text", name: "orgTopics", class: "vmem-input", "aria-label": "Org topics (comma separated, optional)", placeholder: "org topics (optional)" });
76
- const again = h("input", { type: "checkbox", name: "again", "aria-label": "Promote again to another org" });
77
- return h("form", { class: "vmem-inline", onsubmit: (e) => { e.preventDefault(); host.action({ action: "promote", path: n.path, to: orgSelect.value, ...(topics.value.trim() ? { topics: topics.value.trim() } : {}), ...(again.checked ? { again: true } : {}) }); } },
78
- orgSelect, topics, h("label", { class: "vmem-check" }, again, h("span", { text: "again" })), h("button", { type: "submit", class: "btn", text: "Promote to org…" }));
79
- })() : null),
80
- h("details", { open: true }, h("summary", { text: "Body" }), h("pre", { class: "vmem-body", text: n.body ?? "" }), n.truncated ? err("Truncated; open the file for the rest.") : null),
81
- h("details", {}, h("summary", { text: `Links (${out.length} out, ${back.length} in${dead.length ? `, ${dead.length} dead` : ""})` }),
82
- rows([...out.map((l) => ({ path: l.resolved, label: `→ ${l.resolved}` })), ...back.map((l) => ({ path: l.source, label: `← ${l.source}` })), ...dead.map((l) => ({ label: `✕ ${l.target}` }))],
83
- (l) => row(l.label, "", () => l.path && openNote(l.path))) ?? empty("No links")),
84
- h("p", { class: "vmem-mono", text: `${n.path} · sha256 ${String(n.sha256 ?? "").slice(0, 12)}` }),
48
+ const links = [...out.map((l) => ({ path: l.resolved, label: `→ ${l.resolved}` })), ...back.map((l) => ({ path: l.source, label: `← ${l.source}` })), ...dead.map((l) => ({ label: `✕ ${l.target}` }))];
49
+ const actions = [
50
+ ui.button("Delete…", () => host.action({ action: "delete", path: n.path, ...vaultParam() }), { tone: "danger" }),
51
+ h("form", { class: "vmem-inline", onsubmit: (e) => { e.preventDefault(); if (moveInput.value.trim()) host.action({ action: "move", from: n.path, to: moveInput.value.trim(), ...vaultParam() }); } },
52
+ moveInput, h("button", { type: "submit", class: "btn", text: "Move…" })),
85
53
  ];
54
+ if (orgSelect) {
55
+ const topics = h("input", { type: "text", name: "orgTopics", class: "vmem-input", "aria-label": "Org topics (comma separated, optional)", placeholder: "org topics (optional)" });
56
+ const again = h("input", { type: "checkbox", name: "again", "aria-label": "Promote again to another org" });
57
+ actions.push(h("form", { class: "vmem-inline", onsubmit: (e) => { e.preventDefault(); host.action({ action: "promote", path: n.path, to: orgSelect.value, ...(topics.value.trim() ? { topics: topics.value.trim() } : {}), ...(again.checked ? { again: true } : {}) }); } },
58
+ orgSelect, topics, h("label", { class: "vmem-check" }, again, h("span", { text: "again" })), h("button", { type: "submit", class: "btn", text: "Promote to org…" })));
59
+ }
60
+ return [ui.detail({
61
+ kind: fm.type || "note", title: fm.title || n.path,
62
+ ...(fm.status ? { state: { text: fm.status, ...(fm.status === "superseded" ? { tone: "warn" } : {}) } } : {}),
63
+ actions, ...(fm.description ? { summary: fm.description } : {}),
64
+ sections: [
65
+ { title: "Body", open: true, body: h("div", {}, h("pre", { class: "vmem-body", text: n.body ?? "" }), n.truncated ? ui.notice("Truncated; open the file for the rest.", "warn") : null) },
66
+ { title: `Links (${out.length} out, ${back.length} in${dead.length ? `, ${dead.length} dead` : ""})`,
67
+ body: ui.rows(links, (l) => ui.row({ title: l.label, ...(l.path ? { onOpen: () => openNote(l.path) } : {}) })) ?? ui.empty("No links") },
68
+ ],
69
+ footer: [`${n.path} · sha256 ${String(n.sha256 ?? "").slice(0, 12)}`],
70
+ })];
86
71
  },
87
72
  promote(s) {
88
73
  const projects = s.projects ?? [];
89
74
  const all = projects.flatMap((p) => p.candidates);
90
75
  const picked = all.find((c) => c.id === s.selected);
91
- const field = (name, label, required) => h("input", { type: "text", name, class: "vmem-input", "aria-label": label, placeholder: label, required });
92
- const form = picked ? (() => {
93
- const domain = field("domain", "domain (required)", true), topics = field("topics", "topics, comma separated (required)", true), type = field("type", "type (optional)"), description = field("description", "description (optional)"), stem = field("stem", "file stem (needed when the title has no ASCII letters)");
94
- return h("form", { class: "card vmem-form", onsubmit: (e) => {
95
- e.preventDefault();
96
- const meta = Object.fromEntries([["domain", domain], ["topics", topics], ["type", type], ["description", description], ["stem", stem]].filter(([, el]) => el.value.trim()).map(([k, el]) => [k, el.value.trim()]));
97
- host.action({ action: "promote-from-amem", id: picked.id, project: picked.project, ...meta, ...(params.vault ? { vault: params.vault } : {}) });
98
- } }, h("h2", { text: `Promote: ${picked.title || picked.kind}` }), domain, topics, type, description, stem, h("button", { type: "submit", class: "btn primary", text: "Preview promotion…" }));
99
- })() : null;
100
- return [s.unavailable ? err(s.unavailable) : null, form,
101
- rows(all, (c) => row(c.title || c.kind, `${c.kind} · ${c.project} · ${new Date(c.at).toLocaleString()}`, () => go("promote", { id: c.id, project: c.project }),
102
- s.selected === c.id ? chip("selected", "accent") : btn("Select", () => go("promote", { id: c.id, project: c.project }))))
103
- ?? empty("No promotion candidates", "Durable agent memories appear here when agent-mem marks them for the vault.")];
76
+ const form = picked ? h("section", { class: "card vmem-form" }, h("h2", { text: `Promote: ${picked.title || picked.kind}` }),
77
+ ui.form([
78
+ { name: "domain", label: "domain (required)", required: true },
79
+ { name: "topics", label: "topics, comma separated (required)", required: true },
80
+ { name: "type", label: "type (optional)" },
81
+ { name: "description", label: "description (optional)" },
82
+ { name: "stem", label: "file stem (needed when the title has no ASCII letters)" },
83
+ ], { label: "Preview promotion…", primary: true }, (values) => {
84
+ const meta = Object.fromEntries(Object.entries(values).map(([k, v]) => [k, v.trim()]).filter(([, v]) => v));
85
+ host.action({ action: "promote-from-amem", id: picked.id, project: picked.project, ...meta, ...vaultParam() });
86
+ })) : null;
87
+ return [s.unavailable ? ui.notice(s.unavailable, "err") : null, form,
88
+ ui.rows(all, (c) => ui.row({ title: c.title || c.kind, sub: `${c.kind} · ${c.project} · ${new Date(c.at).toLocaleString()}`, onOpen: () => go("promote", { id: c.id, project: c.project }),
89
+ ...(s.selected === c.id ? { chip: { text: "selected", tone: "neutral" } } : { verbs: [ui.button("Select", () => go("promote", { id: c.id, project: c.project }))] }) }))
90
+ ?? ui.empty("No promotion candidates", "Durable agent memories appear here when agent-mem marks them for the vault.")];
104
91
  },
105
92
  lint(s) {
106
93
  const f = s.findings ?? [];
107
94
  return [h("p", { class: "vmem-sub", text: s.summary ?? "" }),
108
- rows(f, (x) => row(x.message, `${x.code}${x.path ? ` · ${x.path}` : ""}`, () => x.path && openNote(x.path), chip(x.severity, x.severity === "error" ? "err" : "warn")))
109
- ?? empty("No lint findings", "The vault passes every check.")];
95
+ ui.rows(f, (x) => ui.row({ title: x.message, sub: `${x.code}${x.path ? ` · ${x.path}` : ""}`, ...(x.path ? { onOpen: () => openNote(x.path) } : {}), chip: { text: x.severity, tone: x.severity === "error" ? "err" : "warn" } }))
96
+ ?? ui.empty("No lint findings", "The vault passes every check.")];
110
97
  },
111
98
  log(s) {
112
99
  const r = s.rows ?? [];
113
- return [s.error ? err(s.error) : null,
114
- rows(r, (x) => row(x.raw ?? `${x.type} ${x.source}${x.dest ? ` → ${x.dest}` : ""}`, x.raw ? "unparsed line" : `${x.at} · ${x.project} · ${x.note}${x.agent ? " · agent" : ""}`,
115
- () => { const p = x.dest ?? x.source; if (typeof p === "string" && p.startsWith("notes/")) openNote(p); })) ?? empty("Log is empty")];
100
+ return [s.error ? ui.notice(s.error, "err") : null,
101
+ ui.rows(r, (x) => {
102
+ const p = x.dest ?? x.source;
103
+ return ui.row({ title: x.raw ?? `${x.type} ${x.source}${x.dest ? ` → ${x.dest}` : ""}`, sub: x.raw ? "unparsed line" : `${x.at} · ${x.project} · ${x.note}${x.agent ? " · agent" : ""}`,
104
+ ...(typeof p === "string" && p.startsWith("notes/") ? { onOpen: () => openNote(p) } : {}) });
105
+ }) ?? ui.empty("Log is empty")];
116
106
  },
117
107
  };
118
108
 
@@ -125,7 +115,7 @@ export default (host) => {
125
115
  // Rule: every form control in this file has a stable name, or its state is lost on the next poll.
126
116
  const values = new Map([...root.querySelectorAll("input[name], select[name]")].map((el) => [el.name, el.type === "checkbox" ? el.checked : el.value]));
127
117
  const focused = root.contains(document.activeElement) ? document.activeElement.getAttribute("name") : null;
128
- root.replaceChildren(...(views[panel]?.(snap) ?? [empty("Unknown panel")]).filter(Boolean));
118
+ root.replaceChildren(...(views[panel]?.(snap) ?? [ui.empty("Unknown panel")]).filter(Boolean));
129
119
  for (const el of root.querySelectorAll("input[name], select[name]")) if (values.has(el.name)) el[el.type === "checkbox" ? "checked" : "value"] = values.get(el.name);
130
120
  if (focused) root.querySelector(`[name="${focused}"]`)?.focus();
131
121
  });
package/src/ui/plugin.ts CHANGED
@@ -10,7 +10,10 @@ import { createVaultMcp } from "../mcp-vault.ts";
10
10
  import { validArguments } from "../mcp.ts";
11
11
  import { listPromotionCandidates } from "../promote.ts";
12
12
  import { loadRegistry } from "../registry.ts";
13
+ import { localSyncPending, STAGED_DESCRIPTION } from "../sync.ts";
14
+ import { isDenied } from "../platform.ts";
13
15
  import { lintVault } from "../vault-lint.ts";
16
+ import { readLogSince } from "../vault-log.ts";
14
17
  import type { LintCode } from "../analysis-types.ts";
15
18
 
16
19
  const asset = (name: string) => readFileSync(new URL(name, import.meta.url), "utf8");
@@ -130,6 +133,22 @@ export const plugin: ConsolePlugin = {
130
133
  lintCache.set(id, { at: Date.now(), report });
131
134
  return report;
132
135
  };
136
+ // Like lint, local Git state refreshes at most once per minute, including failures.
137
+ const syncCache = new Map<string, { at: number; pending: ReturnType<typeof localSyncPending> | null }>();
138
+ const syncPending = (id: string) => {
139
+ const hit = syncCache.get(id);
140
+ if (hit && Date.now() - hit.at < CACHE_MS) return hit.pending;
141
+ let pending: ReturnType<typeof localSyncPending> | null = null;
142
+ try {
143
+ const config = loadRegistry(home), spec = config.vaults.find(v => v.id === id);
144
+ const startup = mcp.vaults.find(v => v.id === id);
145
+ if (!spec || JSON.stringify(spec) !== JSON.stringify(startup)) throw new Error("vault binding changed; restart the console provider");
146
+ if (isDenied(spec.path, config.denyPaths)) throw new Error("vault path is denied; check its path policy in System");
147
+ pending = localSyncPending(spec.path);
148
+ } catch (error) { ctx.log(`vmem: sync pending ${id} failed: ${error instanceof Error ? error.message : String(error)}`); }
149
+ syncCache.set(id, { at: Date.now(), pending });
150
+ return pending;
151
+ };
133
152
  const projectOf = new Map<string, string>();
134
153
  const candidates = async () => {
135
154
  try {
@@ -161,6 +180,16 @@ export const plugin: ConsolePlugin = {
161
180
  if (stale.length) items.push({ id: `stale:${v.id}`, group: "alert", kind: "lint", title: `Graph report is stale in ${v.id}`, detail: stale[0]!, at: since(`stale:${v.id}`),
162
181
  chip: { text: "stale", tone: "warn" }, verbs: [], link: { panel: "lint", params: { vault: v.id } } });
163
182
  }
183
+ for (const v of mcp.vaults.filter(x => x.kind === "org")) {
184
+ const pending = syncPending(v.id);
185
+ if (!pending) continue;
186
+ const count = pending.changed + pending.ahead;
187
+ if (count > 0) items.push({ id: `sync:${v.id}`, group: "alert", kind: "sync", title: `${count} unsynced change${count === 1 ? "" : "s"} in ${v.id}`,
188
+ detail: [`${pending.changed} uncommitted path${pending.changed === 1 ? "" : "s"} to sync`,
189
+ ...(pending.ignored ? [`${pending.ignored} other path${pending.ignored === 1 ? "" : "s"} outside ${STAGED_DESCRIPTION} not counted`] : []),
190
+ ...(pending.upstream ? [`${pending.ahead} local commit${pending.ahead === 1 ? "" : "s"} ahead of upstream`] : [])].join("; "), at: since(`sync:${v.id}`),
191
+ chip: { text: "sync pending", tone: "warn" }, verbs: [], link: { panel: "overview", params: { vault: v.id } } });
192
+ }
164
193
  for (const id of firstSeen.keys()) if (!items.some(i => i.id === id)) firstSeen.delete(id);
165
194
  return items;
166
195
  }
@@ -227,8 +256,10 @@ export const plugin: ConsolePlugin = {
227
256
  case "log": {
228
257
  const vault = vaultOf(args);
229
258
  if (!vault) return { rows: [] };
230
- const r = await call("vmem_log_tail", { vault: vault.id, n: 100, ...(str(args.type) ? { type: args.type } : {}) });
231
- return { vault: vault.id, rows: (Array.isArray(r.lines) ? r.lines as string[] : []).map(parseLogLine).reverse(), ...(r.ok === false ? { error: firstIssue(r) } : {}) };
259
+ // `since` is the `cursor` of the previous answer: only newer rows come back, or the latest with `reset: true`.
260
+ // The console owns the numeric `after` (its server refuses any other type), so the log cursor travels as `since`.
261
+ const r = readLogSince(home, { vault: vault.id, limit: 100, ...(str(args.type) ? { type: str(args.type) } : {}), ...(str(args.since) ? { after: str(args.since) } : {}) });
262
+ 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) }) };
232
263
  }
233
264
  default: return { error: `unknown panel ${input.panel}` };
234
265
  }
@@ -0,0 +1,74 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readdirSync, readSync, realpathSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { join } from "node:path";
4
+ import type { VaultSpec } from "./config.ts";
5
+ import { isDenied } from "./platform.ts";
6
+ import { MAX_NOTE_BYTES, MAX_READ_BYTES, MAX_RESULTS, readPage } from "./vault-index.ts";
7
+
8
+ /** Vault paths readable outside notes/: these directories and root files. Reads never lock, index or write. */
9
+ export const FILE_ROOTS = ["ops/", "reports/", "self/", "templates/", "AGENTS.md", "README.md"] as const;
10
+ const DIRS = new Set(["ops", "reports", "self", "templates"]), FILES = new Set(["AGENTS.md", "README.md"]);
11
+ const ROOTS = "ops/, reports/, self/, templates/, AGENTS.md or README.md";
12
+ function fail(message: string, code = "V04"): never { throw Object.assign(new Error(message), { code }); }
13
+
14
+ /** Checks `path` against the allowed roots and returns its location; every component must be a plain directory or file. */
15
+ function locate(vault: VaultSpec, denyPaths: string[], path: string, kind: "file" | "dir"): string {
16
+ const parts = path.split("/");
17
+ if (path.startsWith("/") || path.includes("\\") || path.includes("\0") || parts.some(part => !part || part === "." || part === ".."))
18
+ fail(`path: absolute, empty, . or .. segments are refused; pass a vault-relative path under ${ROOTS}`);
19
+ if (parts.some(part => part.startsWith("."))) fail(`path: dot paths such as .git are not readable through vmem; read a path under ${ROOTS}`);
20
+ if (parts[0] === "notes") fail("path: notes/ is read with vmem_read or vmem_read_many and listed with vmem_list");
21
+ if (parts[0] === "log") fail("path: the vault log is read with vmem_log_tail");
22
+ if (!(DIRS.has(parts[0]!) || (kind === "file" && parts.length === 1 && FILES.has(parts[0]!))))
23
+ fail(`path: outside the readable roots; use a path under ${ROOTS}`);
24
+ const root = realpathSync(vault.path);
25
+ if (root !== vault.path) fail(`vault ${vault.id}: registered path changed; re-register it with vmem vaults add and restart the MCP server`);
26
+ if (isDenied(join(root, path), denyPaths)) fail("path: denied by the built-in secret rules or registry denyPaths; nothing read", "V06");
27
+ let current = root;
28
+ for (let i = 0; i < parts.length; i++) {
29
+ current = join(current, parts[i]!);
30
+ let stat: ReturnType<typeof lstatSync>;
31
+ try { stat = lstatSync(current); }
32
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") fail(`path: not found; list the parent directory with vmem_list_files`); throw error; }
33
+ // ponytail: every link is refused, not only links leaving the vault; matches the writer's plain-path rule.
34
+ if (stat.isSymbolicLink()) fail("path: symlinked components are refused because a link can leave the vault; read the link target's own vault path");
35
+ const last = i === parts.length - 1, wantDir = !last || kind === "dir";
36
+ if (wantDir ? !stat.isDirectory() : !stat.isFile()) fail(wantDir ? "path: not a directory; list its parent with vmem_list_files" : "path: not a regular file; list it with vmem_list_files");
37
+ }
38
+ return current;
39
+ }
40
+
41
+ /** Bounded UTF-8 read with vmem_read's limits and paging: maxBytes 1..64 KiB, files up to 2 MiB, byte offsets on character boundaries. */
42
+ export function readVaultFile(vault: VaultSpec, denyPaths: string[], path: string, maxBytes = 16384, offset?: number) {
43
+ if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_READ_BYTES) fail(`max-bytes: expected integer 1..${MAX_READ_BYTES}`);
44
+ if (offset !== undefined && (!Number.isSafeInteger(offset) || offset < 0 || offset > MAX_NOTE_BYTES)) fail(`offset: expected integer 0..${MAX_NOTE_BYTES}`);
45
+ const fd = openSync(locate(vault, denyPaths, path, "file"), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
46
+ let bytes: Buffer;
47
+ try {
48
+ const before = fstatSync(fd);
49
+ if (!before.isFile()) fail("path: not a regular file; list it with vmem_list_files");
50
+ if (before.size > MAX_NOTE_BYTES) fail(`file: exceeds the ${MAX_NOTE_BYTES}-byte read bound; read it outside vmem or split it`, "V09");
51
+ const buffer = Buffer.alloc(before.size + 1); let size = 0;
52
+ while (size < buffer.length) { const count = readSync(fd, buffer, size, buffer.length - size, null); if (!count) break; size += count; }
53
+ const after = fstatSync(fd);
54
+ if (size !== before.size || after.size !== before.size || after.mtimeMs !== before.mtimeMs) fail("file: changed during read; retry once it is stable", "V09");
55
+ bytes = buffer.subarray(0, size);
56
+ } finally { closeSync(fd); }
57
+ const text = bytes.toString("utf8");
58
+ if (!Buffer.from(text).equals(bytes)) fail("file: not valid UTF-8 text; vmem_read_file reads text files only", "V01");
59
+ const start = offset ?? 0, page = readPage(bytes.subarray(start, start + maxBytes + 4), maxBytes, start, bytes.length);
60
+ return { path, sha256: createHash("sha256").update(bytes).digest("hex"), truncated: page.truncated, body: page.content,
61
+ ...(offset !== undefined ? { offset } : {}), ...(page.nextOffset !== undefined ? { nextOffset: page.nextOffset } : {}) };
62
+ }
63
+
64
+ /** One directory level under an allowed root, sorted by name; dot, linked, special and denied entries are left out. */
65
+ export function listVaultFiles(vault: VaultSpec, denyPaths: string[], dir: string) {
66
+ const clean = dir.replace(/\/$/, ""), location = locate(vault, denyPaths, clean, "dir");
67
+ // ponytail: readdirSync loads the whole directory before the 500-entry cut; stream with opendir if vault dirs grow huge.
68
+ const entries = readdirSync(location, { withFileTypes: true })
69
+ .filter(entry => !entry.name.startsWith(".") && (entry.isFile() || entry.isDirectory()) && !isDenied(join(location, entry.name), denyPaths))
70
+ .sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
71
+ return { dir: clean, truncated: entries.length > MAX_RESULTS, entries: entries.slice(0, MAX_RESULTS).map(entry => entry.isDirectory()
72
+ ? { name: entry.name, path: `${clean}/${entry.name}`, type: "dir" as const }
73
+ : { name: entry.name, path: `${clean}/${entry.name}`, type: "file" as const, bytes: lstatSync(join(location, entry.name)).size }) };
74
+ }
@@ -1,4 +1,6 @@
1
1
  import type { AnalysisSnapshot } from "./analysis-types.ts";
2
+ import { LINK_RELATIONS } from "./links.ts";
3
+ export { LINK_RELATIONS };
2
4
  import { AnalysisYamlUnsupported, parseAnalysisYaml, scalarText, yamlTruthy } from "./analysis-yaml.ts";
3
5
 
4
6
  export interface GraphNode {
@@ -336,6 +338,16 @@ export const codePointCompare = compare;
336
338
  export function labelCommunities(ids: readonly string[], edges: readonly (readonly [string, string])[]): Map<string, number> {
337
339
  return leidenCommunities(ids, edges).membership;
338
340
  }
341
+ /** The typed relation of a `- [[x]] (relation)` list line, or undefined for any other wiki link. */
342
+ function linkRelation(body: string, index: number, length: number): string | undefined {
343
+ // Only `- [[` can be typed; check the two characters before the link before scanning back to the line start,
344
+ // so a long line of plain links stays linear. The scan back then crosses only whitespace.
345
+ if (index < 2 || body[index - 1] !== " " || body[index - 2] !== "-") return undefined;
346
+ let start = index - 2;
347
+ while (start > 0 && body[start - 1] !== "\n") { if (!/\s/.test(body[start - 1]!)) return undefined; start--; }
348
+ const after = /^ \(([a-z-]+)\)(?::|\s*(?:\n|$))/.exec(body.slice(index + length, index + length + 40));
349
+ return after && (LINK_RELATIONS as readonly string[]).includes(after[1]!) ? after[1] : undefined;
350
+ }
339
351
  /** Pure transformation of the derived-index snapshot, preserving the reference wiki graph semantics. */
340
352
  export function buildGraph(snapshot: AnalysisSnapshot): VaultGraph {
341
353
  if (snapshot.notes.length > MAX_NODES) throw new Error(`graph: exceeds ${MAX_NODES} notes`);
@@ -354,7 +366,9 @@ export function buildGraph(snapshot: AnalysisSnapshot): VaultGraph {
354
366
  const target = match[1]!.trim().toLowerCase().replaceAll(" ", "-");
355
367
  if (!stems.has(target)) continue;
356
368
  const [source, destination] = [id, target].sort(compare) as [string, string];
357
- edges.set(JSON.stringify([source, destination]), { source, target: destination, relation: "wiki_link", confidence_tag: "EXTRACTED", confidence: 1 });
369
+ const key = JSON.stringify([source, destination]), rel = linkRelation(body, match.index, match[0].length), prior = edges.get(key);
370
+ const kept = prior?.rel ?? rel;
371
+ edges.set(key, { source, target: destination, relation: "wiki_link", ...(kept ? { rel: kept } : {}), confidence_tag: "EXTRACTED", confidence: 1 });
358
372
  if (edges.size > MAX_EDGES) throw new Error(`graph: exceeds ${MAX_EDGES} edges`);
359
373
  }
360
374
  }
@@ -365,9 +379,14 @@ export function buildGraph(snapshot: AnalysisSnapshot): VaultGraph {
365
379
  communities(graph);
366
380
  return graph;
367
381
  }
368
- export function graphNeighbors(graph: VaultGraph, start: string, hops: 1 | 2, limit: number): GraphNeighborhood {
382
+ /** An edge's link relation: its typed `rel`, else the edge relation (`wiki_link` for a plain link). */
383
+ export function edgeRelation(edge: GraphEdge): string { return edge.relation === "wiki_link" ? edge.rel ?? "wiki_link" : edge.relation; }
384
+ export function graphNeighbors(graph: VaultGraph, start: string, hops: 1 | 2, limit: number, relation?: string): GraphNeighborhood {
369
385
  if (hops !== 1 && hops !== 2) throw new Error("graph neighbors: hops must be 1 or 2");
370
386
  if (!Number.isInteger(limit) || limit < 1 || limit > 500) throw new Error("graph neighbors: limit must be 1..500");
387
+ if (relation !== undefined && relation !== "wiki_link" && !(LINK_RELATIONS as readonly string[]).includes(relation))
388
+ throw new Error(`graph neighbors: unknown relation ${JSON.stringify(relation)}; use wiki_link or ${LINK_RELATIONS.join(", ")}`);
389
+ if (relation !== undefined) graph = { ...graph, edges: graph.edges.filter(edge => edgeRelation(edge) === relation) };
371
390
  const neighbors = adjacency(graph);
372
391
  if (!neighbors.has(start)) throw new Error("graph neighbors: unknown note");
373
392
  const distances = new Map([[start, 0]]), queue = [start];