axiomsync 1.0.0

Core data-processing engine for AxiomSync local retrieval runtime.
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use std::fs;
use std::path::{Component, Path, PathBuf};

use chrono::{DateTime, Utc};
use globset::{Glob, GlobSet, GlobSetBuilder};
use serde::{Deserialize, Serialize};
use walkdir::WalkDir;

use crate::error::{AxiomError, Result};
use crate::fs::LocalContextFs;
use crate::models::AddResourceIngestOptions;
use crate::parse::ParserRegistry;
use crate::uri::{AxiomUri, Scope};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngestManifest {
    pub ingest_id: String,
    pub source: String,
    pub created_at: DateTime<Utc>,
    pub files: Vec<IngestFileInfo>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IngestFileInfo {
    pub relative_path: String,
    pub parser: String,
    pub is_text: bool,
    pub bytes: u64,
    pub line_count: usize,
    pub content_hash: String,
    pub title: Option<String>,
    pub preview: String,
    pub tags: Vec<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IngestFinalizeMode {
    ReplaceTarget,
    MergeIntoTarget,
}

#[derive(Clone)]
pub struct IngestManager {
    fs: LocalContextFs,
    parser: ParserRegistry,
}

impl std::fmt::Debug for IngestManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IngestManager").finish_non_exhaustive()
    }
}

impl IngestManager {
    #[must_use]
    pub const fn new(fs: LocalContextFs, parser: ParserRegistry) -> Self {
        Self { fs, parser }
    }

    pub fn start_session(&self) -> Result<IngestSession> {
        let ingest_id = uuid::Uuid::new_v4().to_string();
        let root_uri = AxiomUri::root(Scope::Temp)
            .join("ingest")?
            .join(&ingest_id)?;
        let staged_uri = root_uri.join("staged")?;
        self.fs.create_dir_all(&staged_uri, true)?;

        Ok(IngestSession {
            fs: self.fs.clone(),
            parser: self.parser.clone(),
            ingest_id,
            root_uri,
            staged_uri,
            finalized: false,
        })
    }
}

pub struct IngestSession {
    fs: LocalContextFs,
    parser: ParserRegistry,
    ingest_id: String,
    root_uri: AxiomUri,
    staged_uri: AxiomUri,
    finalized: bool,
}

impl std::fmt::Debug for IngestSession {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IngestSession")
            .field("ingest_id", &self.ingest_id)
            .field("root_uri", &self.root_uri)
            .field("staged_uri", &self.staged_uri)
            .finish_non_exhaustive()
    }
}

impl IngestSession {
    #[must_use]
    pub fn ingest_id(&self) -> &str {
        &self.ingest_id
    }

    pub fn stage_local_path(&mut self, source: &Path) -> Result<()> {
        self.stage_local_path_with_options(source, &AddResourceIngestOptions::default())
    }

    pub fn stage_local_path_with_options(
        &mut self,
        source: &Path,
        options: &AddResourceIngestOptions,
    ) -> Result<()> {
        let staged_path = self.fs.resolve_uri(&self.staged_uri);
        if source.is_dir() && options == &AddResourceIngestOptions::default() {
            return copy_dir_contents(source, &staged_path);
        }
        let filter = IngestPathFilter::new(options)?;
        if source.is_file() {
            let name = source
                .file_name()
                .and_then(|s| s.to_str())
                .ok_or_else(|| AxiomError::Validation("invalid source file name".to_string()))?;
            if !filter.allows_file(Path::new(name)) {
                return Err(AxiomError::Validation(format!(
                    "source file excluded by ingest options: {name}"
                )));
            }
            fs::copy(source, staged_path.join(name))?;
            return Ok(());
        }

        let copied = copy_dir_contents_filtered(source, &staged_path, &filter)?;
        if copied == 0 {
            return Err(AxiomError::Validation(
                "ingest filter excluded all files in source directory".to_string(),
            ));
        }
        Ok(())
    }

    pub fn stage_text(&mut self, file_name: &str, text: &str) -> Result<()> {
        if file_name.trim().is_empty() {
            return Err(AxiomError::Validation(
                "stage_text file_name must not be empty".to_string(),
            ));
        }
        if Path::new(file_name).is_absolute() {
            return Err(AxiomError::PathTraversal(file_name.to_string()));
        }
        let target_uri = self.staged_uri.join(file_name)?;
        if target_uri == self.staged_uri {
            return Err(AxiomError::Validation(
                "stage_text file_name must include at least one path segment".to_string(),
            ));
        }
        self.fs.write(&target_uri, text, true)?;
        Ok(())
    }

    pub fn write_manifest(&self, source: &str) -> Result<IngestManifest> {
        let staged_path = self.fs.resolve_uri(&self.staged_uri);
        let files = scan_manifest_files(&self.parser, &staged_path)?;

        let manifest = IngestManifest {
            ingest_id: self.ingest_id.clone(),
            source: source.to_string(),
            created_at: Utc::now(),
            files,
        };

        let manifest_uri = self.root_uri.join("manifest.json")?;
        self.fs.write(
            &manifest_uri,
            &serde_json::to_string_pretty(&manifest)?,
            true,
        )?;

        Ok(manifest)
    }

    pub fn finalize_to(&mut self, target_uri: &AxiomUri, mode: IngestFinalizeMode) -> Result<()> {
        let staged_path = self.fs.resolve_uri(&self.staged_uri);
        let target_path = self.fs.resolve_uri(target_uri);

        if let Some(parent) = target_path.parent() {
            fs::create_dir_all(parent)?;
        }

        match mode {
            IngestFinalizeMode::ReplaceTarget => {
                remove_path_if_exists(&target_path)?;
                fs::rename(&staged_path, &target_path)?;
            }
            IngestFinalizeMode::MergeIntoTarget => {
                if !target_path.exists() {
                    fs::rename(&staged_path, &target_path)?;
                } else {
                    let staged_metadata = fs::symlink_metadata(&staged_path)?;
                    let target_metadata = fs::symlink_metadata(&target_path)?;
                    if staged_metadata.is_dir() && target_metadata.is_dir() {
                        merge_directory_contents(&staged_path, &target_path)?;
                        fs::remove_dir_all(&staged_path)?;
                    } else {
                        remove_path_if_exists(&target_path)?;
                        fs::rename(&staged_path, &target_path)?;
                    }
                }
            }
        }
        self.finalized = true;

        // Cleanup session root after staged folder has moved.
        self.fs.rm(&self.root_uri, true, true)?;
        Ok(())
    }

    pub fn abort(&mut self) {
        let _ = self.fs.rm(&self.root_uri, true, true);
    }
}

impl Drop for IngestSession {
    fn drop(&mut self) {
        if !self.finalized {
            let root: PathBuf = self.fs.resolve_uri(&self.root_uri);
            if root.exists() {
                let _ = fs::remove_dir_all(root);
            }
        }
    }
}

fn scan_manifest_files(parser: &ParserRegistry, staged_path: &Path) -> Result<Vec<IngestFileInfo>> {
    let mut out = Vec::new();

    for entry in WalkDir::new(staged_path).follow_links(false) {
        let entry = entry.map_err(|e| AxiomError::Validation(e.to_string()))?;
        if entry.path().is_dir() {
            continue;
        }

        let rel = entry
            .path()
            .strip_prefix(staged_path)
            .map_err(|e| AxiomError::Validation(e.to_string()))?
            .to_string_lossy()
            .to_string();

        let bytes = fs::read(entry.path())?;
        let hash = blake3::hash(&bytes).to_hex().to_string();
        let parsed = parser.parse_file(entry.path(), &bytes);

        out.push(IngestFileInfo {
            relative_path: rel,
            parser: parsed.parser,
            is_text: parsed.is_text,
            bytes: bytes.len() as u64,
            line_count: parsed.line_count,
            content_hash: hash,
            title: parsed.title,
            preview: parsed.text_preview,
            tags: parsed.tags,
        });
    }

    out.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
    Ok(out)
}

fn copy_dir_contents(src: &Path, dst: &Path) -> Result<()> {
    fs::create_dir_all(dst)?;

    for entry in WalkDir::new(src).follow_links(false) {
        let entry = entry.map_err(|e| AxiomError::Validation(e.to_string()))?;
        let path = entry.path();
        let rel = path
            .strip_prefix(src)
            .map_err(|e| AxiomError::Validation(e.to_string()))?;
        if rel.as_os_str().is_empty() {
            continue;
        }

        let out = dst.join(rel);
        if path.is_dir() {
            fs::create_dir_all(&out)?;
        } else {
            if let Some(parent) = out.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::copy(path, out)?;
        }
    }

    Ok(())
}

fn merge_directory_contents(source: &Path, target: &Path) -> Result<()> {
    fs::create_dir_all(target)?;

    for entry in fs::read_dir(source)? {
        let entry = entry?;
        let source_path = entry.path();
        let target_path = target.join(entry.file_name());
        let file_type = entry.file_type()?;

        if file_type.is_dir() {
            if target_path.exists() && !fs::symlink_metadata(&target_path)?.is_dir() {
                remove_path_if_exists(&target_path)?;
            }
            merge_directory_contents(&source_path, &target_path)?;
            continue;
        }

        remove_path_if_exists(&target_path)?;
        fs::rename(&source_path, &target_path)?;
    }

    Ok(())
}

fn remove_path_if_exists(path: &Path) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }

    let metadata = fs::symlink_metadata(path)?;
    if metadata.is_dir() {
        fs::remove_dir_all(path)?;
    } else {
        fs::remove_file(path)?;
    }
    Ok(())
}

#[derive(Debug)]
struct IngestPathFilter {
    markdown_only: bool,
    include_hidden: bool,
    exclude: GlobSet,
}

impl IngestPathFilter {
    fn new(options: &AddResourceIngestOptions) -> Result<Self> {
        let mut builder = GlobSetBuilder::new();
        for pattern in &options.exclude_globs {
            let trimmed = pattern.trim();
            if trimmed.is_empty() {
                continue;
            }
            let glob = Glob::new(trimmed).map_err(|err| {
                AxiomError::Validation(format!("invalid ingest exclude glob '{trimmed}': {err}"))
            })?;
            builder.add(glob);
        }

        let exclude = builder.build().map_err(|err| {
            AxiomError::Validation(format!("invalid ingest exclude globs: {err}"))
        })?;

        Ok(Self {
            markdown_only: options.markdown_only,
            include_hidden: options.include_hidden,
            exclude,
        })
    }

    fn allows_directory(&self, relative: &Path) -> bool {
        if relative.as_os_str().is_empty() {
            return true;
        }
        if !self.include_hidden && path_has_hidden_component(relative) {
            return false;
        }
        !self.exclude.is_match(relative_to_unix_path(relative))
    }

    fn allows_file(&self, relative: &Path) -> bool {
        if !self.include_hidden && path_has_hidden_component(relative) {
            return false;
        }
        if self.exclude.is_match(relative_to_unix_path(relative)) {
            return false;
        }
        if !self.markdown_only {
            return true;
        }
        relative
            .extension()
            .and_then(|x| x.to_str())
            .map(|x| matches!(x.to_ascii_lowercase().as_str(), "md" | "markdown"))
            .unwrap_or(false)
    }
}

fn copy_dir_contents_filtered(src: &Path, dst: &Path, filter: &IngestPathFilter) -> Result<usize> {
    fs::create_dir_all(dst)?;
    let mut copied_files = 0usize;

    let entries = WalkDir::new(src)
        .follow_links(false)
        .into_iter()
        .filter_entry(|entry| {
            if entry.path() == src {
                return true;
            }
            let Ok(relative) = entry.path().strip_prefix(src) else {
                return true;
            };
            if entry.file_type().is_dir() {
                filter.allows_directory(relative)
            } else {
                true
            }
        });

    for entry in entries {
        let entry = entry.map_err(|e| AxiomError::Validation(e.to_string()))?;
        let path = entry.path();
        let rel = path
            .strip_prefix(src)
            .map_err(|e| AxiomError::Validation(e.to_string()))?;
        if rel.as_os_str().is_empty() {
            continue;
        }

        let out = dst.join(rel);
        if path.is_dir() {
            fs::create_dir_all(&out)?;
            continue;
        }
        if !filter.allows_file(rel) {
            continue;
        }

        if let Some(parent) = out.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::copy(path, out)?;
        copied_files += 1;
    }

    Ok(copied_files)
}

fn path_has_hidden_component(path: &Path) -> bool {
    path.components().any(|component| match component {
        Component::Normal(value) => value.to_string_lossy().starts_with('.'),
        _ => false,
    })
}

fn relative_to_unix_path(relative: &Path) -> String {
    relative
        .components()
        .filter_map(|component| match component {
            Component::Normal(value) => Some(value.to_string_lossy().to_string()),
            _ => None,
        })
        .collect::<Vec<_>>()
        .join("/")
}

#[cfg(test)]
mod tests {
    use tempfile::tempdir;

    use super::*;
    use crate::models::AddResourceIngestOptions;

    #[test]
    fn staged_ingest_finalize_moves_tree_and_cleans_temp() {
        let temp = tempdir().expect("tempdir");
        let fs = LocalContextFs::new(temp.path());
        fs.initialize().expect("init");

        let source = temp.path().join("source");
        fs::create_dir_all(&source).expect("mkdir source");
        fs::write(source.join("a.md"), "# A\ncontent").expect("write source");

        let manager = IngestManager::new(fs.clone(), ParserRegistry::new());
        let mut session = manager.start_session().expect("start session");

        session.stage_local_path(&source).expect("stage local");
        let manifest = session.write_manifest("local://source").expect("manifest");
        assert_eq!(manifest.files.len(), 1);
        assert_eq!(manifest.files[0].parser, "markdown");

        let target = AxiomUri::parse("axiom://resources/demo").expect("target uri");
        session
            .finalize_to(&target, IngestFinalizeMode::ReplaceTarget)
            .expect("finalize");

        assert!(fs.resolve_uri(&target).join("a.md").exists());
        let temp_root = fs.resolve_uri(&AxiomUri::parse("axiom://temp/ingest").expect("temp uri"));
        let entries = fs::read_dir(&temp_root).expect("read temp root");
        assert_eq!(entries.count(), 0);
    }

    #[test]
    fn staged_ingest_finalize_merges_existing_target_directory() {
        let temp = tempdir().expect("tempdir");
        let fs = LocalContextFs::new(temp.path());
        fs.initialize().expect("init");

        let manager = IngestManager::new(fs.clone(), ParserRegistry::new());
        let target = AxiomUri::parse("axiom://resources/merge-demo").expect("target uri");

        let mut first = manager.start_session().expect("first session");
        first.stage_text("a.md", "# A").expect("stage a");
        first
            .finalize_to(&target, IngestFinalizeMode::MergeIntoTarget)
            .expect("finalize first");

        let mut second = manager.start_session().expect("second session");
        second.stage_text("b.md", "# B").expect("stage b");
        second
            .finalize_to(&target, IngestFinalizeMode::MergeIntoTarget)
            .expect("finalize second");

        let root = fs.resolve_uri(&target);
        assert!(root.join("a.md").exists());
        assert!(root.join("b.md").exists());
    }

    #[test]
    fn drop_without_finalize_cleans_temp_session() {
        let temp = tempdir().expect("tempdir");
        let fs = LocalContextFs::new(temp.path());
        fs.initialize().expect("init");

        {
            let manager = IngestManager::new(fs.clone(), ParserRegistry::new());
            let mut session = manager.start_session().expect("start");
            session
                .stage_text("source.txt", "hello world")
                .expect("stage text");
            session.write_manifest("inline").expect("manifest");
        }

        let temp_root = fs.resolve_uri(&AxiomUri::parse("axiom://temp/ingest").expect("temp uri"));
        let entries = fs::read_dir(temp_root).expect("read temp root");
        assert_eq!(entries.count(), 0);
    }

    #[test]
    fn stage_text_rejects_parent_traversal() {
        let temp = tempdir().expect("tempdir");
        let fs = LocalContextFs::new(temp.path());
        fs.initialize().expect("init");

        let manager = IngestManager::new(fs, ParserRegistry::new());
        let mut session = manager.start_session().expect("start");
        let err = session
            .stage_text("../escape.txt", "owned")
            .expect_err("must reject traversal");
        assert!(matches!(err, AxiomError::PathTraversal(_)));
    }

    #[test]
    fn stage_text_rejects_empty_normalized_name() {
        let temp = tempdir().expect("tempdir");
        let fs = LocalContextFs::new(temp.path());
        fs.initialize().expect("init");

        let manager = IngestManager::new(fs, ParserRegistry::new());
        let mut session = manager.start_session().expect("start");
        let err = session
            .stage_text("/", "owned")
            .expect_err("must reject empty normalized target");
        assert!(matches!(
            err,
            AxiomError::Validation(_) | AxiomError::PathTraversal(_)
        ));
    }

    #[test]
    fn stage_local_path_with_markdown_only_filters_hidden_and_json_files() {
        let temp = tempdir().expect("tempdir");
        let fs = LocalContextFs::new(temp.path());
        fs.initialize().expect("init");

        let source = temp.path().join("source");
        fs::create_dir_all(source.join("nested")).expect("mkdir nested");
        fs::create_dir_all(source.join(".obsidian")).expect("mkdir hidden");
        fs::write(source.join("note.md"), "# note").expect("write note");
        fs::write(source.join("meta.json"), "{\"ok\":true}").expect("write json");
        fs::write(source.join("nested").join("todo.markdown"), "# todo").expect("write nested md");
        fs::write(source.join(".obsidian").join("cache.md"), "# hidden").expect("write hidden md");

        let manager = IngestManager::new(fs.clone(), ParserRegistry::new());
        let mut session = manager.start_session().expect("start");
        session
            .stage_local_path_with_options(
                &source,
                &AddResourceIngestOptions::markdown_only_defaults(),
            )
            .expect("stage filtered");
        let manifest = session.write_manifest("local://source").expect("manifest");

        let staged_files = manifest
            .files
            .iter()
            .map(|x| x.relative_path.as_str())
            .collect::<Vec<_>>();
        assert_eq!(staged_files.len(), 2);
        assert!(staged_files.contains(&"note.md"));
        assert!(staged_files.contains(&"nested/todo.markdown"));
    }

    #[test]
    fn stage_local_file_with_markdown_only_rejects_non_markdown_source() {
        let temp = tempdir().expect("tempdir");
        let fs = LocalContextFs::new(temp.path());
        fs.initialize().expect("init");

        let file = temp.path().join("data.json");
        fs::write(&file, "{\"x\":1}").expect("write");

        let manager = IngestManager::new(fs, ParserRegistry::new());
        let mut session = manager.start_session().expect("start");
        let err = session
            .stage_local_path_with_options(
                &file,
                &AddResourceIngestOptions::markdown_only_defaults(),
            )
            .expect_err("non-markdown file must be rejected");
        assert!(matches!(err, AxiomError::Validation(_)));
    }
}