gemel 0.11.1

Evidence-native version control for agentic software development: canonical object encoding, content-addressed identity, immutable object store, change workflow, Git-carried exchange rollups, network transports, and CLI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! Repository verification (STORAGE.md §8, INVARIANTS.md §12).
//!
//! `fsck` verifies: envelope/hash of every object file, schema validity,
//! reference resolution (missing vs. pruned), acyclicity, ref validity,
//! index consistency, workspace metadata, and journal state. Exit codes:
//! 0 clean, 1 repairs made, 2 corruption found.

use crate::decode::decode_object;
use crate::gid::Gid;
use crate::hash::object_id_bytes;
use crate::store::index;
use crate::store::objects;
use crate::store::refs;
use crate::store::tombstone;
use crate::store::{Error, ReadOutcome, Repo};
use std::collections::{HashMap, HashSet};
use std::path::Path;

/// Options controlling the fsck run.
#[derive(Debug, Clone, Default)]
pub struct FsckOptions {
    /// Repair rebuildable artifacts (index rebuild, journal recovery).
    pub repair: bool,
    /// Force an index rebuild (implies repair of the index).
    pub rebuild_index: bool,
    /// Verbose output.
    pub verbose: bool,
}

/// A problem found by fsck.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Problem {
    pub severity: Severity,
    pub code: &'static str,
    pub message: String,
    pub id: Option<Gid>,
}

/// Problem severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    Error,
    Warning,
}

impl Severity {
    pub fn as_str(&self) -> &'static str {
        match self {
            Severity::Error => "error",
            Severity::Warning => "warning",
        }
    }
}

/// The fsck report.
#[derive(Debug, Clone, Default)]
pub struct FsckReport {
    pub objects_scanned: usize,
    pub objects_ok: usize,
    pub problems: Vec<Problem>,
    pub repairs: Vec<String>,
    pub index_drift: Vec<String>,
    pub journal_recovered: bool,
    /// Exchange transport section (EXCHANGE.md §41): discovered/imported
    /// frontiers are reported separately from the native store.
    pub exchange_frontiers: usize,
    pub exchange_imported: usize,
}

impl FsckReport {
    /// The documented exit code (STORAGE.md §8).
    pub fn exit_code(&self) -> u8 {
        let has_errors = self.problems.iter().any(|p| p.severity == Severity::Error);
        if has_errors {
            2
        } else if !self.repairs.is_empty() || self.journal_recovered {
            1
        } else {
            0
        }
    }

    pub fn is_clean(&self) -> bool {
        self.exit_code() == 0
    }
}

/// Runs the full verification.
pub fn run(repo: &Repo, opts: &FsckOptions) -> Result<FsckReport, Error> {
    let mut report = FsckReport::default();

    // -- 0. Exchange transport section (EXCHANGE.md §41): report frontier
    // state separately; blobs omitted by a carrier-backed profile are not
    // native-store corruption.
    let exchange_omitted = exchange_omitted_blobs(repo);
    match crate::exchange::discover_frontiers(repo.meta_dir()) {
        Ok(frontiers) => {
            report.exchange_frontiers = frontiers.len();
            report.exchange_imported = frontiers
                .iter()
                .filter(|(_, id, _)| crate::exchange::export::is_imported(repo.meta_dir(), id))
                .count();
        }
        Err(_) => {
            // A malformed exchange tree is reported by the exchange section
            // of the CLI, never fatal for the native store.
        }
    }

    // -- 1. Object files: envelope, hash, schema --------------------------
    let mut on_disk: HashMap<Gid, u64> = HashMap::new();
    for path in objects::scan(repo.meta_dir())? {
        report.objects_scanned += 1;
        let bytes = match std::fs::read(&path) {
            Ok(b) => b,
            Err(e) => {
                report.problems.push(Problem {
                    severity: Severity::Error,
                    code: "unreadable-object",
                    message: format!("{}: {e}", path.display()),
                    id: None,
                });
                continue;
            }
        };
        let id = match verify_envelope(repo, &bytes) {
            Ok(id) => id,
            Err(problem) => {
                report.problems.push(problem);
                continue;
            }
        };
        // Filename must match the identity digest.
        let file_name = path
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_default();
        let hex = crate::hex::encode(id.digest());
        if file_name != format!("{hex}.gce") {
            report.problems.push(Problem {
                severity: Severity::Error,
                code: "filename-mismatch",
                message: format!("{}: file name does not match identity", path.display()),
                id: Some(id),
            });
        }
        report.objects_ok += 1;
        on_disk.insert(id, bytes.len() as u64);
    }

    // Stray files in the objects tree.
    for (code, message) in stray_files(repo.meta_dir()) {
        report.problems.push(Problem {
            severity: Severity::Warning,
            code,
            message,
            id: None,
        });
    }

    // -- 2/3/4. Reachability, references, cycles --------------------------
    let mut reachable: HashMap<Gid, Vec<Gid>> = HashMap::new();
    let mut queue: Vec<Gid> = Vec::new();
    for (name, gid) in refs::all(repo.meta_dir())? {
        queue.push(gid);
        if opts.verbose {
            eprintln!("fsck: ref {name} -> {gid}");
        }
    }
    let mut visited: HashSet<Gid> = HashSet::new();
    while let Some(id) = queue.pop() {
        if !visited.insert(id) {
            continue;
        }
        match repo.read_object(&id) {
            Ok(ReadOutcome::Object(obj)) => {
                let edges: Vec<Gid> = index::edges_of(&obj)
                    .into_iter()
                    .map(|(_, to, _)| to)
                    .collect();
                reachable.insert(id, edges.clone());
                queue.extend(edges);
            }
            Ok(ReadOutcome::Pruned(t)) => {
                report.problems.push(Problem {
                    severity: Severity::Error,
                    code: "pruned-referenced",
                    message: format!(
                        "reference to pruned object {id} (tier {} rule {})",
                        t.policy_tier, t.policy_rule
                    ),
                    id: Some(id),
                });
            }
            Err(Error::ObjectNotFound(_)) => {
                if exchange_omitted.contains(&id) {
                    report.problems.push(Problem {
                        severity: Severity::Warning,
                        code: "exchange-omitted",
                        message: format!(
                            "object {id} absent by exchange profile (carrier-backed source)"
                        ),
                        id: Some(id),
                    });
                } else {
                    report.problems.push(Problem {
                        severity: Severity::Error,
                        code: "missing-reference",
                        message: format!("reference to missing object {id}"),
                        id: Some(id),
                    });
                }
            }
            Err(Error::ObjectCorrupt { detail, .. }) => {
                report.problems.push(Problem {
                    severity: Severity::Error,
                    code: "corrupt-object",
                    message: format!("{id}: {detail}"),
                    id: Some(id),
                });
            }
            Err(e) => return Err(e),
        }
    }

    // Cycle detection (three-color DFS over the reachable graph).
    if let Some(cycle) = find_cycle(&reachable) {
        report.problems.push(Problem {
            severity: Severity::Error,
            code: "cycle",
            message: format!("object graph contains a cycle at {cycle}"),
            id: Some(cycle),
        });
    }

    // -- 5. Refs -----------------------------------------------------------
    for (name, _gid) in refs::all(repo.meta_dir())? {
        if let Err(e) = refs::read(repo.meta_dir(), &name) {
            report.problems.push(Problem {
                severity: Severity::Error,
                code: "corrupt-ref",
                message: format!("{name}: {e}"),
                id: None,
            });
        }
    }

    // -- 6. Index consistency ---------------------------------------------
    let index_stale = index::is_stale(repo).unwrap_or(false);
    if index_stale {
        report.index_drift.push("index flagged stale".into());
    }
    match (index::refs_mirror(repo), refs::all(repo.meta_dir())) {
        (Ok(mirror), Ok(actual)) => {
            let mirror_set: HashMap<String, String> = mirror
                .into_iter()
                .map(|(n, g)| (n, g.to_string()))
                .collect();
            let actual_set: HashMap<String, String> = actual
                .into_iter()
                .map(|(n, g)| (n, g.to_string()))
                .collect();
            if mirror_set != actual_set {
                report
                    .index_drift
                    .push("index refs mirror differs from on-disk refs".into());
            }
        }
        _ => {
            report.index_drift.push("index unreadable".into());
        }
    }
    match index::indexed_objects(repo) {
        Ok(indexed) => {
            let indexed_set: HashSet<String> = indexed.into_iter().map(|(id, _)| id).collect();
            let disk_set: HashSet<String> = on_disk.keys().map(|g| g.to_string()).collect();
            if indexed_set != disk_set {
                report.index_drift.push(format!(
                    "index objects differ from disk ({} indexed, {} on disk)",
                    indexed_set.len(),
                    disk_set.len()
                ));
            }
        }
        Err(_) => {
            report.index_drift.push("index unreadable".into());
        }
    }
    if !report.index_drift.is_empty() {
        report.problems.push(Problem {
            severity: Severity::Error,
            code: "index-inconsistent",
            message: format!(
                "derived index inconsistent ({} drift items)",
                report.index_drift.len()
            ),
            id: None,
        });
    }

    // -- 7. Workspace metadata --------------------------------------------
    check_workspaces(repo, &mut report);

    // -- 8. Journal --------------------------------------------------------
    if let Ok(content) = std::fs::read_to_string(refs::journal_path(repo.meta_dir())) {
        if !content.trim().is_empty() {
            report.problems.push(Problem {
                severity: Severity::Error,
                code: "interrupted-transaction",
                message: "journal contains an interrupted transaction".into(),
                id: None,
            });
        }
    }

    // -- Repair (derived artifacts only) ----------------------------------
    if opts.repair || opts.rebuild_index {
        if opts.rebuild_index || !report.index_drift.is_empty() {
            match repo.with_write_lock(|| index::rebuild(repo)) {
                Ok(()) => {
                    report.repairs.push("rebuilt derived index".into());
                    report.problems.retain(|p| p.code != "index-inconsistent");
                    report.index_drift.clear();
                }
                Err(e) => report.problems.push(Problem {
                    severity: Severity::Error,
                    code: "repair-failed",
                    message: format!("index rebuild failed: {e}"),
                    id: None,
                }),
            }
        }
        let journal_has_content = std::fs::read_to_string(refs::journal_path(repo.meta_dir()))
            .map(|c| !c.trim().is_empty())
            .unwrap_or(false);
        if journal_has_content {
            // Recover under the writer lock. Rolling back an interrupted
            // transaction changes the canonical ref set, so the derived index
            // must be rebuilt to stay consistent.
            let recovered = repo.with_write_lock(|| {
                let did = refs::recover_unlocked(repo.meta_dir())?;
                if did {
                    index::rebuild(repo)?;
                }
                Ok(did)
            });
            match recovered {
                Ok(true) => {
                    report
                        .repairs
                        .push("recovered interrupted journal transaction".into());
                    report
                        .problems
                        .retain(|p| p.code != "interrupted-transaction");
                }
                Ok(false) => {}
                Err(e) => report.problems.push(Problem {
                    severity: Severity::Error,
                    code: "repair-failed",
                    message: format!("journal recovery failed: {e}"),
                    id: None,
                }),
            }
        }
    }

    Ok(report)
}

/// The blob ids that imported exchange frontiers legitimately omit under a
/// carrier-backed profile (EXCHANGE.md §13, §41): blobs reachable from the
/// head changes of imported frontiers whose coverage does not carry source
/// content. Absence of these is a coverage property, not corruption.
fn exchange_omitted_blobs(repo: &Repo) -> HashSet<Gid> {
    let mut out = HashSet::new();
    let frontiers = match crate::exchange::discover_frontiers(repo.meta_dir()) {
        Ok(f) => f,
        Err(_) => return out,
    };
    let mut queue: Vec<Gid> = Vec::new();
    for (f, _, _) in &frontiers {
        if f.coverage.source_content != "complete" || f.coverage.evidence_payloads != "complete" {
            queue.push(f.head_change);
        }
    }
    let mut visited: HashSet<Gid> = HashSet::new();
    while let Some(id) = queue.pop() {
        if !visited.insert(id) {
            continue;
        }
        let obj = match repo.read_object(&id) {
            Ok(ReadOutcome::Object(o)) => o,
            _ => continue, // absent objects are reported by the main walk
        };
        if obj.family == crate::family::Family::Blob {
            out.insert(id);
            continue;
        }
        for (_, to, _) in index::edges_of(&obj) {
            queue.push(to);
        }
    }
    out
}

fn verify_envelope(repo: &Repo, bytes: &[u8]) -> Result<Gid, Problem> {
    let limits = repo.limits();
    let obj = decode_object(bytes, &limits).map_err(|e| Problem {
        severity: Severity::Error,
        code: "invalid-object",
        message: format!("decode failed: {e}"),
        id: None,
    })?;
    let digest = object_id_bytes(bytes);
    let id = Gid::new(obj.family, digest);
    Ok(id)
}

fn stray_files(meta: &Path) -> Vec<(&'static str, String)> {
    let mut out = Vec::new();
    let objects_dir = meta.join("objects");
    if let Ok(shards) = std::fs::read_dir(&objects_dir) {
        for shard in shards.flatten() {
            if !shard.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                continue;
            }
            if let Ok(entries) = std::fs::read_dir(shard.path()) {
                for entry in entries.flatten() {
                    let name = entry.file_name().to_string_lossy().to_string();
                    if name.starts_with(".tmp-") {
                        out.push((
                            "stale-temp-file",
                            format!("stale temp file: {}", entry.path().display()),
                        ));
                    } else if !name.ends_with(".gce") && !name.ends_with(".tomb") {
                        out.push((
                            "stray-file",
                            format!("stray file: {}", entry.path().display()),
                        ));
                    }
                }
            }
        }
    }
    out
}

fn check_workspaces(repo: &Repo, report: &mut FsckReport) {
    let worktrees = repo.meta_dir().join("worktrees");
    let entries = match std::fs::read_dir(&worktrees) {
        Ok(e) => e,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
            continue;
        }
        let dir = entry.path();
        let state_ref = dir.join("state.ref");
        if let Ok(text) = std::fs::read_to_string(&state_ref) {
            match text.trim().parse::<Gid>() {
                Ok(gid) => {
                    if !tombstone::exists(repo.meta_dir(), &gid).unwrap_or(false)
                        && !objects::exists(repo.meta_dir(), &gid).unwrap_or(false)
                    {
                        report.problems.push(Problem {
                            severity: Severity::Error,
                            code: "workspace-state-missing",
                            message: format!(
                                "workspace {} state.ref resolves to missing {gid}",
                                entry.file_name().to_string_lossy()
                            ),
                            id: Some(gid),
                        });
                    }
                }
                Err(e) => report.problems.push(Problem {
                    severity: Severity::Error,
                    code: "workspace-state-corrupt",
                    message: format!(
                        "workspace {} state.ref unparseable: {e}",
                        entry.file_name().to_string_lossy()
                    ),
                    id: None,
                }),
            }
        }
        let pending = dir.join("pending.json");
        if let Ok(text) = std::fs::read_to_string(&pending) {
            if serde_json::from_str::<serde_json::Value>(&text).is_err() {
                report.problems.push(Problem {
                    severity: Severity::Error,
                    code: "pending-corrupt",
                    message: format!(
                        "workspace {} pending.json unparseable",
                        entry.file_name().to_string_lossy()
                    ),
                    id: None,
                });
            }
        }
    }
}

/// Three-color DFS cycle detection; returns a node on a cycle if one exists.
fn find_cycle(graph: &HashMap<Gid, Vec<Gid>>) -> Option<Gid> {
    const WHITE: u8 = 0;
    const GRAY: u8 = 1;
    const BLACK: u8 = 2;
    let mut color: HashMap<Gid, u8> = HashMap::new();
    for start in graph.keys() {
        if color.get(start).copied().unwrap_or(WHITE) != WHITE {
            continue;
        }
        // Iterative DFS.
        let mut stack: Vec<(Gid, bool)> = vec![(*start, false)];
        while let Some((node, exiting)) = stack.pop() {
            let c = color.get(&node).copied().unwrap_or(WHITE);
            if exiting {
                color.insert(node, BLACK);
                continue;
            }
            if c == GRAY {
                return Some(node); // back edge
            }
            if c == BLACK {
                continue;
            }
            color.insert(node, GRAY);
            stack.push((node, true));
            if let Some(neighbors) = graph.get(&node) {
                for n in neighbors {
                    let nc = color.get(n).copied().unwrap_or(WHITE);
                    if nc == WHITE {
                        stack.push((*n, false));
                    } else if nc == GRAY {
                        return Some(*n);
                    }
                }
            }
        }
    }
    None
}