truth-mirror 0.9.1

Truthfulness gate and adversarial reviewer harness for AI coding agents.
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
use assert_cmd::Command;
use predicates::prelude::*;
use truth_mirror::{
    cli::{Agent, ReviewerHarness},
    ledger::{LedgerEntry, LedgerStore, ReviewerConfig, Verdict},
    resolve::set_stdin_tty_override_for_testing,
};

fn seed_rejection(state_dir: &std::path::Path, sha: &str) {
    let store = LedgerStore::new(state_dir);
    store
        .append_entry(&LedgerEntry::new_at(
            sha,
            Verdict::Reject,
            "CLAIM: rejected | verified: cargo test | evidence: tests:cargo-test",
            vec!["tests:cargo-test".to_owned()],
            ReviewerConfig::new("claude", "claude-opus-4-1", false),
            vec!["unsupported claim".to_owned()],
            100,
        ))
        .unwrap();
}

/// A REAL commit SHA for --fixed-by tests: the CLI now refuses petitions for
/// commit objects that don't exist (so typos can't burn bounded attempts),
/// and these tests run with the crate repo as cwd.
fn head_sha() -> String {
    let out = std::process::Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .expect("git rev-parse HEAD");
    String::from_utf8(out.stdout).unwrap().trim().to_owned()
}

fn seed_rejection_with_attempts(state_dir: &std::path::Path, sha: &str, attempts: u32) {
    let store = LedgerStore::new(state_dir);
    store.append_entry(&rejected_entry_at(sha, 100)).unwrap();
    if attempts > 0 {
        store
            .append_petition_transition(
                sha,
                truth_mirror::ledger::Disposition::Open,
                truth_mirror::ledger::ResolutionKind::Resolved,
                "seeded prior attempt",
                attempts,
            )
            .unwrap();
    }
}

fn rejected_entry_at(sha: &str, timestamp: u64) -> LedgerEntry {
    LedgerEntry::new_at(
        sha,
        Verdict::Reject,
        "CLAIM: rejected | verified: cargo test | evidence: tests:cargo-test",
        vec!["tests:cargo-test".to_owned()],
        ReviewerConfig::new("claude", "claude-opus-4-1", false),
        vec!["unsupported claim".to_owned()],
        timestamp,
    )
}

#[test]
fn resolve_petition_enqueues_record_and_increments_attempts() {
    let temp = tempfile::tempdir().unwrap();
    seed_rejection(temp.path(), "abc123");

    let fix = head_sha();
    Command::cargo_bin("truth-mirror")
        .unwrap()
        .args([
            "--state-dir",
            temp.path().to_str().unwrap(),
            "resolve",
            "abc123",
            "--fixed-by",
            &fix,
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("enqueued petition review"))
        .stdout(predicate::str::contains("attempt 1/2"));

    // The petition must ALSO land in the review queue tagged with the original
    // rejection — the ledger bookkeeping alone left the flow a dead end (the
    // watcher never built a petition job).
    let queue_contents = std::fs::read_to_string(temp.path().join("review-queue.jsonl")).unwrap();
    assert!(queue_contents.contains(&format!("\"commit_sha\":\"{fix}\"")));
    assert!(queue_contents.contains("\"petition_for\":\"abc123\""));

    // The audit trail should now show attempt 1.
    Command::cargo_bin("truth-mirror")
        .unwrap()
        .args([
            "--state-dir",
            temp.path().to_str().unwrap(),
            "ledger",
            "history",
            "abc123",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("attempts=1"));
}

#[test]
fn resolve_petition_refuses_unknown_sha() {
    let temp = tempfile::tempdir().unwrap();

    Command::cargo_bin("truth-mirror")
        .unwrap()
        .args([
            "--state-dir",
            temp.path().to_str().unwrap(),
            "resolve",
            "missing123",
            "--fixed-by",
            &head_sha(),
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("missing123"));
}

#[test]
fn resolve_petition_refuses_when_already_resolved() {
    let temp = tempfile::tempdir().unwrap();
    let store = LedgerStore::new(temp.path());
    store
        .append_entry(&rejected_entry_at("abc123", 100))
        .unwrap();
    store.resolve("abc123").unwrap();

    Command::cargo_bin("truth-mirror")
        .unwrap()
        .args([
            "--state-dir",
            temp.path().to_str().unwrap(),
            "resolve",
            "abc123",
            "--fixed-by",
            &head_sha(),
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("not open"));
}

#[test]
fn resolve_petition_escalates_to_needs_human_on_third_attempt() {
    let temp = tempfile::tempdir().unwrap();
    seed_rejection_with_attempts(temp.path(), "abc123", 2);

    Command::cargo_bin("truth-mirror")
        .unwrap()
        .args([
            "--state-dir",
            temp.path().to_str().unwrap(),
            "resolve",
            "abc123",
            "--fixed-by",
            &head_sha(),
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("refused 3rd petition attempt"))
        .stdout(predicate::str::contains("needs-human"));

    let ledger = LedgerStore::new(temp.path());
    let entry = ledger.show("abc123").unwrap();
    assert_eq!(
        entry.disposition,
        truth_mirror::ledger::Disposition::NeedsHuman
    );
    assert_eq!(
        entry.resolution.as_ref().unwrap().kind,
        truth_mirror::ledger::ResolutionKind::NeedsHuman
    );
}

#[test]
fn resolve_waive_refuses_when_stdin_is_not_a_tty() {
    let temp = tempfile::tempdir().unwrap();
    seed_rejection(temp.path(), "abc123");
    // No override needed: the child subprocess gets a PIPED stdin, so the
    // REAL `is_terminal()` check refuses — this exercises the production
    // gate, not the test override (which never crosses the process boundary).

    let assertion = Command::cargo_bin("truth-mirror")
        .unwrap()
        .args([
            "--state-dir",
            temp.path().to_str().unwrap(),
            "resolve",
            "abc123",
            "--waive",
            "--reason",
            "approved exception",
        ])
        .assert()
        .failure();
    assertion.stderr(predicate::str::contains("TTY"));

    // Sanity: the ledger should NOT have been waived because the TTY gate
    // blocked the call before it could write to the ledger.
    let ledger = LedgerStore::new(temp.path());
    let entry = ledger.show("abc123").unwrap();
    assert_eq!(entry.disposition, truth_mirror::ledger::Disposition::Open);
    assert!(entry.resolution.is_none());
}

#[test]
fn resolve_waive_happy_path_under_simulated_tty() {
    // The waive happy path cannot be driven through a subprocess (a child
    // process cannot have a real interactive TTY under the test harness, and
    // the override is process-local), so this test calls the production
    // `resolve::run` handler IN-PROCESS with the override forced on. The
    // subprocess refusal paths are covered by the piped-stdin tests around
    // this one. This is the ONLY test that touches the process-global
    // override, so there is no cross-test race to serialize.
    let temp = tempfile::tempdir().unwrap();
    seed_rejection(temp.path(), "abc123");

    set_stdin_tty_override_for_testing(Some(true));
    let store = truth_mirror::ledger::LedgerStore::new(temp.path());
    let config = truth_mirror::config::TruthMirrorConfig::default();
    let args = truth_mirror::cli::ResolveArgs {
        rejection_sha: "abc123".to_owned(),
        fixed_by: None,
        waive: true,
        reason: Some("approved exception".to_owned()),
    };
    let exit = truth_mirror::resolve::run(args, temp.path(), &config).unwrap();
    assert_eq!(exit, std::process::ExitCode::SUCCESS);
    set_stdin_tty_override_for_testing(None);

    let entry = store.show("abc123").unwrap();
    assert_eq!(entry.disposition, truth_mirror::ledger::Disposition::Waived);
    let markdown = std::fs::read_to_string(temp.path().join("ledger.md")).unwrap();
    assert!(markdown.contains("approved exception"));
}

#[test]
fn resolve_waive_refuses_with_empty_reason() {
    let temp = tempfile::tempdir().unwrap();
    seed_rejection(temp.path(), "abc123");
    // No override: the blank reason is rejected before the TTY check runs,
    // and the subprocess would not see a parent-process override anyway.

    Command::cargo_bin("truth-mirror")
        .unwrap()
        .args([
            "--state-dir",
            temp.path().to_str().unwrap(),
            "resolve",
            "abc123",
            "--waive",
            "--reason",
            "   ",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("non-empty"));
}

#[test]
fn resolve_waive_without_reason_is_a_clap_error() {
    let temp = tempfile::tempdir().unwrap();
    seed_rejection(temp.path(), "abc123");

    // `--waive` declares `requires = "reason"`, so the missing flag is a
    // CLI-parse error — the handler (and its TTY gate) is never reached.
    Command::cargo_bin("truth-mirror")
        .unwrap()
        .args([
            "--state-dir",
            temp.path().to_str().unwrap(),
            "resolve",
            "abc123",
            "--waive",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("--reason"));
}

#[test]
fn resolve_petition_then_accept_transitions_to_resolved() {
    // End-to-end: invoke the petition plumbing through execute_review_job to
    // confirm that a petition review whose verdict is PASS transitions the
    // original rejection to Resolved with provenance.
    use truth_mirror::claim::{Claim, EvidenceRef};
    use truth_mirror::config::TruthMirrorConfig;
    use truth_mirror::ledger::{Disposition, LedgerStore, ResolutionKind};
    use truth_mirror::reviewer::{
        PetitionContext, ReviewJob, ReviewPlan, ReviewRequest, execute_review_job,
    };

    let temp = tempfile::tempdir().unwrap();
    let store = LedgerStore::new(temp.path());
    store
        .append_entry(&rejected_entry_at("abc123", 100))
        .unwrap();
    // The CLI counts the attempt when it enqueues the petition; the watcher's
    // verdict entry carries the SAME counter — no further increment.
    store
        .append_petition_transition(
            "abc123",
            truth_mirror::ledger::Disposition::Open,
            truth_mirror::ledger::ResolutionKind::Resolved,
            "petition review enqueued: fix=def456, attempts=1/2",
            1,
        )
        .unwrap();

    let claim = Claim::new(
        "petitions to resolve abc123",
        "cargo test",
        vec![EvidenceRef::parse("tests:cargo-test").unwrap()],
    )
    .unwrap();
    let original = store.show("abc123").unwrap();
    let petition = PetitionContext {
        original_sha: "abc123".to_owned(),
        fix_sha: "def456".to_owned(),
        original_claim: original.claim.clone(),
        original_summary: original.summary.clone(),
        original_findings: original.findings.clone(),
        original_structured_findings: original.structured_findings.clone(),
        original_reviewer_model: original.reviewer.model.clone(),
        attempts_so_far: 1,
    };
    let plan_request = ReviewRequest::new(
        Agent::Codex,
        "gpt-5.4",
        ReviewerHarness::Codex,
        "gpt-5.5",
        false,
        "review fix".to_owned(),
    );
    let _ = ReviewPlan::build(plan_request.clone()).unwrap();
    // Build the job manually so we can pass a petition context without
    // spawning a real reviewer process.
    let job = ReviewJob {
        commit_sha: "def456".to_owned(),
        claim,
        diff: "diff --git a/src/lib.rs b/src/lib.rs\n".to_owned(),
        context: String::new(),
        request: plan_request,
        strict: None,
        petition: Some(petition),
    };

    let pass_json = serde_json::json!({
        "verdict": "PASS",
        "summary": "Fix materially addresses each original finding.",
        "findings": [],
        "next_steps": [],
        "memory_skill": {
            "kind": "none",
            "learning_source": "",
            "reasoning": "No reusable procedural memory to propose."
        }
    })
    .to_string();

    struct ConstRunner(String);
    impl truth_mirror::reviewer::ProcessRunner for ConstRunner {
        fn run(
            &self,
            _invocation: &truth_mirror::reviewer::InvocationPlan,
            _prompt: &str,
        ) -> Result<truth_mirror::reviewer::ProcessOutput, truth_mirror::reviewer::ReviewerError>
        {
            Ok(truth_mirror::reviewer::ProcessOutput {
                status_code: Some(0),
                stdout: self.0.clone(),
                stderr: String::new(),
            })
        }
    }

    let config = TruthMirrorConfig::default();
    let _ = config; // Reserved for future reviewer-config plumbing.
    let execution = execute_review_job(job, &ConstRunner(pass_json), &store).unwrap();
    assert_eq!(execution.entries[0].verdict, Verdict::Pass);
    let entry = store.show("abc123").unwrap();
    assert_eq!(entry.disposition, Disposition::Resolved);
    assert_eq!(
        entry.resolution.as_ref().unwrap().kind,
        ResolutionKind::Resolved
    );
    assert!(entry.petition_attempts > 0);
}

#[test]
fn resolve_petition_non_accept_increments_attempts_within_bound() {
    use truth_mirror::claim::{Claim, EvidenceRef};
    use truth_mirror::config::TruthMirrorConfig;
    use truth_mirror::reviewer::{
        PetitionContext, ProcessOutput, ProcessRunner, ReviewJob, ReviewPlan, ReviewRequest,
        execute_review_job,
    };

    let temp = tempfile::tempdir().unwrap();
    let store = LedgerStore::new(temp.path());
    store
        .append_entry(&rejected_entry_at("abc123", 100))
        .unwrap();
    // The CLI counts the attempt when it enqueues the petition (resolve
    // --fixed-by writes this bookkeeping transition); the watcher's verdict
    // entry carries the SAME counter — no further increment.
    store
        .append_petition_transition(
            "abc123",
            truth_mirror::ledger::Disposition::Open,
            truth_mirror::ledger::ResolutionKind::Resolved,
            "petition review enqueued: fix=def456, attempts=1/2",
            1,
        )
        .unwrap();

    let original = store.show("abc123").unwrap();
    let petition = PetitionContext {
        original_sha: "abc123".to_owned(),
        fix_sha: "def456".to_owned(),
        original_claim: original.claim.clone(),
        original_summary: original.summary.clone(),
        original_findings: original.findings.clone(),
        original_structured_findings: original.structured_findings.clone(),
        original_reviewer_model: original.reviewer.model.clone(),
        attempts_so_far: 1,
    };
    let claim = Claim::new(
        "petitions to resolve abc123",
        "cargo test",
        vec![EvidenceRef::parse("tests:cargo-test").unwrap()],
    )
    .unwrap();
    let plan_request = ReviewRequest::new(
        Agent::Codex,
        "gpt-5.4",
        ReviewerHarness::Codex,
        "gpt-5.5",
        false,
        "review fix".to_owned(),
    );
    let _ = ReviewPlan::build(plan_request.clone()).unwrap();
    let job = ReviewJob {
        commit_sha: "def456".to_owned(),
        claim,
        diff: "diff --git a/src/lib.rs b/src/lib.rs\n".to_owned(),
        context: String::new(),
        request: plan_request,
        strict: None,
        petition: Some(petition),
    };

    let reject_json = serde_json::json!({
        "verdict": "REJECT",
        "summary": "Fix does not address the finding.",
        "findings": [{
            "severity": "high",
            "title": "still unaddressed",
            "body": "Fix is incomplete.",
            "file": "src/lib.rs",
            "line_start": 1,
            "line_end": 1,
            "confidence": 90,
            "recommendation": "Address the root cause."
        }],
        "next_steps": ["fix it"],
        "memory_skill": {
            "kind": "none",
            "learning_source": "",
            "reasoning": "no reusable memory"
        }
    })
    .to_string();

    struct ConstRunner(String);
    impl ProcessRunner for ConstRunner {
        fn run(
            &self,
            _invocation: &truth_mirror::reviewer::InvocationPlan,
            _prompt: &str,
        ) -> Result<ProcessOutput, truth_mirror::reviewer::ReviewerError> {
            Ok(ProcessOutput {
                status_code: Some(0),
                stdout: self.0.clone(),
                stderr: String::new(),
            })
        }
    }

    let _config = TruthMirrorConfig::default();
    let execution = execute_review_job(job, &ConstRunner(reject_json), &store).unwrap();
    assert_eq!(execution.entries[0].verdict, Verdict::Reject);
    let entry = store.show("abc123").unwrap();
    assert_eq!(entry.disposition, truth_mirror::ledger::Disposition::Open);
    assert_eq!(entry.petition_attempts, 1);
}

#[test]
fn resolve_petition_non_accept_at_bound_escalates_to_needs_human() {
    use truth_mirror::claim::{Claim, EvidenceRef};
    use truth_mirror::config::TruthMirrorConfig;
    use truth_mirror::reviewer::{
        PetitionContext, ProcessOutput, ProcessRunner, ReviewJob, ReviewPlan, ReviewRequest,
        execute_review_job,
    };

    let temp = tempfile::tempdir().unwrap();
    let store = LedgerStore::new(temp.path());
    store
        .append_entry(&rejected_entry_at("abc123", 100))
        .unwrap();
    // Two CLI petitions have been counted (attempts = MAX = 2); the watcher's
    // non-PASS verdict for the second one crosses the bound and escalates.
    store
        .append_petition_transition(
            "abc123",
            truth_mirror::ledger::Disposition::Open,
            truth_mirror::ledger::ResolutionKind::Resolved,
            "petition review enqueued: fix=def456, attempts=2/2",
            2,
        )
        .unwrap();

    let original = store.show("abc123").unwrap();
    let petition = PetitionContext {
        original_sha: "abc123".to_owned(),
        fix_sha: "def456".to_owned(),
        original_claim: original.claim.clone(),
        original_summary: original.summary.clone(),
        original_findings: original.findings.clone(),
        original_structured_findings: original.structured_findings.clone(),
        original_reviewer_model: original.reviewer.model.clone(),
        attempts_so_far: 2,
    };
    let claim = Claim::new(
        "petitions to resolve abc123",
        "cargo test",
        vec![EvidenceRef::parse("tests:cargo-test").unwrap()],
    )
    .unwrap();
    let plan_request = ReviewRequest::new(
        Agent::Codex,
        "gpt-5.4",
        ReviewerHarness::Codex,
        "gpt-5.5",
        false,
        "review fix".to_owned(),
    );
    let _ = ReviewPlan::build(plan_request.clone()).unwrap();
    let job = ReviewJob {
        commit_sha: "def456".to_owned(),
        claim,
        diff: "diff --git a/src/lib.rs b/src/lib.rs\n".to_owned(),
        context: String::new(),
        request: plan_request,
        strict: None,
        petition: Some(petition),
    };

    let reject_json = serde_json::json!({
        "verdict": "REJECT",
        "summary": "Fix still does not address the finding.",
        "findings": [{
            "severity": "high",
            "title": "still unaddressed",
            "body": "Fix is incomplete.",
            "file": "src/lib.rs",
            "line_start": 1,
            "line_end": 1,
            "confidence": 90,
            "recommendation": "Address the root cause."
        }],
        "next_steps": ["fix it"],
        "memory_skill": {
            "kind": "none",
            "learning_source": "",
            "reasoning": "no reusable memory"
        }
    })
    .to_string();

    struct ConstRunner(String);
    impl ProcessRunner for ConstRunner {
        fn run(
            &self,
            _invocation: &truth_mirror::reviewer::InvocationPlan,
            _prompt: &str,
        ) -> Result<ProcessOutput, truth_mirror::reviewer::ReviewerError> {
            Ok(ProcessOutput {
                status_code: Some(0),
                stdout: self.0.clone(),
                stderr: String::new(),
            })
        }
    }

    let _config = TruthMirrorConfig::default();
    let _ = execute_review_job(job, &ConstRunner(reject_json), &store).unwrap();
    let entry = store.show("abc123").unwrap();
    assert_eq!(
        entry.disposition,
        truth_mirror::ledger::Disposition::NeedsHuman
    );
    assert_eq!(entry.petition_attempts, 2);
}