@staix/vault-mem 0.5.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/README.md +4 -2
- package/package.json +1 -1
- package/src/ui/inbox-source.ts +46 -0
- package/src/ui/inbox-worker.ts +8 -0
- package/src/ui/inbox.ts +134 -0
- package/src/ui/plugin.ts +7 -56
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.5.1] - 2026-11-05
|
|
6
|
+
|
|
7
|
+
- Console inbox snapshots share a background refresh, keep prior rows through refreshes and source failures, and wait at most 700 ms cold before showing a refreshing row. Payloads are capped at 50 prioritized rows with bounded Unicode-safe title and detail. `moreIsLowerBound` identifies "at least N more" when agent-mem's per-project candidate limit prevents an exact total. Applied writes invalidate freshness without clearing triage; source workers refresh on a 60-second cache and have a 30-second termination budget (#149).
|
|
8
|
+
|
|
9
|
+
- Tests: the core fixture copies use NFC names, so a macOS working copy that holds `café.md` under an NFD name no longer fails `bun run check`. A new test pins the path contract: an NFD-named note keeps its on-disk name in `search`, `show` and `links` and resolves from NFC targets, as the README now states (#147).
|
|
10
|
+
|
|
5
11
|
## [0.5.0] - 2026-11-04
|
|
6
12
|
|
|
7
13
|
- Git timeouts and signals are named accurately: `timed out after 60 s` for `vmem sync` and `1 s` for the console check (from Bun's `exitedDueToTimeout`), else `killed by <signal>`, each with its own next step (`check git -C <vault> status, then rerun vmem sync`, the same for `vmem doctor`, or `inspect the vault Git state in System`). `vmem sync` FETCH and PUSH issues with an empty stderr now say why and name a next step. The console sync alert names the staged paths from the same list sync stages (#143).
|
package/README.md
CHANGED
|
@@ -95,7 +95,7 @@ The cache is `$VMEM_HOME/indexes/<canonical-vault-path-sha256>-links<N>-schema<S
|
|
|
95
95
|
|
|
96
96
|
Search uses FTS5 `unicode61` over title, description and body with BM25 weights 5:2:1, ascending score and path tie-breaking. Whitespace-separated query terms are literal AND terms, not a raw FTS expression; quote the query as one shell argument. A term whose letters and digits form one run of 2 or more Hangul, Han, Hiragana or Katakana characters (surrounding punctuation is ignored) matches wherever it occurs in the title, description or body, including particle and compound forms: `사업단` finds `사업단은`, `사업단장` and `해외사업단`. That matching uses a side FTS5 table of overlapping character bigrams (Unicode NFC), so a 2-character term is one indexed lookup and a longer term a phrase of consecutive bigrams; it is substring matching, not morphological analysis. Every other term, including Latin words, single CJK characters and terms mixing CJK with Latin letters or digits (`AI교육`), keeps `unicode61` token matching, and a query without CJK terms ranks exactly as before. With a CJK term, notes where every CJK term is a standalone word or occurs in the title or description rank before notes that contain it only inside a longer body word; within each group BM25 over the bigram table (5:2:1) and path break ties, and the snippet is a body window around the first CJK term. `--type` and `--domain` are exact scalar frontmatter filters. Results include a bounded snippet and metadata, not the full body. Search queries and note targets accept at most 1024 UTF-8 bytes. Search/links default to 50 results, with an enforced 1..500 range. Show defaults to 16384 UTF-8 bytes and permits 1..65536, returning `truncated` and the full note SHA-256. `--section "Exact H2"` selects one real H2 through the next H1/H2, including its H3 children; code-fenced headings are ignored and duplicate/missing names refuse. Truncated reads include bounded `headings` (at most 64 names/8KiB metadata; `headingsTruncated` when omitted) and `nextOffset`. `--offset N` is a UTF-8 byte offset within the selected section or whole note; use the returned `nextOffset` to page even a single section larger than 64 KiB, and compare note hashes across pages. Invalid UTF-8 boundaries and zero-progress byte budgets refuse. Link string fields are capped at 1024 bytes in command results. Oversized arguments fail instead of silently raising a bound.
|
|
97
97
|
|
|
98
|
-
Link resolution uses NFC and case-insensitive filename stems only, as Obsidian and `vmem lint` L01 do. Frontmatter `aliases` (string or string array; legacy `alias` accepted) are not link targets; `show`, `links <target>` and `vmem_read` still find a note by alias. A link that only an alias matches is a missing-note link, so the writer refuses a new one and org promotion drops it to text. An optional `notes/` prefix and `.md` suffix are accepted. `[[target|label]]`, `[[target#heading]]`, `[[target#^block]]`, `![[target]]` and same-note anchors work. ATX/Setext headings and end-of-line block ids are checked; fenced code is skipped. Missing/ambiguous targets and missing anchors remain explicit with a reason. Stems that differ only by case or Unicode normalization are ambiguous. Links returns outgoing links in source order, with one-based body-relative `line` values (frontmatter excluded); it does not write backlinks or repair dead links.
|
|
98
|
+
Link resolution uses NFC and case-insensitive filename stems only, as Obsidian and `vmem lint` L01 do. Frontmatter `aliases` (string or string array; legacy `alias` accepted) are not link targets; `show`, `links <target>` and `vmem_read` still find a note by alias. A link that only an alias matches is a missing-note link, so the writer refuses a new one and org promotion drops it to text. An optional `notes/` prefix and `.md` suffix are accepted. `[[target|label]]`, `[[target#heading]]`, `[[target#^block]]`, `![[target]]` and same-note anchors work. ATX/Setext headings and end-of-line block ids are checked; fenced code is skipped. Missing/ambiguous targets and missing anchors remain explicit with a reason. Stems that differ only by case or Unicode normalization are ambiguous. Reported `path` values are the on-disk file names byte for byte, while targets (`show`, `links`, `vmem_read`, wiki-links) are compared after NFC: a note another tool saved under an NFD name is found from an NFC target and reported under its NFD name. Links returns outgoing links in source order, with one-based body-relative `line` values (frontmatter excluded); it does not write backlinks or repair dead links.
|
|
99
99
|
|
|
100
100
|
`parseFrontmatter` retains source bytes alongside semantic YAML data using Bun's built-in YAML parser. `emitFrontmatter(document, changes)` returns the entire note, preserving omitted and semantically unchanged keys byte-identically (comments, quoting, sequences, one-level mappings, folded/literal/chomped scalars, BOM and line endings). Changed keys use canonical JSON-compatible YAML; `undefined` removes a key. Editing requires a block mapping, while an unchanged flow mapping round-trips. This is a library transformation only, not a note-write command. Synthetic fixtures and create/edit/delete/rename parity tests cover this increment; Linux/macOS CI remains the platform verification gate.
|
|
101
101
|
|
|
@@ -246,7 +246,9 @@ vmem promote-from-amem personal mem:<id> --link-to existing-note # link an exis
|
|
|
246
246
|
`vmem setup <target> --apply` also writes `$AGENTHUB_HOME/console/plugins/vmem.json` (default `~/.agenthub`; directory 0700, file 0600) with the absolute path and sha256 of `src/ui/plugin.ts`. `acon ui` then shows a Vault area. The panel needs agent-console 0.1.0 or later, the first release with the `host.ui` panel kit and `ui.button`. An older acon still loads the plugin, but the panel then fails with a TypeError on `host.ui`; upgrade agent-console to fix it. Re-run setup after upgrading vmem: acon refuses a module whose hash changed.
|
|
247
247
|
|
|
248
248
|
- Panels: Overview (vaults, maps, recent log), Search, Note (body, links, actions), Promote (agent-mem candidates), Lint (typed findings linked to notes) and Log (parsed rows).
|
|
249
|
-
- Inbox: promotion candidates (group `candidate`), lint errors, a stale graph report and org-vault sync pending (group `alert`). Sync pending counts uncommitted paths plus local commits ahead of the upstream tracking ref; without an upstream it counts only uncommitted paths. It reads local Git state only (no fetch or credential prompt)
|
|
249
|
+
- Inbox: promotion candidates (group `candidate`), lint errors, a stale graph report and org-vault sync pending (group `alert`). Sync pending counts uncommitted paths plus local commits ahead of the upstream tracking ref; without an upstream it counts only uncommitted paths. It reads local Git state only (no fetch or credential prompt) and opens Overview with that vault, with no one-key sync verb. The palette searches notes.
|
|
250
|
+
- Inbox snapshots share one background refresh, with one worker source at a time. A cold snapshot waits at most 700 ms and then shows a refreshing status row; `refreshing: true` also marks an active collection. Later snapshots keep serving the last complete rows while refreshing. A source failure retains its last rows; if every source is unavailable at startup, a separate unavailable status row opens Overview and advises checking System. Refreshes are cached for 60 seconds, including failed attempts. Applied writes invalidate freshness without clearing the rows.
|
|
251
|
+
- The inbox returns at most 50 rows, errors and alerts first, then newest candidates, with titles capped at 160 Unicode code points and detail at 240. `more` counts omitted rows. Because agent-mem limits candidates per project and exposes no total-count API, vmem fetches 51 per project to detect overflow: when `moreIsLowerBound: true`, read `more` as "at least N more", not an exact total. That lower bound does not decrease when candidates are added to the same population, but may stay flat once a project reaches the fetch limit. A source failure retains its previous count too. Full candidate and lint details are available in their panels. Each source has a 30-second budget to initiate worker termination; shutdown may wait for an active native call, without blocking inbox responses.
|
|
250
252
|
- Actions: `delete`, `move`, `promote` (to an org vault) and `promote-from-amem` reuse the two-step MCP tools. Each first answers a preview with the planned changes; the write happens only after the console's confirm dialog, and only while the fingerprint still matches.
|
|
251
253
|
- The provider calls the `vmem mcp` handlers in process, so the console has exactly the MCP rights: writes need a vault with `write: mcp`, and log lines carry the agent attribution.
|
|
252
254
|
- The module is exported as `@staix/vault-mem/ui-plugin`. Lint results are cached for 60 seconds per vault.
|
package/package.json
CHANGED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** One read-only inbox source. Runs off the request thread, with a parent-enforced deadline. */
|
|
2
|
+
import type { InboxItem } from "@staix/agent-console/contract";
|
|
3
|
+
import { analysisInput } from "../analysis-input.ts";
|
|
4
|
+
import { listPromotionCandidates } from "../promote.ts";
|
|
5
|
+
import { loadRegistry } from "../registry.ts";
|
|
6
|
+
import type { VaultSpec } from "../config.ts";
|
|
7
|
+
import { isDenied } from "../platform.ts";
|
|
8
|
+
import { localSyncPending, STAGED_DESCRIPTION } from "../sync.ts";
|
|
9
|
+
import { boundInbox, type InboxRows } from "./inbox.ts";
|
|
10
|
+
import { lintVault } from "../vault-lint.ts";
|
|
11
|
+
|
|
12
|
+
export type InboxSource = { kind: "candidates" } | { kind: "lint" | "sync"; vault: VaultSpec };
|
|
13
|
+
export async function collectInboxSource(home: string, source: InboxSource): Promise<InboxRows> {
|
|
14
|
+
const at = new Date().toISOString();
|
|
15
|
+
if (source.kind === "candidates") {
|
|
16
|
+
// Fetch one beyond the payload cap. The API limits per project and has no cheap total.
|
|
17
|
+
// `more` is "at least N more" when any project saturates: it cannot fall as candidates
|
|
18
|
+
// are added to the same population, and a single overflowing project never reports zero.
|
|
19
|
+
const { projects } = await listPromotionCandidates({ allProjects: true, limit: 51, piiPatterns: loadRegistry(home).piiPatterns });
|
|
20
|
+
const items: InboxItem[] = projects.flatMap(p => p.candidates.map(c => ({
|
|
21
|
+
id: `mem:${c.id}`, group: "candidate" as const, kind: "promotion", title: c.title ?? c.kind, detail: `${c.kind} memory to promote into a vault note`,
|
|
22
|
+
project: c.project, at: new Date(c.at).toISOString(), verbs: [],
|
|
23
|
+
link: { panel: "promote", params: { id: c.id, project: c.project } },
|
|
24
|
+
})));
|
|
25
|
+
return boundInbox(items, 0, projects.some(p => p.candidates.length === 51));
|
|
26
|
+
}
|
|
27
|
+
const v = source.vault;
|
|
28
|
+
if (source.kind === "lint") {
|
|
29
|
+
const report = lintVault(analysisInput(home, v.id, { expectedVault: v }).snapshot);
|
|
30
|
+
const items: InboxItem[] = [];
|
|
31
|
+
if (report.errors > 0) items.push({ id: `lint:${v.id}`, group: "alert", kind: "lint", title: `${report.errors} lint errors in ${v.id}`,
|
|
32
|
+
detail: report.summary, at, chip: { text: `${report.errors} errors`, tone: "err" }, verbs: [], link: { panel: "lint", params: { vault: v.id } } });
|
|
33
|
+
if (report.findings.L11?.length) items.push({ id: `stale:${v.id}`, group: "alert", kind: "lint", title: `Graph report is stale in ${v.id}`,
|
|
34
|
+
detail: report.findings.L11[0]!, at, chip: { text: "stale", tone: "warn" }, verbs: [], link: { panel: "lint", params: { vault: v.id } } });
|
|
35
|
+
return boundInbox(items);
|
|
36
|
+
}
|
|
37
|
+
const config = loadRegistry(home), spec = config.vaults.find(x => x.id === v.id);
|
|
38
|
+
if (!spec || JSON.stringify(spec) !== JSON.stringify(v)) throw new Error("vault binding changed; restart the console provider");
|
|
39
|
+
if (isDenied(spec.path, config.denyPaths)) throw new Error("vault path is denied; check its path policy in System");
|
|
40
|
+
const pending = localSyncPending(spec.path), count = pending.changed + pending.ahead;
|
|
41
|
+
return boundInbox(count > 0 ? [{ id: `sync:${v.id}`, group: "alert", kind: "sync", title: `${count} unsynced change${count === 1 ? "" : "s"} in ${v.id}`,
|
|
42
|
+
detail: [`${pending.changed} uncommitted path${pending.changed === 1 ? "" : "s"} to sync`,
|
|
43
|
+
...(pending.ignored ? [`${pending.ignored} other path${pending.ignored === 1 ? "" : "s"} outside ${STAGED_DESCRIPTION} not counted`] : []),
|
|
44
|
+
...(pending.upstream ? [`${pending.ahead} local commit${pending.ahead === 1 ? "" : "s"} ahead of upstream`] : [])].join("; "),
|
|
45
|
+
at, chip: { text: "sync pending", tone: "warn" }, verbs: [], link: { panel: "overview", params: { vault: v.id } } }] : []);
|
|
46
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
2
|
+
import { collectInboxSource } from "./inbox-source.ts";
|
|
3
|
+
|
|
4
|
+
try {
|
|
5
|
+
parentPort!.postMessage({ result: await collectInboxSource(workerData.home, workerData.source) });
|
|
6
|
+
} catch (error) {
|
|
7
|
+
parentPort!.postMessage({ error: error instanceof Error ? error.message : String(error) });
|
|
8
|
+
}
|
package/src/ui/inbox.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
import type { InboxItem } from "@staix/agent-console/contract";
|
|
3
|
+
import type { VaultSpec } from "../config.ts";
|
|
4
|
+
import type { InboxSource } from "./inbox-source.ts";
|
|
5
|
+
|
|
6
|
+
const CACHE_MS = 60_000;
|
|
7
|
+
const FIRST_WAIT_MS = 700;
|
|
8
|
+
const SOURCE_MS = 30_000;
|
|
9
|
+
// agent-mem has no total-count API; a saturated candidate source can only report a lower bound.
|
|
10
|
+
export type InboxRows = { items: InboxItem[]; more: number; moreIsLowerBound?: boolean };
|
|
11
|
+
|
|
12
|
+
function readInboxRows(value: unknown): InboxRows {
|
|
13
|
+
if (!value || typeof value !== "object" || !("items" in value) || !Array.isArray(value.items)
|
|
14
|
+
|| !("more" in value) || typeof value.more !== "number" || !Number.isSafeInteger(value.more) || value.more < 0) {
|
|
15
|
+
throw new Error("inbox source returned no valid result; inspect System and restart the console provider");
|
|
16
|
+
}
|
|
17
|
+
return value as InboxRows;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** An explicit error is a failure even when its message is empty. */
|
|
21
|
+
export function readInboxWorkerMessage(message: unknown): InboxRows {
|
|
22
|
+
if (message && typeof message === "object" && "error" in message) {
|
|
23
|
+
throw new Error(typeof message.error === "string" && message.error ? message.error
|
|
24
|
+
: "inbox source failed without an error message; inspect System and retry");
|
|
25
|
+
}
|
|
26
|
+
return readInboxRows(message && typeof message === "object" && "result" in message ? message.result : undefined);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Urgent rows precede candidates; newest candidates first. Never ship full lint reports or memory bodies. */
|
|
30
|
+
export function boundInbox(items: InboxItem[], more = 0, moreIsLowerBound = false): InboxRows {
|
|
31
|
+
const rank = (i: InboxItem) => {
|
|
32
|
+
if (i.chip?.tone === "err") return 0;
|
|
33
|
+
if (i.group === "alert") return 1;
|
|
34
|
+
return 2;
|
|
35
|
+
};
|
|
36
|
+
const clip = (value: string, limit: number) => {
|
|
37
|
+
let out = "", count = 0;
|
|
38
|
+
for (const point of value) { if (count++ === limit) break; out += point; }
|
|
39
|
+
return out;
|
|
40
|
+
};
|
|
41
|
+
const sorted = [...items].sort((a, b) => rank(a) - rank(b) || b.at.localeCompare(a.at) || a.id.localeCompare(b.id));
|
|
42
|
+
return { items: sorted.slice(0, 50).map(i => ({ ...i, title: clip(i.title, 160), ...(i.detail ? { detail: clip(i.detail, 240) } : {}) })),
|
|
43
|
+
more: more + Math.max(0, items.length - 50), ...(moreIsLowerBound ? { moreIsLowerBound: true } : {}) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Workers isolate synchronous lint, SQLite and Git from requests. The deadline initiates termination;
|
|
47
|
+
* shutdown can still wait for a blocking native call, so the queue waits before starting another worker. */
|
|
48
|
+
export function runInboxSource(home: string, source: InboxSource): { result: Promise<InboxRows>; cancel: () => void } {
|
|
49
|
+
const panel = { candidates: "Promote", lint: "Lint", sync: "Overview" }[source.kind];
|
|
50
|
+
const worker = new Worker(new URL("./inbox-worker.ts", import.meta.url), { workerData: { home, source }, env: { ...process.env } });
|
|
51
|
+
let cancel = () => {};
|
|
52
|
+
const result = new Promise<InboxRows>((resolve, reject) => {
|
|
53
|
+
let settled = false;
|
|
54
|
+
const finish = (error?: Error, rows?: InboxRows) => {
|
|
55
|
+
if (settled) return;
|
|
56
|
+
settled = true; clearTimeout(timer);
|
|
57
|
+
void worker.terminate().then(() => {
|
|
58
|
+
if (error) reject(error); else resolve(rows!);
|
|
59
|
+
}, failure => reject(failure));
|
|
60
|
+
};
|
|
61
|
+
const timer = setTimeout(() => finish(new Error(`inbox ${source.kind} timed out after 30 s; inspect ${panel} and System, then retry`)), SOURCE_MS);
|
|
62
|
+
cancel = () => finish(new Error("inbox closed"));
|
|
63
|
+
worker.once("message", (message: unknown) => {
|
|
64
|
+
try { finish(undefined, readInboxWorkerMessage(message)); }
|
|
65
|
+
catch (error) { finish(error instanceof Error ? error : new Error(String(error))); }
|
|
66
|
+
});
|
|
67
|
+
worker.once("error", error => finish(error instanceof Error ? error : new Error(String(error))));
|
|
68
|
+
worker.once("exit", code => finish(new Error(`inbox worker exited (${code}); inspect System and restart the console provider`)));
|
|
69
|
+
});
|
|
70
|
+
return { result, cancel: () => cancel() };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
type Runner = typeof runInboxSource;
|
|
74
|
+
export function createInboxSnapshot(home: string, vaults: VaultSpec[], log: (message: string) => void, run: Runner = runInboxSource) {
|
|
75
|
+
const sources: InboxSource[] = [...vaults.filter(v => v.kind === "org").map(vault => ({ kind: "sync" as const, vault })),
|
|
76
|
+
...vaults.filter(v => v.kind === "personal").map(vault => ({ kind: "lint" as const, vault })), { kind: "candidates" }];
|
|
77
|
+
const rows = new Map<number, InboxRows>(), firstSeen = new Map<string, string>();
|
|
78
|
+
let cached: InboxRows | undefined, flight: Promise<void> | undefined, at = -Infinity, revision = 0, closed = false;
|
|
79
|
+
let cancel: (() => void) | undefined;
|
|
80
|
+
const statusAt = new Date().toISOString();
|
|
81
|
+
const status = (unavailable: boolean): InboxRows => ({ items: [{
|
|
82
|
+
id: unavailable ? "inbox:unavailable" : "inbox:refresh", group: "alert", kind: "status",
|
|
83
|
+
title: unavailable ? "Vault inbox is unavailable" : "Vault inbox is refreshing",
|
|
84
|
+
detail: unavailable ? "Inspect System, then retry." : "The first collection is running; check again shortly.",
|
|
85
|
+
at: statusAt, verbs: [], link: { panel: "overview" },
|
|
86
|
+
}], more: 0 });
|
|
87
|
+
function refresh() {
|
|
88
|
+
if (closed || flight || Date.now() - at < CACHE_MS) return;
|
|
89
|
+
const started = revision;
|
|
90
|
+
flight = (async () => {
|
|
91
|
+
// One worker at a time, including failed sources. A source's deadline covers its entire expensive step.
|
|
92
|
+
for (const [index, source] of sources.entries()) {
|
|
93
|
+
if (closed) return;
|
|
94
|
+
try {
|
|
95
|
+
const job = run(home, source); cancel = job.cancel;
|
|
96
|
+
rows.set(index, readInboxRows(await job.result));
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if (!closed) log(`vmem: ${source.kind === "sync" ? "sync pending" : source.kind}${"vault" in source ? ` ${source.vault.id}` : ""} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
99
|
+
} finally { cancel = undefined; }
|
|
100
|
+
}
|
|
101
|
+
if (closed) return;
|
|
102
|
+
const all = [...rows.values()].flatMap(r => r.items);
|
|
103
|
+
for (const item of all) if (item.group === "alert") {
|
|
104
|
+
item.at = firstSeen.get(item.id) ?? item.at; firstSeen.set(item.id, item.at);
|
|
105
|
+
}
|
|
106
|
+
const ids = new Set(all.map(i => i.id));
|
|
107
|
+
for (const id of firstSeen.keys()) if (!ids.has(id)) firstSeen.delete(id);
|
|
108
|
+
cached = rows.size === 0 ? status(true) : boundInbox(all, [...rows.values()].reduce((n, r) => n + r.more, 0), [...rows.values()].some(r => r.moreIsLowerBound));
|
|
109
|
+
// An action during collection makes the next poll refresh again, without erasing the last rows.
|
|
110
|
+
at = started === revision ? Date.now() : -Infinity;
|
|
111
|
+
})().catch(error => {
|
|
112
|
+
// Warm snapshots do not await this promise. Never let a refresh failure escape to the console.
|
|
113
|
+
if (!closed) {
|
|
114
|
+
cached ??= status(true);
|
|
115
|
+
at = started === revision ? Date.now() : -Infinity;
|
|
116
|
+
try { log(`vmem: inbox refresh failed: ${error instanceof Error ? error.message : String(error)}; inspect System and retry`); }
|
|
117
|
+
catch { /* A failed log sink must not create another unhandled rejection. */ }
|
|
118
|
+
}
|
|
119
|
+
}).finally(() => { flight = undefined; });
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
async snapshot(): Promise<InboxRows & { refreshing?: boolean }> {
|
|
123
|
+
refresh();
|
|
124
|
+
if (!cached && flight) {
|
|
125
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
126
|
+
await Promise.race([flight, new Promise<void>(resolve => { timer = setTimeout(resolve, FIRST_WAIT_MS); })]);
|
|
127
|
+
clearTimeout(timer);
|
|
128
|
+
}
|
|
129
|
+
return { ...(cached ?? status(false)), ...(flight ? { refreshing: true } : {}) };
|
|
130
|
+
},
|
|
131
|
+
invalidate() { revision++; at = -Infinity; },
|
|
132
|
+
async close() { closed = true; cancel?.(); await flight; },
|
|
133
|
+
};
|
|
134
|
+
}
|
package/src/ui/plugin.ts
CHANGED
|
@@ -3,15 +3,14 @@
|
|
|
3
3
|
* The provider reuses the `vmem mcp` handlers in process, so the console acts with exactly the MCP rights and checks.
|
|
4
4
|
*/
|
|
5
5
|
import { readFileSync } from "node:fs";
|
|
6
|
-
import type { ActionResult, Change, ConsolePlugin, ConsoleProvider
|
|
6
|
+
import type { ActionResult, Change, ConsolePlugin, ConsoleProvider } from "@staix/agent-console/contract";
|
|
7
7
|
import { analysisInput } from "../analysis-input.ts";
|
|
8
8
|
import { resolveHome } from "../home.ts";
|
|
9
9
|
import { createVaultMcp } from "../mcp-vault.ts";
|
|
10
10
|
import { validArguments } from "../mcp.ts";
|
|
11
11
|
import { listPromotionCandidates } from "../promote.ts";
|
|
12
12
|
import { loadRegistry } from "../registry.ts";
|
|
13
|
-
import {
|
|
14
|
-
import { isDenied } from "../platform.ts";
|
|
13
|
+
import { createInboxSnapshot } from "./inbox.ts";
|
|
15
14
|
import { lintVault } from "../vault-lint.ts";
|
|
16
15
|
import { readLogSince } from "../vault-log.ts";
|
|
17
16
|
import type { LintCode } from "../analysis-types.ts";
|
|
@@ -123,7 +122,7 @@ export const plugin: ConsolePlugin = {
|
|
|
123
122
|
return validArguments(out, schema ?? { type: "object" }) ? out : `invalid input for ${tool}`;
|
|
124
123
|
};
|
|
125
124
|
|
|
126
|
-
//
|
|
125
|
+
// The Lint panel reuses its report for 60 s; inbox collection has its own off-thread cache.
|
|
127
126
|
const lintCache = new Map<string, { at: number; report: ReturnType<typeof lintVault> }>();
|
|
128
127
|
const lint = (id: string) => {
|
|
129
128
|
const hit = lintCache.get(id);
|
|
@@ -133,22 +132,6 @@ export const plugin: ConsolePlugin = {
|
|
|
133
132
|
lintCache.set(id, { at: Date.now(), report });
|
|
134
133
|
return report;
|
|
135
134
|
};
|
|
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
|
-
};
|
|
152
135
|
const projectOf = new Map<string, string>();
|
|
153
136
|
const candidates = async () => {
|
|
154
137
|
try {
|
|
@@ -159,40 +142,7 @@ export const plugin: ConsolePlugin = {
|
|
|
159
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" }; }
|
|
160
143
|
};
|
|
161
144
|
|
|
162
|
-
|
|
163
|
-
const firstSeen = new Map<string, string>();
|
|
164
|
-
const since = (id: string) => { const at = firstSeen.get(id) ?? new Date().toISOString(); firstSeen.set(id, at); return at; };
|
|
165
|
-
async function inbox(): Promise<InboxItem[]> {
|
|
166
|
-
const items: InboxItem[] = [];
|
|
167
|
-
for (const p of (await candidates()).projects) for (const c of p.candidates) items.push({
|
|
168
|
-
id: `mem:${c.id}`, group: "candidate", kind: "promotion", title: c.title ?? c.kind, detail: `${c.kind} memory to promote into a vault note`,
|
|
169
|
-
project: c.project, at: new Date(c.at).toISOString(),
|
|
170
|
-
// Promotion needs a domain and topics, so the item opens the Promote panel instead of offering a one-key verb.
|
|
171
|
-
verbs: [],
|
|
172
|
-
link: { panel: "promote", params: { id: c.id, project: c.project } },
|
|
173
|
-
});
|
|
174
|
-
for (const v of mcp.vaults.filter(x => x.kind === "personal")) {
|
|
175
|
-
let report;
|
|
176
|
-
try { report = lint(v.id); } catch (error) { ctx.log(`vmem: lint ${v.id} failed: ${error instanceof Error ? error.message : String(error)}`); continue; }
|
|
177
|
-
if (report.errors > 0) items.push({ id: `lint:${v.id}`, group: "alert", kind: "lint", title: `${report.errors} lint errors in ${v.id}`, detail: report.summary, at: since(`lint:${v.id}`),
|
|
178
|
-
chip: { text: `${report.errors} errors`, tone: "err" }, verbs: [], link: { panel: "lint", params: { vault: v.id } } });
|
|
179
|
-
const stale = report.findings.L11 ?? [];
|
|
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}`),
|
|
181
|
-
chip: { text: "stale", tone: "warn" }, verbs: [], link: { panel: "lint", params: { vault: v.id } } });
|
|
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
|
-
}
|
|
193
|
-
for (const id of firstSeen.keys()) if (!items.some(i => i.id === id)) firstSeen.delete(id);
|
|
194
|
-
return items;
|
|
195
|
-
}
|
|
145
|
+
const inbox = createInboxSnapshot(home, mcp.vaults, ctx.log);
|
|
196
146
|
|
|
197
147
|
/** One two-step operation: preview, and with the console's confirmation recompute and write only on the same fingerprint. */
|
|
198
148
|
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> {
|
|
@@ -204,16 +154,17 @@ export const plugin: ConsolePlugin = {
|
|
|
204
154
|
return { ok: false, needsConfirm: true, fingerprint: preview.fingerprint, verb: d.verb, preview: d.preview, changes: d.changes, ...(d.warnings.length ? { warnings: d.warnings } : {}) };
|
|
205
155
|
}
|
|
206
156
|
const done = await call(tool, { ...args, confirm: true, fingerprint });
|
|
207
|
-
if (done.applied === true) lintCache.clear();
|
|
157
|
+
if (done.applied === true) { lintCache.clear(); inbox.invalidate(); }
|
|
208
158
|
return confirmedOutcome(done, describe(preview).verb);
|
|
209
159
|
}
|
|
210
160
|
|
|
211
161
|
return {
|
|
162
|
+
async close() { await inbox.close(); },
|
|
212
163
|
assets: { js: asset("./panel.js"), css: asset("./panel.css") },
|
|
213
164
|
async snapshot(input) {
|
|
214
165
|
const args = input as Args;
|
|
215
166
|
switch (input.panel) {
|
|
216
|
-
case "inbox": return
|
|
167
|
+
case "inbox": return inbox.snapshot();
|
|
217
168
|
case "search": {
|
|
218
169
|
const q = str(args.q);
|
|
219
170
|
if (!q) return { hits: [], total: 0 };
|