Skip to main content

git2db/
registry.rs

1//! Unified git2db registry implementation
2//!
3//! Combines artifact management with hyprstream's UUID-based model patterns
4
5use chrono::Utc;
6use git2::{IndexAddOption, Repository};
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::path::{Path, PathBuf};
10use tokio::fs;
11use uuid::Uuid;
12
13use crate::config::Git2DBConfig;
14use crate::errors::{Git2DBError, Git2DBResult};
15use crate::manager::GitManager;
16use crate::references::GitRef;
17use crate::repository_handle::RepositoryHandle;
18use crate::storage::{Driver, StorageDriver};
19use tracing::{debug, info, trace, warn};
20
21/// Runtime-private state must not be swept up by registry metadata commits.
22const REGISTRY_RUNTIME_IGNORES: &str =
23    "/pds/\n/pds-store/\n/sessions.jsonl\n/credential-revocations.jsonl\n";
24
25async fn ensure_registry_runtime_ignores(registry_path: &Path) -> Git2DBResult<()> {
26    use tokio::io::AsyncWriteExt;
27
28    let ignore_path = registry_path.join(".gitignore");
29    let existing = match fs::read_to_string(&ignore_path).await {
30        Ok(content) => content,
31        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
32        Err(error) => return Err(Git2DBError::repository(&ignore_path, error.to_string())),
33    };
34    // A final block wins over earlier unignore rules without replacing custom rules.
35    if existing.ends_with(REGISTRY_RUNTIME_IGNORES) {
36        return Ok(());
37    }
38    let mut ignore = fs::OpenOptions::new()
39        .create(true)
40        .append(true)
41        .open(&ignore_path)
42        .await
43        .map_err(|error| Git2DBError::repository(&ignore_path, error.to_string()))?;
44    if !existing.is_empty() && !existing.ends_with('\n') {
45        ignore
46            .write_all(b"\n")
47            .await
48            .map_err(|error| Git2DBError::repository(&ignore_path, error.to_string()))?;
49    }
50    ignore
51        .write_all(REGISTRY_RUNTIME_IGNORES.as_bytes())
52        .await
53        .map_err(|error| Git2DBError::repository(&ignore_path, error.to_string()))?;
54    ignore
55        .flush()
56        .await
57        .map_err(|error| Git2DBError::repository(&ignore_path, error.to_string()))?;
58    Ok(())
59}
60
61/// UUID v5 namespace for the registry's own self-tracking entry.
62const REGISTRY_SELF_NS: Uuid = uuid::uuid!("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
63
64/// Deterministic UUID for the `.registry` self-tracked entry.
65pub fn registry_self_uuid() -> Uuid {
66    Uuid::new_v5(&REGISTRY_SELF_NS, b".registry")
67}
68
69/// Repository identifier using UUID
70#[derive(Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
71pub struct RepoId(pub Uuid);
72
73impl RepoId {
74    /// Create a new repository ID with a random UUID
75    pub fn new() -> Self {
76        Self(Uuid::new_v4())
77    }
78
79    /// Create from an existing UUID
80    pub fn from_uuid(uuid: Uuid) -> Self {
81        Self(uuid)
82    }
83
84    /// Get the inner UUID
85    pub fn uuid(&self) -> Uuid {
86        self.0
87    }
88}
89
90impl std::str::FromStr for RepoId {
91    type Err = uuid::Error;
92
93    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
94        Ok(Self(Uuid::parse_str(s)?))
95    }
96}
97
98impl std::fmt::Display for RepoId {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        write!(f, "{}", self.0)
101    }
102}
103
104impl Default for RepoId {
105    fn default() -> Self {
106        Self::new()
107    }
108}
109
110/// Remote configuration for a tracked repository
111#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
112pub struct RemoteConfig {
113    pub name: String,
114    pub url: String,
115    #[serde(default)]
116    pub fetch_refs: Vec<String>,
117}
118
119impl RemoteConfig {
120    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
121        Self {
122            name: name.into(),
123            url: url.into(),
124            fetch_refs: vec![],
125        }
126    }
127}
128
129/// A tracked repository in the registry
130#[derive(Debug, Clone, Serialize, Deserialize)]
131pub struct TrackedRepository {
132    pub id: RepoId,
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub name: Option<String>,
135    pub url: String,
136    pub worktree_path: PathBuf,
137    pub tracking_ref: GitRef,
138    #[serde(default)]
139    pub remotes: Vec<RemoteConfig>,
140    pub registered_at: i64,
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub current_oid: Option<String>,
143    #[serde(default)]
144    pub metadata: HashMap<String, String>,
145}
146
147impl TrackedRepository {
148    /// Get the UUID of this repository
149    pub fn uuid(&self) -> Uuid {
150        self.id.0
151    }
152
153    /// Get the repository name or UUID as fallback
154    pub fn display_name(&self) -> String {
155        self.name.clone().unwrap_or_else(|| self.id.to_string())
156    }
157}
158
159/// Registry metadata stored in registry.json
160#[derive(Debug, Clone, Serialize, Deserialize)]
161pub struct RegistryMetadata {
162    pub version: String,
163    #[serde(default)]
164    #[serde(skip_serializing_if = "HashMap::is_empty")]
165    pub repositories: HashMap<Uuid, TrackedRepository>,
166}
167
168impl Default for RegistryMetadata {
169    fn default() -> Self {
170        Self {
171            version: "2.0.0".to_owned(),
172            repositories: HashMap::new(),
173        }
174    }
175}
176
177/// Git-based model registry using submodules (unified implementation)
178pub struct Git2DB {
179    /// Path to the .registry Git repository
180    registry_path: PathBuf,
181    /// Base models directory
182    base_dir: PathBuf,
183    /// Registry metadata
184    metadata: RegistryMetadata,
185    /// Git manager for operations
186    git_manager: &'static GitManager,
187    /// Pre-loaded storage driver for this registry (loaded once)
188    storage_driver: std::sync::Arc<dyn Driver>,
189}
190
191impl Git2DB {
192    /// Get the pre-loaded storage driver for this registry
193    pub fn storage_driver(&self) -> &std::sync::Arc<dyn Driver> {
194        &self.storage_driver
195    }
196
197    /// Get the registry version
198    ///
199    /// Returns the version string from the registry metadata.
200    pub fn version(&self) -> &str {
201        &self.metadata.version
202    }
203}
204
205impl Git2DB {
206    /// Initialize or open the registry
207    pub async fn open<P: AsRef<Path>>(base_dir: P) -> Git2DBResult<Self> {
208        let base_dir = base_dir.as_ref().to_path_buf();
209        let registry_path = base_dir.join(".registry");
210        let git_manager = GitManager::global();
211
212        // Check if directory exists AND is a git repository
213        // (directory might exist but not be initialized, e.g., from Docker volume mount)
214        let rp = registry_path.clone();
215        let is_valid_repo = tokio::task::spawn_blocking(move || Repository::open(&rp).is_ok())
216            .await
217            .unwrap_or(false);
218        let is_git_repo =
219            registry_path.join(".git").exists() || (registry_path.exists() && is_valid_repo);
220
221        // Create or open registry repo
222        if is_git_repo {
223            // Verify we can open it (git2 is blocking)
224            let rp = registry_path.clone();
225            tokio::task::spawn_blocking(move || {
226                GitManager::global().get_repository(&rp).map_err(|e| {
227                    Git2DBError::repository(&rp, format!("Failed to open registry repository: {e}"))
228                })
229            })
230            .await
231            .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))??;
232            ensure_registry_runtime_ignores(&registry_path).await?;
233        } else {
234            // Initialize new registry
235            info!("Initializing new model registry at {:?}", registry_path);
236
237            fs::create_dir_all(&registry_path).await.map_err(|e| {
238                Git2DBError::repository(&registry_path, format!("Failed to create directory: {e}"))
239            })?;
240
241            // Restrict registry directory — may contain URLs with embedded tokens
242            #[cfg(unix)]
243            {
244                use std::os::unix::fs::PermissionsExt;
245                fs::set_permissions(&registry_path, std::fs::Permissions::from_mode(0o700))
246                    .await
247                    .map_err(|e| {
248                        Git2DBError::repository(
249                            &registry_path,
250                            format!("Failed to set directory permissions: {e}"),
251                        )
252                    })?;
253            }
254
255            // Create directory structure for v2
256            fs::create_dir_all(registry_path.join("repos"))
257                .await
258                .map_err(|e| {
259                    Git2DBError::repository(
260                        &registry_path,
261                        format!("Failed to create repos directory: {e}"),
262                    )
263                })?;
264            fs::create_dir_all(registry_path.join(".worktrees"))
265                .await
266                .map_err(|e| {
267                    Git2DBError::repository(
268                        &registry_path,
269                        format!("Failed to create .worktrees directory: {e}"),
270                    )
271                })?;
272
273            // Create initial registry.json
274            let metadata = RegistryMetadata::default();
275            let json = serde_json::to_string_pretty(&metadata)
276                .map_err(|e| Git2DBError::internal(format!("Failed to serialize metadata: {e}")))?;
277            fs::write(registry_path.join("registry.json"), &json)
278                .await
279                .map_err(|e| {
280                    Git2DBError::repository(
281                        &registry_path,
282                        format!("Failed to write registry.json: {e}"),
283                    )
284                })?;
285
286            // Restrict registry.json — contains repo URLs that may embed credentials
287            #[cfg(unix)]
288            {
289                use std::os::unix::fs::PermissionsExt;
290                fs::set_permissions(
291                    registry_path.join("registry.json"),
292                    std::fs::Permissions::from_mode(0o600),
293                )
294                .await
295                .map_err(|e| {
296                    Git2DBError::repository(
297                        &registry_path,
298                        format!("Failed to set registry.json permissions: {e}"),
299                    )
300                })?;
301            }
302
303            ensure_registry_runtime_ignores(&registry_path).await?;
304
305            // Init repo + initial commit in spawn_blocking (git2::Repository is !Send)
306            let rp = registry_path.clone();
307            tokio::task::spawn_blocking(move || -> Git2DBResult<()> {
308                let repo = Repository::init(&rp).map_err(|e| {
309                    Git2DBError::repository(&rp, format!("Failed to init repository: {e}"))
310                })?;
311
312                let sig = GitManager::global()
313                    .create_signature(None, None)
314                    .map_err(|e| {
315                        Git2DBError::internal(format!("Failed to create signature: {e}"))
316                    })?;
317
318                let tree_id = {
319                    let mut index = repo.index().map_err(|e| {
320                        Git2DBError::repository(&rp, format!("Failed to get index: {e}"))
321                    })?;
322                    index
323                        .add_all(["*"].iter(), IndexAddOption::DEFAULT, None)
324                        .map_err(|e| {
325                            Git2DBError::repository(&rp, format!("Failed to stage files: {e}"))
326                        })?;
327                    index.write().map_err(|e| {
328                        Git2DBError::repository(&rp, format!("Failed to write index: {e}"))
329                    })?;
330                    index.write_tree().map_err(|e| {
331                        Git2DBError::repository(&rp, format!("Failed to write tree: {e}"))
332                    })?
333                };
334
335                let tree = repo.find_tree(tree_id).map_err(|e| {
336                    Git2DBError::repository(&rp, format!("Failed to find tree: {e}"))
337                })?;
338
339                repo.commit(
340                    Some("HEAD"),
341                    &sig,
342                    &sig,
343                    "Initialize model registry",
344                    &tree,
345                    &[],
346                )
347                .map_err(|e| {
348                    Git2DBError::repository(&rp, format!("Failed to create initial commit: {e}"))
349                })?;
350
351                Ok(())
352            })
353            .await
354            .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))??;
355        }
356
357        // Load metadata
358        let metadata_path = registry_path.join("registry.json");
359        let metadata = if metadata_path.exists() {
360            let content = fs::read_to_string(&metadata_path).await.map_err(|e| {
361                Git2DBError::repository(
362                    &registry_path,
363                    format!("Failed to read registry.json: {e}"),
364                )
365            })?;
366            serde_json::from_str(&content).map_err(|e| {
367                Git2DBError::repository(
368                    &registry_path,
369                    format!("Failed to parse registry.json: {e}"),
370                )
371            })?
372        } else {
373            RegistryMetadata::default()
374        };
375
376        // Load storage driver once based on fresh configuration
377        let config = Git2DBConfig::load()
378            .map_err(|e| Git2DBError::internal(format!("Failed to load configuration: {e}")))?;
379        // Debug logging for configuration
380        info!(
381            "Worktree driver configuration loaded: '{}'",
382            config.worktree.driver
383        );
384
385        let driver_config = config
386            .worktree
387            .driver
388            .parse::<StorageDriver>()
389            .map_err(|e| {
390                Git2DBError::internal(format!(
391                    "Invalid storage driver config '{}': {}",
392                    config.worktree.driver, e
393                ))
394            })?;
395
396        info!("Parsed driver configuration: {:?}", driver_config);
397
398        let storage_driver = git_manager
399            .driver_registry()
400            .get_driver(driver_config)
401            .map_err(|e| Git2DBError::internal(format!("Failed to load storage driver: {e}")))?;
402
403        // Validate that the selected driver is available
404        if !storage_driver.is_available() {
405            return Err(Git2DBError::internal(format!(
406                "Selected storage driver '{}' is not available on this system",
407                storage_driver.name()
408            )));
409        }
410
411        let mut registry = Self {
412            registry_path,
413            base_dir,
414            metadata,
415            git_manager,
416            storage_driver,
417        };
418
419        // Check for and recover from uncommitted changes (e.g., from interrupted operations)
420        if let Err(e) = registry.recover_uncommitted_changes() {
421            warn!("Failed to recover uncommitted changes: {}", e);
422        }
423
424        // Initialize submodules if configured (equivalent to git clone --recurse-submodules)
425        let config = git_manager.config();
426        if config.repository.auto_init_submodules {
427            if let Err(e) = registry.init_submodules().await {
428                warn!("Failed to initialize submodules: {}", e);
429            }
430        }
431
432        // Initialize XET filter if configured
433        #[cfg(feature = "xet-storage")]
434        {
435            let config = git_manager.config();
436            if !config.xet.endpoint.is_empty() {
437                // Note: XET filter initialization will now properly fail with a clear error
438                // if called from within an existing runtime context
439                if let Err(e) = crate::xet_filter::initialize(config.xet.clone()).await {
440                    warn!(
441                        "Failed to initialize XET filter: {}. Falling back to Git LFS.",
442                        e
443                    );
444                }
445            }
446        }
447
448        // Self-track .registry as a repository (bypasses submodule registration)
449        let self_uuid = registry_self_uuid();
450        if !registry.metadata.repositories.contains_key(&self_uuid) {
451            info!("Registering .registry as self-tracked repository");
452            registry.metadata.repositories.insert(
453                self_uuid,
454                TrackedRepository {
455                    id: RepoId::from_uuid(self_uuid),
456                    name: Some(".registry".to_owned()),
457                    url: format!("file://{}", registry.registry_path.display()),
458                    worktree_path: registry.registry_path.clone(),
459                    tracking_ref: GitRef::DefaultBranch,
460                    remotes: Vec::new(),
461                    registered_at: Utc::now().timestamp(),
462                    current_oid: None,
463                    metadata: HashMap::new(),
464                },
465            );
466            registry.save_metadata().await?;
467            registry.commit_changes("Register .registry as self-tracked repository")?;
468        }
469
470        Ok(registry)
471    }
472
473    /// Open the repository on-demand
474    fn open_repo(&self) -> Git2DBResult<Repository> {
475        let repo_cache = self
476            .git_manager
477            .get_repository(&self.registry_path)
478            .map_err(|e| {
479                Git2DBError::repository(
480                    &self.registry_path,
481                    format!("Failed to open registry repository: {e}"),
482                )
483            })?;
484        repo_cache.open()
485    }
486
487    /// Add a repository to the registry
488    ///
489    /// Clones the repository and registers it with the given name.
490    /// Names must be unique - attempting to add a repository with a duplicate name will fail.
491    ///
492    /// # Arguments
493    /// * `name` - Unique name for the repository
494    /// * `url` - Git URL to clone from
495    ///
496    /// # Returns
497    /// The UUID (RepoId) of the newly added repository
498    ///
499    /// # Examples
500    /// ```rust,ignore
501    /// let id = registry.add_repository("myrepo", "https://github.com/user/repo.git").await?;
502    /// ```
503    pub async fn add_repository(&mut self, name: &str, url: &str) -> Git2DBResult<RepoId> {
504        let repo_id = RepoId::new();
505        self.add_repository_with_id(repo_id.clone(), name, url)
506            .await?;
507        Ok(repo_id)
508    }
509
510    /// Add a repository with a specific ID (used by transactions)
511    ///
512    /// This is an internal method used by the transaction system to ensure
513    /// IDs are consistent between transaction creation and commit.
514    pub(crate) async fn add_repository_with_id(
515        &mut self,
516        repo_id: RepoId,
517        name: &str,
518        url: &str,
519    ) -> Git2DBResult<()> {
520        // Path to the actual repository
521        let repo_path = self.base_dir.join(repo_id.0.to_string());
522
523        // Clone the repository
524        self.git_manager
525            .clone_repository(url, &repo_path, None)
526            .await
527            .map_err(|e| {
528                Git2DBError::repository(&repo_path, format!("Failed to clone repository: {e}"))
529            })?;
530
531        // Register the repository using the builder API
532        let repo_path = self.base_dir.join(repo_id.0.to_string());
533        self.register(repo_id.clone())
534            .name(name)
535            .url(url)
536            .worktree_path(repo_path)
537            .exec()
538            .await?;
539
540        Ok(())
541    }
542
543    /// Register a repository that was cloned to a UUID directory
544    ///
545    /// **DEPRECATED:** Use `registry.register(repo_id)` builder instead.
546    ///
547    /// This method assumes the repository is at `base_dir/{uuid}/` which doesn't
548    /// work for worktrees at custom paths. Use the builder for flexibility:
549    ///
550    /// ```rust,ignore
551    /// registry.register(repo_id)
552    ///     .name("my-repo")
553    ///     .worktree_path(actual_path)
554    ///     .exec().await?;
555    /// ```
556    #[deprecated(
557        since = "2.1.0",
558        note = "Use `registry.register(repo_id)` builder instead"
559    )]
560    pub async fn register_repository(
561        &mut self,
562        repo_id: &RepoId,
563        name: Option<String>,
564        url: String,
565    ) -> Git2DBResult<()> {
566        // Check if UUID is already registered
567        if self.metadata.repositories.contains_key(&repo_id.0) {
568            warn!(
569                "Repository with UUID {} is already registered, skipping",
570                repo_id.0
571            );
572            return Ok(());
573        }
574        if let Some(name) = name.as_deref() {
575            if self.get_by_name(name).is_some() {
576                return Err(Git2DBError::invalid_repository(
577                    repo_id.to_string(),
578                    "Repository name is already registered",
579                ));
580            }
581        }
582
583        // Path to the actual repository
584        let repo_path = self.base_dir.join(repo_id.0.to_string());
585        if !repo_path.exists() {
586            return Err(Git2DBError::invalid_repository(
587                repo_id.to_string(),
588                "Repository directory does not exist",
589            ));
590        }
591
592        // Add as submodule (relative path from .registry)
593        // For register_repository, the repo is always at <uuid> location
594        let relative_path = format!("../{}", repo_id.0);
595        let submodule_path = format!("repos/{}", repo_id.0);
596
597        // Check if submodule already exists
598        let repo = self.open_repo()?;
599        if repo.find_submodule(&submodule_path).is_ok() {
600            warn!("Submodule {} already exists, skipping", submodule_path);
601        } else {
602            // Add submodule
603            repo.submodule(
604                &relative_path,
605                Path::new(&submodule_path),
606                true, // use gitlink
607            )
608            .map_err(|e| {
609                Git2DBError::submodule(repo_id.to_string(), format!("Failed to add submodule: {e}"))
610            })?;
611        }
612
613        // Update metadata
614        self.metadata.repositories.insert(
615            repo_id.0,
616            TrackedRepository {
617                id: repo_id.clone(),
618                name,
619                url: url.clone(),
620                worktree_path: repo_path.clone(),
621                tracking_ref: GitRef::DefaultBranch,
622                remotes: vec![RemoteConfig::new("origin", url)],
623                registered_at: Utc::now().timestamp(),
624                current_oid: None,
625                metadata: HashMap::new(),
626            },
627        );
628
629        // Save metadata and commit
630        self.save_metadata().await?;
631        self.commit_changes(&format!("Register repository: {}", repo_id.0))?;
632
633        info!("Registered repository with UUID {}", repo_id.0);
634        Ok(())
635    }
636
637    /// Internal registration method with full configuration
638    ///
639    /// Used by both CloneBuilder and RegistrationBuilder.
640    /// External callers should use `registry.register(repo_id)` builder.
641    #[allow(clippy::too_many_arguments)]
642    pub(crate) async fn register_repository_internal(
643        &mut self,
644        repo_id: RepoId,
645        name: Option<String>,
646        url: String,
647        worktree_path: PathBuf,
648        tracking_ref: GitRef,
649        remotes: Vec<RemoteConfig>,
650        metadata: std::collections::HashMap<String, String>,
651    ) -> Git2DBResult<()> {
652        // Check if UUID is already registered
653        if self.metadata.repositories.contains_key(&repo_id.0) {
654            warn!(
655                "Repository with UUID {} is already registered, skipping",
656                repo_id.0
657            );
658            return Ok(());
659        }
660        // Both RegistrationBuilder and CloneBuilder end here under their
661        // caller's write lock. A pre-clone read check alone loses the race
662        // when another registration commits during the network clone.
663        if let Some(name) = name.as_deref() {
664            if self.get_by_name(name).is_some() {
665                return Err(Git2DBError::invalid_repository(
666                    repo_id.to_string(),
667                    "Repository name is already registered",
668                ));
669            }
670        }
671
672        // Verify path exists
673        if !worktree_path.exists() {
674            return Err(Git2DBError::invalid_repository(
675                repo_id.to_string(),
676                "Repository directory does not exist",
677            ));
678        }
679
680        // The first Registry response and initial PDS publication must carry
681        // the same commit as the already-existing Git worktree. A repository
682        // with an unborn HEAD remains registerable and has no initial pointer.
683        let existing_repo = Repository::open(&worktree_path).map_err(|error| {
684            Git2DBError::repository(&worktree_path, format!("Open Git worktree: {error}"))
685        })?;
686        let current_oid = match existing_repo.head() {
687            Ok(head) => Some(
688                head.peel_to_commit()
689                    .map_err(|error| {
690                        Git2DBError::repository(&worktree_path, format!("Read Git HEAD: {error}"))
691                    })?
692                    .id()
693                    .to_string(),
694            ),
695            Err(error)
696                if matches!(
697                    error.code(),
698                    git2::ErrorCode::UnbornBranch | git2::ErrorCode::NotFound
699                ) =>
700            {
701                None
702            }
703            Err(error) => {
704                return Err(Git2DBError::repository(
705                    &worktree_path,
706                    format!("Read Git HEAD: {error}"),
707                ));
708            }
709        };
710
711        // Add as submodule (relative path from .registry)
712        // Use the actual worktree path to calculate the relative path
713        let worktree_name = worktree_path
714            .file_name()
715            .and_then(|n| n.to_str())
716            .ok_or_else(|| Git2DBError::internal("Invalid worktree path"))?;
717        let relative_path = format!("../{worktree_name}");
718        let submodule_path = format!("repos/{}", repo_id.0);
719
720        // Check if submodule already exists
721        let repo = self.open_repo()?;
722        if repo.find_submodule(&submodule_path).is_ok() {
723            warn!("Submodule {} already exists, skipping", submodule_path);
724        } else {
725            // Add submodule
726            repo.submodule(
727                &relative_path,
728                Path::new(&submodule_path),
729                true, // use gitlink
730            )
731            .map_err(|e| {
732                Git2DBError::submodule(repo_id.to_string(), format!("Failed to add submodule: {e}"))
733            })?;
734        }
735
736        // Update metadata with full configuration
737        self.metadata.repositories.insert(
738            repo_id.0,
739            TrackedRepository {
740                id: repo_id.clone(),
741                name,
742                url,
743                worktree_path,
744                tracking_ref,
745                remotes,
746                registered_at: Utc::now().timestamp(),
747                current_oid,
748                metadata,
749            },
750        );
751
752        // Save metadata and commit
753        self.save_metadata().await?;
754        self.commit_changes(&format!("Register repository: {}", repo_id.0))?;
755
756        info!(
757            "Registered repository with UUID {} (full config)",
758            repo_id.0
759        );
760        Ok(())
761    }
762
763    /// Remove a repository from the registry with complete cleanup
764    ///
765    /// This performs proper git submodule cleanup including:
766    /// - Removes from .gitmodules
767    /// - Removes from .git/config
768    /// - Removes .git/modules/{id}/ directory
769    /// - Removes working directory
770    /// - Removes from registry metadata
771    ///
772    /// Similar to `git submodule deinit --force <name> && git rm --force <name>`
773    ///
774    /// # Examples
775    ///
776    /// ```rust,no_run
777    /// # async fn example(registry: &mut git2db::Git2DB, id: &git2db::RepoId) -> Result<(), Box<dyn std::error::Error>> {
778    /// registry.remove_repository(id).await?;
779    /// # Ok(())
780    /// # }
781    /// ```
782    pub async fn remove_repository(&mut self, id: &RepoId) -> Git2DBResult<()> {
783        // Guard: cannot remove the self-tracked .registry entry
784        if id.0 == registry_self_uuid() {
785            return Err(Git2DBError::internal(
786                "Cannot remove the self-tracked .registry entry",
787            ));
788        }
789
790        // Get repository info before removal
791        let repo_info = self
792            .get_by_id(id)
793            .ok_or_else(|| Git2DBError::invalid_repository(id.to_string(), "Repository not found"))?
794            .clone();
795
796        info!("Removing repository {}", id);
797
798        let submodule_path = format!("repos/{}", id.0);
799        let worktree_path = repo_info.worktree_path.clone();
800
801        // Open registry repository
802        let repo = self.open_repo()?;
803
804        // 1. Remove submodule from git (handles .gitmodules, .git/config, .git/modules cleanup)
805        if let Ok(mut submodule) = repo.find_submodule(&submodule_path) {
806            debug!("Removing submodule {}", submodule_path);
807
808            // Deinitialize submodule (removes from .git/config)
809            match submodule.init(false) {
810                Ok(_) => {}
811                Err(e) => warn!(
812                    "Failed to deinit submodule (may already be deinitialized): {}",
813                    e
814                ),
815            }
816
817            // Remove submodule (removes from .gitmodules and working directory)
818            // Note: libgit2 doesn't have a direct remove_submodule, so we do manual cleanup
819
820            // Remove .git/modules/{id} directory
821            let modules_dir = self
822                .registry_path
823                .join(".git")
824                .join("modules")
825                .join(id.to_string());
826            if modules_dir.exists() {
827                // I4 fix: Containment check before remove_dir_all
828                self.validate_within_base(&modules_dir)?;
829                debug!("Removing git modules directory: {:?}", modules_dir);
830                fs::remove_dir_all(&modules_dir).await.map_err(|e| {
831                    Git2DBError::internal(format!("Failed to remove .git/modules/{id}: {e}"))
832                })?;
833            }
834
835            // Remove from .gitmodules manually (libgit2 submodule API is limited)
836            let gitmodules_path = self.registry_path.join(".gitmodules");
837            if gitmodules_path.exists() {
838                let content = fs::read_to_string(&gitmodules_path).await.map_err(|e| {
839                    Git2DBError::internal(format!("Failed to read .gitmodules: {e}"))
840                })?;
841
842                // Filter out the entire [submodule "repos/{id}"] section
843                let mut new_content = String::new();
844                let mut skip_section = false;
845                let section_marker = format!("[submodule \"repos/{}\"", id.0);
846
847                for line in content.lines() {
848                    // Check if this is the start of the submodule section we want to remove
849                    if line.starts_with(&section_marker) {
850                        skip_section = true;
851                        continue;
852                    }
853                    // Check if we've reached a new section
854                    if line.starts_with('[') && skip_section {
855                        skip_section = false;
856                    }
857                    // Only include lines not in the skipped section
858                    if !skip_section {
859                        new_content.push_str(line);
860                        new_content.push('\n');
861                    }
862                }
863
864                // Remove trailing newline if content is now empty
865                let final_content = new_content.trim_end();
866
867                if final_content.is_empty() {
868                    // Remove .gitmodules file if it's now empty
869                    fs::remove_file(&gitmodules_path).await.map_err(|e| {
870                        Git2DBError::internal(format!("Failed to remove empty .gitmodules: {e}"))
871                    })?;
872                } else {
873                    fs::write(&gitmodules_path, final_content)
874                        .await
875                        .map_err(|e| {
876                            Git2DBError::internal(format!("Failed to update .gitmodules: {e}"))
877                        })?;
878                }
879            }
880
881            // Remove submodule working directory from registry
882            let submodule_work_path = self.registry_path.join(&submodule_path);
883            if submodule_work_path.exists() {
884                // I4 fix: Containment check before remove_dir_all
885                self.validate_within_base(&submodule_work_path)?;
886                debug!(
887                    "Removing submodule working directory: {:?}",
888                    submodule_work_path
889                );
890                fs::remove_dir_all(&submodule_work_path)
891                    .await
892                    .map_err(|e| {
893                        Git2DBError::internal(format!("Failed to remove submodule directory: {e}"))
894                    })?;
895            }
896        } else {
897            warn!(
898                "Submodule {} not found in registry repo, continuing cleanup",
899                submodule_path
900            );
901        }
902
903        // 2. Remove actual repository working directory
904        if worktree_path.exists() {
905            // I4 fix: Containment check before remove_dir_all
906            self.validate_within_base(&worktree_path)?;
907            debug!("Removing repository working directory: {:?}", worktree_path);
908            fs::remove_dir_all(&worktree_path).await.map_err(|e| {
909                Git2DBError::repository(
910                    &worktree_path,
911                    format!("Failed to remove repository directory: {e}"),
912                )
913            })?;
914        }
915
916        // 3. Remove from metadata
917        self.metadata.repositories.remove(&id.0);
918
919        // 4. Save metadata and commit
920        self.save_metadata().await?;
921        self.commit_changes(&format!("Remove repository: {}", id.0))?;
922
923        info!("Successfully removed repository {}", id);
924        Ok(())
925    }
926
927    /// Upsert a repository by name (add if missing, return existing if present)
928    ///
929    /// This operation embodies git's philosophy that "something is there but maybe you just don't know it yet".
930    /// If a repository with the given name exists, returns its ID. Otherwise, clones and registers it.
931    ///
932    /// # Examples
933    ///
934    /// ```rust,no_run
935    /// # async fn example(registry: &mut git2db::Git2DB) -> Result<(), Box<dyn std::error::Error>> {
936    /// // First call clones the repository
937    /// let id1 = registry.upsert_repository("my-repo", "https://github.com/user/repo.git").await?;
938    ///
939    /// // Second call returns the same ID without cloning
940    /// let id2 = registry.upsert_repository("my-repo", "https://github.com/user/repo.git").await?;
941    /// assert_eq!(id1, id2);
942    /// # Ok(())
943    /// # }
944    /// ```
945    pub async fn upsert_repository(&mut self, name: &str, url: &str) -> Git2DBResult<RepoId> {
946        // Check if repository with this name already exists
947        if let Some(existing) = self.get_by_name(name) {
948            info!(
949                "Repository '{}' already exists with ID {}",
950                name, existing.id
951            );
952
953            // Optionally update URL if different
954            if existing.url != url {
955                warn!(
956                    "Repository '{}' exists with different URL. Existing: {}, Requested: {}",
957                    name, existing.url, url
958                );
959                // For now, just return existing ID. In the future, could update remotes.
960            }
961
962            return Ok(existing.id.clone());
963        }
964
965        // Repository doesn't exist, add it
966        info!("Repository '{}' not found, adding from {}", name, url);
967        self.add_repository(name, url).await
968    }
969
970    /// Update a repository's configuration
971    ///
972    /// Allows updating URL, tracking ref, or remotes for an existing repository.
973    ///
974    /// # Examples
975    ///
976    /// ```rust,ignore
977    /// // Update the primary URL
978    /// registry.update_repository(id, Some("https://new-host.com/repo.git".to_owned())).await?;
979    ///
980    /// // Refresh without changing URL
981    /// registry.update_repository(id, None).await?;
982    /// ```
983    pub async fn update_repository(
984        &mut self,
985        id: &RepoId,
986        new_url: Option<String>,
987    ) -> Git2DBResult<()> {
988        // Get mutable reference to repository metadata
989        let repo = self.metadata.repositories.get_mut(&id.0).ok_or_else(|| {
990            Git2DBError::invalid_repository(id.to_string(), "Repository not found")
991        })?;
992
993        // Update URL if provided
994        if let Some(url) = new_url {
995            info!("Updating repository {} URL: {} -> {}", id, repo.url, url);
996            repo.url = url.clone();
997
998            // Update origin remote config
999            if let Some(origin) = repo.remotes.iter_mut().find(|r| r.name == "origin") {
1000                origin.url = url;
1001            }
1002        }
1003
1004        // Save and commit changes
1005        self.save_metadata().await?;
1006        self.commit_changes(&format!("Update repository: {}", id.0))?;
1007
1008        Ok(())
1009    }
1010
1011    /// Register an existing repository or worktree using fluent builder API
1012    ///
1013    /// Returns a builder for configuring registration parameters.
1014    /// Use this to register repos/worktrees at custom paths.
1015    ///
1016    /// # Examples
1017    ///
1018    /// ```rust,ignore
1019    /// // Register a worktree (adapter)
1020    /// registry.register(adapter_id)
1021    ///     .name("my-adapter")
1022    ///     .worktree_path(worktree_path)
1023    ///     .tracking_ref(GitRef::Branch("adapter/uuid".to_owned()))
1024    ///     .metadata("type", "adapter")
1025    ///     .exec()
1026    ///     .await?;
1027    /// ```
1028    pub fn register<'a>(
1029        &'a mut self,
1030        repo_id: RepoId,
1031    ) -> crate::registration_builder::RegistrationBuilder<'a> {
1032        crate::registration_builder::RegistrationBuilder::new(self, repo_id)
1033    }
1034
1035    /// Get the base directory where repositories are stored
1036    pub fn base_dir(&self) -> &Path {
1037        &self.base_dir
1038    }
1039
1040    /// List all repositories in the registry
1041    pub fn list(&self) -> impl Iterator<Item = &TrackedRepository> {
1042        self.metadata.repositories.values()
1043    }
1044
1045    /// Get repository by name
1046    pub fn get_by_name(&self, name: &str) -> Option<&TrackedRepository> {
1047        self.metadata
1048            .repositories
1049            .values()
1050            .find(|repo| repo.name.as_ref().map(|n| n == name).unwrap_or(false))
1051    }
1052
1053    /// Get repository by ID
1054    pub fn get_by_id(&self, id: &RepoId) -> Option<&TrackedRepository> {
1055        self.metadata.repositories.get(&id.0)
1056    }
1057
1058    /// Get repository worktree path
1059    pub fn get_worktree_path(&self, id: &RepoId) -> Option<PathBuf> {
1060        self.get_by_id(id).map(|repo| repo.worktree_path.clone())
1061    }
1062
1063    /// Get a handle to a repository by ID
1064    pub fn repo(&self, id: &RepoId) -> Git2DBResult<RepositoryHandle<'_>> {
1065        if self.get_by_id(id).is_none() {
1066            return Err(Git2DBError::invalid_repository(
1067                id.to_string(),
1068                "Repository not found",
1069            ));
1070        }
1071        Ok(RepositoryHandle::new(self, id.clone()))
1072    }
1073
1074    /// Get a handle to a repository by name
1075    pub fn repo_by_name(&self, name: &str) -> Git2DBResult<RepositoryHandle<'_>> {
1076        let repo = self
1077            .get_by_name(name)
1078            .ok_or_else(|| Git2DBError::invalid_repository(name, "Repository not found"))?;
1079        Ok(RepositoryHandle::new(self, repo.id.clone()))
1080    }
1081
1082    /// Get registry path
1083    pub fn registry_path(&self) -> &Path {
1084        &self.registry_path
1085    }
1086
1087    /// Validate that a path is within the base directory (I4 fix).
1088    ///
1089    /// Prevents `remove_dir_all` from being tricked into deleting outside the registry.
1090    fn validate_within_base(&self, path: &Path) -> Git2DBResult<()> {
1091        let canonical_target = path.canonicalize().map_err(|e| {
1092            Git2DBError::internal(format!("Failed to canonicalize target {:?}: {e}", path))
1093        })?;
1094        let canonical_base = self.base_dir.canonicalize().map_err(|e| {
1095            Git2DBError::internal(format!(
1096                "Failed to canonicalize base {:?}: {e}",
1097                self.base_dir
1098            ))
1099        })?;
1100        if !canonical_target.starts_with(&canonical_base) {
1101            return Err(Git2DBError::internal(format!(
1102                "Path {:?} is outside base directory {:?}",
1103                canonical_target, canonical_base
1104            )));
1105        }
1106        Ok(())
1107    }
1108
1109    /// Initialize and update all submodules
1110    ///
1111    /// Equivalent to:
1112    /// ```bash
1113    /// git submodule init
1114    /// git submodule update --init
1115    /// ```
1116    ///
1117    /// This ensures all tracked repositories (stored as submodules) are cloned
1118    /// and checked out to the correct commit.
1119    async fn init_submodules(&self) -> Git2DBResult<()> {
1120        let registry_path = self.registry_path.clone();
1121
1122        tokio::task::spawn_blocking(move || -> Git2DBResult<()> {
1123            let repo = Repository::open(&registry_path).map_err(|e| {
1124                Git2DBError::repository(&registry_path, format!("Failed to open registry: {e}"))
1125            })?;
1126
1127            // Get all submodules
1128            let submodules = repo.submodules().map_err(|e| {
1129                Git2DBError::submodule("*", format!("Failed to list submodules: {e}"))
1130            })?;
1131
1132            if submodules.is_empty() {
1133                debug!("No submodules found in registry");
1134                return Ok(());
1135            }
1136
1137            info!("Initializing {} submodule(s)", submodules.len());
1138
1139            for mut submodule in submodules {
1140                let name = submodule.name().unwrap_or("unknown").to_owned();
1141
1142                // Check if submodule is checked out by trying to open it
1143                let needs_init = submodule.open().is_err();
1144
1145                if needs_init {
1146                    debug!("Initializing submodule: {}", name);
1147
1148                    // Initialize (adds to .git/config)
1149                    if let Err(e) = submodule.init(false) {
1150                        warn!("Failed to init submodule '{}': {}", name, e);
1151                        continue;
1152                    }
1153
1154                    // Update (clone + checkout)
1155                    let mut update_opts = git2::SubmoduleUpdateOptions::new();
1156                    if let Err(e) = submodule.update(true, Some(&mut update_opts)) {
1157                        warn!("Failed to update submodule '{}': {}", name, e);
1158                        continue;
1159                    }
1160
1161                    info!("Initialized submodule: {}", name);
1162                } else {
1163                    trace!("Submodule '{}' already initialized", name);
1164                }
1165            }
1166
1167            Ok(())
1168        })
1169        .await
1170        .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
1171    }
1172
1173    /// Save metadata to disk
1174    async fn save_metadata(&self) -> Git2DBResult<()> {
1175        let metadata_path = self.registry_path.join("registry.json");
1176
1177        let json = serde_json::to_string_pretty(&self.metadata)
1178            .map_err(|e| Git2DBError::internal(format!("Failed to serialize metadata: {e}")))?;
1179        fs::write(&metadata_path, json).await.map_err(|e| {
1180            Git2DBError::repository(
1181                &self.registry_path,
1182                format!("Failed to write registry.json: {e}"),
1183            )
1184        })?;
1185
1186        // Ensure restrictive permissions after every write (write resets to umask)
1187        #[cfg(unix)]
1188        {
1189            use std::os::unix::fs::PermissionsExt;
1190            let _ =
1191                fs::set_permissions(&metadata_path, std::fs::Permissions::from_mode(0o600)).await;
1192        }
1193
1194        Ok(())
1195    }
1196
1197    /// Commit changes to registry
1198    ///
1199    /// This method stages and commits all changes. If the commit fails, staged changes
1200    /// remain in the index and will be recovered on the next registry open.
1201    fn commit_changes(&self, message: &str) -> Git2DBResult<()> {
1202        let repo = self.open_repo()?;
1203
1204        // Create signature early to fail fast if this is misconfigured
1205        let sig = self.git_manager.create_signature(None, None).map_err(|e| {
1206            Git2DBError::internal(format!(
1207                "Failed to create git signature (check git config): {e}"
1208            ))
1209        })?;
1210
1211        // Stage all changes
1212        let mut index = repo.index().map_err(|e| {
1213            Git2DBError::repository(&self.registry_path, format!("Failed to get index: {e}"))
1214        })?;
1215
1216        index
1217            .add_all(["*"].iter(), IndexAddOption::DEFAULT, None)
1218            .map_err(|e| {
1219                Git2DBError::repository(
1220                    &self.registry_path,
1221                    format!("Failed to stage changes: {e}"),
1222                )
1223            })?;
1224        index.write().map_err(|e| {
1225            Git2DBError::repository(&self.registry_path, format!("Failed to write index: {e}"))
1226        })?;
1227
1228        let tree_id = index.write_tree().map_err(|e| {
1229            Git2DBError::repository(&self.registry_path, format!("Failed to write tree: {e}"))
1230        })?;
1231        let tree = repo.find_tree(tree_id).map_err(|e| {
1232            Git2DBError::repository(&self.registry_path, format!("Failed to find tree: {e}"))
1233        })?;
1234
1235        // Get parent commit with proper error handling
1236        let parent_commit = match repo.head() {
1237            Ok(head) => Some(head.peel_to_commit().map_err(|e| {
1238                Git2DBError::repository(
1239                    &self.registry_path,
1240                    format!("Failed to peel HEAD to commit: {e}"),
1241                )
1242            })?),
1243            Err(e) if e.code() == git2::ErrorCode::UnbornBranch => {
1244                // No commits yet, this is fine
1245                None
1246            }
1247            Err(e) => {
1248                return Err(Git2DBError::repository(
1249                    &self.registry_path,
1250                    format!("Failed to get HEAD: {e}"),
1251                ));
1252            }
1253        };
1254
1255        let parent_commits: Vec<&git2::Commit> =
1256            parent_commit.as_ref().map(|c| vec![c]).unwrap_or_default();
1257
1258        // Create the commit
1259        repo.commit(
1260            Some("HEAD"),
1261            &sig,
1262            &sig,
1263            message,
1264            &tree,
1265            &parent_commits,
1266        ).map_err(|e| Git2DBError::repository(&self.registry_path,
1267            format!("Failed to create commit '{message}': {e}. Staged changes remain in index and will be recovered on next open.")))?;
1268
1269        debug!("Committed to registry: {}", message);
1270        Ok(())
1271    }
1272
1273    /// Recover from uncommitted changes left by interrupted operations
1274    ///
1275    /// This detects if there are staged changes without a corresponding commit
1276    /// and either commits them or resets the index depending on the situation.
1277    fn recover_uncommitted_changes(&mut self) -> Git2DBResult<()> {
1278        let repo = self.open_repo()?;
1279
1280        // Check if there are staged changes
1281        let statuses = repo.statuses(None).map_err(|e| {
1282            Git2DBError::repository(&self.registry_path, format!("Failed to get status: {e}"))
1283        })?;
1284
1285        let has_staged_changes = statuses.iter().any(|s| {
1286            s.status().intersects(
1287                git2::Status::INDEX_NEW
1288                    | git2::Status::INDEX_MODIFIED
1289                    | git2::Status::INDEX_DELETED,
1290            )
1291        });
1292
1293        if !has_staged_changes {
1294            return Ok(()); // Nothing to recover
1295        }
1296
1297        info!("Detecting staged but uncommitted changes in registry, attempting recovery...");
1298
1299        // Try to commit the staged changes with a recovery message
1300        let sig = self.git_manager.create_signature(None, None).map_err(|e| {
1301            Git2DBError::internal(format!("Failed to create signature for recovery: {e}"))
1302        })?;
1303
1304        let mut index = repo.index().map_err(|e| {
1305            Git2DBError::repository(&self.registry_path, format!("Failed to get index: {e}"))
1306        })?;
1307
1308        let tree_id = index.write_tree().map_err(|e| {
1309            Git2DBError::repository(
1310                &self.registry_path,
1311                format!("Failed to write tree during recovery: {e}"),
1312            )
1313        })?;
1314        let tree = repo.find_tree(tree_id).map_err(|e| {
1315            Git2DBError::repository(
1316                &self.registry_path,
1317                format!("Failed to find tree during recovery: {e}"),
1318            )
1319        })?;
1320
1321        let parent_commit = match repo.head() {
1322            Ok(head) => Some(head.peel_to_commit().map_err(|e| {
1323                Git2DBError::repository(
1324                    &self.registry_path,
1325                    format!("Failed to peel HEAD during recovery: {e}"),
1326                )
1327            })?),
1328            Err(_) => None,
1329        };
1330
1331        let parent_commits: Vec<&git2::Commit> =
1332            parent_commit.as_ref().map(|c| vec![c]).unwrap_or_default();
1333
1334        // Commit the recovered changes
1335        repo.commit(
1336            Some("HEAD"),
1337            &sig,
1338            &sig,
1339            "[git2db recovery] Commit staged changes from interrupted operation",
1340            &tree,
1341            &parent_commits,
1342        )
1343        .map_err(|e| {
1344            Git2DBError::repository(
1345                &self.registry_path,
1346                format!("Failed to commit during recovery: {e}"),
1347            )
1348        })?;
1349
1350        info!("Successfully recovered uncommitted changes in registry");
1351
1352        // Reload metadata to reflect recovered state
1353        let metadata_path = self.registry_path.join("registry.json");
1354        if metadata_path.exists() {
1355            let content = std::fs::read_to_string(&metadata_path).map_err(|e| {
1356                Git2DBError::repository(
1357                    &self.registry_path,
1358                    format!("Failed to read registry.json during recovery: {e}"),
1359                )
1360            })?;
1361            self.metadata = serde_json::from_str(&content).map_err(|e| {
1362                Git2DBError::repository(
1363                    &self.registry_path,
1364                    format!("Failed to parse registry.json during recovery: {e}"),
1365                )
1366            })?;
1367        }
1368
1369        Ok(())
1370    }
1371}
1372
1373#[cfg(test)]
1374mod tests {
1375    use super::*;
1376    use tempfile::TempDir;
1377
1378    #[tokio::test]
1379    async fn new_registry_ignores_runtime_private_state() -> crate::Git2DBResult<()> {
1380        let base = TempDir::new()?;
1381        let registry = Git2DB::open(base.path()).await?;
1382        let root = registry.registry_path();
1383        std::fs::create_dir_all(root.join("pds"))?;
1384        std::fs::create_dir_all(root.join("pds-store"))?;
1385        for path in [
1386            "pds/atproto-signing-key",
1387            "pds-store/private-fixture",
1388            "sessions.jsonl",
1389            "credential-revocations.jsonl",
1390        ] {
1391            std::fs::write(root.join(path), "private fixture")?;
1392        }
1393        std::fs::create_dir_all(root.join("policies"))?;
1394        std::fs::write(root.join("policies/policy.csv"), "policy fixture")?;
1395        let repo = registry.open_repo()?;
1396        let mut index = repo.index()?;
1397        index.add_all(["."], IndexAddOption::DEFAULT, None)?;
1398        assert!(index
1399            .get_path(Path::new("policies/policy.csv"), 0)
1400            .is_some());
1401        for path in [
1402            "pds/atproto-signing-key",
1403            "pds-store/private-fixture",
1404            "sessions.jsonl",
1405            "credential-revocations.jsonl",
1406        ] {
1407            assert!(index.get_path(Path::new(path), 0).is_none());
1408        }
1409        Ok(())
1410    }
1411
1412    #[tokio::test]
1413    async fn existing_registry_broad_commit_ignores_private_state() -> crate::Git2DBResult<()> {
1414        let base = TempDir::new()?;
1415        let registry = Git2DB::open(base.path()).await?;
1416        let root = registry.registry_path().to_path_buf();
1417        // Represent a pre-fix repository with custom rules, including an old
1418        // unignore. No fixture content is secret.
1419        std::fs::write(root.join(".gitignore"), "*.tmp\n!/pds/\n")?;
1420        std::fs::create_dir_all(root.join("pds"))?;
1421        std::fs::create_dir_all(root.join("pds-store"))?;
1422        for path in [
1423            "pds/atproto-signing-key",
1424            "pds-store/private-fixture",
1425            "sessions.jsonl",
1426            "credential-revocations.jsonl",
1427        ] {
1428            std::fs::write(root.join(path), "private fixture")?;
1429        }
1430        drop(registry);
1431
1432        let registry = Git2DB::open(base.path()).await?;
1433        let ignore = std::fs::read_to_string(root.join(".gitignore"))?;
1434        assert!(ignore.starts_with("*.tmp\n!/pds/\n"));
1435        assert!(ignore.ends_with(REGISTRY_RUNTIME_IGNORES));
1436        std::fs::write(root.join("test.txt"), "public fixture")?;
1437        registry.commit_changes("metadata fixture")?;
1438        let repo = registry.open_repo()?;
1439        let tree = repo.head()?.peel_to_tree()?;
1440        assert!(tree.get_path(Path::new("test.txt")).is_ok());
1441        for path in [
1442            "pds/atproto-signing-key",
1443            "pds-store/private-fixture",
1444            "sessions.jsonl",
1445            "credential-revocations.jsonl",
1446        ] {
1447            assert!(tree.get_path(Path::new(path)).is_err());
1448        }
1449        drop(registry);
1450        Git2DB::open(base.path()).await?;
1451        assert_eq!(std::fs::read_to_string(root.join(".gitignore"))?, ignore);
1452        Ok(())
1453    }
1454
1455    #[tokio::test]
1456    async fn test_recovery_from_uncommitted_changes() -> crate::Git2DBResult<()> {
1457        // Create a temporary directory for testing
1458        let temp_dir = TempDir::new()?;
1459        let base_dir = temp_dir.path().to_path_buf();
1460
1461        // Create initial registry
1462        let mut registry = Git2DB::open(&base_dir).await?;
1463
1464        // Simulate interrupted operation by manually staging changes without committing
1465        {
1466            let repo = registry.open_repo()?;
1467            let test_file = registry.registry_path().join("test_uncommitted.txt");
1468            std::fs::write(&test_file, "uncommitted data")?;
1469
1470            let mut index = repo.index()?;
1471            index.add_path(Path::new("test_uncommitted.txt"))?;
1472            index.write()?;
1473        }
1474
1475        // Verify there are staged changes
1476        {
1477            let repo = registry.open_repo()?;
1478            let statuses = repo.statuses(None)?;
1479            let has_staged = statuses
1480                .iter()
1481                .any(|s| s.status().intersects(git2::Status::INDEX_NEW));
1482            assert!(has_staged, "Should have staged changes before recovery");
1483        }
1484
1485        // Call recovery mechanism
1486        registry.recover_uncommitted_changes()?;
1487
1488        // Verify staged changes were committed
1489        {
1490            let repo = registry.open_repo()?;
1491            let statuses = repo.statuses(None)?;
1492            let has_staged = statuses.iter().any(|s| {
1493                s.status()
1494                    .intersects(git2::Status::INDEX_NEW | git2::Status::INDEX_MODIFIED)
1495            });
1496            assert!(!has_staged, "Should have no staged changes after recovery");
1497
1498            // Verify commit was created
1499            let head = repo.head()?;
1500            let commit = head.peel_to_commit()?;
1501            let msg = commit
1502                .message()
1503                .ok_or_else(|| crate::Git2DBError::internal("no commit message"))?;
1504            assert!(msg.contains("recovery"), "Recovery commit should exist");
1505        }
1506        Ok(())
1507    }
1508
1509    #[tokio::test]
1510    async fn test_recovery_does_nothing_when_no_staged_changes() -> crate::Git2DBResult<()> {
1511        let temp_dir = TempDir::new()?;
1512        let base_dir = temp_dir.path().to_path_buf();
1513
1514        let mut registry = Git2DB::open(&base_dir).await?;
1515
1516        // Get initial commit count
1517        let initial_commit_count = {
1518            let repo = registry.open_repo()?;
1519            let count = repo.revwalk()?.count();
1520            count
1521        };
1522
1523        // Call recovery when there are no staged changes
1524        registry.recover_uncommitted_changes()?;
1525
1526        // Verify no new commit was created
1527        let final_commit_count = {
1528            let repo = registry.open_repo()?;
1529            let count = repo.revwalk()?.count();
1530            count
1531        };
1532
1533        assert_eq!(
1534            initial_commit_count, final_commit_count,
1535            "Recovery should not create commit when no staged changes"
1536        );
1537        Ok(())
1538    }
1539
1540    #[tokio::test]
1541    async fn test_automatic_recovery_on_open() -> crate::Git2DBResult<()> {
1542        let temp_dir = TempDir::new()?;
1543        let base_dir = temp_dir.path().to_path_buf();
1544
1545        // Create registry and simulate interrupted operation
1546        {
1547            let registry = Git2DB::open(&base_dir).await?;
1548            let repo = registry.open_repo()?;
1549            let test_file = registry.registry_path().join("auto_recovery_test.txt");
1550            std::fs::write(&test_file, "test data")?;
1551
1552            let mut index = repo.index()?;
1553            index.add_path(Path::new("auto_recovery_test.txt"))?;
1554            index.write()?;
1555        }
1556
1557        // Reopen registry - should automatically recover
1558        let registry = Git2DB::open(&base_dir).await?;
1559
1560        // Verify recovery happened
1561        let repo = registry.open_repo()?;
1562        let statuses = repo.statuses(None)?;
1563        let has_staged = statuses.iter().any(|s| {
1564            s.status()
1565                .intersects(git2::Status::INDEX_NEW | git2::Status::INDEX_MODIFIED)
1566        });
1567        assert!(
1568            !has_staged,
1569            "Automatic recovery should have committed staged changes"
1570        );
1571        Ok(())
1572    }
1573}