codebase-graph 3.0.3

Native codebaseGraph CLI and MCP server for local code knowledge graphs.
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
use crate::error::NativeError;
use crate::storage::atomic::write_json_atomically;
use crate::storage::layout::managed_generation_id;
use crate::storage::locks::{open_locked, try_open_locked_in_existing_parent, LockMode, RunLease};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub(crate) enum RunPhase {
    Created,
    Staged,
    CandidateReady,
    Publishing,
    Published,
    Failed,
    CleanupPending,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct RunJournal {
    pub run_id: String,
    pub phase: RunPhase,
    #[serde(default)]
    pub base_generation_id: Option<String>,
    #[serde(default)]
    pub candidate_generation_id: Option<String>,
    #[serde(default)]
    pub active_generation_id: Option<String>,
    #[serde(default)]
    pub last_error: Option<String>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct RunWorkspaceRecovery {
    pub deleted: usize,
    pub skipped_locked: usize,
    pub publishing_recovered: usize,
}

#[derive(Debug)]
pub(crate) struct RunWorkspace {
    root: PathBuf,
    run_id: String,
    lease: Option<RunLease>,
    finished: bool,
    cleanup_barrier: Option<PathBuf>,
}

impl RunWorkspace {
    pub(crate) fn create(
        runs_root: impl AsRef<Path>,
        base_generation_id: Option<String>,
    ) -> Result<Self, NativeError> {
        let runs_root = runs_root.as_ref();
        fs::create_dir_all(runs_root)?;
        let run_id = managed_generation_id();
        let root = runs_root.join(format!("run-{run_id}"));
        fs::create_dir(&root)?;
        let lease = open_locked(root.join("lease.lock"), LockMode::Exclusive)?;
        let this = Self {
            root,
            run_id,
            lease: Some(lease),
            finished: false,
            cleanup_barrier: None,
        };
        this.write_journal(RunJournal {
            run_id: this.run_id.clone(),
            phase: RunPhase::Created,
            base_generation_id,
            candidate_generation_id: None,
            active_generation_id: None,
            last_error: None,
        })?;
        fs::create_dir_all(this.staging_root())?;
        fs::create_dir_all(this.candidate_root())?;
        Ok(this)
    }

    pub(crate) fn set_cleanup_barrier(&mut self, root: PathBuf) -> Result<(), NativeError> {
        // Keep the in-memory guard even if persistence fails: Drop must retain
        // this run while its unknown phase can still own candidate files.
        self.cleanup_barrier = Some(root.clone());
        // Direct destinations retain their spelling for journal/lock keys.
        // Anchor only this derived private path so later janitors do not
        // reinterpret it relative to a different process working directory.
        let root = if root.is_absolute() {
            root
        } else {
            std::env::current_dir()?.join(root)
        };
        self.cleanup_barrier = Some(root.clone());
        write_json_atomically(&self.root.join("cleanup-barrier.json"), &root)
    }

    fn ensure_cleanup_allowed(&self) -> Result<(), NativeError> {
        if let Some(root) = &self.cleanup_barrier {
            crate::storage::containment::ensure_registry_empty(root)
                .map_err(NativeError::InvalidInput)?;
        }
        ensure_persisted_cleanup_allowed(&self.root)?;
        Ok(())
    }

    pub(crate) fn root(&self) -> &Path {
        &self.root
    }

    pub(crate) fn staging_root(&self) -> PathBuf {
        self.root.join("staging")
    }

    pub(crate) fn candidate_root(&self) -> PathBuf {
        self.root.join("candidate")
    }

    pub(crate) fn journal_path(&self) -> PathBuf {
        self.root.join("journal.json")
    }

    pub(crate) fn journal(&self) -> Result<RunJournal, NativeError> {
        let text = fs::read_to_string(self.journal_path())?;
        Ok(serde_json::from_str(&text)?)
    }

    pub(crate) fn register_candidate(
        &self,
        candidate_generation_id: String,
    ) -> Result<(), NativeError> {
        let mut journal = self.journal()?;
        journal.candidate_generation_id = Some(candidate_generation_id);
        journal.phase = RunPhase::Staged;
        self.write_journal(journal)
    }

    pub(crate) fn mark_candidate_ready(&self) -> Result<(), NativeError> {
        let mut journal = self.journal()?;
        if journal.candidate_generation_id.is_none() {
            return Err(NativeError::InvalidInput(
                "cannot mark candidate ready without a candidate generation id".to_string(),
            ));
        }
        journal.phase = RunPhase::CandidateReady;
        journal.last_error = None;
        self.write_journal(journal)
    }

    pub(crate) fn mark_phase(
        &self,
        phase: RunPhase,
        active_generation_id: Option<String>,
        last_error: Option<String>,
    ) -> Result<(), NativeError> {
        let mut journal = self.journal()?;
        journal.phase = phase;
        journal.active_generation_id = active_generation_id;
        journal.last_error = last_error;
        self.write_journal(journal)
    }

    pub(crate) fn finish(mut self) -> Result<(), NativeError> {
        self.finish_inner(None)
    }

    pub(crate) fn abort(mut self, error: Option<String>) -> Result<(), NativeError> {
        self.finish_inner(error)
    }

    pub(crate) fn cleanup_orphans(
        runs_root: impl AsRef<Path>,
    ) -> Result<RunWorkspaceRecovery, NativeError> {
        let runs_root = runs_root.as_ref();
        if !runs_root.exists() {
            return Ok(RunWorkspaceRecovery::default());
        }

        let mut report = RunWorkspaceRecovery::default();
        for entry in fs::read_dir(runs_root)? {
            let entry = entry?;
            let path = entry.path();
            if !entry.file_type()?.is_dir() {
                continue;
            }
            let Some(name) = path.file_name().and_then(|value| value.to_str()) else {
                continue;
            };
            if !name.starts_with("run-") {
                continue;
            }

            let lease_path = path.join("lease.lock");
            let lease = match try_open_locked_in_existing_parent(&lease_path, LockMode::Exclusive) {
                Ok(Some(lease)) => lease,
                Err(NativeError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => continue,
                Err(e) => return Err(e),
                Ok(None) => {
                    report.skipped_locked += 1;
                    continue;
                }
            };
            if ensure_persisted_cleanup_allowed(&path).is_err() {
                report.skipped_locked += 1;
                continue;
            }
            let journal = read_orphan_journal(&path, name)?;
            if journal.phase == RunPhase::Publishing {
                report.publishing_recovered += 1;
            }
            drop(lease);
            remove_run_tree(&path)?;
            report.deleted += 1;
        }
        Ok(report)
    }

    fn finish_inner(&mut self, primary_error: Option<String>) -> Result<(), NativeError> {
        if let Err(error) = self.ensure_cleanup_allowed() {
            self.finished = true;
            let _ = self.mark_cleanup_pending(primary_error, &error);
            drop(self.lease.take());
            return Err(error);
        }
        if let Some(error) = primary_error.clone() {
            self.mark_phase(RunPhase::Failed, None, Some(error))?;
        }
        self.finished = true;
        drop(self.lease.take());
        if let Err(cleanup_error) = remove_run_tree(&self.root) {
            self.mark_cleanup_pending(primary_error, &cleanup_error)?;
            return Err(cleanup_error);
        }
        Ok(())
    }

    fn mark_cleanup_pending(
        &self,
        primary_error: Option<String>,
        cleanup_error: &NativeError,
    ) -> Result<(), NativeError> {
        let message = match primary_error {
            Some(primary) => format!("{primary}; cleanup pending: {cleanup_error}"),
            None => format!("cleanup pending: {cleanup_error}"),
        };
        self.mark_phase(RunPhase::CleanupPending, None, Some(message))
    }

    fn write_journal(&self, journal: RunJournal) -> Result<(), NativeError> {
        write_json_atomically(&self.journal_path(), &journal)
    }
}

impl Drop for RunWorkspace {
    fn drop(&mut self) {
        if self.finished {
            return;
        }
        let _ = self.mark_phase(
            RunPhase::CleanupPending,
            None,
            Some("workspace dropped without finish or abort".to_string()),
        );
        drop(self.lease.take());
        if self.ensure_cleanup_allowed().is_ok() {
            let _ = remove_run_tree(&self.root);
        }
    }
}

fn ensure_persisted_cleanup_allowed(root: &Path) -> Result<(), NativeError> {
    let bytes = match fs::read(root.join("cleanup-barrier.json")) {
        Ok(bytes) => bytes,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(e.into()),
    };
    let barrier: PathBuf = serde_json::from_slice(&bytes).map_err(|e| {
        NativeError::InvalidInput(format!(
            "containment_unknown: invalid run cleanup barrier: {e}"
        ))
    })?;
    if !barrier.is_absolute() {
        return Err(NativeError::InvalidInput(
            "containment_unknown: run cleanup barrier has no absolute origin".to_string(),
        ));
    }
    crate::storage::containment::ensure_registry_empty(&barrier).map_err(NativeError::InvalidInput)
}

fn read_orphan_journal(path: &Path, name: &str) -> Result<RunJournal, NativeError> {
    let journal_path = path.join("journal.json");
    if !journal_path.exists() {
        return Ok(RunJournal {
            run_id: name.trim_start_matches("run-").to_string(),
            phase: RunPhase::CleanupPending,
            base_generation_id: None,
            candidate_generation_id: None,
            active_generation_id: None,
            last_error: Some("missing journal".to_string()),
        });
    }
    let text = fs::read_to_string(journal_path)?;
    Ok(serde_json::from_str(&text)?)
}

fn remove_run_tree(root: &Path) -> Result<(), NativeError> {
    let parent = root.parent().ok_or_else(|| {
        NativeError::InvalidInput(format!("run path {} has no parent", root.display()))
    })?;
    remove_run_root_confined(root, parent)
}

pub(super) fn remove_run_root_confined(root: &Path, runs_root: &Path) -> Result<(), NativeError> {
    let Some(metadata) = symlink_metadata_if_present(root)? else {
        return Ok(());
    };
    if metadata.file_type().is_symlink() {
        return Err(NativeError::InvalidInput(format!(
            "refusing to remove symlinked path {}",
            root.display()
        )));
    }

    let canonical_runs_root = fs::canonicalize(runs_root)?;
    let canonical_root = match fs::canonicalize(root) {
        Ok(path) => path,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(error) => return Err(error.into()),
    };
    if canonical_root.parent() != Some(canonical_runs_root.as_path()) {
        return Err(NativeError::InvalidInput(format!(
            "refusing to remove run path outside root: {}",
            root.display()
        )));
    }
    remove_path_without_symlinks(&canonical_root)
}

fn remove_path_without_symlinks(path: &Path) -> Result<(), NativeError> {
    validate_tree_has_no_symlinks(path)?;
    remove_validated_path(path)
}

fn validate_tree_has_no_symlinks(path: &Path) -> Result<(), NativeError> {
    let Some(metadata) = symlink_metadata_if_present(path)? else {
        return Ok(());
    };
    if metadata.file_type().is_symlink() {
        return Err(NativeError::InvalidInput(format!(
            "refusing to remove symlinked path {}",
            path.display()
        )));
    }
    if metadata.is_dir() {
        let entries = match fs::read_dir(path) {
            Ok(entries) => entries,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(error) => return Err(error.into()),
        };
        for entry in entries {
            let entry = match entry {
                Ok(entry) => entry,
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                Err(error) => return Err(error.into()),
            };
            validate_tree_has_no_symlinks(&entry.path())?;
        }
    }
    Ok(())
}

fn remove_validated_path(path: &Path) -> Result<(), NativeError> {
    let Some(metadata) = symlink_metadata_if_present(path)? else {
        return Ok(());
    };
    if metadata.file_type().is_symlink() {
        return Err(NativeError::InvalidInput(format!(
            "refusing to remove symlinked path {}",
            path.display()
        )));
    }
    if metadata.is_dir() {
        let entries = match fs::read_dir(path) {
            Ok(entries) => entries,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(error) => return Err(error.into()),
        };
        for entry in entries {
            let entry = match entry {
                Ok(entry) => entry,
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                Err(error) => return Err(error.into()),
            };
            remove_validated_path(&entry.path())?;
        }
        remove_dir_if_present(path)?;
    } else {
        remove_file_if_present(path)?;
    }
    Ok(())
}

fn symlink_metadata_if_present(path: &Path) -> Result<Option<fs::Metadata>, NativeError> {
    match fs::symlink_metadata(path) {
        Ok(metadata) => Ok(Some(metadata)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error.into()),
    }
}

fn remove_dir_if_present(path: &Path) -> Result<(), NativeError> {
    match fs::remove_dir(path) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error.into()),
    }
}

fn remove_file_if_present(path: &Path) -> Result<(), NativeError> {
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error.into()),
    }
}

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

    #[test]
    fn cleanup_barrier_records_its_absolute_origin() {
        let root = std::env::temp_dir().join(format!("run-origin-{}", managed_generation_id()));
        let mut workspace = RunWorkspace::create(root.join("runs"), None).unwrap();
        let relative = PathBuf::from("private-relative-phase-registry");
        workspace.set_cleanup_barrier(relative.clone()).unwrap();
        let stored: PathBuf = serde_json::from_slice(
            &fs::read(workspace.root().join("cleanup-barrier.json")).unwrap(),
        )
        .unwrap();
        assert!(stored.is_absolute());
        assert_eq!(stored, std::env::current_dir().unwrap().join(relative));
        workspace.finish().unwrap();
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn unanchored_persisted_barrier_cannot_authorize_orphan_cleanup() {
        let root = std::env::temp_dir().join(format!("run-unbound-{}", managed_generation_id()));
        let runs = root.join("runs");
        let workspace = RunWorkspace::create(&runs, None).unwrap();
        let candidate = workspace.candidate_root().join("partial.db");
        fs::write(
            &candidate,
            b"candidate still belongs to an unverified phase",
        )
        .unwrap();
        write_json_atomically(
            &workspace.root().join("cleanup-barrier.json"),
            &PathBuf::from("unbound-phase-registry"),
        )
        .unwrap();
        drop(workspace);
        let recovery = RunWorkspace::cleanup_orphans(&runs).unwrap();
        assert_eq!(recovery.deleted, 0);
        assert_eq!(recovery.skipped_locked, 1);
        assert!(candidate.is_file());
        fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn confined_run_cleanup_is_idempotent() {
        let root = std::env::temp_dir().join(format!(
            "codebase-graph-run-cleanup-{}",
            managed_generation_id()
        ));
        let runs_root = root.join("runs");
        let run_root = runs_root.join("run-repeat");
        fs::create_dir_all(run_root.join("staging")).unwrap();
        fs::write(run_root.join("staging/source.rs"), "fn main() {}\n").unwrap();

        remove_run_root_confined(&run_root, &runs_root).unwrap();
        remove_run_root_confined(&run_root, &runs_root).unwrap();
        assert!(!run_root.exists());

        let raced_run_root = runs_root.join("run-raced");
        fs::create_dir_all(raced_run_root.join("candidate")).unwrap();
        validate_tree_has_no_symlinks(&raced_run_root).unwrap();
        fs::remove_dir_all(&raced_run_root).unwrap();
        remove_validated_path(&raced_run_root).unwrap();

        fs::remove_dir_all(root).unwrap();
    }
}