@jacklika/dsh-tool-memory-filesystem 0.1.3-alpha.3 → 0.1.3-alpha.5
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 +4 -4
- package/README.zh.md +4 -4
- package/lib/index.js +180 -51
- package/lib/search.js +150 -0
- package/lib/types/index.d.ts +25 -10
- package/lib/types/search.d.ts +41 -0
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -53,7 +53,7 @@ A relative `vaultRoot` resolves against the calling session's workspace.
|
|
|
53
53
|
### Tools
|
|
54
54
|
|
|
55
55
|
- `wiki_read(id)` — read one note by vault-relative path and return its frontmatter, body, links, linked notes, and a `version` content fingerprint.
|
|
56
|
-
- `wiki_search(query)` — keyword search across note titles, ids, and bodies;
|
|
56
|
+
- `wiki_search(query)` — keyword search across note titles, ids, and bodies; query terms are OR-matched and ranked by field-weighted BM25-style scoring (title/id hits weigh most, rare terms weigh more) plus a verbatim-phrase bonus and a link-graph boost; when `wiki_semantic_search` is mounted the two rankings fuse via reciprocal rank fusion. Results include the score and backlink counts.
|
|
57
57
|
- `wiki_write(id, content, mode?, baseVersion?)` — create or append to a note. Append mode preserves frontmatter and adds a timestamp header. Passing a `version` from `wiki_read` as `baseVersion` makes the write fail loudly when another writer changed the note in between.
|
|
58
58
|
|
|
59
59
|
### Security
|
|
@@ -65,7 +65,7 @@ All paths are resolved under the vault root for that call; a path that escapes t
|
|
|
65
65
|
<a id="understand-the-implementation"></a>
|
|
66
66
|
## Understand the implementation
|
|
67
67
|
|
|
68
|
-
This package is a single Cordis function plugin with no runtime service. It registers three typed tools on `ctx.tools`. The vault root is resolved per tool call: the explicit `vaultRoot` config when set (relative paths anchor at the session workspace), otherwise `<session cwd>/.dsh/memory/` so each workspace owns its notes. Each tool reads Markdown files directly through `node:fs/promises` and stays inside the resolved root via `path.resolve` + prefix checking. YAML frontmatter is parsed with `js-yaml`; `[[link|alias]]` references extract the target before the pipe. Search builds a transient index from the vault contents and
|
|
68
|
+
This package is a single Cordis function plugin with no runtime service. It registers three typed tools on `ctx.tools`. The vault root is resolved per tool call: the explicit `vaultRoot` config when set (relative paths anchor at the session workspace), otherwise `<session cwd>/.dsh/memory/` so each workspace owns its notes. Each tool reads Markdown files directly through `node:fs/promises` and stays inside the resolved root via `path.resolve` + prefix checking. YAML frontmatter is parsed with `js-yaml`; `[[link|alias]]` references extract the target before the pipe; `[[...]]` inside inline code spans or fenced code blocks is documentation, not a link, and is ignored. Link targets resolve Obsidian-style against the indexed note ids: an exact vault-relative path first, then a path-suffix match (`[[notes/foo]]` finds `shared/notes/foo.md`), then a basename match anywhere in the vault — each tier tolerates the target carrying or omitting the extension. Ambiguous matches pick the fewest path segments, then the lowest id in code-point order, so resolution is deterministic across platforms. Search builds a transient index from the vault contents and ranks it in layers: OR-matched field-weighted scoring (id/title ×3, backlinks ×1, body ×1, with IDF so rare terms weigh more and BM25 saturation plus length normalization so long notes do not dominate), a verbatim-phrase bonus, and a graph boost for notes linked from strong hits. When `wiki_semantic_search` is registered, its ranking is fused in via reciprocal rank fusion; semantic failures fall back to the lexical ranking. `wiki_write` publishes atomically: the body is staged in a sibling temp file and `rename`d over the target, so concurrent readers never observe a partially written note.
|
|
69
69
|
|
|
70
70
|
-----
|
|
71
71
|
|
|
@@ -76,7 +76,7 @@ This package is a single Cordis function plugin with no runtime service. It regi
|
|
|
76
76
|
|
|
77
77
|
#### What the model sees
|
|
78
78
|
|
|
79
|
-
The model sees the generated
|
|
79
|
+
The model sees the generated `wiki_read`, `wiki_search`, and `wiki_write` schemas. Their descriptions tell the model that notes are Markdown files with YAML frontmatter and Obsidian-style `[[link]]` references, and that `wiki_read` follows links up to the configured depth.
|
|
80
80
|
|
|
81
81
|
##### Verbatim description for `wiki_read`
|
|
82
82
|
|
|
@@ -87,7 +87,7 @@ Read one Markdown note from the wiki vault, optionally following Obsidian-style
|
|
|
87
87
|
##### Verbatim description for `wiki_search`
|
|
88
88
|
|
|
89
89
|
```markdown
|
|
90
|
-
Search the wiki vault by note title or body keyword. Returns matching note ids, titles, and backlink counts. Use this before asking the user which note to read.
|
|
90
|
+
Search the wiki vault by note title or body keyword. Terms are OR-matched; results are ranked by field-weighted relevance (title/id hits outrank body hits, rare terms weigh more, notes linked from strong hits get a boost, and results may be fused with semantic search when available). Returns matching note ids, titles, scores, and backlink counts. Use this before asking the user which note to read.
|
|
91
91
|
```
|
|
92
92
|
|
|
93
93
|
##### Verbatim description for `wiki_write`
|
package/README.zh.md
CHANGED
|
@@ -53,7 +53,7 @@ kind: "package-reference"
|
|
|
53
53
|
### 工具
|
|
54
54
|
|
|
55
55
|
- `wiki_read(id)` — 按仓库相对路径读取笔记,返回 frontmatter、正文、链接、已解析的链接笔记,以及内容指纹 `version`。
|
|
56
|
-
- `wiki_search(query)` — 按标题、id
|
|
56
|
+
- `wiki_search(query)` — 按标题、id、正文关键词搜索;查询词采用 OR 匹配,并按字段加权的 BM25 式评分排序(标题/id 命中权重最高,稀有词权重更高),另有整段短语加分与被强命中笔记链接的图增强;挂载 `wiki_semantic_search` 时两路排序经 RRF 融合。结果包含分数与反向链接数量。
|
|
57
57
|
- `wiki_write(id, content, mode?, baseVersion?)` — 创建或追加笔记。追加模式保留 frontmatter 并添加时间戳标题。把 `wiki_read` 返回的 `version` 作为 `baseVersion` 传入时,若笔记在读取后被其他写入方改动,写入会显式失败。
|
|
58
58
|
|
|
59
59
|
### 安全
|
|
@@ -65,7 +65,7 @@ kind: "package-reference"
|
|
|
65
65
|
<a id="understand-the-implementation"></a>
|
|
66
66
|
## 实现说明
|
|
67
67
|
|
|
68
|
-
本包是一个没有运行时服务的 Cordis 函数插件,只在 `ctx.tools` 上注册三个类型化工具。仓库根目录在每次工具调用时解析:优先使用显式 `vaultRoot`(相对路径锚定会话工作区),否则使用 `<session cwd>/.dsh/memory/`,使每个工作区拥有自己的笔记。每个工具都通过 `node:fs/promises` 直接读取 Markdown 文件,并借助 `path.resolve` + 前缀检查保持在解析出的根目录内。YAML frontmatter 使用 `js-yaml` 解析;`[[link|alias]]`
|
|
68
|
+
本包是一个没有运行时服务的 Cordis 函数插件,只在 `ctx.tools` 上注册三个类型化工具。仓库根目录在每次工具调用时解析:优先使用显式 `vaultRoot`(相对路径锚定会话工作区),否则使用 `<session cwd>/.dsh/memory/`,使每个工作区拥有自己的笔记。每个工具都通过 `node:fs/promises` 直接读取 Markdown 文件,并借助 `path.resolve` + 前缀检查保持在解析出的根目录内。YAML frontmatter 使用 `js-yaml` 解析;`[[link|alias]]` 形式的引用会提取管道符前的目标;出现在行内代码或围栏代码块中的 `[[...]]` 是语法示例而非链接,会被忽略。链接目标按 Obsidian 语义对已索引的笔记 id 解析:先精确匹配仓库相对路径,再做路径后缀匹配(`[[notes/foo]]` 可命中 `shared/notes/foo.md`),最后匹配仓库内任意位置的 basename——每一级都容忍目标带或不带扩展名。多重命中时优先路径段最少者,仍并列则取码点序最小的 id,因此解析结果跨平台确定。搜索时从仓库内容构建临时索引并分层排序:OR 匹配的字段加权评分(id/标题 ×3、反向链接 ×1、正文 ×1,含 IDF 使稀有词权重更高、BM25 饱和与长度归一化避免长笔记占优)、整段短语加分,以及被强命中笔记链接的图增强。挂载 `wiki_semantic_search` 时其排序经倒数排名融合并入;语义检索失败时回退到纯词法排序。`wiki_write` 以原子方式发布:正文先写入同级临时文件,再 `rename` 覆盖目标,因此并发读者永远不会读到写了一半的笔记。
|
|
69
69
|
|
|
70
70
|
-----
|
|
71
71
|
|
|
@@ -76,7 +76,7 @@ kind: "package-reference"
|
|
|
76
76
|
|
|
77
77
|
#### 模型看到的内容
|
|
78
78
|
|
|
79
|
-
模型看到的是生成的
|
|
79
|
+
模型看到的是生成的 `wiki_read`、`wiki_search` 和 `wiki_write` schema。工具描述会告知模型:笔记是带 YAML frontmatter 和 Obsidian 风格 `[[link]]` 链接的 Markdown 文件,`wiki_read` 会按配置深度跟随链接。
|
|
80
80
|
|
|
81
81
|
##### `wiki_read` 的完整描述
|
|
82
82
|
|
|
@@ -87,7 +87,7 @@ Read one Markdown note from the wiki vault, optionally following Obsidian-style
|
|
|
87
87
|
##### `wiki_search` 的完整描述
|
|
88
88
|
|
|
89
89
|
```markdown
|
|
90
|
-
Search the wiki vault by note title or body keyword. Returns matching note ids, titles, and backlink counts. Use this before asking the user which note to read.
|
|
90
|
+
Search the wiki vault by note title or body keyword. Terms are OR-matched; results are ranked by field-weighted relevance (title/id hits outrank body hits, rare terms weigh more, notes linked from strong hits get a boost, and results may be fused with semantic search when available). Returns matching note ids, titles, scores, and backlink counts. Use this before asking the user which note to read.
|
|
91
91
|
```
|
|
92
92
|
|
|
93
93
|
##### `wiki_write` 的完整描述
|
package/lib/index.js
CHANGED
|
@@ -12,7 +12,9 @@ import { readdir, readFile, realpath, rename, rm, stat, writeFile, mkdir } from
|
|
|
12
12
|
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
13
13
|
import z from '@deepseek-ai/schemastery';
|
|
14
14
|
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
15
|
+
import { formatBeijingTime } from '@jacklika/dsh-memory-time';
|
|
15
16
|
import yaml from 'js-yaml';
|
|
17
|
+
import { codeUnitCompare, fuseRankings, rankNotes } from "./search.js";
|
|
16
18
|
/**
|
|
17
19
|
* Compute a vault-relative note id from an absolute path. The result always
|
|
18
20
|
* uses POSIX separators so note ids are stable across Windows, macOS, and Linux.
|
|
@@ -20,31 +22,6 @@ import yaml from 'js-yaml';
|
|
|
20
22
|
export function vaultRelativeId(root, absolutePath) {
|
|
21
23
|
return relative(root, absolutePath).replace(/\\/g, '/');
|
|
22
24
|
}
|
|
23
|
-
/**
|
|
24
|
-
* Format a Date as an ISO-like string in Asia/Shanghai (+08:00).
|
|
25
|
-
* The project convention is to store all vault timestamps in Beijing time.
|
|
26
|
-
* Keep this in sync with the helper in `@jacklika/dsh-memory-curator`.
|
|
27
|
-
*/
|
|
28
|
-
export function formatBeijingTime(date) {
|
|
29
|
-
const parts = new Intl.DateTimeFormat('sv-SE', {
|
|
30
|
-
timeZone: 'Asia/Shanghai',
|
|
31
|
-
year: 'numeric',
|
|
32
|
-
month: '2-digit',
|
|
33
|
-
day: '2-digit',
|
|
34
|
-
hour: '2-digit',
|
|
35
|
-
minute: '2-digit',
|
|
36
|
-
second: '2-digit',
|
|
37
|
-
hour12: false,
|
|
38
|
-
}).formatToParts(date);
|
|
39
|
-
const get = (type) => parts.find((p) => p.type === type)?.value ?? '00';
|
|
40
|
-
const yyyy = get('year');
|
|
41
|
-
const MM = get('month');
|
|
42
|
-
const dd = get('day');
|
|
43
|
-
const HH = get('hour');
|
|
44
|
-
const mm = get('minute');
|
|
45
|
-
const ss = get('second');
|
|
46
|
-
return `${yyyy}-${MM}-${dd}T${HH}:${mm}:${ss}+08:00`;
|
|
47
|
-
}
|
|
48
25
|
/** Cordis plugin name used by loader diagnostics. */
|
|
49
26
|
export const name = 'tool-memory-filesystem';
|
|
50
27
|
/** Services required by the wiki/memory tool suite. */
|
|
@@ -135,12 +112,16 @@ export function splitFrontmatter(text) {
|
|
|
135
112
|
const bodyText = match[2] ?? '';
|
|
136
113
|
try {
|
|
137
114
|
const parsed = yaml.load(frontmatterText);
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
115
|
+
const frontmatter = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
116
|
+
? parsed
|
|
117
|
+
: {};
|
|
118
|
+
// js-yaml coerces unquoted timestamps to Date; vault convention stores them
|
|
119
|
+
// as Asia/Shanghai +08:00 strings, so convert back before they reach callers.
|
|
120
|
+
for (const [key, value] of Object.entries(frontmatter)) {
|
|
121
|
+
if (value instanceof Date)
|
|
122
|
+
frontmatter[key] = formatBeijingTime(value);
|
|
123
|
+
}
|
|
124
|
+
return { frontmatter, body: bodyText };
|
|
144
125
|
}
|
|
145
126
|
catch {
|
|
146
127
|
return { frontmatter: {}, body: text };
|
|
@@ -165,12 +146,66 @@ export function extractLinks(text) {
|
|
|
165
146
|
const links = [];
|
|
166
147
|
const pattern = /\[\[([^|\]\r\n]+)(?:\|[^\]]*)?\]\]/g;
|
|
167
148
|
let match;
|
|
168
|
-
while ((match = pattern.exec(text)) !== null) {
|
|
149
|
+
while ((match = pattern.exec(stripCode(text))) !== null) {
|
|
169
150
|
if (match[1] !== undefined)
|
|
170
151
|
links.push(match[1].trim());
|
|
171
152
|
}
|
|
172
153
|
return [...new Set(links)];
|
|
173
154
|
}
|
|
155
|
+
/**
|
|
156
|
+
* Remove fenced code blocks and inline code spans so literal `[[...]]` inside
|
|
157
|
+
* them is not treated as a link. Fences follow CommonMark: a closing fence
|
|
158
|
+
* must use the same marker character and be at least as long as the opener —
|
|
159
|
+
* a rule a regex backreference cannot express, so fences are scanned line by
|
|
160
|
+
* line. Inline spans treat backtick runs as maximal units: a run closes only
|
|
161
|
+
* at a later run of exactly equal length; an unmatched run is literal text.
|
|
162
|
+
* @param text - note body.
|
|
163
|
+
* @returns the text with all code sections dropped.
|
|
164
|
+
*/
|
|
165
|
+
function stripCode(text) {
|
|
166
|
+
const kept = [];
|
|
167
|
+
let fenceChar = '';
|
|
168
|
+
let fenceLen = 0;
|
|
169
|
+
for (const line of text.split('\n')) {
|
|
170
|
+
if (fenceChar === '') {
|
|
171
|
+
const open = /^( {0,3})(`{3,}|~{3,})/.exec(line);
|
|
172
|
+
if (open?.[2] !== undefined) {
|
|
173
|
+
fenceChar = open[2][0] ?? '';
|
|
174
|
+
fenceLen = open[2].length;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
kept.push(line);
|
|
178
|
+
}
|
|
179
|
+
else if (new RegExp(`^ {0,3}${fenceChar === '`' ? '`' : '~'}{${fenceLen},}[ \t]*$`).test(line)) {
|
|
180
|
+
fenceChar = '';
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const body = kept.join('\n');
|
|
184
|
+
let out = '';
|
|
185
|
+
let i = 0;
|
|
186
|
+
while (i < body.length) {
|
|
187
|
+
if (body[i] !== '`') {
|
|
188
|
+
out += body[i];
|
|
189
|
+
i++;
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
let j = i;
|
|
193
|
+
while (body[j] === '`')
|
|
194
|
+
j++;
|
|
195
|
+
const run = body.slice(i, j);
|
|
196
|
+
let close = body.indexOf(run, j);
|
|
197
|
+
while (close !== -1 && (body[close - 1] === '`' || body[close + run.length] === '`')) {
|
|
198
|
+
close = body.indexOf(run, close + 1);
|
|
199
|
+
}
|
|
200
|
+
if (close === -1) {
|
|
201
|
+
out += run;
|
|
202
|
+
i = j;
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
i = close + run.length;
|
|
206
|
+
}
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
174
209
|
/**
|
|
175
210
|
* Normalize a configured file extension to a dot-prefixed form.
|
|
176
211
|
* @param ext - extension string.
|
|
@@ -180,14 +215,79 @@ export function dottedExtension(ext) {
|
|
|
180
215
|
return ext.startsWith('.') ? ext : `.${ext}`;
|
|
181
216
|
}
|
|
182
217
|
/**
|
|
183
|
-
*
|
|
184
|
-
*
|
|
218
|
+
* Build a resolver over the known note ids, matching Obsidian semantics: an
|
|
219
|
+
* exact vault-relative path first, then a path-suffix match, then a bare
|
|
220
|
+
* basename match — each tier tolerates the target carrying or omitting the
|
|
221
|
+
* extension. Ambiguity within a tier resolves to the id with the fewest path
|
|
222
|
+
* segments, ties by code-unit order, so results are identical across hosts.
|
|
223
|
+
* @param ids - vault-relative note ids (e.g. `shared/notes/foo.md`).
|
|
224
|
+
* @returns resolver function for `[[...]]` targets.
|
|
225
|
+
*/
|
|
226
|
+
export function createLinkResolver(ids) {
|
|
227
|
+
const entries = ids.map(id => {
|
|
228
|
+
const stem = id.replace(/\.[^./]+$/, '');
|
|
229
|
+
return {
|
|
230
|
+
id,
|
|
231
|
+
stem,
|
|
232
|
+
basenameId: id.slice(id.lastIndexOf('/') + 1),
|
|
233
|
+
basenameStem: stem.slice(stem.lastIndexOf('/') + 1),
|
|
234
|
+
segments: id.split('/').length,
|
|
235
|
+
};
|
|
236
|
+
});
|
|
237
|
+
// O(1) lookup tables keyed by every segment-boundary suffix of each id and
|
|
238
|
+
// stem: an exact hit is the full-string key, a path-suffix hit is a proper
|
|
239
|
+
// suffix, and a basename hit is the last segment.
|
|
240
|
+
const exact = new Map();
|
|
241
|
+
const suffix = new Map();
|
|
242
|
+
const basename = new Map();
|
|
243
|
+
const add = (table, key, entry) => {
|
|
244
|
+
const list = table.get(key);
|
|
245
|
+
if (list === undefined)
|
|
246
|
+
table.set(key, [entry]);
|
|
247
|
+
else
|
|
248
|
+
list.push(entry);
|
|
249
|
+
};
|
|
250
|
+
for (const entry of entries) {
|
|
251
|
+
add(basename, entry.basenameId, entry);
|
|
252
|
+
add(basename, entry.basenameStem, entry);
|
|
253
|
+
for (const s of [entry.id, entry.stem]) {
|
|
254
|
+
let boundary = -1;
|
|
255
|
+
while ((boundary = s.indexOf('/', boundary + 1)) !== -1) {
|
|
256
|
+
add(suffix, s.slice(boundary + 1), entry);
|
|
257
|
+
}
|
|
258
|
+
add(exact, s, entry);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const pick = (matches) => {
|
|
262
|
+
if (matches === undefined || matches.length === 0)
|
|
263
|
+
return undefined;
|
|
264
|
+
matches.sort((a, b) => a.segments - b.segments || codeUnitCompare(a.id, b.id));
|
|
265
|
+
return matches[0]?.id;
|
|
266
|
+
};
|
|
267
|
+
return (target) => {
|
|
268
|
+
const t = target.replace(/\\/g, '/');
|
|
269
|
+
const hit = pick(exact.get(t)) ?? pick(suffix.get(t)) ?? pick(basename.get(t));
|
|
270
|
+
return hit;
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Resolve a link target to an existing note file inside the vault. When
|
|
275
|
+
* `resolve` is provided the target is first looked up in the note-id set with
|
|
276
|
+
* Obsidian semantics (exact path, then path suffix, then basename); otherwise
|
|
277
|
+
* the target is probed as a vault-relative path and extensions are tried in
|
|
278
|
+
* config order. Every result still passes the realpath containment check.
|
|
185
279
|
* @param root - vault root.
|
|
186
280
|
* @param extensions - note extensions.
|
|
187
281
|
* @param target - link target from `[[...]]`.
|
|
282
|
+
* @param resolve - optional resolver built by {@link createLinkResolver}.
|
|
188
283
|
* @returns the resolved absolute path, or `undefined` if no file exists.
|
|
189
284
|
*/
|
|
190
|
-
export async function resolveLinkTarget(root, extensions, target) {
|
|
285
|
+
export async function resolveLinkTarget(root, extensions, target, resolve) {
|
|
286
|
+
if (resolve !== undefined) {
|
|
287
|
+
const id = resolve(target);
|
|
288
|
+
if (id !== undefined)
|
|
289
|
+
return containedPathReal(root, id);
|
|
290
|
+
}
|
|
191
291
|
const candidates = extensions.map(ext => `${target}${dottedExtension(ext)}`);
|
|
192
292
|
candidates.push(target);
|
|
193
293
|
for (const candidate of candidates) {
|
|
@@ -251,9 +351,11 @@ export async function listNotePaths(root, extensions, indexHiddenDirs = false) {
|
|
|
251
351
|
* @param maxLinkDepth - how many link hops to resolve.
|
|
252
352
|
* @param absolutePath - absolute path of the note.
|
|
253
353
|
* @param visited - set of already-visited absolute paths to prevent cycles.
|
|
354
|
+
* @param linkResolver - resolver over the vault's note ids; built once per
|
|
355
|
+
* call tree so bare `[[filename]]` links resolve without rescanning.
|
|
254
356
|
* @returns the parsed note with linked notes attached.
|
|
255
357
|
*/
|
|
256
|
-
export async function readNote(root, extensions, maxLinkDepth, absolutePath, visited = new Set()) {
|
|
358
|
+
export async function readNote(root, extensions, maxLinkDepth, absolutePath, visited = new Set(), linkResolver) {
|
|
257
359
|
if (visited.has(absolutePath)) {
|
|
258
360
|
return {
|
|
259
361
|
path: absolutePath,
|
|
@@ -273,9 +375,9 @@ export async function readNote(root, extensions, maxLinkDepth, absolutePath, vis
|
|
|
273
375
|
const linkedNotes = [];
|
|
274
376
|
if (maxLinkDepth > 0) {
|
|
275
377
|
for (const link of links) {
|
|
276
|
-
const target = await resolveLinkTarget(root, extensions, link);
|
|
378
|
+
const target = await resolveLinkTarget(root, extensions, link, linkResolver);
|
|
277
379
|
if (target !== undefined) {
|
|
278
|
-
const child = await readNote(root, extensions, maxLinkDepth - 1, target, nextVisited);
|
|
380
|
+
const child = await readNote(root, extensions, maxLinkDepth - 1, target, nextVisited, linkResolver);
|
|
279
381
|
linkedNotes.push(child);
|
|
280
382
|
}
|
|
281
383
|
}
|
|
@@ -322,12 +424,10 @@ export async function buildIndex(root, extensions, indexHiddenDirs = false) {
|
|
|
322
424
|
: note.id.replace(/\.[^.]+$/, '');
|
|
323
425
|
index.set(note.id, { id: note.id, title, backlinks: [], body: note.body });
|
|
324
426
|
}
|
|
427
|
+
const linkResolver = createLinkResolver([...index.keys()]);
|
|
325
428
|
for (const note of notes) {
|
|
326
429
|
for (const link of note.links) {
|
|
327
|
-
const targetId =
|
|
328
|
-
const base = id.replace(/\.[^.]+$/, '');
|
|
329
|
-
return base === link || id === link;
|
|
330
|
-
});
|
|
430
|
+
const targetId = linkResolver(link);
|
|
331
431
|
if (targetId !== undefined) {
|
|
332
432
|
const entry = index.get(targetId);
|
|
333
433
|
if (entry !== undefined && !entry.backlinks.includes(note.id)) {
|
|
@@ -395,13 +495,15 @@ export function apply(ctx, config) {
|
|
|
395
495
|
async execute(args, exec) {
|
|
396
496
|
const vaultRoot = vaultRootFor(exec);
|
|
397
497
|
const absolutePath = await containedPathReal(vaultRoot, args.id);
|
|
398
|
-
const
|
|
498
|
+
const linkResolver = createLinkResolver((await listNotePaths(vaultRoot, resolved.extensions, resolved.indexHiddenDirs))
|
|
499
|
+
.map(path => vaultRelativeId(vaultRoot, path)));
|
|
500
|
+
const note = await readNote(vaultRoot, resolved.extensions, resolved.maxLinkDepth, absolutePath, new Set(), linkResolver);
|
|
399
501
|
return note;
|
|
400
502
|
},
|
|
401
503
|
})));
|
|
402
504
|
ctx.effect(() => ctx.tools.register(defineTool({
|
|
403
505
|
name: 'wiki_search',
|
|
404
|
-
description: 'Search the wiki vault by note title or body keyword. Returns matching note ids, titles, and backlink counts. Use this before asking the user which note to read.',
|
|
506
|
+
description: 'Search the wiki vault by note title or body keyword. Terms are OR-matched; results are ranked by field-weighted relevance (title/id hits outrank body hits, rare terms weigh more, notes linked from strong hits get a boost, and results may be fused with semantic search when available). Returns matching note ids, titles, scores, and backlink counts. Use this before asking the user which note to read.',
|
|
405
507
|
parameters: {
|
|
406
508
|
query: {
|
|
407
509
|
type: 'string',
|
|
@@ -418,6 +520,7 @@ export function apply(ctx, config) {
|
|
|
418
520
|
properties: {
|
|
419
521
|
id: { type: 'string' },
|
|
420
522
|
title: { type: 'string' },
|
|
523
|
+
score: { type: 'number' },
|
|
421
524
|
backlinks: { type: 'array', items: { type: 'string' } },
|
|
422
525
|
},
|
|
423
526
|
},
|
|
@@ -427,15 +530,41 @@ export function apply(ctx, config) {
|
|
|
427
530
|
async execute(args, exec) {
|
|
428
531
|
const vaultRoot = vaultRootFor(exec);
|
|
429
532
|
const index = await buildIndex(vaultRoot, resolved.extensions, resolved.indexHiddenDirs);
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
533
|
+
let hits = rankNotes(index, args.query);
|
|
534
|
+
// Optional semantic layer: when `wiki_semantic_search` is mounted, fuse
|
|
535
|
+
// both rankings via reciprocal rank fusion. Only the dispatch is
|
|
536
|
+
// fail-soft — an unavailable or erroring semantic layer degrades to the
|
|
537
|
+
// lexical ranking; parse/fusion errors propagate so real bugs surface
|
|
538
|
+
// instead of silently weakening results.
|
|
539
|
+
if (ctx.tools.get('wiki_semantic_search') !== undefined) {
|
|
540
|
+
let semantic;
|
|
541
|
+
try {
|
|
542
|
+
semantic = await ctx.tools.execute({
|
|
543
|
+
callId: `${exec.callId}:wiki_semantic_search:${randomUUID()}`,
|
|
544
|
+
rootCallId: exec.rootCallId,
|
|
545
|
+
name: 'wiki_semantic_search',
|
|
546
|
+
arguments: { query: args.query },
|
|
547
|
+
parent: exec.token,
|
|
548
|
+
signal: exec.signal,
|
|
549
|
+
...(exec.agent !== undefined ? { agent: exec.agent } : {}),
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
catch (error) {
|
|
553
|
+
ctx.logger?.warn('tool-memory-filesystem: semantic fusion skipped: ' + String(error));
|
|
554
|
+
}
|
|
555
|
+
if (semantic !== undefined && !semantic.isError) {
|
|
556
|
+
const semanticHits = JSON.parse(semantic.content
|
|
557
|
+
.map(block => {
|
|
558
|
+
const maybe = block;
|
|
559
|
+
return maybe.type === 'text' && typeof maybe.text === 'string' ? maybe.text : '';
|
|
560
|
+
})
|
|
561
|
+
.join('') || '[]');
|
|
562
|
+
hits = fuseRankings(hits, semanticHits.map(hit => hit.id), index);
|
|
563
|
+
}
|
|
564
|
+
else if (semantic !== undefined) {
|
|
565
|
+
ctx.logger?.warn('tool-memory-filesystem: semantic fusion skipped: wiki_semantic_search returned an error');
|
|
436
566
|
}
|
|
437
567
|
}
|
|
438
|
-
hits.sort((a, b) => b.backlinks.length - a.backlinks.length);
|
|
439
568
|
return hits.slice(0, resolved.maxSearchResults);
|
|
440
569
|
},
|
|
441
570
|
})));
|
package/lib/search.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-layer lexical ranking for `wiki_search`: field-weighted BM25-style
|
|
3
|
+
* scoring over note id/title/backlinks/body, a verbatim-phrase bonus, and a
|
|
4
|
+
* link-graph boost for notes referenced by strong lexical hits. Substring
|
|
5
|
+
* matching (not tokenization) keeps CJK text working without a segmenter.
|
|
6
|
+
* @module @jacklika/dsh-tool-memory-filesystem/search
|
|
7
|
+
*/
|
|
8
|
+
const K1 = 1.2;
|
|
9
|
+
const B = 0.75;
|
|
10
|
+
const TITLE_WEIGHT = 3;
|
|
11
|
+
const BODY_WEIGHT = 1;
|
|
12
|
+
const BACKLINK_WEIGHT = 1;
|
|
13
|
+
const GRAPH_BOOST = 0.15;
|
|
14
|
+
const RRF_K = 60;
|
|
15
|
+
function countOccurrences(haystack, needle) {
|
|
16
|
+
if (needle === '')
|
|
17
|
+
return 0;
|
|
18
|
+
let count = 0;
|
|
19
|
+
let from = 0;
|
|
20
|
+
while ((from = haystack.indexOf(needle, from)) !== -1) {
|
|
21
|
+
count += 1;
|
|
22
|
+
from += needle.length;
|
|
23
|
+
}
|
|
24
|
+
return count;
|
|
25
|
+
}
|
|
26
|
+
function toHit(note, score) {
|
|
27
|
+
return {
|
|
28
|
+
id: note.id,
|
|
29
|
+
title: note.title,
|
|
30
|
+
score: Math.round(score * 10000) / 10000,
|
|
31
|
+
backlinks: note.backlinks,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Rank every note in `index` against `query`. Any note containing at least one
|
|
36
|
+
* query term (OR semantics) is a candidate; scores follow BM25 saturation with
|
|
37
|
+
* field weights (`id`/`title` ×3, backlinks ×1, body ×1), a phrase bonus for a
|
|
38
|
+
* verbatim multi-term match, and a graph boost for notes linked from a scored
|
|
39
|
+
* hit.
|
|
40
|
+
* @param index - note index built by {@link buildIndex}.
|
|
41
|
+
* @param query - raw query text.
|
|
42
|
+
* @returns hits sorted by descending score.
|
|
43
|
+
*/
|
|
44
|
+
export function rankNotes(index, query) {
|
|
45
|
+
const lowered = query.toLowerCase();
|
|
46
|
+
const terms = [...new Set(lowered.split(/\s+/).filter(Boolean))];
|
|
47
|
+
if (terms.length === 0)
|
|
48
|
+
return [];
|
|
49
|
+
const prepared = [...index.values()].map(note => ({
|
|
50
|
+
note,
|
|
51
|
+
titleField: `${note.id} ${note.title}`.toLowerCase(),
|
|
52
|
+
backlinkField: note.backlinks.join(' ').toLowerCase(),
|
|
53
|
+
bodyField: note.body.toLowerCase(),
|
|
54
|
+
docLen: Math.max(1, note.body.length),
|
|
55
|
+
}));
|
|
56
|
+
const docCount = prepared.length;
|
|
57
|
+
const avgdl = prepared.reduce((sum, p) => sum + p.docLen, 0) / Math.max(1, docCount);
|
|
58
|
+
const idf = new Map();
|
|
59
|
+
for (const term of terms) {
|
|
60
|
+
const df = prepared.filter(p => p.titleField.includes(term) || p.backlinkField.includes(term) || p.bodyField.includes(term)).length;
|
|
61
|
+
idf.set(term, Math.log(1 + (docCount - df + 0.5) / (df + 0.5)));
|
|
62
|
+
}
|
|
63
|
+
const sumIdf = [...idf.values()].reduce((a, b) => a + b, 0);
|
|
64
|
+
const scores = new Map();
|
|
65
|
+
const phrase = lowered.trim();
|
|
66
|
+
for (const p of prepared) {
|
|
67
|
+
let score = 0;
|
|
68
|
+
for (const term of terms) {
|
|
69
|
+
const tf = TITLE_WEIGHT * countOccurrences(p.titleField, term) +
|
|
70
|
+
BACKLINK_WEIGHT * countOccurrences(p.backlinkField, term) +
|
|
71
|
+
BODY_WEIGHT * countOccurrences(p.bodyField, term);
|
|
72
|
+
if (tf === 0)
|
|
73
|
+
continue;
|
|
74
|
+
const termIdf = idf.get(term) ?? 0;
|
|
75
|
+
score += termIdf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + (B * p.docLen) / avgdl));
|
|
76
|
+
}
|
|
77
|
+
if (terms.length > 1) {
|
|
78
|
+
if (p.titleField.includes(phrase))
|
|
79
|
+
score += sumIdf;
|
|
80
|
+
else if (p.bodyField.includes(phrase))
|
|
81
|
+
score += 0.5 * sumIdf;
|
|
82
|
+
}
|
|
83
|
+
if (score > 0)
|
|
84
|
+
scores.set(p.note.id, score);
|
|
85
|
+
}
|
|
86
|
+
// Graph boost: a note linked from a scored hit gains a fraction of that
|
|
87
|
+
// hit's score (the strongest link wins). `backlinks` lists the sources, so
|
|
88
|
+
// hit H links to T exactly when H.id ∈ T.backlinks.
|
|
89
|
+
const linkedBoost = new Map();
|
|
90
|
+
for (const p of prepared) {
|
|
91
|
+
for (const sourceId of p.note.backlinks) {
|
|
92
|
+
const sourceScore = scores.get(sourceId);
|
|
93
|
+
if (sourceScore !== undefined) {
|
|
94
|
+
linkedBoost.set(p.note.id, Math.max(linkedBoost.get(p.note.id) ?? 0, GRAPH_BOOST * sourceScore));
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const hits = [];
|
|
99
|
+
for (const p of prepared) {
|
|
100
|
+
const score = (scores.get(p.note.id) ?? 0) + (linkedBoost.get(p.note.id) ?? 0);
|
|
101
|
+
if (score > 0)
|
|
102
|
+
hits.push(toHit(p.note, score));
|
|
103
|
+
}
|
|
104
|
+
hits.sort((a, b) => b.score - a.score || codeUnitCompare(a.id, b.id));
|
|
105
|
+
return hits;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Locale-independent code-unit ordering — `localeCompare` without a locale
|
|
109
|
+
* follows the host runtime locale, which makes tied-score ordering differ
|
|
110
|
+
* across machines.
|
|
111
|
+
*/
|
|
112
|
+
export function codeUnitCompare(a, b) {
|
|
113
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Fuse the lexical ranking with a semantic-search ranking using reciprocal
|
|
117
|
+
* rank fusion (k = 60). Semantic-only notes are surfaced with their index
|
|
118
|
+
* metadata so the output shape stays uniform.
|
|
119
|
+
* @param lexical - hits from {@link rankNotes}.
|
|
120
|
+
* @param semanticIds - note ids ordered by descending semantic similarity.
|
|
121
|
+
* @param index - the note index for metadata lookup.
|
|
122
|
+
* @returns fused hits sorted by descending RRF score.
|
|
123
|
+
*/
|
|
124
|
+
export function fuseRankings(lexical, semanticIds, index) {
|
|
125
|
+
const fused = new Map();
|
|
126
|
+
const contribute = (id, rank) => {
|
|
127
|
+
const existing = fused.get(id);
|
|
128
|
+
if (existing !== undefined) {
|
|
129
|
+
existing.score += 1 / (RRF_K + rank + 1);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const note = index.get(id);
|
|
133
|
+
if (note === undefined)
|
|
134
|
+
return; // never fabricate a hit for an id outside the vault index
|
|
135
|
+
fused.set(id, {
|
|
136
|
+
id,
|
|
137
|
+
title: note.title,
|
|
138
|
+
score: 1 / (RRF_K + rank + 1),
|
|
139
|
+
backlinks: note.backlinks,
|
|
140
|
+
});
|
|
141
|
+
};
|
|
142
|
+
lexical.forEach((hit, rank) => contribute(hit.id, rank));
|
|
143
|
+
semanticIds.forEach((id, rank) => contribute(id, rank));
|
|
144
|
+
const hits = [...fused.values()];
|
|
145
|
+
for (const hit of hits)
|
|
146
|
+
hit.score = Math.round(hit.score * 10000) / 10000;
|
|
147
|
+
hits.sort((a, b) => b.score - a.score || codeUnitCompare(a.id, b.id));
|
|
148
|
+
return hits;
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=search.js.map
|
package/lib/types/index.d.ts
CHANGED
|
@@ -17,12 +17,6 @@ export type * from './types.ts';
|
|
|
17
17
|
* uses POSIX separators so note ids are stable across Windows, macOS, and Linux.
|
|
18
18
|
*/
|
|
19
19
|
export declare function vaultRelativeId(root: string, absolutePath: string): string;
|
|
20
|
-
/**
|
|
21
|
-
* Format a Date as an ISO-like string in Asia/Shanghai (+08:00).
|
|
22
|
-
* The project convention is to store all vault timestamps in Beijing time.
|
|
23
|
-
* Keep this in sync with the helper in `@jacklika/dsh-memory-curator`.
|
|
24
|
-
*/
|
|
25
|
-
export declare function formatBeijingTime(date: Date): string;
|
|
26
20
|
/** Cordis plugin name used by loader diagnostics. */
|
|
27
21
|
export declare const name = "tool-memory-filesystem";
|
|
28
22
|
/** Services required by the wiki/memory tool suite. */
|
|
@@ -108,14 +102,33 @@ export declare function extractLinks(text: string): string[];
|
|
|
108
102
|
*/
|
|
109
103
|
export declare function dottedExtension(ext: string): string;
|
|
110
104
|
/**
|
|
111
|
-
*
|
|
112
|
-
*
|
|
105
|
+
* A link resolver maps an Obsidian `[[target]]` to a vault-relative note id,
|
|
106
|
+
* or `undefined` when nothing matches.
|
|
107
|
+
*/
|
|
108
|
+
export type LinkResolver = (target: string) => string | undefined;
|
|
109
|
+
/**
|
|
110
|
+
* Build a resolver over the known note ids, matching Obsidian semantics: an
|
|
111
|
+
* exact vault-relative path first, then a path-suffix match, then a bare
|
|
112
|
+
* basename match — each tier tolerates the target carrying or omitting the
|
|
113
|
+
* extension. Ambiguity within a tier resolves to the id with the fewest path
|
|
114
|
+
* segments, ties by code-unit order, so results are identical across hosts.
|
|
115
|
+
* @param ids - vault-relative note ids (e.g. `shared/notes/foo.md`).
|
|
116
|
+
* @returns resolver function for `[[...]]` targets.
|
|
117
|
+
*/
|
|
118
|
+
export declare function createLinkResolver(ids: string[]): LinkResolver;
|
|
119
|
+
/**
|
|
120
|
+
* Resolve a link target to an existing note file inside the vault. When
|
|
121
|
+
* `resolve` is provided the target is first looked up in the note-id set with
|
|
122
|
+
* Obsidian semantics (exact path, then path suffix, then basename); otherwise
|
|
123
|
+
* the target is probed as a vault-relative path and extensions are tried in
|
|
124
|
+
* config order. Every result still passes the realpath containment check.
|
|
113
125
|
* @param root - vault root.
|
|
114
126
|
* @param extensions - note extensions.
|
|
115
127
|
* @param target - link target from `[[...]]`.
|
|
128
|
+
* @param resolve - optional resolver built by {@link createLinkResolver}.
|
|
116
129
|
* @returns the resolved absolute path, or `undefined` if no file exists.
|
|
117
130
|
*/
|
|
118
|
-
export declare function resolveLinkTarget(root: string, extensions: string[], target: string): Promise<string | undefined>;
|
|
131
|
+
export declare function resolveLinkTarget(root: string, extensions: string[], target: string, resolve?: LinkResolver): Promise<string | undefined>;
|
|
119
132
|
/**
|
|
120
133
|
* Recursively discover note files under the vault root. `.git`, `.obsidian`,
|
|
121
134
|
* and `node_modules` are always excluded; other dot-directories are skipped
|
|
@@ -143,9 +156,11 @@ export interface LinkedNote {
|
|
|
143
156
|
* @param maxLinkDepth - how many link hops to resolve.
|
|
144
157
|
* @param absolutePath - absolute path of the note.
|
|
145
158
|
* @param visited - set of already-visited absolute paths to prevent cycles.
|
|
159
|
+
* @param linkResolver - resolver over the vault's note ids; built once per
|
|
160
|
+
* call tree so bare `[[filename]]` links resolve without rescanning.
|
|
146
161
|
* @returns the parsed note with linked notes attached.
|
|
147
162
|
*/
|
|
148
|
-
export declare function readNote(root: string, extensions: string[], maxLinkDepth: number, absolutePath: string, visited?: ReadonlySet<string
|
|
163
|
+
export declare function readNote(root: string, extensions: string[], maxLinkDepth: number, absolutePath: string, visited?: ReadonlySet<string>, linkResolver?: LinkResolver): Promise<Note & {
|
|
149
164
|
linkedNotes: LinkedNote[];
|
|
150
165
|
}>;
|
|
151
166
|
/**
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-layer lexical ranking for `wiki_search`: field-weighted BM25-style
|
|
3
|
+
* scoring over note id/title/backlinks/body, a verbatim-phrase bonus, and a
|
|
4
|
+
* link-graph boost for notes referenced by strong lexical hits. Substring
|
|
5
|
+
* matching (not tokenization) keeps CJK text working without a segmenter.
|
|
6
|
+
* @module @jacklika/dsh-tool-memory-filesystem/search
|
|
7
|
+
*/
|
|
8
|
+
import type { IndexedNote, SearchResult } from './types.ts';
|
|
9
|
+
/** A search hit carrying its fused relevance score. */
|
|
10
|
+
export interface RankedHit extends SearchResult {
|
|
11
|
+
/** Relevance score: BM25 sum (+phrase/graph bonuses), or an RRF score when semantic fusion ran. */
|
|
12
|
+
score: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Rank every note in `index` against `query`. Any note containing at least one
|
|
16
|
+
* query term (OR semantics) is a candidate; scores follow BM25 saturation with
|
|
17
|
+
* field weights (`id`/`title` ×3, backlinks ×1, body ×1), a phrase bonus for a
|
|
18
|
+
* verbatim multi-term match, and a graph boost for notes linked from a scored
|
|
19
|
+
* hit.
|
|
20
|
+
* @param index - note index built by {@link buildIndex}.
|
|
21
|
+
* @param query - raw query text.
|
|
22
|
+
* @returns hits sorted by descending score.
|
|
23
|
+
*/
|
|
24
|
+
export declare function rankNotes(index: Map<string, IndexedNote>, query: string): RankedHit[];
|
|
25
|
+
/**
|
|
26
|
+
* Locale-independent code-unit ordering — `localeCompare` without a locale
|
|
27
|
+
* follows the host runtime locale, which makes tied-score ordering differ
|
|
28
|
+
* across machines.
|
|
29
|
+
*/
|
|
30
|
+
export declare function codeUnitCompare(a: string, b: string): number;
|
|
31
|
+
/**
|
|
32
|
+
* Fuse the lexical ranking with a semantic-search ranking using reciprocal
|
|
33
|
+
* rank fusion (k = 60). Semantic-only notes are surfaced with their index
|
|
34
|
+
* metadata so the output shape stays uniform.
|
|
35
|
+
* @param lexical - hits from {@link rankNotes}.
|
|
36
|
+
* @param semanticIds - note ids ordered by descending semantic similarity.
|
|
37
|
+
* @param index - the note index for metadata lookup.
|
|
38
|
+
* @returns fused hits sorted by descending RRF score.
|
|
39
|
+
*/
|
|
40
|
+
export declare function fuseRankings(lexical: RankedHit[], semanticIds: string[], index: Map<string, IndexedNote>): RankedHit[];
|
|
41
|
+
//# sourceMappingURL=search.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jacklika/dsh-tool-memory-filesystem",
|
|
3
3
|
"description": "Model-facing wiki/memory tools over a local Markdown vault: read, search, and write notes with Obsidian-style links and YAML frontmatter.",
|
|
4
|
-
"version": "0.1.3-alpha.
|
|
4
|
+
"version": "0.1.3-alpha.5",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
7
7
|
},
|
|
@@ -32,7 +32,8 @@
|
|
|
32
32
|
"license": "MIT",
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@deepseek-ai/schemastery": "3.18.4",
|
|
35
|
-
"js-yaml": "^4.2.0"
|
|
35
|
+
"js-yaml": "^4.2.0",
|
|
36
|
+
"@jacklika/dsh-memory-time": "^0.1.0-alpha.0"
|
|
36
37
|
},
|
|
37
38
|
"peerDependencies": {
|
|
38
39
|
"@deepseek-ai/cordis": "4.0.4",
|