monochromatic-git-policy-cli 0.1.0

Repository-owned Git policy wrapper: forwards Git commands and checks commits against configured policies.
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
//! Controls for dead-transaction recovery against real repositories,
//!  and the scene builder the
//! registry and entry tests share.

use super::*;
use crate::capture_records::{
    CAPTURED_FILENAME, CapturedRecord, encode_captured_record, landed_record_directory,
};
use crate::recovery_files::file_identity_of;
use crate::recovery_files::tests::lock_identity_of;
use crate::recovery_inspect::tests::owner_bytes;
use crate::test_support::{fixture, git, git_context, git_text, remove, repository};
use crate::transaction_journal::{AddedPath, FileIdentity, IndexLockRecord, LockIdentity};
use crate::transaction_journal_encode::tests::sample_preparing;
use crate::transaction_journal_encode::{
    encode_index_lock, encode_landing, encode_preparing, encode_ref_updated,
};
use crate::transaction_registry::{
    TRANSACTION_ROOT_NAME, ensure_transaction_root, publish_transaction_directory,
};

/// The transaction ID the fixtures use.
pub(crate) const ID: &str = "0b6c2c1e-6f5b-4d0e-9a55-3f5d8e2f6a10";

/// A repository with a registry and one published transaction directory.
pub(crate) struct Scene {
    /// Fixture root.
    pub(crate) root: PathBuf,
    /// Repository worktree.
    pub(crate) repo: PathBuf,
    /// Its Git directory.
    pub(crate) git_dir: PathBuf,
    /// Registry root.
    pub(crate) registry: PathBuf,
    /// Transaction directory.
    pub(crate) directory: PathBuf,
    /// Shadow repository path.
    pub(crate) shadow: PathBuf,
    /// `HEAD` before the transaction.
    pub(crate) base: String,
    /// The commit the transaction prepared,
    ///  not on any branch yet.
    pub(crate) prepared: String,
}

/// Methods building transaction state in a scene.
impl Scene {
    /// What:
    ///  A fresh scene whose transaction is owned by a live or dead owner.
    /// Why:
    ///   Every recovery case starts from a published directory.
    pub(crate) fn new(name: &str, live: bool) -> Scene {
        let root: PathBuf = fixture(name);
        let repo: PathBuf = repository(root.as_path(), "repo");
        let git_dir: PathBuf = repo.join(".git");
        // An empty commit leaves no index file; landings always have one.
        git(repo.as_path(), &["read-tree", "HEAD"]);
        let registry: PathBuf = git_dir.join(TRANSACTION_ROOT_NAME);
        ensure_transaction_root(registry.as_path()).expect("registry");
        let directory: PathBuf = publish_transaction_directory(
            registry.as_path(),
            ID,
            owner_bytes(ID, "2026-10-06T00:00:00.000Z", live).as_slice(),
        )
        .expect("published");
        let base: String = git_text(repo.as_path(), &["rev-parse", "HEAD"]);
        let tree: String = git_text(repo.as_path(), &["rev-parse", "HEAD^{tree}"]);
        let prepared: String = git_text(
            repo.as_path(),
            &[
                "commit-tree",
                "-p",
                base.as_str(),
                "-m",
                "prepared",
                tree.as_str(),
            ],
        );
        let shadow: PathBuf = git_dir.join("cli-git").join("shadow").join(ID);
        return Scene {
            root,
            repo,
            git_dir,
            registry,
            directory,
            shadow,
            base,
            prepared,
        };
    }

    /// What:
    ///  The preparing record of this scene.
    /// Why:
    ///   Recovery reads every path from it.
    pub(crate) fn preparing(&self) -> PreparingRecord {
        let mut record: PreparingRecord = sample_preparing();
        record.transaction_id = String::from(ID);
        record.base = Base::Commit(self.base.clone());
        record.repository_root = text(self.repo.as_path());
        record.git_dir = text(self.git_dir.as_path());
        record.common_dir = text(self.git_dir.as_path());
        record.real_index_path = text(self.git_dir.join("index").as_path());
        record.object_directory = text(self.git_dir.join("objects").as_path());
        record.shadow_path = text(self.shadow.as_path());
        return record;
    }

    /// What:
    ///  Write `preparing.json` and create the shadow repository directory.
    /// Why:
    ///   A transaction past capture.
    pub(crate) fn capture(&self) {
        std::fs::write(
            self.directory.join(PREPARING_FILENAME),
            encode_preparing(&self.preparing()),
        )
        .expect("preparing");
        std::fs::create_dir_all(self.shadow.join("objects").join("info")).expect("shadow");
        // The shadow store reaches the real objects through alternates, as a real shadow does.
        std::fs::write(
            self.shadow.join("objects").join("info").join("alternates"),
            format!("{}\n", self.git_dir.join("objects").display()),
        )
        .expect("alternates");
    }

    /// What:
    ///  Create the real `index.lock` and record it as attempt 1.
    /// Why:
    ///   A transaction inside the landing critical section.
    pub(crate) fn lock_index(&self) -> LockIdentity {
        let lock: PathBuf = self.git_dir.join("index.lock");
        std::fs::write(&lock, b"").expect("index lock");
        let identity: LockIdentity = lock_identity_of(lock.as_path());
        std::fs::write(
            self.directory.join("index-lock-1.json"),
            encode_index_lock(&IndexLockRecord {
                attempt: 1,
                lock: identity.clone(),
            }),
        )
        .expect("index lock record");
        std::fs::write(
            self.git_dir.join("index~pid.lock"),
            format!("pid {}\n", std::process::id()),
        )
        .expect("pid file");
        return identity;
    }

    /// What:
    ///  Write landing attempt 1 for a commit (or a normalization) with both index snapshots.
    /// Why:
    ///   A transaction that reached the compare-and-swap.
    pub(crate) fn land(&self, operation: LandingOperation, added: Vec<AddedPath>) -> LandingRecord {
        let lock: LockIdentity = self.lock_index();
        let real_index: PathBuf = self.git_dir.join("index");
        std::fs::copy(&real_index, self.directory.join("pre-landing-1.index"))
            .expect("pre-landing");
        std::fs::write(self.directory.join("post-1.index"), b"post index").expect("post");
        let record: LandingRecord = LandingRecord {
            attempt: 1,
            operation,
            expected_old: Base::Commit(self.base.clone()),
            new_oid: if operation == LandingOperation::Commit {
                Some(self.prepared.clone())
            } else {
                None
            },
            landed_tree_oid: String::from("4b825dc642cb6eb9a060e54bf8d69288fbee4904"),
            pre_landing_index: identity(self.directory.join("pre-landing-1.index").as_path()),
            post_index: identity(self.directory.join("post-1.index").as_path()),
            lock,
            pack_name: None,
            added_paths: added,
            selected_worktree_paths: Vec::new(),
        };
        std::fs::write(
            self.directory.join("landing-1.json"),
            encode_landing(&record),
        )
        .expect("landing");
        return record;
    }

    /// What:
    ///  Move `main` to the prepared commit with the nonce reflog entry,
    ///  as the landing does.
    /// Why:
    ///   A transaction whose compare-and-swap succeeded.
    pub(crate) fn move_branch(&self) {
        let message: String = format!("commit (cli-git {ID}): prepared");
        git(
            self.repo.as_path(),
            &[
                "update-ref",
                "-m",
                message.as_str(),
                "refs/heads/main",
                self.prepared.as_str(),
                self.base.as_str(),
            ],
        );
    }

    /// What:
    ///  The recovery place of this scene.
    /// Why:
    ///   Recovery runs Git in the repository.
    pub(crate) fn place(&self) -> RecoveryPlace {
        return RecoveryPlace {
            git: git_context(),
            cwd: self.repo.clone(),
            common_dir: self.git_dir.clone(),
        };
    }

    /// What:
    ///  Remove the fixture.
    /// Why:
    ///   Every test cleans up after itself.
    pub(crate) fn finish(self) {
        remove(self.root.as_path());
    }
}

/// A path as UTF-8 text.
fn text(path: &Path) -> String {
    return path.to_str().expect("UTF-8 fixture path").to_string();
}

/// The recorded identity of an artifact.
fn identity(path: &Path) -> FileIdentity {
    let (device, inode, _) = file_identity_of(path).expect("identity");
    return FileIdentity { device, inode };
}

/// Action names are the incumbent's.
#[test]
fn actions_have_the_incumbent_names() {
    let pairs: [(RecoveryAction, &str); 9] = [
        (RecoveryAction::CommitNotCreated, "commit-not-created"),
        (
            RecoveryAction::NormalizationInstalled,
            "normalization-installed",
        ),
        (RecoveryAction::IndexInstalled, "index-installed"),
        (RecoveryAction::AlreadyInstalled, "already-installed"),
        (RecoveryAction::OwnerActive, "owner-active"),
        (RecoveryAction::Vanished, "vanished"),
        (RecoveryAction::StagingUnattributed, "staging-unattributed"),
        (RecoveryAction::StagingRetained, "staging-retained"),
        (RecoveryAction::RetiredRemoved, "retired-removed"),
    ];
    for (action, name) in pairs {
        assert_eq!(action_name(action), name);
    }
}

/// An owner that died before capture leaves only its directory and maybe a shadow.
#[test]
fn deaths_before_capture_remove_everything() {
    let scene: Scene = Scene::new("recovery-landing-precapture", false);
    std::fs::create_dir_all(scene.shadow.as_path()).expect("shadow");
    let action: RecoveryAction =
        recover_dead_transaction(&scene.place(), scene.directory.as_path(), ID, 1)
            .expect("recovered");
    assert_eq!(action, RecoveryAction::CommitNotCreated);
    assert!(!scene.directory.exists());
    assert!(!scene.shadow.exists());
    scene.finish();
}

/// An unreleased journal format stops recovery and keeps the directory.
#[test]
fn unreleased_journals_fail_closed() {
    let scene: Scene = Scene::new("recovery-landing-unreleased", false);
    std::fs::write(scene.directory.join(UNRELEASED_JOURNAL_FILENAME), b"{}").expect("journal");
    assert_eq!(
        recover_dead_transaction(&scene.place(), scene.directory.as_path(), ID, 1)
            .expect_err("unreleased")
            .0,
        format!(
            "Transaction directory uses an unreleased journal format; inspect it before removing it: {}",
            scene.directory.display()
        )
    );
    assert!(scene.directory.join(UNRELEASED_JOURNAL_FILENAME).exists());
    scene.finish();
}

/// Without a landing record the owned lock,
///  PID file,
///  keeps and shadow go.
#[test]
fn deaths_before_landing_discard_the_attempt() {
    let scene: Scene = Scene::new("recovery-landing-prelanding", false);
    scene.capture();
    scene.lock_index();
    let pack: PathBuf = scene.git_dir.join("objects").join("pack");
    std::fs::create_dir_all(&pack).expect("pack directory");
    std::fs::write(pack.join("pack-x.keep"), format!("cli-git {ID}\n")).expect("keep");
    let index_before: Vec<u8> = std::fs::read(scene.git_dir.join("index")).expect("index");
    let action: RecoveryAction = recover_dead_transaction(
        &scene.place(),
        scene.directory.as_path(),
        ID,
        i64::from(std::process::id()),
    )
    .expect("recovered");
    assert_eq!(action, RecoveryAction::CommitNotCreated);
    assert!(!scene.git_dir.join("index.lock").exists());
    assert!(!scene.git_dir.join("index~pid.lock").exists());
    assert!(!pack.join("pack-x.keep").exists());
    assert!(!scene.shadow.exists());
    assert!(!scene.directory.exists());
    assert_eq!(
        std::fs::read(scene.git_dir.join("index")).expect("index"),
        index_before
    );
    assert_eq!(
        git_text(scene.repo.as_path(), &["rev-parse", "HEAD"]),
        scene.base
    );
    scene.finish();
}

/// A landing that never moved the branch is discarded.
#[test]
fn unlanded_attempts_are_discarded() {
    let scene: Scene = Scene::new("recovery-landing-unlanded", false);
    scene.capture();
    scene.land(LandingOperation::Commit, Vec::new());
    let action: RecoveryAction = recover_dead_transaction(
        &scene.place(),
        scene.directory.as_path(),
        ID,
        i64::from(std::process::id()),
    )
    .expect("recovered");
    assert_eq!(action, RecoveryAction::CommitNotCreated);
    assert!(!scene.git_dir.join("index.lock").exists());
    assert!(!scene.directory.exists());
    assert_eq!(
        git_text(scene.repo.as_path(), &["rev-parse", "HEAD"]),
        scene.base
    );
    scene.finish();
}

/// A landed commit gets its index,
///  landed record,
///  added-path copies and cleanup.
#[test]
fn landed_commits_are_completed() {
    let scene: Scene = Scene::new("recovery-landing-landed", false);
    scene.capture();
    std::fs::write(scene.repo.join("added.txt"), b"x").expect("worktree copy");
    let original: String = git_text(scene.repo.as_path(), &["hash-object", "-w", "added.txt"]);
    std::fs::write(scene.root.join("intended"), b"x\n").expect("intended input");
    let intended_path: String = text(scene.root.join("intended").as_path());
    let intended: String = git_text(
        scene.repo.as_path(),
        &["hash-object", "-w", intended_path.as_str()],
    );
    let added: AddedPath = AddedPath {
        path: String::from("added.txt"),
        git_mode: String::from("100644"),
        original_oid: original,
        intended_oid: intended,
    };
    std::fs::write(
        scene.directory.join(CAPTURED_FILENAME),
        encode_captured_record(&CapturedRecord {
            worktree_id: String::from("w"),
            sequence: 1,
            next_sequence_before_base: 1,
            worktree_paths: vec![String::from("added.txt")],
        }),
    )
    .expect("captured");
    scene.land(LandingOperation::Commit, vec![added]);
    scene.move_branch();
    std::fs::write(
        scene.directory.join(REF_UPDATED_FILENAME_FOR_TEST),
        encode_ref_updated(scene.prepared.as_str()),
    )
    .expect("marker");
    let action: RecoveryAction = recover_dead_transaction(
        &scene.place(),
        scene.directory.as_path(),
        ID,
        i64::from(std::process::id()),
    )
    .expect("recovered");
    assert_eq!(action, RecoveryAction::IndexInstalled);
    assert_eq!(
        std::fs::read(scene.git_dir.join("index")).expect("index"),
        b"post index"
    );
    assert!(!scene.git_dir.join("index.lock").exists());
    assert_eq!(
        std::fs::read(scene.repo.join("added.txt")).expect("completed copy"),
        b"x\n"
    );
    assert!(
        landed_record_directory(scene.git_dir.as_path())
            .join(format!("{}.json", scene.prepared))
            .exists()
    );
    assert!(!scene.shadow.exists());
    assert!(!scene.directory.exists());
    scene.finish();
}

/// The marker filename,
///  spelled out so a renamed constant fails this test.
const REF_UPDATED_FILENAME_FOR_TEST: &str = "ref-updated.json";

/// A landed commit whose index was already installed is recognized.
#[test]
fn installed_indexes_are_recognized() {
    let scene: Scene = Scene::new("recovery-landing-installed", false);
    scene.capture();
    scene.land(LandingOperation::Commit, Vec::new());
    scene.move_branch();
    std::fs::copy(
        scene.directory.join("post-1.index"),
        scene.git_dir.join("index"),
    )
    .expect("installed");
    let action: RecoveryAction = recover_dead_transaction(
        &scene.place(),
        scene.directory.as_path(),
        ID,
        i64::from(std::process::id()),
    )
    .expect("recovered");
    assert_eq!(action, RecoveryAction::AlreadyInstalled);
    assert!(!scene.git_dir.join("index.lock").exists());
    assert!(!scene.directory.exists());
    scene.finish();
}

/// A normalization is completed only while the target did not move.
#[test]
fn normalizations_need_an_unmoved_target() {
    let scene: Scene = Scene::new("recovery-landing-normalize", false);
    scene.capture();
    scene.land(LandingOperation::NormalizeOnly, Vec::new());
    git(
        scene.repo.as_path(),
        &["update-ref", "refs/heads/main", scene.prepared.as_str()],
    );
    assert_eq!(
        recover_dead_transaction(&scene.place(), scene.directory.as_path(), ID, 1)
            .expect_err("moved")
            .0,
        format!(
            "refs/heads/main moved after an interrupted normalization; recovery retained at {}",
            scene.directory.display()
        )
    );
    assert!(scene.directory.exists());
    git(
        scene.repo.as_path(),
        &["update-ref", "refs/heads/main", scene.base.as_str()],
    );
    assert_eq!(
        recover_dead_transaction(&scene.place(), scene.directory.as_path(), ID, 1)
            .expect("unmoved"),
        RecoveryAction::NormalizationInstalled
    );
    assert_eq!(
        std::fs::read(scene.git_dir.join("index")).expect("index"),
        b"post index"
    );
    assert!(!scene.directory.exists());
    scene.finish();
}

/// An unborn target compares as unborn.
#[test]
fn unborn_targets_compare_as_unborn() {
    let scene: Scene = Scene::new("recovery-landing-unborn", false);
    let mut preparing: PreparingRecord = scene.preparing();
    preparing.target_ref = String::from("refs/heads/none");
    assert!(target_unmoved(&scene.place(), &preparing, &Base::Unborn));
    assert!(!target_unmoved(
        &scene.place(),
        &preparing,
        &Base::Commit(scene.base.clone())
    ));
    preparing.target_ref = String::from("refs/heads/main");
    assert!(target_unmoved(
        &scene.place(),
        &preparing,
        &Base::Commit(scene.base.clone())
    ));
    scene.finish();
}