obsidian-hybrid-search 0.2.2 → 0.3.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
@@ -72,9 +72,14 @@ obsidian-hybrid-search "daily review" --scope notes/periodic/
72
72
  obsidian-hybrid-search "productivity" --tag pkm
73
73
  obsidian-hybrid-search "machine learning" --tag note/basic/primary
74
74
 
75
- # Find notes similar to a specific note
75
+ # Find semantically similar notes (default for path input)
76
76
  obsidian-hybrid-search "notes/pkm/zettelkasten.md"
77
77
 
78
+ # Graph traversal: show notes linked to/from this note
79
+ # Results show depth: -1/-2 = backlinks, 0 = source, +1/+2 = outgoing links
80
+ obsidian-hybrid-search "notes/pkm/zettelkasten.md" --related
81
+ obsidian-hybrid-search "notes/pkm/zettelkasten.md" --related --depth 2
82
+
78
83
  # JSON output (for scripting)
79
84
  obsidian-hybrid-search "spaced repetition" --json
80
85
 
@@ -162,7 +167,7 @@ The server exposes three tools:
162
167
 
163
168
  | Tool | Description |
164
169
  |------|-------------|
165
- | `search` | Search the vault with optional `mode`, `scope`, `limit`, `threshold`, `tag` |
170
+ | `search` | Search the vault with optional `mode`, `scope`, `limit`, `threshold`, `tag`, `related`, `depth` |
166
171
  | `reindex` | Reindex the vault or a specific file |
167
172
  | `status` | Show total notes, indexed count, last indexed time |
168
173
 
package/dist/src/cli.js CHANGED
@@ -9,6 +9,14 @@ import { getContextLength, getEmbeddingDim } from './embedder.js';
9
9
  import { search } from './searcher.js';
10
10
  import { indexVaultSync, indexFile } from './indexer.js';
11
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,
@@ -95,6 +103,8 @@ program
95
103
  .option('--limit <n>', 'Maximum results', '10')
96
104
  .option('--threshold <n>', 'Minimum score threshold 0..1', '0')
97
105
  .option('--tag <tag>', 'Filter by tag, e.g. pkm or note/basic/primary')
106
+ .option('--related', 'Graph traversal: show notes linked to/from this note (path input only)')
107
+ .option('--depth <n>', 'Traversal depth for --related mode', '1')
98
108
  .option('--json', 'Output as JSON')
99
109
  .action(async (query, opts) => {
100
110
  if (!query) {
@@ -108,6 +118,8 @@ program
108
118
  limit: parseInt(opts.limit),
109
119
  threshold: parseFloat(opts.threshold),
110
120
  tag: opts.tag,
121
+ related: opts.related ?? false,
122
+ depth: parseInt(opts.depth),
111
123
  });
112
124
  if (opts.json) {
113
125
  console.log(JSON.stringify(results, null, 2));
@@ -117,6 +129,25 @@ program
117
129
  console.log('No results found.');
118
130
  return;
119
131
  }
132
+ // Related mode: depth-centered table
133
+ if (opts.related) {
134
+ const table = new Table({
135
+ head: ['DEPTH', 'PATH', 'SNIPPET'],
136
+ colWidths: [7, 45, 55],
137
+ wordWrap: true,
138
+ });
139
+ for (const r of results) {
140
+ const d = r.depth ?? 0;
141
+ const depthStr = d === 0 ? ' 0 ●' : d > 0 ? `+${d}` : `${d}`;
142
+ const context = r.snippet
143
+ ? truncateAtWord(r.snippet.replace(/\t/g, ' ').replace(/ {2,}/g, ' '), 160)
144
+ : r.title;
145
+ table.push([depthStr, r.path, context]);
146
+ }
147
+ console.log(table.toString());
148
+ return;
149
+ }
150
+ // Normal search table
120
151
  const hasSnippets = results.some(r => (r.snippet ?? '').trim().length > 0);
121
152
  const table = hasSnippets
122
153
  ? new Table({ head: ['SCORE', 'PATH', 'SNIPPET'], colWidths: [7, 45, 60], wordWrap: true })
@@ -1,3 +1,4 @@
1
+ import path from 'node:path';
1
2
  import { getDb, hasVecTable, getNoteByPath, getLinksForPaths } from './db.js';
2
3
  import { embed } from './embedder.js';
3
4
  function applyScope(results, scope) {
@@ -188,6 +189,133 @@ function rrfFusion(lists, k = 60) {
188
189
  .sort((a, b) => b.rrfScore - a.rrfScore)
189
190
  .map(({ rrfScore, result }) => ({ ...result, score: rrfScore / maxPossibleScore }));
190
191
  }
192
+ // ─── Graph traversal ─────────────────────────────────────
193
+ /**
194
+ * Extract the sentence/line context around a wikilink [[target]] inside a note.
195
+ * contentNotePath: the note whose content we search in
196
+ * linkedNotePath: the target note we're looking for a link to
197
+ */
198
+ function getLinkContext(contentNotePath, linkedNotePath) {
199
+ const db = getDb();
200
+ const note = db.prepare('SELECT content FROM notes WHERE path = ?')
201
+ .get(contentNotePath);
202
+ if (!note?.content)
203
+ return '';
204
+ const basename = path.basename(linkedNotePath, '.md');
205
+ // Match [[basename]], [[basename|alias]], [[basename#heading]], [[folder/basename]], etc.
206
+ const escaped = basename.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
207
+ const regex = new RegExp(`\\[\\[(?:[^\\]|#]*\\/)?${escaped}(?:[|#][^\\]]*)?\\]\\]`, 'i');
208
+ const match = regex.exec(note.content);
209
+ if (!match)
210
+ return '';
211
+ const window = 100;
212
+ let start = Math.max(0, match.index - window);
213
+ let end = Math.min(note.content.length, match.index + match[0].length + window);
214
+ // Snap to word boundaries so we don't cut mid-word
215
+ if (start > 0) {
216
+ while (start < match.index && !/\s/.test(note.content[start]))
217
+ start++;
218
+ }
219
+ if (end < note.content.length) {
220
+ while (end > match.index + match[0].length && !/\s/.test(note.content[end - 1]))
221
+ end--;
222
+ }
223
+ const prefix = start > 0 ? '...' : '';
224
+ const suffix = end < note.content.length ? '...' : '';
225
+ // Preserve newlines so CLI can strip line-based markdown (headings, blockquotes)
226
+ return (prefix + note.content.slice(start, end).trim() + suffix);
227
+ }
228
+ function searchRelated(notePath, maxDepth) {
229
+ const db = getDb();
230
+ const sourcePath = notePath.normalize('NFD');
231
+ const results = [];
232
+ const makeResult = (notePth, depth, snippet) => {
233
+ const note = db.prepare('SELECT path, title, tags FROM notes WHERE path = ?').get(notePth);
234
+ if (!note)
235
+ return null;
236
+ let tags = [];
237
+ try {
238
+ tags = JSON.parse(note.tags || '[]');
239
+ }
240
+ catch {
241
+ tags = [];
242
+ }
243
+ return {
244
+ path: note.path,
245
+ title: note.title ?? '',
246
+ tags,
247
+ score: 0,
248
+ depth,
249
+ snippet,
250
+ links: [],
251
+ backlinks: [],
252
+ scores: { semantic: null, bm25: null, fuzzy_title: null },
253
+ };
254
+ };
255
+ // Source note at depth 0 — no context
256
+ const source = makeResult(sourcePath, 0, '');
257
+ if (!source)
258
+ return [];
259
+ results.push(source);
260
+ // Forward BFS — follow outgoing links (+depth)
261
+ // Context: text in the parent note where [[child]] appears
262
+ const visitedFwd = new Set([sourcePath]);
263
+ let frontier = [sourcePath];
264
+ for (let d = 1; d <= maxDepth; d++) {
265
+ const next = [];
266
+ for (const parentPath of frontier) {
267
+ const links = db.prepare('SELECT to_path FROM links WHERE from_path = ?')
268
+ .all(parentPath);
269
+ for (const { to_path } of links) {
270
+ if (!visitedFwd.has(to_path)) {
271
+ visitedFwd.add(to_path);
272
+ const snippet = getLinkContext(parentPath, to_path);
273
+ const r = makeResult(to_path, d, snippet);
274
+ if (r)
275
+ results.push(r);
276
+ next.push(to_path);
277
+ }
278
+ }
279
+ }
280
+ frontier = next;
281
+ if (frontier.length === 0)
282
+ break;
283
+ }
284
+ // Backward BFS — follow backlinks (-depth)
285
+ // Context: text in the child note where [[parent]] appears
286
+ const visitedBwd = new Set([sourcePath]);
287
+ frontier = [sourcePath];
288
+ for (let d = 1; d <= maxDepth; d++) {
289
+ const next = [];
290
+ for (const parentPath of frontier) {
291
+ const backlinks = db.prepare('SELECT from_path FROM links WHERE to_path = ?')
292
+ .all(parentPath);
293
+ for (const { from_path } of backlinks) {
294
+ if (!visitedBwd.has(from_path)) {
295
+ visitedBwd.add(from_path);
296
+ const snippet = getLinkContext(from_path, parentPath);
297
+ const r = makeResult(from_path, -d, snippet);
298
+ if (r)
299
+ results.push(r);
300
+ next.push(from_path);
301
+ }
302
+ }
303
+ }
304
+ frontier = next;
305
+ if (frontier.length === 0)
306
+ break;
307
+ }
308
+ // Sort: -N ... -1, 0, +1 ... +N
309
+ results.sort((a, b) => (a.depth ?? 0) - (b.depth ?? 0));
310
+ // Populate links/backlinks for all results
311
+ const paths = results.map(r => r.path);
312
+ const { links, backlinks } = getLinksForPaths(paths);
313
+ for (const r of results) {
314
+ r.links = links.get(r.path) ?? [];
315
+ r.backlinks = backlinks.get(r.path) ?? [];
316
+ }
317
+ return results;
318
+ }
191
319
  // ─── LRU cache ───────────────────────────────────────────
192
320
  // Avoids redundant searches when the same query is repeated (common in MCP usage).
193
321
  // Path-based lookups are cached by path:mtime so stale entries auto-invalidate.
@@ -222,6 +350,17 @@ export async function search(input, options = {}) {
222
350
  const limit = options.limit ?? 10;
223
351
  const threshold = options.threshold ?? 0.0;
224
352
  const isPathLookup = input.includes('/') || input.endsWith('.md');
353
+ // Related mode: graph traversal, skip the normal search pipeline
354
+ if (isPathLookup && options.related) {
355
+ const maxDepth = options.depth ?? 1;
356
+ const key = `related\0${input}\0${maxDepth}`;
357
+ const cached = searchCache.get(key);
358
+ if (cached)
359
+ return cached;
360
+ const related = searchRelated(input, maxDepth);
361
+ searchCache.set(key, related);
362
+ return related;
363
+ }
225
364
  // For path lookups, include mtime in cache key so stale entries auto-invalidate
226
365
  let key = cacheKey(input, options);
227
366
  if (isPathLookup) {
@@ -65,6 +65,14 @@ async function main() {
65
65
  type: 'string',
66
66
  description: 'Filter results by tag, e.g. "pkm" or "note/basic/primary"',
67
67
  },
68
+ related: {
69
+ type: 'boolean',
70
+ description: 'Graph traversal mode: find notes linked to/from the given note path. Results include depth field (negative = backlink direction, positive = outgoing link direction, 0 = source note).',
71
+ },
72
+ depth: {
73
+ type: 'number',
74
+ description: 'Max traversal depth for related mode (default: 1)',
75
+ },
68
76
  },
69
77
  required: ['input'],
70
78
  },
@@ -107,6 +115,8 @@ async function main() {
107
115
  limit: a.limit,
108
116
  threshold: a.threshold,
109
117
  tag: a.tag,
118
+ related: a.related,
119
+ depth: a.depth,
110
120
  });
111
121
  return {
112
122
  content: [{ type: 'text', text: JSON.stringify({ results }, null, 2) }],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "obsidian-hybrid-search",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "obsidian-hybrid-search": "./dist/src/cli.js",