cordance-core 0.1.1

Cordance core types, schemas, and ports. No I/O.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! `cordance-source-lock.v1` — every input source + every output's sha256.
//!
//! Drives `cordance check`: any source-anchor sha drift → fail.
//! Combined with fenced regions, this is how Cordance avoids
//! laundering hand-edits as authoritative output.

use std::collections::{HashMap, HashSet};

use camino::Utf8PathBuf;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::pack::CordancePack;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SourceLock {
    pub schema: String,
    pub pack_id: String,
    pub doctrine_commit: Option<String>,
    pub axiom_algorithm_pin: Option<String>,
    pub sources: Vec<SourceLockEntry>,
    pub outputs: Vec<SourceLockEntry>,
}

impl SourceLock {
    #[must_use]
    pub fn empty() -> Self {
        Self {
            schema: crate::schema::CORDANCE_SOURCE_LOCK_V1.into(),
            pack_id: String::new(),
            doctrine_commit: None,
            axiom_algorithm_pin: None,
            sources: vec![],
            outputs: vec![],
        }
    }

    /// Compute a `SourceLock` from a `CordancePack`.
    ///
    /// `pack_id` is the sha256 of a deterministic byte stream that mixes:
    /// 1. project identity (`name`, a fixed `repo:.` placeholder, optional
    ///    `axiom_pin`), so that two unrelated empty projects can never
    ///    collide on the same id, and
    /// 2. every source's `id:sha256`, sorted by id, so the digest is stable
    ///    across runs that produce the same logical pack.
    ///
    /// `axiom_algorithm_pin` is propagated from `pack.project.axiom_pin` so
    /// that a downstream `cordance check` notices a doctrine-shaped drift in
    /// the axiom algorithm version (the cellos drift problem cordance exists
    /// to solve).
    ///
    /// # Cross-host determinism — Round-8 bughunt #4 (R8-bughunt-4)
    ///
    /// Earlier rounds (round-5 R5-bughunt-5 / round-5 R5-bughunt-8 / round-6
    /// LOW / round-7 R7-bughunt-6) hashed `pack.project.repo_root.as_str()`
    /// directly. That string was the operator's host-absolute path
    /// (`C:\\Users\\0ryant\\prj\\cordance` on Windows,
    /// `/home/op/projects/cordance` on Linux), so two clones of the same
    /// git commit on different hosts produced different `pack_id`s — and
    /// the cortex receipt that hashes `pack_id` then disagreed about pack
    /// identity across CI runners and developer machines. The cellos drift
    /// problem the receipt was supposed to detect was masked by a
    /// path-shape drift cordance itself was introducing.
    ///
    /// The mix now uses a fixed placeholder (`b"."`). Project distinction
    /// still comes from `name` and `axiom_pin`. `pack_cmd::run` writes the
    /// matching `"."` into `pack.project.repo_root` for the on-disk shape;
    /// the framing constant here is the second half of the same contract
    /// so any future code that builds a pack with a non-`"."` `repo_root`
    /// (test fixtures, MCP shims) still hashes identically.
    #[must_use]
    pub fn compute_from_pack(pack: &CordancePack) -> Self {
        // Build the set of paths that should NOT appear in the lock's
        // `sources` list:
        //   1. Every path Cordance emitted as a target artifact (lives in
        //      `pack.outputs`). On the first `cordance pack` the scanner
        //      doesn't see these because they don't exist yet, but a
        //      subsequent `cordance check` rescan picks them up — round-4
        //      bughunt #2's new-file detection then flags every one of them
        //      as an "ADDED" source. The output sha is already captured in
        //      `lock.outputs`, so the source-side entry is redundant noise.
        //   2. Cordance-internal metadata under `.cordance/` that no emitter
        //      claims (sources.lock itself, evidence-map.json, the optional
        //      llm-candidate.json). These never appear in `pack.outputs` but
        //      do appear in scans of a directory where `cordance pack` has
        //      already run.
        let mut excluded_paths: HashSet<String> = pack
            .outputs
            .iter()
            .map(|o| o.path.as_str().to_string())
            .collect();
        excluded_paths.insert(".cordance/sources.lock".into());
        excluded_paths.insert(".cordance/evidence-map.json".into());
        excluded_paths.insert(".cordance/llm-candidate.json".into());
        excluded_paths.insert(".cordance/cortex-receipt.json".into());

        let mut sorted_sources: Vec<_> = pack
            .sources
            .iter()
            .filter(|r| !excluded_paths.contains(r.path.as_str()))
            .cloned()
            .collect();
        sorted_sources.sort_by(|a, b| a.id.cmp(&b.id));

        // Domain-separated framing keeps "project:name" from colliding with a
        // source whose id happens to start with that prefix.
        //
        // Round-8 bughunt #4 (R8-bughunt-4): the `repo:` mix is now a fixed
        // `b"."` placeholder rather than `pack.project.repo_root.as_str()`.
        // See the doc-comment above for the cross-host-determinism rationale;
        // we keep the framing line so the byte stream layout (and therefore
        // any historical re-derivation) is shape-compatible — only the
        // value-bytes changed from a host-absolute path to a single `.`.
        let mut hasher = Sha256::new();
        hasher.update(b"project:");
        hasher.update(pack.project.name.as_bytes());
        hasher.update(b"\nrepo:");
        hasher.update(b".");
        if let Some(pin) = &pack.project.axiom_pin {
            hasher.update(b"\naxiom:");
            hasher.update(pin.as_bytes());
        }
        for r in &sorted_sources {
            hasher.update(b"\n");
            hasher.update(r.id.as_bytes());
            hasher.update(b":");
            hasher.update(r.sha256.as_bytes());
        }
        let pack_id = hex::encode(hasher.finalize());

        let sources = sorted_sources
            .iter()
            .map(|r| SourceLockEntry {
                id: r.id.clone(),
                path: r.path.clone(),
                sha256: r.sha256.clone(),
                bytes: r.size_bytes,
            })
            .collect();

        let outputs = pack
            .outputs
            .iter()
            .map(|o| SourceLockEntry {
                id: o.path.to_string(),
                path: o.path.as_str().into(),
                sha256: o.sha256.clone(),
                bytes: o.bytes,
            })
            .collect();

        let doctrine_commit = pack.doctrine_pins.first().map(|p| p.commit.clone());

        Self {
            schema: crate::schema::CORDANCE_SOURCE_LOCK_V1.into(),
            pack_id,
            doctrine_commit,
            axiom_algorithm_pin: pack.project.axiom_pin.clone(),
            sources,
            outputs,
        }
    }

    /// Diff `self` (the current/new state) against `previous`.
    ///
    /// `fenced_outputs` is the set of output paths (as `entry.path.as_str()`)
    /// that currently contain cordance fence markers on disk. The caller is
    /// responsible for computing this set; keeping the read out of `diff`
    /// preserves the modularity-and-ports-adapters boundary — `SourceLock`
    /// is a pure domain type and must not touch the filesystem.
    ///
    /// Output paths absent from `fenced_outputs` are treated as **fenced**
    /// when they are missing on disk (so a deleted managed region still
    /// counts as drift). This matches the previous behaviour exactly.
    #[must_use]
    pub fn diff(&self, previous: &Self, fenced_outputs: &HashSet<String>) -> DriftReport {
        let current_sources: HashMap<&str, &SourceLockEntry> =
            self.sources.iter().map(|e| (e.id.as_str(), e)).collect();
        let previous_sources: HashMap<&str, &SourceLockEntry> = previous
            .sources
            .iter()
            .map(|e| (e.id.as_str(), e))
            .collect();

        let mut source_drifts = Vec::new();

        // Pass 1: every previous entry that is gone or whose sha drifted.
        for entry in &previous.sources {
            match current_sources.get(entry.id.as_str()) {
                None => {
                    source_drifts.push(SourceDriftEntry {
                        id: entry.id.clone(),
                        path: entry.path.to_string(),
                        old_sha256: entry.sha256.clone(),
                        new_sha256: "DELETED".into(),
                    });
                }
                Some(current) if current.sha256 != entry.sha256 => {
                    source_drifts.push(SourceDriftEntry {
                        id: entry.id.clone(),
                        path: entry.path.to_string(),
                        old_sha256: entry.sha256.clone(),
                        new_sha256: current.sha256.clone(),
                    });
                }
                _ => {}
            }
        }

        // Pass 2: every CURRENT entry not in the previous lock — a newly-added
        // source. Round-4 bughunt #2: the previous diff was blind to new
        // files, so `cordance check` would report "clean" after `touch
        // newfile.md`. We mark new entries with `old_sha256 == "ADDED"` so the
        // formatter can surface them as additions rather than zero-byte
        // changes. The same flag also catches "a previously-blocked file is
        // now classified" and "a renamed file produces a fresh id" — both
        // were silently missed under the old single-pass loop.
        for entry in &self.sources {
            if !previous_sources.contains_key(entry.id.as_str()) {
                source_drifts.push(SourceDriftEntry {
                    id: entry.id.clone(),
                    path: entry.path.to_string(),
                    old_sha256: "ADDED".into(),
                    new_sha256: entry.sha256.clone(),
                });
            }
        }

        let current_outputs: HashMap<&str, &SourceLockEntry> =
            self.outputs.iter().map(|e| (e.id.as_str(), e)).collect();

        let mut fenced_output_drifts = Vec::new();
        let mut unfenced_output_drifts = Vec::new();

        for entry in &previous.outputs {
            // Output gone from lock entirely → treat as fenced drift (managed region gone).
            let drifted = current_outputs
                .get(entry.id.as_str())
                .is_none_or(|current| current.sha256 != entry.sha256);

            if !drifted {
                continue;
            }

            // A missing file is still a managed-region drift (fenced) — the
            // caller signals that by leaving the path out of
            // `fenced_outputs`. Only outputs that the caller explicitly
            // observed without fence markers are classified as unfenced.
            // Said another way: "fenced or missing" == fenced drift,
            // "observed and unfenced" == user-owned drift.
            let path_key = entry.path.as_str();
            let observed_unfenced =
                current_outputs.contains_key(path_key) && !fenced_outputs.contains(path_key);

            let drift_entry = OutputDriftEntry {
                path: entry.path.to_string(),
                old_sha256: entry.sha256.clone(),
                new_sha256: current_outputs
                    .get(entry.id.as_str())
                    .map_or_else(|| "DELETED".into(), |e| e.sha256.clone()),
            };

            if observed_unfenced {
                unfenced_output_drifts.push(drift_entry);
            } else {
                fenced_output_drifts.push(drift_entry);
            }
        }

        DriftReport {
            source_drifts,
            fenced_output_drifts,
            unfenced_output_drifts,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SourceLockEntry {
    pub id: String,
    pub path: Utf8PathBuf,
    pub sha256: String,
    pub bytes: u64,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct DriftReport {
    pub source_drifts: Vec<SourceDriftEntry>,
    pub fenced_output_drifts: Vec<OutputDriftEntry>,
    pub unfenced_output_drifts: Vec<OutputDriftEntry>,
}

impl DriftReport {
    #[must_use]
    pub const fn is_clean(&self) -> bool {
        self.source_drifts.is_empty() && self.fenced_output_drifts.is_empty()
    }

    /// Exit code: 0=clean, 1=source drift, 2=fenced output drift, 3=both.
    #[must_use]
    pub const fn exit_code(&self) -> i32 {
        match (
            !self.source_drifts.is_empty(),
            !self.fenced_output_drifts.is_empty(),
        ) {
            (false, false) => 0,
            (true, false) => 1,
            (false, true) => 2,
            (true, true) => 3,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SourceDriftEntry {
    pub id: String,
    pub path: String,
    pub old_sha256: String,
    pub new_sha256: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OutputDriftEntry {
    pub path: String,
    pub old_sha256: String,
    pub new_sha256: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::advise::AdviseReport;
    use crate::pack::{CordancePack, PackTargets, ProjectIdentity};
    use crate::schema;

    fn minimal_empty_pack(name: &str) -> CordancePack {
        CordancePack {
            schema: schema::CORDANCE_PACK_V1.into(),
            project: ProjectIdentity {
                name: name.into(),
                repo_root: format!("/tmp/{name}").into(),
                kind: "test".into(),
                host_os: "linux".into(),
                axiom_pin: None,
            },
            sources: vec![],
            doctrine_pins: vec![],
            targets: PackTargets::default(),
            outputs: vec![],
            source_lock: SourceLock::empty(),
            advise: AdviseReport::empty(),
            residual_risk: vec!["test".into()],
        }
    }

    #[test]
    fn empty_lock_has_v1_schema() {
        let l = SourceLock::empty();
        assert_eq!(l.schema, crate::schema::CORDANCE_SOURCE_LOCK_V1);
    }

    /// Two unrelated empty projects must never share a `pack_id`; the cellos
    /// drift problem (HIGH bughunt #5) is precisely the false-equality this
    /// guards against.
    #[test]
    fn empty_packs_with_different_names_have_different_pack_ids() {
        let p1 = minimal_empty_pack("project_a");
        let p2 = minimal_empty_pack("project_b");
        let l1 = SourceLock::compute_from_pack(&p1);
        let l2 = SourceLock::compute_from_pack(&p2);
        assert_ne!(l1.pack_id, l2.pack_id);
    }

    /// `pack_id` is stable across re-computation on the same logical pack.
    #[test]
    fn same_empty_pack_yields_same_pack_id() {
        let p = minimal_empty_pack("project_a");
        let l1 = SourceLock::compute_from_pack(&p);
        let l2 = SourceLock::compute_from_pack(&p);
        assert_eq!(l1.pack_id, l2.pack_id);
    }

    /// Empty pack must never produce the trivial `sha256("")` digest — that
    /// is the exact symptom of CRITICAL #5 from the bughunt review.
    #[test]
    fn empty_pack_id_is_not_sha256_of_empty_string() {
        let p = minimal_empty_pack("any");
        let lock = SourceLock::compute_from_pack(&p);
        let empty_sha = hex::encode(Sha256::digest(b""));
        assert_ne!(lock.pack_id, empty_sha);
    }

    /// `axiom_pin` on the pack must round-trip through to
    /// `lock.axiom_algorithm_pin`.
    #[test]
    fn axiom_pin_propagates_to_lock() {
        let mut pack = minimal_empty_pack("test");
        pack.project.axiom_pin = Some("v3.1.1-axiom".into());
        let lock = SourceLock::compute_from_pack(&pack);
        assert_eq!(lock.axiom_algorithm_pin.as_deref(), Some("v3.1.1-axiom"));
    }

    /// Two empty packs that differ only in `axiom_pin` must produce different
    /// `pack_id`s — otherwise an axiom version bump silently looks identical
    /// to the previous lock.
    #[test]
    fn axiom_pin_affects_pack_id() {
        let mut p1 = minimal_empty_pack("same_name");
        let mut p2 = minimal_empty_pack("same_name");
        p1.project.axiom_pin = Some("v3.1.0-axiom".into());
        p2.project.axiom_pin = Some("v3.1.1-axiom".into());
        let l1 = SourceLock::compute_from_pack(&p1);
        let l2 = SourceLock::compute_from_pack(&p2);
        assert_ne!(l1.pack_id, l2.pack_id);
    }

    /// Round-8 bughunt #4 (R8-bughunt-4): the cross-host-determinism pin.
    /// Two operators on different machines cloning the same git commit
    /// produce historical `repo_root` values like `/tmp/foo` and
    /// `C:\Users\op\foo`. Under the old shape, those host-absolute paths
    /// were mixed into the `pack_id` sha and the two operators' receipts
    /// disagreed about pack identity for the same logical commit — masking
    /// the cellos drift problem the receipt was meant to surface.
    ///
    /// With the placeholder mix, `compute_from_pack` ignores `repo_root`
    /// entirely. Identical name + identical `axiom_pin` + identical sources
    /// MUST yield identical `pack_id`, even if a caller passed two
    /// different `repo_root` values (legacy test fixtures, MCP shims that
    /// haven't been migrated yet). This test pins the contract on the
    /// hash side; the construction-site fix in `pack_cmd::run` writes
    /// `"."` for all real packs.
    #[test]
    fn pack_id_ignores_repo_root_across_hosts() {
        let mut p1 = minimal_empty_pack("cordance");
        let mut p2 = minimal_empty_pack("cordance");
        p1.project.axiom_pin = Some("v3.1.1-axiom".into());
        p2.project.axiom_pin = Some("v3.1.1-axiom".into());
        // Simulate the same logical project cloned to different hosts.
        p1.project.repo_root = "/tmp/foo".into();
        p2.project.repo_root = r"C:\Users\op\foo".into();
        let l1 = SourceLock::compute_from_pack(&p1);
        let l2 = SourceLock::compute_from_pack(&p2);
        assert_eq!(
            l1.pack_id, l2.pack_id,
            "pack_id must be host-independent: identical name+axiom_pin+sources \
             must yield identical pack_id regardless of repo_root \
             (l1={}, l2={})",
            l1.pack_id, l2.pack_id
        );
    }

    /// Round-8 bughunt #4 (R8-bughunt-4) companion: the placeholder mix
    /// must not collapse the existing name-distinction guarantee. Two
    /// packs with different names must still produce different `pack_id`s
    /// even when they share an (identical) `repo_root` value. This is the
    /// negative bound on the previous test: removing `repo_root` from the
    /// hash must not strengthen collisions, just align cross-host.
    #[test]
    fn pack_id_still_differs_by_name_when_repo_root_matches() {
        let p1 = minimal_empty_pack("project_a");
        let p2 = minimal_empty_pack("project_b");
        // `minimal_empty_pack` already sets repo_root from the name, so
        // overwrite both with an identical placeholder to isolate the
        // name-distinction signal.
        let mut p1 = p1;
        let mut p2 = p2;
        p1.project.repo_root = ".".into();
        p2.project.repo_root = ".".into();
        let l1 = SourceLock::compute_from_pack(&p1);
        let l2 = SourceLock::compute_from_pack(&p2);
        assert_ne!(
            l1.pack_id, l2.pack_id,
            "different project names must still yield different pack_ids \
             even when repo_root is identical"
        );
    }

    #[test]
    fn drift_report_clean_exit_code() {
        let report = DriftReport::default();
        assert!(report.is_clean());
        assert_eq!(report.exit_code(), 0);
    }

    #[test]
    fn drift_report_source_only_exit_code() {
        let report = DriftReport {
            source_drifts: vec![SourceDriftEntry {
                id: "x".into(),
                path: "x.md".into(),
                old_sha256: "aa".into(),
                new_sha256: "bb".into(),
            }],
            fenced_output_drifts: vec![],
            unfenced_output_drifts: vec![],
        };
        assert!(!report.is_clean());
        assert_eq!(report.exit_code(), 1);
    }

    /// Round-4 bughunt #2: `cordance check` was blind to NEW source files
    /// because `SourceLock::diff` iterated only `previous.sources`. A `touch
    /// newfile.md` between two packs must show up as an ADDED entry.
    #[test]
    fn diff_reports_newly_added_sources() {
        let prev = SourceLock::empty();
        let mut current = SourceLock::empty();
        current.sources.push(SourceLockEntry {
            id: "project_readme:README.md".into(),
            path: "README.md".into(),
            sha256: "newhash".into(),
            bytes: 100,
        });
        let report = current.diff(&prev, &HashSet::new());
        assert_eq!(report.source_drifts.len(), 1);
        assert_eq!(report.source_drifts[0].old_sha256, "ADDED");
        assert_eq!(report.source_drifts[0].new_sha256, "newhash");
        assert_eq!(report.source_drifts[0].path, "README.md");
        assert!(!report.is_clean());
    }

    /// Symmetric: a previously-present source that is gone in the current
    /// lock is reported as DELETED — same as before the bughunt fix.
    #[test]
    fn diff_reports_deleted_sources() {
        let mut prev = SourceLock::empty();
        prev.sources.push(SourceLockEntry {
            id: "project_readme:README.md".into(),
            path: "README.md".into(),
            sha256: "oldhash".into(),
            bytes: 100,
        });
        let current = SourceLock::empty();
        let report = current.diff(&prev, &HashSet::new());
        assert_eq!(report.source_drifts.len(), 1);
        assert_eq!(report.source_drifts[0].old_sha256, "oldhash");
        assert_eq!(report.source_drifts[0].new_sha256, "DELETED");
    }

    /// Mixed: one entry drifts in place, one is added, one is deleted.
    /// All three must appear in `source_drifts`.
    #[test]
    fn diff_handles_mixed_drift_added_deleted() {
        let mut prev = SourceLock::empty();
        prev.sources.push(SourceLockEntry {
            id: "a".into(),
            path: "a.md".into(),
            sha256: "aaa".into(),
            bytes: 1,
        });
        prev.sources.push(SourceLockEntry {
            id: "b".into(),
            path: "b.md".into(),
            sha256: "bbb".into(),
            bytes: 1,
        });
        let mut current = SourceLock::empty();
        current.sources.push(SourceLockEntry {
            id: "a".into(),
            path: "a.md".into(),
            sha256: "aaa_drifted".into(),
            bytes: 1,
        });
        // 'b' removed, 'c' added.
        current.sources.push(SourceLockEntry {
            id: "c".into(),
            path: "c.md".into(),
            sha256: "ccc".into(),
            bytes: 1,
        });
        let report = current.diff(&prev, &HashSet::new());
        assert_eq!(report.source_drifts.len(), 3);
        let by_id: std::collections::HashMap<String, &SourceDriftEntry> = report
            .source_drifts
            .iter()
            .map(|d| (d.id.clone(), d))
            .collect();
        assert_eq!(by_id["a"].new_sha256, "aaa_drifted");
        assert_eq!(by_id["b"].new_sha256, "DELETED");
        assert_eq!(by_id["c"].old_sha256, "ADDED");
    }

    /// Round-4 bughunt #1: `SourceLock` must not embed a wall-clock so
    /// `sources.lock` is byte-deterministic across runs.
    #[test]
    fn source_lock_does_not_serialise_generated_at() {
        let lock = SourceLock::empty();
        let s = serde_json::to_string(&lock).expect("ser");
        assert!(
            !s.contains("generated_at"),
            "sources.lock must not embed a wall-clock timestamp: {s}"
        );
    }

    #[test]
    fn drift_report_both_exit_code() {
        let report = DriftReport {
            source_drifts: vec![SourceDriftEntry {
                id: "x".into(),
                path: "x.md".into(),
                old_sha256: "aa".into(),
                new_sha256: "bb".into(),
            }],
            fenced_output_drifts: vec![OutputDriftEntry {
                path: "out.md".into(),
                old_sha256: "cc".into(),
                new_sha256: "dd".into(),
            }],
            unfenced_output_drifts: vec![],
        };
        assert!(!report.is_clean());
        assert_eq!(report.exit_code(), 3);
    }
}