relate.mjs
54 lines 1.8 KB
Raw
sha256:8915fe406161f95c1681f9469375e7bae5b28c884f00bedbdef65e4b0cd0738d docs(flow): commit FLOW-V0-SPEC.md hygiene for 7A-INT merge Human 21 hours ago
1 /**
2 * Semantic "related notes" for a path (Issue #1 Phase C1).
3 */
4
5 import { loadConfig } from './config.mjs';
6 import { readNote, normalizeSlug } from './vault.mjs';
7 import { embed } from './embedding.mjs';
8 import { createVectorStore } from './vector-store.mjs';
9
10 const BODY_SLICE = 12000;
11
12 /**
13 * @param {string} vaultRelativePath
14 * @param {{ limit?: number, project?: string }} options
15 * @returns {Promise<{ path: string, related: { path: string, score: number, title: string|null, snippet: string }[] }>}
16 */
17 export async function runRelate(vaultRelativePath, options = {}) {
18 const config = loadConfig();
19 const note = readNote(config.vault_path, vaultRelativePath);
20 const text = `${note.frontmatter?.title ? String(note.frontmatter.title) + '\n' : ''}${note.body || ''}`.slice(0, BODY_SLICE);
21 const [vector] = await embed([text], config.embedding || {}, { voyageInputType: 'document' });
22 if (!vector?.length) throw new Error('Embedding failed for relate.');
23
24 const store = await createVectorStore(config);
25 const want = Math.max(1, Math.min(options.limit ?? 5, 20));
26 const hits = await store.search(vector, {
27 limit: Math.min(want + 15, 50),
28 project: options.project != null ? normalizeSlug(String(options.project)) : undefined,
29 });
30
31 const src = note.path.replace(/\\/g, '/');
32 const seen = new Set();
33 const related = [];
34 for (const h of hits) {
35 const p = (h.path || '').replace(/\\/g, '/');
36 if (!p || p === src) continue;
37 if (seen.has(p)) continue;
38 seen.add(p);
39 let title = null;
40 try {
41 const n = readNote(config.vault_path, p);
42 title = n.frontmatter?.title ?? null;
43 } catch (_) {}
44 related.push({
45 path: p,
46 score: h.score,
47 title,
48 snippet: (h.text || '').slice(0, 200).replace(/\s+/g, ' ').trim(),
49 });
50 if (related.length >= want) break;
51 }
52
53 return { path: src, related };
54 }
File History 1 commit
sha256:8915fe406161f95c1681f9469375e7bae5b28c884f00bedbdef65e4b0cd0738d docs(flow): commit FLOW-V0-SPEC.md hygiene for 7A-INT merge Human 21 hours ago