@staix/vault-mem 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/enrichment-query.ts +21 -0
- package/src/enrichment-store.ts +11 -0
- package/src/mcp-vault.ts +19 -2
- package/src/ui/graph-snapshot.ts +80 -11
- package/src/ui/panel-types.ts +5 -0
- package/src/ui/plugin.ts +57 -13
- package/src/vault-graph.ts +27 -1
- package/src/writer.ts +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.14.0] - 2026-11-22
|
|
6
|
+
|
|
7
|
+
- N-1: 0.13.1 and 0.14.0 share the note and spec index files, config format 6 and the enrichment sidecar format. CLI commands and MCP tool names, arguments and receipts are unchanged. Only the console provider differs: its Graph snapshot adds the first-page `enrichment` field and the `similar` and `semantic` arguments, which the 0.13.1 provider does not offer.
|
|
8
|
+
|
|
9
|
+
- Add Graph enrichment capability metadata, similar-note queries and opt-in paged semantic similarity edges; embeddings remain inside the provider.
|
|
10
|
+
|
|
11
|
+
## [0.13.1] - 2026-11-22
|
|
12
|
+
|
|
13
|
+
- Add directed `supersedes` and `superseded_by` frontmatter edges to Graph console snapshots. CLI and MCP graph outputs keep their existing behavior.
|
|
14
|
+
|
|
15
|
+
- 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.
|
|
16
|
+
|
|
5
17
|
## [0.13.0] - 2026-11-22
|
|
6
18
|
|
|
7
19
|
- 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.
|
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 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:
|
|
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 with optional enrichment and semantic edges, 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`
|
package/package.json
CHANGED
package/src/enrichment-query.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
/** Bounded hybrid ranking over current indexed notes and local stored vectors. */
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import type { AnalysisSnapshot } from "./analysis-types.ts";
|
|
3
5
|
import { loadRegistry } from "./registry.ts";
|
|
4
6
|
import { logBinding, matchesBinding } from "./vault-log.ts";
|
|
5
7
|
import { canonicalPath, isDenied } from "./platform.ts";
|
|
@@ -39,6 +41,25 @@ function candidates(ctx: ReturnType<typeof queryContext>, index: VaultIndex, que
|
|
|
39
41
|
return [{ id, score: vectorSimilarity(query.values, r.value as number[]), note }];
|
|
40
42
|
}).sort((a, b) => b.score - a.score || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
41
43
|
}
|
|
44
|
+
/** Internal graph inputs: only current, allowed vectors; callers must never serialize values. */
|
|
45
|
+
export function graphEnrichmentInputs(home: string, vault: string, snapshot: AnalysisSnapshot) {
|
|
46
|
+
const ctx = queryContext(home, vault);
|
|
47
|
+
if (!ctx.store) { ctx.check(); return undefined; }
|
|
48
|
+
const metadata = new Map(snapshot.notes.map(note => {
|
|
49
|
+
const path = note.path.replace(/^notes\//, "");
|
|
50
|
+
return [path, createHash("sha256").update(note.source).digest("hex")] as const;
|
|
51
|
+
}));
|
|
52
|
+
const vectors = ctx.store.records.flatMap(record => {
|
|
53
|
+
if (record.kind !== "embedding" || !Array.isArray(record.value)) return [];
|
|
54
|
+
const path = record.path.slice(6);
|
|
55
|
+
if (!allowed(ctx, path) || metadata.get(path) !== record.contentHash) return [];
|
|
56
|
+
return [{ path, values: record.value as number[] }];
|
|
57
|
+
}).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
58
|
+
const hash = createHash("sha256").update(JSON.stringify([ctx.store.model ?? null, snapshot.notes.length]));
|
|
59
|
+
for (const item of vectors) hash.update(JSON.stringify([item.path, item.values]));
|
|
60
|
+
ctx.check();
|
|
61
|
+
return { model: ctx.store.model ?? null, embedded: vectors.length, total: snapshot.notes.length, digest: hash.digest("hex"), vectors };
|
|
62
|
+
}
|
|
42
63
|
export function hybridSearch(home: string, vault: string, index: VaultIndex, query: string, options: SearchOptions, vector: QueryVector): SearchResult[] {
|
|
43
64
|
const limit = resultLimit(options.limit), ctx = queryContext(home, vault);
|
|
44
65
|
if (index.vault.id !== ctx.vault.id || index.vault.path !== ctx.vault.path || !index.sourceIdentityCurrent()) throw new Error("enrichment: index is unscanned or belongs to another vault; reopen and scan the selected vault before retrying");
|
package/src/enrichment-store.ts
CHANGED
|
@@ -111,6 +111,17 @@ function readFile(loc: ReturnType<typeof location>): EnrichmentStore {
|
|
|
111
111
|
export function readEnrichmentStore(home: string, vault: VaultSpec, roots: VaultSpec[], denyPaths: string[]): EnrichmentStore {
|
|
112
112
|
return readFile(location(home, vault, roots, denyPaths, false));
|
|
113
113
|
}
|
|
114
|
+
/** Metadata-only identity for invalidating in-process views after an atomic sidecar replacement. */
|
|
115
|
+
export function enrichmentStoreStamp(home: string, vault: VaultSpec, roots: VaultSpec[], denyPaths: string[]): string {
|
|
116
|
+
const loc = location(home, vault, roots, denyPaths, false);
|
|
117
|
+
try {
|
|
118
|
+
const stat = lstatSync(loc.file, { bigint: true });
|
|
119
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing";
|
|
122
|
+
throw new Error("enrichment: sidecar identity cannot be read; inspect the local enrichment store", { cause: error });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
114
125
|
/** Validate complete metadata and vector shape before any side effects. */
|
|
115
126
|
export function validateEnrichmentRecord(record: EnrichmentRecord): void {
|
|
116
127
|
if (!record || typeof record !== "object") fail("intake record is missing; supply a complete result");
|
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/ui/graph-snapshot.ts
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import type { AnalysisSnapshot } from "../analysis-types.ts";
|
|
3
3
|
import { scalarText } from "../analysis-yaml.ts";
|
|
4
|
-
import { buildGraph, collectUnresolvedGraph, codePointCompare, graphFrontmatter, pythonTitle } from "../vault-graph.ts";
|
|
4
|
+
import { buildGraph, collectUnresolvedGraph, collectSupersedesEdges, codePointCompare, graphFrontmatter, pythonTitle } from "../vault-graph.ts";
|
|
5
5
|
import type { GraphEdge } from "../vault-graph.ts";
|
|
6
|
-
import type { GraphSnapshotPage, GraphNodeColumns, GraphEdgeColumns } from "./panel-types.ts";
|
|
6
|
+
import type { GraphSnapshotPage, GraphNodeColumns, GraphEdgeColumns, SemanticGraphPage } from "./panel-types.ts";
|
|
7
7
|
|
|
8
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
9
|
export type GraphEdgeRow = { source: number; target: number; relation: string; field: string | null; rel: string | null; confidence_tag: string; confidence: number };
|
|
10
|
-
export interface
|
|
10
|
+
export interface GraphEnrichmentInputs { model: string | null; embedded: number; total: number; digest: string; vectors: { path: string; values: number[] }[] }
|
|
11
|
+
export interface GraphSnapshotAssembly { vault: string; revision: string; pages: GraphSnapshotPage[]; enrichment?: GraphEnrichmentInputs }
|
|
11
12
|
const MAX_BYTES = 1_048_576 - 32;
|
|
12
13
|
const MAX_NODES = 10_000, MAX_EDGES = 100_000;
|
|
14
|
+
// ponytail: exact all-pairs search is bounded here; larger vaults need ANN or precomputed neighbors.
|
|
15
|
+
const MAX_SEMANTIC_EMBEDDINGS = 3_000;
|
|
13
16
|
const scalar = (v: unknown): string | null => scalarText(v) ?? (typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "bigint" ? String(v) : null);
|
|
14
17
|
const token = (vault: string, revision: string, kind: string, offset: number): string => Buffer.from(JSON.stringify([1, vault, revision, kind, offset])).toString("base64url");
|
|
15
18
|
export const encodeGraphPage = (assembly: GraphSnapshotAssembly, page: GraphSnapshotPage): string => token(assembly.vault, assembly.revision, page.kind, page.offset);
|
|
@@ -30,8 +33,11 @@ export function graphEdgeColumns(rows: GraphEdgeRow[]): GraphEdgeColumns {
|
|
|
30
33
|
const relations = [...new Set(rows.map(r => r.relation))], tags = rows.map(r => r.confidence_tag), confidence = rows.map(r => r.confidence);
|
|
31
34
|
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
35
|
}
|
|
33
|
-
export function assembleGraphSnapshot(snapshot: AnalysisSnapshot, vault: string): GraphSnapshotAssembly {
|
|
34
|
-
const graph = buildGraph(snapshot),
|
|
36
|
+
export function assembleGraphSnapshot(snapshot: AnalysisSnapshot, vault: string, enrichment?: GraphEnrichmentInputs): GraphSnapshotAssembly {
|
|
37
|
+
const graph = buildGraph(snapshot), ids = new Set(graph.nodes.map(node => node.id));
|
|
38
|
+
const supersedes = collectSupersedesEdges(snapshot), resolved = supersedes.filter(edge => ids.has(edge.target));
|
|
39
|
+
if (graph.edges.length + resolved.length > MAX_EDGES) throw new Error(`graph: exceeds ${MAX_EDGES} edges`);
|
|
40
|
+
const unresolved = [...collectUnresolvedGraph(snapshot), ...supersedes.filter(edge => !ids.has(edge.target))];
|
|
35
41
|
const grouped = new Map<string, GraphEdge[]>();
|
|
36
42
|
for (const edge of unresolved) { const list = grouped.get(edge.target) ?? []; list.push(edge); grouped.set(edge.target, list); }
|
|
37
43
|
const notes = new Map(snapshot.notes.map(n => [n.path.replace(/^notes\//, "").slice(0, -3), n]));
|
|
@@ -41,23 +47,23 @@ export function assembleGraphSnapshot(snapshot: AnalysisSnapshot, vault: string)
|
|
|
41
47
|
});
|
|
42
48
|
const extra: GraphEdge[] = [];
|
|
43
49
|
let omitted = 0, full = false;
|
|
44
|
-
for (const [id, edges] of grouped) {
|
|
45
|
-
if (full || nodes.length >= MAX_NODES || graph.edges.length + extra.length + edges.length > MAX_EDGES) { full = true; omitted++; continue; }
|
|
50
|
+
for (const [id, edges] of [...grouped].sort(([a], [b]) => codePointCompare(a, b))) {
|
|
51
|
+
if (full || nodes.length >= MAX_NODES || graph.edges.length + resolved.length + extra.length + edges.length > MAX_EDGES) { full = true; omitted++; continue; }
|
|
46
52
|
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 });
|
|
47
53
|
extra.push(...edges);
|
|
48
54
|
}
|
|
49
55
|
extra.sort((a, b) => codePointCompare(a.source, b.source) || codePointCompare(a.target, b.target));
|
|
50
56
|
const indices = new Map(nodes.map((n, i) => [n.id, i]));
|
|
51
|
-
const edges: GraphEdgeRow[] = [...graph.edges, ...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 }));
|
|
57
|
+
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 }));
|
|
52
58
|
const metadata = { directed: graph.directed, multigraph: graph.multigraph, ...graph.graph };
|
|
53
59
|
const totals = { nodes: nodes.length, edges: edges.length, placeholders: nodes.length - graph.nodes.length, placeholdersOmitted: omitted };
|
|
54
|
-
const revision = createHash("sha256").update(JSON.stringify([1, vault, metadata, totals, nodes, edges])).digest("hex");
|
|
60
|
+
const revision = createHash("sha256").update(JSON.stringify([1, vault, metadata, totals, nodes, edges, ...(enrichment ? [enrichment.digest] : [])])).digest("hex");
|
|
55
61
|
const pages: GraphSnapshotPage[] = [];
|
|
56
62
|
const envelope = (kind: "nodes" | "edges", offset: number, count: number, columns: GraphNodeColumns | GraphEdgeColumns): GraphSnapshotPage => {
|
|
57
63
|
const total = kind === "nodes" ? nodes.length : edges.length;
|
|
58
64
|
const next = offset + count < total ? token(vault, revision, kind, offset + count)
|
|
59
65
|
: kind === "nodes" && edges.length ? token(vault, revision, "edges", 0) : null;
|
|
60
|
-
return { schema: 1, vault, revision, graph: metadata, totals, kind, offset, count, columns, next };
|
|
66
|
+
return { schema: 1, vault, revision, graph: metadata, totals, kind, offset, count, columns, next, ...(enrichment && kind === "nodes" && offset === 0 ? { enrichment: { model: enrichment.model, embedded: enrichment.embedded, total: enrichment.total } } : {}) };
|
|
61
67
|
};
|
|
62
68
|
// Binary search each page boundary: every candidate is measured before its rows are accepted.
|
|
63
69
|
function paginate<T>(kind: "nodes" | "edges", rows: T[], columns: (items: T[]) => GraphNodeColumns | GraphEdgeColumns): void {
|
|
@@ -84,5 +90,68 @@ export function assembleGraphSnapshot(snapshot: AnalysisSnapshot, vault: string)
|
|
|
84
90
|
}
|
|
85
91
|
}
|
|
86
92
|
paginate("nodes", nodes, nodeColumns); paginate("edges", edges, graphEdgeColumns);
|
|
87
|
-
return { vault, revision, pages };
|
|
93
|
+
return { vault, revision, pages, ...(enrichment ? { enrichment } : {}) };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Exact undirected union of each note's top-k cosine neighbors. Vectors remain in process. */
|
|
97
|
+
export function assembleSemanticPages(assembly: GraphSnapshotAssembly, k: number, minScore: number): SemanticGraphPage[] {
|
|
98
|
+
if (!Number.isInteger(k) || k < 1 || k > 20 || typeof minScore !== "number" || !Number.isFinite(minScore) || minScore < 0 || minScore > 1)
|
|
99
|
+
throw new Error("graph semantic: k must be 1..20 and minScore must be 0..1; correct the parameters and restart");
|
|
100
|
+
if (!assembly.enrichment) throw new Error("enrichment: enrichment is disabled; enable it in settings");
|
|
101
|
+
if (assembly.enrichment.embedded > MAX_SEMANTIC_EMBEDDINGS) throw new Error(`graph semantic: exceeds ${MAX_SEMANTIC_EMBEDDINGS} current embeddings; reduce the embedded set or use similar notes`);
|
|
102
|
+
const ids = new Map<string, number>();
|
|
103
|
+
for (const page of assembly.pages) if (page.kind === "nodes") {
|
|
104
|
+
const columns = page.columns as GraphNodeColumns;
|
|
105
|
+
columns.source_file.forEach((path, i) => { if (path) ids.set(path.slice(6), page.offset + i); });
|
|
106
|
+
}
|
|
107
|
+
const vectors = assembly.enrichment.vectors.flatMap(item => {
|
|
108
|
+
const index = ids.get(item.path); if (index === undefined) return [];
|
|
109
|
+
let scale = 0; for (const v of item.values) scale = Math.max(scale, Math.abs(v));
|
|
110
|
+
let norm = 0; for (const v of item.values) norm += (v / scale) ** 2;
|
|
111
|
+
norm = Math.sqrt(norm);
|
|
112
|
+
return [{ index, vector: Float64Array.from(item.values, v => v / scale / norm) }];
|
|
113
|
+
}).sort((a, b) => a.index - b.index);
|
|
114
|
+
const tops: { index: number; score: number }[][] = vectors.map(() => []);
|
|
115
|
+
const insert = (list: { index: number; score: number }[], index: number, score: number) => {
|
|
116
|
+
let at = 0;
|
|
117
|
+
while (at < list.length && (list[at]!.score > score || (list[at]!.score === score && list[at]!.index < index))) at++;
|
|
118
|
+
if (at >= k) return;
|
|
119
|
+
list.splice(at, 0, { index, score }); if (list.length > k) list.pop();
|
|
120
|
+
};
|
|
121
|
+
for (let i = 0; i < vectors.length; i++) for (let j = i + 1; j < vectors.length; j++) {
|
|
122
|
+
const left = vectors[i]!.vector, right = vectors[j]!.vector;
|
|
123
|
+
let score = 0; for (let d = 0; d < left.length; d++) score += left[d]! * right[d]!;
|
|
124
|
+
score = Math.max(-1, Math.min(1, score));
|
|
125
|
+
if (score >= minScore) { insert(tops[i]!, j, score); insert(tops[j]!, i, score); }
|
|
126
|
+
}
|
|
127
|
+
const unique = new Map<string, { source: number; target: number; score: number }>();
|
|
128
|
+
tops.forEach((list, i) => { for (const item of list) {
|
|
129
|
+
const source = Math.min(vectors[i]!.index, vectors[item.index]!.index), target = Math.max(vectors[i]!.index, vectors[item.index]!.index);
|
|
130
|
+
unique.set(`${source}:${target}`, { source, target, score: item.score });
|
|
131
|
+
} });
|
|
132
|
+
const rows = [...unique.values()].sort((a, b) => a.source - b.source || a.target - b.target);
|
|
133
|
+
const encode = (offset: number) => Buffer.from(JSON.stringify([1, assembly.vault, assembly.revision, "semantic", k, minScore, offset])).toString("base64url");
|
|
134
|
+
const make = (offset: number, count: number): SemanticGraphPage => {
|
|
135
|
+
const slice = rows.slice(offset, offset + count);
|
|
136
|
+
return { schema: 1, vault: assembly.vault, revision: assembly.revision, kind: "semantic", offset, count, semantic: { source: slice.map(r => r.source), target: slice.map(r => r.target), score: slice.map(r => r.score) }, next: offset + count < rows.length ? encode(offset + count) : null };
|
|
137
|
+
};
|
|
138
|
+
const pages: SemanticGraphPage[] = []; let offset = 0;
|
|
139
|
+
do {
|
|
140
|
+
let low = 0, high = rows.length - offset;
|
|
141
|
+
if (Buffer.byteLength(JSON.stringify(make(offset, high))) <= MAX_BYTES) { pages.push(make(offset, high)); break; }
|
|
142
|
+
high--;
|
|
143
|
+
while (low < high) { const mid = Math.ceil((low + high) / 2); if (Buffer.byteLength(JSON.stringify(make(offset, mid))) <= MAX_BYTES) low = mid; else high = mid - 1; }
|
|
144
|
+
if (!low) throw new Error("graph semantic: page exceeds the byte budget; reduce the vault id and restart");
|
|
145
|
+
pages.push(make(offset, low)); offset += low;
|
|
146
|
+
} while (offset < rows.length);
|
|
147
|
+
return pages;
|
|
148
|
+
}
|
|
149
|
+
export function resolveSemanticPage(assembly: GraphSnapshotAssembly, pages: SemanticGraphPage[], k: number, minScore: number, page?: string): SemanticGraphPage {
|
|
150
|
+
if (page === undefined) return pages[0]!;
|
|
151
|
+
try {
|
|
152
|
+
const value: unknown = JSON.parse(Buffer.from(page, "base64url").toString("utf8"));
|
|
153
|
+
if (!Array.isArray(value) || value.length !== 7 || value[0] !== 1 || value[1] !== assembly.vault || value[2] !== assembly.revision || value[3] !== "semantic" || value[4] !== k || value[5] !== minScore || !Number.isSafeInteger(value[6]) || value[6] < 0 || Buffer.from(JSON.stringify(value)).toString("base64url") !== page) throw new Error();
|
|
154
|
+
const found = pages.find(p => p.offset === value[6]); if (found) return found;
|
|
155
|
+
} catch { /* All invalid tokens get the same recovery instruction. */ }
|
|
156
|
+
throw new Error("graph semantic page is invalid or expired; restart from the first page");
|
|
88
157
|
}
|
package/src/ui/panel-types.ts
CHANGED
|
@@ -57,6 +57,11 @@ export interface GraphSnapshotPage {
|
|
|
57
57
|
totals: { nodes: number; edges: number; placeholders: number; placeholdersOmitted: number };
|
|
58
58
|
kind: "nodes" | "edges"; offset: number; count: number;
|
|
59
59
|
columns: GraphNodeColumns | GraphEdgeColumns; next: string | null;
|
|
60
|
+
enrichment?: { model: string | null; embedded: number; total: number };
|
|
61
|
+
}
|
|
62
|
+
export interface SemanticGraphPage {
|
|
63
|
+
schema: 1; vault: string; revision: string; kind: "semantic"; offset: number; count: number;
|
|
64
|
+
semantic: { source: number[]; target: number[]; score: number[] }; next: string | null;
|
|
60
65
|
}
|
|
61
66
|
/** The provider attaches a numeric cursor for console conditional polling. */
|
|
62
67
|
export type GraphPanelPage = GraphSnapshotPage & { cursor: number };
|
package/src/ui/plugin.ts
CHANGED
|
@@ -11,11 +11,15 @@ 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";
|
|
14
|
+
import { assembleGraphSnapshot, resolveGraphPage, assembleSemanticPages, resolveSemanticPage } from "./graph-snapshot.ts";
|
|
15
15
|
import type { GraphSnapshotAssembly } from "./graph-snapshot.ts";
|
|
16
|
+
import type { SemanticGraphPage } from "./panel-types.ts";
|
|
17
|
+
import { graphEnrichmentInputs } from "../enrichment-query.ts";
|
|
18
|
+
import { enrichmentStoreStamp } from "../enrichment-store.ts";
|
|
16
19
|
import { assertionCoverageWarnings } from "./panel-types.ts";
|
|
17
20
|
import type { AssertionsReadResult } from "../assertion-read.ts";
|
|
18
21
|
import { createInboxSnapshot } from "./inbox.ts";
|
|
22
|
+
import { LINK_RELATIONS } from "../links.ts";
|
|
19
23
|
import { lintVault } from "../vault-lint.ts";
|
|
20
24
|
import { readLogSince } from "../vault-log.ts";
|
|
21
25
|
import type { LintCode } from "../analysis-types.ts";
|
|
@@ -25,32 +29,48 @@ const VERSION = (JSON.parse(asset("../../package.json")) as { version: string })
|
|
|
25
29
|
const LINT_ERRORS: LintCode[] = ["L01", "L02", "L13"];
|
|
26
30
|
const CACHE_MS = 60_000;
|
|
27
31
|
/** Revision-bound assemblies, shared between concurrent requests and bounded to two vaults. */
|
|
28
|
-
export function createGraphSnapshotCache(revision: () => number, load: (vault: string) => Promise<GraphSnapshotAssembly>, now: () => number = Date.now) {
|
|
29
|
-
type Entry = { stamp: number; at: number; assembly: GraphSnapshotAssembly; cursors: Map<string, number> };
|
|
32
|
+
export function createGraphSnapshotCache(revision: (vault: string) => number | string, load: (vault: string) => Promise<GraphSnapshotAssembly>, now: () => number = Date.now) {
|
|
33
|
+
type Entry = { stamp: number | string; at: number; assembly: GraphSnapshotAssembly; cursors: Map<string, number>; semantic: Map<string, SemanticGraphPage[]> };
|
|
30
34
|
const cache = new Map<string, Entry>(), flights = new Map<string, Promise<Entry>>();
|
|
31
35
|
return {
|
|
32
36
|
async snapshot(vault: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {
|
|
33
37
|
let entry: Entry | undefined;
|
|
34
38
|
for (let attempts = 0; attempts < 3; attempts++) {
|
|
35
|
-
const stamp = revision(), hit = cache.get(vault);
|
|
39
|
+
const stamp = revision(vault), hit = cache.get(vault);
|
|
36
40
|
if (hit && hit.stamp === stamp && now() - hit.at < CACHE_MS) { entry = hit; break; }
|
|
37
41
|
let flight = flights.get(vault);
|
|
38
42
|
if (!flight) {
|
|
39
|
-
flight = load(vault).then(assembly => ({ stamp, at: now(), assembly, cursors: new Map<string, number>() }));
|
|
43
|
+
flight = load(vault).then(assembly => ({ stamp, at: now(), assembly, cursors: new Map<string, number>(), semantic: new Map<string, SemanticGraphPage[]>() }));
|
|
40
44
|
flights.set(vault, flight);
|
|
41
45
|
}
|
|
42
46
|
try { entry = await flight; } finally { if (flights.get(vault) === flight) flights.delete(vault); }
|
|
43
|
-
if (entry.stamp === revision()) { cache.delete(vault); cache.set(vault, entry); while (cache.size > 2) cache.delete(cache.keys().next().value!); break; }
|
|
47
|
+
if (entry.stamp === revision(vault)) { cache.delete(vault); cache.set(vault, entry); while (cache.size > 2) cache.delete(cache.keys().next().value!); break; }
|
|
44
48
|
entry = undefined;
|
|
45
49
|
}
|
|
46
50
|
if (!entry) throw new Error("graph changed while assembling; restart from the first page");
|
|
47
51
|
cache.delete(vault); cache.set(vault, entry);
|
|
48
52
|
while (cache.size > 2) cache.delete(cache.keys().next().value!);
|
|
49
53
|
if (args.page !== undefined && typeof args.page !== "string") throw new Error("graph page is invalid; restart from the first page");
|
|
50
|
-
|
|
51
|
-
|
|
54
|
+
let page: ReturnType<typeof resolveGraphPage> | SemanticGraphPage;
|
|
55
|
+
let query = "";
|
|
56
|
+
if (args.semantic !== undefined) {
|
|
57
|
+
const options = args.semantic;
|
|
58
|
+
if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some(key => key !== "k" && key !== "minScore")) throw new Error("graph semantic: supply k and minScore; correct the parameters and restart");
|
|
59
|
+
const { k, minScore } = options as Record<string, unknown>;
|
|
60
|
+
if (typeof k !== "number" || !Number.isInteger(k) || k < 1 || k > 20 || typeof minScore !== "number" || !Number.isFinite(minScore) || minScore < 0 || minScore > 1) throw new Error("graph semantic: k must be 1..20 and minScore must be 0..1; correct the parameters and restart");
|
|
61
|
+
query = JSON.stringify([k, minScore]);
|
|
62
|
+
let pages = entry.semantic.get(query);
|
|
63
|
+
if (!pages) {
|
|
64
|
+
pages = assembleSemanticPages(entry.assembly, k, minScore);
|
|
65
|
+
if (entry.stamp !== revision(vault)) throw new Error("graph changed while assembling semantic edges; restart from the first page");
|
|
66
|
+
if (entry.semantic.size >= 4) entry.semantic.delete(entry.semantic.keys().next().value!);
|
|
67
|
+
entry.semantic.set(query, pages);
|
|
68
|
+
}
|
|
69
|
+
page = resolveSemanticPage(entry.assembly, pages, k, minScore, args.page as string | undefined);
|
|
70
|
+
} else page = resolveGraphPage(entry.assembly, args.page as string | undefined);
|
|
71
|
+
const key = `${page.kind}:${query}:${page.offset}`;
|
|
52
72
|
let cursor = entry.cursors.get(key);
|
|
53
|
-
if (cursor === undefined) { cursor = nextSnapshotCursor(); entry.cursors.set(key, cursor); }
|
|
73
|
+
if (cursor === undefined) { if (entry.cursors.size >= 256) entry.cursors.delete(entry.cursors.keys().next().value!); cursor = nextSnapshotCursor(); entry.cursors.set(key, cursor); }
|
|
54
74
|
if (args.after === cursor) return { changed: false, cursor };
|
|
55
75
|
return { ...page, cursor };
|
|
56
76
|
},
|
|
@@ -132,7 +152,7 @@ export const plugin: ConsolePlugin = {
|
|
|
132
152
|
{ id: "history", title: "History", order: 10 },
|
|
133
153
|
{ id: "graph", title: "Graph", order: 11, maxAgeMs: REUSE_MS },
|
|
134
154
|
],
|
|
135
|
-
capabilities: { actions: ["delete", "move", "promote", "promote-from-amem", "settings", "proposal-apply", "proposal-reject"], confirm: true, inbox: true, inboxMaxAgeMs: REUSE_MS, search: true },
|
|
155
|
+
capabilities: { actions: ["delete", "move", "promote", "promote-from-amem", "settings", "proposal-apply", "proposal-reject", "link"], confirm: true, inbox: true, inboxMaxAgeMs: REUSE_MS, search: true },
|
|
136
156
|
},
|
|
137
157
|
async open(ctx): Promise<ConsoleProvider> {
|
|
138
158
|
const home = resolveHome().home;
|
|
@@ -191,9 +211,15 @@ export const plugin: ConsolePlugin = {
|
|
|
191
211
|
};
|
|
192
212
|
|
|
193
213
|
const promote = createPromoteSnapshot(revision.current, candidates);
|
|
194
|
-
const
|
|
214
|
+
const graphStamp = (id: string) => {
|
|
215
|
+
const config = loadRegistry(home), vault = config.vaults.find(v => v.id === id);
|
|
216
|
+
if (!vault) throw new Error("graph: vault is no longer registered; select a registered vault");
|
|
217
|
+
return `${revision.current()}:${vault.enrichment?.enabled ? enrichmentStoreStamp(home, vault, config.vaults, config.denyPaths ?? []) : "disabled"}`;
|
|
218
|
+
};
|
|
219
|
+
const graph = createGraphSnapshotCache(graphStamp, async id => {
|
|
195
220
|
const spec = mcp.vaults.find(v => v.id === id)!;
|
|
196
|
-
|
|
221
|
+
const snapshot = analysisInput(home, id, { expectedVault: spec }).snapshot;
|
|
222
|
+
return assembleGraphSnapshot(snapshot, id, graphEnrichmentInputs(home, id, snapshot));
|
|
197
223
|
});
|
|
198
224
|
const inbox = createInboxSnapshot(home, mcp.vaults, ctx.log, undefined, revision.current);
|
|
199
225
|
// One cursor for the whole Promote failure: a fresh one per failed scan would rebuild the panel every poll.
|
|
@@ -204,11 +230,17 @@ export const plugin: ConsolePlugin = {
|
|
|
204
230
|
if (typeof args === "string") return { ok: false, error: args };
|
|
205
231
|
const preview = await call(tool, args);
|
|
206
232
|
if (preview.refused || preview.ok === false || typeof preview.fingerprint !== "string") return { ok: false, error: firstIssue(preview) };
|
|
233
|
+
if (preview.unchanged === true) return { ok: true, message: `${describe(preview).verb}: already done, nothing changed` };
|
|
207
234
|
if (!confirmed || fingerprint !== preview.fingerprint) {
|
|
208
235
|
const d = describe(preview);
|
|
209
236
|
return { ok: false, needsConfirm: true, fingerprint: preview.fingerprint, verb: d.verb, preview: d.preview, changes: d.changes, ...(d.warnings.length ? { warnings: d.warnings } : {}) };
|
|
210
237
|
}
|
|
211
238
|
const done = await call(tool, { ...args, confirm: true, fingerprint });
|
|
239
|
+
// A tool that answers a stale fingerprint with a fresh preview (vmem_link) gets a new confirmation, never a write.
|
|
240
|
+
if (done.stale === true && typeof done.fingerprint === "string") {
|
|
241
|
+
const d = describe(done);
|
|
242
|
+
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] };
|
|
243
|
+
}
|
|
212
244
|
if (done.applied === true) { lintCache.clear(); revision.invalidate(); inbox.invalidate(); }
|
|
213
245
|
return confirmedOutcome(done, describe(preview).verb);
|
|
214
246
|
}
|
|
@@ -236,6 +268,10 @@ export const plugin: ConsolePlugin = {
|
|
|
236
268
|
case "graph": {
|
|
237
269
|
const vault = vaultOf(args);
|
|
238
270
|
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" };
|
|
271
|
+
if (args.similar !== undefined) {
|
|
272
|
+
const result = await readTool("vmem_similar", args, { vault: vault.id, path: args.similar });
|
|
273
|
+
return "error" in result ? result : { similar: result.result.hits };
|
|
274
|
+
}
|
|
239
275
|
const stem = (value: unknown) => typeof value === "string" && value.startsWith("notes/") && value.endsWith(".md") ? value.slice(6, -3) : value;
|
|
240
276
|
if (args.neighbors !== undefined) {
|
|
241
277
|
const r = await readTool("vmem_graph_neighbors", args, { vault: vault.id, path: stem(args.neighbors) });
|
|
@@ -370,6 +406,14 @@ export const plugin: ConsolePlugin = {
|
|
|
370
406
|
warnings: backlinks.length ? [`${backlinks.length} links point here: ${[...new Set(backlinks.map(b => b.source))].slice(0, 5).join(", ")}`] : [] };
|
|
371
407
|
});
|
|
372
408
|
}
|
|
409
|
+
case "link": {
|
|
410
|
+
const from = str(args.from), to = str(args.to), relation = str(args.relation);
|
|
411
|
+
if (!from || !to || !relation) return { ok: false, error: "link: from, to and relation are required; pick both notes and a relation" };
|
|
412
|
+
if (!(LINK_RELATIONS as readonly string[]).includes(relation)) return { ok: false, error: `link: invalid relation ${relation}; use one of ${LINK_RELATIONS.join(", ")}` };
|
|
413
|
+
const both = args.bidirectional !== false && args.bidirectional !== "false";
|
|
414
|
+
return twoStep("vmem_link", forward("vmem_link", args, { preview: true, bidirectional: both }), confirmed, fingerprint, p => ({ verb: "Link notes",
|
|
415
|
+
preview: [`link ${from} → ${to} (${relation})${both ? ", both directions" : ", one way"}`, ...(p.logEvent ? [`log: ${JSON.stringify(p.logEvent)}`] : [])], changes: changesOf(p), warnings: [] }));
|
|
416
|
+
}
|
|
373
417
|
case "move": {
|
|
374
418
|
const from = str(args.from), to = str(args.to);
|
|
375
419
|
if (!from || !to) return { ok: false, error: "from and to are required" };
|
|
@@ -446,5 +490,5 @@ export const plugin: ConsolePlugin = {
|
|
|
446
490
|
};
|
|
447
491
|
|
|
448
492
|
export default plugin;
|
|
449
|
-
export type { ProposalState, ProposalsSnapshot, AssertionsSnapshot, HistorySnapshot, CoverageWarning, GraphSnapshotPage, GraphPanelPage, GraphNodeColumns, GraphEdgeColumns } from "./panel-types.ts";
|
|
493
|
+
export type { ProposalState, ProposalsSnapshot, AssertionsSnapshot, HistorySnapshot, CoverageWarning, GraphSnapshotPage, GraphPanelPage, GraphNodeColumns, GraphEdgeColumns, SemanticGraphPage } from "./panel-types.ts";
|
|
450
494
|
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
|
|
|
@@ -137,6 +137,32 @@ export function collectUnresolvedGraph(snapshot: AnalysisSnapshot): GraphEdge[]
|
|
|
137
137
|
}
|
|
138
138
|
return [...edges.values()].sort((a, b) => compare(a.target, b.target) || compare(a.source, b.source));
|
|
139
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
|
+
}
|
|
140
166
|
function adjacency(graph: Pick<VaultGraph, "nodes" | "edges">): Map<string, Set<string>> {
|
|
141
167
|
const neighbors = new Map(graph.nodes.map(node => [node.id, new Set<string>()]));
|
|
142
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) {
|