@staix/vault-mem 0.5.1 → 0.7.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 (48) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +147 -23
  3. package/package.json +5 -4
  4. package/src/amem/seam.ts +15 -6
  5. package/src/analysis-commands.ts +1 -1
  6. package/src/analysis-input.ts +24 -3
  7. package/src/analysis-reports.ts +1 -1
  8. package/src/analysis-types.ts +13 -1
  9. package/src/canon-tables.ts +190 -0
  10. package/src/cli-output.ts +15 -1
  11. package/src/cli.ts +3 -1
  12. package/src/commands-table.ts +7 -2
  13. package/src/config.ts +31 -3
  14. package/src/frontmatter.ts +10 -3
  15. package/src/links.ts +13 -1
  16. package/src/mcp-spec.ts +19 -11
  17. package/src/mcp-vault.ts +20 -12
  18. package/src/mcp.ts +4 -2
  19. package/src/org-promote.ts +29 -12
  20. package/src/promote.ts +25 -13
  21. package/src/read-commands.ts +1 -2
  22. package/src/read-output.ts +7 -5
  23. package/src/registry.ts +1 -0
  24. package/src/skills-mine.ts +5 -4
  25. package/src/spec-command-table.ts +10 -1
  26. package/src/spec-commands.ts +7 -3
  27. package/src/spec-gitlinks.ts +106 -0
  28. package/src/spec-output.ts +30 -0
  29. package/src/spec-source.ts +9 -3
  30. package/src/spec-validate.ts +6 -3
  31. package/src/spec-write.ts +469 -0
  32. package/src/ui/inbox.ts +28 -10
  33. package/src/ui/panel.js +26 -5
  34. package/src/ui/plugin.ts +38 -12
  35. package/src/ui/snapshot-cache.ts +123 -0
  36. package/src/vault-brief.ts +90 -0
  37. package/src/vault-index.ts +158 -21
  38. package/src/vault-lint.ts +53 -5
  39. package/src/vault-log.ts +3 -2
  40. package/src/vault-stats.ts +110 -5
  41. package/src/write-commands.ts +4 -3
  42. package/src/write-files.ts +72 -0
  43. package/src/write-operations.ts +175 -25
  44. package/src/write-output.ts +20 -9
  45. package/src/write-types.ts +8 -1
  46. package/src/write-validation.ts +46 -17
  47. package/src/writer.ts +145 -42
  48. package/src/yaml-quoted.ts +12 -2
package/src/ui/panel.js CHANGED
@@ -84,9 +84,17 @@ export default (host) => {
84
84
  const meta = Object.fromEntries(Object.entries(values).map(([k, v]) => [k, v.trim()]).filter(([, v]) => v));
85
85
  host.action({ action: "promote-from-amem", id: picked.id, project: picked.project, ...meta, ...vaultParam() });
86
86
  })) : null;
87
+ // `reset` only says the page token was stale: the reply can land on the page holding the selected candidate.
88
+ // The returned page index decides whether an earlier page exists; an unavailable reply has none, so there a
89
+ // stale page param can still be cleared.
90
+ const pageIndex = Number(String(s.page ?? "").split(":")[1]);
91
+ const showFirst = Number.isSafeInteger(pageIndex) ? pageIndex > 0 : Boolean(params.page);
87
92
  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 }))] }) }))
93
+ s.nextPage || showFirst ? h("div", { class: "vmem-bar" },
94
+ ...(showFirst ? [ui.button("First page", () => go("promote"))] : []),
95
+ ...(s.nextPage ? [ui.button("Next page", () => go("promote", { page: s.nextPage }))] : [])) : null,
96
+ 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, page: s.page }),
97
+ ...(s.selected === c.id ? { chip: { text: "selected", tone: "neutral" } } : { verbs: [ui.button("Select", () => go("promote", { id: c.id, project: c.project, page: s.page }))] }) }))
90
98
  ?? ui.empty("No promotion candidates", "Durable agent memories appear here when agent-mem marks them for the vault.")];
91
99
  },
92
100
  lint(s) {
@@ -106,8 +114,9 @@ export default (host) => {
106
114
  },
107
115
  };
108
116
 
109
- let last = "";
110
- host.onSnapshot((snap) => {
117
+ let last = "", savedView = "", savedSnapshot;
118
+ const viewKey = () => JSON.stringify([panel, params]);
119
+ const render = (snap) => {
111
120
  const sig = JSON.stringify([panel, snap]);
112
121
  if (sig === last) return; // unchanged poll: keep focus and scroll
113
122
  last = sig;
@@ -118,9 +127,21 @@ export default (host) => {
118
127
  root.replaceChildren(...(views[panel]?.(snap) ?? [ui.empty("Unknown panel")]).filter(Boolean));
119
128
  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);
120
129
  if (focused) root.querySelector(`[name="${focused}"]`)?.focus();
130
+ };
131
+ host.onSnapshot((snap) => {
132
+ if (snap.changed === false) {
133
+ if (last === "" && savedView === viewKey() && savedSnapshot) render(savedSnapshot);
134
+ return;
135
+ }
136
+ savedView = viewKey(); savedSnapshot = snap;
137
+ render(snap);
121
138
  });
122
139
  return {
123
- show(id, p = {}) { panel = id; params = p; last = ""; root.replaceChildren(); },
140
+ show(id, p = {}) {
141
+ panel = id; params = p; last = ""; root.replaceChildren();
142
+ // Some shells suppress unchanged replies before invoking onSnapshot. Restore on show too.
143
+ if (savedView === viewKey() && savedSnapshot) render(savedSnapshot);
144
+ },
124
145
  hide() {},
125
146
  destroy() { root.remove(); },
126
147
  };
package/src/ui/plugin.ts CHANGED
@@ -10,6 +10,7 @@ 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 { createSnapshotRevision, createPromoteSnapshot, nextSnapshotCursor } from "./snapshot-cache.ts";
13
14
  import { createInboxSnapshot } from "./inbox.ts";
14
15
  import { lintVault } from "../vault-lint.ts";
15
16
  import { readLogSince } from "../vault-log.ts";
@@ -133,16 +134,18 @@ export const plugin: ConsolePlugin = {
133
134
  return report;
134
135
  };
135
136
  const projectOf = new Map<string, string>();
137
+ const revision = createSnapshotRevision(home, mcp.vaults);
136
138
  const candidates = async () => {
137
- try {
138
- const { projects } = await listPromotionCandidates({ allProjects: true, limit: 50, piiPatterns: loadRegistry(home).piiPatterns });
139
- for (const p of projects) for (const c of p.candidates) projectOf.set(c.id, c.project);
140
- return { projects };
141
- }
142
- catch (error) { ctx.log(`vmem: promotion candidates unavailable: ${error instanceof Error ? error.message : String(error)}`); return { projects: [], unavailable: "agent-mem candidates are unavailable; see System" }; }
139
+ const { projects } = await listPromotionCandidates({ allProjects: true, limit: 50, piiPatterns: loadRegistry(home).piiPatterns });
140
+ projectOf.clear();
141
+ for (const p of projects) for (const c of p.candidates) projectOf.set(c.id, c.project);
142
+ return { projects };
143
143
  };
144
144
 
145
- const inbox = createInboxSnapshot(home, mcp.vaults, ctx.log);
145
+ const promote = createPromoteSnapshot(revision.current, candidates);
146
+ const inbox = createInboxSnapshot(home, mcp.vaults, ctx.log, undefined, revision.current);
147
+ // One cursor for the whole Promote failure: a fresh one per failed scan would rebuild the panel every poll.
148
+ let promoteErrorCursor: number | undefined;
146
149
 
147
150
  /** One two-step operation: preview, and with the console's confirmation recompute and write only on the same fingerprint. */
148
151
  async function twoStep(tool: string, args: Args | string, confirmed: boolean, fingerprint: string | undefined, describe: (preview: Args) => { verb: string; preview: string[]; changes: Change[]; warnings: string[] }): Promise<ActionResult> {
@@ -154,7 +157,7 @@ export const plugin: ConsolePlugin = {
154
157
  return { ok: false, needsConfirm: true, fingerprint: preview.fingerprint, verb: d.verb, preview: d.preview, changes: d.changes, ...(d.warnings.length ? { warnings: d.warnings } : {}) };
155
158
  }
156
159
  const done = await call(tool, { ...args, confirm: true, fingerprint });
157
- if (done.applied === true) { lintCache.clear(); inbox.invalidate(); }
160
+ if (done.applied === true) { lintCache.clear(); revision.invalidate(); inbox.invalidate(); }
158
161
  return confirmedOutcome(done, describe(preview).verb);
159
162
  }
160
163
 
@@ -164,7 +167,10 @@ export const plugin: ConsolePlugin = {
164
167
  async snapshot(input) {
165
168
  const args = input as Args;
166
169
  switch (input.panel) {
167
- case "inbox": return inbox.snapshot();
170
+ case "inbox": {
171
+ const result = await inbox.snapshot();
172
+ return args.after === result.cursor ? { changed: false, cursor: result.cursor } : result;
173
+ }
168
174
  case "search": {
169
175
  const q = str(args.q);
170
176
  if (!q) return { hits: [], total: 0 };
@@ -197,7 +203,20 @@ export const plugin: ConsolePlugin = {
197
203
  const promotable = vaultOf(args)?.id === mcp.defaultVault && vaultOf(args)?.kind === "personal";
198
204
  return { note, links, orgVaults: promotable ? mcp.vaults.filter(v => v.kind === "org").map(v => v.id) : [] };
199
205
  }
200
- case "promote": return { ...(await candidates()), selected: str(args.id) ?? null };
206
+ case "promote": {
207
+ try {
208
+ const result = await promote.snapshot(args);
209
+ promoteErrorCursor = undefined;
210
+ return result;
211
+ } catch (error) {
212
+ ctx.log(`vmem: promotion snapshot unavailable: ${error instanceof Error ? error.message : String(error)}`);
213
+ promoteErrorCursor ??= nextSnapshotCursor();
214
+ // The shell keeps that one cursor: a matching `after` suppresses the unchanged error view.
215
+ return args.after === promoteErrorCursor
216
+ ? { changed: false, cursor: promoteErrorCursor }
217
+ : { projects: [], unavailable: "Promotion candidates are unavailable; see System", cursor: promoteErrorCursor };
218
+ }
219
+ }
201
220
  case "lint": {
202
221
  const vault = vaultOf(args);
203
222
  if (!vault) return { findings: [] };
@@ -251,8 +270,15 @@ export const plugin: ConsolePlugin = {
251
270
  case "promote-from-amem": {
252
271
  const id = (str(args.id) ?? "").replace(/^mem:/, "");
253
272
  if (!/^[0-9a-f-]{32,36}$/i.test(id)) return { ok: false, error: "a memory id is required" };
254
- if (!projectOf.has(id)) await candidates();
255
- const project = str(args.project) ?? projectOf.get(id);
273
+ let project = str(args.project) ?? projectOf.get(id);
274
+ if (!project) {
275
+ try { await candidates(); }
276
+ catch (error) {
277
+ ctx.log(`vmem: promotion candidates unavailable: ${error instanceof Error ? error.message : String(error)}`);
278
+ return { ok: false, error: "Promotion candidates are unavailable; see System" };
279
+ }
280
+ project = projectOf.get(id);
281
+ }
256
282
  return twoStep("vmem_promote_from_amem", forward("vmem_promote_from_amem", args, { id, ...(project ? { project } : {}) }), confirmed, fingerprint, p => {
257
283
  const dupes = Array.isArray(p.possibleDuplicates) ? p.possibleDuplicates as string[] : [];
258
284
  // Linking an existing note writes no vault file; it records the link in agent-mem only.
@@ -0,0 +1,123 @@
1
+ import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { join } from "node:path";
4
+ import type { VaultSpec } from "../config.ts";
5
+ import { CONFIG_FILE } from "../config.ts";
6
+ import type { listPromotionCandidates } from "../promote.ts";
7
+
8
+ type Candidates = Awaited<ReturnType<typeof listPromotionCandidates>>;
9
+ type Candidate = Candidates["projects"][number]["candidates"][number];
10
+ const PAGE_BYTES = 32 * 1024;
11
+ // Each of the 64 accepted selection characters can occupy six bytes after JSON escaping.
12
+ const SELECTED_BYTES = 64 * 6 + 2;
13
+ let sequence = Date.now();
14
+ export const nextSnapshotCursor = () => ++sequence;
15
+
16
+ /** Receipt metadata can share a timestamp across writes on coarse filesystems. Include a bounded
17
+ * log tail (or the entire size-limited registry) so same-size rewrites still invalidate. */
18
+ function revisionStamp(file: string, budget: number): string {
19
+ let fd: number | undefined;
20
+ try {
21
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
22
+ const s = fstatSync(fd, { bigint: true });
23
+ const metadata = `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`;
24
+ if (!s.isFile()) return metadata;
25
+ const size = Number(s.size);
26
+ if (!Number.isSafeInteger(size)) throw new Error("revision source is too large");
27
+ if (budget > 256 && size > budget) throw new Error("registry exceeds its revision read budget");
28
+ const bytes = Buffer.alloc(Math.min(budget, size));
29
+ const count = readSync(fd, bytes, 0, bytes.length, Math.max(0, size - bytes.length));
30
+ return `${metadata}:${createHash("sha256").update(bytes.subarray(0, count)).digest("hex")}`;
31
+ } catch (error) {
32
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing";
33
+ // A broken source must not prevent healthy vaults or unrelated panels from opening.
34
+ // Recovery changes this stamp back to file evidence and invalidates the cache.
35
+ return `error:${(error as NodeJS.ErrnoException).code ?? "UNREADABLE"}`;
36
+ } finally { if (fd !== undefined) closeSync(fd); }
37
+ }
38
+
39
+ /** A vmem write appends a receipt to its vault log. Check bounded receipt evidence, never scan notes or open Git/SQLite.
40
+ * Configuration changes also invalidate policy-screened candidates. An explicit invalidation covers an
41
+ * applied console write whose follow-up log failed, including link-only agent-mem promotions. */
42
+ export function createSnapshotRevision(home: string, vaults: VaultSpec[]) {
43
+ const files = [{ file: join(home, CONFIG_FILE), budget: 64 * 1024 }, ...vaults.map(vault => ({ file: join(vault.path, "log"), budget: 256 }))];
44
+ let previous = "", cursor = nextSnapshotCursor();
45
+ return {
46
+ current(): number {
47
+ const stamp = files.map(({ file, budget }) => revisionStamp(file, budget)).join("|");
48
+ if (stamp !== previous) { previous = stamp; cursor = nextSnapshotCursor(); }
49
+ return cursor;
50
+ },
51
+ invalidate() { cursor = nextSnapshotCursor(); },
52
+ };
53
+ }
54
+
55
+ /** Retain only the brief candidate metadata, and prepare byte-bounded pages once per revision.
56
+ * `cursor` identifies the page (including selection), `nextPage` is navigation, and `after` is conditional polling. */
57
+ export function createPromoteSnapshot(revision: () => number, load: () => Promise<Candidates>, now: () => number = Date.now) {
58
+ let cached: { revision: number; generation: number; digest: string; at: number; pages: Candidate[][] } | undefined;
59
+ let flight: Promise<void> | undefined;
60
+ const cursors = new Map<string, number>();
61
+ function response(rows: Candidate[], selected: string | null, cursor: number, page: string, nextPage?: string) {
62
+ const projects: Candidates["projects"] = [];
63
+ for (const row of rows) {
64
+ let project = projects.find(p => p.project === row.project);
65
+ if (!project) { project = { project: row.project, candidates: [] }; projects.push(project); }
66
+ project.candidates.push(row);
67
+ }
68
+ return { projects, selected, cursor, page, ...(nextPage ? { nextPage } : {}) };
69
+ }
70
+ return {
71
+ async snapshot(args: Record<string, unknown>): Promise<Record<string, unknown>> {
72
+ // A concurrent write may move the revision while the scan runs. Never label that scan as the new revision.
73
+ let attempts = 0;
74
+ while (!cached || cached.revision !== revision() || now() - cached.at >= 60_000) {
75
+ // Bound retries under sustained writes, retaining the last completed pages at their old revision.
76
+ if (++attempts > 2 && cached) break;
77
+ if (!flight) {
78
+ const started = revision();
79
+ flight = (async () => {
80
+ const result = await load();
81
+ const pages: Candidate[][] = [[]];
82
+ for (const project of result.projects) for (const item of project.candidates) {
83
+ const candidate = { ...item, title: item.title === null ? null : [...item.title].slice(0, 160).join("") };
84
+ const rows = pages.at(-1)!;
85
+ // Reserve enough envelope space for cursors, page tokens, and selection/reset metadata.
86
+ if (Buffer.byteLength(JSON.stringify(response([...rows, candidate], null, Number.MAX_SAFE_INTEGER, "x".repeat(80), "x".repeat(80)))) + SELECTED_BYTES > PAGE_BYTES - 256) {
87
+ if (rows.length === 0) throw new Error(`promotion candidate ${candidate.id.slice(0, 64)} in project ${candidate.project.slice(0, 160)} exceeds the 32 KiB page budget; inspect and shorten its agent-mem project or candidate metadata, then retry`);
88
+ pages.push([]);
89
+ if (Buffer.byteLength(JSON.stringify(response([candidate], null, Number.MAX_SAFE_INTEGER, "x".repeat(80), "x".repeat(80)))) + SELECTED_BYTES > PAGE_BYTES - 256) throw new Error(`promotion candidate ${candidate.id.slice(0, 64)} in project ${candidate.project.slice(0, 160)} exceeds the 32 KiB page budget; inspect and shorten its agent-mem project or candidate metadata, then retry`);
90
+ }
91
+ pages.at(-1)!.push(candidate);
92
+ }
93
+ const digest = createHash("sha256").update(JSON.stringify(pages)).digest("hex");
94
+ const identical = cached?.digest === digest;
95
+ cached = { revision: started, generation: identical ? cached!.generation : nextSnapshotCursor(), digest, at: now(), pages };
96
+ if (!identical) cursors.clear();
97
+ })().catch(error => {
98
+ // An error view replaces the last good view. Recovery must send full rows even when identical.
99
+ cursors.clear();
100
+ throw error;
101
+ }).finally(() => { flight = undefined; });
102
+ }
103
+ await flight;
104
+ }
105
+ const { pages, generation: rev } = cached;
106
+ const selected = typeof args.id === "string" && args.id.length <= 64 ? args.id : null;
107
+ const token = typeof args.page === "string" ? /^(\d+):(\d+)$/.exec(args.page) : null;
108
+ const validPage = token !== null && Number(token[1]) === rev && Number.isSafeInteger(Number(token[2])) && Number(token[2]) < pages.length;
109
+ const reset = args.page !== undefined && !validPage;
110
+ let index = validPage ? Number(token[2]) : 0;
111
+ if (!validPage && selected) index = Math.max(0, pages.findIndex(rows => rows.some(row => row.id === selected)));
112
+ const key = `${index}:${selected ?? ""}`;
113
+ let cursor = cursors.get(key);
114
+ if (cursor === undefined) {
115
+ // A bounded set of view cursors avoids growing with arbitrary selection inputs.
116
+ if (cursors.size >= 256) cursors.delete(cursors.keys().next().value!);
117
+ cursor = nextSnapshotCursor(); cursors.set(key, cursor);
118
+ }
119
+ if (args.after === cursor) return { changed: false, cursor };
120
+ return { ...response(pages[index]!, selected, cursor, `${rev}:${index}`, index + 1 < pages.length ? `${rev}:${index + 1}` : undefined), ...(reset ? { reset: true } : {}) };
121
+ },
122
+ };
123
+ }
@@ -0,0 +1,90 @@
1
+ import { join } from "node:path";
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import { unenforceablePii, type VaultSpec } from "./config.ts";
4
+ import { canonicalPath, isDenied } from "./platform.ts";
5
+ import { loadRegistry } from "./registry.ts";
6
+ import { VaultIndex, type BriefPointer } from "./vault-index.ts";
7
+ import { screenContent, screenMetadata } from "./write-validation.ts";
8
+
9
+ export interface VaultBrief { vault: string; lines: string[]; omitted: number; bytes: number }
10
+ export interface BriefRequest { vault: string; intent: string; paths?: string[]; bytes?: number }
11
+ export function briefText(result: VaultBrief): string { return [...result.lines, `${result.omitted} matches omitted`].join("\n"); }
12
+ function sized(vault: string, lines: string[], omitted: number): VaultBrief {
13
+ const result = { vault, lines, omitted, bytes: 0 };
14
+ for (let i = 0; i < 4; i++) {
15
+ const bytes = Buffer.byteLength(JSON.stringify(result));
16
+ if (bytes === result.bytes) break;
17
+ result.bytes = bytes;
18
+ }
19
+ return result;
20
+ }
21
+ const flat = (value: string) => value.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, " ");
22
+ /** Metadata pointers only. The normal metadata refresh is the only source-reading/cache-writing phase. */
23
+ export function vaultBrief(home: string, request: BriefRequest, expectedVault?: VaultSpec): VaultBrief {
24
+ const { vault: id, intent, paths = [], bytes = 1024 } = request;
25
+ if (typeof intent !== "string" || !intent.trim() || Buffer.byteLength(intent) > 1024) throw new Error("brief: intent must contain 1..1024 UTF-8 bytes; use --for with a shorter task description");
26
+ if (!Number.isSafeInteger(bytes) || bytes < 256 || bytes > 4096) throw new Error("brief: bytes must be an integer 256..4096; choose a supported byte cap");
27
+ if (!Array.isArray(paths) || paths.length > 16 || paths.some(p => typeof p !== "string" || !p.trim() || Buffer.byteLength(p) > 1024 || /\p{Cc}/u.test(p))) throw new Error("brief: paths must be at most 16 nonempty hints of at most 1024 bytes without control characters; remove control characters, shorten or remove path hints");
28
+ const words = [...new Set([intent, ...paths.map(p => p.split(/[\\/]/).at(-1)!.replace(/\.[^.]+$/, ""))].flatMap(value => value.normalize("NFC").match(/[\p{L}\p{N}]+/gu) ?? []))];
29
+ if (!words.length) throw new Error("brief: intent and path basenames contain no searchable letters or digits; provide words containing letters or digits");
30
+ if (words.length > 32 || Buffer.byteLength(words.join(" ")) > 4096) throw new Error("brief: expected 1..32 searchable words within 4096 bytes; shorten the intent or path basenames");
31
+ const config = loadRegistry(home), vault = config.vaults.find(v => v.id === id);
32
+ if (!vault) throw new Error("brief: unknown vault id; choose a registered id from vmem vaults list");
33
+ if (expectedVault && !isDeepStrictEqual(vault, expectedVault)) throw new Error("brief: vault binding changed since MCP startup; restart the MCP server before reading");
34
+ if (unenforceablePii(vault)) throw new Error("brief: vault PII policy cannot be enforced by this version; inspect vmem doctor and update the client or policy");
35
+ const denied = (file: string) => isDenied(file, config.denyPaths ?? []) || isDenied(canonicalPath(file), config.denyPaths ?? []);
36
+ if (denied(vault.path) || denied(join(vault.path, "notes"))) throw new Error("brief: vault or notes directory is denied; choose an allowed registered vault");
37
+ const index = new VaultIndex(home, vault, config.vaults.map(v => v.path));
38
+ try {
39
+ index.scan(false, { denyPaths: config.denyPaths ?? [] });
40
+ const ranked = index.briefMatches(words), direct = new Set(ranked.map(row => row.path));
41
+ // Count every attempt, including oversized or screened metadata, and pass the remaining bytes into SQL.
42
+ const cache = new Map<string, BriefPointer | undefined>(); let remaining = 256 * 1024, attempts = 0;
43
+ const load = (path: string) => {
44
+ if (cache.has(path)) return cache.get(path);
45
+ if (denied(join(vault.path, "notes", path))) { cache.set(path, undefined); return undefined; }
46
+ if (attempts >= 512 || remaining <= 0) return undefined;
47
+ attempts++;
48
+ let pointer = index.briefPointer(path, Math.min(4096, remaining));
49
+ if (pointer) {
50
+ remaining -= pointer.bytes;
51
+ const text = [pointer.path, pointer.title, pointer.type, pointer.description].join("\n");
52
+ if (/[\p{Cc}\p{Zl}\p{Zp}|]/u.test(pointer.path) || screenMetadata({ title: pointer.title, type: pointer.type, description: pointer.description }, { vault, config }, pointer.path).length || screenContent(text, vault, config).length || screenContent(flat(text), vault, config).length) pointer = undefined;
53
+ }
54
+ cache.set(path, pointer); return pointer;
55
+ };
56
+ const seeds: string[] = [];
57
+ for (const row of ranked) { if (load(row.path)) seeds.push(row.path); if (seeds.length === 5 || attempts >= 512 || remaining <= 0) break; }
58
+ const neighbors = index.briefNeighbors(seeds).filter(path => !direct.has(path));
59
+ const order = [...new Set([...seeds, ...neighbors, ...ranked.map(row => row.path)])];
60
+ const lines: string[] = [];
61
+ for (const path of order) {
62
+ const pointer = load(path);
63
+ if (!pointer) continue;
64
+ const line = `${direct.has(path) ? "" : "[neighbor] "}notes/${pointer.path} | ${flat(pointer.title)} | ${flat(pointer.type)} | ${flat(pointer.description)}`;
65
+ if (screenContent(line, vault, config).length) continue;
66
+ const candidate = sized(vault.id, [...lines, line], order.length - lines.length - 1);
67
+ if (candidate.bytes <= bytes && Buffer.byteLength(briefText(candidate)) + 1 <= bytes) lines.push(line);
68
+ }
69
+ return sized(vault.id, lines, order.length - lines.length);
70
+ } finally { index.close(); }
71
+ }
72
+
73
+ export function runBriefCommand(args: string[], home: string): { text: string; code: number } {
74
+ const paths: string[] = [], positional: string[] = []; let intent: string | undefined, bytes: number | undefined, json = false;
75
+ for (let i = 0; i < args.length; i++) {
76
+ const arg = args[i]!;
77
+ if (!arg.startsWith("-")) { positional.push(arg); continue; }
78
+ if (arg === "--json" && !json) { json = true; continue; }
79
+ if (!["--for", "--paths", "--bytes"].includes(arg)) throw new Error(`brief: unknown or repeated option ${arg}; run vmem brief --help`);
80
+ const value = args[++i];
81
+ if (!value || value.startsWith("--")) throw new Error(`brief: ${arg} requires a value; run vmem brief --help`);
82
+ if (arg === "--paths") paths.push(value);
83
+ else if (arg === "--for" && intent === undefined) intent = value;
84
+ else if (arg === "--bytes" && bytes === undefined && /^[0-9]+$/.test(value)) bytes = Number(value);
85
+ else throw new Error(`brief: repeated option or invalid value for ${arg}; run vmem brief --help`);
86
+ }
87
+ if (positional.length !== 1 || intent === undefined) throw new Error("brief: requires one registered vault and --for intent; run vmem brief --help");
88
+ const result = vaultBrief(home, { vault: positional[0]!, intent, paths, bytes });
89
+ return { text: json ? JSON.stringify(result) : briefText(result), code: 0 };
90
+ }