Skip to main content

nap_core/
repository.rs

1//! Universe repository — filesystem layout and manifest CRUD.
2//!
3//! A NAP repository represents a single fictional universe.
4//! Repository structure:
5//!
6//! ```text
7//! starwars/               ← universe root
8//! ├── .nap/               ← NAP metadata
9//! │   └── config.yaml     ← repository config
10//! ├── universe.yaml       ← world manifest (root-level)
11//! ├── characters/
12//! │   ├── lukeskywalker.yaml
13//! │   └── darthvader.yaml
14//! ├── locations/
15//! │   └── tatooine.yaml
16//! ├── scenes/
17//! │   └── cantina-scene.yaml
18//! └── props/
19//! ```
20
21use std::path::{Path, PathBuf};
22
23use tracing::{debug, info};
24
25use crate::commit::{Change, Commit};
26use crate::error::NapError;
27use crate::manifest::Manifest;
28use crate::types::EntityType;
29use crate::uri::NapUri;
30use crate::vcs::VcsBackend;
31
32/// NAP metadata directory name.
33const NAP_DIR: &str = ".nap";
34
35/// A NAP universe repository.
36pub struct Repository {
37    /// Filesystem path to the repository root.
38    pub root: PathBuf,
39    /// The universe name (derived from directory name).
40    pub universe: String,
41    /// The VCS backend (Lore).
42    vcs: Box<dyn VcsBackend>,
43}
44
45impl Repository {
46    /// Open an existing NAP repository at the given path.
47    pub fn open(path: &Path, vcs: Box<dyn VcsBackend>) -> Result<Self, NapError> {
48        let nap_dir = path.join(NAP_DIR);
49        if !nap_dir.exists() {
50            return Err(NapError::RepositoryNotFound(path.display().to_string()));
51        }
52        let universe = path
53            .file_name()
54            .and_then(|n| n.to_str())
55            .unwrap_or("unknown")
56            .to_string();
57
58        debug!(
59            path = %path.display(),
60            universe = %universe,
61            "opened NAP repository"
62        );
63
64        Ok(Self {
65            root: path.to_path_buf(),
66            universe,
67            vcs,
68        })
69    }
70
71    /// Initialize a new NAP repository.
72    pub fn init(path: &Path, universe: &str, vcs: Box<dyn VcsBackend>) -> Result<Self, NapError> {
73        let repo_root = path.join(universe);
74        if repo_root.join(NAP_DIR).exists() {
75            return Err(NapError::RepositoryAlreadyExists(
76                repo_root.display().to_string(),
77            ));
78        }
79
80        info!(
81            path = %repo_root.display(),
82            universe = %universe,
83            "initializing NAP repository"
84        );
85
86        // Create directory structure
87        std::fs::create_dir_all(&repo_root)?;
88        std::fs::create_dir_all(repo_root.join(NAP_DIR))?;
89
90        // Create entity type subdirectories
91        for entity_type in EntityType::subdirectory_types() {
92            std::fs::create_dir_all(repo_root.join(entity_type.directory_name()))?;
93        }
94
95        // Create .nap/config.yaml
96        let config = format!(
97            "# NAP Repository Configuration\nuniverse: {universe}\nprotocol_version: \"0.1.0\"\n"
98        );
99        std::fs::write(repo_root.join(NAP_DIR).join("config.yaml"), config)?;
100
101        // Create universe.yaml (world manifest)
102        let world_manifest = Manifest::new(
103            universe,
104            EntityType::World,
105            universe,
106            &format!("{universe} Universe"),
107        );
108        world_manifest.to_file(&repo_root.join("universe.yaml"))?;
109
110        // Initialize VCS
111        vcs.init(&repo_root)?;
112
113        // Initial commit
114        vcs.commit(
115            &repo_root,
116            &format!("Initialize {universe} universe"),
117            "nap-init",
118        )?;
119
120        info!(
121            path = %repo_root.display(),
122            universe = %universe,
123            "NAP repository initialized successfully"
124        );
125
126        Ok(Self {
127            root: repo_root,
128            universe: universe.to_string(),
129            vcs,
130        })
131    }
132
133    /// Get the full filesystem path to an entity's manifest file.
134    pub fn manifest_path(&self, entity_type: EntityType, entity_id: &str) -> PathBuf {
135        let uri = NapUri::new(&self.universe, entity_type, entity_id);
136        self.root.join(uri.manifest_path())
137    }
138
139    /// Read a manifest from the repository.
140    pub fn read_manifest(
141        &self,
142        entity_type: EntityType,
143        entity_id: &str,
144    ) -> Result<Manifest, NapError> {
145        let path = self.manifest_path(entity_type, entity_id);
146        debug!(
147            path = %path.display(),
148            entity_type = %entity_type,
149            entity_id = %entity_id,
150            "reading manifest"
151        );
152        Manifest::from_file(&path)
153    }
154
155    /// Read a manifest at a specific VCS ref (commit, branch, tag).
156    pub fn read_manifest_at_ref(
157        &self,
158        entity_type: EntityType,
159        entity_id: &str,
160        reference: &str,
161    ) -> Result<Manifest, NapError> {
162        let uri = NapUri::new(&self.universe, entity_type, entity_id);
163        let file_path = uri.manifest_path();
164
165        debug!(
166            file_path = %file_path,
167            reference = %reference,
168            "reading manifest at ref"
169        );
170
171        let content = self
172            .vcs
173            .read_file_at_ref(&self.root, &file_path, Some(reference))?;
174        Manifest::from_yaml(&content)
175    }
176
177    /// Write a manifest to the repository (does NOT commit).
178    pub fn write_manifest(&self, manifest: &Manifest) -> Result<PathBuf, NapError> {
179        let uri: NapUri = manifest.id.parse()?;
180        let path = self.root.join(uri.manifest_path());
181
182        debug!(
183            path = %path.display(),
184            manifest_id = %manifest.id,
185            "writing manifest"
186        );
187
188        manifest.to_file(&path)?;
189        Ok(path)
190    }
191
192    /// Create a new entity manifest and commit it.
193    pub fn create_entity(
194        &self,
195        entity_type: EntityType,
196        entity_id: &str,
197        name: &str,
198        author: &str,
199    ) -> Result<(Manifest, String), NapError> {
200        let mut manifest = Manifest::new(&self.universe, entity_type, entity_id, name);
201
202        // Validate against schema before writing
203        crate::schema::validate_manifest(&manifest)
204            .map_err(|errors| NapError::ManifestValidationError(errors.join("; ")))?;
205
206        // Write the manifest
207        self.write_manifest(&manifest)?;
208
209        // Commit via VCS
210        let commit_message = format!("Create {entity_type} '{name}' ({entity_id})");
211        let commit_hash = self.vcs.commit(&self.root, &commit_message, author)?;
212
213        // Update manifest with head pointer
214        manifest.head = Some(commit_hash.clone());
215        manifest.bump_version();
216        self.write_manifest(&manifest)?;
217
218        info!(
219            manifest_id = %manifest.id,
220            commit_hash = %commit_hash,
221            "created entity"
222        );
223
224        Ok((manifest, commit_hash))
225    }
226
227    /// Update an existing manifest and commit the changes.
228    pub fn commit_manifest(
229        &self,
230        manifest: &mut Manifest,
231        message: &str,
232        author: &str,
233        changes: Vec<Change>,
234    ) -> Result<Commit, NapError> {
235        // Validate against schema before writing
236        crate::schema::validate_manifest(manifest)
237            .map_err(|errors| NapError::ManifestValidationError(errors.join("; ")))?;
238
239        // Bump version
240        manifest.bump_version();
241
242        // Write updated manifest (without new head — we don't know it yet)
243        self.write_manifest(manifest)?;
244
245        // Compute manifest hash
246        let manifest_hash = manifest.content_hash()?.as_str().to_string();
247
248        // VCS commit — produces the new HEAD hash
249        let vcs_hash = self.vcs.commit(&self.root, message, author)?;
250
251        // Create NAP commit object with the now-known VCS hash
252        let nap_commit = Commit::new(
253            manifest.head.clone(),
254            author,
255            message,
256            &manifest_hash,
257            changes,
258        );
259
260        // Update head pointer and write again (leaves working tree dirty,
261        // same pattern as create_entity)
262        manifest.head = Some(vcs_hash.clone());
263        self.write_manifest(manifest)?;
264
265        debug!(
266            manifest_id = %manifest.id,
267            version = manifest.version,
268            nap_commit_id = %nap_commit.id,
269            vcs_hash = %vcs_hash,
270            "manifest committed"
271        );
272
273        Ok(nap_commit)
274    }
275
276    /// Get the commit history for a specific entity.
277    pub fn history(
278        &self,
279        entity_type: EntityType,
280        entity_id: &str,
281        limit: usize,
282    ) -> Result<Vec<crate::vcs::CommitInfo>, NapError> {
283        let uri = NapUri::new(&self.universe, entity_type, entity_id);
284        let file_path = uri.manifest_path();
285        self.vcs.log(&self.root, Some(&file_path), limit)
286    }
287
288    /// List all entity IDs of a given type in the repository.
289    pub fn list_entities(&self, entity_type: EntityType) -> Result<Vec<String>, NapError> {
290        let dir = self.root.join(entity_type.directory_name());
291        if !dir.exists() {
292            return Ok(vec![]);
293        }
294
295        let mut entities = Vec::new();
296        for entry in std::fs::read_dir(&dir)? {
297            let entry = entry?;
298            let path = entry.path();
299            if path.extension().and_then(|e| e.to_str()) == Some("yaml")
300                && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
301            {
302                entities.push(stem.to_string());
303            }
304        }
305        entities.sort();
306        Ok(entities)
307    }
308
309    /// Delete an entity manifest and commit the deletion.
310    pub fn delete_entity(
311        &self,
312        entity_type: EntityType,
313        entity_id: &str,
314        author: &str,
315    ) -> Result<String, NapError> {
316        let path = self.manifest_path(entity_type, entity_id);
317        if !path.exists() {
318            return Err(NapError::ManifestNotFound(path.display().to_string()));
319        }
320
321        std::fs::remove_file(&path)?;
322
323        let message = format!("Delete {entity_type} '{entity_id}'");
324        let hash = self.vcs.commit(&self.root, &message, author)?;
325        info!(entity_type = %entity_type, entity_id = %entity_id, "deleted entity");
326        Ok(hash)
327    }
328
329    /// Create a branch in the underlying VCS.
330    pub fn create_branch(&self, name: &str) -> Result<(), NapError> {
331        self.vcs.create_branch(&self.root, name)
332    }
333
334    /// Switch to a branch.
335    pub fn switch_branch(&self, name: &str) -> Result<(), NapError> {
336        self.vcs.switch_branch(&self.root, name)
337    }
338
339    /// Create a tag.
340    pub fn create_tag(&self, name: &str) -> Result<(), NapError> {
341        self.vcs.create_tag(&self.root, name)
342    }
343
344    /// List branches.
345    pub fn list_branches(&self) -> Result<Vec<String>, NapError> {
346        self.vcs.list_branches(&self.root)
347    }
348
349    /// List tags.
350    pub fn list_tags(&self) -> Result<Vec<String>, NapError> {
351        self.vcs.list_tags(&self.root)
352    }
353
354    /// Revert a commit by creating a new VCS commit that undoes the specified one.
355    ///
356    /// The revert is a universe-level operation (not entity-scoped).
357    /// After reverting, working-tree files are restored to their pre-commit content
358    /// and a new revert commit is created in VCS history.
359    pub fn revert_commit(&self, commit_hash: &str, author: &str) -> Result<String, NapError> {
360        let new_hash = self.vcs.revert(&self.root, commit_hash)?;
361
362        // Re-read all entity manifests and update their `head` pointer
363        // so manifests are consistent with the new VCS state.
364        for et in EntityType::subdirectory_types() {
365            if let Ok(ids) = self.list_entities(*et) {
366                for id in &ids {
367                    if let Ok(mut manifest) = self.read_manifest(*et, id) {
368                        manifest.head = Some(new_hash.clone());
369                        self.write_manifest(&manifest).ok();
370                    }
371                }
372            }
373        }
374
375        info!(
376            commit = %commit_hash,
377            revert = %new_hash,
378            author = %author,
379            "commit reverted"
380        );
381
382        Ok(new_hash)
383    }
384
385    /// Get current HEAD hash.
386    pub fn head_hash(&self) -> Result<String, NapError> {
387        self.vcs.head_hash(&self.root)
388    }
389
390    /// Resolve the most recent commit hash on a given branch.
391    pub fn resolve_branch_head(&self, branch: &str) -> Result<String, NapError> {
392        self.vcs.resolve_branch_head(&self.root, branch)
393    }
394
395    // ── Remote operations ─────────────────────────────────────────
396
397    /// Add a remote to the repository.
398    pub fn add_remote(&self, name: &str, url: &str) -> Result<(), NapError> {
399        self.vcs.add_remote(&self.root, name, url)
400    }
401
402    /// Remove a remote from the repository.
403    pub fn remove_remote(&self, name: &str) -> Result<(), NapError> {
404        self.vcs.remove_remote(&self.root, name)
405    }
406
407    /// List remotes as `(name, url)` pairs.
408    pub fn list_remotes(&self) -> Result<Vec<(String, String)>, NapError> {
409        self.vcs.list_remotes(&self.root)
410    }
411
412    /// Push the current branch to a remote.
413    pub fn push(&self, remote: Option<&str>, branch: Option<&str>) -> Result<(), NapError> {
414        self.vcs.push(&self.root, remote, branch)
415    }
416
417    /// Pull the current branch from a remote.
418    pub fn pull(&self, remote: Option<&str>, branch: Option<&str>) -> Result<(), NapError> {
419        self.vcs.pull(&self.root, remote, branch)
420    }
421
422    /// Access the VCS backend (for the resolver to read files at specific refs).
423    pub fn vcs(&self) -> &dyn VcsBackend {
424        self.vcs.as_ref()
425    }
426}
427
428// ── In-memory mock VcsBackend for testing ──────────────────────────────
429// (Moved to nap-test-utils)
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434    use crate::test_utils::{MockBackend, mock_repo};
435    use tempfile::TempDir;
436
437    #[test]
438    fn test_mock_backend_contract() {
439        crate::test_utils::contract::run_repository_contract(MockBackend::new());
440    }
441
442    #[test]
443    fn test_init_creates_structure() {
444        let tmp = TempDir::new().unwrap();
445        let repo = mock_repo(&tmp);
446
447        assert!(repo.root.join(".nap").exists());
448        assert!(repo.root.join("universe.yaml").exists());
449        assert!(repo.root.join("characters").exists());
450        assert!(repo.root.join("locations").exists());
451        assert!(repo.root.join("scenes").exists());
452        assert!(repo.root.join("props").exists());
453    }
454
455    #[test]
456    fn test_create_and_read_entity() {
457        let tmp = TempDir::new().unwrap();
458        let repo = mock_repo(&tmp);
459
460        let (manifest, _hash) = repo
461            .create_entity(EntityType::Character, "hero", "The Hero", "test-author")
462            .unwrap();
463
464        assert_eq!(manifest.name, "The Hero");
465        assert_eq!(manifest.entity_type, EntityType::Character);
466
467        // Read it back
468        let read_back = repo.read_manifest(EntityType::Character, "hero").unwrap();
469        assert_eq!(read_back.name, "The Hero");
470    }
471
472    #[test]
473    fn test_list_entities() {
474        let tmp = TempDir::new().unwrap();
475        let repo = mock_repo(&tmp);
476
477        repo.create_entity(EntityType::Character, "alice", "Alice", "author")
478            .unwrap();
479        repo.create_entity(EntityType::Character, "bob", "Bob", "author")
480            .unwrap();
481
482        let chars = repo.list_entities(EntityType::Character).unwrap();
483        assert_eq!(chars, vec!["alice", "bob"]);
484    }
485
486    #[test]
487    fn test_commit_manifest_updates() {
488        let tmp = TempDir::new().unwrap();
489        let repo = mock_repo(&tmp);
490
491        let (mut manifest, _) = repo
492            .create_entity(EntityType::Character, "hero", "The Hero", "author")
493            .unwrap();
494
495        // Modify and commit
496        manifest.set_property("species", serde_yaml::Value::String("elf".to_string()));
497        let changes = vec![Change::set("properties.species", None, "elf".to_string())];
498        let commit = repo
499            .commit_manifest(&mut manifest, "set species to elf", "author", changes)
500            .unwrap();
501
502        assert!(!commit.id.is_empty());
503        assert_eq!(commit.message, "set species to elf");
504
505        // Verify version incremented
506        let read_back = repo.read_manifest(EntityType::Character, "hero").unwrap();
507        assert!(read_back.version >= 2);
508    }
509
510    #[test]
511    fn test_history() {
512        let tmp = TempDir::new().unwrap();
513        let repo = mock_repo(&tmp);
514
515        let (mut manifest, _) = repo
516            .create_entity(EntityType::Character, "hero", "The Hero", "author")
517            .unwrap();
518
519        manifest.set_property(
520            "name",
521            serde_yaml::Value::String("Updated Hero".to_string()),
522        );
523        repo.commit_manifest(&mut manifest, "update name", "author", vec![])
524            .unwrap();
525
526        let hist = repo.history(EntityType::Character, "hero", 10).unwrap();
527        assert!(hist.len() >= 2);
528    }
529
530    #[test]
531    fn test_revert_commit() {
532        let tmp = TempDir::new().unwrap();
533        let repo = mock_repo(&tmp);
534
535        // Create entity and note its name
536        let (mut manifest, _) = repo
537            .create_entity(EntityType::Character, "hero", "The Hero", "author")
538            .unwrap();
539        assert_eq!(manifest.name, "The Hero");
540
541        // Modify and commit
542        manifest.set_property("species", serde_yaml::Value::String("elf".to_string()));
543        let changes = vec![Change::set("properties.species", None, "elf".to_string())];
544        let _commit = repo
545            .commit_manifest(&mut manifest, "set species to elf", "author", changes)
546            .unwrap();
547
548        // Verify the property was set
549        let read_back = repo.read_manifest(EntityType::Character, "hero").unwrap();
550        assert_eq!(
551            read_back.properties.get("species").and_then(|v| v.as_str()),
552            Some("elf")
553        );
554
555        // Get the VCS commit hash from the manifest's head pointer.
556        // After commit_manifest, this is the single VCS commit containing
557        // the property change (the head pointer update is left dirty).
558        let vcs_hash = read_back
559            .head
560            .as_ref()
561            .expect("head should be set after commit");
562
563        // Revert that VCS commit
564        let revert_hash = repo.revert_commit(vcs_hash, "author").unwrap();
565        assert!(!revert_hash.is_empty());
566
567        // Verify the manifest head was updated to the revert commit
568        let after_revert = repo.read_manifest(EntityType::Character, "hero").unwrap();
569        assert_eq!(after_revert.head.as_deref(), Some(revert_hash.as_str()));
570
571        // Verify the revert appears in history
572        let hist = repo.history(EntityType::Character, "hero", 10).unwrap();
573        assert!(hist.iter().any(|c| c.id == revert_hash));
574    }
575
576    // fn test_remote_operations() {
577    //     let tmp = TempDir::new().unwrap();
578    //     let repo = mock_repo(&tmp);
579
580    //     repo.add_remote("origin", "git@github.com:user/repo.git")
581    //         .unwrap();
582    //     let remotes = repo.list_remotes().unwrap();
583    //     assert_eq!(remotes.len(), 1);
584    //     assert_eq!(remotes[0].0, "origin");
585
586    //     repo.remove_remote("origin").unwrap();
587    //     let remotes = repo.list_remotes().unwrap();
588    //     assert!(remotes.is_empty());
589    // }
590}
591
592// ── Integration tests: Repository + LoreBackend ─────────────────────
593// These require a running Lore server. Run with:
594//   cargo test --features lore-integration
595#[cfg(all(test, feature = "lore-integration"))]
596mod lore_integration_tests {
597    use super::*;
598    use crate::vcs_lore::LoreBackend;
599    use std::time::{SystemTime, UNIX_EPOCH};
600    use tempfile::TempDir;
601
602    fn unique_suffix() -> u64 {
603        SystemTime::now()
604            .duration_since(UNIX_EPOCH)
605            .unwrap()
606            .as_nanos() as u64
607    }
608
609    fn setup_lore_repo() -> (TempDir, Repository) {
610        let universe = format!("ri-{}", unique_suffix());
611        let tmp = TempDir::new().unwrap();
612        let repo =
613            Repository::init(tmp.path(), &universe, Box::new(LoreBackend::from_env())).unwrap();
614        (tmp, repo)
615    }
616
617    #[test]
618    fn test_lore_init_creates_structure() {
619        let (_tmp, repo) = setup_lore_repo();
620        assert!(repo.root.join(".nap").exists());
621        assert!(repo.root.join("universe.yaml").exists());
622    }
623
624    #[test]
625    fn test_lore_create_and_read_entity() {
626        let (_tmp, repo) = setup_lore_repo();
627
628        let (manifest, _hash) = repo
629            .create_entity(
630                EntityType::Character,
631                "hero",
632                "Test Hero",
633                "integration-test",
634            )
635            .unwrap();
636        assert_eq!(manifest.name, "Test Hero");
637
638        let read_back = repo.read_manifest(EntityType::Character, "hero").unwrap();
639        assert_eq!(read_back.name, "Test Hero");
640    }
641
642    #[test]
643    fn test_lore_commit_and_branch() {
644        let (_tmp, repo) = setup_lore_repo();
645
646        let (mut manifest, _) = repo
647            .create_entity(
648                EntityType::Character,
649                "hero",
650                "Test Hero",
651                "integration-test",
652            )
653            .unwrap();
654
655        manifest.set_property("species", serde_yaml::Value::String("human".to_string()));
656        let changes = vec![Change::set("properties.species", None, "human".to_string())];
657        repo.commit_manifest(&mut manifest, "add species", "integration-test", changes)
658            .unwrap();
659
660        let read_back = repo.read_manifest(EntityType::Character, "hero").unwrap();
661        assert_eq!(read_back.version, 2);
662
663        repo.create_branch("feature-branch").unwrap();
664        let branches = repo.list_branches().unwrap();
665        assert!(branches.contains(&"feature-branch".to_string()));
666    }
667
668    #[test]
669    fn test_lore_delete_entity() {
670        let (_tmp, repo) = setup_lore_repo();
671
672        repo.create_entity(
673            EntityType::Character,
674            "hero",
675            "Test Hero",
676            "integration-test",
677        )
678        .unwrap();
679
680        repo.delete_entity(EntityType::Character, "hero", "integration-test")
681            .unwrap();
682
683        let entities = repo.list_entities(EntityType::Character).unwrap();
684        assert!(!entities.contains(&"hero".to_string()));
685    }
686
687    #[test]
688    fn test_lore_history() {
689        let (_tmp, repo) = setup_lore_repo();
690
691        let (mut manifest, _) = repo
692            .create_entity(
693                EntityType::Character,
694                "hero",
695                "Test Hero",
696                "integration-test",
697            )
698            .unwrap();
699
700        manifest.set_property(
701            "name",
702            serde_yaml::Value::String("Updated Hero".to_string()),
703        );
704        repo.commit_manifest(&mut manifest, "update name", "integration-test", vec![])
705            .unwrap();
706
707        let hist = repo.history(EntityType::Character, "hero", 10).unwrap();
708        assert!(hist.len() >= 2);
709    }
710}