@staix/vault-mem 0.4.0 → 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.
package/src/sync.ts CHANGED
@@ -19,7 +19,7 @@ export interface SyncResult {
19
19
  branch: string | null;
20
20
  /** Planned changed paths that will be staged and committed. */
21
21
  paths: string[];
22
- /** Changed paths outside notes/, reports/ and log: never staged. */
22
+ /** Changed paths outside STAGE_PREFIXES and STAGE_FILES: never staged. */
23
23
  ignored: string[];
24
24
  ahead: number;
25
25
  behind: number;
@@ -28,7 +28,8 @@ export interface SyncResult {
28
28
  pushed?: boolean;
29
29
  issues: WriteIssue[];
30
30
  }
31
- type Git = (args: string[], options?: { allowFail?: boolean }) => SpawnSyncReturns<string>;
31
+ /** A git call; `cause` names why a failed call failed (timeout, signal or the last stderr line). */
32
+ type Git = (args: string[], options?: { allowFail?: boolean }) => SpawnSyncReturns<string> & { cause: string };
32
33
  const issue = (code: string, message: string): WriteIssue => ({ code, severity: "error", message });
33
34
  /** Compare remotes after removing transport noise: scheme, credentials, trailing .git and slash. Host remotes compare case-insensitively without a trailing .git; local and file: paths keep their case and their .git suffix. */
34
35
  export function sameRemote(a: string, b: string): boolean {
@@ -43,12 +44,28 @@ export function sameRemote(a: string, b: string): boolean {
43
44
  };
44
45
  return norm(a) === norm(b);
45
46
  }
46
- function gitIn(cwd: string, env: NodeJS.ProcessEnv): Git {
47
+ /** Time budget of the console's local sync check. */
48
+ const GIT_TIMEOUT_BUDGET_MS = 1000;
49
+ /** The paths `vmem sync` stages (STAGE_PREFIXES, then STAGE_FILES), as people read them. */
50
+ export const STAGED_DESCRIPTION = ((items: string[]) => items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items.at(-1)}` : items.join(""))([...STAGE_PREFIXES, ...STAGE_FILES]);
51
+ type SpawnResult = { exitCode: number | null; signalCode?: string | number | null; exitedDueToTimeout?: boolean; stderr: { toString(): string } };
52
+ /** Why a git call failed: its timeout or signal when it left no exit code, else the last stderr line. */
53
+ function failureCause(result: SpawnResult, budgetMs: number): string {
54
+ if (result.exitedDueToTimeout) return `timed out after ${budgetMs / 1000} s`;
55
+ if (result.exitCode === null) return `killed by ${result.signalCode ?? "a signal"}`;
56
+ return result.stderr.toString().trim().split("\n").at(-1)?.slice(0, 300) || "error";
57
+ }
58
+ const NEXT_STEP = { console: "inspect the vault Git state in System and retry", sync: "check `git -C <vault> status`, then rerun vmem sync", doctor: "check `git -C <vault> status`, then rerun vmem doctor" } as const;
59
+ function gitIn(cwd: string, env: NodeJS.ProcessEnv, deadline?: number, context: keyof typeof NEXT_STEP = "sync"): Git {
47
60
  return (args, options = {}) => {
61
+ const timeout = deadline === undefined ? GIT_TIMEOUT_MS : deadline - Date.now();
62
+ if (timeout <= 0) throw new Error(`git ${args[0]} not started: the ${GIT_TIMEOUT_BUDGET_MS / 1000} s budget is used up; ${NEXT_STEP[context]}`);
48
63
  const argv = memoryGitArgv(["-C", cwd, ...args]);
49
- const result = Bun.spawnSync(argv, { env: memoryGitEnv({ ...env, GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" }, { repositoryIsolation: true }), stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout: GIT_TIMEOUT_MS });
50
- const out = { status: result.exitCode, stdout: result.stdout.toString(), stderr: result.stderr.toString(), pid: result.pid, output: [], signal: null } as unknown as SpawnSyncReturns<string>;
51
- if (!options.allowFail && result.exitCode !== 0) throw Object.assign(new Error(`git ${args[0]} failed: ${out.stderr.trim().split("\n").at(-1)?.slice(0, 300) ?? "error"}`), { git: true });
64
+ const result = Bun.spawnSync(argv, { env: memoryGitEnv({ ...env, GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" }, { repositoryIsolation: true }), stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout });
65
+ // A timeout or signal leaves no exit code and usually no stderr, so `cause` names it instead.
66
+ const cause = result.exitCode === 0 ? "" : failureCause(result, deadline === undefined ? GIT_TIMEOUT_MS : GIT_TIMEOUT_BUDGET_MS);
67
+ const out = { status: result.exitCode, stdout: result.stdout.toString(), stderr: result.stderr.toString(), pid: result.pid, output: [], signal: null, cause } as unknown as ReturnType<Git>;
68
+ if (!options.allowFail && result.exitCode !== 0) throw Object.assign(new Error(`git ${args[0]} failed: ${cause}${result.exitCode === null ? `; ${NEXT_STEP[context]}` : ""}`), { git: true });
52
69
  return out;
53
70
  };
54
71
  }
@@ -65,8 +82,8 @@ function applicableRewrites(lines: (args: string[]) => string[], urls: string[])
65
82
  });
66
83
  }
67
84
  /** Local-only origin validation shared by doctor and sync; never fetches or pushes. */
68
- export function originCheck(root: string, remote: string, env: NodeJS.ProcessEnv = process.env): { ok: boolean; origin: string | null; fetchUrls: string[]; pushUrls: string[]; issue?: string } {
69
- const git = gitIn(root, env);
85
+ export function originCheck(root: string, remote: string, env: NodeJS.ProcessEnv = process.env, context: "sync" | "doctor" = "sync"): { ok: boolean; origin: string | null; fetchUrls: string[]; pushUrls: string[]; issue?: string } {
86
+ const git = gitIn(root, env, undefined, context);
70
87
  if (realpathSync(git(["rev-parse", "--show-toplevel"]).stdout.trim()) !== root) throw new Error("vault path is not the root of its git repository");
71
88
  const origin = git(["remote", "get-url", "origin"], { allowFail: true });
72
89
  const originUrl = origin.status === 0 ? origin.stdout.trim() : null;
@@ -78,15 +95,42 @@ export function originCheck(root: string, remote: string, env: NodeJS.ProcessEnv
78
95
  return { ok, origin: originUrl, fetchUrls, pushUrls, ...(!ok ? { issue: originUrl === null ? "repository has no origin remote" : rewrites.length ? `git url rewrite ${rewrites[0]} applies to the vault remote; refusing because the push destination cannot be verified` : "an origin fetch or push URL does not match the configured remote; nothing was fetched or pushed" } : {}) };
79
96
  }
80
97
  function planned(path: string): boolean { return STAGE_FILES.includes(path) || STAGE_PREFIXES.some(prefix => path.startsWith(prefix)); }
81
- /** Parse `status --porcelain=v1 -z` into changed paths (renames contribute both sides). */
82
- function changed(git: Git): string[] {
83
- const parts = git(["status", "--porcelain=v1", "-z", "--untracked-files=all"]).stdout.split("\0").filter(Boolean), paths: string[] = [];
98
+ /** Parse `status --porcelain=v1 -z` into one entry per change; a rename or copy is one entry with both sides. */
99
+ function changedEntries(git: Git): string[][] {
100
+ const parts = git(["status", "--porcelain=v1", "-z", "--untracked-files=all"]).stdout.split("\0").filter(Boolean), entries: string[][] = [];
84
101
  for (let i = 0; i < parts.length; i++) {
85
102
  const entry = parts[i]!, code = entry.slice(0, 2);
86
- paths.push(entry.slice(3));
87
- if (code.includes("R") || code.includes("C")) paths.push(parts[++i]!);
103
+ entries.push(code.includes("R") || code.includes("C") ? [entry.slice(3), parts[++i]!] : [entry.slice(3)]);
88
104
  }
89
- return [...new Set(paths)].sort();
105
+ return entries;
106
+ }
107
+ /** Changed paths, both sides of a rename included, sorted and unique. */
108
+ function changed(git: Git): string[] { return [...new Set(changedEntries(git).flat())].sort(); }
109
+
110
+ /** Shared local history counts; no fetch is needed to compare stored refs. */
111
+ function aheadBehind(git: Git, upstream: string): { behind: number; ahead: number } {
112
+ const [behind, ahead] = git(["rev-list", "--left-right", "--count", `${upstream}...HEAD`]).stdout.trim().split(/\s+/).map(Number);
113
+ if (!Number.isSafeInteger(behind) || !Number.isSafeInteger(ahead) || behind! < 0 || ahead! < 0) throw new Error("git rev-list returned invalid counts; inspect the vault Git state in System and retry");
114
+ return { behind: behind!, ahead: ahead! };
115
+ }
116
+ /** Local-only inbox state: dirty paths plus commits ahead of the configured tracking ref. */
117
+ export function localSyncPending(root: string, env: NodeJS.ProcessEnv = process.env): { changed: number; ignored: number; ahead: number; upstream: boolean } {
118
+ const git = gitIn(root, { ...env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "Never", GIT_NO_LAZY_FETCH: "1" }, Date.now() + GIT_TIMEOUT_BUDGET_MS, "console");
119
+ if (realpathSync(root) !== root || realpathSync(git(["rev-parse", "--show-toplevel"]).stdout.trim()) !== root) throw new Error("sync pending requires the registered Git worktree root; check the vault path in System");
120
+ // Only changes sync would stage count; a rename counts once. Other dirty paths are reported separately.
121
+ const entries = changedEntries(git), dirty = entries.filter(paths => paths.some(planned)).length, ignored = entries.length - dirty;
122
+ const none = { changed: dirty, ignored, ahead: 0, upstream: false };
123
+ // `symbolic-ref` exits 1 only for a detached HEAD, which has no branch and so no upstream. An unborn branch
124
+ // passes here, but its branch ref does not exist yet, so `for-each-ref` below finds no upstream.
125
+ const branch = git(["symbolic-ref", "--quiet", "HEAD"], { allowFail: true });
126
+ if (branch.status === 1) return none;
127
+ if (branch.status !== 0) throw new Error("sync pending cannot read the current branch; inspect the vault Git state in System and retry");
128
+ const upstream = git(["for-each-ref", "--format=%(upstream)", branch.stdout.trim()]).stdout.trim();
129
+ if (!upstream) return none;
130
+ const tracking = git(["rev-parse", "--verify", "--quiet", upstream], { allowFail: true });
131
+ if (tracking.status === 1) return none;
132
+ if (tracking.status !== 0) throw new Error("sync pending cannot verify the tracking ref; inspect the vault Git state in System and retry");
133
+ return { changed: dirty, ignored, ahead: aheadBehind(git, upstream).ahead, upstream: true };
90
134
  }
91
135
 
92
136
  /**
@@ -120,12 +164,12 @@ export function syncVault(home: string, request: { vault: string; confirm?: bool
120
164
  result.branch = branch.stdout.trim();
121
165
  if (git(["rev-parse", "--verify", "--quiet", "REBASE_HEAD"], { allowFail: true }).status === 0 || git(["rev-parse", "--verify", "--quiet", "MERGE_HEAD"], { allowFail: true }).status === 0) return { ...result, issues: [issue("SYNC", "a rebase or merge is in progress; resolve it first")] };
122
166
  const fetch = git(["fetch", "--quiet", "--no-tags", "origin", result.branch], { allowFail: true });
123
- if (fetch.status !== 0) return { ...result, issues: [issue("FETCH", `fetch failed: ${fetch.stderr.trim().split("\n").at(-1)?.slice(0, 300) ?? "error"}`)] };
167
+ if (fetch.status !== 0) return { ...result, issues: [issue("FETCH", `fetch failed: ${fetch.cause}; check the network and credentials for origin, then rerun vmem sync`)] };
124
168
  const upstream = `origin/${result.branch}`;
125
169
  const hasUpstream = git(["rev-parse", "--verify", "--quiet", `refs/remotes/${upstream}`], { allowFail: true }).status === 0;
126
170
  if (hasUpstream) {
127
- const [behind, ahead] = git(["rev-list", "--left-right", "--count", `${upstream}...HEAD`]).stdout.trim().split(/\s+/).map(Number);
128
- result.behind = behind ?? 0; result.ahead = ahead ?? 0;
171
+ const counts = aheadBehind(git, upstream);
172
+ result.behind = counts.behind; result.ahead = counts.ahead;
129
173
  }
130
174
  const all = changed(git);
131
175
  result.paths = all.filter(planned); result.ignored = all.filter(path => !planned(path));
@@ -155,7 +199,7 @@ export function syncVault(home: string, request: { vault: string; confirm?: bool
155
199
  const pushNow = lines(["remote", "get-url", "--push", "--all", "origin"]);
156
200
  if (pushNow.some(url => !sameRemote(url, spec.remote!)) || applicableRewrites(lines, [spec.remote, ...fetchUrls, ...pushNow]).length) return { ...result, applied: Boolean(result.commit), pushed: false, issues: [issue("REMOTE", "push destination changed before push; nothing was pushed")] };
157
201
  const push = git(["push", "--quiet", "--porcelain", "origin", `HEAD:refs/heads/${result.branch}`], { allowFail: true });
158
- if (push.status !== 0) return { ...result, applied: Boolean(result.commit), pushed: false, issues: [issue("PUSH", `push failed: ${push.stderr.trim().split("\n").at(-1)?.slice(0, 300) ?? "error"}; the local commit was kept`)] };
202
+ if (push.status !== 0) return { ...result, applied: Boolean(result.commit), pushed: false, issues: [issue("PUSH", `push failed: ${push.cause}; the local commit was kept; check the network and push access for origin, then rerun vmem sync`)] };
159
203
  // Verify the remote really has our head before reporting success.
160
204
  git(["fetch", "--quiet", "--no-tags", "origin", result.branch]);
161
205
  const pushedHead = git(["rev-parse", upstream]).stdout.trim(), localHead = git(["rev-parse", "HEAD"]).stdout.trim();
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Text output for people (#114), after agent-hub's CLI conventions: uppercase-header tables sized by display width,
3
+ * aligned field blocks, a wrapped description column and `--color=auto|always|never`. `--json` output never comes
4
+ * through here, and color only adds emphasis: every renderer's text is complete without it.
5
+ */
6
+ import type { WriteIssue } from "./write-types.ts";
7
+
8
+ export type Tone = "ok" | "warn" | "fail" | "muted" | "info" | "accent" | "bold";
9
+ export interface TextOptions { color: boolean; columns?: number }
10
+ export interface Cell { text: string; tone?: Tone }
11
+ export type CellInput = string | number | boolean | null | undefined | Cell;
12
+
13
+ /** Plain text, no wrapping: the default for library callers and tests. */
14
+ export const PLAIN: TextOptions = { color: false };
15
+ const CODES: Record<Tone, string> = { ok: "32", warn: "33", fail: "31", muted: "2", info: "36", accent: "35", bold: "1" };
16
+ const COLOR_USAGE = "--color: expected --color=auto, --color=always or --color=never";
17
+
18
+ /** Removes the one allowed `--color=` flag from args. It may appear anywhere before a `--` separator. */
19
+ export function takeColorFlag(args: string[]): { args: string[]; color?: string } {
20
+ const end = args.includes("--") ? args.indexOf("--") : args.length;
21
+ const found = args.slice(0, end).filter(arg => arg === "--color" || arg.startsWith("--color="));
22
+ if (!found.length) return { args };
23
+ if (found.length > 1 || found[0] === "--color") throw new Error(`${COLOR_USAGE}, given once`);
24
+ return { args: args.filter((arg, i) => i >= end || arg !== found[0]), color: found[0]!.slice("--color=".length) };
25
+ }
26
+ export function resolveColor(flag: string | undefined, env: { isTTY: boolean; TERM?: string; NO_COLOR?: string }): boolean {
27
+ if (flag === "always") return true;
28
+ if (flag === "never") return false;
29
+ if (flag === undefined || flag === "auto") return env.isTTY && env.TERM !== "dumb" && !env.NO_COLOR;
30
+ throw new Error(COLOR_USAGE);
31
+ }
32
+ /** Terminal width on a TTY (at least 80), else `COLUMNS` when set, else no wrapping. */
33
+ export function outputWidth(env: { isTTY: boolean; columns?: number; COLUMNS?: string }): number | undefined {
34
+ if (env.isTTY) return Math.max(80, env.columns && Number.isFinite(env.columns) ? env.columns : 80);
35
+ return env.COLUMNS && /^[1-9][0-9]*$/.test(env.COLUMNS) ? Number(env.COLUMNS) : undefined;
36
+ }
37
+ /** Options for a stdout; the default is a non-terminal, so library calls and tests get the same text everywhere. */
38
+ export function textOptions(flag: string | undefined, env: NodeJS.ProcessEnv = process.env, stdout: { isTTY?: boolean; columns?: number } = {}): TextOptions {
39
+ const isTTY = stdout.isTTY === true, color = resolveColor(flag, { isTTY, TERM: env.TERM, NO_COLOR: env.NO_COLOR });
40
+ const columns = outputWidth({ isTTY, columns: stdout.columns, COLUMNS: env.COLUMNS });
41
+ return { color, ...(columns !== undefined ? { columns } : {}) };
42
+ }
43
+
44
+ const cell = (value: CellInput): Cell => typeof value === "object" && value !== null ? value : { text: value === null || value === undefined ? "" : String(value) };
45
+ /** Control characters (terminal escapes, tabs, newlines) never reach the terminal from data. */
46
+ export const clean = (text: string) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ");
47
+ export const width = (text: string) => Bun.stringWidth(text);
48
+ /** Note and spec bodies printed as is, minus terminal escape sequences (OSC, CSI, C1) and control characters other than tab and newline. */
49
+ export const stripTerminal = (text: string) => text
50
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\u001b\[[0-?]*[ -/]*[@-~]?|\u009b[0-?]*[ -/]*[@-~]?|\u001b[^[\]]?/g, "")
51
+ .replace(/\r\n?/g, "\n").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "");
52
+ export function paint(text: string, tone: Tone | undefined, o: TextOptions): string {
53
+ return o.color && tone && text ? `\u001b[${CODES[tone]}m${text}\u001b[0m` : text;
54
+ }
55
+ export const tone = (text: CellInput, t: Tone): Cell => ({ text: cell(text).text, tone: t });
56
+ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
57
+
58
+ /** Word wrap by display width; a word longer than the width is split by grapheme. */
59
+ export function wrap(text: string, columns: number | undefined, indent = ""): string[] {
60
+ const flat = clean(text);
61
+ if (columns === undefined) return [indent + flat];
62
+ const room = Math.max(10, columns - width(indent)), lines: string[] = [];
63
+ let line = "";
64
+ for (const word of flat.split(/ +/).filter(Boolean)) {
65
+ const pieces: string[] = [];
66
+ if (width(word) <= room) pieces.push(word);
67
+ else { let piece = ""; for (const { segment } of graphemes.segment(word)) { if (width(piece + segment) > room) { pieces.push(piece); piece = ""; } piece += segment; } if (piece) pieces.push(piece); }
68
+ for (const piece of pieces) {
69
+ if (line && width(line + " " + piece) > room) { lines.push(line); line = ""; }
70
+ line = line ? `${line} ${piece}` : piece;
71
+ }
72
+ }
73
+ if (line || !lines.length) lines.push(line);
74
+ return lines.map(value => indent + value);
75
+ }
76
+ const pad = (text: string, size: number) => text + " ".repeat(Math.max(0, size - width(text)));
77
+
78
+ /**
79
+ * Table with uppercase headers and two-space gaps. When a width is known and the row is too wide, the last column
80
+ * wraps under itself; with no width (pipes, tests) rows stay on one line.
81
+ */
82
+ export function table(headers: string[], rows: CellInput[][], o: TextOptions): string {
83
+ const data = rows.map(row => headers.map((_, i) => { const c = cell(row[i]); return { ...c, text: clean(c.text) }; }));
84
+ const sizes = headers.map((header, i) => Math.max(width(header), ...data.map(row => width(row[i]!.text))));
85
+ const last = headers.length - 1, lead = sizes.slice(0, last).reduce((sum, size) => sum + size + 2, 0);
86
+ const lastRoom = o.columns !== undefined && lead + sizes[last]! > o.columns ? Math.max(20, o.columns - lead) : undefined;
87
+ const line = (cells: Cell[], bold = false) => {
88
+ const tail = wrap(cells[last]!.text, lastRoom);
89
+ const head = cells.slice(0, last).map((c, i) => paint(pad(c.text, sizes[i]!), bold ? "bold" : c.tone, o)).join(" ");
90
+ return tail.map((part, i) => (i ? " ".repeat(lead) : head + (last ? " " : "")) + paint(part, bold ? "bold" : cells[last]!.tone, o)).join("\n").replace(/ +$/gm, "");
91
+ };
92
+ return [line(headers.map(text => ({ text })), true), ...data.map(row => line(row))].join("\n");
93
+ }
94
+ /** `label value` lines with aligned values, indented by two spaces. Empty values are left out. */
95
+ export function fields(pairs: [label: string, value: CellInput][], o: TextOptions, indent = " "): string {
96
+ const shown = pairs.map(([label, value]) => [label, cell(value)] as const).filter(([, value]) => value.text !== "");
97
+ const size = Math.max(0, ...shown.map(([label]) => width(label)));
98
+ const hang = indent + " ".repeat(size + 2);
99
+ return shown.map(([label, value]) => {
100
+ const lines = wrap(value.text, o.columns === undefined ? undefined : o.columns - width(hang));
101
+ return lines.map((text, i) => (i ? hang : indent + pad(label, size) + " ") + paint(text, value.tone, o)).join("\n");
102
+ }).join("\n");
103
+ }
104
+ export const heading = (text: string, o: TextOptions) => paint(clean(text), "bold", o);
105
+ /** Paragraph wrapped to the width, for hints and verdicts. */
106
+ export const paragraph = (text: string, o: TextOptions, t?: Tone, indent = "") => wrap(text, o.columns, indent).map(line => paint(line, t, o)).join("\n");
107
+ /** Joins the non-empty blocks with one blank line. */
108
+ export const blocks = (...parts: (string | undefined | false)[]) => parts.filter((part): part is string => !!part).join("\n\n");
109
+ export const plural = (count: number, one: string, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
110
+
111
+ /** Write and validation issues: LEVEL, CODE, PATH and MESSAGE, errors first. */
112
+ export function issueTable(issues: readonly WriteIssue[], o: TextOptions): string | undefined {
113
+ if (!issues.length) return undefined;
114
+ const sorted = [...issues].sort((a, b) => (a.severity === b.severity ? 0 : a.severity === "error" ? -1 : 1));
115
+ return table(["LEVEL", "CODE", "PATH", "MESSAGE"], sorted.map(issue => [tone(issue.severity, issue.severity === "error" ? "fail" : "warn"), issue.code, issue.path ?? "-", issue.message]), o);
116
+ }
117
+ /** The command a person runs next, for example to confirm a preview or read the next page. */
118
+ export const nextCommand = (label: string, command: string, o: TextOptions) => `${label}: ${paint(clean(command), "info", o)}`;
119
+ /** Quotes one shell word only when it needs it, so a printed command can be pasted. */
120
+ export const shellWord = (word: string) => /^[\p{L}\p{N}_./:=@%+,-]+$/u.test(word) ? word : `'${word.replace(/'/g, `'"'"'`)}'`;
package/src/ui/panel.css CHANGED
@@ -1,16 +1,12 @@
1
+ .vmem-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(300px, 100%), 1fr)); gap: var(--acon-space-4); }
1
2
  .vmem { display: flex; flex-direction: column; gap: var(--acon-space-3); word-break: keep-all; }
2
3
  .vmem-bar { display: flex; flex-wrap: wrap; align-items: center; gap: var(--acon-space-2); }
3
4
  .vmem-inline { display: inline-flex; gap: var(--acon-space-2); }
4
5
  .vmem-input { min-height: 32px; min-width: 0; padding: 0 10px; border: 1px solid var(--acon-line-2); border-radius: var(--acon-radius-2); background: var(--acon-surface); color: var(--acon-text); font: inherit; }
5
6
  .vmem-bar input[type="search"] { flex: 1; max-width: 480px; }
6
- .vmem-head { display: flex; flex-wrap: wrap; align-items: center; gap: var(--acon-space-2); }
7
- .vmem-head h2 { margin: 0; font-size: 17px; }
8
7
  .vmem-sub { margin: 0; color: var(--acon-text-2); }
9
8
  .vmem-body { margin: var(--acon-space-2) 0 0; padding: var(--acon-space-3); max-height: 60vh; overflow: auto; white-space: pre-wrap; word-break: break-word; background: var(--acon-surface); border: 1px solid var(--acon-line); border-radius: var(--acon-radius-2); font: 13px/1.5 var(--acon-font-mono); }
10
- .vmem-mono { margin: 0; color: var(--acon-text-2); font: 12px var(--acon-font-mono); word-break: break-all; }
11
- .vmem details > summary { cursor: pointer; font-weight: 600; padding: var(--acon-space-1) 0; }
12
9
  @media (max-width: 600px) { .vmem-inline { width: 100%; } .vmem-inline .vmem-input { flex: 1; } }
13
10
  .vmem-form { display: flex; flex-direction: column; gap: var(--acon-space-2); max-width: 560px; }
14
11
  .vmem-form h2 { margin: 0; font-size: 15px; }
15
- .vmem-form .btn { align-self: flex-start; }
16
12
  .vmem-check { display: inline-flex; align-items: center; gap: 4px; color: var(--acon-text-2); }
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
  }
@@ -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];