axiomsync 1.0.1

Local retrieval runtime and CLI for AxiomSync.
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
use std::fs;
use std::io::Write;
use std::path::{Component, Path, PathBuf};

use globset::{Glob, GlobSetBuilder};
use walkdir::WalkDir;

use crate::error::{AxiomError, Result};
use crate::models::{Entry, TreeNode, TreeResult};
use crate::uri::{AxiomUri, Scope};

#[derive(Debug, Clone)]
pub struct LocalContextFs {
    root: PathBuf,
}

impl LocalContextFs {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self { root: root.into() }
    }

    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    pub fn initialize(&self) -> Result<()> {
        fs::create_dir_all(&self.root)?;
        for scope in [
            Scope::Resources,
            Scope::User,
            Scope::Agent,
            Scope::Session,
            Scope::Temp,
            Scope::Queue,
        ] {
            let path = self.root.join(scope.as_str());
            fs::create_dir_all(path)?;
        }
        Ok(())
    }

    #[must_use]
    pub fn resolve_uri(&self, uri: &AxiomUri) -> PathBuf {
        let mut out = self.root.join(uri.scope().as_str());
        for segment in uri.segments() {
            out.push(segment);
        }
        out
    }

    pub fn uri_from_path(&self, path: &Path) -> Result<AxiomUri> {
        let relative = path.strip_prefix(&self.root).map_err(|_| {
            AxiomError::Validation(format!("path is outside root: {}", path.display()))
        })?;

        let mut components = relative.components();
        let scope = components
            .next()
            .ok_or_else(|| AxiomError::Validation("missing scope component".to_string()))?;

        let scope_str = match scope {
            Component::Normal(s) => s.to_string_lossy().to_string(),
            _ => {
                return Err(AxiomError::Validation(
                    "invalid scope component".to_string(),
                ));
            }
        };

        let mut uri = AxiomUri::parse(&format!("axiom://{scope_str}"))?;
        for comp in components {
            if let Component::Normal(s) = comp {
                uri = uri.join(&s.to_string_lossy())?;
            }
        }
        Ok(uri)
    }

    #[must_use]
    pub fn exists(&self, uri: &AxiomUri) -> bool {
        self.resolve_uri(uri).exists()
    }

    #[must_use]
    pub fn is_dir(&self, uri: &AxiomUri) -> bool {
        self.resolve_uri(uri).is_dir()
    }

    pub fn create_dir_all(&self, uri: &AxiomUri, system: bool) -> Result<()> {
        Self::ensure_writable(uri, system)?;
        let path = self.resolve_uri(uri);
        self.ensure_path_within_root(&path)?;
        fs::create_dir_all(path)?;
        Ok(())
    }

    pub fn read(&self, uri: &AxiomUri) -> Result<String> {
        let path = self.resolve_uri(uri);
        if !path.exists() {
            return Err(AxiomError::NotFound(uri.to_string()));
        }
        if path.is_dir() {
            return Err(AxiomError::Validation(format!(
                "cannot read directory: {uri}"
            )));
        }
        self.ensure_path_within_root(&path)?;
        Ok(fs::read_to_string(path)?)
    }

    pub fn write(&self, uri: &AxiomUri, content: &str, system: bool) -> Result<()> {
        Self::ensure_writable(uri, system)?;
        let path = self.resolve_uri(uri);
        self.ensure_path_within_root(&path)?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(path, content)?;
        Ok(())
    }

    pub fn write_atomic(&self, uri: &AxiomUri, content: &str, system: bool) -> Result<()> {
        Self::ensure_writable(uri, system)?;
        let path = self.resolve_uri(uri);
        self.ensure_path_within_root(&path)?;
        let parent = path
            .parent()
            .ok_or_else(|| AxiomError::Validation(format!("target has no parent: {uri}")))?;
        fs::create_dir_all(parent)?;

        let file_name = path
            .file_name()
            .and_then(|x| x.to_str())
            .ok_or_else(|| AxiomError::Validation(format!("invalid target filename: {uri}")))?;
        let tmp_name = format!(
            ".{file_name}.axiomsync.tmp.{}",
            uuid::Uuid::new_v4().simple()
        );
        let tmp_path = parent.join(tmp_name);
        self.ensure_path_within_root(&tmp_path)?;

        {
            let mut tmp = fs::OpenOptions::new()
                .create_new(true)
                .write(true)
                .open(&tmp_path)?;
            tmp.write_all(content.as_bytes())?;
            tmp.sync_all()?;
        }

        if let Err(err) = fs::rename(&tmp_path, &path) {
            let _ = fs::remove_file(&tmp_path);
            return Err(AxiomError::from(err));
        }

        if let Ok(dir) = fs::File::open(parent) {
            let _ = dir.sync_all();
        }
        Ok(())
    }

    pub fn append(&self, uri: &AxiomUri, content: &str, system: bool) -> Result<()> {
        Self::ensure_writable(uri, system)?;
        let path = self.resolve_uri(uri);
        self.ensure_path_within_root(&path)?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let mut file = fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)?;
        file.write_all(content.as_bytes())?;
        Ok(())
    }

    pub fn write_bytes(&self, uri: &AxiomUri, bytes: &[u8], system: bool) -> Result<()> {
        Self::ensure_writable(uri, system)?;
        let path = self.resolve_uri(uri);
        self.ensure_path_within_root(&path)?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(path, bytes)?;
        Ok(())
    }

    pub fn read_bytes(&self, uri: &AxiomUri) -> Result<Vec<u8>> {
        let path = self.resolve_uri(uri);
        if !path.exists() {
            return Err(AxiomError::NotFound(uri.to_string()));
        }
        if path.is_dir() {
            return Err(AxiomError::Validation(format!(
                "cannot read directory: {uri}"
            )));
        }
        self.ensure_path_within_root(&path)?;
        Ok(fs::read(path)?)
    }

    pub fn list(&self, uri: &AxiomUri, recursive: bool) -> Result<Vec<Entry>> {
        let base = self.resolve_uri(uri);
        if !base.exists() {
            return Err(AxiomError::NotFound(uri.to_string()));
        }
        self.ensure_path_within_root(&base)?;
        let mut entries = Vec::new();

        if recursive {
            for item in WalkDir::new(&base).follow_links(false) {
                let item = item.map_err(|e| AxiomError::Validation(e.to_string()))?;
                if item.path() == base {
                    continue;
                }
                let meta = item
                    .metadata()
                    .map_err(|e| AxiomError::Validation(e.to_string()))?;
                let item_uri = self.uri_from_path(item.path())?;
                entries.push(Entry {
                    uri: item_uri.to_string(),
                    name: item.file_name().to_string_lossy().to_string(),
                    is_dir: meta.is_dir(),
                    size: if meta.is_file() { meta.len() } else { 0 },
                });
            }
        } else {
            for item in fs::read_dir(&base)? {
                let item = item?;
                let path = item.path();
                let meta = fs::symlink_metadata(&path)?;
                let item_uri = self.uri_from_path(&path)?;
                entries.push(Entry {
                    uri: item_uri.to_string(),
                    name: item.file_name().to_string_lossy().to_string(),
                    is_dir: meta.file_type().is_dir(),
                    size: if meta.is_file() { meta.len() } else { 0 },
                });
            }
        }

        entries.sort_by(|a, b| a.uri.cmp(&b.uri));
        Ok(entries)
    }

    pub fn glob(&self, uri: Option<&AxiomUri>, pattern: &str) -> Result<Vec<String>> {
        let base_uri = uri
            .cloned()
            .unwrap_or_else(|| AxiomUri::root(Scope::Resources));
        let base = self.resolve_uri(&base_uri);
        if !base.exists() {
            return Ok(Vec::new());
        }
        self.ensure_path_within_root(&base)?;

        let mut builder = GlobSetBuilder::new();
        builder.add(Glob::new(pattern).map_err(|e| AxiomError::Validation(e.to_string()))?);
        let matcher = builder
            .build()
            .map_err(|e| AxiomError::Validation(e.to_string()))?;

        let mut matched_uris = Vec::new();
        for item in WalkDir::new(&base).follow_links(false) {
            let item = item.map_err(|e| AxiomError::Validation(e.to_string()))?;
            if item.path() == base {
                continue;
            }
            let rel = item
                .path()
                .strip_prefix(&base)
                .map_err(|e| AxiomError::Validation(e.to_string()))?;
            if matcher.is_match(rel) {
                let item_uri = self.uri_from_path(item.path())?;
                matched_uris.push(item_uri.to_string());
            }
        }
        matched_uris.sort();
        Ok(matched_uris)
    }

    pub fn rm(&self, uri: &AxiomUri, recursive: bool, system: bool) -> Result<()> {
        Self::ensure_writable(uri, system)?;
        let path = self.resolve_uri(uri);
        if !path.exists() {
            return Ok(());
        }
        self.ensure_path_within_root(&path)?;
        if path.is_dir() {
            if recursive {
                fs::remove_dir_all(path)?;
            } else {
                fs::remove_dir(path)?;
            }
        } else {
            fs::remove_file(path)?;
        }
        Ok(())
    }

    pub fn mv(&self, from: &AxiomUri, to: &AxiomUri, system: bool) -> Result<()> {
        Self::ensure_writable(from, system)?;
        Self::ensure_writable(to, system)?;
        let from_path = self.resolve_uri(from);
        let to_path = self.resolve_uri(to);
        self.ensure_path_within_root(&from_path)?;
        self.ensure_path_within_root(&to_path)?;
        if let Some(parent) = to_path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::rename(from_path, to_path)?;
        Ok(())
    }

    pub fn tree(&self, uri: &AxiomUri) -> Result<TreeResult> {
        let path = self.resolve_uri(uri);
        if !path.exists() {
            return Err(AxiomError::NotFound(uri.to_string()));
        }
        self.ensure_path_within_root(&path)?;
        let root = self.build_tree(uri, &path)?;
        Ok(TreeResult { root })
    }

    fn build_tree(&self, uri: &AxiomUri, path: &Path) -> Result<TreeNode> {
        let meta = fs::symlink_metadata(path)?;
        let is_dir = meta.file_type().is_dir();
        let mut node = TreeNode {
            uri: uri.to_string(),
            is_dir,
            children: Vec::new(),
        };

        if is_dir {
            let mut children = Vec::new();
            for entry in fs::read_dir(path)? {
                let entry = entry?;
                let child_path = entry.path();
                let child_uri = self.uri_from_path(&child_path)?;
                children.push(self.build_tree(&child_uri, &child_path)?);
            }
            children.sort_by(|a, b| a.uri.cmp(&b.uri));
            node.children = children;
        }

        Ok(node)
    }

    fn ensure_writable(uri: &AxiomUri, system: bool) -> Result<()> {
        if !system && matches!(uri.scope(), Scope::Queue) {
            return Err(AxiomError::PermissionDenied(
                "queue scope is read-only for non-system operations".to_string(),
            ));
        }
        Ok(())
    }

    fn ensure_path_within_root(&self, path: &Path) -> Result<()> {
        let root = self.canonical_root()?;
        let mut probe = path.to_path_buf();
        while !probe.exists() {
            if !probe.pop() {
                return Err(AxiomError::SecurityViolation(format!(
                    "path has no existing ancestor: {}",
                    path.display()
                )));
            }
        }

        let probe_canonical = fs::canonicalize(&probe)?;
        if !probe_canonical.starts_with(&root) {
            return Err(AxiomError::SecurityViolation(format!(
                "path escapes root boundary: {}",
                path.display()
            )));
        }

        if path.exists() {
            let path_canonical = fs::canonicalize(path)?;
            if !path_canonical.starts_with(&root) {
                return Err(AxiomError::SecurityViolation(format!(
                    "path resolves outside root boundary: {}",
                    path.display()
                )));
            }
        }

        Ok(())
    }

    fn canonical_root(&self) -> Result<PathBuf> {
        if !self.root.exists() {
            fs::create_dir_all(&self.root)?;
        }
        Ok(fs::canonicalize(&self.root)?)
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use tempfile::tempdir;

    use super::*;
    use crate::models::RelationLink;
    use crate::relation_documents::{read_relations, write_relations};
    use crate::tier_documents::{read_abstract, read_overview, write_tiers};

    #[cfg(unix)]
    use std::os::unix::fs::symlink;

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

        let uri = AxiomUri::parse("axiom://queue/events.log").expect("parse failed");
        let err = fs.write(&uri, "x", false).expect_err("must fail");
        assert!(matches!(err, AxiomError::PermissionDenied(_)));
    }

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

        let uri = AxiomUri::parse("axiom://queue/logs/requests.jsonl").expect("parse failed");
        fs.append(&uri, "{\"a\":1}\n", true).expect("append 1");
        fs.append(&uri, "{\"b\":2}\n", true).expect("append 2");
        let raw = fs.read(&uri).expect("read");
        assert!(raw.contains("{\"a\":1}"));
        assert!(raw.contains("{\"b\":2}"));
    }

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

        let uri = AxiomUri::parse("axiom://resources/docs/atomic.md").expect("parse");
        fs.write(&uri, "v1", true).expect("write v1");
        fs.write_atomic(&uri, "v2", true).expect("write atomic");

        let raw = fs.read(&uri).expect("read");
        assert_eq!(raw, "v2");
    }

    #[cfg(unix)]
    #[test]
    fn write_rejects_symlink_escape_outside_root() {
        let temp = tempdir().expect("tempdir");
        let outside = tempdir().expect("outside");
        let fs = LocalContextFs::new(temp.path());
        fs.initialize().expect("init failed");

        let link_path = temp.path().join("resources").join("escape-link");
        symlink(outside.path(), &link_path).expect("symlink");

        let uri = AxiomUri::parse("axiom://resources/escape-link/pwned.txt").expect("parse uri");
        let err = fs.write(&uri, "owned", true).expect_err("must fail");
        assert!(matches!(err, AxiomError::SecurityViolation(_)));
    }

    #[cfg(unix)]
    #[test]
    fn read_rejects_symlink_escape_outside_root() {
        let temp = tempdir().expect("tempdir");
        let outside = tempdir().expect("outside");
        let fs = LocalContextFs::new(temp.path());
        fs.initialize().expect("init failed");

        let outside_file = outside.path().join("secret.txt");
        fs::write(&outside_file, "secret").expect("write outside");

        let link_path = temp.path().join("resources").join("secret-link.txt");
        symlink(&outside_file, &link_path).expect("symlink file");

        let uri = AxiomUri::parse("axiom://resources/secret-link.txt").expect("parse uri");
        let err = fs.read(&uri).expect_err("must fail");
        assert!(matches!(err, AxiomError::SecurityViolation(_)));
    }

    #[cfg(unix)]
    #[test]
    fn write_tiers_rejects_symlink_escape_outside_root() {
        let temp = tempdir().expect("tempdir");
        let outside = tempdir().expect("outside");
        let fs = LocalContextFs::new(temp.path());
        fs.initialize().expect("init failed");

        let link_path = temp.path().join("resources").join("escape-tiers");
        symlink(outside.path(), &link_path).expect("symlink");

        let uri = AxiomUri::parse("axiom://resources/escape-tiers").expect("parse uri");
        let err = write_tiers(&fs, &uri, "abstract", "overview", true).expect_err("must fail");
        assert!(matches!(err, AxiomError::SecurityViolation(_)));
    }

    #[cfg(unix)]
    #[test]
    fn read_tiers_reject_symlink_escape_outside_root() {
        let temp = tempdir().expect("tempdir");
        let outside = tempdir().expect("outside");
        let fs = LocalContextFs::new(temp.path());
        fs.initialize().expect("init failed");

        fs::write(outside.path().join(".abstract.md"), "secret abstract").expect("write abstract");
        fs::write(outside.path().join(".overview.md"), "secret overview").expect("write overview");

        let link_path = temp.path().join("resources").join("escape-tiers");
        symlink(outside.path(), &link_path).expect("symlink");
        let uri = AxiomUri::parse("axiom://resources/escape-tiers").expect("parse uri");

        let abstract_err = read_abstract(&fs, &uri).expect_err("must fail abstract read");
        assert!(matches!(abstract_err, AxiomError::SecurityViolation(_)));
        let overview_err = read_overview(&fs, &uri).expect_err("must fail overview read");
        assert!(matches!(overview_err, AxiomError::SecurityViolation(_)));
    }

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

        let owner = AxiomUri::parse("axiom://resources/docs").expect("owner parse");
        let links = vec![RelationLink {
            id: "auth-security".to_string(),
            uris: vec![
                "axiom://resources/docs/auth".to_string(),
                "axiom://resources/docs/security".to_string(),
            ],
            reason: "Security dependency".to_string(),
        }];

        write_relations(&fs, &owner, &links, true).expect("write relations");
        let loaded = read_relations(&fs, &owner).expect("read relations");
        assert_eq!(loaded, links);
    }

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

        let owner = AxiomUri::parse("axiom://resources/docs").expect("owner parse");
        let links = vec![RelationLink {
            id: "invalid".to_string(),
            uris: vec![
                "axiom://resources/docs/auth".to_string(),
                "not-a-axiom-uri".to_string(),
            ],
            reason: "Broken relation".to_string(),
        }];

        let err = write_relations(&fs, &owner, &links, true).expect_err("must reject invalid uri");
        assert!(matches!(err, AxiomError::Validation(_)));
    }

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

        let owner = AxiomUri::parse("axiom://resources/docs").expect("owner parse");
        let links = vec![
            RelationLink {
                id: "dup".to_string(),
                uris: vec![
                    "axiom://resources/docs/auth".to_string(),
                    "axiom://resources/docs/security".to_string(),
                ],
                reason: "First".to_string(),
            },
            RelationLink {
                id: "dup".to_string(),
                uris: vec![
                    "axiom://resources/docs/auth".to_string(),
                    "axiom://resources/docs/api".to_string(),
                ],
                reason: "Second".to_string(),
            },
        ];

        let err = write_relations(&fs, &owner, &links, true).expect_err("must reject duplicate id");
        assert!(matches!(err, AxiomError::Validation(_)));
    }

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

        let file_uri = AxiomUri::parse("axiom://resources/docs/readme.md").expect("uri parse");
        fs.write(&file_uri, "hello", true).expect("write file");
        let err = read_relations(&fs, &file_uri).expect_err("must fail");
        assert!(matches!(err, AxiomError::Validation(_)));
    }
}