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
use std::collections::HashSet;
use std::fs::{self};
use std::path::Path;
use terraphim_persistence::Persistable;
use terraphim_types::{Document, DocumentType, Index};
use super::IndexMiddleware;
use crate::command::ripgrep::{Data, Message, RipgrepCommand};
use crate::Result;
use cached::proc_macro::cached;
use terraphim_config::Haystack;
use tokio::fs as tfs;
/// Find the largest byte index <= `index` that is a valid UTF-8 char boundary.
/// Polyfill for str::floor_char_boundary (stable since Rust 1.91).
fn floor_char_boundary(s: &str, index: usize) -> usize {
if index >= s.len() {
return s.len();
}
let mut i = index;
while i > 0 && !s.is_char_boundary(i) {
i -= 1;
}
i
}
/// Middleware that uses ripgrep to index Markdown haystacks.
#[derive(Default)]
pub struct RipgrepIndexer {}
/// Cached wrapper that performs ripgrep indexing for a given haystack/query.
#[cached(
result = true,
size = 64,
key = "String",
convert = r#"{ format!("{}::{}::{:?}", haystack.location, needle, haystack.get_extra_parameters()) }"#
)]
async fn cached_ripgrep_index(needle: &str, haystack: &Haystack) -> Result<Index> {
let command = RipgrepCommand::default();
let haystack_path = Path::new(&haystack.location);
log::debug!(
"RipgrepIndexer::index called with needle: '{}' haystack: {:?}",
needle,
haystack_path
);
// Check if haystack path exists
if !haystack_path.exists() {
log::warn!("Haystack path does not exist: {:?}", haystack_path);
return Ok(Index::default());
}
// List files in haystack directory
if let Ok(entries) = fs::read_dir(haystack_path) {
let files: Vec<_> = entries
.filter_map(|entry| entry.ok())
.filter(|entry| entry.path().extension().is_some_and(|ext| ext == "md"))
.collect();
log::debug!(
"Found {} markdown files in haystack: {:?}",
files.len(),
files.iter().map(|e| e.path()).collect::<Vec<_>>()
);
}
// Parse extra parameters from haystack configuration
let extra_params = haystack.get_extra_parameters();
log::debug!("Haystack extra_parameters: {:?}", extra_params);
let extra_args = command.parse_extra_parameters(extra_params);
if !extra_args.is_empty() {
log::info!("🏷️ Using extra ripgrep parameters: {:?}", extra_args);
log::info!("🔍 This will modify the ripgrep command to include tag filtering");
} else {
log::debug!("No extra parameters provided for ripgrep command");
}
// Run ripgrep with extra arguments if any
let messages = if extra_args.is_empty() {
command.run(needle, haystack_path).await?
} else {
command
.run_with_extra_args(needle, haystack_path, &extra_args)
.await?
};
log::debug!("Ripgrep returned {} messages", messages.len());
// Debug: Log the first few messages to understand the JSON structure
log::debug!("RipgrepIndexer got {} messages", messages.len());
for (i, message) in messages.iter().take(3).enumerate() {
log::debug!("Message {}: {:?}", i, message);
}
let indexer = RipgrepIndexer::default();
let documents = indexer.index_inner(messages).await;
log::debug!("Index_inner created {} documents", documents.len());
Ok(documents)
}
impl IndexMiddleware for RipgrepIndexer {
/// Index the haystack using ripgrep and return an index of documents
///
/// # Errors
///
/// Returns an error if the middleware fails to index the haystack
async fn index(&self, needle: &str, haystack: &Haystack) -> Result<Index> {
cached_ripgrep_index(needle, haystack).await
}
}
impl RipgrepIndexer {
/// Normalize document ID to match persistence layer expectations
fn normalize_document_id(&self, file_path: &str) -> String {
// Create a dummy document to access the normalize_key method
let dummy_doc = Document {
id: "dummy".to_string(),
title: "dummy".to_string(),
body: "dummy".to_string(),
url: "dummy".to_string(),
description: None,
summarization: None,
stub: None,
tags: None,
rank: None,
source_haystack: None,
doc_type: DocumentType::KgEntry,
synonyms: None,
route: None,
priority: None,
};
// Create a meaningful ID from the file path
let original_id = format!("ripgrep_{}", file_path);
dummy_doc.normalize_key(&original_id)
}
/// Update the underlying Markdown file on disk with the edited document body.
///
/// The `Document.url` field is expected to hold an absolute or haystack-relative
/// path to the original file. When haystacks are marked as read-only this
/// method SHOULD NOT be called.
pub async fn update_document(&self, document: &Document) -> Result<()> {
use std::path::Path;
use tokio::fs;
let path = Path::new(&document.url);
// Ensure the parent directory exists (it should, given the document was
// indexed from this path). If not, return an IO error via ?.
if let Some(parent) = path.parent() {
if !parent.exists() {
log::warn!("Parent directory does not exist for {:?}", path);
}
}
let mut content = document.body.clone();
// Heuristically detect HTML (presence of tags). If HTML detected, convert to Markdown.
if content.contains('<') && content.contains('>') {
log::debug!("Converting HTML content to Markdown for file {:?}", path);
content = html2md::parse_html(&content);
}
log::info!("Writing updated document back to markdown file: {:?}", path);
fs::write(path, content).await?;
Ok(())
}
/// This is the inner function that indexes the documents
/// which allows us to cache requests to the index service
async fn index_inner(&self, messages: Vec<Message>) -> Index {
log::debug!("index_inner called with {} messages", messages.len());
// Cache of already processed documents
let mut index: Index = Index::default();
let mut existing_paths: HashSet<String> = HashSet::new();
let mut document = Document::default();
let mut document_count = 0;
let mut match_count = 0;
for message in messages {
match message {
Message::Begin(message) => {
document = Document::default();
document_count += 1;
let Some(path) = message.path() else {
log::warn!("Begin message without path");
continue;
};
if existing_paths.contains(&path) {
log::warn!("Skipping duplicate document: {}", path);
continue;
}
existing_paths.insert(path.clone());
document.id = self.normalize_document_id(&path);
let title = Path::new(&path)
.file_stem()
.unwrap()
.to_str()
.unwrap()
.to_string();
document.title = title;
document.url = path.clone();
log::debug!(
"Creating document {}: {} ({})",
document_count,
document.title,
document.id
);
}
Message::Match(message) => {
match_count += 1;
let Some(path) = message.path() else {
log::warn!("Match message without path");
continue;
};
log::trace!("Processing match {} for document: {}", match_count, path);
let body = match tfs::read_to_string(&path).await {
Ok(body) => {
log::trace!("Successfully read file: {} ({} bytes)", path, body.len());
body
}
Err(e) => {
log::warn!("Failed to read file: {} - {:?}", path, e);
continue;
}
};
document.body = body;
let lines = match &message.lines {
Data::Text { text } => {
log::trace!("Match text: {}", text);
text
}
_ => {
log::warn!("Match lines is not text: {:?}", message.lines);
continue;
}
};
// Only use the first match for description to avoid long concatenations
// Limit description to 200 characters for readability
// Use floor_char_boundary to safely truncate at a valid UTF-8 boundary
if document.description.is_none() {
let cleaned_lines = lines.trim();
if !cleaned_lines.is_empty() {
let description = if cleaned_lines.len() > 200 {
let safe_end = floor_char_boundary(cleaned_lines, 197);
format!("{}...", &cleaned_lines[..safe_end])
} else {
cleaned_lines.to_string()
};
document.description = Some(description);
}
}
}
Message::Context(message) => {
let document_url = document.url.clone();
let Some(path) = message.path() else {
log::warn!("Context message without path");
continue;
};
// We got a context for a different document
if document_url != *path {
log::warn!(
"Context for different document. document_url != path: {document_url:?} != {path:?}"
);
continue;
}
let lines = match &message.lines {
Data::Text { text } => text,
_ => {
log::warn!("Context lines is not text: {:?}", message.lines);
continue;
}
};
// Only use the first context for description to avoid long concatenations
// Limit description to 200 characters for readability
// Use floor_char_boundary to safely truncate at a valid UTF-8 boundary
if document.description.is_none() {
let cleaned_lines = lines.trim();
if !cleaned_lines.is_empty() {
let description = if cleaned_lines.len() > 200 {
let safe_end = floor_char_boundary(cleaned_lines, 197);
format!("{}...", &cleaned_lines[..safe_end])
} else {
cleaned_lines.to_string()
};
document.description = Some(description);
}
}
}
Message::End(_) => {
// The `End` message could be received before the `Begin`
// message causing the document to be empty
if !document.title.is_empty() {
log::debug!(
"Inserting document into index: {} ({})",
document.title,
document.id
);
index.insert(document.id.to_string(), document.clone());
} else {
log::debug!("Skipping empty document");
}
}
_ => {
log::trace!("Other message type: {:?}", message);
}
};
}
log::debug!(
"Index_inner completed: {} documents processed, {} matches found, {} documents in final index",
document_count,
match_count,
index.len()
);
index
}
}