terraphim_automata 1.19.3

Automata for searching and processing knowledge graphs
Documentation
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use std::collections::HashSet;
#[cfg(feature = "tokio-runtime")]
use std::path::Path;
use std::path::PathBuf;
#[cfg(feature = "tokio-runtime")]
use std::process::Stdio;
use std::time;
use thiserror::Error;
#[cfg(feature = "tokio-runtime")]
use tokio::io::AsyncReadExt;
#[cfg(feature = "tokio-runtime")]
use tokio::process::Command;

use cached::proc_macro::cached;
use serde::Deserialize;
use terraphim_types::{Concept, NormalizedTerm, NormalizedTermValue, Thesaurus};

/// Errors that can occur while building a thesaurus or running ripgrep.
#[derive(Error, Debug)]
pub enum BuilderError {
    #[error("IO error")]
    Io(#[from] std::io::Error),
    #[error("JSON error")]
    Json(#[from] serde_json::Error),
    #[error("Indexation error: {0}")]
    Indexation(String),
}

/// Convenience alias for `Result<T, BuilderError>`.
pub type Result<T> = std::result::Result<T, BuilderError>;

/// Compute a SHA-256 hash of all markdown files in a directory tree.
///
/// Files are processed in sorted order to ensure deterministic output.
/// The hash incorporates both the relative file path and file content,
/// so renames and edits are both detected.
///
/// Returns `Ok(None)` if the directory does not exist or contains no markdown files.
pub fn compute_kg_source_hash(dir: &std::path::Path) -> std::io::Result<Option<String>> {
    use sha2::{Digest, Sha256};
    use std::io::Read;

    if !dir.exists() {
        return Ok(None);
    }

    let mut hasher = Sha256::new();
    let mut found_any = false;

    let mut entries: Vec<_> = walkdir::WalkDir::new(dir)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.path()
                .extension()
                .map(|ext| ext.eq_ignore_ascii_case("md"))
                .unwrap_or(false)
        })
        .collect();

    entries.sort_by_key(|e| e.path().to_path_buf());

    for entry in entries {
        let path = entry.path();
        let relative = path.strip_prefix(dir).unwrap_or(path);
        hasher.update(relative.to_string_lossy().as_bytes());
        hasher.update(b"\0");

        let mut file = std::fs::File::open(path)?;
        let mut contents = Vec::new();
        file.read_to_end(&mut contents)?;
        hasher.update(&contents);
        hasher.update(b"\0");
        found_any = true;
    }

    if found_any {
        let result = format!("{:x}", hasher.finalize());
        Ok(Some(result))
    } else {
        Ok(None)
    }
}

/// A ThesaurusBuilder receives a path containing
/// resources (e.g. files) with key-value pairs and returns a `Thesaurus`
/// (a dictionary with synonyms which map to higher-level concepts)
pub trait ThesaurusBuilder {
    /// Build the thesaurus from the data source
    fn build<P: Into<PathBuf> + Send>(
        &self,
        name: String,
        haystack: P,
    ) -> impl std::future::Future<Output = Result<Thesaurus>> + Send;
}

const LOGSEQ_KEY_VALUE_DELIMITER: &str = "::";
const LOGSEQ_SYNONYMS_KEYWORD: &str = "synonyms";

#[derive(Default)]
pub struct Logseq {
    #[allow(dead_code)]
    service: LogseqService,
}

impl ThesaurusBuilder for Logseq {
    async fn build<P: Into<PathBuf> + Send>(&self, name: String, haystack: P) -> Result<Thesaurus> {
        #[cfg(feature = "tokio-runtime")]
        let haystack = haystack.into();
        #[cfg(not(feature = "tokio-runtime"))]
        let _haystack = haystack.into();
        #[cfg(feature = "tokio-runtime")]
        let messages = self
            .service
            .get_raw_messages(LOGSEQ_KEY_VALUE_DELIMITER, &haystack)
            .await?;
        #[cfg(not(feature = "tokio-runtime"))]
        let messages: Vec<Message> = Vec::new();
        #[allow(unused_mut)]
        let mut thesaurus = index_inner(name, messages);

        // Compute source hash for cache invalidation
        #[cfg(feature = "tokio-runtime")]
        match compute_kg_source_hash(&haystack) {
            Ok(Some(hash)) => {
                thesaurus.source_hash = Some(hash);
            }
            Ok(None) => {
                log::debug!(
                    "No markdown files found in {:?}, source_hash left empty",
                    haystack
                );
            }
            Err(e) => {
                log::warn!("Failed to compute source hash for {:?}: {}", haystack, e);
            }
        }

        Ok(thesaurus)
    }
}

#[allow(dead_code)]
pub struct LogseqService {
    command: String,
    default_args: Vec<String>,
}

impl Default for LogseqService {
    fn default() -> Self {
        Self {
            command: "rg".to_string(),
            default_args: ["--json", "--trim", "--ignore-case", "-tmarkdown"]
                .into_iter()
                .map(String::from)
                .collect(),
        }
    }
}

#[cfg(feature = "tokio-runtime")]
impl LogseqService {
    pub async fn get_raw_messages(&self, needle: &str, haystack: &Path) -> Result<Vec<Message>> {
        let haystack = haystack.to_string_lossy().to_string();
        log::debug!("Running logseq with needle `{needle}` and haystack `{haystack}`");
        let args: Vec<String> = vec![needle.to_string(), haystack]
            .into_iter()
            .chain(self.default_args.clone())
            .collect();
        let mut child = Command::new(&self.command)
            .args(args)
            .stdout(Stdio::piped())
            .spawn()?;
        let mut stdout = child.stdout.take().expect("Stdout is not available");
        let read = async move {
            let mut data = String::new();
            stdout.read_to_string(&mut data).await.map(|_| data)
        };
        let output = read.await?;
        json_decode(&output)
    }
}

#[cached]
fn index_inner(name: String, messages: Vec<Message>) -> Thesaurus {
    let mut thesaurus = Thesaurus::new(name);
    let mut current_concept: Option<ConceptWithDisplay> = None;
    let mut existing_paths: HashSet<PathBuf> = HashSet::new();
    for message in messages {
        match message {
            Message::Begin(message) => {
                let Some(path_str) = message.path() else {
                    continue;
                };
                let path = PathBuf::from(&path_str);
                if existing_paths.contains(&path) {
                    continue;
                }
                existing_paths.insert(path.clone());
                let concept_with_display = match concept_from_path(path) {
                    Ok(c) => c,
                    Err(e) => {
                        log::info!("Failed to get concept from path: {:?}. Skipping", e);
                        continue;
                    }
                };
                current_concept = Some(concept_with_display);
            }
            Message::Match(message) => {
                if message.path.is_none() {
                    continue;
                };
                let lines = match &message.lines {
                    Data::Text { text } => text,
                    _ => {
                        log::warn!("Error: lines is not text: {:?}", message.lines);
                        continue;
                    }
                };
                let Some((synonym_keyword, synonym)) = lines.split_once(LOGSEQ_KEY_VALUE_DELIMITER)
                else {
                    log::warn!("Error: Expected key-value pair, got {}. Skipping", lines);
                    continue;
                };
                if synonym_keyword != LOGSEQ_SYNONYMS_KEYWORD {
                    continue;
                }
                let synonyms: Vec<String> = synonym
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                let concept_with_display = match current_concept {
                    Some(ref cwd) => {
                        // Create NormalizedTerm with display_value preserving original case
                        let nterm = NormalizedTerm::new(cwd.concept.id, cwd.concept.value.clone())
                            .with_display_value(cwd.display_name.clone());
                        thesaurus.insert(cwd.concept.value.clone(), nterm.clone());
                        cwd
                    }
                    None => {
                        log::warn!("Error: No concept found. Skipping");
                        continue;
                    }
                };
                for synonym in synonyms {
                    // Synonyms also get the same display_value (the concept's original name)
                    let nterm = NormalizedTerm::new(
                        concept_with_display.concept.id,
                        concept_with_display.concept.value.clone(),
                    )
                    .with_display_value(concept_with_display.display_name.clone());
                    thesaurus.insert(NormalizedTermValue::new(synonym), nterm.clone());
                }
            }
            _ => {}
        };
    }
    thesaurus
}

/// A concept with its original display name preserved.
/// The concept value is normalized (lowercase), but display_name preserves original case.
struct ConceptWithDisplay {
    concept: Concept,
    display_name: String,
}

fn concept_from_path(path: PathBuf) -> Result<ConceptWithDisplay> {
    let stem = path.file_stem().ok_or(BuilderError::Indexation(format!(
        "No file stem in path {path:?}"
    )))?;
    let stem_name = stem.to_string_lossy().to_string();

    // Use heading from markdown directives (parsed when the file is first read).
    // Falls back to file stem if directives are unavailable for this path.
    let display_name = crate::markdown_directives::extract_heading_from_path(&path)
        .unwrap_or_else(|| stem_name.clone());

    let concept = Concept::from(stem_name);
    Ok(ConceptWithDisplay {
        concept,
        display_name,
    })
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
#[serde(tag = "type", content = "data")]
#[serde(rename_all = "snake_case")]
pub enum Message {
    Begin(Begin),
    End(End),
    Match(Match),
    Context(Context),
    Summary(Summary),
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
pub struct Begin {
    pub path: Option<Data>,
}

impl Begin {
    pub(crate) fn path(&self) -> Option<String> {
        as_path(&self.path)
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
pub struct End {
    path: Option<Data>,
    binary_offset: Option<u64>,
    stats: Stats,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
pub struct Summary {
    elapsed_total: Duration,
    stats: Stats,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
pub struct Match {
    pub path: Option<Data>,
    pub lines: Data,
    line_number: Option<u64>,
    absolute_offset: u64,
    pub submatches: Vec<SubMatch>,
}

impl Match {}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
pub struct Context {
    pub path: Option<Data>,
    pub lines: Data,
    line_number: Option<u64>,
    absolute_offset: u64,
    submatches: Vec<SubMatch>,
}

impl Context {}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
pub struct SubMatch {
    #[serde(rename = "match")]
    m: Data,
    start: usize,
    end: usize,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
#[serde(untagged)]
pub enum Data {
    Text { text: String },
    Bytes { bytes: String },
}

fn as_path(data: &Option<Data>) -> Option<String> {
    let data = match data {
        Some(data) => data,
        None => return None,
    };
    match data {
        Data::Text { text } => Some(text.clone()),
        _ => None,
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
struct Stats {
    elapsed: Duration,
    searches: u64,
    searches_with_match: u64,
    bytes_searched: u64,
    bytes_printed: u64,
    matched_lines: u64,
    matches: u64,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
struct Duration {
    #[serde(flatten)]
    duration: time::Duration,
    human: String,
}

/// Decodes a newline-delimited JSON string into a vector of `Message` values.
pub fn json_decode(jsonlines: &str) -> Result<Vec<Message>> {
    Ok(serde_json::Deserializer::from_str(jsonlines)
        .into_iter()
        .collect::<std::result::Result<Vec<Message>, serde_json::Error>>()?)
}

#[cfg(test)]
mod hash_tests {
    use crate::builder::compute_kg_source_hash;
    use std::io::Write;

    #[test]
    fn compute_hash_empty_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let result = compute_kg_source_hash(tmp.path()).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn compute_hash_detects_content_change() {
        let tmp = tempfile::tempdir().unwrap();
        let md_path = tmp.path().join("concept.md");
        {
            let mut f = std::fs::File::create(&md_path).unwrap();
            f.write_all(b"synonyms:: foo, bar").unwrap();
        }

        let hash1 = compute_kg_source_hash(tmp.path()).unwrap().unwrap();

        // Edit the file
        {
            let mut f = std::fs::File::create(&md_path).unwrap();
            f.write_all(b"synonyms:: foo, baz").unwrap();
        }

        let hash2 = compute_kg_source_hash(tmp.path()).unwrap().unwrap();
        assert_ne!(hash1, hash2, "Hash should change when file content changes");
    }

    #[test]
    fn compute_hash_detects_rename() {
        let tmp = tempfile::tempdir().unwrap();
        let md_path = tmp.path().join("concept.md");
        {
            let mut f = std::fs::File::create(&md_path).unwrap();
            f.write_all(b"synonyms:: foo, bar").unwrap();
        }

        let hash1 = compute_kg_source_hash(tmp.path()).unwrap().unwrap();

        // Rename the file
        let renamed_path = tmp.path().join("renamed.md");
        std::fs::rename(&md_path, &renamed_path).unwrap();

        let hash2 = compute_kg_source_hash(tmp.path()).unwrap().unwrap();
        assert_ne!(hash1, hash2, "Hash should change when file is renamed");
    }

    #[test]
    fn compute_hash_ignores_non_md() {
        let tmp = tempfile::tempdir().unwrap();
        {
            let mut f = std::fs::File::create(tmp.path().join("readme.txt")).unwrap();
            f.write_all(b"synonyms:: foo, bar").unwrap();
        }

        let result = compute_kg_source_hash(tmp.path()).unwrap();
        assert!(result.is_none(), "Non-markdown files should be ignored");
    }

    #[test]
    fn compute_hash_stable_across_runs() {
        let tmp = tempfile::tempdir().unwrap();
        let md_path = tmp.path().join("concept.md");
        {
            let mut f = std::fs::File::create(&md_path).unwrap();
            f.write_all(b"synonyms:: foo, bar").unwrap();
        }

        let hash1 = compute_kg_source_hash(tmp.path()).unwrap().unwrap();
        let hash2 = compute_kg_source_hash(tmp.path()).unwrap().unwrap();
        assert_eq!(
            hash1, hash2,
            "Hash should be stable when files don't change"
        );
    }
}