@staix/vault-mem 0.12.1 → 0.13.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 +18 -0
- package/README.md +3 -1
- package/package.json +1 -1
- package/skills/skill-mine/SKILL.md +2 -0
- package/src/assertion-coverage.ts +26 -0
- package/src/assertions-command.ts +2 -2
- package/src/assertions.ts +20 -14
- package/src/mcp-vault.ts +19 -2
- package/src/skills-mine.ts +22 -7
- package/src/ui/graph-snapshot.ts +91 -0
- package/src/ui/panel-types.ts +24 -17
- package/src/ui/panel.js +10 -0
- package/src/ui/plugin.ts +71 -2
- package/src/vault-graph.ts +50 -1
- package/src/writer.ts +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.13.1] - 2026-11-22
|
|
6
|
+
|
|
7
|
+
- Add directed `supersedes` and `superseded_by` frontmatter edges to Graph console snapshots. CLI and MCP graph outputs keep their existing behavior.
|
|
8
|
+
|
|
9
|
+
- Add an opt-in two-step mode to `vmem_link` (`preview`, `confirm`, `fingerprint`; a stale fingerprint returns a fresh preview) and a console `link` action that previews both notes, the relation and the log event before confirming; an existing link is a no-op. Calls without `preview` or `confirm` write in one step as before.
|
|
10
|
+
|
|
11
|
+
## [0.13.0] - 2026-11-22
|
|
12
|
+
|
|
13
|
+
- N-1: 0.12.1 and 0.13.0 share the note and spec index files and config format 6. The 0.13.0 CLI adds assertion coverage lines and changes skills-mine filtering and cap reporting; the 0.12.1 CLI keeps its previous behavior. MCP tool names and arguments are unchanged; `vmem_assertions` coverage and `vmem_skills_mine` dropped counts gain additive fields, which 0.12.1 clients may ignore; for an unsupported entry inside an incomplete batch, `coverage.unsupported[].seq` now identifies the first excluded batch entry, as `untrusted[].seq` already did. In 0.12.1 it identifies the unsupported line; `failedSeq` now retains that value. The 0.13.0 console provider adds the Graph panel; an older provider remains usable without it.
|
|
14
|
+
|
|
15
|
+
- Fixed: assertion coverage counts excluded entries per damaged segment and partial batch, and shows the same coverage messages in CLI text and the console.
|
|
16
|
+
|
|
17
|
+
- Fixed: the Graph panel says no vault is selected when none is, instead of an empty unknown-vault id, and offers First page next to a page error.
|
|
18
|
+
|
|
19
|
+
- Add a Graph console panel with revision-bound, byte-bounded snapshot pages, unresolved-link placeholders, and existing neighborhood and path queries.
|
|
20
|
+
|
|
21
|
+
- `vmem skills mine` skips host-injected `UserPromptSubmit` envelopes (`<task-notification>`, `<channel `, `<agent-message `), counted as `dropped.synthetic`, and no longer fails over 20,000 records or 64 MiB: it keeps the newest records, counts the rest in `dropped.overCap` and names the narrowing step in the report. CLI flags and MCP arguments are unchanged.
|
|
22
|
+
|
|
5
23
|
## [0.12.1] - 2026-11-22
|
|
6
24
|
|
|
7
25
|
- Add the bundled `vault-enrich` skill for hash-bound offline enrichment intake, review and reconciliation.
|
package/README.md
CHANGED
|
@@ -81,7 +81,7 @@ Each installed directory has a `.vmem-skill.json` ownership marker with its pack
|
|
|
81
81
|
|
|
82
82
|
## Library
|
|
83
83
|
|
|
84
|
-
The only runtime dependency is the first-party range <!-- facts:amem-pin -->`@staix/agent-mem@>=0.33.0 <1.0.0`<!-- /facts:amem-pin -->; host API 1 is checked at load before any agent-mem store opens. Registry commands do not load the agent-mem root. New compatible minors are resolved on installation or update; an existing installation keeps its resolved version. Public library exports (`@staix/vault-mem`, from `src/index.ts`) cover configuration and home resolution, registry operations, frontmatter, link resolution and the derived index, validated writes, the append-only log, the MCP server and its vault tools, host setup, the CLI command table and completion, promotion from agent-mem and to org vaults, lint and graph analysis, sync, source references, migration tidy, the temporal assertion journal and its evaluation, and the spec source registry, graph, validation and freshness. `@staix/vault-mem/ui-plugin` is the console plugin entry, with panels for proposals (list, show, apply, reject), assertions and note history and changes, and their snapshot types (see [Console plugin](docs/reference/mcp-and-setup.md#console-plugin)). No console bin is shipped. Exported functions and constants by module:
|
|
84
|
+
The only runtime dependency is the first-party range <!-- facts:amem-pin -->`@staix/agent-mem@>=0.33.0 <1.0.0`<!-- /facts:amem-pin -->; host API 1 is checked at load before any agent-mem store opens. Registry commands do not load the agent-mem root. New compatible minors are resolved on installation or update; an existing installation keeps its resolved version. Public library exports (`@staix/vault-mem`, from `src/index.ts`) cover configuration and home resolution, registry operations, frontmatter, link resolution and the derived index, validated writes, the append-only log, the MCP server and its vault tools, host setup, the CLI command table and completion, promotion from agent-mem and to org vaults, lint and graph analysis, sync, source references, migration tidy, the temporal assertion journal and its evaluation, and the spec source registry, graph, validation and freshness. `@staix/vault-mem/ui-plugin` is the console plugin entry, with panels for graph snapshots, proposals (list, show, apply, reject), assertions and note history and changes, and their snapshot types (see [Console plugin](docs/reference/mcp-and-setup.md#console-plugin)). No console bin is shipped. Exported functions and constants by module:
|
|
85
85
|
<!-- facts:exports -->
|
|
86
86
|
|
|
87
87
|
- `src/assertion-read.ts`: `readAssertions`, `ASSERTIONS_PAGE_LIMIT`
|
|
@@ -124,6 +124,8 @@ The only runtime dependency is the first-party range <!-- facts:amem-pin -->`@st
|
|
|
124
124
|
|
|
125
125
|
<!-- /facts:exports -->
|
|
126
126
|
|
|
127
|
+
The `./ui-plugin` entry also exports `GraphSnapshotPage`, `GraphPanelPage`, `GraphNodeColumns` and `GraphEdgeColumns`.
|
|
128
|
+
|
|
127
129
|
## Development
|
|
128
130
|
|
|
129
131
|
```sh
|
package/package.json
CHANGED
|
@@ -31,6 +31,8 @@ vmem skills mine <vault> --days 30 \
|
|
|
31
31
|
|
|
32
32
|
- MCP만 있으면 `vmem_skills_mine`에 `vault`, `days`, `vocab`, `skills`를 전달한다. amem 데이터가 없으면 이용 가능한 vault 노트로 실행하고 누락된 입력을 보고한다.
|
|
33
33
|
- 입력: amem curated(decision·finding·contract·fail), amem capture(사용자 프롬프트·observation·summary), vault 노트(person·moc·reference 제외). 기간은 `--days`(기본 30), 프로젝트는 기본 전체이고 `--project <key>`로 좁힌다.
|
|
34
|
+
- 호스트가 `UserPromptSubmit`으로 주입한 합성 프롬프트(`<task-notification>`, `<channel `, `<agent-message `로 시작)는 사람 프롬프트가 아니므로 제외되고 리포트 `dropped:` 줄의 `synthetic N`으로 집계된다.
|
|
35
|
+
- 상한(20,000건·총 64 MiB)을 넘으면 실패하지 않고 최신 레코드만 남긴다. 리포트 머리의 `over cap:` 줄이 남긴 건수와 제외한 건수를 알려 준다. 그 줄이 보이면 `--days`를 줄이거나 `--project <key>`로 프로젝트별로 나눠 다시 실행한다.
|
|
34
36
|
- 표준출력이 리포트 본문(markdown)이다. `--json`은 후보·점수·출처별 건수를 구조화해 돌려준다. MCP에서는 `vmem_skills_mine`.
|
|
35
37
|
- workspace가 있으면 리포트를 `<workspace-root>/_meta/reports/skill-candidates-YYMMDD.md`로 저장한다. 없으면 사용자에게 결과를 보여주고 workspace 저장을 건너뛰었다고 보고한다. 같은 날 재실행은 덮어쓴다.
|
|
36
38
|
- `--skills`는 novelty 비교용 기존 스킬 카탈로그다. 사용 가능한 호스트 스킬 설치 디렉토리를 반복해서 넘긴다.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { AssertionsReadResult } from "./assertion-read.ts";
|
|
2
|
+
|
|
3
|
+
export interface CoverageWarning { tone: "err" | "warn" | "neutral"; message: string }
|
|
4
|
+
|
|
5
|
+
/** Describe coverage once for both the console and the CLI. */
|
|
6
|
+
export function assertionCoverageWarnings(coverage: AssertionsReadResult["coverage"] | undefined): CoverageWarning[] {
|
|
7
|
+
if (!coverage) return [];
|
|
8
|
+
const out: CoverageWarning[] = [];
|
|
9
|
+
if (coverage.untrusted.length) {
|
|
10
|
+
const count = coverage.untrusted.reduce((n, item) => n + item.entries, 0);
|
|
11
|
+
const details = coverage.untrusted.slice(0, 3).map(u => `${u.segment}#${u.seq}, failed #${u.failedSeq}, ${u.entries} left out: ${u.reason}`).join("; ");
|
|
12
|
+
out.push({ tone: "err", message: `${count} journal ${count === 1 ? "entry is" : "entries are"} untrusted and left out (${details}); run \`vmem assertions <vault> --history --json\` and inspect the journal segments` });
|
|
13
|
+
}
|
|
14
|
+
if (coverage.unsupported.length) {
|
|
15
|
+
const count = coverage.unsupported.reduce((n, item) => n + item.entries, 0);
|
|
16
|
+
const details = coverage.unsupported.slice(0, 3).map(u => `${u.segment}#${u.seq}, failed #${u.failedSeq}, ${u.entries} left out`).join("; ");
|
|
17
|
+
out.push({ tone: "warn", message: `${count} journal ${count === 1 ? "entry is" : "entries are"} left out after an unsupported schema (${details}); upgrade vmem to read them` });
|
|
18
|
+
}
|
|
19
|
+
if (coverage.tornTail.length) out.push({ tone: "warn", message: `torn journal tail in ${coverage.tornTail.join(", ")}: the incomplete last entry is ignored; the next append repairs it` });
|
|
20
|
+
for (const batch of coverage.partialBatch) out.push({ tone: "warn", message: `batch ${batch.segment}:${batch.seq} has ${batch.entries} of ${batch.size} entries; all ${batch.entries} are left out; resubmit the batch` });
|
|
21
|
+
if (coverage.purged) out.push({ tone: "neutral", message: `${coverage.purged} purged ${coverage.purged === 1 ? "payload is" : "payloads are"} not shown` });
|
|
22
|
+
if (coverage.unsynced) out.push({ tone: "warn", message: `${coverage.unsynced} assertion ${coverage.unsynced === 1 ? "file is" : "files are"} not committed; run \`vmem sync\` to share them` });
|
|
23
|
+
if (coverage.unsynced === null) out.push({ tone: "neutral", message: "journal sync state is unknown (no Git repository or Git unavailable)" });
|
|
24
|
+
if (coverage.indexIssue) out.push({ tone: "warn", message: coverage.indexIssue });
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** CLI surface for the shared assertion read provider. */
|
|
2
2
|
import { readAssertions } from "./assertion-read.ts";
|
|
3
|
+
import { assertionCoverageWarnings } from "./assertion-coverage.ts";
|
|
3
4
|
import { scanAssertionExposure, writeReplaceFile, type ExposureReceipt } from "./assertion-exposure.ts";
|
|
4
5
|
import { purgeAssertions, type PurgeReceipt } from "./assertions.ts";
|
|
5
6
|
import { blocks, clean, heading, issueTable, nextCommand, paragraph, plural, status, table, PLAIN, UsageError, type TextOptions } from "./text-output.ts";
|
|
@@ -34,8 +35,7 @@ export function runAssertionsCommand(args: string[], home: string, env: NodeJS.P
|
|
|
34
35
|
const rows = result.items.map(item => [clean(item.subject), clean(item.relation), item.answer ?? "-", typeof item.value === "string" ? clean(item.value) : item.value ? "withheld" : "-", item.id]);
|
|
35
36
|
return { text: blocks(heading(`Assertions in ${clean(result.vault)}`, text), table(["SUBJECT", "RELATION", "ANSWER", "VALUE", "ID"], rows, text),
|
|
36
37
|
result.truncated ? status("pending", `more results: rerun with --cursor ${result.continuation}`, text) : status("ok", `${result.items.length} assertion(s) shown`, text),
|
|
37
|
-
result.coverage.
|
|
38
|
-
result.coverage.indexIssue ? status("warn", result.coverage.indexIssue, text) : undefined), code: 0 };
|
|
38
|
+
...assertionCoverageWarnings(result.coverage).map(w => status(w.tone === "err" ? "fail" : w.tone === "warn" ? "warn" : "unknown", w.message, text))), code: 0 };
|
|
39
39
|
}
|
|
40
40
|
|
|
41
41
|
/** What a purge receipt means in words; `argv` is the command without `vmem`, so the confirm line is pasteable. */
|
package/src/assertions.ts
CHANGED
|
@@ -63,9 +63,9 @@ export interface SegmentReport {
|
|
|
63
63
|
verifiedBytes: number;
|
|
64
64
|
size: number;
|
|
65
65
|
tornTail: boolean;
|
|
66
|
-
partialBatch: { seq: number } | null;
|
|
67
|
-
untrusted: { seq: number; reason: string } | null;
|
|
68
|
-
unsupported: { seq: number; version: unknown } | null;
|
|
66
|
+
partialBatch: { seq: number; entries: number; size: number } | null;
|
|
67
|
+
untrusted: { seq: number; failedSeq: number; entries: number; reason: string } | null;
|
|
68
|
+
unsupported: { seq: number; failedSeq: number; entries: number; version: unknown } | null;
|
|
69
69
|
}
|
|
70
70
|
export interface VerifiedJournal { present: boolean; segments: SegmentReport[]; ignored: string[]; bytes: number; entries: number }
|
|
71
71
|
|
|
@@ -86,8 +86,8 @@ export interface AssertionAnswerSet {
|
|
|
86
86
|
pin: { segment: string; seq: number; hash: string }[];
|
|
87
87
|
coverage: {
|
|
88
88
|
journal: "present" | "absent"; beforeFirstEntry: boolean;
|
|
89
|
-
untrusted: { segment: string; seq: number; reason: string }[]; unsupported: { segment: string; seq: number }[];
|
|
90
|
-
tornTail: string[]; partialBatch: { segment: string; seq: number }[]; purged: number;
|
|
89
|
+
untrusted: { segment: string; seq: number; failedSeq: number; entries: number; reason: string }[]; unsupported: { segment: string; seq: number; failedSeq: number; entries: number }[];
|
|
90
|
+
tornTail: string[]; partialBatch: { segment: string; seq: number; entries: number; size: number }[]; purged: number;
|
|
91
91
|
};
|
|
92
92
|
items: AssertionItem[];
|
|
93
93
|
overlaps: { subject: string; relation: string; ids: string[]; possible?: true }[];
|
|
@@ -218,12 +218,12 @@ export function verifySegment(segment: string, bytes: Buffer): SegmentReport {
|
|
|
218
218
|
const newline = bytes.indexOf(10, offset);
|
|
219
219
|
if (newline < 0) { report.tornTail = true; break; }
|
|
220
220
|
const seq = report.entries.length + pending.length + 1, raw = bytes.subarray(offset, newline);
|
|
221
|
-
const fail = (reason: string) => { report.untrusted = { seq, reason }; };
|
|
221
|
+
const fail = (reason: string) => { report.untrusted = { seq, failedSeq: seq, entries: 0, reason }; };
|
|
222
222
|
let entry: JournalEntry;
|
|
223
223
|
try {
|
|
224
224
|
const text = decoder.decode(raw), parsed = JSON.parse(text) as Record<string, unknown>;
|
|
225
225
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { fail("not an object"); break; }
|
|
226
|
-
if (parsed.v !== ASSERTION_SCHEMA_VERSION) { report.unsupported = { seq, version: parsed.v }; break; }
|
|
226
|
+
if (parsed.v !== ASSERTION_SCHEMA_VERSION) { report.unsupported = { seq, failedSeq: seq, entries: 0, version: parsed.v }; break; }
|
|
227
227
|
if (canonical(parsed) !== text) { fail("not canonical JSON"); break; }
|
|
228
228
|
const problem = shapeProblem(parsed);
|
|
229
229
|
if (problem) { fail(problem); break; }
|
|
@@ -248,8 +248,14 @@ export function verifySegment(segment: string, bytes: Buffer): SegmentReport {
|
|
|
248
248
|
report.entries.push(...pending.map(item => item.entry)); report.verifiedBytes = offset; pending = [];
|
|
249
249
|
}
|
|
250
250
|
}
|
|
251
|
-
if (pending.length && !report.untrusted && !report.unsupported) report.partialBatch = { seq: pending[0]!.entry.seq };
|
|
252
|
-
|
|
251
|
+
if (pending.length && !report.untrusted && !report.unsupported) report.partialBatch = { seq: pending[0]!.entry.seq, entries: pending.length, size: pending[0]!.entry.batch.size };
|
|
252
|
+
if (report.untrusted || report.unsupported) {
|
|
253
|
+
let entries = 0;
|
|
254
|
+
for (let i = report.verifiedBytes; i < bytes.length; i++) if (bytes[i] === 10) entries++;
|
|
255
|
+
const failure = report.untrusted ?? report.unsupported!;
|
|
256
|
+
failure.entries = entries;
|
|
257
|
+
if (pending.length) failure.seq = pending[0]!.entry.seq;
|
|
258
|
+
}
|
|
253
259
|
const tail = report.entries.at(-1);
|
|
254
260
|
if (tail) report.tail = { seq: tail.seq, hash: tail.hash, recordedAt: tail.recorded_at };
|
|
255
261
|
return report;
|
|
@@ -289,7 +295,7 @@ export function readJournal(vaultPath: string, denyPaths: readonly string[] = []
|
|
|
289
295
|
|
|
290
296
|
/** `depth` is the longest parent chain below the entry, so a parent always sorts before its child. */
|
|
291
297
|
interface Kept { entry: JournalEntry; effective: string; inverted: boolean; depth: number; assertionId?: string }
|
|
292
|
-
interface Resolved { kept: Map<string, Kept>; untrusted: { segment: string; seq: number; reason: string }[] }
|
|
298
|
+
interface Resolved { kept: Map<string, Kept>; untrusted: { segment: string; seq: number; failedSeq: number; entries: number; reason: string }[] }
|
|
293
299
|
/** Steps 2: effective record times across segments; an entry whose parent is missing, untrusted or foreign is untrusted. */
|
|
294
300
|
function resolveEntries(journal: VerifiedJournal): Resolved {
|
|
295
301
|
const byHash = new Map<string, JournalEntry>();
|
|
@@ -321,7 +327,7 @@ function resolveEntries(journal: VerifiedJournal): Resolved {
|
|
|
321
327
|
const kept = new Map<string, Kept>(), untrusted: Resolved["untrusted"] = [];
|
|
322
328
|
for (const segment of journal.segments) for (const entry of segment.entries) {
|
|
323
329
|
const result = resolve(entry);
|
|
324
|
-
if (typeof result === "string") untrusted.push({ segment: entry.seg, seq: entry.seq, reason: result });
|
|
330
|
+
if (typeof result === "string") untrusted.push({ segment: entry.seg, seq: entry.seq, failedSeq: entry.seq, entries: 1, reason: result });
|
|
325
331
|
else kept.set(entry.hash, result);
|
|
326
332
|
}
|
|
327
333
|
return { kept, untrusted };
|
|
@@ -446,10 +452,10 @@ export function evaluateAssertions(journal: VerifiedJournal, query: AssertionQue
|
|
|
446
452
|
coverage: {
|
|
447
453
|
journal: journal.present ? "present" : "absent",
|
|
448
454
|
beforeFirstEntry: !!asOf && all.length > 0 && kept.length === 0,
|
|
449
|
-
untrusted: [...journal.segments.filter(s => s.untrusted).map(s => ({ segment: s.segment,
|
|
450
|
-
unsupported: journal.segments.filter(s => s.unsupported).map(s => ({ segment: s.segment, seq: s.unsupported!.seq })),
|
|
455
|
+
untrusted: [...journal.segments.filter(s => s.untrusted).map(s => ({ segment: s.segment, ...s.untrusted! })), ...resolved.untrusted],
|
|
456
|
+
unsupported: journal.segments.filter(s => s.unsupported).map(s => ({ segment: s.segment, seq: s.unsupported!.seq, failedSeq: s.unsupported!.failedSeq, entries: s.unsupported!.entries })),
|
|
451
457
|
tornTail: journal.segments.filter(s => s.tornTail).map(s => s.segment),
|
|
452
|
-
partialBatch: journal.segments.filter(s => s.partialBatch).map(s => ({ segment: s.segment,
|
|
458
|
+
partialBatch: journal.segments.filter(s => s.partialBatch).map(s => ({ segment: s.segment, ...s.partialBatch! })),
|
|
453
459
|
purged,
|
|
454
460
|
},
|
|
455
461
|
items, overlaps,
|
package/src/mcp-vault.ts
CHANGED
|
@@ -92,7 +92,7 @@ export function vaultTools(ids: readonly string[], orgIds: readonly string[] = [
|
|
|
92
92
|
tool("vmem_patch", "Replace exact strings in a note: one oldString/newString pair, or edits (1..32 pairs, each matching once in the original text, non-overlapping) applied all-or-nothing with one receipt and one log event.", object({ vault, path: note, oldString: string(8192), newString: string(8192, 0), edits: { type: "array", minItems: 1, maxItems: 32, items: object({ oldString: string(8192), newString: string(8192, 0) }, ["oldString", "newString"]) }, expectedSha: sha, log: logEvent }, ["path"]), "write"),
|
|
93
93
|
tool("vmem_append", "Append markdown to a section of a note.", object({ vault, path: note, section: string(120), markdown: string(16384), expectedSha: sha, log: logEvent }, ["path", "section", "markdown"]), "write"),
|
|
94
94
|
tool("vmem_set_frontmatter", "Set or unset frontmatter keys of a note.", object({ vault, path: note, set: metadata, unset: { type: "array", maxItems: 32, items: string(64) }, expectedSha: sha, log: logEvent }, ["path"]), "write"),
|
|
95
|
-
tool("vmem_link", "Add a typed relation link between two notes (bidirectional by default).", object({ vault, from: note, to: note, relation: { type: "string", enum: RELATIONS }, context: string(500), bidirectional: { type: "boolean" }, log: logEvent }, ["from", "to", "relation"]), "write"),
|
|
95
|
+
tool("vmem_link", "Add a typed relation link between two notes (bidirectional by default). One step by default. Opt-in two-step: preview=true returns the planned changes to each note, the log event and a fingerprint without writing; confirm=true with that fingerprint writes only while it still matches, otherwise a fresh preview (stale=true) is returned and nothing is written.", object({ vault, from: note, to: note, relation: { type: "string", enum: RELATIONS }, context: string(500), bidirectional: { type: "boolean" }, preview: { type: "boolean" }, ...twoStep, log: logEvent }, ["from", "to", "relation"]), "write"),
|
|
96
96
|
tool("vmem_supersede", "Mark a note superseded by another.", object({ vault, old: note, next: note, log: logEvent }, ["old", "next"]), "write"),
|
|
97
97
|
tool("vmem_log_append", "Append one validated event line to the vault log.", object({ vault, type: { type: "string", enum: LOG_TYPES }, project: string(64), source: string(512), dest: string(512), note: string(500) }, ["type", "project", "source", "note"]), "write"),
|
|
98
98
|
tool("vmem_move", "Two-step rename with link rewrites: without confirm returns preview and fingerprint; then confirm=true with that fingerprint (pass log on the confirm call).", object({ vault, from: note, to: note, ...twoStep, log: logEvent }, ["from", "to"]), "confirm"),
|
|
@@ -313,7 +313,24 @@ export function createVaultMcp(home: string, env: NodeJS.ProcessEnv = process.en
|
|
|
313
313
|
vmem_patch: args => write(args, { op: "patch", path: str(args.path)!, ...(args.oldString !== undefined ? { oldString: str(args.oldString) } : {}), ...(args.newString !== undefined ? { newString: str(args.newString) } : {}), ...(args.edits !== undefined ? { edits: args.edits as PatchEdit[] } : {}), expectedSha: str(args.expectedSha) }),
|
|
314
314
|
vmem_append: args => write(args, { op: "append", path: str(args.path)!, section: str(args.section)!, markdown: str(args.markdown)!, expectedSha: str(args.expectedSha) }),
|
|
315
315
|
vmem_set_frontmatter: args => write(args, { op: "frontmatter", path: str(args.path)!, set: (args.set as Record<string, unknown> | undefined) ?? {}, ...(args.unset ? { unset: args.unset as string[] } : {}), expectedSha: str(args.expectedSha) }),
|
|
316
|
-
vmem_link: args =>
|
|
316
|
+
vmem_link: args => {
|
|
317
|
+
const operation: WriteOp = { op: "link", from: str(args.from)!, to: str(args.to)!, relation: args.relation as Extract<WriteOp, { op: "link" }>["relation"], ...(str(args.context) ? { context: str(args.context) } : {}), bidirectional: args.bidirectional !== false };
|
|
318
|
+
if (args.confirm === true && !str(args.fingerprint)) throw new Error("link: confirm requires the preview fingerprint; request a preview with preview=true");
|
|
319
|
+
if (args.confirm !== true && args.fingerprint !== undefined) throw new Error("link: fingerprint requires confirm=true; request a new preview");
|
|
320
|
+
// The default log event the write would append; a given `log` replaces it.
|
|
321
|
+
const preview = (stale: boolean) => {
|
|
322
|
+
const receipt = write(args, operation, { dryRun: true });
|
|
323
|
+
if (!receipt.ok) return receipt;
|
|
324
|
+
const event = (args.log as LogEvent | undefined) ?? { type: "CONNECT", project: "-", source: notePath(operation.from), dest: notePath(operation.to), note: "link" };
|
|
325
|
+
return { ...receipt, logEvent: event, ...(stale ? { stale: true } : {}) };
|
|
326
|
+
};
|
|
327
|
+
if (args.confirm === true) {
|
|
328
|
+
const receipt = write(args, operation, twoStep(args));
|
|
329
|
+
const staleFingerprint = !receipt.ok && !receipt.applied && receipt.issues.length === 1 && receipt.issues[0]?.code === "V09" && /fingerprint/.test(receipt.issues[0].message);
|
|
330
|
+
return staleFingerprint ? preview(true) : receipt;
|
|
331
|
+
}
|
|
332
|
+
return args.preview === true ? preview(false) : write(args, operation);
|
|
333
|
+
},
|
|
317
334
|
vmem_supersede: args => write(args, { op: "supersede", old: str(args.old)!, next: str(args.next)! }),
|
|
318
335
|
vmem_log_append: args => {
|
|
319
336
|
const event: LogEvent = { type: str(args.type)!, project: str(args.project)!, source: str(args.source)!, note: str(args.note)!, ...(str(args.dest) ? { dest: str(args.dest) } : {}) };
|
package/src/skills-mine.ts
CHANGED
|
@@ -47,7 +47,7 @@ export interface MineOptions {
|
|
|
47
47
|
export interface MineResult {
|
|
48
48
|
vault: string; days: number; since: string; projects: string[];
|
|
49
49
|
records: Record<RecordSource, number>;
|
|
50
|
-
dropped: { secret: number; policy: number; oversized: number; duplicate: number; unreadable: number; truncatedCapture: number; malformedRecord: number;
|
|
50
|
+
dropped: { synthetic: number; overCap: number; secret: number; policy: number; oversized: number; duplicate: number; unreadable: number; truncatedCapture: number; malformedRecord: number;
|
|
51
51
|
recordOutsideWindow: number; recordOutsideCapped: number; recordOutsideUnavailable: number };
|
|
52
52
|
graph: { nodes: number; edges: number; communities: number; partitioner: "leiden" };
|
|
53
53
|
godNodes: { id: string; degree: number }[];
|
|
@@ -120,6 +120,14 @@ export function maskText(text: string, people: readonly string[]): string {
|
|
|
120
120
|
}
|
|
121
121
|
return masked;
|
|
122
122
|
}
|
|
123
|
+
/** Host runtimes inject these envelopes through UserPromptSubmit; they are not human prompts. */
|
|
124
|
+
const SYNTHETIC_PREFIXES = ["<task-notification>", "<task-notification ", "<channel ", "<agent-message "] as const;
|
|
125
|
+
/** True for a capture UserPromptSubmit record whose text, after leading whitespace, starts with a synthetic envelope. */
|
|
126
|
+
export function isSyntheticPrompt(record: Pick<MineRecord, "source" | "kind" | "text">): boolean {
|
|
127
|
+
if (record.source !== "capture" || record.kind !== "UserPromptSubmit") return false;
|
|
128
|
+
const text = record.text.trimStart();
|
|
129
|
+
return SYNTHETIC_PREFIXES.some(prefix => text.startsWith(prefix));
|
|
130
|
+
}
|
|
123
131
|
/** The vault config's `piiPatterns` (regular expressions, as everywhere in vmem) redact sample text from every source to `[PII]`. */
|
|
124
132
|
export function redactPatterns(text: string, patterns: readonly string[]): string {
|
|
125
133
|
let out = text;
|
|
@@ -320,24 +328,30 @@ export interface MineInputs {
|
|
|
320
328
|
vocab: { actions: VocabEntry[]; objects: VocabEntry[] }; registry: RegistryProject[]; skills: SkillEntry[];
|
|
321
329
|
minSize: number; minNovelty: number; today: string; piiPatterns?: string[];
|
|
322
330
|
dropped?: Partial<MineResult["dropped"]>;
|
|
331
|
+
/** Kept-set bounds; default MAX_RECORDS and MAX_TOTAL_BYTES. */
|
|
332
|
+
limits?: { records?: number; bytes?: number };
|
|
323
333
|
}
|
|
324
334
|
/** The pure part: screen, mask, match, cluster, score and render. */
|
|
325
335
|
export function mineRecords(input: MineInputs): MineResult {
|
|
326
|
-
const dropped: MineResult["dropped"] = { secret: 0, policy: 0, oversized: 0, duplicate: 0, unreadable: 0, truncatedCapture: 0, malformedRecord: 0, recordOutsideWindow: 0, recordOutsideCapped: 0, recordOutsideUnavailable: 0, ...input.dropped };
|
|
336
|
+
const dropped: MineResult["dropped"] = { synthetic: 0, overCap: 0, secret: 0, policy: 0, oversized: 0, duplicate: 0, unreadable: 0, truncatedCapture: 0, malformedRecord: 0, recordOutsideWindow: 0, recordOutsideCapped: 0, recordOutsideUnavailable: 0, ...input.dropped };
|
|
327
337
|
const ordered = [...input.records].sort((a, b) => compare(a.at, b.at) || compare(a.source, b.source) || compare(a.project, b.project) || compare(a.text, b.text));
|
|
328
|
-
const kept: MineRecord[] = [], texts = new Set<string>();
|
|
338
|
+
const kept: MineRecord[] = [], sizes: number[] = [], texts = new Set<string>();
|
|
329
339
|
let total = 0;
|
|
330
340
|
for (const record of ordered) {
|
|
341
|
+
if (isSyntheticPrompt(record)) { dropped.synthetic++; continue; }
|
|
331
342
|
const text = record.text.trim();
|
|
332
343
|
if (SECRET_PATTERNS.some(pattern => pattern.test(text))) { dropped.secret++; continue; }
|
|
333
344
|
const bytes = Buffer.byteLength(text);
|
|
334
345
|
if (bytes > MAX_RECORD_BYTES) { dropped.oversized++; continue; }
|
|
335
346
|
if (texts.has(text)) { dropped.duplicate++; continue; }
|
|
336
|
-
texts.add(text); kept.push({ ...record, text });
|
|
347
|
+
texts.add(text); kept.push({ ...record, text }); sizes.push(bytes);
|
|
337
348
|
total += bytes;
|
|
338
|
-
if (kept.length > MAX_RECORDS) throw new Error(`skills mine: more than ${MAX_RECORDS} records; narrow --days or --project`);
|
|
339
|
-
if (total > MAX_TOTAL_BYTES) throw new Error("skills mine: records exceed 64 MiB; narrow --days or --project");
|
|
340
349
|
}
|
|
350
|
+
// Over a bound, keep the newest records: `ordered` is oldest first, so leave out from the front.
|
|
351
|
+
const maxRecords = input.limits?.records ?? MAX_RECORDS, maxBytes = input.limits?.bytes ?? MAX_TOTAL_BYTES;
|
|
352
|
+
let cut = 0;
|
|
353
|
+
while (cut < kept.length && (kept.length - cut > maxRecords || total > maxBytes)) total -= sizes[cut++]!;
|
|
354
|
+
if (cut) { kept.splice(0, cut); dropped.overCap += cut; }
|
|
341
355
|
const index = buildSurfaceIndex(input.vocab.actions, input.vocab.objects, input.registry), people = allPeople(input.registry);
|
|
342
356
|
const recordIds = new Map<string, MineRecord>(), neighbors = new Map<string, Set<string>>(), edges: [string, string][] = [];
|
|
343
357
|
const width = String(kept.length).length;
|
|
@@ -398,7 +412,8 @@ export function renderReport(result: Omit<MineResult, "report">, today: string,
|
|
|
398
412
|
`# Skill Candidates (${today}, memory-based)`, "",
|
|
399
413
|
`- corpus: ${total} records / ${result.days} days (curated ${result.records.curated}, capture ${result.records.capture}, vault ${result.records.vault})`,
|
|
400
414
|
`- projects: ${result.projects.length}`,
|
|
401
|
-
`-
|
|
415
|
+
...(result.dropped.overCap ? [`- over cap: kept the newest ${total} records, left out ${result.dropped.overCap} older ones over the record or byte bound; narrow --days or --project to mine them`] : []),
|
|
416
|
+
`- dropped: synthetic ${result.dropped.synthetic}, secret ${result.dropped.secret}, policy ${result.dropped.policy}, oversized ${result.dropped.oversized}, duplicate ${result.dropped.duplicate}, unreadable ${result.dropped.unreadable}, malformed Record ${result.dropped.malformedRecord}`,
|
|
402
417
|
`- truncated capture machine shards: ${result.dropped.truncatedCapture}; rows of any event beyond maxReadRows were not read`,
|
|
403
418
|
`- Record rows outside the read window: ${result.dropped.recordOutsideCapped ? "at least " : ""}${result.dropped.recordOutsideWindow}${result.dropped.recordOutsideUnavailable ? `; ${result.dropped.recordOutsideUnavailable} truncated ${result.dropped.recordOutsideUnavailable === 1 ? "shard" : "shards"} could not be counted (no Record index yet, or no bounded index plan; an off-hook \`amem search\` in the project builds a missing index)` : ""}`,
|
|
404
419
|
`- graph: ${result.graph.nodes} nodes, ${result.graph.edges} edges, ${result.graph.communities} communities (deterministic Leiden)`, "",
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { AnalysisSnapshot } from "../analysis-types.ts";
|
|
3
|
+
import { scalarText } from "../analysis-yaml.ts";
|
|
4
|
+
import { buildGraph, collectUnresolvedGraph, collectSupersedesEdges, codePointCompare, graphFrontmatter, pythonTitle } from "../vault-graph.ts";
|
|
5
|
+
import type { GraphEdge } from "../vault-graph.ts";
|
|
6
|
+
import type { GraphSnapshotPage, GraphNodeColumns, GraphEdgeColumns } from "./panel-types.ts";
|
|
7
|
+
|
|
8
|
+
type NodeRow = { id: string; label: string; type: string | null; domain: string | null; source_file: string | null; community: number | null; degree: number; updated: string | null; date: string | null; placeholder: boolean; description: string | null; confidence: string | null; topics: string | null };
|
|
9
|
+
export type GraphEdgeRow = { source: number; target: number; relation: string; field: string | null; rel: string | null; confidence_tag: string; confidence: number };
|
|
10
|
+
export interface GraphSnapshotAssembly { vault: string; revision: string; pages: GraphSnapshotPage[] }
|
|
11
|
+
const MAX_BYTES = 1_048_576 - 32;
|
|
12
|
+
const MAX_NODES = 10_000, MAX_EDGES = 100_000;
|
|
13
|
+
const scalar = (v: unknown): string | null => scalarText(v) ?? (typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : null);
|
|
14
|
+
const token = (vault: string, revision: string, kind: string, offset: number): string => Buffer.from(JSON.stringify([1, vault, revision, kind, offset])).toString("base64url");
|
|
15
|
+
export const encodeGraphPage = (assembly: GraphSnapshotAssembly, page: GraphSnapshotPage): string => token(assembly.vault, assembly.revision, page.kind, page.offset);
|
|
16
|
+
export function resolveGraphPage(assembly: GraphSnapshotAssembly, page?: string): GraphSnapshotPage {
|
|
17
|
+
if (page === undefined) return assembly.pages[0]!;
|
|
18
|
+
try {
|
|
19
|
+
const decoded: unknown = JSON.parse(Buffer.from(page, "base64url").toString("utf8"));
|
|
20
|
+
if (!Array.isArray(decoded) || decoded.length !== 5 || decoded[0] !== 1 || decoded[1] !== assembly.vault || decoded[2] !== assembly.revision || (decoded[3] !== "nodes" && decoded[3] !== "edges") || !Number.isSafeInteger(decoded[4]) || decoded[4] < 0 || token(decoded[1], decoded[2], decoded[3], decoded[4]) !== page) throw new Error();
|
|
21
|
+
const found = assembly.pages.find(p => p.kind === decoded[3] && p.offset === decoded[4]);
|
|
22
|
+
if (found) return found;
|
|
23
|
+
} catch { /* Invalid tokens all receive the same refusal. */ }
|
|
24
|
+
throw new Error("graph page is invalid or expired; restart from the first page");
|
|
25
|
+
}
|
|
26
|
+
function nodeColumns(rows: NodeRow[]): GraphNodeColumns {
|
|
27
|
+
return { id: rows.map(r => r.id), label: rows.map(r => r.label), type: rows.map(r => r.type), domain: rows.map(r => r.domain), source_file: rows.map(r => r.source_file), community: rows.map(r => r.community), degree: rows.map(r => r.degree), updated: rows.map(r => r.updated), date: rows.map(r => r.date), placeholder: rows.map(r => r.placeholder), description: rows.map(r => r.description), confidence: rows.map(r => r.confidence), topics: rows.map(r => r.topics) };
|
|
28
|
+
}
|
|
29
|
+
export function graphEdgeColumns(rows: GraphEdgeRow[]): GraphEdgeColumns {
|
|
30
|
+
const relations = [...new Set(rows.map(r => r.relation))], tags = rows.map(r => r.confidence_tag), confidence = rows.map(r => r.confidence);
|
|
31
|
+
return { source: rows.map(r => r.source), target: rows.map(r => r.target), relations, relation: rows.map(r => relations.indexOf(r.relation)), field: rows.map(r => r.field), rel: rows.map(r => r.rel), confidence_tag: tags.every(t => t === tags[0]) ? tags[0] ?? [] : tags, confidence: confidence.every(c => c === confidence[0]) ? confidence[0] ?? [] : confidence };
|
|
32
|
+
}
|
|
33
|
+
export function assembleGraphSnapshot(snapshot: AnalysisSnapshot, vault: string): GraphSnapshotAssembly {
|
|
34
|
+
const graph = buildGraph(snapshot), ids = new Set(graph.nodes.map(node => node.id));
|
|
35
|
+
const supersedes = collectSupersedesEdges(snapshot), resolved = supersedes.filter(edge => ids.has(edge.target));
|
|
36
|
+
if (graph.edges.length + resolved.length > MAX_EDGES) throw new Error(`graph: exceeds ${MAX_EDGES} edges`);
|
|
37
|
+
const unresolved = [...collectUnresolvedGraph(snapshot), ...supersedes.filter(edge => !ids.has(edge.target))];
|
|
38
|
+
const grouped = new Map<string, GraphEdge[]>();
|
|
39
|
+
for (const edge of unresolved) { const list = grouped.get(edge.target) ?? []; list.push(edge); grouped.set(edge.target, list); }
|
|
40
|
+
const notes = new Map(snapshot.notes.map(n => [n.path.replace(/^notes\//, "").slice(0, -3), n]));
|
|
41
|
+
const nodes: NodeRow[] = graph.nodes.map(n => {
|
|
42
|
+
const fm = graphFrontmatter(notes.get(n.id)!.source);
|
|
43
|
+
return { ...n, description: n.description || null, confidence: n.confidence || null, topics: n.topics || null, updated: scalar(fm.updated), date: scalar(fm.created) ?? scalar(fm.date), placeholder: false };
|
|
44
|
+
});
|
|
45
|
+
const extra: GraphEdge[] = [];
|
|
46
|
+
let omitted = 0, full = false;
|
|
47
|
+
for (const [id, edges] of [...grouped].sort(([a], [b]) => codePointCompare(a, b))) {
|
|
48
|
+
if (full || nodes.length >= MAX_NODES || graph.edges.length + resolved.length + extra.length + edges.length > MAX_EDGES) { full = true; omitted++; continue; }
|
|
49
|
+
nodes.push({ id, label: pythonTitle(id.replaceAll("-", " ")), type: null, domain: null, source_file: null, community: null, degree: edges.length, updated: null, date: null, placeholder: true, description: null, confidence: null, topics: null });
|
|
50
|
+
extra.push(...edges);
|
|
51
|
+
}
|
|
52
|
+
extra.sort((a, b) => codePointCompare(a.source, b.source) || codePointCompare(a.target, b.target));
|
|
53
|
+
const indices = new Map(nodes.map((n, i) => [n.id, i]));
|
|
54
|
+
const edges: GraphEdgeRow[] = [...graph.edges, ...resolved, ...extra].map(e => ({ source: indices.get(e.source)!, target: indices.get(e.target)!, relation: e.relation, field: e.field ?? null, rel: e.rel ?? null, confidence_tag: e.confidence_tag, confidence: e.confidence }));
|
|
55
|
+
const metadata = { directed: graph.directed, multigraph: graph.multigraph, ...graph.graph };
|
|
56
|
+
const totals = { nodes: nodes.length, edges: edges.length, placeholders: nodes.length - graph.nodes.length, placeholdersOmitted: omitted };
|
|
57
|
+
const revision = createHash("sha256").update(JSON.stringify([1, vault, metadata, totals, nodes, edges])).digest("hex");
|
|
58
|
+
const pages: GraphSnapshotPage[] = [];
|
|
59
|
+
const envelope = (kind: "nodes" | "edges", offset: number, count: number, columns: GraphNodeColumns | GraphEdgeColumns): GraphSnapshotPage => {
|
|
60
|
+
const total = kind === "nodes" ? nodes.length : edges.length;
|
|
61
|
+
const next = offset + count < total ? token(vault, revision, kind, offset + count)
|
|
62
|
+
: kind === "nodes" && edges.length ? token(vault, revision, "edges", 0) : null;
|
|
63
|
+
return { schema: 1, vault, revision, graph: metadata, totals, kind, offset, count, columns, next };
|
|
64
|
+
};
|
|
65
|
+
// Binary search each page boundary: every candidate is measured before its rows are accepted.
|
|
66
|
+
function paginate<T>(kind: "nodes" | "edges", rows: T[], columns: (items: T[]) => GraphNodeColumns | GraphEdgeColumns): void {
|
|
67
|
+
let offset = 0;
|
|
68
|
+
while (offset < rows.length || (kind === "nodes" && !pages.length)) {
|
|
69
|
+
let low = 0, high = rows.length - offset;
|
|
70
|
+
const all = envelope(kind, offset, high, columns(rows.slice(offset)));
|
|
71
|
+
if (Buffer.byteLength(JSON.stringify(all)) <= MAX_BYTES) { pages.push(all); break; }
|
|
72
|
+
if (!high) throw new Error("graph page envelope exceeds the page budget; shorten the vault id and retry");
|
|
73
|
+
// The last page can be smaller because it has no next token; it was checked above.
|
|
74
|
+
high--;
|
|
75
|
+
while (low < high) {
|
|
76
|
+
const mid = Math.ceil((low + high) / 2), candidate = envelope(kind, offset, mid, columns(rows.slice(offset, offset + mid)));
|
|
77
|
+
if (Buffer.byteLength(JSON.stringify(candidate)) <= MAX_BYTES) low = mid; else high = mid - 1;
|
|
78
|
+
}
|
|
79
|
+
if (!low && rows.length > offset) {
|
|
80
|
+
const row = rows[offset] as NodeRow | GraphEdgeRow;
|
|
81
|
+
const id = "id" in row ? row.id : nodes[row.source]?.id ?? "unknown";
|
|
82
|
+
throw new Error(`graph row ${id.slice(0, 80)} exceeds the page budget; shorten its metadata and retry`);
|
|
83
|
+
}
|
|
84
|
+
pages.push(envelope(kind, offset, low, columns(rows.slice(offset, offset + low))));
|
|
85
|
+
offset += low;
|
|
86
|
+
if (!low) break;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
paginate("nodes", nodes, nodeColumns); paginate("edges", edges, graphEdgeColumns);
|
|
90
|
+
return { vault, revision, pages };
|
|
91
|
+
}
|
package/src/ui/panel-types.ts
CHANGED
|
@@ -9,8 +9,9 @@ import type { ChangesResult, HistoryResult } from "../vault-history.ts";
|
|
|
9
9
|
|
|
10
10
|
export type ProposalState = "pending" | "applied" | "rejected" | "apply_unknown";
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
export
|
|
12
|
+
export { assertionCoverageWarnings } from "../assertion-coverage.ts";
|
|
13
|
+
export type { CoverageWarning } from "../assertion-coverage.ts";
|
|
14
|
+
import type { CoverageWarning } from "../assertion-coverage.ts";
|
|
14
15
|
|
|
15
16
|
/** `proposals` panel: params `vault`, `state` (default pending), `after` page cursor, `id` to show one proposal. */
|
|
16
17
|
export interface ProposalsSnapshot {
|
|
@@ -21,21 +22,6 @@ export interface ProposalsSnapshot {
|
|
|
21
22
|
error?: string;
|
|
22
23
|
}
|
|
23
24
|
|
|
24
|
-
/** Coverage notices for an assertion read: anything short of a fully verified, synced and indexed journal is named with its next step. */
|
|
25
|
-
export function assertionCoverageWarnings(coverage: AssertionsReadResult["coverage"] | undefined): CoverageWarning[] {
|
|
26
|
-
if (!coverage) return [];
|
|
27
|
-
const out: CoverageWarning[] = [];
|
|
28
|
-
if (coverage.untrusted.length) out.push({ tone: "err", message: `${coverage.untrusted.length} journal ${coverage.untrusted.length === 1 ? "entry is" : "entries are"} untrusted and left out (${coverage.untrusted.slice(0, 3).map(u => `${u.segment}#${u.seq}: ${u.reason}`).join("; ")}); run \`vmem assertions <vault> --history --json\` and inspect the journal segments` });
|
|
29
|
-
if (coverage.unsupported.length) out.push({ tone: "warn", message: `${coverage.unsupported.length} journal ${coverage.unsupported.length === 1 ? "entry uses" : "entries use"} an unsupported schema and ${coverage.unsupported.length === 1 ? "is" : "are"} left out; upgrade vmem to read them` });
|
|
30
|
-
if (coverage.tornTail.length) out.push({ tone: "warn", message: `torn journal tail in ${coverage.tornTail.join(", ")}: the incomplete last entry is ignored; the next append repairs it` });
|
|
31
|
-
if (coverage.partialBatch.length) out.push({ tone: "warn", message: `${coverage.partialBatch.length} ${coverage.partialBatch.length === 1 ? "entry belongs" : "entries belong"} to an incomplete batch and ${coverage.partialBatch.length === 1 ? "is" : "are"} left out; resubmit the batch` });
|
|
32
|
-
if (coverage.purged) out.push({ tone: "neutral", message: `${coverage.purged} purged ${coverage.purged === 1 ? "payload is" : "payloads are"} not shown` });
|
|
33
|
-
if (coverage.unsynced) out.push({ tone: "warn", message: `${coverage.unsynced} assertion ${coverage.unsynced === 1 ? "file is" : "files are"} not committed; run \`vmem sync\` to share them` });
|
|
34
|
-
if (coverage.unsynced === null) out.push({ tone: "neutral", message: "journal sync state is unknown (no Git repository or Git unavailable)" });
|
|
35
|
-
if (coverage.indexIssue) out.push({ tone: "warn", message: coverage.indexIssue });
|
|
36
|
-
return out;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
25
|
/** `assertions` panel: params `vault`, `subject`, `relation`, `at`, `asOf`, `history`, `cursor`, as `vmem_assertions`. */
|
|
40
26
|
export interface AssertionsSnapshot {
|
|
41
27
|
vault: string | null;
|
|
@@ -53,3 +39,24 @@ export interface HistorySnapshot {
|
|
|
53
39
|
changes: ChangesResult | null;
|
|
54
40
|
error?: string;
|
|
55
41
|
}
|
|
42
|
+
|
|
43
|
+
export interface GraphNodeColumns {
|
|
44
|
+
id: string[]; label: string[]; type: (string | null)[]; domain: (string | null)[];
|
|
45
|
+
source_file: (string | null)[]; community: (number | null)[]; degree: number[];
|
|
46
|
+
updated: (string | null)[]; date: (string | null)[]; placeholder: boolean[];
|
|
47
|
+
description: (string | null)[]; confidence: (string | null)[]; topics: (string | null)[];
|
|
48
|
+
}
|
|
49
|
+
export interface GraphEdgeColumns {
|
|
50
|
+
source: number[]; target: number[]; relations: string[]; relation: number[];
|
|
51
|
+
field: (string | null)[]; rel: (string | null)[];
|
|
52
|
+
confidence_tag: string | string[]; confidence: number | number[];
|
|
53
|
+
}
|
|
54
|
+
export interface GraphSnapshotPage {
|
|
55
|
+
schema: 1; vault: string; revision: string;
|
|
56
|
+
graph: { directed: boolean; multigraph: boolean; partitioner: string; resolution: number; modularity: number; iterations: number; max_iterations: number };
|
|
57
|
+
totals: { nodes: number; edges: number; placeholders: number; placeholdersOmitted: number };
|
|
58
|
+
kind: "nodes" | "edges"; offset: number; count: number;
|
|
59
|
+
columns: GraphNodeColumns | GraphEdgeColumns; next: string | null;
|
|
60
|
+
}
|
|
61
|
+
/** The provider attaches a numeric cursor for console conditional polling. */
|
|
62
|
+
export type GraphPanelPage = GraphSnapshotPage & { cursor: number };
|
package/src/ui/panel.js
CHANGED
|
@@ -21,6 +21,16 @@ export default (host) => {
|
|
|
21
21
|
const assertionQuery = () => Object.fromEntries(["subject", "relation", "at", "asOf", "history", "limit"].filter((k) => params[k] !== undefined && params[k] !== "").map((k) => [k, params[k]]));
|
|
22
22
|
|
|
23
23
|
const views = {
|
|
24
|
+
graph(s) {
|
|
25
|
+
if (s.error) return [ui.notice(s.error, "err"), ...(params.page ? [h("div", { class: "vmem-bar" }, ui.button("First page", () => go("graph")))] : [])];
|
|
26
|
+
const graph = s.graph ?? {}, totals = s.totals ?? {};
|
|
27
|
+
return [h("section", { class: "card" }, h("h2", { text: `Graph · ${s.vault}` }),
|
|
28
|
+
h("p", { text: `Revision: ${s.revision}` }),
|
|
29
|
+
h("p", { text: `Nodes: ${totals.nodes} · edges: ${totals.edges} · placeholders: ${totals.placeholders} · omitted: ${totals.placeholdersOmitted}` }),
|
|
30
|
+
h("p", { text: `${graph.partitioner} · resolution ${graph.resolution} · modularity ${graph.modularity} · iterations ${graph.iterations}/${graph.max_iterations}` }),
|
|
31
|
+
h("p", { text: `${s.kind} · offset ${s.offset} · ${s.count} of ${totals[s.kind]} rows · ${s.next !== null ? "more pages follow" : "last page"}` })),
|
|
32
|
+
h("div", { class: "vmem-bar" }, ...(params.page ? [ui.button("First page", () => go("graph"))] : []), ...(s.next ? [ui.button("Next page", () => go("graph", { page: s.next }))] : []))];
|
|
33
|
+
},
|
|
24
34
|
settings(s) {
|
|
25
35
|
if (s.error) return [ui.notice(s.error, "err")];
|
|
26
36
|
const defaultVault = h("input", { type: "text", name: "defaultVault", value: s.defaultVault ?? "", class: "vmem-input", "aria-label": "Default vault" });
|
package/src/ui/plugin.ts
CHANGED
|
@@ -11,9 +11,12 @@ import { validArguments } from "../mcp.ts";
|
|
|
11
11
|
import { listPromotionCandidates } from "../promote.ts";
|
|
12
12
|
import { changeSettings, settingsSnapshot, loadRegistry } from "../registry.ts";
|
|
13
13
|
import { createSnapshotRevision, createPromoteSnapshot, nextSnapshotCursor } from "./snapshot-cache.ts";
|
|
14
|
+
import { assembleGraphSnapshot, resolveGraphPage } from "./graph-snapshot.ts";
|
|
15
|
+
import type { GraphSnapshotAssembly } from "./graph-snapshot.ts";
|
|
14
16
|
import { assertionCoverageWarnings } from "./panel-types.ts";
|
|
15
17
|
import type { AssertionsReadResult } from "../assertion-read.ts";
|
|
16
18
|
import { createInboxSnapshot } from "./inbox.ts";
|
|
19
|
+
import { LINK_RELATIONS } from "../links.ts";
|
|
17
20
|
import { lintVault } from "../vault-lint.ts";
|
|
18
21
|
import { readLogSince } from "../vault-log.ts";
|
|
19
22
|
import type { LintCode } from "../analysis-types.ts";
|
|
@@ -22,6 +25,38 @@ const asset = (name: string) => readFileSync(new URL(name, import.meta.url), "ut
|
|
|
22
25
|
const VERSION = (JSON.parse(asset("../../package.json")) as { version: string }).version;
|
|
23
26
|
const LINT_ERRORS: LintCode[] = ["L01", "L02", "L13"];
|
|
24
27
|
const CACHE_MS = 60_000;
|
|
28
|
+
/** Revision-bound assemblies, shared between concurrent requests and bounded to two vaults. */
|
|
29
|
+
export function createGraphSnapshotCache(revision: () => number, load: (vault: string) => Promise<GraphSnapshotAssembly>, now: () => number = Date.now) {
|
|
30
|
+
type Entry = { stamp: number; at: number; assembly: GraphSnapshotAssembly; cursors: Map<string, number> };
|
|
31
|
+
const cache = new Map<string, Entry>(), flights = new Map<string, Promise<Entry>>();
|
|
32
|
+
return {
|
|
33
|
+
async snapshot(vault: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
34
|
+
let entry: Entry | undefined;
|
|
35
|
+
for (let attempts = 0; attempts < 3; attempts++) {
|
|
36
|
+
const stamp = revision(), hit = cache.get(vault);
|
|
37
|
+
if (hit && hit.stamp === stamp && now() - hit.at < CACHE_MS) { entry = hit; break; }
|
|
38
|
+
let flight = flights.get(vault);
|
|
39
|
+
if (!flight) {
|
|
40
|
+
flight = load(vault).then(assembly => ({ stamp, at: now(), assembly, cursors: new Map<string, number>() }));
|
|
41
|
+
flights.set(vault, flight);
|
|
42
|
+
}
|
|
43
|
+
try { entry = await flight; } finally { if (flights.get(vault) === flight) flights.delete(vault); }
|
|
44
|
+
if (entry.stamp === revision()) { cache.delete(vault); cache.set(vault, entry); while (cache.size > 2) cache.delete(cache.keys().next().value!); break; }
|
|
45
|
+
entry = undefined;
|
|
46
|
+
}
|
|
47
|
+
if (!entry) throw new Error("graph changed while assembling; restart from the first page");
|
|
48
|
+
cache.delete(vault); cache.set(vault, entry);
|
|
49
|
+
while (cache.size > 2) cache.delete(cache.keys().next().value!);
|
|
50
|
+
if (args.page !== undefined && typeof args.page !== "string") throw new Error("graph page is invalid; restart from the first page");
|
|
51
|
+
const page = resolveGraphPage(entry.assembly, args.page as string | undefined);
|
|
52
|
+
const key = `${page.kind}:${page.offset}`;
|
|
53
|
+
let cursor = entry.cursors.get(key);
|
|
54
|
+
if (cursor === undefined) { cursor = nextSnapshotCursor(); entry.cursors.set(key, cursor); }
|
|
55
|
+
if (args.after === cursor) return { changed: false, cursor };
|
|
56
|
+
return { ...page, cursor };
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
25
60
|
const POLL_MS = 15_000;
|
|
26
61
|
// The shell reuses a snapshot for maxAgeMs, then serves it stale once more while it refreshes, and drops it on every
|
|
27
62
|
// console action. Half the poll keeps both windows inside one poll, so the shell cache never delays a refresh past the
|
|
@@ -96,8 +131,9 @@ export const plugin: ConsolePlugin = {
|
|
|
96
131
|
{ id: "proposals", title: "Proposals", order: 8, maxAgeMs: REUSE_MS },
|
|
97
132
|
{ id: "assertions", title: "Assertions", order: 9 },
|
|
98
133
|
{ id: "history", title: "History", order: 10 },
|
|
134
|
+
{ id: "graph", title: "Graph", order: 11, maxAgeMs: REUSE_MS },
|
|
99
135
|
],
|
|
100
|
-
capabilities: { actions: ["delete", "move", "promote", "promote-from-amem", "settings", "proposal-apply", "proposal-reject"], confirm: true, inbox: true, inboxMaxAgeMs: REUSE_MS, search: true },
|
|
136
|
+
capabilities: { actions: ["delete", "move", "promote", "promote-from-amem", "settings", "proposal-apply", "proposal-reject", "link"], confirm: true, inbox: true, inboxMaxAgeMs: REUSE_MS, search: true },
|
|
101
137
|
},
|
|
102
138
|
async open(ctx): Promise<ConsoleProvider> {
|
|
103
139
|
const home = resolveHome().home;
|
|
@@ -156,6 +192,10 @@ export const plugin: ConsolePlugin = {
|
|
|
156
192
|
};
|
|
157
193
|
|
|
158
194
|
const promote = createPromoteSnapshot(revision.current, candidates);
|
|
195
|
+
const graph = createGraphSnapshotCache(revision.current, async id => {
|
|
196
|
+
const spec = mcp.vaults.find(v => v.id === id)!;
|
|
197
|
+
return assembleGraphSnapshot(analysisInput(home, id, { expectedVault: spec }).snapshot, id);
|
|
198
|
+
});
|
|
159
199
|
const inbox = createInboxSnapshot(home, mcp.vaults, ctx.log, undefined, revision.current);
|
|
160
200
|
// One cursor for the whole Promote failure: a fresh one per failed scan would rebuild the panel every poll.
|
|
161
201
|
let promoteErrorCursor: number | undefined;
|
|
@@ -165,11 +205,17 @@ export const plugin: ConsolePlugin = {
|
|
|
165
205
|
if (typeof args === "string") return { ok: false, error: args };
|
|
166
206
|
const preview = await call(tool, args);
|
|
167
207
|
if (preview.refused || preview.ok === false || typeof preview.fingerprint !== "string") return { ok: false, error: firstIssue(preview) };
|
|
208
|
+
if (preview.unchanged === true) return { ok: true, message: `${describe(preview).verb}: already done, nothing changed` };
|
|
168
209
|
if (!confirmed || fingerprint !== preview.fingerprint) {
|
|
169
210
|
const d = describe(preview);
|
|
170
211
|
return { ok: false, needsConfirm: true, fingerprint: preview.fingerprint, verb: d.verb, preview: d.preview, changes: d.changes, ...(d.warnings.length ? { warnings: d.warnings } : {}) };
|
|
171
212
|
}
|
|
172
213
|
const done = await call(tool, { ...args, confirm: true, fingerprint });
|
|
214
|
+
// A tool that answers a stale fingerprint with a fresh preview (vmem_link) gets a new confirmation, never a write.
|
|
215
|
+
if (done.stale === true && typeof done.fingerprint === "string") {
|
|
216
|
+
const d = describe(done);
|
|
217
|
+
return { ok: false, needsConfirm: true, fingerprint: done.fingerprint, verb: d.verb, preview: d.preview, changes: d.changes, warnings: ["the notes changed since the preview; review the fresh preview", ...d.warnings] };
|
|
218
|
+
}
|
|
173
219
|
if (done.applied === true) { lintCache.clear(); revision.invalidate(); inbox.invalidate(); }
|
|
174
220
|
return confirmedOutcome(done, describe(preview).verb);
|
|
175
221
|
}
|
|
@@ -194,6 +240,21 @@ export const plugin: ConsolePlugin = {
|
|
|
194
240
|
async snapshot(input) {
|
|
195
241
|
const args = input as Args;
|
|
196
242
|
switch (input.panel) {
|
|
243
|
+
case "graph": {
|
|
244
|
+
const vault = vaultOf(args);
|
|
245
|
+
if (!vault) return { vault: null, error: str(args.vault) ? `unknown vault ${str(args.vault)}; pick a registered vault from Overview` : "graph: no selected vault; select a registered vault" };
|
|
246
|
+
const stem = (value: unknown) => typeof value === "string" && value.startsWith("notes/") && value.endsWith(".md") ? value.slice(6, -3) : value;
|
|
247
|
+
if (args.neighbors !== undefined) {
|
|
248
|
+
const r = await readTool("vmem_graph_neighbors", args, { vault: vault.id, path: stem(args.neighbors) });
|
|
249
|
+
return "error" in r ? r : { neighborhood: r.result };
|
|
250
|
+
}
|
|
251
|
+
if (args.from !== undefined || args.to !== undefined) {
|
|
252
|
+
const r = await readTool("vmem_graph_path", args, { vault: vault.id, from: stem(args.from), to: stem(args.to) });
|
|
253
|
+
return "error" in r ? r : { path: r.result };
|
|
254
|
+
}
|
|
255
|
+
try { return await graph.snapshot(vault.id, args); }
|
|
256
|
+
catch (error) { return { error: error instanceof Error ? error.message : String(error) }; }
|
|
257
|
+
}
|
|
197
258
|
case "settings": {
|
|
198
259
|
const vault = vaultOf(args);
|
|
199
260
|
if (!vault) return { error: "settings: no selected vault; select a registered vault" };
|
|
@@ -316,6 +377,14 @@ export const plugin: ConsolePlugin = {
|
|
|
316
377
|
warnings: backlinks.length ? [`${backlinks.length} links point here: ${[...new Set(backlinks.map(b => b.source))].slice(0, 5).join(", ")}`] : [] };
|
|
317
378
|
});
|
|
318
379
|
}
|
|
380
|
+
case "link": {
|
|
381
|
+
const from = str(args.from), to = str(args.to), relation = str(args.relation);
|
|
382
|
+
if (!from || !to || !relation) return { ok: false, error: "link: from, to and relation are required; pick both notes and a relation" };
|
|
383
|
+
if (!(LINK_RELATIONS as readonly string[]).includes(relation)) return { ok: false, error: `link: invalid relation ${relation}; use one of ${LINK_RELATIONS.join(", ")}` };
|
|
384
|
+
const both = args.bidirectional !== false && args.bidirectional !== "false";
|
|
385
|
+
return twoStep("vmem_link", forward("vmem_link", args, { preview: true, bidirectional: both }), confirmed, fingerprint, p => ({ verb: "Link notes",
|
|
386
|
+
preview: [`link ${from} → ${to} (${relation})${both ? ", both directions" : ", one way"}`, ...(p.logEvent ? [`log: ${JSON.stringify(p.logEvent)}`] : [])], changes: changesOf(p), warnings: [] }));
|
|
387
|
+
}
|
|
319
388
|
case "move": {
|
|
320
389
|
const from = str(args.from), to = str(args.to);
|
|
321
390
|
if (!from || !to) return { ok: false, error: "from and to are required" };
|
|
@@ -392,5 +461,5 @@ export const plugin: ConsolePlugin = {
|
|
|
392
461
|
};
|
|
393
462
|
|
|
394
463
|
export default plugin;
|
|
395
|
-
export type { ProposalState, ProposalsSnapshot, AssertionsSnapshot, HistorySnapshot, CoverageWarning } from "./panel-types.ts";
|
|
464
|
+
export type { ProposalState, ProposalsSnapshot, AssertionsSnapshot, HistorySnapshot, CoverageWarning, GraphSnapshotPage, GraphPanelPage, GraphNodeColumns, GraphEdgeColumns } from "./panel-types.ts";
|
|
396
465
|
export { assertionCoverageWarnings } from "./panel-types.ts";
|
package/src/vault-graph.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AnalysisSnapshot } from "./analysis-types.ts";
|
|
2
|
-
import { authoredLinkOffsets, LINK_RELATIONS } from "./links.ts";
|
|
2
|
+
import { authoredLinkOffsets, LINK_RELATIONS, noteKey } from "./links.ts";
|
|
3
3
|
export { LINK_RELATIONS };
|
|
4
4
|
import { AnalysisYamlUnsupported, parseAnalysisYaml, scalarText, yamlTruthy } from "./analysis-yaml.ts";
|
|
5
5
|
|
|
@@ -114,6 +114,55 @@ function parse(source: string): { fm: Record<string, unknown>; body: string } {
|
|
|
114
114
|
}
|
|
115
115
|
return { fm, body: source.slice(match[0].length) };
|
|
116
116
|
}
|
|
117
|
+
/** Frontmatter for consumers of the same analysis snapshot as buildGraph. */
|
|
118
|
+
export function graphFrontmatter(source: string): Record<string, unknown> { return parse(source).fm; }
|
|
119
|
+
|
|
120
|
+
/** Unresolved edges use the same normalization and duplicate semantics as the resolved graph. */
|
|
121
|
+
export function collectUnresolvedGraph(snapshot: AnalysisSnapshot): GraphEdge[] {
|
|
122
|
+
const sources = [...snapshot.notes].sort((a, b) => compare(a.path, b.path));
|
|
123
|
+
const stems = new Set(sources.map(note => note.path.replace(/^notes\//, "").slice(0, -3)));
|
|
124
|
+
const edges = new Map<string, GraphEdge>();
|
|
125
|
+
for (const note of sources) {
|
|
126
|
+
const id = note.path.replace(/^notes\//, "").slice(0, -3), { fm, body } = parse(note.source);
|
|
127
|
+
const inferredTargets = inferredLinkTargets(fm.inferred_links), authored = authoredLinkOffsets(body);
|
|
128
|
+
for (const match of body.matchAll(LEGACY_LINK)) {
|
|
129
|
+
const target = legacyTarget(match[1]!.split("#", 1)[0]!);
|
|
130
|
+
if (!target || stems.has(target)) continue;
|
|
131
|
+
const key = JSON.stringify([id, target]), prior = edges.get(key);
|
|
132
|
+
const rel = prior?.rel ?? linkRelation(body, match.index, match[0].length);
|
|
133
|
+
const inferred = inferredTargets.has(target) && authored.has(match.index);
|
|
134
|
+
edges.set(key, { source: id, target, relation: "wiki_link", ...(rel ? { rel } : {}),
|
|
135
|
+
confidence_tag: inferred || prior?.confidence_tag === "INFERRED" ? "INFERRED" : "EXTRACTED", confidence: 1 });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return [...edges.values()].sort((a, b) => compare(a.target, b.target) || compare(a.source, b.source));
|
|
139
|
+
}
|
|
140
|
+
/** Directed frontmatter references for the console snapshot; the legacy graph stays unchanged. */
|
|
141
|
+
export function collectSupersedesEdges(snapshot: AnalysisSnapshot): GraphEdge[] {
|
|
142
|
+
const sources = [...snapshot.notes].sort((a, b) => compare(a.path, b.path));
|
|
143
|
+
const ids = new Map<string, string>();
|
|
144
|
+
for (const note of sources) {
|
|
145
|
+
const id = note.path.replace(/^notes\//, "").slice(0, -3);
|
|
146
|
+
ids.set(noteKey(note.path), id);
|
|
147
|
+
}
|
|
148
|
+
const edges: GraphEdge[] = [];
|
|
149
|
+
for (const note of sources) {
|
|
150
|
+
const source = note.path.replace(/^notes\//, "").slice(0, -3), fm = parse(note.source).fm;
|
|
151
|
+
for (const field of ["supersedes", "superseded_by"] as const) {
|
|
152
|
+
const values = Array.isArray(fm[field]) ? fm[field] : [fm[field]];
|
|
153
|
+
for (const value of values) {
|
|
154
|
+
if (typeof value !== "string") continue;
|
|
155
|
+
for (const match of value.matchAll(LEGACY_LINK)) {
|
|
156
|
+
const raw = match[1]!.split("#", 1)[0]!.trim(), key = noteKey(raw);
|
|
157
|
+
if (!key) continue;
|
|
158
|
+
const target = ids.get(key) ?? ids.get(noteKey(legacyTarget(key))) ?? legacyTarget(key);
|
|
159
|
+
edges.push({ source, target, relation: "supersedes", field, confidence_tag: "EXTRACTED", confidence: 1 });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return edges;
|
|
165
|
+
}
|
|
117
166
|
function adjacency(graph: Pick<VaultGraph, "nodes" | "edges">): Map<string, Set<string>> {
|
|
118
167
|
const neighbors = new Map(graph.nodes.map(node => [node.id, new Set<string>()]));
|
|
119
168
|
for (const edge of graph.edges) { neighbors.get(edge.source)?.add(edge.target); neighbors.get(edge.target)?.add(edge.source); }
|
package/src/writer.ts
CHANGED
|
@@ -360,7 +360,8 @@ function runWrite(home: string, request: WriteRequest, options: WriteOptions & {
|
|
|
360
360
|
const logIssues = checkLogEvent(home, { vault: request.vault, event: request.log, channel: request.channel }, options.env);
|
|
361
361
|
if (logIssues.length) throw new WriteRefusal(logIssues.map(issue => ({ ...issue, message: `log event refused, nothing written: ${issue.message}; fix the event fields (rules as for \`log append\`) or omit the event for the default line` })));
|
|
362
362
|
}
|
|
363
|
-
|
|
363
|
+
// link is one-step unless the caller confirms a preview fingerprint (opt-in two-step, #295).
|
|
364
|
+
const twoStep = ["move", "delete", "tidy", "merge"].includes(request.operation.op) || (request.operation.op === "link" && request.confirm === true);
|
|
364
365
|
const preview = request.operation.op === "check" || request.dryRun === true || (twoStep && request.confirm !== true);
|
|
365
366
|
if (options.proposal && (preview || !options.binding || !["create", "patch", "infer-link"].includes(request.operation.op))) refuse("V01", "proposal confirmation requires one supported proposal operation and a bound vault; request a new preview");
|
|
366
367
|
if (!preview) {
|