@jacklika/dsh-tool-memory-graph 0.1.0-alpha.5 → 0.1.0-alpha.6

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/README.md CHANGED
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
9
9
 
10
10
  ## Summary
11
11
 
12
- `dsh-tool-memory-graph` gives agents read-only graph queries over the Markdown vault used by [`dsh-tool-memory-filesystem`](../tool-memory-filesystem/README.md). The model sees one tool, `wiki_graph`, which returns note nodes and directed edges derived from Obsidian-style `[[link]]` references — either the whole vault or the reachable subgraph around one note. The package reuses the filesystem plugin's vault resolution and parsing helpers, so path containment, frontmatter handling, and the `indexHiddenDirs` policy match without a second parser.
12
+ `dsh-tool-memory-graph` gives agents read-only graph queries over the Markdown vault used by [`dsh-tool-memory-filesystem`](../tool-memory-filesystem/README.md). The model sees one tool, `wiki_graph`, which returns note nodes and directed edges derived from two sources: explicit Obsidian-style `[[link]]` references, and keyword co-occurrence between notes (frontmatter tags/title and body terms). It can therefore expose an implicit association such as "B and C both mention `word1`", and that association automatically disappears when one note is rewritten and the shared term is no longer present — or is replaced by a new shared term such as `word2`. The package reuses the filesystem plugin's vault resolution and parsing helpers, so path containment, frontmatter handling, and the `indexHiddenDirs` policy match without a second parser.
13
13
 
14
14
  ## Table of Contents
15
15
 
@@ -44,14 +44,14 @@ It resolves the same vault root per call as `tool-memory-filesystem`: an explici
44
44
 
45
45
  ### Tools
46
46
 
47
- - `wiki_graph(id?, depth?)` — without `id`, return every note and directed edge in the vault. With `id`, return the reachable subgraph within `depth` hops; edges from boundary nodes are included when both endpoints are selected.
47
+ - `wiki_graph(id?, depth?)` — without `id`, return every note and directed edge in the vault. With `id`, return the reachable subgraph within `depth` hops; edges from boundary nodes are included when both endpoints are selected. Edges carry `type` (`link` or `keyword`), `keywords` (for `keyword` edges), and `weight` (combined term frequency).
48
48
 
49
49
  -----
50
50
 
51
51
  <a id="understand-the-implementation"></a>
52
52
  ## Understand the implementation
53
53
 
54
- The package is a single Cordis function plugin that registers `wiki_graph` on `ctx.tools`. Per call it resolves the vault root through the shared `resolveMemoryVaultRoot` helper, lists notes through the shared `listNotePaths` walker, and extracts `[[link]]` targets through `extractLinks`/`resolveLinkTarget`. Targets resolve with the same Obsidian-style tiers as `wiki_read` — exact vault-relative path, then path suffix, then basename anywhere in the vault, with deterministic ambiguity handling. A breadth-first walk selects the node set first; edges are then collected from every selected node so boundary-node outgoing edges are not dropped. When the node set exceeds `maxNodes`, a whole-vault graph keeps the lowest ids in code-unit order (the ordering `tool-memory-filesystem` tie-breaks with) and a subgraph keeps the notes nearest the center — BFS level first, then id — so which notes survive the cap never depends on directory-listing order and a subgraph never drops its own center. Output is `{ nodes: [{ id, title }], edges: [{ from, to }], truncated: boolean }`.
54
+ The package is a single Cordis function plugin that registers `wiki_graph` on `ctx.tools`. Per call it resolves the vault root through the shared `resolveMemoryVaultRoot` helper, lists notes through the shared `listNotePaths` walker, and extracts `[[link]]` targets through `extractLinks`/`resolveLinkTarget`. Targets resolve with the same Obsidian-style tiers as `wiki_read` — exact vault-relative path, then path suffix, then basename anywhere in the vault, with deterministic ambiguity handling. In addition to explicit links, the tool extracts significant terms from each note (frontmatter `tags` ×3, frontmatter `title` ×2, body terms ×1) and creates `keyword` edges between any two notes that share one or more terms. A breadth-first walk that follows both `link` and `keyword` edges selects the node set first; edges are then collected from every selected node so boundary-node outgoing edges are not dropped. When the node set exceeds `maxNodes`, a whole-vault graph keeps the lowest ids in code-unit order (the ordering `tool-memory-filesystem` tie-breaks with) and a subgraph keeps the notes nearest the center — BFS level first, then id — so which notes survive the cap never depends on directory-listing order and a subgraph never drops its own center. Because `wiki_graph` recomputes from disk on every call, rewriting a note removes stale `keyword` edges and creates new ones for the terms that survive or appear in the new text. Output is `{ nodes: [{ id, title }], edges: [{ from, to, type, keywords?, weight? }], truncated: boolean }`.
55
55
 
56
56
  -----
57
57
 
@@ -62,12 +62,12 @@ The package is a single Cordis function plugin that registers `wiki_graph` on `c
62
62
 
63
63
  #### What the model sees
64
64
 
65
- The model sees the generated `wiki_graph` schema. The description states that the graph is read-only and derived from `[[link]]` references.
65
+ The model sees the generated `wiki_graph` schema. The description states that the graph is read-only and derived from `[[link]]` references plus shared keywords.
66
66
 
67
67
  ##### Verbatim description for `wiki_graph`
68
68
 
69
69
  ```markdown
70
- Return the Obsidian-style [[link]] graph of the wiki vault: note ids, titles, and directed edges. Without an id it returns the whole vault graph (node-capped); with an id it returns the subgraph reachable from that note within the given depth.
70
+ Return the link and keyword graph of the wiki vault: note ids, titles, and directed edges. Explicit `[[link]]` edges are type `link`; edges derived from shared significant terms are type `keyword` with `keywords` and `weight`. Without an id it returns the whole vault graph (node-capped); with an id it returns the subgraph reachable from that note within the given depth.
71
71
  ```
72
72
 
73
73
  #### Token effect
package/README.zh.md CHANGED
@@ -9,7 +9,7 @@ kind: "package-reference"
9
9
 
10
10
  ## 概述
11
11
 
12
- `dsh-tool-memory-graph` 让 agent 对 [`dsh-tool-memory-filesystem`](../tool-memory-filesystem/README.zh.md) 使用的 Markdown 仓库做只读图查询。模型可见一个工具 `wiki_graph`,返回由 Obsidian 风格 `[[link]]` 引用推导的笔记节点和有向边——可以是全仓库图,也可以是以某条笔记为中心的可达子图。该包复用 filesystem 插件的仓库根解析与解析辅助函数,路径约束、frontmatter 处理和 `indexHiddenDirs` 策略完全一致,不引入第二套解析器。
12
+ `dsh-tool-memory-graph` 让 agent 对 [`dsh-tool-memory-filesystem`](../tool-memory-filesystem/README.zh.md) 使用的 Markdown 仓库做只读图查询。模型可见一个工具 `wiki_graph`,返回两类来源推导的笔记节点和有向边:显式 Obsidian 风格 `[[link]]` 引用,以及笔记之间的关键词共现(frontmatter tags/title 与正文中的显著词)。因此它能暴露类似“B 与 C 都提到 `word1`”的隐式关联,且当某条笔记被重写、共同词消失时该关联自动消失;若重写后双方出现新的共词(如 `word2`),则自动建立以 `word2` 为标签的新关联。该包复用 filesystem 插件的仓库根解析与解析辅助函数,路径约束、frontmatter 处理和 `indexHiddenDirs` 策略完全一致,不引入第二套解析器。
13
13
 
14
14
  ## 目录
15
15
 
@@ -44,14 +44,14 @@ kind: "package-reference"
44
44
 
45
45
  ### 工具
46
46
 
47
- - `wiki_graph(id?, depth?)` —— 不传 `id` 时返回全仓库的节点与有向边;传 `id` 时返回 `depth` 跳内的可达子图,两个端点都被选中时边界节点的出边也会包含。
47
+ - `wiki_graph(id?, depth?)` —— 不传 `id` 时返回全仓库的节点与有向边;传 `id` 时返回 `depth` 跳内的可达子图,两个端点都被选中时边界节点的出边也会包含。边携带 `type`(`link` 或 `keyword`)、`keywords`(仅 `keyword` 边)和 `weight`(合并词频)。
48
48
 
49
49
  -----
50
50
 
51
51
  <a id="understand-the-implementation"></a>
52
52
  ## 实现说明
53
53
 
54
- 本包是单个 Cordis 函数插件,在 `ctx.tools` 上注册 `wiki_graph`。每次调用通过共享的 `resolveMemoryVaultRoot` 解析仓库根,用 `listNotePaths` 遍历笔记,用 `extractLinks`/`resolveLinkTarget` 提取 `[[link]]` 目标。目标按与 `wiki_read` 相同的 Obsidian 语义解析——先精确仓库相对路径,再路径后缀,最后全仓库 basename 匹配,多重命中按确定性规则选择。先用广度优先遍历确定节点集合,再从所有已选节点收集边,因此边界节点的出边不会丢失。节点集合超过 `maxNodes` 时,全仓库图保留码点序最小的若干 id(与 `tool-memory-filesystem` 的并列排序规则一致),子图则保留离中心最近的笔记——先按 BFS 层级、再按 id——因此保留哪些笔记不依赖目录列举顺序,子图也不会丢掉自己的中心节点。输出为 `{ nodes: [{ id, title }], edges: [{ from, to }], truncated: boolean }`。
54
+ 本包是单个 Cordis 函数插件,在 `ctx.tools` 上注册 `wiki_graph`。每次调用通过共享的 `resolveMemoryVaultRoot` 解析仓库根,用 `listNotePaths` 遍历笔记,用 `extractLinks`/`resolveLinkTarget` 提取 `[[link]]` 目标。目标按与 `wiki_read` 相同的 Obsidian 语义解析——先精确仓库相对路径,再路径后缀,最后全仓库 basename 匹配,多重命中按确定性规则选择。除显式链接外,工具还会从每条笔记提取显著词(frontmatter `tags` ×3、frontmatter `title` ×2、正文词 ×1),并为任意两篇共享一个或多个词的笔记创建 `keyword` 边。广度优先遍历同时跟随 `link` 边与 `keyword` 边以确定节点集合,再从所有已选节点收集边,因此边界节点的出边不会丢失。节点集合超过 `maxNodes` 时,全仓库图保留码点序最小的若干 id(与 `tool-memory-filesystem` 的并列排序规则一致),子图则保留离中心最近的笔记——先按 BFS 层级、再按 id——因此保留哪些笔记不依赖目录列举顺序,子图也不会丢掉自己的中心节点。由于 `wiki_graph` 每次调用都会从磁盘重新计算,重写一条笔记会移除旧的 `keyword` 边,并为新正文中保留下来的或新出现的词建立新边。输出为 `{ nodes: [{ id, title }], edges: [{ from, to, type, keywords?, weight? }], truncated: boolean }`。
55
55
 
56
56
  -----
57
57
 
@@ -62,12 +62,12 @@ kind: "package-reference"
62
62
 
63
63
  #### 模型可见内容
64
64
 
65
- 模型看到生成的 `wiki_graph` schema。描述声明该图是只读的,由 `[[link]]` 引用推导。
65
+ 模型看到生成的 `wiki_graph` schema。描述声明该图是只读的,由 `[[link]]` 引用与共享关键词共同推导。
66
66
 
67
67
  ##### `wiki_graph` 的原文描述
68
68
 
69
69
  ```markdown
70
- Return the Obsidian-style [[link]] graph of the wiki vault: note ids, titles, and directed edges. Without an id it returns the whole vault graph (node-capped); with an id it returns the subgraph reachable from that note within the given depth.
70
+ Return the link and keyword graph of the wiki vault: note ids, titles, and directed edges. Explicit `[[link]]` edges are type `link`; edges derived from shared significant terms are type `keyword` with `keywords` and `weight`. Without an id it returns the whole vault graph (node-capped); with an id it returns the subgraph reachable from that note within the given depth.
71
71
  ```
72
72
 
73
73
  #### Token 影响
package/lib/index.js CHANGED
@@ -3,6 +3,12 @@
3
3
  * registers `wiki_graph`, which returns the vault's note/link graph or the
4
4
  * subgraph reachable from one note, so an agent can reason about how memory
5
5
  * notes connect before reading them.
6
+ *
7
+ * In addition to explicit Obsidian-style `[[link]]` edges, `wiki_graph` now
8
+ * derives keyword edges: two notes share a directed keyword edge for every
9
+ * significant term that appears in both. Rewriting a note therefore
10
+ * automatically removes stale keyword edges and creates new ones for the terms
11
+ * that survive or appear in the new text.
6
12
  * @module @jacklika/dsh-tool-memory-graph
7
13
  */
8
14
  import { readFile } from 'node:fs/promises';
@@ -26,8 +32,85 @@ function assertPositiveInteger(name, value) {
26
32
  throw new Error(`tool-memory-graph: ${name} must be a positive integer`);
27
33
  }
28
34
  }
29
- async function noteTitle(absolutePath, id) {
30
- const text = await readFile(absolutePath, 'utf8');
35
+ /**
36
+ * Minimal English stopwords. The list is intentionally short; the model-facing
37
+ * graph is most useful for distinctive project terms, not for hiding grammar.
38
+ */
39
+ const STOPWORDS = new Set([
40
+ 'the', 'a', 'an', 'and', 'or', 'but', 'is', 'are', 'was', 'were', 'be', 'been', 'being',
41
+ 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'shall', 'should', 'may', 'might',
42
+ 'can', 'could', 'of', 'in', 'on', 'at', 'to', 'for', 'with', 'by', 'from', 'as', 'it', 'its',
43
+ 'this', 'that', 'these', 'those', 'i', 'me', 'my', 'you', 'your', 'we', 'us', 'our', 'he', 'him',
44
+ 'his', 'she', 'her', 'they', 'them', 'their', 'not', 'no', 'if', 'then', 'than', 'so', 'very',
45
+ 'just', 'only', 'also', 'about', 'into', 'through', 'during', 'before', 'after', 'above', 'below',
46
+ 'up', 'down', 'out', 'off', 'over', 'under', 'again', 'further', 'once', 'here', 'there', 'when',
47
+ 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some',
48
+ 'such', 'what', 'which', 'who', 'whom', 'whose', 'see', 'one', 'two', 'three', 'four', 'five',
49
+ 'get', 'got', 'go', 'went', 'come', 'came', 'take', 'took', 'make', 'made', 'know', 'knew',
50
+ 'think', 'thought', 'say', 'said', 'look', 'use', 'used', 'find', 'found', 'give', 'gave',
51
+ 'tell', 'told', 'ask', 'asked', 'work', 'worked', 'seem', 'seemed', 'feel', 'felt', 'try',
52
+ 'tried', 'leave', 'left', 'call', 'called', 'keep', 'kept', 'let', 'put', 'bring', 'brought',
53
+ 'begin', 'began', 'help', 'helped', 'show', 'showed', 'hear', 'heard', 'play', 'played', 'run',
54
+ 'ran', 'move', 'moved', 'live', 'lived', 'believe', 'believed', 'hold', 'held', 'must', 'need',
55
+ 'needed', 'able', 'due', 'while', 'whereas', 'nevertheless', 'however', 'therefore', 'moreover',
56
+ 'furthermore', 'nonetheless', 'otherwise', 'meanwhile', 'besides', 'thus', 'hence', 'accordingly',
57
+ 'consequently', 'now', 'later', 'soon', 'early', 'late', 'long', 'much', 'many', 'little', 'less',
58
+ 'least', 'well', 'better', 'best', 'bad', 'worse', 'worst', 'good', 'great', 'new', 'old',
59
+ 'first', 'last', 'next', 'previous', 'same', 'different', 'own', 'another', 'none', 'either',
60
+ 'neither', 'whether', 'nor', 'even', 'still', 'yet', 'already', 'always', 'never', 'often',
61
+ 'sometimes', 'usually', 'rarely', 'seldom', 'back', 'already', 'quite', 'rather', 'really',
62
+ 'actually', 'certainly', 'definitely', 'probably', 'possibly', 'perhaps', 'maybe', 'likely',
63
+ 'sure', 'course', 'absolutely', 'completely', 'entirely', 'totally', 'almost', 'nearly',
64
+ 'hardly', 'barely', 'scarcely', 'enough',
65
+ ]);
66
+ /** Token pattern: starts with a letter, then letters or digits. Unicode-aware. */
67
+ const TOKEN_RE = /[\p{L}][\p{L}\p{N}]*/gu;
68
+ /**
69
+ * Extract normalised significant terms from Markdown text.
70
+ * - Frontmatter `tags` count 3x (they are explicit metadata).
71
+ * - Frontmatter `title` counts 2x.
72
+ * - Body terms count 1x.
73
+ * - Numbers-only tokens and short/stop tokens are dropped.
74
+ */
75
+ function extractTerms(text) {
76
+ const { frontmatter, body } = splitFrontmatter(text);
77
+ const terms = new Map();
78
+ const addToken = (raw, multiplier = 1) => {
79
+ const normalized = raw.normalize('NFC').toLowerCase();
80
+ if (normalized.length < 2)
81
+ return;
82
+ if (/^\d+$/.test(normalized))
83
+ return;
84
+ if (STOPWORDS.has(normalized))
85
+ return;
86
+ terms.set(normalized, (terms.get(normalized) ?? 0) + multiplier);
87
+ };
88
+ const tokenize = (source) => {
89
+ const re = new RegExp(TOKEN_RE.source, TOKEN_RE.flags);
90
+ return source.match(re) ?? [];
91
+ };
92
+ if (Array.isArray(frontmatter.tags)) {
93
+ for (const tag of frontmatter.tags) {
94
+ if (typeof tag === 'string') {
95
+ for (const token of tokenize(tag))
96
+ addToken(token, 3);
97
+ }
98
+ }
99
+ }
100
+ if (typeof frontmatter.title === 'string') {
101
+ for (const token of tokenize(frontmatter.title))
102
+ addToken(token, 2);
103
+ }
104
+ // Strip Obsidian `[[link]]` syntax so explicit links do not also create
105
+ // redundant keyword edges; keep markdown link text, not the URL.
106
+ const bodyForTerms = body
107
+ .replace(/\[\[[^\]]*\]\]/g, ' ')
108
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');
109
+ for (const token of tokenize(bodyForTerms))
110
+ addToken(token, 1);
111
+ return terms;
112
+ }
113
+ function noteTitleFromText(text, id) {
31
114
  const { frontmatter, body } = splitFrontmatter(text);
32
115
  const explicitTitle = typeof frontmatter.title === 'string' ? frontmatter.title.trim() : '';
33
116
  if (explicitTitle !== '')
@@ -35,88 +118,157 @@ async function noteTitle(absolutePath, id) {
35
118
  const heading = /^#\s+(.+)$/m.exec(body);
36
119
  return heading?.[1]?.trim() ?? id.replace(/\.[^.]+$/, '');
37
120
  }
121
+ /**
122
+ * Build undirected keyword edges for a set of notes. Each pair of notes that
123
+ * share one or more terms receives two directed edges (A→B and B→A) carrying
124
+ * the sorted shared keywords and a combined weight.
125
+ */
126
+ function buildKeywordEdges(noteTerms) {
127
+ const inverted = new Map();
128
+ for (const [id, terms] of noteTerms) {
129
+ for (const term of terms.keys()) {
130
+ const list = inverted.get(term) ?? [];
131
+ list.push(id);
132
+ inverted.set(term, list);
133
+ }
134
+ }
135
+ const pairData = new Map();
136
+ for (const [term, ids] of inverted) {
137
+ if (ids.length < 2)
138
+ continue;
139
+ for (let i = 0; i < ids.length; i += 1) {
140
+ for (let j = i + 1; j < ids.length; j += 1) {
141
+ const a = ids[i];
142
+ const b = ids[j];
143
+ const [first, second] = codeUnitCompare(a, b) <= 0 ? [a, b] : [b, a];
144
+ const weight = (noteTerms.get(a)?.get(term) ?? 0) + (noteTerms.get(b)?.get(term) ?? 0);
145
+ const key = `${first}\x00${second}`;
146
+ const entry = pairData.get(key) ?? { keywords: [], weight: 0 };
147
+ entry.keywords.push(term);
148
+ entry.weight += weight;
149
+ pairData.set(key, entry);
150
+ }
151
+ }
152
+ }
153
+ const edges = [];
154
+ for (const [key, { keywords, weight }] of pairData) {
155
+ const parts = key.split('\x00');
156
+ const from = parts[0];
157
+ const to = parts[1];
158
+ const sortedKeywords = [...keywords].sort(codeUnitCompare);
159
+ edges.push({ from, to, type: 'keyword', keywords: sortedKeywords, weight });
160
+ edges.push({ from: to, to: from, type: 'keyword', keywords: sortedKeywords, weight });
161
+ }
162
+ return edges;
163
+ }
164
+ async function loadVaultNotes(root, resolved) {
165
+ const paths = await listNotePaths(root, resolved.extensions, resolved.indexHiddenDirs);
166
+ const ids = paths.map(path => vaultRelativeId(root, path));
167
+ const linkResolver = createLinkResolver(ids);
168
+ const parsed = [];
169
+ const parsedById = new Map();
170
+ for (const path of paths) {
171
+ const id = vaultRelativeId(root, path);
172
+ const text = await readFile(path, 'utf8');
173
+ const note = { id, path, text, terms: extractTerms(text) };
174
+ parsed.push(note);
175
+ parsedById.set(id, note);
176
+ }
177
+ return { parsed, parsedById, linkResolver };
178
+ }
38
179
  /**
39
180
  * Build the vault-wide link graph: every note is a node; every `[[link]]`
40
- * that resolves to an existing note is an edge.
181
+ * that resolves to an existing note is an edge; every shared significant term
182
+ * between two nodes becomes a directed `keyword` edge in both directions.
41
183
  * @param root - vault root.
42
184
  * @param resolved - applied plugin configuration.
43
185
  * @returns the full graph, node-capped.
44
186
  */
45
187
  async function buildGraph(root, resolved) {
46
- const paths = await listNotePaths(root, resolved.extensions, resolved.indexHiddenDirs);
47
- const entries = paths.map(path => [vaultRelativeId(root, path), path]);
48
- const linkResolver = createLinkResolver(entries.map(([id]) => id));
49
- const truncated = entries.length > resolved.maxNodes;
50
- // `listNotePaths` follows readdir order, so the node cap would otherwise keep
51
- // a filesystem-dependent subset of the vault.
52
- const capped = [...entries].sort((a, b) => codeUnitCompare(a[0], b[0])).slice(0, resolved.maxNodes);
53
- const nodes = [];
54
- for (const [id, path] of capped)
55
- nodes.push({ id, title: await noteTitle(path, id) });
56
- const idSet = new Set(capped.map(([id]) => id));
188
+ const { parsed, linkResolver } = await loadVaultNotes(root, resolved);
189
+ const truncated = parsed.length > resolved.maxNodes;
190
+ const capped = [...parsed].sort((a, b) => codeUnitCompare(a.id, b.id)).slice(0, resolved.maxNodes);
191
+ const idSet = new Set(capped.map(p => p.id));
192
+ const nodes = capped.map(p => ({ id: p.id, title: noteTitleFromText(p.text, p.id) }));
57
193
  const edges = [];
58
- for (const [id, path] of capped) {
59
- const text = await readFile(path, 'utf8');
60
- for (const link of extractLinks(text)) {
194
+ for (const p of capped) {
195
+ for (const link of extractLinks(p.text)) {
61
196
  const targetPath = await resolveLinkTarget(root, resolved.extensions, link, linkResolver);
62
197
  if (targetPath === undefined)
63
198
  continue;
64
199
  const targetId = vaultRelativeId(root, targetPath);
65
200
  if (idSet.has(targetId))
66
- edges.push({ from: id, to: targetId });
201
+ edges.push({ from: p.id, to: targetId });
67
202
  }
68
203
  }
69
- return { nodes, edges, truncated };
204
+ const noteTerms = new Map(capped.map(p => [p.id, p.terms]));
205
+ edges.push(...buildKeywordEdges(noteTerms));
206
+ // Safety: every edge endpoint must be in the returned node set.
207
+ const safeEdges = edges.filter(e => idSet.has(e.from) && idSet.has(e.to));
208
+ return { nodes, edges: safeEdges, truncated };
70
209
  }
71
210
  /**
72
211
  * Collect the subgraph reachable from one note by following `[[link]]`
73
- * references breadth-first up to `depth`.
212
+ * references and shared-keyword edges breadth-first up to `depth`.
74
213
  * @param root - vault root.
75
214
  * @param resolved - applied plugin configuration.
76
215
  * @param startId - vault-relative id of the center note.
77
- * @param depth - maximum link hops from the center.
216
+ * @param depth - maximum link/keyword hops from the center.
78
217
  * @returns the neighborhood graph, node-capped.
79
218
  */
80
219
  async function buildSubgraph(root, resolved, startId, depth) {
220
+ const { parsed, parsedById, linkResolver } = await loadVaultNotes(root, resolved);
81
221
  const startPath = await containedPathReal(root, startId);
82
- const linkResolver = createLinkResolver((await listNotePaths(root, resolved.extensions, resolved.indexHiddenDirs))
83
- .map(path => vaultRelativeId(root, path)));
84
- const visited = new Map([[vaultRelativeId(root, startPath), startPath]]);
85
- const levels = new Map([[vaultRelativeId(root, startPath), 0]]);
86
- let frontier = [startPath];
222
+ const startNoteId = vaultRelativeId(root, startPath);
223
+ const idSetAll = new Set(parsed.map(p => p.id));
224
+ const adjacency = new Map();
225
+ for (const p of parsed) {
226
+ const neighbors = [];
227
+ for (const link of extractLinks(p.text)) {
228
+ const targetPath = await resolveLinkTarget(root, resolved.extensions, link, linkResolver);
229
+ if (targetPath === undefined)
230
+ continue;
231
+ const targetId = vaultRelativeId(root, targetPath);
232
+ if (idSetAll.has(targetId) && !neighbors.includes(targetId))
233
+ neighbors.push(targetId);
234
+ }
235
+ adjacency.set(p.id, neighbors);
236
+ }
237
+ const noteTerms = new Map(parsed.map(p => [p.id, p.terms]));
238
+ const keywordEdges = buildKeywordEdges(noteTerms);
239
+ for (const { from, to } of keywordEdges) {
240
+ const list = adjacency.get(from) ?? [];
241
+ if (!list.includes(to))
242
+ list.push(to);
243
+ adjacency.set(from, list);
244
+ }
245
+ const visited = new Map([[startNoteId, 0]]);
246
+ let frontier = [startNoteId];
87
247
  for (let level = 0; level < depth && frontier.length > 0; level += 1) {
88
248
  const next = [];
89
- for (const path of frontier) {
90
- const text = await readFile(path, 'utf8');
91
- for (const link of extractLinks(text)) {
92
- const targetPath = await resolveLinkTarget(root, resolved.extensions, link, linkResolver);
93
- if (targetPath === undefined)
94
- continue;
95
- const toId = vaultRelativeId(root, targetPath);
96
- if (!visited.has(toId)) {
97
- visited.set(toId, targetPath);
98
- levels.set(toId, level + 1);
99
- next.push(targetPath);
249
+ for (const id of frontier) {
250
+ for (const neighbor of adjacency.get(id) ?? []) {
251
+ if (!visited.has(neighbor)) {
252
+ visited.set(neighbor, level + 1);
253
+ next.push(neighbor);
100
254
  }
101
255
  }
102
256
  }
103
257
  frontier = next;
104
258
  }
105
259
  const truncated = visited.size > resolved.maxNodes;
106
- // Truncate by distance from the center, then by id: the neighborhood closest
107
- // to the requested note survives the cap, and which notes those are does not
108
- // depend on readdir or link order.
109
260
  const ids = [...visited.keys()]
110
- .sort((a, b) => (levels.get(a) ?? 0) - (levels.get(b) ?? 0) || codeUnitCompare(a, b))
261
+ .sort((a, b) => (visited.get(a) ?? 0) - (visited.get(b) ?? 0) || codeUnitCompare(a, b))
111
262
  .slice(0, resolved.maxNodes);
112
263
  const idSet = new Set(ids);
264
+ const nodes = ids.map(id => {
265
+ const p = parsedById.get(id);
266
+ return { id, title: noteTitleFromText(p.text, id) };
267
+ });
113
268
  const edges = [];
114
- const nodes = [];
115
269
  for (const id of ids) {
116
- const path = await containedPathReal(root, id);
117
- nodes.push({ id, title: await noteTitle(path, id) });
118
- const text = await readFile(path, 'utf8');
119
- for (const link of extractLinks(text)) {
270
+ const p = parsedById.get(id);
271
+ for (const link of extractLinks(p.text)) {
120
272
  const targetPath = await resolveLinkTarget(root, resolved.extensions, link, linkResolver);
121
273
  if (targetPath === undefined)
122
274
  continue;
@@ -125,12 +277,14 @@ async function buildSubgraph(root, resolved, startId, depth) {
125
277
  edges.push({ from: id, to: toId });
126
278
  }
127
279
  }
280
+ const filteredKeywordEdges = keywordEdges.filter(e => idSet.has(e.from) && idSet.has(e.to));
281
+ edges.push(...filteredKeywordEdges);
128
282
  return { nodes, edges, truncated };
129
283
  }
130
284
  /**
131
285
  * Register the `wiki_graph` tool on `ctx.tools`.
132
286
  * @param ctx - registrant context carrying the tool registry.
133
- * @param config - deployment's explicit vault configuration.
287
+ * @param config - plugin configuration.
134
288
  */
135
289
  export function apply(ctx, config) {
136
290
  const tools = ctx.get('tools');
@@ -143,7 +297,7 @@ export function apply(ctx, config) {
143
297
  assertPositiveInteger('maxNodes', resolved.maxNodes);
144
298
  ctx.effect(() => ctx.tools.register(defineTool({
145
299
  name: 'wiki_graph',
146
- description: 'Return the Obsidian-style [[link]] graph of the wiki vault: note ids, titles, and directed edges. Without an id it returns the whole vault graph (node-capped); with an id it returns the subgraph reachable from that note within the given depth.',
300
+ description: 'Return the link and keyword graph of the wiki vault: note ids, titles, and directed edges. Explicit `[[link]]` edges are type `link`; edges derived from shared significant terms are type `keyword` with `keywords` and `weight`. Without an id it returns the whole vault graph (node-capped); with an id it returns the subgraph reachable from that note within the given depth.',
147
301
  parameters: {
148
302
  id: {
149
303
  type: 'string',
@@ -151,7 +305,7 @@ export function apply(ctx, config) {
151
305
  },
152
306
  depth: {
153
307
  type: 'integer',
154
- description: 'Maximum [[link]] hops from the center note; defaults to the configured maxDepth.',
308
+ description: 'Maximum link or keyword hops from the center note; defaults to the configured maxDepth.',
155
309
  },
156
310
  },
157
311
  output: {
@@ -3,6 +3,12 @@
3
3
  * registers `wiki_graph`, which returns the vault's note/link graph or the
4
4
  * subgraph reachable from one note, so an agent can reason about how memory
5
5
  * notes connect before reading them.
6
+ *
7
+ * In addition to explicit Obsidian-style `[[link]]` edges, `wiki_graph` now
8
+ * derives keyword edges: two notes share a directed keyword edge for every
9
+ * significant term that appears in both. Rewriting a note therefore
10
+ * automatically removes stale keyword edges and creates new ones for the terms
11
+ * that survive or appear in the new text.
6
12
  * @module @jacklika/dsh-tool-memory-graph
7
13
  */
8
14
  import type { Context } from '@deepseek-ai/cordis';
@@ -33,7 +39,7 @@ export declare const Config: z<Config>;
33
39
  /**
34
40
  * Register the `wiki_graph` tool on `ctx.tools`.
35
41
  * @param ctx - registrant context carrying the tool registry.
36
- * @param config - deployment's explicit vault configuration.
42
+ * @param config - plugin configuration.
37
43
  */
38
44
  export declare function apply(ctx: Context, config: Config): void;
39
45
  //# sourceMappingURL=index.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jacklika/dsh-tool-memory-graph",
3
3
  "description": "Model-facing link-graph tool over a Markdown memory vault: returns note nodes and [[link]] edges, or the subgraph reachable from one note.",
4
- "version": "0.1.0-alpha.5",
4
+ "version": "0.1.0-alpha.6",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },