@staix/vault-mem 0.11.0 → 0.12.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +17 -2
  3. package/bin/vmem.js +5 -1
  4. package/package.json +2 -1
  5. package/skills/_shared/vault-adapter.md +131 -0
  6. package/skills/skill-mine/SKILL.md +52 -0
  7. package/skills/skill-mine/vocab/actions.yaml +110 -0
  8. package/skills/skill-mine/vocab/objects.yaml +123 -0
  9. package/skills/vault-connect/SKILL.md +75 -0
  10. package/skills/vault-extract/README.md +20 -0
  11. package/skills/vault-extract/SKILL.md +139 -0
  12. package/skills/vault-graph/SKILL.md +120 -0
  13. package/skills/vault-learn/SKILL.md +111 -0
  14. package/skills/vault-lint/README.md +32 -0
  15. package/skills/vault-lint/SKILL.md +137 -0
  16. package/skills/vault-lint/references/lint-output.md +97 -0
  17. package/skills/vault-lint/references/vault-scope-rules.md +26 -0
  18. package/skills/vault-lint/references/work-scope-checks.md +71 -0
  19. package/skills/vault-refactor/SKILL.md +112 -0
  20. package/skills/vault-remember/SKILL.md +38 -0
  21. package/skills/vault-rethink/README.md +15 -0
  22. package/skills/vault-rethink/SKILL.md +58 -0
  23. package/skills/vault-stats/SKILL.md +49 -0
  24. package/skills/vault-sync/README.md +15 -0
  25. package/skills/vault-sync/SKILL.md +195 -0
  26. package/skills/vault-sync/references/r4-method-evidence.md +12 -0
  27. package/skills/vault-update/SKILL.md +68 -0
  28. package/skills/vmem-status/SKILL.md +30 -0
  29. package/src/amem/host-api.ts +5 -1
  30. package/src/analysis-input.ts +15 -0
  31. package/src/analysis-types.ts +3 -1
  32. package/src/assertion-policy.ts +4 -2
  33. package/src/assertions.ts +48 -8
  34. package/src/cli-output.ts +10 -3
  35. package/src/cli.ts +29 -3
  36. package/src/commands-table.ts +3 -1
  37. package/src/config.ts +21 -7
  38. package/src/enrichment-query.ts +65 -0
  39. package/src/enrichment-search.ts +69 -0
  40. package/src/enrichment-store.ts +197 -0
  41. package/src/enrichment.ts +245 -0
  42. package/src/graph-evidence.ts +2 -2
  43. package/src/index.ts +9 -0
  44. package/src/mcp-vault.ts +46 -8
  45. package/src/proposal-provider.ts +3 -2
  46. package/src/proposals.ts +10 -4
  47. package/src/read-output.ts +1 -1
  48. package/src/registry.ts +57 -2
  49. package/src/setup.ts +12 -3
  50. package/src/skills-install.ts +216 -0
  51. package/src/ui/panel-types.ts +55 -0
  52. package/src/ui/panel.js +76 -0
  53. package/src/ui/plugin.ts +95 -5
  54. package/src/vault-graph.ts +15 -7
  55. package/src/vault-index.ts +17 -0
  56. package/src/vault-lint.ts +12 -4
  57. package/src/write-operations.ts +38 -1
  58. package/src/write-types.ts +1 -0
  59. package/src/write-validation.ts +2 -1
  60. package/src/writer.ts +1 -1
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Snapshot shapes of the console panels added in vault-mem#266 increment 1b. Each panel answers with the result of the
3
+ * existing reader (proposal provider, assertion reader, Git snapshot history) unchanged, plus the selection it was asked
4
+ * for; a refusal arrives as `error`, naming its cause and next step.
5
+ */
6
+ import type { ProposalPage, ProposalView } from "../proposal-provider.ts";
7
+ import type { AssertionsReadResult } from "../assertion-read.ts";
8
+ import type { ChangesResult, HistoryResult } from "../vault-history.ts";
9
+
10
+ export type ProposalState = "pending" | "applied" | "rejected" | "apply_unknown";
11
+
12
+ /** A coverage notice for the panel: `err` when entries are left out as untrusted, `warn` for other gaps, `neutral` for information. */
13
+ export interface CoverageWarning { tone: "err" | "warn" | "neutral"; message: string }
14
+
15
+ /** `proposals` panel: params `vault`, `state` (default pending), `after` page cursor, `id` to show one proposal. */
16
+ export interface ProposalsSnapshot {
17
+ vault: string | null;
18
+ state: ProposalState;
19
+ page: ProposalPage | null;
20
+ selected: ProposalView | null;
21
+ error?: string;
22
+ }
23
+
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
+ /** `assertions` panel: params `vault`, `subject`, `relation`, `at`, `asOf`, `history`, `cursor`, as `vmem_assertions`. */
40
+ export interface AssertionsSnapshot {
41
+ vault: string | null;
42
+ result: AssertionsReadResult | null;
43
+ /** Every gap in the reported coverage (untrusted, unsupported, torn, partial, purged, unsynced, index), empty when complete. */
44
+ warnings: CoverageWarning[];
45
+ error?: string;
46
+ }
47
+
48
+ /** `history` panel: params `vault`, `path`, `cursor`, and `from` with `to` (full commit ids) for the changes between them. */
49
+ export interface HistorySnapshot {
50
+ vault: string | null;
51
+ path: string | null;
52
+ history: HistoryResult | null;
53
+ changes: ChangesResult | null;
54
+ error?: string;
55
+ }
package/src/ui/panel.js CHANGED
@@ -15,7 +15,33 @@ export default (host) => {
15
15
  input, h("button", { type: "submit", class: "btn", text: "Search" }));
16
16
  };
17
17
 
18
+ /** Journal coverage warnings computed by the provider (`warnings`); anything short of a fully verified journal shows. */
19
+ const coverageNotices = (warnings) => (warnings ?? []).map((w) => ui.notice(w.message, w.tone));
20
+ // A continuation is bound to the query that produced it, so every query param travels with it.
21
+ const assertionQuery = () => Object.fromEntries(["subject", "relation", "at", "asOf", "history", "limit"].filter((k) => params[k] !== undefined && params[k] !== "").map((k) => [k, params[k]]));
22
+
18
23
  const views = {
24
+ settings(s) {
25
+ if (s.error) return [ui.notice(s.error, "err")];
26
+ const defaultVault = h("input", { type: "text", name: "defaultVault", value: s.defaultVault ?? "", class: "vmem-input", "aria-label": "Default vault" });
27
+ const write = h("select", { name: "write", class: "vmem-input", "aria-label": "Write mode" }, ...["none", "cli", "mcp"].map(v => h("option", { value: v, text: v, ...(v === s.write ? { selected: true } : {}) })));
28
+ const patterns = h("input", { type: "text", name: "piiPatterns", value: JSON.stringify(s.piiPatterns ?? []), class: "vmem-input", "aria-label": "PII patterns as JSON array", oninput: (e) => e.target.setCustomValidity("") });
29
+ const resolution = h("input", { type: "number", name: "resolution", value: String(s.graphResolution), min: "0.01", max: "100", step: "any", class: "vmem-input", "aria-label": "Graph resolution" });
30
+ const enrichment = h("input", { type: "checkbox", name: "enrichmentEnabled", checked: s.enrichmentEnabled, "aria-label": "Enable enrichment" });
31
+ return [h("p", { text: `Settings for ${s.vault}${s.defaultVaultExplicit ? "" : " (default vault uses fallback)"}` }), h("form", { class: "vmem-bar", onsubmit: e => {
32
+ e.preventDefault();
33
+ let piiPatterns;
34
+ try { piiPatterns = JSON.parse(patterns.value); } catch { patterns.setCustomValidity("Use a JSON array of patterns"); patterns.reportValidity(); return; }
35
+ patterns.setCustomValidity("");
36
+ const changes = {};
37
+ if (defaultVault.value !== (s.defaultVault ?? "")) changes.defaultVault = defaultVault.value;
38
+ if (write.value !== s.write) changes.write = write.value;
39
+ if (JSON.stringify(piiPatterns) !== JSON.stringify(s.piiPatterns ?? [])) changes.piiPatterns = piiPatterns;
40
+ if (Number(resolution.value) !== s.graphResolution) changes.graphResolution = Number(resolution.value);
41
+ if (enrichment.checked !== s.enrichmentEnabled) changes.enrichmentEnabled = enrichment.checked;
42
+ host.action({ action: "settings", ...vaultParam(), changes });
43
+ } }, defaultVault, write, patterns, resolution, h("label", {}, enrichment, h("span", { text: "Enable enrichment" })), h("button", { type: "submit", class: "btn", text: "Review settings" }))];
44
+ },
19
45
  overview(s) {
20
46
  const vaults = s.status?.vaults ?? [];
21
47
  if (!vaults.length) return [ui.empty("No vault registered", "Run `vmem vaults add <id> <path>` to register one.")];
@@ -112,6 +138,56 @@ export default (host) => {
112
138
  ...(typeof p === "string" && p.startsWith("notes/") ? { onOpen: () => openNote(p) } : {}) });
113
139
  }) ?? ui.empty("Log is empty")];
114
140
  },
141
+ proposals(s) {
142
+ const items = s.page?.items ?? [], p = s.selected;
143
+ const stateSelect = h("select", { name: "state", class: "vmem-input", "aria-label": "Proposal state", onchange: () => go("proposals", { state: stateSelect.value }) },
144
+ ...["pending", "applied", "rejected", "apply_unknown"].map((v) => h("option", { value: v, text: v, ...(v === s.state ? { selected: true } : {}) })));
145
+ const reason = h("input", { type: "text", name: "reason", class: "vmem-input", "aria-label": "Rejection reason", placeholder: "reason for rejecting" });
146
+ const detail = p ? ui.detail({
147
+ kind: "proposal", title: p.path, state: { text: p.state, ...(p.state === "apply_unknown" ? { tone: "warn" } : {}) },
148
+ actions: p.state === "pending" ? [
149
+ ui.button("Apply…", () => host.action({ action: "proposal-apply", id: p.id, ...vaultParam() }), { tone: "primary" }),
150
+ h("form", { class: "vmem-inline", onsubmit: (e) => { e.preventDefault(); if (reason.value.trim()) host.action({ action: "proposal-reject", id: p.id, reason: reason.value.trim(), ...vaultParam() }); } },
151
+ reason, h("button", { type: "submit", class: "btn", text: "Reject…" })),
152
+ ] : [],
153
+ ...(p.decisionReason ? { summary: `reason: ${p.decisionReason}` } : {}),
154
+ sections: [{ title: "Operation", open: true, body: h("div", {}, h("pre", { class: "vmem-body", text: p.content ?? "" }), p.truncated ? ui.notice("Truncated; read the rest with `vmem proposal show`.", "warn") : null) }],
155
+ footer: [`${p.id} · ${p.createdAt}${p.agentLabelUnverified ? ` · agent ${p.agentLabelUnverified} (unverified)` : ""}`],
156
+ }) : null;
157
+ return [s.error ? ui.notice(s.error, "err") : null, h("div", { class: "vmem-bar" }, stateSelect,
158
+ ...(s.page?.nextCursor ? [ui.button("Next page", () => go("proposals", { state: s.state, page: s.page.nextCursor }))] : [])), detail,
159
+ ui.rows(items, (x) => ui.row({ title: x.path, sub: `${x.state} · ${x.createdAt}`, onOpen: () => go("proposals", { state: s.state, id: x.id }), ...(p?.id === x.id ? { chip: { text: "shown", tone: "neutral" } } : {}) }))
160
+ ?? ui.empty(`No ${s.state} proposals`, "Agents submit proposals with `vmem_proposal_submit` when the vault opts in.")];
161
+ },
162
+ assertions(s) {
163
+ const r = s.result, items = r?.items ?? [];
164
+ const subject = h("input", { type: "text", name: "subject", class: "vmem-input", "aria-label": "Subject", placeholder: "subject (optional)", value: params.subject ?? "" });
165
+ const relation = h("input", { type: "text", name: "relation", class: "vmem-input", "aria-label": "Relation", placeholder: "relation (optional)", value: params.relation ?? "" });
166
+ const filter = h("form", { class: "vmem-bar", onsubmit: (e) => { e.preventDefault(); const { subject: _s, relation: _r, ...rest } = assertionQuery(); go("assertions", { ...rest, ...(subject.value.trim() ? { subject: subject.value.trim() } : {}), ...(relation.value.trim() ? { relation: relation.value.trim() } : {}) }); } },
167
+ subject, relation, h("button", { type: "submit", class: "btn", text: "Filter" }));
168
+ return [s.error ? ui.notice(s.error, "err") : null, filter,
169
+ ...coverageNotices(s.warnings),
170
+ ui.rows(items, (a) => ui.row({ title: `${a.subject} · ${a.relation}${a.value !== undefined ? ` = ${a.value}` : ""}`, sub: [a.op, a.from && `from ${a.from}`, a.to && `to ${a.to}`, a.on && `on ${a.on}`, `recorded ${a.recordedAt}`].filter(Boolean).join(" · "),
171
+ ...(a.subjectNote?.path ? { onOpen: () => openNote(a.subjectNote.path) } : {}) }))
172
+ ?? ui.empty("No assertions", "Agents record them with `vmem_assert`."),
173
+ r?.continuation ? ui.button("Next page", () => go("assertions", { ...assertionQuery(), cursor: r.continuation })) : null];
174
+ },
175
+ history(s) {
176
+ const path = h("input", { type: "text", name: "path", class: "vmem-input", "aria-label": "Note path", placeholder: "notes/stem.md", value: s.path ?? "" });
177
+ const form = h("form", { class: "vmem-bar", onsubmit: (e) => { e.preventDefault(); if (path.value.trim()) go("history", { path: path.value.trim() }); } }, path, h("button", { type: "submit", class: "btn", text: "History" }));
178
+ const revs = s.history?.revisions ?? [], changed = s.changes?.changed ?? [];
179
+ const reason = s.history?.capability ?? s.changes?.capability;
180
+ return [s.error ? ui.notice(s.error, "err") : null, form,
181
+ reason ? ui.notice(`Git history is unavailable: ${reason}`, "warn") : null,
182
+ s.changes ? h("section", { class: "card" }, h("h2", { text: `Changes ${s.changes.from.slice(0, 10)} → ${s.changes.to.slice(0, 10)}` }),
183
+ ui.rows(changed, (c) => ui.row({ title: c.path, sub: c.status, onOpen: () => openNote(c.path) })) ?? ui.empty("No note changed"),
184
+ s.changes.continuation ? ui.button("More changes", () => go("history", { ...(s.path ? { path: s.path } : {}), ...(params.cursor ? { cursor: params.cursor } : {}), from: s.changes.from, to: s.changes.to, changesCursor: s.changes.continuation })) : null) : null,
185
+ s.path ? ui.rows(revs.map((r, i) => ({ r, prev: revs[i + 1] })), ({ r, prev }) => ui.row({ title: `${r.revision.slice(0, 10)} · ${r.committedAt}`, sub: `${r.bytes} bytes`,
186
+ ...(prev ? { verbs: [ui.button("Changes since previous", () => go("history", { path: s.path, from: prev.revision, to: r.revision }))] } : {}) }))
187
+ ?? ui.empty("No revisions", "The note has no committed history yet.") : ui.empty("No note selected", "Enter a note path to see its Git history."),
188
+ s.history?.continuation ? h("div", { class: "vmem-bar" }, ui.button("Older revisions", () => go("history", { path: s.path, cursor: s.history.continuation })), ...(params.cursor ? [ui.button("Newest", () => go("history", { path: s.path }))] : [])) : null,
189
+ s.history?.coverage && s.history.coverage.complete === false ? ui.notice(`History is incomplete${s.history.coverage.reason ? `: ${s.history.coverage.reason}` : ""}.`, "warn") : null];
190
+ },
115
191
  };
116
192
 
117
193
  let last = "", savedView = "", savedSnapshot;
package/src/ui/plugin.ts CHANGED
@@ -9,8 +9,10 @@ import { resolveHome } from "../home.ts";
9
9
  import { createVaultMcp } from "../mcp-vault.ts";
10
10
  import { validArguments } from "../mcp.ts";
11
11
  import { listPromotionCandidates } from "../promote.ts";
12
- import { loadRegistry } from "../registry.ts";
12
+ import { changeSettings, settingsSnapshot, loadRegistry } from "../registry.ts";
13
13
  import { createSnapshotRevision, createPromoteSnapshot, nextSnapshotCursor } from "./snapshot-cache.ts";
14
+ import { assertionCoverageWarnings } from "./panel-types.ts";
15
+ import type { AssertionsReadResult } from "../assertion-read.ts";
14
16
  import { createInboxSnapshot } from "./inbox.ts";
15
17
  import { lintVault } from "../vault-lint.ts";
16
18
  import { readLogSince } from "../vault-log.ts";
@@ -90,8 +92,12 @@ export const plugin: ConsolePlugin = {
90
92
  { id: "promote", title: "Promote", order: 4, maxAgeMs: REUSE_MS },
91
93
  { id: "lint", title: "Lint", order: 5, maxAgeMs: REUSE_MS },
92
94
  { id: "log", title: "Log", order: 6, maxAgeMs: REUSE_MS },
95
+ { id: "settings", title: "Settings", order: 7 },
96
+ { id: "proposals", title: "Proposals", order: 8, maxAgeMs: REUSE_MS },
97
+ { id: "assertions", title: "Assertions", order: 9 },
98
+ { id: "history", title: "History", order: 10 },
93
99
  ],
94
- capabilities: { actions: ["delete", "move", "promote", "promote-from-amem"], confirm: true, inbox: true, inboxMaxAgeMs: REUSE_MS, search: true },
100
+ capabilities: { actions: ["delete", "move", "promote", "promote-from-amem", "settings", "proposal-apply", "proposal-reject"], confirm: true, inbox: true, inboxMaxAgeMs: REUSE_MS, search: true },
95
101
  },
96
102
  async open(ctx): Promise<ConsoleProvider> {
97
103
  const home = resolveHome().home;
@@ -100,6 +106,7 @@ export const plugin: ConsolePlugin = {
100
106
  // The shell's tabs navigate without params, so the vault chosen on one panel is kept for the others.
101
107
  // ponytail: one choice per provider; fine for H0's single person, per session once H1 serves several.
102
108
  let chosen: string | undefined;
109
+ const promotionSource = mcp.vaults.find(v => v.id === mcp.defaultVault && v.kind === "personal") ?? mcp.vaults.find(v => v.kind === "personal");
103
110
  // An explicit vault must exist (undefined otherwise, like MCP's own check); only an omitted one falls back.
104
111
  const vaultOf = (args: Args) => {
105
112
  const asked = str(args.vault);
@@ -167,12 +174,31 @@ export const plugin: ConsolePlugin = {
167
174
  return confirmedOutcome(done, describe(preview).verb);
168
175
  }
169
176
 
177
+ /**
178
+ * A read panel through the MCP handler: arguments are checked against the tool schema, and a thrown refusal
179
+ * (unknown vault, invalid cursor, missing proposal) becomes the snapshot's `error` text, which names cause and next step.
180
+ */
181
+ async function readTool(tool: string, args: Args, fixed: Args = {}): Promise<{ result: Args } | { error: string }> {
182
+ const checked = forward(tool, args, fixed);
183
+ if (typeof checked === "string") return { error: `${checked}; correct the panel parameters and reload` };
184
+ try {
185
+ const result = await call(tool, checked);
186
+ return result.refused ? { error: firstIssue(result) } : { result };
187
+ } catch (error) { return { error: error instanceof Error ? error.message : String(error) }; }
188
+ }
189
+ const PROPOSAL_STATES = ["pending", "applied", "rejected", "apply_unknown"];
190
+
170
191
  return {
171
192
  async close() { await inbox.close(); },
172
193
  assets: { js: asset("./panel.js"), css: asset("./panel.css") },
173
194
  async snapshot(input) {
174
195
  const args = input as Args;
175
196
  switch (input.panel) {
197
+ case "settings": {
198
+ const vault = vaultOf(args);
199
+ if (!vault) return { error: "settings: no selected vault; select a registered vault" };
200
+ return settingsSnapshot(home, vault.id);
201
+ }
176
202
  case "inbox": {
177
203
  const result = await inbox.snapshot();
178
204
  return args.after === result.cursor ? { changed: false, cursor: result.cursor } : result;
@@ -205,8 +231,8 @@ export const plugin: ConsolePlugin = {
205
231
  const note = await call("vmem_read", { path, ...pass(args) });
206
232
  if (note.refused) return { note: null, error: firstIssue(note) };
207
233
  const links = await call("vmem_links", { path, ...pass(args) });
208
- // vmem_promote always reads from the default personal vault, so offer it only there.
209
- const promotable = vaultOf(args)?.id === mcp.defaultVault && vaultOf(args)?.kind === "personal";
234
+ // vmem_promote reads from the preferred personal vault, so offer it only there.
235
+ const promotable = vaultOf(args)?.id === promotionSource?.id && promotionSource !== undefined;
210
236
  return { note, links, orgVaults: promotable ? mcp.vaults.filter(v => v.kind === "org").map(v => v.id) : [] };
211
237
  }
212
238
  case "promote": {
@@ -237,12 +263,50 @@ export const plugin: ConsolePlugin = {
237
263
  const r = readLogSince(home, { vault: vault.id, limit: 100, ...(str(args.type) ? { type: str(args.type) } : {}), ...(str(args.since) ? { after: str(args.since) } : {}) });
238
264
  return { vault: vault.id, rows: r.lines.map(parseLogLine).reverse(), cursor: r.cursor, ...(r.reset ? { reset: true } : {}), ...(r.more ? { more: true } : {}), ...(r.ok ? {} : { error: firstIssue(r as unknown as Args) }) };
239
265
  }
266
+ case "proposals": {
267
+ const vault = vaultOf(args);
268
+ const state = PROPOSAL_STATES.includes(String(args.state)) ? String(args.state) : "pending";
269
+ if (!vault) return { vault: null, state, page: null, selected: null, ...(str(args.vault) ? { error: `unknown vault ${str(args.vault)}; pick a registered vault from Overview` } : {}) };
270
+ // The console owns the numeric `after`, so the proposal page cursor travels as `page`.
271
+ const list = await readTool("vmem_proposal_list", args, { vault: vault.id, state, after: str(args.page) });
272
+ const id = str(args.id);
273
+ const shown = id ? await readTool("vmem_proposal_show", args, { vault: vault.id, id }) : undefined;
274
+ const error = "error" in list ? list.error : shown && "error" in shown ? shown.error : undefined;
275
+ return { vault: vault.id, state, page: "result" in list ? list.result : null, selected: shown && "result" in shown ? shown.result : null, ...(error ? { error } : {}) };
276
+ }
277
+ case "assertions": {
278
+ const vault = vaultOf(args);
279
+ if (!vault) return { vault: null, result: null, warnings: [], ...(str(args.vault) ? { error: `unknown vault ${str(args.vault)}; pick a registered vault from Overview` } : {}) };
280
+ const r = await readTool("vmem_assertions", args, { vault: vault.id });
281
+ const result = "result" in r ? r.result : null;
282
+ return { vault: vault.id, result, warnings: assertionCoverageWarnings(result?.coverage as AssertionsReadResult["coverage"] | undefined), ...("error" in r ? { error: r.error } : {}) };
283
+ }
284
+ case "history": {
285
+ const vault = vaultOf(args), path = str(args.path), from = str(args.from), to = str(args.to);
286
+ if (!vault) return { vault: null, path: path ?? null, history: null, changes: null, ...(str(args.vault) ? { error: `unknown vault ${str(args.vault)}; pick a registered vault from Overview` } : {}) };
287
+ if ((from === undefined) !== (to === undefined)) return { vault: vault.id, path: path ?? null, history: null, changes: null, error: "changes need both from and to commit ids; pick two revisions from the history list" };
288
+ const history = path ? await readTool("vmem_history", args, { vault: vault.id, path }) : undefined;
289
+ const changes = from && to ? await readTool("vmem_changes", args, { vault: vault.id, from, to, cursor: str(args.changesCursor) }) : undefined;
290
+ const error = history && "error" in history ? history.error : changes && "error" in changes ? changes.error : undefined;
291
+ return { vault: vault.id, path: path ?? null, history: history && "result" in history ? history.result : null, changes: changes && "result" in changes ? changes.result : null, ...(error ? { error } : {}) };
292
+ }
240
293
  default: return { error: `unknown panel ${input.panel}` };
241
294
  }
242
295
  },
243
296
  async action(input) {
244
297
  const args = input as Args, confirmed = input.confirmed === true, fingerprint = str(input.fingerprint);
245
298
  switch (input.action) {
299
+ case "settings": {
300
+ const vault = vaultOf(args);
301
+ if (!vault) return { ok: false, error: "settings: no selected vault; select a registered vault" };
302
+ try {
303
+ const changes = args.changes as import("../registry.ts").SettingsChanges;
304
+ const preview = changeSettings(home, { vault: vault.id, changes });
305
+ if (!confirmed || fingerprint !== preview.fingerprint) return { ok: false, needsConfirm: true, fingerprint: preview.fingerprint, verb: "Change settings", preview: Object.entries(preview.changes).map(([key, value]) => `${key}: ${JSON.stringify(value)}`), changes: [{ op: "modify", target: "vmem.config.json" }] };
306
+ changeSettings(home, { vault: vault.id, changes, confirm: true, fingerprint });
307
+ return { ok: true, message: "Settings updated; restart the console and MCP server to apply the default vault and permission changes" };
308
+ } catch (error) { return { ok: false, error: error instanceof Error ? error.message : "settings: change failed; inspect the configuration and retry" }; }
309
+ }
246
310
  case "delete": {
247
311
  const path = str(args.path) ?? str(args.id);
248
312
  if (!path) return { ok: false, error: "path is required" };
@@ -260,7 +324,7 @@ export const plugin: ConsolePlugin = {
260
324
  case "promote": {
261
325
  const path = str(args.path), to = str(args.to);
262
326
  if (!path || !to) return { ok: false, error: "path and to are required" };
263
- if (vaultOf(args)?.id !== mcp.defaultVault) return { ok: false, error: `promotion to an org vault reads from ${mcp.defaultVault}; open the note there` };
327
+ if (vaultOf(args)?.id !== promotionSource?.id || !promotionSource) return { ok: false, error: promotionSource ? `promotion to an org vault reads from ${promotionSource.id}; open the note there` : "promotion needs a personal vault; register one with vmem vaults add" };
264
328
  return twoStep("vmem_promote", forward("vmem_promote", args), confirmed, fingerprint, p => {
265
329
  const screen = rec(p.screen), dropped = Array.isArray(p.droppedLinks) ? p.droppedLinks as string[] : [];
266
330
  const target = String(p.target ?? `${to}:${path}`);
@@ -296,6 +360,30 @@ export const plugin: ConsolePlugin = {
296
360
  warnings: dupes.length ? [`possible duplicates: ${dupes.slice(0, 5).join(", ")}`] : [] };
297
361
  });
298
362
  }
363
+ case "proposal-apply":
364
+ case "proposal-reject": {
365
+ const id = str(args.id), reason = str(args.reason), apply = input.action === "proposal-apply";
366
+ if (!id) return { ok: false, error: "a proposal id is required; select a proposal in the Proposals panel" };
367
+ if (!apply && !reason?.trim()) return { ok: false, error: "rejection needs a reason; enter one and reject again" };
368
+ const tool = apply ? "vmem_proposal_apply" : "vmem_proposal_reject";
369
+ const checked = forward(tool, args, { id, ...(apply ? {} : { reason }) });
370
+ if (typeof checked === "string") return { ok: false, error: `${checked}; ${apply ? "select the proposal again from the Proposals panel" : "shorten the reason to at most 4096 bytes and reject again"}` };
371
+ try {
372
+ if (apply) return await twoStep(tool, checked, confirmed, fingerprint, p => ({ verb: "Apply proposal", preview: [`apply proposal ${id}`], changes: changesOf(p), warnings: (Array.isArray(p.issues) ? p.issues as { message?: string }[] : []).map(i => String(i.message ?? "")).filter(Boolean) }));
373
+ // Rejection answers `rejected`, not `applied`, so its confirm step reads that receipt field itself.
374
+ if (typeof checked === "string") return { ok: false, error: checked };
375
+ const preview = await call(tool, checked);
376
+ if (typeof preview.fingerprint !== "string") return { ok: false, error: firstIssue(preview) };
377
+ if (!confirmed || fingerprint !== preview.fingerprint)
378
+ return { ok: false, needsConfirm: true, fingerprint: preview.fingerprint, verb: "Reject proposal", preview: [`reject proposal ${id}`, `reason: ${String(preview.reason ?? reason)}`], changes: [{ op: "modify", target: `proposal ${id}`, note: "state → rejected; no note or log changes" }] };
379
+ const done = await call(tool, { ...checked, confirm: true, fingerprint });
380
+ if (done.rejected === true) { revision.invalidate(); inbox.invalidate(); return done.ok === true ? { ok: true, message: "Reject proposal: done" } : { ok: true, message: `Reject proposal: recorded, but ${firstIssue(done)}` }; }
381
+ return { ok: false, error: firstIssue(done) };
382
+ } catch (error) {
383
+ // The provider refuses by throwing (no longer pending, apply_unknown, binding drift); its message names the next step.
384
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
385
+ }
386
+ }
299
387
  default: return { ok: false, error: `unknown action ${input.action}` };
300
388
  }
301
389
  },
@@ -304,3 +392,5 @@ export const plugin: ConsolePlugin = {
304
392
  };
305
393
 
306
394
  export default plugin;
395
+ export type { ProposalState, ProposalsSnapshot, AssertionsSnapshot, HistorySnapshot, CoverageWarning } from "./panel-types.ts";
396
+ export { assertionCoverageWarnings } from "./panel-types.ts";
@@ -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
- edges.set(key, { source, target: destination, relation: "wiki_link", ...(kept ? { rel: kept } : {}), confidence_tag: "EXTRACTED", confidence: 1 });
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
  }
@@ -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 텍스트는 힌트 미계산 (미탐 아님)` : "",
@@ -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);
@@ -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 }
@@ -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") {