oxios-kernel 0.3.0

Oxios kernel: supervisor, event bus, state store
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
//! Git-based version control layer using gix.
//! Provides in-process commits, logs, tags, and restore.

use anyhow::{bail, Result};
use gix::bstr::{BStr, ByteSlice};
use gix::hash::ObjectId;
use gix::objs::tree::EntryKind;
use gix::refs::transaction::PreviousValue;
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
use std::sync::Arc;

const GITIGNORE: &str = r#"# Oxios
*.tmp
*.lock
.env
api-keys.json
"#;

/// Commit information returned after a successful commit.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CommitInfo {
    /// Full commit hash (hex).
    pub hash: String,
    /// Short hash (7 chars).
    pub short_hash: String,
    /// Commit message.
    pub message: String,
    /// ISO-8601 timestamp.
    pub timestamp: String,
    /// Author name.
    pub author: String,
}

/// A single commit log entry.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LogEntry {
    /// Full commit hash (hex).
    pub hash: String,
    /// Short hash (7 chars).
    pub short_hash: String,
    /// Commit message.
    pub message: String,
    /// Timestamp string.
    pub timestamp: String,
    /// Author name.
    pub author: String,
}

/// Git-based version control layer.
///
/// Uses `gix` for in-process git operations — no subprocess spawning,
/// no performance overhead of forking `git` CLI commands.
pub struct GitLayer {
    repo: Arc<Mutex<gix::Repository>>,
    root: PathBuf,
    committer_name: String,
    #[allow(dead_code)]
    committer_email: String,
    enabled: bool,
}

impl GitLayer {
    /// Create a new GitLayer, initializing a repo if needed.
    pub fn new(root: PathBuf, enabled: bool) -> Result<Self> {
        let repo = if root.join(".git").exists() {
            gix::open(&root)?
        } else {
            std::fs::create_dir_all(&root)?;
            gix::init(&root)?
        };

        // Write .gitignore
        let gitignore = root.join(".gitignore");
        if !gitignore.exists() {
            std::fs::write(&gitignore, GITIGNORE)?;
        }

        let repo_ref = Arc::new(Mutex::new(repo));

        // Create initial commit if repo is empty
        if Self::head_id_detached(&repo_ref).is_none() {
            Self::create_initial_commit(&repo_ref, &root)?;
        }

        Ok(Self {
            repo: repo_ref,
            root,
            committer_name: "oxios".into(),
            committer_email: "oxios@oxios".into(),
            enabled,
        })
    }

    /// Get head commit as ObjectId (detached, no repo reference).
    fn head_id_detached(repo_arc: &Arc<Mutex<gix::Repository>>) -> Option<ObjectId> {
        let repo = repo_arc.lock();
        repo.head_id().ok().map(|id| id.detach())
    }

    fn create_initial_commit(repo: &Arc<Mutex<gix::Repository>>, root: &Path) -> Result<()> {
        let repo_lock = repo.lock();
        let gitignore = root.join(".gitignore");
        let content = std::fs::read(&gitignore)?;
        let blob_id = repo_lock.write_blob(&content)?;
        let empty_tree = ObjectId::empty_tree(repo_lock.object_hash());
        let mut editor = repo_lock.edit_tree(empty_tree)?;
        editor.upsert(".gitignore", EntryKind::Blob, blob_id)?;
        let tree_id = editor.write()?;
        let _sig = self_signature_ref();
        repo_lock.commit_as(
            self_signature_ref(),
            self_signature_ref(),
            "refs/heads/main",
            "Initial commit",
            tree_id.detach(),
            Vec::<ObjectId>::new(),
        )?;
        Ok(())
    }

    /// Commit a single file with a message.
    pub fn commit_file(&self, rel_path: &str, message: &str) -> Result<CommitInfo> {
        if !self.enabled {
            return self.noop_commit(message);
        }
        let repo = self.repo.lock();
        let abs = self.root.join(rel_path);
        if !abs.exists() {
            bail!("File not found: {}", rel_path);
        }

        let content = std::fs::read(&abs)?;
        let blob_id = repo.write_blob(&content)?;
        let head_tree = Self::head_tree_oid(&repo)?;
        let mut editor = repo.edit_tree(head_tree)?;
        editor.upsert(rel_path, EntryKind::Blob, blob_id)?;
        let tree_id = editor.write()?;

        // BUGFIX: Use the already-locked repo reference instead of self.repo
        // which would deadlock (parking_lot::Mutex is not reentrant).
        let parent = repo.head_id().ok().map(|id| id.detach());
        let _sig = self_signature_ref();
        let commit_id = repo.commit_as(
            self_signature_ref(),
            self_signature_ref(),
            "refs/heads/main",
            message,
            tree_id.detach(),
            parent.into_iter().collect::<Vec<_>>(),
        )?;

        Ok(self.make_info(&commit_id, message))
    }

    /// Commit multiple files in a single commit.
    pub fn commit_files(&self, rel_paths: &[&str], message: &str) -> Result<CommitInfo> {
        if !self.enabled {
            return self.noop_commit(message);
        }
        let repo = self.repo.lock();
        let head_tree = Self::head_tree_oid(&repo)?;
        let mut editor = repo.edit_tree(head_tree)?;

        for path in rel_paths {
            let abs = self.root.join(path);
            if abs.exists() {
                let content = std::fs::read(&abs)?;
                let blob_id = repo.write_blob(&content)?;
                editor.upsert(*path, EntryKind::Blob, blob_id)?;
            }
        }
        let tree_id = editor.write()?;

        // BUGFIX: Use the already-locked repo reference instead of self.repo
        // which would deadlock (parking_lot::Mutex is not reentrant).
        let parent = repo.head_id().ok().map(|id| id.detach());
        let _sig = self_signature_ref();
        let commit_id = repo.commit_as(
            self_signature_ref(),
            self_signature_ref(),
            "refs/heads/main",
            message,
            tree_id.detach(),
            parent.into_iter().collect::<Vec<_>>(),
        )?;

        Ok(self.make_info(&commit_id, message))
    }

    /// Remove a file from the repo and commit.
    pub fn remove_file(&self, rel_path: &str, message: &str) -> Result<CommitInfo> {
        if !self.enabled {
            return self.noop_commit(message);
        }
        let repo = self.repo.lock();
        let head_tree = Self::head_tree_oid(&repo)?;
        let mut editor = repo.edit_tree(head_tree)?;
        editor.remove(rel_path)?;
        let tree_id = editor.write()?;

        let parent = repo.head_id().ok().map(|id| id.detach());
        let _sig = self_signature_ref();
        let commit_id = repo.commit_as(
            self_signature_ref(),
            self_signature_ref(),
            "refs/heads/main",
            message,
            tree_id.detach(),
            parent.into_iter().collect::<Vec<_>>(),
        )?;

        Ok(self.make_info(&commit_id, message))
    }

    /// Append an audit entry to a monthly audit log file and commit it.
    pub fn log_action(
        &self,
        agent: &str,
        action: &str,
        target: &str,
        allowed: bool,
        detail: Option<&str>,
    ) -> Result<()> {
        let now = chrono::Utc::now();
        let filename = format!("audit/{}.audit", now.format("%Y-%m"));
        let entry = format!(
            "{} | {} | {} | {} | {} | {}\n",
            now.to_rfc3339(),
            agent,
            action,
            target,
            if allowed { "ALLOW" } else { "DENY" },
            detail.unwrap_or("-")
        );
        let dir = self.root.join("audit");
        std::fs::create_dir_all(&dir)?;
        use std::io::Write;
        std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(self.root.join(&filename))?
            .write_all(entry.as_bytes())?;
        self.commit_file(
            &filename,
            &format!("audit: {} {} {}", agent, action, target),
        )?;
        Ok(())
    }

    /// Create an annotated tag at the current HEAD.
    pub fn tag(&self, name: &str, message: &str) -> Result<()> {
        if !self.enabled {
            return Ok(());
        }
        let repo = self.repo.lock();
        let head_id = repo
            .head_id()
            .ok()
            .map(|id| id.detach())
            .ok_or_else(|| anyhow::anyhow!("No HEAD commit to tag"))?;
        let _sig = self_signature_ref();
        repo.tag(
            name,
            head_id,
            gix::objs::Kind::Commit,
            Some(_sig),
            message,
            PreviousValue::MustNotExist,
        )?;
        Ok(())
    }

    /// List all tags in the repository.
    pub fn list_tags(&self) -> Result<Vec<String>> {
        let repo = self.repo.lock();
        let mut tags = Vec::new();
        for reference in repo.references()?.all()? {
            let reference = reference.map_err(|e| anyhow::anyhow!("ref iter: {e:#}"))?;
            let name = reference.name().shorten().to_string();
            if name.starts_with("tags/") || (!name.contains('/') && !name.is_empty()) {
                let tag_name = name.strip_prefix("tags/").unwrap_or(&name);
                tags.push(tag_name.to_string());
            }
        }
        Ok(tags)
    }

    /// Return commit log entries, most recent first.
    pub fn log(&self, max_count: usize) -> Result<Vec<LogEntry>> {
        let repo = self.repo.lock();
        let head_id = repo.head_id()?.detach();
        let mut entries = Vec::new();
        let mut current_id: Option<ObjectId> = Some(head_id);

        while let Some(id) = current_id {
            if entries.len() >= max_count {
                break;
            }
            let commit = repo.find_commit(id)?;
            let decoded = commit.decode()?;
            let msg_ref = decoded.message();
            let msg = if let Some(body) = msg_ref.body {
                format!("{}\n\n{}", msg_ref.title, body)
            } else {
                msg_ref.title.to_string()
            };
            let timestamp = decoded.time().map(|t| t.to_string()).unwrap_or_default();
            let author = decoded
                .author()
                .map(|a| a.name.to_string())
                .unwrap_or_default();
            let hex = id.to_hex().to_string();
            entries.push(LogEntry {
                hash: hex.clone(),
                short_hash: hex[..7].into(),
                message: msg,
                timestamp,
                author,
            });
            // First parent via iterator
            current_id = decoded.parents().next();
        }

        Ok(entries)
    }

    /// Resolve a partial commit hash to full ObjectId.
    ///
    /// Git allows abbreviating commit hashes (e.g., "abc1234") as long as
    /// they're unique within the repository. This method uses `rev_parse_single`
    /// to resolve partial hashes to full commit IDs.
    ///
    /// # Arguments
    /// * `partial` - A partial hash (4-40 hex characters)
    ///
    /// # Returns
    /// The resolved `ObjectId` or error if the hash cannot be resolved.
    pub fn resolve_partial_hash(&self, partial: &str) -> Result<ObjectId> {
        if partial.len() < 4 {
            bail!("Partial hash too short (minimum 4 characters)");
        }
        // Check if it's already a full hash (40 hex chars for SHA-1)
        if partial.len() >= 40 {
            // Full hash - validate and return directly
            return Ok(ObjectId::from_hex(partial.as_bytes())?);
        }
        // Partial hash - use rev_parse_single to resolve
        let repo = self.repo.lock();
        // rev_parse_single handles both full and partial hashes
        let id = repo.rev_parse_single(BStr::new(partial))?;
        Ok(id.detach())
    }

    /// Restore a file to its state in a specific commit.
    pub fn restore_file(&self, rel_path: &str, hash: &str) -> Result<()> {
        let commit_id = self.resolve_partial_hash(hash)?;
        let repo = self.repo.lock();
        let commit = repo.find_commit(commit_id)?;
        let decoded = commit.decode()?;
        let tree_id = ObjectId::from_hex(decoded.tree.as_bytes())?;
        let tree = repo.find_tree(tree_id)?;
        let decoded_tree = tree.decode()?;

        // Find entry by filename (as bytes)
        let rel_bytes = BStr::new(rel_path);
        let entry = decoded_tree
            .entries
            .iter()
            .find(|e| e.filename == rel_bytes)
            .ok_or_else(|| anyhow::anyhow!("Path {} not found in commit {}", rel_path, hash))?;

        let blob = repo.find_blob(entry.oid.to_owned())?;
        std::fs::write(self.root.join(rel_path), &blob.data)?;
        Ok(())
    }

    /// Verify repository integrity.
    pub fn verify(&self) -> Result<bool> {
        let repo = self.repo.lock();
        let refs = repo.references()?;
        for reference in refs.all()? {
            let _ = reference.map_err(|e| anyhow::anyhow!("ref verify: {e:#}"))?;
        }
        // head_id() fails on an empty repo (no commits yet) — that's fine.
        if repo.head_id().is_err() {
            tracing::debug!("verify: no HEAD yet (empty repository)");
        }
        Ok(true)
    }

    /// Whether auto-commit is enabled.
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    // ── Private helpers ───────────────────────────────────────────────────────

    /// Get the current HEAD tree's ObjectId.
    fn head_tree_oid(repo: &gix::Repository) -> Result<ObjectId> {
        match Self::head_id_detached_raw(repo) {
            Some(id) => {
                let commit = repo.find_commit(id)?;
                let decoded = commit.decode()?;
                let oid = ObjectId::from_hex(decoded.tree)?;
                Ok(oid)
            }
            None => Ok(ObjectId::empty_tree(repo.object_hash())),
        }
    }

    /// Get head commit as ObjectId (raw, borrowed repo).
    fn head_id_detached_raw(repo: &gix::Repository) -> Option<ObjectId> {
        repo.head_id().ok().map(|id| id.detach())
    }

    fn noop_commit(&self, message: &str) -> Result<CommitInfo> {
        Ok(CommitInfo {
            hash: "(disabled)".into(),
            short_hash: "(dis)".into(),
            message: message.into(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            author: "oxios".into(),
        })
    }

    fn make_info(&self, id: &gix::Id, message: &str) -> CommitInfo {
        let hex = id.to_hex().to_string();
        CommitInfo {
            short_hash: hex[..7].into(),
            hash: hex,
            message: message.into(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            author: self.committer_name.clone(),
        }
    }
}

/// Create a signature ref for committer/author identity.
fn self_signature_ref() -> gix::actor::SignatureRef<'static> {
    static TIME_BUF: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    let time_str = TIME_BUF.get_or_init(|| gix::date::Time::now_local_or_utc().to_string());
    gix::actor::SignatureRef {
        name: "oxios".into(),
        email: "oxios@oxios".into(),
        time: time_str.as_str(),
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn setup() -> (TempDir, GitLayer) {
        let dir = tempfile::tempdir().unwrap();
        let layer = GitLayer::new(dir.path().to_path_buf(), true).unwrap();
        (dir, layer)
    }

    #[test]
    fn test_init_creates_repo() {
        let (dir, _) = setup();
        assert!(dir.path().join(".git").exists());
    }

    #[test]
    fn test_commit_file() {
        let (dir, layer) = setup();
        std::fs::write(dir.path().join("test.json"), b"{\"hello\":1}").unwrap();
        let info = layer.commit_file("test.json", "test commit").unwrap();
        assert!(!info.hash.is_empty());
        assert_eq!(info.short_hash.len(), 7);
        assert_eq!(info.message, "test commit");
        assert!(info.hash.starts_with(&info.short_hash));
    }

    #[test]
    fn test_log_query() {
        let (dir, layer) = setup();
        std::fs::write(dir.path().join("a.json"), b"1").unwrap();
        layer.commit_file("a.json", "first").unwrap();
        std::fs::write(dir.path().join("a.json"), b"2").unwrap();
        layer.commit_file("a.json", "second").unwrap();
        let log = layer.log(10).unwrap();
        assert!(log.len() >= 2);
        assert!(log[0].message.contains("second"));
    }

    #[test]
    fn test_tag_create_list() {
        let (dir, layer) = setup();
        std::fs::write(dir.path().join("x.json"), b"1").unwrap();
        layer.commit_file("x.json", "tag test").unwrap();
        layer.tag("v1", "first tag").unwrap();
        let tags = layer.list_tags().unwrap();
        assert!(tags.iter().any(|t| t.contains("v1")));
    }

    #[test]
    fn test_disabled_noop() {
        let dir = tempfile::tempdir().unwrap();
        let layer = GitLayer::new(dir.path().to_path_buf(), false).unwrap();
        std::fs::write(dir.path().join("test.json"), b"1").unwrap();
        let info = layer.commit_file("test.json", "noop").unwrap();
        assert_eq!(info.hash, "(disabled)");
        assert_eq!(info.short_hash, "(dis)");
    }

    #[test]
    fn test_log_action() {
        let (dir, layer) = setup();
        layer
            .log_action("agent-A", "read", "file.txt", true, None)
            .unwrap();
        let audit_file = dir
            .path()
            .join("audit")
            .join(format!("{}.audit", chrono::Utc::now().format("%Y-%m")));
        assert!(audit_file.exists());
        let content = std::fs::read_to_string(&audit_file).unwrap();
        assert!(content.contains("agent-A"));
        assert!(content.contains("ALLOW"));
    }

    #[test]
    fn test_verify() {
        let (_, layer) = setup();
        assert!(layer.verify().unwrap());
    }

    #[test]
    fn test_remove_file() {
        let (dir, layer) = setup();
        std::fs::write(dir.path().join("todelete.json"), b"1").unwrap();
        layer.commit_file("todelete.json", "add file").unwrap();
        std::fs::remove_file(dir.path().join("todelete.json")).unwrap();
        let info = layer.remove_file("todelete.json", "remove file").unwrap();
        assert!(!info.hash.is_empty());
        assert!(info.hash != "(disabled)");
    }

    #[test]
    fn test_commit_files_batch() {
        let (dir, layer) = setup();
        std::fs::write(dir.path().join("a.json"), b"1").unwrap();
        std::fs::write(dir.path().join("b.json"), b"2").unwrap();
        let info = layer
            .commit_files(&["a.json", "b.json"], "batch commit")
            .unwrap();
        assert!(!info.hash.is_empty());
        assert_eq!(info.message, "batch commit");
    }

    #[test]
    fn test_restore_file() {
        let (dir, layer) = setup();
        std::fs::write(dir.path().join("state.json"), b"v1").unwrap();
        let first = layer.commit_file("state.json", "v1").unwrap();
        std::fs::write(dir.path().join("state.json"), b"v2").unwrap();
        layer.commit_file("state.json", "v2").unwrap();
        layer.restore_file("state.json", &first.short_hash).unwrap();
        let content = std::fs::read_to_string(dir.path().join("state.json")).unwrap();
        assert_eq!(content, "v1");
    }

    #[test]
    fn test_gitignore_created() {
        let (dir, _) = setup();
        assert!(dir.path().join(".gitignore").exists());
        let content = std::fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(content.contains("Oxios"));
    }
}