-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathgraph.rs
More file actions
426 lines (382 loc) · 13.2 KB
/
Copy pathgraph.rs
File metadata and controls
426 lines (382 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use std::collections::{HashMap, HashSet, hash_map::Entry};
use anyhow::Result;
use crate::fusion::RankedResult;
use crate::store::Store;
/// Extract unique wikilink targets from text.
/// Handles [[Target]], [[Target|Display]], [[Target#Heading]].
/// Skips embeds (![[...]]).
pub fn extract_wikilink_targets(text: &str) -> Vec<String> {
let bytes = text.as_bytes();
let mut targets = Vec::new();
let mut seen = HashSet::new();
let mut i = 0;
while i + 1 < bytes.len() {
if bytes[i] == b'[' && bytes[i + 1] == b'[' {
// Check for embed prefix (! before [[)
let is_embed = i > 0 && bytes[i - 1] == b'!';
if let Some(rest) = text.get(i + 2..)
&& let Some(close) = rest.find("]]")
{
let inner = &rest[..close];
if !is_embed && !inner.is_empty() && !inner.contains('\n') {
// Strip heading: [[Note#Section]] → "Note"
let target = inner.split('#').next().unwrap_or(inner);
// Strip display: [[Note|Display]] → "Note"
let target = target.split('|').next().unwrap_or(target);
let target = target.trim().to_string();
if !target.is_empty() && seen.insert(target.clone()) {
targets.push(target);
}
}
i += 2 + close + 2;
continue;
}
}
i += 1;
}
targets
}
/// Extract query terms for relevance filtering.
/// Splits on whitespace, lowercases, drops terms shorter than 3 chars.
pub fn extract_query_terms(query: &str) -> Vec<String> {
query
.split_whitespace()
.map(|t| t.to_lowercase())
.filter(|t| t.len() >= 3)
.collect()
}
/// Expand search results by following graph connections.
/// Seeds are the top results from semantic + FTS lanes.
/// Returns expanded results suitable for RRF fusion.
pub fn graph_expand(
store: &Store,
seeds: &[RankedResult],
query: &str,
max_hops: usize,
max_expansions: usize,
) -> Result<Vec<RankedResult>> {
let query_terms = extract_query_terms(query);
let seed_ids: HashSet<i64> = seeds.iter().map(|s| s.file_id).collect();
// Track best score per expanded file (multi-parent merge: take highest)
// (file_id) → (best_score, hop_depth, seed_file_path)
let mut expansions: HashMap<i64, (f64, usize, String)> = HashMap::new();
for seed in seeds {
let neighbors = store.get_neighbors(seed.file_id, max_hops)?;
for (neighbor_id, hop) in neighbors {
if seed_ids.contains(&neighbor_id) {
continue;
}
let decay = match hop {
1 => 0.8,
2 => 0.5,
_ => 0.3,
};
let mut expansion_score = seed.score * decay;
// Relevance filter: must match a query term via FTS or share tags
let term_match = query_terms
.iter()
.any(|t| store.file_contains_term(neighbor_id, t).unwrap_or(false));
if !term_match {
let shared = store
.get_shared_tags_files(neighbor_id, 100)
.unwrap_or_default();
if shared.contains(&seed.file_id) {
expansion_score *= 0.7;
} else {
continue; // tangential — skip
}
}
// Multi-parent merge: keep highest score
match expansions.entry(neighbor_id) {
Entry::Occupied(mut e) => {
if expansion_score > e.get().0 {
e.insert((expansion_score, hop, seed.file_path.clone()));
}
}
Entry::Vacant(e) => {
e.insert((expansion_score, hop, seed.file_path.clone()));
}
}
}
}
// Sort by score descending, cap at max_expansions
let mut results: Vec<(i64, f64, usize, String)> = expansions
.into_iter()
.map(|(fid, (score, hop, seed))| (fid, score, hop, seed))
.collect();
results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
results.truncate(max_expansions);
// Convert to RankedResult
let mut ranked = Vec::new();
for (file_id, score, _hop, _seed) in results {
let file = store.get_file_by_id(file_id)?;
let (file_path, docid) = match file {
Some(f) => (f.path, f.docid),
None => continue,
};
let (heading, snippet) = store
.get_best_chunk_for_file(file_id)?
.unwrap_or_else(|| (String::new(), String::new()));
let heading = if heading.is_empty() {
None
} else {
Some(heading)
};
ranked.push(RankedResult {
file_path,
file_id,
score,
heading,
snippet,
docid,
});
}
Ok(ranked)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::docid::generate_docid;
use crate::fusion::RankedResult;
use crate::store::Store;
#[test]
fn test_extract_wikilink_targets() {
let text =
"See [[Note One]] and [[Note Two|display]] for details. Also [[Note One]] again.";
let targets = extract_wikilink_targets(text);
assert!(targets.contains(&"Note One".to_string()));
assert!(targets.contains(&"Note Two".to_string()));
assert_eq!(targets.len(), 2); // deduplicated
}
#[test]
fn test_extract_wikilinks_with_headings() {
let text = "Link to [[Note#Section]] here.";
let targets = extract_wikilink_targets(text);
assert_eq!(targets, vec!["Note"]);
}
#[test]
fn test_extract_wikilinks_empty() {
assert!(extract_wikilink_targets("no links here").is_empty());
assert!(extract_wikilink_targets("").is_empty());
}
#[test]
fn test_extract_wikilinks_skip_embeds() {
let text = "![[embedded image.png]] and [[real link]]";
let targets = extract_wikilink_targets(text);
assert_eq!(targets, vec!["real link"]);
}
#[test]
fn test_extract_wikilinks_heading_and_display() {
let text = "[[Note#Section|Custom Display]]";
let targets = extract_wikilink_targets(text);
assert_eq!(targets, vec!["Note"]); // strip both heading and display
}
#[test]
fn test_extract_query_terms() {
let terms = extract_query_terms("BRE-2579 delivery date");
assert_eq!(terms, vec!["bre-2579", "delivery", "date"]);
}
#[test]
fn test_extract_query_terms_short_words_dropped() {
let terms = extract_query_terms("a is the big query");
assert_eq!(terms, vec!["the", "big", "query"]);
}
#[test]
fn test_graph_expand_basic() {
let store = Store::open_memory().unwrap();
let f1 = store
.insert_file(
"seed.md",
"h1",
100,
&["rust".into()],
&generate_docid("seed.md"),
None,
)
.unwrap();
let f2 = store
.insert_file(
"linked.md",
"h2",
100,
&["rust".into()],
&generate_docid("linked.md"),
None,
)
.unwrap();
let _f3 = store
.insert_file(
"unlinked.md",
"h3",
100,
&[],
&generate_docid("unlinked.md"),
None,
)
.unwrap();
store.insert_edge(f1, f2, "wikilink").unwrap();
store
.insert_chunk(f2, "## Linked", "Linked content about delivery", 10, 20)
.unwrap();
store
.insert_fts_chunk(f2, 0, "Linked content about delivery")
.unwrap();
let seeds = vec![RankedResult {
file_path: "seed.md".into(),
file_id: f1,
score: 0.85,
heading: None,
snippet: "Seed".into(),
docid: None,
}];
let expanded = graph_expand(&store, &seeds, "delivery", 2, 20).unwrap();
assert_eq!(expanded.len(), 1);
assert_eq!(expanded[0].file_path, "linked.md");
assert!(expanded[0].score > 0.0 && expanded[0].score < 0.85);
}
#[test]
fn test_graph_expand_skips_seeds() {
let store = Store::open_memory().unwrap();
let f1 = store
.insert_file("a.md", "h1", 100, &[], &generate_docid("a.md"), None)
.unwrap();
let f2 = store
.insert_file("b.md", "h2", 100, &[], &generate_docid("b.md"), None)
.unwrap();
store.insert_edge(f1, f2, "wikilink").unwrap();
store.insert_chunk(f2, "## B", "Content B", 10, 20).unwrap();
store.insert_fts_chunk(f2, 0, "Content B").unwrap();
let seeds = vec![
RankedResult {
file_path: "a.md".into(),
file_id: f1,
score: 0.9,
heading: None,
snippet: "A".into(),
docid: None,
},
RankedResult {
file_path: "b.md".into(),
file_id: f2,
score: 0.8,
heading: None,
snippet: "B".into(),
docid: None,
},
];
let expanded = graph_expand(&store, &seeds, "content", 2, 20).unwrap();
assert!(expanded.is_empty());
}
#[test]
fn test_graph_expand_multi_parent_takes_highest() {
let store = Store::open_memory().unwrap();
let f1 = store
.insert_file("a.md", "h1", 100, &[], &generate_docid("a.md"), None)
.unwrap();
let f2 = store
.insert_file("b.md", "h2", 100, &[], &generate_docid("b.md"), None)
.unwrap();
let f3 = store
.insert_file(
"shared.md",
"h3",
100,
&[],
&generate_docid("shared.md"),
None,
)
.unwrap();
store.insert_edge(f1, f3, "wikilink").unwrap();
store.insert_edge(f2, f3, "wikilink").unwrap();
store
.insert_chunk(f3, "## Shared", "Shared topic content", 10, 20)
.unwrap();
store
.insert_fts_chunk(f3, 0, "Shared topic content")
.unwrap();
let seeds = vec![
RankedResult {
file_path: "a.md".into(),
file_id: f1,
score: 0.9,
heading: None,
snippet: "A".into(),
docid: None,
},
RankedResult {
file_path: "b.md".into(),
file_id: f2,
score: 0.5,
heading: None,
snippet: "B".into(),
docid: None,
},
];
let expanded = graph_expand(&store, &seeds, "topic", 1, 20).unwrap();
assert_eq!(expanded.len(), 1);
assert_eq!(expanded[0].file_path, "shared.md");
// Should use highest parent: 0.9 * 0.8 = 0.72
assert!((expanded[0].score - 0.72).abs() < 0.01);
}
#[test]
fn test_graph_expand_empty_graph() {
let store = Store::open_memory().unwrap();
let f1 = store
.insert_file("a.md", "h1", 100, &[], "aaa111", None)
.unwrap();
let seeds = vec![RankedResult {
file_path: "a.md".into(),
file_id: f1,
score: 0.9,
heading: None,
snippet: "A".into(),
docid: None,
}];
let expanded = graph_expand(&store, &seeds, "query", 2, 20).unwrap();
assert!(expanded.is_empty());
}
#[test]
fn test_graph_expand_tag_fallback() {
let store = Store::open_memory().unwrap();
let f1 = store
.insert_file(
"seed.md",
"h1",
100,
&["rust".into(), "cli".into()],
&generate_docid("seed.md"),
None,
)
.unwrap();
let f2 = store
.insert_file(
"linked.md",
"h2",
100,
&["rust".into()],
&generate_docid("linked.md"),
None,
)
.unwrap();
store.insert_edge(f1, f2, "wikilink").unwrap();
store
.insert_chunk(f2, "## Linked", "Unrelated content", 10, 20)
.unwrap();
store
.insert_fts_chunk(f2, 0, "Unrelated content here")
.unwrap();
let seeds = vec![RankedResult {
file_path: "seed.md".into(),
file_id: f1,
score: 0.85,
heading: None,
snippet: "Seed".into(),
docid: None,
}];
// Query doesn't match FTS, but shared tag "rust" should keep it (with 0.7x penalty)
let expanded = graph_expand(&store, &seeds, "nonexistent query term", 2, 20).unwrap();
assert_eq!(expanded.len(), 1);
// Score: 0.85 * 0.8 * 0.7 = 0.476
assert!((expanded[0].score - 0.476).abs() < 0.01);
}
}