@staix/vault-mem 0.11.0 → 0.12.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 +16 -0
- package/README.md +17 -2
- package/bin/vmem.js +5 -1
- package/package.json +2 -1
- package/skills/_shared/vault-adapter.md +131 -0
- package/skills/skill-mine/SKILL.md +52 -0
- package/skills/skill-mine/vocab/actions.yaml +110 -0
- package/skills/skill-mine/vocab/objects.yaml +123 -0
- package/skills/vault-connect/SKILL.md +75 -0
- package/skills/vault-enrich/SKILL.md +31 -0
- package/skills/vault-extract/README.md +20 -0
- package/skills/vault-extract/SKILL.md +139 -0
- package/skills/vault-graph/SKILL.md +120 -0
- package/skills/vault-learn/SKILL.md +111 -0
- package/skills/vault-lint/README.md +32 -0
- package/skills/vault-lint/SKILL.md +137 -0
- package/skills/vault-lint/references/lint-output.md +97 -0
- package/skills/vault-lint/references/vault-scope-rules.md +26 -0
- package/skills/vault-lint/references/work-scope-checks.md +71 -0
- package/skills/vault-refactor/SKILL.md +112 -0
- package/skills/vault-remember/SKILL.md +38 -0
- package/skills/vault-rethink/README.md +15 -0
- package/skills/vault-rethink/SKILL.md +58 -0
- package/skills/vault-stats/SKILL.md +49 -0
- package/skills/vault-sync/README.md +15 -0
- package/skills/vault-sync/SKILL.md +195 -0
- package/skills/vault-sync/references/r4-method-evidence.md +12 -0
- package/skills/vault-update/SKILL.md +68 -0
- package/skills/vmem-status/SKILL.md +30 -0
- package/src/amem/host-api.ts +5 -1
- package/src/analysis-input.ts +15 -0
- package/src/analysis-types.ts +3 -1
- package/src/assertion-policy.ts +4 -2
- package/src/assertions.ts +48 -8
- package/src/cli-output.ts +10 -3
- package/src/cli.ts +29 -3
- package/src/commands-table.ts +3 -1
- package/src/config.ts +21 -7
- package/src/enrichment-query.ts +65 -0
- package/src/enrichment-search.ts +69 -0
- package/src/enrichment-store.ts +197 -0
- package/src/enrichment.ts +245 -0
- package/src/graph-evidence.ts +2 -2
- package/src/index.ts +9 -0
- package/src/mcp-vault.ts +46 -8
- package/src/proposal-provider.ts +3 -2
- package/src/proposals.ts +10 -4
- package/src/read-output.ts +1 -1
- package/src/registry.ts +57 -2
- package/src/setup.ts +12 -3
- package/src/skills-install.ts +216 -0
- package/src/ui/panel-types.ts +55 -0
- package/src/ui/panel.js +76 -0
- package/src/ui/plugin.ts +95 -5
- package/src/vault-graph.ts +15 -7
- package/src/vault-index.ts +17 -0
- package/src/vault-lint.ts +12 -4
- package/src/write-operations.ts +38 -1
- package/src/write-types.ts +1 -0
- package/src/write-validation.ts +2 -1
- package/src/writer.ts +1 -1
package/src/vault-graph.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AnalysisSnapshot } from "./analysis-types.ts";
|
|
2
|
-
import { LINK_RELATIONS } from "./links.ts";
|
|
2
|
+
import { authoredLinkOffsets, LINK_RELATIONS } from "./links.ts";
|
|
3
3
|
export { LINK_RELATIONS };
|
|
4
4
|
import { AnalysisYamlUnsupported, parseAnalysisYaml, scalarText, yamlTruthy } from "./analysis-yaml.ts";
|
|
5
5
|
|
|
@@ -15,7 +15,7 @@ export interface GraphNode {
|
|
|
15
15
|
community: number | null;
|
|
16
16
|
degree: number;
|
|
17
17
|
}
|
|
18
|
-
export interface GraphEdge { source: string; target: string; relation: "wiki_link" | "fm_ref" | "bu_member" | "source_ref" | "related" | "supersedes"; field?: string; rel?: string; confidence_tag: "EXTRACTED"; confidence: 1 }
|
|
18
|
+
export interface GraphEdge { source: string; target: string; relation: "wiki_link" | "fm_ref" | "bu_member" | "source_ref" | "related" | "supersedes"; field?: string; rel?: string; confidence_tag: "EXTRACTED" | "INFERRED"; confidence: 1 }
|
|
19
19
|
export interface VaultGraph {
|
|
20
20
|
directed: false;
|
|
21
21
|
multigraph: false;
|
|
@@ -120,9 +120,9 @@ function adjacency(graph: Pick<VaultGraph, "nodes" | "edges">): Map<string, Set<
|
|
|
120
120
|
return neighbors;
|
|
121
121
|
}
|
|
122
122
|
/** Leiden over the graph's own nodes and edges, with MOC/bu hubs excluded; writes `community` and the method metadata. */
|
|
123
|
-
function communities(graph: VaultGraph): void {
|
|
123
|
+
function communities(graph: VaultGraph, resolution: number): void {
|
|
124
124
|
const exclude = new Set(graph.nodes.filter(node => HUB_TYPES.has(node.type)).map(node => node.id));
|
|
125
|
-
const result = leidenCommunities(graph.nodes.map(node => node.id), graph.edges.map(edge => [edge.source, edge.target] as const), { exclude });
|
|
125
|
+
const result = leidenCommunities(graph.nodes.map(node => node.id), graph.edges.map(edge => [edge.source, edge.target] as const), { exclude, resolution });
|
|
126
126
|
for (const node of graph.nodes) node.community = result.membership.get(node.id) ?? null;
|
|
127
127
|
graph.graph = { partitioner: "leiden", resolution: result.resolution, modularity: result.modularity, iterations: result.levels, max_iterations: MAX_ITERATIONS };
|
|
128
128
|
}
|
|
@@ -357,6 +357,10 @@ export function graphBody(source: string): { body: string; offset: number } {
|
|
|
357
357
|
export const LEGACY_LINK = /\[\[([^\]|]+?)(?:\|[^\]]+?)?\]\]/g;
|
|
358
358
|
/** Legacy target normalisation: trimmed, lower case, spaces to hyphens. */
|
|
359
359
|
export const legacyTarget = (text: string) => text.trim().toLowerCase().replaceAll(" ", "-");
|
|
360
|
+
/** Canonical inferred link targets are lowercase kebab-case note stems. */
|
|
361
|
+
export function inferredLinkTargets(value: unknown): Set<string> {
|
|
362
|
+
return new Set(Array.isArray(value) ? value.filter((item): item is string => typeof item === "string" && /^[a-z0-9][a-z0-9-]{0,190}$/.test(item)) : []);
|
|
363
|
+
}
|
|
360
364
|
/** Pure transformation of the derived-index snapshot, preserving the reference wiki graph semantics. */
|
|
361
365
|
export function buildGraph(snapshot: AnalysisSnapshot): VaultGraph {
|
|
362
366
|
if (snapshot.notes.length > MAX_NODES) throw new Error(`graph: exceeds ${MAX_NODES} notes`);
|
|
@@ -371,13 +375,17 @@ export function buildGraph(snapshot: AnalysisSnapshot): VaultGraph {
|
|
|
371
375
|
confidence: pyString(truthy(fm.confidence) ? fm.confidence : ""), source_file: `notes/${id}.md`,
|
|
372
376
|
topics: Array.isArray(topics) ? topics.map(topic => pyString(topic).replaceAll("[[", "").replaceAll("]]", "")).join(", ") : pyString(topics),
|
|
373
377
|
community: null, degree: 0 });
|
|
378
|
+
const inferredTargets = inferredLinkTargets(fm.inferred_links), authored = authoredLinkOffsets(body);
|
|
374
379
|
for (const match of body.matchAll(LEGACY_LINK)) {
|
|
375
380
|
const target = legacyTarget(match[1]!);
|
|
376
381
|
if (!stems.has(target)) continue;
|
|
377
382
|
const [source, destination] = [id, target].sort(compare) as [string, string];
|
|
378
383
|
const key = JSON.stringify([source, destination]), rel = linkRelation(body, match.index, match[0].length), prior = edges.get(key);
|
|
379
384
|
const kept = prior?.rel ?? rel;
|
|
380
|
-
|
|
385
|
+
const inferred = inferredTargets.has(target) && authored.has(match.index);
|
|
386
|
+
// This declaration is unverified; any qualifying authored occurrence marks the undirected edge.
|
|
387
|
+
const tag = inferred || prior?.confidence_tag === "INFERRED" ? "INFERRED" : "EXTRACTED";
|
|
388
|
+
edges.set(key, { source, target: destination, relation: "wiki_link", ...(kept ? { rel: kept } : {}), confidence_tag: tag, confidence: 1 });
|
|
381
389
|
if (edges.size > MAX_EDGES) throw new Error(`graph: exceeds ${MAX_EDGES} edges`);
|
|
382
390
|
}
|
|
383
391
|
}
|
|
@@ -385,7 +393,7 @@ export function buildGraph(snapshot: AnalysisSnapshot): VaultGraph {
|
|
|
385
393
|
edges: [...edges.values()].sort((a, b) => compare(a.source, b.source) || compare(a.target, b.target)) };
|
|
386
394
|
const neighbors = adjacency(graph);
|
|
387
395
|
for (const node of nodes) node.degree = neighbors.get(node.id)!.size + Number(neighbors.get(node.id)!.has(node.id));
|
|
388
|
-
communities(graph);
|
|
396
|
+
communities(graph, snapshot.graphResolution ?? LEIDEN_RESOLUTION);
|
|
389
397
|
return graph;
|
|
390
398
|
}
|
|
391
399
|
/** An edge's link relation: its typed `rel`, else the edge relation (`wiki_link` for a plain link). */
|
|
@@ -497,6 +505,6 @@ export function graphReport(graph: VaultGraph, today: string): string {
|
|
|
497
505
|
export function finalizeGraph(graph: VaultGraph): VaultGraph {
|
|
498
506
|
const neighbors = adjacency(graph);
|
|
499
507
|
for (const node of graph.nodes) node.degree = neighbors.get(node.id)!.size + Number(neighbors.get(node.id)!.has(node.id));
|
|
500
|
-
communities(graph);
|
|
508
|
+
communities(graph, graph.graph.resolution);
|
|
501
509
|
return graph;
|
|
502
510
|
}
|
package/src/vault-index.ts
CHANGED
|
@@ -188,10 +188,14 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
|
|
|
188
188
|
private readonly db: Database;
|
|
189
189
|
readonly file: string;
|
|
190
190
|
private readonly root: string;
|
|
191
|
+
private readonly rootIdentity: { dev: number; ino: number };
|
|
192
|
+
private hasScanned = false;
|
|
191
193
|
private readonly adapter?: IndexSourceAdapter;
|
|
192
194
|
constructor(home: string, readonly vault: Source, vaultRoots: string[] = [vault.path], options: IndexOptions = {}) {
|
|
193
195
|
this.adapter = options.adapter;
|
|
194
196
|
this.root = this.adapter ? realPath(vault.path) : realpathSync(vault.path);
|
|
197
|
+
const rootStat = lstatSync(this.root);
|
|
198
|
+
this.rootIdentity = { dev: rootStat.dev, ino: rootStat.ino };
|
|
195
199
|
if (this.root !== vault.path) throw new Error(this.adapter ? "spec index: worktree path changed; resolve the source again with resolveSpecWorktree" : `vault ${vault.id}: registered path changed`);
|
|
196
200
|
const notes = join(this.root, "notes");
|
|
197
201
|
if (this.adapter) this.adapter.validate();
|
|
@@ -284,6 +288,7 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
|
|
|
284
288
|
}
|
|
285
289
|
/** Scan metadata each call; hash only new or metadata-changed files. Atomic cache update. */
|
|
286
290
|
scan(rebuild = false, options: { skipInvalidFrontmatter?: boolean; captureInvalidFrontmatter?: boolean; denyPaths?: string[] } = {}): { notes: number; changed: number; removed: number; skipped?: string[] } {
|
|
291
|
+
this.hasScanned = false;
|
|
287
292
|
if (rebuild && options.denyPaths?.length) throw new Error("index: rebuild cannot use denyPaths restrictions; use scan(false, { denyPaths }) for a restricted refresh or vmem rebuild <vault> for an unrestricted rebuild");
|
|
288
293
|
// Discovery/binding Git calls must never hold a SQLite writer lock.
|
|
289
294
|
let preparedPaths: string[] | undefined;
|
|
@@ -419,6 +424,7 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
|
|
|
419
424
|
return { notes: live.size, changed, removed, ...(skipped.length ? { skipped } : {}) };
|
|
420
425
|
}).immediate();
|
|
421
426
|
this.adapter?.validate();
|
|
427
|
+
this.hasScanned = true;
|
|
422
428
|
return result;
|
|
423
429
|
}
|
|
424
430
|
/** Consume cached note sources only. Auxiliary inputs are captured separately by analysisInput. */
|
|
@@ -450,6 +456,17 @@ export class VaultIndex<Source extends VaultSpec | SpecSourceSpec = VaultSpec> {
|
|
|
450
456
|
.slice(snapshot ? snapshotOffset : 0, (snapshot ? snapshotOffset : 0) + (snapshot && allSnapshotRows ? 10000 : limit))
|
|
451
457
|
.map(({ sourceHash: _, ...row }) => ({ ...row, title: boundedText(row.title, 512).content, snippet: boundedText(row.snippet, 1024).content, type: boundedText(row.type, 256).content, domain: boundedText(row.domain, 256).content }));
|
|
452
458
|
}
|
|
459
|
+
/** True only while the source directory is the one this index was opened against. */
|
|
460
|
+
sourceIdentityCurrent(): boolean {
|
|
461
|
+
try { const stat = lstatSync(this.root); return this.hasScanned && stat.isDirectory() && !stat.isSymbolicLink() && stat.dev === this.rootIdentity.dev && stat.ino === this.rootIdentity.ino && realpathSync(this.root) === this.root; }
|
|
462
|
+
catch { return false; }
|
|
463
|
+
}
|
|
464
|
+
/** Bounded metadata and content hashes for a vector join; never returns note bodies. */
|
|
465
|
+
enrichmentPointers(): (SearchResult & { hash: string })[] {
|
|
466
|
+
const rows = this.db.query<{path:string;hash:string;title:string;description:string;type:string;domain:string}, []>("SELECT path,hash,title,substr(description,1,512) AS description,type,domain FROM notes ORDER BY path LIMIT 10001").all();
|
|
467
|
+
if (rows.length > 10000) throw new Error("enrichment: more than 10000 indexed notes; reduce the vault before vector search");
|
|
468
|
+
return rows.map(r => ({ ...r, title: boundedText(r.title, 512).content, type: boundedText(r.type, 256).content, domain: boundedText(r.domain, 256).content, score: 0, snippet: "" }));
|
|
469
|
+
}
|
|
453
470
|
/** Intent words are OR terms; reuse the search tokenizer, BM25 weights and CJK substring/strong-match rules.
|
|
454
471
|
* Materialize scores before grouping: FTS5 auxiliary functions cannot run in an aggregate context. No bodies leave SQL. */
|
|
455
472
|
briefMatches(words: string[]): { path: string; score: number }[] {
|
package/src/vault-lint.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { BUILTIN_DOMAINS } from "./config.ts";
|
|
2
2
|
import { parseAnalysisYaml, scalarText, yamlTruthy, AnalysisYamlUnsupported } from "./analysis-yaml.ts";
|
|
3
|
+
import { authoredLinkOffsets } from "./links.ts";
|
|
4
|
+
import { inferredLinkTargets, legacyTarget, LEGACY_LINK } from "./vault-graph.ts";
|
|
3
5
|
import type { AnalysisSnapshot, LintCode, LintReport } from "./analysis-types.ts";
|
|
4
6
|
const TYPES = ["decision", "insight", "method", "moc", "observation", "person", "project", "reference"];
|
|
5
7
|
const CONFIDENCE = ["experimental", "likely", "proven"], STATUS = ["active", "archived", "superseded"];
|
|
@@ -9,7 +11,7 @@ const LEGACY = new Set("CREATE UPDATE MIGRATE REFACTOR MERGE MOVE RELOCATE RENAM
|
|
|
9
11
|
const CODE_TITLES: Record<LintCode, string> = {
|
|
10
12
|
L01: "L01 — dead wiki-link", L02: "L02 — 필수 frontmatter / 허용값", L03: "L03 — orphan",
|
|
11
13
|
L09: "L09 — 로그 포맷", L10: "L10 — project 값", L11: "L11 — graph report staleness", L12: "L12 — island community", L13: "L13 — filename", L14: "L14 — source paths",
|
|
12
|
-
L15: "L15 — proven confidence의 source", L16: "L16 — evidence drift", L17: "L17 — source changed after updated",
|
|
14
|
+
L15: "L15 — proven confidence의 source", L16: "L16 — evidence drift", L17: "L17 — source changed after updated", L18: "L18 — enrichment vectors", L19: "L19 — inferred link without body link",
|
|
13
15
|
};
|
|
14
16
|
const truth = yamlTruthy;
|
|
15
17
|
const emptySource = (value: unknown) => !truth(value) || typeof value === "string" && !value.trim();
|
|
@@ -121,8 +123,10 @@ function sourceAgeInfo(age: AnalysisSnapshot["sourceAge"]): string {
|
|
|
121
123
|
export function lintVault(snapshot: AnalysisSnapshot, only?: string): LintReport { return lintDetails(snapshot, only).report; }
|
|
122
124
|
/** The report plus what only its markdown carries: the note count, check titles and per-check info lines, for the CLI text view. */
|
|
123
125
|
export function lintDetails(snapshot: AnalysisSnapshot, only?: string): { report: LintReport; notes: number; titles: Record<LintCode, string>; info: Partial<Record<LintCode, string>> } {
|
|
124
|
-
const findings: Record<LintCode,string[]> = {L01:[],L02:[],L03:[],L09:[],L10:[],L11:[],L12:[],L13:[],L14:[],L15:[],L16:[],L17:[]}
|
|
126
|
+
const findings: Record<LintCode,string[]> = {L01:[],L02:[],L03:[],L09:[],L10:[],L11:[],L12:[],L13:[],L14:[],L15:[],L16:[],L17:[]} as unknown as Record<LintCode, string[]>;
|
|
127
|
+
if (snapshot.enrichmentWarnings !== undefined) findings.L18 = [];
|
|
125
128
|
const notes = [...snapshot.notes].sort((a,b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).map(n => ({...n,...legacyDocument(n.source),stem: n.path.replace(/^notes\//, "").slice(0,-3)}));
|
|
129
|
+
if (notes.some(note => note.fm && Object.hasOwn(note.fm, "inferred_links"))) findings.L19 = [];
|
|
126
130
|
const stems = new Set(notes.map(n => n.stem)), inlinks = new Map(notes.map(n => [n.stem,0]));
|
|
127
131
|
// A text the hint pass never reached was not looked up, so its line must not read as a title that merely did not match.
|
|
128
132
|
const bound = snapshot.linkHintBound, attempted = bound ? new Set(bound.attempted) : undefined;
|
|
@@ -132,6 +136,7 @@ export function lintDetails(snapshot: AnalysisSnapshot, only?: string): { report
|
|
|
132
136
|
for (const message of ownValue(snapshot.sourceWarnings, note.path) ?? []) findings.L14.push(prefix+message);
|
|
133
137
|
for (const message of ownValue(snapshot.evidenceWarnings, note.path) ?? []) findings.L16.push(prefix+message);
|
|
134
138
|
for (const message of ownValue(snapshot.sourceAge?.findings, note.path) ?? []) findings.L17.push(prefix+message);
|
|
139
|
+
for (const message of ownValue(snapshot.enrichmentWarnings, note.path) ?? []) findings.L18.push(prefix+message);
|
|
135
140
|
const allLinks: [string,string][] = links(note.body).map(t => ["body",t]);
|
|
136
141
|
if (fm) for (const field of FIELDS) for (const t of links(fm[field])) allLinks.push([field,t]);
|
|
137
142
|
for (const [field,t] of allLinks) {
|
|
@@ -144,6 +149,9 @@ export function lintDetails(snapshot: AnalysisSnapshot, only?: string): { report
|
|
|
144
149
|
findings.L01.push(prefix + `\`[[${t}]]\` (${field}) → 대상 노트 없음` + suffix);
|
|
145
150
|
}
|
|
146
151
|
}
|
|
152
|
+
const authored = authoredLinkOffsets(note.body);
|
|
153
|
+
const bodyTargets = new Set([...note.body.matchAll(LEGACY_LINK)].filter(match => authored.has(match.index)).map(match => legacyTarget(match[1]!)));
|
|
154
|
+
for (const target of inferredLinkTargets(fm?.inferred_links)) if (!bodyTargets.has(target)) findings.L19!.push(prefix + `inferred_links \`${target}\` has no body link`);
|
|
147
155
|
if (fm === null) { findings.L02.push(prefix + "frontmatter 없음/파싱 실패"); continue; }
|
|
148
156
|
if (fm.status === "superseded") superseded++;
|
|
149
157
|
if (!TYPES.includes(String(fm.type))) findings.L02.push(prefix + `\`type: ${py(fm.type)}\` 허용값 아님 (${TYPES.join(" | ")})`);
|
|
@@ -177,9 +185,9 @@ export function lintDetails(snapshot: AnalysisSnapshot, only?: string): { report
|
|
|
177
185
|
}
|
|
178
186
|
if (data > 20000) findings.L09.push(`log ${data} 라인 > 20000 — 수동 아카이브 권장`);
|
|
179
187
|
const graph = graphChecks(snapshot); findings.L11 = graph.l11; findings.L12 = graph.l12;
|
|
180
|
-
if (only) for (const code of ["L01","L02","L03","L10","L13","L14","L15","L16","L17"] as const) findings[code] = findings[code].filter(s => s.startsWith(`\`${only}\``));
|
|
188
|
+
if (only) for (const code of ["L01","L02","L03","L10","L13","L14","L15","L16","L17","L18","L19"] as const) if (findings[code]) findings[code] = findings[code].filter(s => s.startsWith(`\`${only}\``));
|
|
181
189
|
const errors = findings.L01.length + findings.L02.length + findings.L13.length;
|
|
182
|
-
const warnings = findings.L03.length + findings.L09.length + findings.L10.length + findings.L11.length + findings.L12.length + findings.L14.length + findings.L15.length + findings.L16.length + findings.L17.length;
|
|
190
|
+
const warnings = findings.L03.length + findings.L09.length + findings.L10.length + findings.L11.length + findings.L12.length + findings.L14.length + findings.L15.length + findings.L16.length + findings.L17.length + (findings.L18?.length ?? 0) + (findings.L19?.length ?? 0);
|
|
183
191
|
const summary = `SUMMARY errors=${errors} warnings=${warnings}`;
|
|
184
192
|
const extra: Partial<Record<LintCode,string>> = {
|
|
185
193
|
L01: bound ? `정보: 힌트 상한 ${bound.cap}개 텍스트 초과 — ${bound.skipped}개 dead link 텍스트는 힌트 미계산 (미탐 아님)` : "",
|
package/src/write-operations.ts
CHANGED
|
@@ -176,6 +176,10 @@ function referenceReplacement(notes: Map<string, string>, from: string, to: stri
|
|
|
176
176
|
return candidates?.size === 1 && candidates.has(from) ? to.slice(6, -3) : undefined;
|
|
177
177
|
};
|
|
178
178
|
}
|
|
179
|
+
const INFERRED_STEM = /^[a-z0-9][a-z0-9-]{0,190}$/;
|
|
180
|
+
function authoredGraphTargets(body: string): Set<string> {
|
|
181
|
+
return new Set(extractLinks(body).filter(link => !link.heading && !link.block).map(link => link.target.trim().toLowerCase().replaceAll(" ", "-")));
|
|
182
|
+
}
|
|
179
183
|
/** Same metadata recursion and visible-body rewrite that move has always used. */
|
|
180
184
|
function rewriteNoteReferences(source: string, path: string, replace: (target: string) => string | undefined, inbound?: MergeInboundLink[], preserve: ReadonlySet<string> = new Set()): string {
|
|
181
185
|
const doc = document(source, path);
|
|
@@ -194,6 +198,18 @@ function rewriteNoteReferences(source: string, path: string, replace: (target: s
|
|
|
194
198
|
};
|
|
195
199
|
const changes: Record<string, unknown> = {};
|
|
196
200
|
for (const [key, value] of Object.entries(doc.data)) changes[key] = preserve.has(key) ? value : rewriteValue(value, key);
|
|
201
|
+
if (Array.isArray(doc.data.inferred_links)) {
|
|
202
|
+
const original = doc.data.inferred_links, beforeTargets = authoredGraphTargets(doc.body), afterBody = rewriteLinkTargets(doc.body, replace), afterTargets = authoredGraphTargets(afterBody);
|
|
203
|
+
const rewritten = original.map(value => typeof value === "string" && INFERRED_STEM.test(value) ? replace(value) ?? value : value);
|
|
204
|
+
for (const [i, value] of original.entries()) {
|
|
205
|
+
if (typeof value !== "string" || !INFERRED_STEM.test(value)) continue;
|
|
206
|
+
const next = rewritten[i];
|
|
207
|
+
if (typeof next !== "string" || !afterTargets.has(next)) continue;
|
|
208
|
+
const priorWitness = original.some(item => typeof item === "string" && INFERRED_STEM.test(item) && (replace(item) ?? item) === next && beforeTargets.has(item));
|
|
209
|
+
if (!priorWitness) refuse("V01", "rewrite would attach an orphan inferred_links declaration to a different body link; repair the declaration before retrying", path);
|
|
210
|
+
}
|
|
211
|
+
changes.inferred_links = rewritten;
|
|
212
|
+
}
|
|
197
213
|
record(doc.body, "body", true);
|
|
198
214
|
const frontmatter = emitFrontmatter(doc, changes).slice(0, -doc.body.length || undefined);
|
|
199
215
|
return (doc.body.length ? frontmatter : emitFrontmatter(doc, changes)) + rewriteLinkTargets(doc.body, replace);
|
|
@@ -281,9 +297,16 @@ export function planMerge(operation: Extract<WriteOp, { op: "merge" }>, notes: M
|
|
|
281
297
|
const removeLeadingTitle = /^ {0,3}#[ \t]+\S/.test(originalLeadingLine);
|
|
282
298
|
const first = withoutMergeTopics(keepDoc.body, keepTopics, keep), second = demoteMergeHeadings(withoutMergeTopics(absorbDoc.body, absorbTopics, absorb), removeLeadingTitle);
|
|
283
299
|
const body = mergeGap(mergeGap(first, newline) + `## Merged from [[${absorb.slice(6, -3)}]]${newline}${newline}` + second, newline) + `## Topics${newline}${newline}` + topics.map(topic => `- ${topic}${newline}`).join("");
|
|
300
|
+
const lists = [keepDoc.data.inferred_links, absorbDoc.data.inferred_links];
|
|
301
|
+
if (lists.some(value => value !== undefined && (!Array.isArray(value) || value.some(item => typeof item !== "string" || !INFERRED_STEM.test(item))))) refuse("V01", "merge requires valid inferred_links lists; repair them before retrying", keep);
|
|
302
|
+
const keepLinks = (lists[0] ?? []) as string[], absorbLinks = (lists[1] ?? []) as string[];
|
|
303
|
+
const keepTargets = authoredGraphTargets(keepDoc.body), absorbTargets = authoredGraphTargets(absorbDoc.body), mergedTargets = authoredGraphTargets(body);
|
|
304
|
+
for (const target of keepLinks) if (!keepTargets.has(target) && mergedTargets.has(target)) refuse("V01", "merge would attach an orphan inferred_links declaration to a different body link; repair it before retrying", keep);
|
|
305
|
+
const inferred = [...new Set([...keepLinks, ...absorbLinks.filter(target => absorbTargets.has(target) && mergedTargets.has(target))])];
|
|
306
|
+
if (inferred.length > 1000) refuse("V09", "merged inferred_links exceeds 1000 entries; trim the lists before retrying", keep);
|
|
284
307
|
if (Buffer.byteLength(body) > MAX_WRITE_BYTES) refuse("V09", "merged body exceeds 256 KiB; shorten either note's content before retrying the merge", keep);
|
|
285
308
|
try {
|
|
286
|
-
const metadata = emitFrontmatter(keepDoc, { source: sources.length ? sources : undefined, topics });
|
|
309
|
+
const metadata = emitFrontmatter(keepDoc, { source: sources.length ? sources : undefined, topics, ...(lists[0] !== undefined || inferred.length ? { inferred_links: inferred } : {}) });
|
|
287
310
|
rewritten.set(keep, (parseFrontmatter(metadata).frontmatter ?? "") + body);
|
|
288
311
|
rewritten.set(absorb, supersededNote(rewritten.get(absorb)!, absorb, keep));
|
|
289
312
|
} catch { refuse("V01", "merge metadata cannot be edited losslessly; convert endpoint headers to editable block mappings and retry the merge", keep); }
|
|
@@ -361,6 +384,20 @@ export function planOperation(operation: WriteOp, notes: Map<string, string>, re
|
|
|
361
384
|
set(path, after + source.slice(cursor));
|
|
362
385
|
break;
|
|
363
386
|
}
|
|
387
|
+
case "infer-link": {
|
|
388
|
+
const from = existing(operation.path), to = existing(operation.target), stem = to.path.slice(6, -3);
|
|
389
|
+
if (from.path === to.path) refuse("V01", "inferred link endpoints must differ; select another target note", from.path);
|
|
390
|
+
if (typeof operation.expectedSha !== "string" || !/^[a-f0-9]{64}$/.test(operation.expectedSha)) refuse("V09", "inferred link requires the source note's current SHA-256; reread the source before retrying", from.path);
|
|
391
|
+
const doc = document(from.source, from.path), links = doc.data.inferred_links;
|
|
392
|
+
if (links !== undefined && (!Array.isArray(links) || links.some(value => typeof value !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(value)))) refuse("V01", "inferred_links must be a list of note stems; repair it before adding a link", from.path);
|
|
393
|
+
if (bodyAlreadyLinks(notes, from.path, to.path)) refuse("V08", "the target is already linked in the body; inspect the note", from.path);
|
|
394
|
+
try {
|
|
395
|
+
const current = links as string[] | undefined;
|
|
396
|
+
const metadata = current?.includes(stem) ? from.source : emitFrontmatter(doc, { inferred_links: [...(current ?? []), stem] });
|
|
397
|
+
set(from.path, appendSection(metadata, "Relevant Notes", `- [[${stem}]]`, from.path));
|
|
398
|
+
} catch (error) { if (error instanceof WriteRefusal) throw error; refuse("V01", "cannot update inferred_links without rewriting frontmatter; repair the header", from.path); }
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
364
401
|
case "append": { const { path, source } = existing(operation.path); set(path, appendSection(source, operation.section, operation.markdown, path)); break; }
|
|
365
402
|
case "frontmatter": {
|
|
366
403
|
const { path, source } = existing(operation.path);
|
package/src/write-types.ts
CHANGED
|
@@ -10,6 +10,7 @@ export type WriteOp =
|
|
|
10
10
|
| { op: "create"; path: string; frontmatter: Record<string, unknown>; body?: string }
|
|
11
11
|
/** One `oldString`/`newString` pair or `edits` (1..32 pairs), never both; edits apply all-or-nothing against the original text. */
|
|
12
12
|
| { op: "patch"; path: string; oldString?: string; newString?: string; edits?: PatchEdit[]; expectedSha?: string }
|
|
13
|
+
| { op: "infer-link"; path: string; target: string; expectedSha: string }
|
|
13
14
|
| { op: "append"; path: string; section: string; markdown: string; expectedSha?: string }
|
|
14
15
|
| { op: "frontmatter"; path: string; set: Record<string, unknown>; unset?: string[]; expectedSha?: string }
|
|
15
16
|
| { op: "link"; from: string; to: string; relation: "supports" | "contradicts" | "extends" | "applies-to" | "context-for"; context?: string; bidirectional?: boolean }
|
package/src/write-validation.ts
CHANGED
|
@@ -16,7 +16,7 @@ const CONFIDENCE = new Set(["proven", "likely", "experimental"]);
|
|
|
16
16
|
const STATUS = new Set(["active", "superseded", "archived"]);
|
|
17
17
|
const CATEGORY = new Set(["gap", "prompt", "workflow"]);
|
|
18
18
|
const KEYS = new Set([
|
|
19
|
-
"description", "type", "domain", "topics", "source", "confidence", "status",
|
|
19
|
+
"description", "type", "domain", "topics", "source", "confidence", "status", "inferred_links",
|
|
20
20
|
"methodology", "evidence_strength", "project", "alternatives", "superseded_by", "supersedes", "stakeholders",
|
|
21
21
|
"course", "semester", "student_level", "institution", "policy_area", "role", "affiliation", "last_contact",
|
|
22
22
|
"tool", "category", "resolution_status", "aliases", "tags", "cssclasses", "title", "created", "updated", "received", "entities",
|
|
@@ -162,6 +162,7 @@ function schema(note: ParsedNote, vault: VaultSpec): SchemaIssue[] {
|
|
|
162
162
|
for (const [key, allowed] of [["confidence", CONFIDENCE], ["status", STATUS], ["category", CATEGORY]] as const) {
|
|
163
163
|
if (data[key] !== undefined && (typeof data[key] !== "string" || !allowed.has(data[key]))) add(key,`invalid ${key} enum`);
|
|
164
164
|
}
|
|
165
|
+
if (data.inferred_links !== undefined && (!Array.isArray(data.inferred_links) || data.inferred_links.length > 1000 || data.inferred_links.some(value => typeof value !== "string" || !/^[a-z0-9][a-z0-9-]{0,190}$/.test(value)))) add("inferred_links", "inferred_links must be a list of at most 1000 lowercase kebab-case note stems");
|
|
165
166
|
if(data.source!==undefined)try{sourceReferences(data.source);}catch{add("source","source must contain workspace-relative paths, mem ids or URLs");}
|
|
166
167
|
if(data.evidence!==undefined){const problem=evidenceProblem(data.evidence,data.source);if(problem)add("evidence",problem,["evidence","source"]);}
|
|
167
168
|
if (data.type === "reference") {
|
package/src/writer.ts
CHANGED
|
@@ -362,7 +362,7 @@ function runWrite(home: string, request: WriteRequest, options: WriteOptions & {
|
|
|
362
362
|
}
|
|
363
363
|
const twoStep = ["move", "delete", "tidy", "merge"].includes(request.operation.op);
|
|
364
364
|
const preview = request.operation.op === "check" || request.dryRun === true || (twoStep && request.confirm !== true);
|
|
365
|
-
if (options.proposal && (preview || !options.binding || !["create", "patch"].includes(request.operation.op))) refuse("V01", "proposal confirmation requires one
|
|
365
|
+
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
366
|
if (!preview) {
|
|
367
367
|
lockFile = join(root, MUTATION_LOCK);
|
|
368
368
|
try { lockFd = openSync(lockFile, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); }
|