obsidian-hybrid-search 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,9 +8,12 @@ Works as an [MCP server](https://modelcontextprotocol.io) for Claude and other A
8
8
 
9
9
  - **Hybrid search** — BM25 + fuzzy title + semantic embeddings, fused with RRF
10
10
  - **Four search modes** — `hybrid`, `semantic`, `fulltext`, `title`
11
- - **Similar note lookup** — pass a path to find semantically related notes
11
+ - **Similar note lookup** — pass `--path` to find semantically related notes
12
+ - **Graph traversal** — `--related` shows linked notes at configurable depth; filter by `--direction outgoing|backlinks|both`
12
13
  - **Links & backlinks** — every result includes outgoing links and backlinks
13
- - **Scope filtering** — restrict search to a subfolder
14
+ - **Scope filtering** — restrict to subfolder(s); supports multiple values and exclusions (`-notes/dev/`)
15
+ - **Tag filtering** — filter by tag(s); supports multiple values and exclusions (`-category/cs`)
16
+ - **Snippet control** — `--snippet-length` sets the context window; empty snippets always fall back to note content
14
17
  - **Incremental indexing** — only re-indexes changed files; watches for edits in real time
15
18
  - **Local embeddings** — works offline via `@xenova/transformers` (no API key required)
16
19
  - **Remote embeddings** — OpenAI-compatible API (OpenRouter, Ollama, etc.)
@@ -56,7 +59,7 @@ obsidian-hybrid-search "zettelkasten atomic notes"
56
59
  # Fulltext BM25 search
57
60
  obsidian-hybrid-search "permanent notes" --mode fulltext
58
61
 
59
- # Fuzzy title search (fast, no snippets)
62
+ # Fuzzy title search (fast, typo-tolerant)
60
63
  obsidian-hybrid-search "zettleksten" --mode title
61
64
 
62
65
  # Semantic / vector search
@@ -68,12 +71,35 @@ obsidian-hybrid-search "productivity systems" --limit 5 --threshold 0.3
68
71
  # Restrict to a subfolder
69
72
  obsidian-hybrid-search "daily review" --scope notes/periodic/
70
73
 
71
- # Filter by tag (frontmatter tags and inline #tags are both indexed)
74
+ # Restrict to multiple subfolders (OR)
75
+ obsidian-hybrid-search "productivity" --scope notes/pkm/ --scope notes/projects/
76
+
77
+ # Exclude a subfolder
78
+ obsidian-hybrid-search "programming" --scope notes/ --scope -notes/archive/
79
+
80
+ # Filter by tag
72
81
  obsidian-hybrid-search "productivity" --tag pkm
73
82
  obsidian-hybrid-search "machine learning" --tag note/basic/primary
74
83
 
75
- # Find notes similar to a specific note
76
- obsidian-hybrid-search "notes/pkm/zettelkasten.md"
84
+ # Filter by multiple tags (OR include, exclude with -)
85
+ obsidian-hybrid-search "learning" --tag pkm --tag -draft
86
+
87
+ # Find semantically similar notes
88
+ obsidian-hybrid-search --path notes/pkm/zettelkasten.md
89
+
90
+ # Graph traversal: show notes linked to/from this note
91
+ # Results show depth: -1/-2 = backlinks, 0 = source, +1/+2 = outgoing links
92
+ obsidian-hybrid-search --path notes/pkm/zettelkasten.md --related
93
+ obsidian-hybrid-search --path notes/pkm/zettelkasten.md --related --depth 2
94
+
95
+ # Only outgoing links (what this note references)
96
+ obsidian-hybrid-search --path notes/pkm/zettelkasten.md --related --direction outgoing
97
+
98
+ # Only backlinks (who references this note)
99
+ obsidian-hybrid-search --path notes/pkm/zettelkasten.md --related --direction backlinks
100
+
101
+ # Longer context around each link
102
+ obsidian-hybrid-search --path notes/pkm/zettelkasten.md --related --snippet-length 500
77
103
 
78
104
  # JSON output (for scripting)
79
105
  obsidian-hybrid-search "spaced repetition" --json
@@ -162,7 +188,7 @@ The server exposes three tools:
162
188
 
163
189
  | Tool | Description |
164
190
  |------|-------------|
165
- | `search` | Search the vault with optional `mode`, `scope`, `limit`, `threshold`, `tag` |
191
+ | `search` | Search the vault. Use `query` for text search or `path` for similarity/graph lookup. Supports `mode`, `scope`, `tag`, `limit`, `threshold`, `related`, `depth`, `direction`, `snippet_length` |
166
192
  | `reindex` | Reindex the vault or a specific file |
167
193
  | `status` | Show total notes, indexed count, last indexed time |
168
194
 
@@ -199,7 +225,7 @@ npm test # run test suite
199
225
  npm run build # compile TypeScript
200
226
  ```
201
227
 
202
- Tests use fake embeddings (no API key required) and run against a temporary vault. All 25 tests cover chunking, BM25 scoring, fuzzy search, links/backlinks, `deleteNote` semantics, and ignore pattern matching.
228
+ Tests use fake embeddings (no API key required) and run against a temporary vault. All tests cover chunking, BM25 scoring, fuzzy search, links/backlinks, tag filtering, scope filtering, related-mode traversal, direction/score logic, snippet fallback, and ignore pattern matching.
203
229
 
204
230
  ## License
205
231
 
package/dist/src/cli.js CHANGED
@@ -1,14 +1,22 @@
1
1
  #!/usr/bin/env node
2
- import { Command } from 'commander';
2
+ import Database from 'better-sqlite3';
3
3
  import Table from 'cli-table3';
4
- import path from 'node:path';
4
+ import { Command } from 'commander';
5
5
  import { existsSync } from 'node:fs';
6
- import Database from 'better-sqlite3';
7
- import { openDb, initVecTable, getStats } from './db.js';
6
+ import path from 'node:path';
7
+ import { config } from './config.js';
8
+ import { getStats, initVecTable, openDb } from './db.js';
8
9
  import { getContextLength, getEmbeddingDim } from './embedder.js';
10
+ import { indexFile, indexVaultSync } from './indexer.js';
9
11
  import { search } from './searcher.js';
10
- import { indexVaultSync, indexFile } from './indexer.js';
11
- import { config } from './config.js';
12
+ /** Truncate text at a word boundary, appending '...' if cut */
13
+ function truncateAtWord(text, maxLen) {
14
+ if (text.length <= maxLen)
15
+ return text;
16
+ const cut = text.slice(0, maxLen);
17
+ const lastSpace = cut.lastIndexOf(' ');
18
+ return (lastSpace > maxLen * 0.7 ? cut.slice(0, lastSpace) : cut) + '...';
19
+ }
12
20
  /**
13
21
  * Find .obsidian-hybrid-search.db by walking up from dir,
14
22
  * read vault_path / api_base_url / api_model from its settings table,
@@ -91,23 +99,36 @@ program
91
99
  .command('search [query]', { isDefault: true })
92
100
  .description('Search the vault (default command)')
93
101
  .option('--mode <mode>', 'Search mode: hybrid|semantic|fulltext|title', 'hybrid')
94
- .option('--scope <scope>', 'Limit to a subfolder, e.g. notes/pkm/')
102
+ .option('--path <path>', 'Note path for similarity/related search (overrides positional query)')
103
+ .option('--scope <scope>', 'Limit to subfolder(s). Repeatable; prefix with "-" to exclude', (v, a) => [...a, v], [])
95
104
  .option('--limit <n>', 'Maximum results', '10')
96
105
  .option('--threshold <n>', 'Minimum score threshold 0..1', '0')
97
- .option('--tag <tag>', 'Filter by tag, e.g. pkm or note/basic/primary')
106
+ .option('--tag <tag>', 'Filter by tag. Repeatable; prefix with "-" to exclude', (v, a) => [...a, v], [])
107
+ .option('--related', 'Graph traversal: show notes linked to/from this note (path input only)')
108
+ .option('--depth <n>', 'Traversal depth for --related mode', '1')
109
+ .option('--direction <direction>', 'Direction for --related: outgoing|backlinks|both (default: both)')
110
+ .option('--snippet-length <n>', 'Max snippet length in characters (default: 300)')
98
111
  .option('--json', 'Output as JSON')
99
112
  .action(async (query, opts) => {
100
- if (!query) {
113
+ const effectiveInput = opts.path ?? query;
114
+ if (!effectiveInput) {
101
115
  program.help();
102
116
  return;
103
117
  }
104
118
  await init();
105
- const results = await search(query, {
119
+ const results = await search(effectiveInput, {
106
120
  mode: opts.mode,
107
- scope: opts.scope,
121
+ scope: opts.scope.length > 0 ? opts.scope : undefined,
108
122
  limit: parseInt(opts.limit),
109
123
  threshold: parseFloat(opts.threshold),
110
- tag: opts.tag,
124
+ tag: opts.tag.length > 0 ? opts.tag : undefined,
125
+ related: opts.related ?? false,
126
+ depth: parseInt(opts.depth),
127
+ direction: opts.direction,
128
+ snippetLength: opts.snippetLength
129
+ ? parseInt(opts.snippetLength)
130
+ : undefined,
131
+ notePath: opts.path,
111
132
  });
112
133
  if (opts.json) {
113
134
  console.log(JSON.stringify(results, null, 2));
@@ -117,13 +138,44 @@ program
117
138
  console.log('No results found.');
118
139
  return;
119
140
  }
141
+ // Related mode: depth-centered table
142
+ if (opts.related) {
143
+ const table = new Table({
144
+ head: ['DEPTH', 'PATH', 'SNIPPET'],
145
+ colWidths: [7, 45, 55],
146
+ wordWrap: true,
147
+ });
148
+ for (const r of results) {
149
+ const d = r.depth ?? 0;
150
+ const depthStr = d === 0 ? ' 0 ●' : d > 0 ? `+${d}` : `${d}`;
151
+ const context = r.snippet
152
+ ? truncateAtWord(r.snippet.replace(/\t/g, ' ').replace(/ {2,}/g, ' '), 160)
153
+ : r.title;
154
+ table.push([depthStr, r.path, context]);
155
+ }
156
+ console.log(table.toString());
157
+ return;
158
+ }
159
+ // Normal search table
120
160
  const hasSnippets = results.some(r => (r.snippet ?? '').trim().length > 0);
121
161
  const table = hasSnippets
122
- ? new Table({ head: ['SCORE', 'PATH', 'SNIPPET'], colWidths: [7, 45, 60], wordWrap: true })
123
- : new Table({ head: ['SCORE', 'PATH'], colWidths: [7, 60], wordWrap: true });
162
+ ? new Table({
163
+ head: ['SCORE', 'PATH', 'SNIPPET'],
164
+ colWidths: [7, 45, 60],
165
+ wordWrap: true,
166
+ })
167
+ : new Table({
168
+ head: ['SCORE', 'PATH'],
169
+ colWidths: [7, 60],
170
+ wordWrap: true,
171
+ });
124
172
  for (const r of results) {
125
173
  if (hasSnippets) {
126
- table.push([r.score.toFixed(2), r.path, (r.snippet ?? '').slice(0, 120)]);
174
+ table.push([
175
+ r.score.toFixed(2),
176
+ r.path,
177
+ (r.snippet ?? '').slice(0, 120),
178
+ ]);
127
179
  }
128
180
  else {
129
181
  table.push([r.score.toFixed(2), r.path]);
@@ -144,7 +196,18 @@ program
144
196
  ? { indexed: 1, skipped: 0, errors: [] }
145
197
  : status === 'skipped'
146
198
  ? { indexed: 0, skipped: 1, errors: [] }
147
- : { indexed: 0, skipped: 0, errors: [{ path: filePath, error: typeof status === 'object' ? status.error : 'indexing failed' }] }, null, 2));
199
+ : {
200
+ indexed: 0,
201
+ skipped: 0,
202
+ errors: [
203
+ {
204
+ path: filePath,
205
+ error: typeof status === 'object'
206
+ ? status.error
207
+ : 'indexing failed',
208
+ },
209
+ ],
210
+ }, null, 2));
148
211
  }
149
212
  else {
150
213
  console.error('Indexing vault...');
@@ -164,7 +227,9 @@ program
164
227
  indexed: stats.indexed,
165
228
  pending: stats.pending,
166
229
  last_indexed: stats.lastIndexed,
167
- model: (config.apiKey || process.env.OPENAI_BASE_URL) ? config.apiModel : 'Xenova/all-MiniLM-L6-v2 (local)',
230
+ model: config.apiKey || process.env.OPENAI_BASE_URL
231
+ ? config.apiModel
232
+ : 'Xenova/all-MiniLM-L6-v2 (local)',
168
233
  context_length: contextLength,
169
234
  }, null, 2));
170
235
  });
@@ -1,20 +1,44 @@
1
- import { getDb, hasVecTable, getNoteByPath, getLinksForPaths } from './db.js';
1
+ import path from 'node:path';
2
+ import { getDb, getLinksForPaths, getNoteByPath, hasVecTable } from './db.js';
2
3
  import { embed } from './embedder.js';
4
+ function matchesScopeFilter(notePath, scope) {
5
+ const scopes = (Array.isArray(scope) ? scope : [scope]).map(s => s.normalize('NFD'));
6
+ const includes = scopes.filter(s => !s.startsWith('-'));
7
+ const excludes = scopes.filter(s => s.startsWith('-')).map(s => s.slice(1));
8
+ if (excludes.some(ex => notePath.startsWith(ex)))
9
+ return false;
10
+ if (includes.length === 0)
11
+ return true;
12
+ return includes.some(inc => notePath.startsWith(inc));
13
+ }
3
14
  function applyScope(results, scope) {
4
15
  if (!scope)
5
16
  return results;
6
- const normalized = scope.normalize('NFD');
7
- return results.filter(r => r.path.startsWith(normalized));
17
+ return results.filter(r => matchesScopeFilter(r.path, scope));
8
18
  }
9
19
  function applyThreshold(results, threshold) {
10
20
  return results.filter(r => r.score >= threshold);
11
21
  }
22
+ function matchesTagFilter(tags, tag) {
23
+ const filters = Array.isArray(tag) ? tag : [tag];
24
+ const includes = filters
25
+ .filter(t => !t.startsWith('-'))
26
+ .map(t => t.toLowerCase());
27
+ const excludes = filters
28
+ .filter(t => t.startsWith('-'))
29
+ .map(t => t.slice(1).toLowerCase());
30
+ const lowerTags = tags.map(t => t.toLowerCase());
31
+ if (excludes.some(ex => lowerTags.some(t => t === ex || t.includes(ex))))
32
+ return false;
33
+ if (includes.length === 0)
34
+ return true;
35
+ return includes.some(inc => lowerTags.some(t => t === inc || t.includes(inc)));
36
+ }
12
37
  function applyTagFilter(results, tag) {
13
- const needle = tag.toLowerCase();
14
38
  return results.filter(r => {
15
39
  try {
16
40
  const tags = JSON.parse(r.tags || '[]');
17
- return tags.some(t => t.toLowerCase() === needle || t.toLowerCase().includes(needle));
41
+ return matchesTagFilter(tags, tag);
18
42
  }
19
43
  catch {
20
44
  return false;
@@ -55,7 +79,8 @@ export function searchBm25(query, limit) {
55
79
  const db = getDb();
56
80
  const ftsQuery = toFtsQuery(query);
57
81
  try {
58
- const rows = db.prepare(`
82
+ const rows = db
83
+ .prepare(`
59
84
  SELECT n.path, n.title, n.tags,
60
85
  snippet(notes_fts_bm25, 1, '', '', '...', 40) AS snippet,
61
86
  bm25(notes_fts_bm25) AS rank
@@ -64,14 +89,17 @@ export function searchBm25(query, limit) {
64
89
  WHERE notes_fts_bm25 MATCH ?
65
90
  ORDER BY rank
66
91
  LIMIT ?
67
- `).all(ftsQuery, limit);
92
+ `)
93
+ .all(ftsQuery, limit);
68
94
  return rows.map((row, i) => ({
69
95
  path: row.path,
70
96
  title: row.title ?? '',
71
97
  tags: row.tags ?? '[]',
72
98
  snippet: row.snippet ?? '',
73
99
  score: Math.max(0, Math.abs(row.rank) / (1 + Math.abs(row.rank))),
74
- scores: { bm25: Math.max(0, Math.abs(row.rank) / (1 + Math.abs(row.rank))) },
100
+ scores: {
101
+ bm25: Math.max(0, Math.abs(row.rank) / (1 + Math.abs(row.rank))),
102
+ },
75
103
  }));
76
104
  }
77
105
  catch {
@@ -91,7 +119,8 @@ export function searchFuzzyTitle(query, limit) {
91
119
  const db = getDb();
92
120
  const ftsQuery = buildTrigramOrQuery(query);
93
121
  try {
94
- const rows = db.prepare(`
122
+ const rows = db
123
+ .prepare(`
95
124
  SELECT n.path, n.title, n.tags,
96
125
  bm25(notes_fts_fuzzy) AS rank
97
126
  FROM notes_fts_fuzzy
@@ -99,14 +128,17 @@ export function searchFuzzyTitle(query, limit) {
99
128
  WHERE notes_fts_fuzzy MATCH ?
100
129
  ORDER BY rank
101
130
  LIMIT ?
102
- `).all(ftsQuery, limit);
103
- return rows.map((row) => ({
131
+ `)
132
+ .all(ftsQuery, limit);
133
+ return rows.map(row => ({
104
134
  path: row.path,
105
135
  title: row.title ?? '',
106
136
  tags: row.tags ?? '[]',
107
137
  snippet: '',
108
138
  score: Math.max(0, Math.abs(row.rank) / (1 + Math.abs(row.rank))),
109
- scores: { fuzzy_title: Math.max(0, Math.abs(row.rank) / (1 + Math.abs(row.rank))) },
139
+ scores: {
140
+ fuzzy_title: Math.max(0, Math.abs(row.rank) / (1 + Math.abs(row.rank))),
141
+ },
110
142
  }));
111
143
  }
112
144
  catch {
@@ -118,7 +150,8 @@ export async function searchVector(queryEmbedding, limit) {
118
150
  return [];
119
151
  const db = getDb();
120
152
  try {
121
- const rows = db.prepare(`
153
+ const rows = db
154
+ .prepare(`
122
155
  SELECT vc.chunk_id, vc.distance,
123
156
  c.note_id, c.text AS chunk_text,
124
157
  n.path, n.title, n.tags
@@ -127,7 +160,8 @@ export async function searchVector(queryEmbedding, limit) {
127
160
  JOIN notes n ON n.id = c.note_id
128
161
  WHERE vc.embedding MATCH ?
129
162
  AND k = ?
130
- `).all(queryEmbedding, limit * 5);
163
+ `)
164
+ .all(queryEmbedding, limit * 5);
131
165
  // Aggregate: best chunk per note
132
166
  const noteMap = new Map();
133
167
  for (const row of rows) {
@@ -179,14 +213,164 @@ function rrfFusion(lists, k = 60) {
179
213
  }
180
214
  }
181
215
  else {
182
- scores.set(result.path, { rrfScore, result: { ...result, scores: { ...result.scores } } });
216
+ scores.set(result.path, {
217
+ rrfScore,
218
+ result: { ...result, scores: { ...result.scores } },
219
+ });
183
220
  }
184
221
  });
185
222
  }
186
223
  const maxPossibleScore = lists.length / (k + 1);
187
224
  return Array.from(scores.values())
188
225
  .sort((a, b) => b.rrfScore - a.rrfScore)
189
- .map(({ rrfScore, result }) => ({ ...result, score: rrfScore / maxPossibleScore }));
226
+ .map(({ rrfScore, result }) => ({
227
+ ...result,
228
+ score: rrfScore / maxPossibleScore,
229
+ }));
230
+ }
231
+ // ─── Graph traversal ─────────────────────────────────────
232
+ /** Get the first maxChars characters of a note's content as a fallback snippet. */
233
+ function getSnippetFallback(notePath, maxChars) {
234
+ const db = getDb();
235
+ const note = db
236
+ .prepare('SELECT content FROM notes WHERE path = ?')
237
+ .get(notePath);
238
+ if (!note?.content)
239
+ return '';
240
+ return note.content.slice(0, maxChars).trim();
241
+ }
242
+ /**
243
+ * Extract the sentence/line context around a wikilink [[target]] inside a note.
244
+ * contentNotePath: the note whose content we search in
245
+ * linkedNotePath: the target note we're looking for a link to
246
+ */
247
+ function getLinkContext(contentNotePath, linkedNotePath, windowSize = 300) {
248
+ const db = getDb();
249
+ const note = db
250
+ .prepare('SELECT content FROM notes WHERE path = ?')
251
+ .get(contentNotePath);
252
+ if (!note?.content)
253
+ return '';
254
+ const basename = path.basename(linkedNotePath, '.md');
255
+ // Match [[basename]], [[basename|alias]], [[basename#heading]], [[folder/basename]], etc.
256
+ const escaped = basename.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
257
+ const regex = new RegExp(`\\[\\[(?:[^\\]|#]*\\/)?${escaped}(?:[|#][^\\]]*)?\\]\\]`, 'i');
258
+ const match = regex.exec(note.content);
259
+ if (!match)
260
+ return '';
261
+ let start = Math.max(0, match.index - windowSize);
262
+ let end = Math.min(note.content.length, match.index + match[0].length + windowSize);
263
+ // Snap to word boundaries so we don't cut mid-word
264
+ if (start > 0) {
265
+ while (start < match.index && !/\s/.test(note.content[start]))
266
+ start++;
267
+ }
268
+ if (end < note.content.length) {
269
+ while (end > match.index + match[0].length &&
270
+ !/\s/.test(note.content[end - 1]))
271
+ end--;
272
+ }
273
+ const prefix = start > 0 ? '...' : '';
274
+ const suffix = end < note.content.length ? '...' : '';
275
+ // Preserve newlines so CLI can strip line-based markdown (headings, blockquotes)
276
+ return prefix + note.content.slice(start, end).trim() + suffix;
277
+ }
278
+ function searchRelated(notePath, maxDepth, direction = 'both', snippetLength = 300) {
279
+ const db = getDb();
280
+ const sourcePath = notePath.normalize('NFD');
281
+ const results = [];
282
+ const makeResult = (notePth, depth, snippet) => {
283
+ const note = db
284
+ .prepare('SELECT path, title, tags FROM notes WHERE path = ?')
285
+ .get(notePth);
286
+ if (!note)
287
+ return null;
288
+ let tags = [];
289
+ try {
290
+ tags = JSON.parse(note.tags || '[]');
291
+ }
292
+ catch {
293
+ tags = [];
294
+ }
295
+ return {
296
+ path: note.path,
297
+ title: note.title ?? '',
298
+ tags,
299
+ score: 1 / (1 + Math.abs(depth)),
300
+ depth,
301
+ snippet,
302
+ links: [],
303
+ backlinks: [],
304
+ scores: { semantic: null, bm25: null, fuzzy_title: null },
305
+ };
306
+ };
307
+ // Source note at depth 0
308
+ const source = makeResult(sourcePath, 0, '');
309
+ if (!source)
310
+ return [];
311
+ results.push(source);
312
+ // Forward BFS — follow outgoing links (+depth)
313
+ if (direction === 'outgoing' || direction === 'both') {
314
+ const visitedFwd = new Set([sourcePath]);
315
+ let frontier = [sourcePath];
316
+ for (let d = 1; d <= maxDepth; d++) {
317
+ const next = [];
318
+ for (const parentPath of frontier) {
319
+ const links = db
320
+ .prepare('SELECT to_path FROM links WHERE from_path = ?')
321
+ .all(parentPath);
322
+ for (const { to_path } of links) {
323
+ if (!visitedFwd.has(to_path)) {
324
+ visitedFwd.add(to_path);
325
+ const snippet = getLinkContext(parentPath, to_path, snippetLength);
326
+ const r = makeResult(to_path, d, snippet);
327
+ if (r)
328
+ results.push(r);
329
+ next.push(to_path);
330
+ }
331
+ }
332
+ }
333
+ frontier = next;
334
+ if (frontier.length === 0)
335
+ break;
336
+ }
337
+ }
338
+ // Backward BFS — follow backlinks (-depth)
339
+ if (direction === 'backlinks' || direction === 'both') {
340
+ const visitedBwd = new Set([sourcePath]);
341
+ let frontier = [sourcePath];
342
+ for (let d = 1; d <= maxDepth; d++) {
343
+ const next = [];
344
+ for (const parentPath of frontier) {
345
+ const backlinks = db
346
+ .prepare('SELECT from_path FROM links WHERE to_path = ?')
347
+ .all(parentPath);
348
+ for (const { from_path } of backlinks) {
349
+ if (!visitedBwd.has(from_path)) {
350
+ visitedBwd.add(from_path);
351
+ const snippet = getLinkContext(from_path, parentPath, snippetLength);
352
+ const r = makeResult(from_path, -d, snippet);
353
+ if (r)
354
+ results.push(r);
355
+ next.push(from_path);
356
+ }
357
+ }
358
+ }
359
+ frontier = next;
360
+ if (frontier.length === 0)
361
+ break;
362
+ }
363
+ }
364
+ // Sort: -N ... -1, 0, +1 ... +N
365
+ results.sort((a, b) => (a.depth ?? 0) - (b.depth ?? 0));
366
+ // Populate links/backlinks for all results
367
+ const paths = results.map(r => r.path);
368
+ const { links, backlinks } = getLinksForPaths(paths);
369
+ for (const r of results) {
370
+ r.links = links.get(r.path) ?? [];
371
+ r.backlinks = backlinks.get(r.path) ?? [];
372
+ }
373
+ return results;
190
374
  }
191
375
  // ─── LRU cache ───────────────────────────────────────────
192
376
  // Avoids redundant searches when the same query is repeated (common in MCP usage).
@@ -215,17 +399,60 @@ class LRUCache {
215
399
  }
216
400
  const searchCache = new LRUCache(20);
217
401
  function cacheKey(input, options) {
218
- return `${input}\0${options.mode ?? ''}\0${options.scope ?? ''}\0${options.limit ?? ''}\0${options.threshold ?? ''}\0${options.tag ?? ''}`;
402
+ const scopeStr = Array.isArray(options.scope)
403
+ ? options.scope.join(',')
404
+ : (options.scope ?? '');
405
+ const tagStr = Array.isArray(options.tag)
406
+ ? options.tag.join(',')
407
+ : (options.tag ?? '');
408
+ return `${input}\0${options.mode ?? ''}\0${scopeStr}\0${options.limit ?? ''}\0${options.threshold ?? ''}\0${tagStr}\0${options.snippetLength ?? ''}\0${options.notePath ?? ''}`;
219
409
  }
220
410
  export async function search(input, options = {}) {
221
411
  const mode = options.mode ?? 'hybrid';
222
412
  const limit = options.limit ?? 10;
223
413
  const threshold = options.threshold ?? 0.0;
224
- const isPathLookup = input.includes('/') || input.endsWith('.md');
414
+ const snippetLength = options.snippetLength ?? 300;
415
+ // Explicit notePath overrides heuristic; legacy: detect by shape of input string
416
+ const isPathLookup = options.notePath !== undefined ||
417
+ input.includes('/') ||
418
+ input.endsWith('.md');
419
+ const resolvedPath = options.notePath ?? input;
420
+ // Related mode: graph traversal, skip the normal search pipeline
421
+ if (isPathLookup && options.related) {
422
+ const maxDepth = options.depth ?? 1;
423
+ const direction = options.direction ?? 'both';
424
+ const scopeStr = Array.isArray(options.scope)
425
+ ? options.scope.join(',')
426
+ : (options.scope ?? '');
427
+ const tagStr = Array.isArray(options.tag)
428
+ ? options.tag.join(',')
429
+ : (options.tag ?? '');
430
+ const key = `related\0${resolvedPath}\0${maxDepth}\0${direction}\0${snippetLength}\0${scopeStr}\0${tagStr}`;
431
+ const cached = searchCache.get(key);
432
+ if (cached)
433
+ return cached;
434
+ let related = searchRelated(resolvedPath, maxDepth, direction, snippetLength);
435
+ // Apply scope and tag filters (related bypasses the normal pipeline)
436
+ if (options.scope)
437
+ related = related.filter(r => matchesScopeFilter(r.path, options.scope));
438
+ if (options.tag &&
439
+ (!Array.isArray(options.tag) || options.tag.length > 0)) {
440
+ related = related.filter(r => matchesTagFilter(r.tags, options.tag));
441
+ }
442
+ // Snippet fallback for results with empty snippets; cap all to snippetLength
443
+ for (const r of related) {
444
+ if (!r.snippet)
445
+ r.snippet = getSnippetFallback(r.path, snippetLength);
446
+ if (r.snippet.length > snippetLength)
447
+ r.snippet = r.snippet.slice(0, snippetLength);
448
+ }
449
+ searchCache.set(key, related);
450
+ return related;
451
+ }
225
452
  // For path lookups, include mtime in cache key so stale entries auto-invalidate
226
- let key = cacheKey(input, options);
453
+ let key = cacheKey(resolvedPath, options);
227
454
  if (isPathLookup) {
228
- const note = getNoteByPath(input.normalize('NFD'));
455
+ const note = getNoteByPath(resolvedPath.normalize('NFD'));
229
456
  if (note)
230
457
  key += `\0${note.mtime}`;
231
458
  }
@@ -234,23 +461,31 @@ export async function search(input, options = {}) {
234
461
  return cached;
235
462
  let results;
236
463
  if (isPathLookup) {
237
- results = await searchSimilar(input, limit);
464
+ results = await searchSimilar(resolvedPath, limit);
238
465
  }
239
466
  else {
240
467
  results = await searchByQuery(input, mode, limit);
241
468
  }
242
469
  results = applyScope(results, options.scope);
243
470
  results = applyThreshold(results, threshold);
244
- if (options.tag)
471
+ if (options.tag && (!Array.isArray(options.tag) || options.tag.length > 0)) {
245
472
  results = applyTagFilter(results, options.tag);
473
+ }
246
474
  results = results.slice(0, limit);
247
475
  const paths = results.map(r => r.path);
248
476
  const { links, backlinks } = getLinksForPaths(paths);
249
- const final = results.map(r => ({
250
- ...toSearchResult(r),
251
- links: links.get(r.path) ?? [],
252
- backlinks: backlinks.get(r.path) ?? [],
253
- }));
477
+ const final = results.map(r => {
478
+ const sr = toSearchResult(r);
479
+ if (!sr.snippet)
480
+ sr.snippet = getSnippetFallback(sr.path, snippetLength);
481
+ if (sr.snippet.length > snippetLength)
482
+ sr.snippet = sr.snippet.slice(0, snippetLength);
483
+ return {
484
+ ...sr,
485
+ links: links.get(sr.path) ?? [],
486
+ backlinks: backlinks.get(sr.path) ?? [],
487
+ };
488
+ });
254
489
  searchCache.set(key, final);
255
490
  return final;
256
491
  }
@@ -3,9 +3,9 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
3
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
4
  import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
5
5
  import { config } from './config.js';
6
- import { openDb, initVecTable, checkModelChanged, getStats, saveConfigMeta } from './db.js';
6
+ import { checkModelChanged, getStats, initVecTable, openDb, saveConfigMeta, } from './db.js';
7
7
  import { getContextLength, getEmbeddingDim } from './embedder.js';
8
- import { startBackgroundIndexing, startWatcher, indexFile, indexVaultSync, populateMissingLinks } from './indexer.js';
8
+ import { indexFile, indexVaultSync, populateMissingLinks, startBackgroundIndexing, startWatcher, } from './indexer.js';
9
9
  import { search } from './searcher.js';
10
10
  async function main() {
11
11
  // Phase 1: open database
@@ -18,7 +18,9 @@ async function main() {
18
18
  ignorePatternsCsv: config.ignorePatterns.join(','),
19
19
  });
20
20
  // Check if model changed — wipes DB if so, forces full reindex
21
- const modelName = (config.apiKey || process.env.OPENAI_BASE_URL) ? config.apiModel : 'local:Xenova/all-MiniLM-L6-v2';
21
+ const modelName = config.apiKey || process.env.OPENAI_BASE_URL
22
+ ? config.apiModel
23
+ : 'local:Xenova/all-MiniLM-L6-v2';
22
24
  const modelChanged = checkModelChanged(modelName);
23
25
  if (modelChanged) {
24
26
  console.error('[server] embedding model changed — database cleared, full reindex will run');
@@ -35,14 +37,18 @@ async function main() {
35
37
  tools: [
36
38
  {
37
39
  name: 'search',
38
- description: 'Search the Obsidian vault. Supports hybrid, semantic, fulltext, and title modes. ' +
39
- 'Pass a path (contains / or ends with .md) to find similar notes.',
40
+ description: 'Search the Obsidian vault. Use "query" for text search or "path" to find similar notes / traverse the graph. ' +
41
+ 'Supports hybrid, semantic, fulltext, and title modes.',
40
42
  inputSchema: {
41
43
  type: 'object',
42
44
  properties: {
43
- input: {
45
+ query: {
44
46
  type: 'string',
45
- description: 'Search query or note path for similarity search',
47
+ description: 'Text search query (use this for keyword/semantic search)',
48
+ },
49
+ path: {
50
+ type: 'string',
51
+ description: 'Note path for similarity search or graph traversal, e.g. "notes/pkm/zettelkasten.md"',
46
52
  },
47
53
  mode: {
48
54
  type: 'string',
@@ -50,8 +56,11 @@ async function main() {
50
56
  description: 'Search mode (default: hybrid)',
51
57
  },
52
58
  scope: {
53
- type: 'string',
54
- description: 'Limit search to a subfolder, e.g. "notes/pkm/"',
59
+ description: 'Limit search to subfolder(s). String or array. Prefix with "-" to exclude, e.g. ["-notes/dev/"]',
60
+ oneOf: [
61
+ { type: 'string' },
62
+ { type: 'array', items: { type: 'string' } },
63
+ ],
55
64
  },
56
65
  limit: {
57
66
  type: 'number',
@@ -62,11 +71,30 @@ async function main() {
62
71
  description: 'Minimum score threshold 0..1 (default: 0)',
63
72
  },
64
73
  tag: {
74
+ description: 'Filter by tag(s). String or array. Prefix with "-" to exclude, e.g. ["-category/cs", "note/basic/primary"]',
75
+ oneOf: [
76
+ { type: 'string' },
77
+ { type: 'array', items: { type: 'string' } },
78
+ ],
79
+ },
80
+ related: {
81
+ type: 'boolean',
82
+ description: 'Graph traversal mode: find notes linked to/from the given path. Results include depth field (negative = backlink, positive = outgoing, 0 = source).',
83
+ },
84
+ depth: {
85
+ type: 'number',
86
+ description: 'Max traversal depth for related mode (default: 1)',
87
+ },
88
+ direction: {
65
89
  type: 'string',
66
- description: 'Filter results by tag, e.g. "pkm" or "note/basic/primary"',
90
+ enum: ['outgoing', 'backlinks', 'both'],
91
+ description: 'Direction for related mode (default: both). "outgoing" = notes this note links to; "backlinks" = notes that link to this note.',
92
+ },
93
+ snippet_length: {
94
+ type: 'number',
95
+ description: 'Max snippet length in characters (default: 300). Controls context window for link snippets and fallback text.',
67
96
  },
68
97
  },
69
- required: ['input'],
70
98
  },
71
99
  },
72
100
  {
@@ -101,15 +129,24 @@ async function main() {
101
129
  const a = (args ?? {});
102
130
  try {
103
131
  if (name === 'search') {
104
- const results = await search(String(a.input), {
132
+ const notePath = a.path;
133
+ const inputStr = notePath ?? String(a.query ?? '');
134
+ const results = await search(inputStr, {
105
135
  mode: a.mode,
106
136
  scope: a.scope,
107
137
  limit: a.limit,
108
138
  threshold: a.threshold,
109
139
  tag: a.tag,
140
+ related: a.related,
141
+ depth: a.depth,
142
+ direction: a.direction,
143
+ snippetLength: a.snippet_length,
144
+ notePath,
110
145
  });
111
146
  return {
112
- content: [{ type: 'text', text: JSON.stringify({ results }, null, 2) }],
147
+ content: [
148
+ { type: 'text', text: JSON.stringify({ results }, null, 2) },
149
+ ],
113
150
  };
114
151
  }
115
152
  if (name === 'reindex') {
@@ -121,7 +158,18 @@ async function main() {
121
158
  ? { indexed: 1, skipped: 0, errors: [] }
122
159
  : status === 'skipped'
123
160
  ? { indexed: 0, skipped: 1, errors: [] }
124
- : { indexed: 0, skipped: 0, errors: [{ path: String(a.path), error: typeof status === 'object' ? status.error : 'indexing failed' }] };
161
+ : {
162
+ indexed: 0,
163
+ skipped: 0,
164
+ errors: [
165
+ {
166
+ path: String(a.path),
167
+ error: typeof status === 'object'
168
+ ? status.error
169
+ : 'indexing failed',
170
+ },
171
+ ],
172
+ };
125
173
  return {
126
174
  content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
127
175
  };
@@ -144,7 +192,9 @@ async function main() {
144
192
  indexed: stats.indexed,
145
193
  pending: stats.pending,
146
194
  last_indexed: stats.lastIndexed,
147
- model: config.apiKey ? config.apiModel : 'Xenova/all-MiniLM-L6-v2 (local)',
195
+ model: config.apiKey
196
+ ? config.apiModel
197
+ : 'Xenova/all-MiniLM-L6-v2 (local)',
148
198
  context_length: contextLength,
149
199
  }, null, 2),
150
200
  },
@@ -158,7 +208,12 @@ async function main() {
158
208
  }
159
209
  catch (err) {
160
210
  return {
161
- content: [{ type: 'text', text: `Error: ${err instanceof Error ? err.message : String(err)}` }],
211
+ content: [
212
+ {
213
+ type: 'text',
214
+ text: `Error: ${err instanceof Error ? err.message : String(err)}`,
215
+ },
216
+ ],
162
217
  isError: true,
163
218
  };
164
219
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "obsidian-hybrid-search",
3
- "version": "0.2.2",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "obsidian-hybrid-search": "./dist/src/cli.js",