truth-mirror 0.10.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
612
613
614
615
616
617
//! Resolution-as-petition flow and human-only waive lane.
//!
//! `truth-mirror resolve <rejection-sha> --fixed-by <fix-sha>` enqueues a
//! RESOLUTION re-review. The reviewer is asked whether the fix materially
//! addresses each finding; an accepting verdict — `PASS`, or `FLAG` with its
//! non-blocking debt (see [`petition_accepts`], the one accept criterion) —
//! transitions the original rejection to `resolved`. A `REJECT` leaves the
//! bounded attempt counter spent; once the counter hits
//! [`MAX_PETITION_ATTEMPTS`], the rejection escalates to `needs-human` and
//! stays visible in reinjection but is no longer agent-actionable.
//!
//! `truth-mirror resolve <rejection-sha> --waive --reason <text>` is the
//! human-only waive lane. It refuses to run when stdin is not an
//! interactive TTY so agents structurally cannot invoke it.

use std::{
    fs,
    io::{self, IsTerminal, Write},
    path::Path,
    process::ExitCode,
    sync::atomic::{AtomicI32, Ordering},
    time::{Duration, Instant},
};

use anyhow::Result;

use crate::{
    cli::ResolveArgs,
    config::TruthMirrorConfig,
    ledger::{LedgerStore, ResolutionKind, Verdict},
};

/// Maximum number of `resolve --fixed-by` attempts allowed before the
/// rejection escalates to `needs-human`. The brief fixes this at 2
/// (the 3rd attempt is refused and escalates).
pub const MAX_PETITION_ATTEMPTS: u32 = 2;

pub fn run(args: ResolveArgs, state_dir: &Path, _config: &TruthMirrorConfig) -> Result<ExitCode> {
    let store = LedgerStore::new(state_dir);

    if args.waive {
        return run_waive(args, &store);
    }
    if let Some(fix_sha) = args.fixed_by {
        return run_petition(args.rejection_sha, fix_sha, &store, state_dir);
    }

    anyhow::bail!(
        "resolve requires either --fixed-by <fix-sha> (agent petition) or --waive --reason <text> (human-only)"
    )
}

fn run_waive(args: ResolveArgs, store: &LedgerStore) -> Result<ExitCode> {
    let reason = args
        .reason
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| anyhow::anyhow!("--waive requires a non-empty --reason"))?;

    let entry = waive_human(store, &args.rejection_sha, reason)?;
    println!(
        "truth-mirror: waived {} via human lane ({:?})",
        entry.commit_sha,
        ResolutionKind::Waived
    );
    Ok(ExitCode::SUCCESS)
}

/// Human-only waive lane shared by the CLI and the control-panel TUI.
///
/// Refuses when stdin is not a TTY so agents cannot invoke it structurally.
pub fn waive_human(
    store: &LedgerStore,
    rejection_sha: &str,
    reason: &str,
) -> Result<crate::ledger::LedgerEntry> {
    let reason = reason.trim();
    if reason.is_empty() {
        anyhow::bail!("waive requires a non-empty reason");
    }
    if !stdin_is_tty() {
        anyhow::bail!(
            "--waive requires an interactive terminal (TTY); refuse when stdin is not a tty so agents structurally cannot invoke it"
        );
    }
    store
        .waive(rejection_sha, reason)
        .map_err(|error| anyhow::anyhow!(error.to_string()))
}

fn run_petition(
    rejection_sha: String,
    fix_sha: String,
    store: &LedgerStore,
    state_dir: &Path,
) -> Result<ExitCode> {
    let message = petition_fix(store, state_dir, &rejection_sha, &fix_sha)?;
    println!("truth-mirror: {message}");
    Ok(ExitCode::SUCCESS)
}

/// Enqueue a petition re-review for `fix_sha` against an open rejection.
///
/// Same guards and ledger/queue writes as `truth-mirror resolve --fixed-by`.
/// Returns a human-readable status line (no terminal I/O).
pub fn petition_fix(
    store: &LedgerStore,
    state_dir: &Path,
    rejection_sha: &str,
    fix_sha: &str,
) -> Result<String> {
    let original = store.show(rejection_sha).map_err(|error| {
        anyhow::anyhow!("rejection {rejection_sha} not found in ledger: {error}")
    })?;
    if !original.is_unresolved_rejection() {
        let disposition = original.disposition;
        let verdict = original.verdict;
        let petition_attempts = store.petition_attempts_for(rejection_sha).unwrap_or(0);
        anyhow::bail!(
            "rejection {rejection_sha} is not open (verdict={verdict}, disposition={disposition}, petition_attempts={petition_attempts}); no petition review is needed"
        );
    }

    // The unresolvable-fix-ref guard must NOT spend an attempt (two typos
    // would otherwise exhaust the bound and escalate to needs-human without a
    // single real review), so it stays outside the admission lock below.
    //
    // Inside a git work tree the ref is resolved to a full commit SHA at
    // enqueue time: 0.9.2 recorded the literal string "HEAD" as the fix
    // identity, and short SHAs gave one commit two independent ledger
    // identities. The guarantee is scoped to git work trees: outside one the
    // value passes through unchanged BY DESIGN (ledger-only setups have
    // nothing to resolve against — see resolve_fix_ref_to_full_sha).
    let fix_sha = &resolve_fix_ref_to_full_sha(fix_sha)?;

    // Everything from here down — the in-flight check, the attempt-count
    // read, spending the attempt, and enqueuing — is one serialized
    // transaction. CodeRabbit MAJOR (PR #13, resolve.rs ~136-182): without
    // this lock, two concurrent petitions for the same rejection could both
    // read an empty queue and an unspent attempt count, both append a spent
    // attempt, and both enqueue — producing duplicate petitions in the
    // queue, exactly the bug this closes.
    let admission_guard = PetitionAdmissionLock::acquire(state_dir)?;

    let in_flight = crate::reviewer::ReviewQueue::new(state_dir)
        .pending()
        .map_err(|error| anyhow::anyhow!(error.to_string()))?
        .into_iter()
        .any(|item| item.petition_for.as_deref() == Some(rejection_sha));
    if in_flight {
        anyhow::bail!(
            "refusing petition without spending an attempt: a petition for {rejection_sha} is already queued; let the watcher drain it first"
        );
    }

    let prior_attempts = store.petition_attempts_for(rejection_sha).unwrap_or(0);
    if prior_attempts >= MAX_PETITION_ATTEMPTS {
        let reason = format!(
            "petition refused: {MAX_PETITION_ATTEMPTS} attempts already recorded for {rejection_sha}; escalating to needs-human"
        );
        store
            .escalate_to_needs_human(rejection_sha, &reason)
            .map_err(|error| anyhow::anyhow!(error.to_string()))?;
        return Ok(format!(
            "refused 3rd petition attempt for {rejection_sha}; escalation to needs-human recorded"
        ));
    }

    // Two writes make a petition: (1) the attempt bookkeeping entry on the
    // rejection so the counter is spent even before the reviewer verdict
    // lands, and (2) the QUEUE item for the fix commit, tagged with the
    // original rejection SHA so drain builds a petition job. The watcher
    // (or `truth-mirror watch --once`) drains it; execute_review_job swaps
    // in the petition prompt and apply_petition_transition transitions the
    // original rejection based on the verdict.
    let next_attempts = prior_attempts.saturating_add(1);
    let reason = format!(
        "petition review enqueued: fix={fix_sha}, attempts={next_attempts}/{MAX_PETITION_ATTEMPTS}"
    );
    store
        .append_petition_transition(
            rejection_sha,
            crate::ledger::Disposition::Open,
            ResolutionKind::Resolved,
            &reason,
            next_attempts,
        )
        .map_err(|error| anyhow::anyhow!(error.to_string()))?;
    if let Err(enqueue_error) = crate::reviewer::ReviewQueue::new(state_dir)
        .enqueue_petition(fix_sha, rejection_sha)
        .map_err(|error| anyhow::anyhow!(error.to_string()))
    {
        // Codex round-2 P2: a compensating entry writing `prior_attempts`
        // does NOT roll anything back. `petition_attempts_for` takes the
        // MAX attempt count across the sha's whole history (a deliberate
        // defense against any accidental non-monotonic write elsewhere), so
        // the just-appended `next_attempts` entry keeps winning regardless
        // of what we append after it — round 1's "rollback" was silently a
        // no-op. And we cannot fix this by writing the ledger entry only
        // AFTER a successful enqueue either: `petition_context_from_ledger`
        // reads `petition_attempts_for` when the watcher drains the queued
        // item, and an already-running watcher can dequeue and read that
        // BEFORE a second post-enqueue write lands, using a stale
        // (not-yet-incremented) attempt count.
        //
        // So be honest about what actually happened instead: the attempt is
        // genuinely spent with nothing queued for it, which is exactly the
        // outcome a REJECT verdict produces (see `apply_petition_transition`)
        // — escalate if this exhausted the bound, otherwise leave it Open at
        // the now-correct count, and surface the enqueue failure so the
        // caller knows to retry.
        if next_attempts >= MAX_PETITION_ATTEMPTS {
            let reason = format!(
                "petition enqueue failed after the attempt was recorded ({enqueue_error}); {MAX_PETITION_ATTEMPTS} attempts now spent for {rejection_sha}; escalating to needs-human"
            );
            store
                .escalate_to_needs_human_with_attempts(rejection_sha, &reason, next_attempts)
                .map_err(|error| anyhow::anyhow!(error.to_string()))?;
            anyhow::bail!(
                "failed to enqueue petition review for {rejection_sha}: {enqueue_error}; the spent attempt exhausted the bound and the rejection was escalated to needs-human"
            );
        }
        anyhow::bail!(
            "failed to enqueue petition review for {rejection_sha}: {enqueue_error}; the attempt was already recorded (attempts={next_attempts}/{MAX_PETITION_ATTEMPTS}) with nothing queued — retry resolve --fixed-by if attempts remain"
        );
    }
    // Codex round-2 P2: the duplicate-petition critical section this lock
    // exists for is complete now that the ledger and queue writes both
    // succeeded. `ensure_watcher` can reconcile stale runs and wait on the
    // run-store lock for its own timeout; holding admission through that call
    // would let an unrelated concurrent petition time out on THIS lock even
    // though nothing about its critical section still overlaps.
    drop(admission_guard);
    // Same contract as the post-commit hook: enqueuing must guarantee a
    // consumer exists. Best-effort — a failed spawn must not fail the
    // petition; the next enqueue (or a manual `watch`) retries.
    if let Err(error) = crate::watcher::ensure_watcher(state_dir) {
        eprintln!("truth-mirror: warning: failed to ensure a review watcher: {error}");
    }
    Ok(format!(
        "enqueued petition review for fix={fix_sha} against rejection={rejection_sha} (attempt {next_attempts}/{MAX_PETITION_ATTEMPTS}); the watcher will drain and transition the rejection based on the verdict"
    ))
}

/// Name of the lockfile serializing petition admission inside a state dir.
/// Created once and never deleted — see `PetitionAdmissionLock`'s doc comment
/// for why.
const PETITION_ADMISSION_LOCK_FILE: &str = "resolve-petition-admission.lock";
/// Total time to wait for a concurrent admission to finish before giving up.
/// Admission is a handful of filesystem reads/writes, never a network call or
/// a long-held guard, so ordinary contention resolves in milliseconds.
const PETITION_ADMISSION_LOCK_WAIT: Duration = Duration::from_secs(10);
const PETITION_ADMISSION_LOCK_POLL: Duration = Duration::from_millis(25);

/// Serializes petition admission (in-flight check, attempt spend, and
/// enqueue) per state dir. Dropping the guard releases the lock.
///
/// Round 1 backed this with a `create_new` marker file plus an mtime-based
/// staleness heuristic — the identical TOCTOU CodeRabbit/Gemini/Codex found
/// in `reviewer.rs`'s round-1 reclaim gate: two contenders can both decide a
/// stranded marker is stale and race to unlink it, letting both through. A
/// real OS advisory lock (`flock` via `std::fs::File::try_lock`/`lock`) has
/// no such problem: the kernel releases it automatically when the holding
/// process's file descriptor closes, crash included, so there is nothing to
/// detect as stale and nothing to unlink. The backing file is created once
/// and never deleted: unlinking a `flock`ed file while another process still
/// holds it open would let a new caller open-and-lock a fresh inode at the
/// same path, silently reintroducing a second holder.
struct PetitionAdmissionLock {
    // Held only for its RAII effect: dropping it closes the fd, which
    // releases the flock. Never read directly.
    #[allow(dead_code)]
    file: fs::File,
}

impl PetitionAdmissionLock {
    fn acquire(state_dir: &Path) -> Result<Self> {
        fs::create_dir_all(state_dir)?;
        let path = state_dir.join(PETITION_ADMISSION_LOCK_FILE);
        let file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(false)
            .open(&path)?;
        let started = Instant::now();
        loop {
            match file.try_lock() {
                Ok(()) => return Ok(Self { file }),
                Err(fs::TryLockError::WouldBlock) => {
                    if started.elapsed() >= PETITION_ADMISSION_LOCK_WAIT {
                        anyhow::bail!(
                            "timed out after {}s waiting for the petition admission lock at {}",
                            PETITION_ADMISSION_LOCK_WAIT.as_secs(),
                            path.display()
                        );
                    }
                    std::thread::sleep(PETITION_ADMISSION_LOCK_POLL);
                }
                Err(fs::TryLockError::Error(error)) => return Err(error.into()),
            }
        }
    }
}

/// Resolve `fix_ref` — a ref name, short SHA, or full SHA — to the full
/// commit SHA it points at.
///
/// The full-SHA guarantee holds ONLY inside a git work tree. Outside one the
/// value passes through unchanged BY DESIGN: ledger-only setups have nothing
/// to resolve against, and the review itself fails loudly later if the object
/// never materializes (same contract as before). In that pass-through mode
/// ref literals like "HEAD" and short SHAs remain recordable — the fix's
/// ledger identity is only normalized where `git rev-parse` can answer.
/// Inside a repo an unresolvable ref is a hard error WITHOUT spending an
/// attempt: recording a literal like "HEAD" (0.9.2 field bug) or a short SHA
/// forks the commit's ledger identity, and a typo must never burn a bounded
/// attempt.
fn resolve_fix_ref_to_full_sha(fix_ref: &str) -> Result<String> {
    let in_repo = std::process::Command::new("git")
        .args(["rev-parse", "--is-inside-work-tree"])
        .output()
        .map(|out| out.status.success())
        .unwrap_or(false);
    if !in_repo {
        return Ok(fix_ref.to_owned());
    }
    let output = std::process::Command::new("git")
        .args(["rev-parse", "--verify", &format!("{fix_ref}^{{commit}}")])
        .output()
        .map_err(|error| {
            anyhow::anyhow!("failed to run git rev-parse for --fixed-by {fix_ref:?}: {error}")
        })?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!(
            "refusing petition without spending an attempt: cannot resolve --fixed-by {fix_ref:?} to a commit in this repository ({})",
            stderr.trim()
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
}

/// Whether stdin is currently attached to an interactive terminal. Tests
/// override this via [`set_stdin_tty_override_for_testing`].
pub fn stdin_is_tty() -> bool {
    if let Some(value) = stdin_tty_override() {
        return value;
    }
    io::stdin().is_terminal()
}

const STDIN_TTY_OVERRIDE_NONE: i32 = i32::MIN;

static STDIN_TTY_OVERRIDE: AtomicI32 = AtomicI32::new(STDIN_TTY_OVERRIDE_NONE);

fn stdin_tty_override() -> Option<bool> {
    let value = STDIN_TTY_OVERRIDE.load(Ordering::SeqCst);
    if value == STDIN_TTY_OVERRIDE_NONE {
        None
    } else {
        Some(value != 0)
    }
}

/// Test-only override: `Some(true)` / `Some(false)` forces the tty check; the
/// default sentinel (no override set) defers to the real stdin.
///
/// Compiled out of release builds (`debug_assertions` off) so no production
/// binary or in-process consumer can flip the TTY gate that keeps agents out
/// of the `--waive` lane; integration tests build with dev profile and keep
/// access. Hidden from docs — this is test plumbing, not API.
#[cfg(any(test, debug_assertions))]
#[doc(hidden)]
pub fn set_stdin_tty_override_for_testing(value: Option<bool>) {
    match value {
        Some(flag) => {
            STDIN_TTY_OVERRIDE.store(flag as i32, Ordering::SeqCst);
        }
        None => {
            STDIN_TTY_OVERRIDE.store(STDIN_TTY_OVERRIDE_NONE, Ordering::SeqCst);
        }
    }
}

/// Whether `verdict` accepts a petition re-review (i.e. the reviewer accepted
/// that the fix materially addresses each finding). `PASS` accepts outright;
/// `FLAG` ALSO accepts — the petition prompt defines FLAG as "the fix
/// materially addresses the findings" plus non-blocking debt, and that debt
/// lives on the petition review entry (surfaced via `truth-mirror debt`),
/// not on the original rejection. There is no separate `ACCEPT` variant on
/// the wire. This is the ONE accept criterion — the petition plumbing in
/// `reviewer::apply_petition_transition` delegates here.
pub fn petition_accepts(verdict: Verdict) -> bool {
    matches!(verdict, Verdict::Pass | Verdict::Flag)
}

/// Helper for printing an interactive waiver prompt. Surfaced so the
/// `--waive --reason` flow can be exercised end-to-end without consuming
/// the parent's stdin.
#[doc(hidden)]
pub fn prompt_waiver_reason_to_writer(writer: &mut dyn Write, default: &str) -> io::Result<()> {
    write!(writer, "waiver reason [{default}]: ")?;
    writer.flush()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Barrier, atomic::AtomicUsize};

    #[test]
    fn concurrent_petitions_for_the_same_rejection_never_double_enqueue() {
        // CodeRabbit MAJOR (PR #13, resolve.rs ~136-182): the in-flight
        // check, the attempt-count read, spending the attempt, and the
        // enqueue used to be independent steps. Two concurrent petitions for
        // the same rejection could both pass the guards before either wrote
        // anything, and both enqueue — producing duplicate petitions in the
        // queue (the exact bug this closes in field use). Race N callers
        // against one seeded rejection and assert only one ever gets in.
        const THREADS: usize = 8;

        let temp = tempfile::tempdir().unwrap();
        let state_dir = Arc::new(temp.path().to_path_buf());
        let seed_store = LedgerStore::new(state_dir.as_ref());
        seed_store
            .append_entry(&crate::ledger::LedgerEntry::new_at(
                "deadbeef",
                Verdict::Reject,
                "CLAIM: rejected | verified: cargo test | evidence: tests:cargo-test",
                vec!["tests:cargo-test".to_owned()],
                crate::ledger::ReviewerConfig::new("claude", "claude-opus-4-1", false),
                vec!["unsupported claim".to_owned()],
                100,
            ))
            .unwrap();

        let barrier = Arc::new(Barrier::new(THREADS));
        let succeeded = Arc::new(AtomicUsize::new(0));
        let mut threads = Vec::with_capacity(THREADS);

        for _ in 0..THREADS {
            let state_dir = Arc::clone(&state_dir);
            let barrier = Arc::clone(&barrier);
            let succeeded = Arc::clone(&succeeded);
            threads.push(std::thread::spawn(move || {
                let store = LedgerStore::new(state_dir.as_ref());
                barrier.wait();
                if petition_fix(&store, state_dir.as_ref(), "deadbeef", "HEAD").is_ok() {
                    succeeded.fetch_add(1, Ordering::SeqCst);
                }
            }));
        }
        for thread in threads {
            thread.join().unwrap();
        }

        assert_eq!(
            succeeded.load(Ordering::SeqCst),
            1,
            "exactly one concurrent petition for the same rejection must succeed"
        );

        let queue = crate::reviewer::ReviewQueue::new(state_dir.as_ref())
            .pending()
            .unwrap();
        let petitions_for_rejection = queue
            .iter()
            .filter(|item| item.petition_for.as_deref() == Some("deadbeef"))
            .count();
        assert_eq!(
            petitions_for_rejection, 1,
            "exactly one petition must be enqueued for the rejection, never a duplicate"
        );

        let attempts = seed_store.petition_attempts_for("deadbeef").unwrap();
        assert_eq!(
            attempts, 1,
            "exactly one attempt must be spent, not one per racing caller"
        );
    }

    /// Force `enqueue_petition` to fail deterministically: a regular file
    /// where the run store needs to create its "runs" directory makes
    /// `create_dir_all` fail with a real OS error, without touching the
    /// ledger's own storage.
    fn block_run_store_directory(state_dir: &Path) {
        fs::write(
            state_dir.join(crate::reviewer::REVIEW_RUNS_DIR),
            b"not a directory",
        )
        .unwrap();
    }

    #[test]
    fn petition_enqueue_failure_records_the_spent_attempt_honestly() {
        // Codex round-2 P2 (resolve.rs ~205): the round-1 "rollback" wrote a
        // compensating ledger entry carrying the PRIOR attempt count, but
        // petition_attempts_for takes the MAX attempt count across the sha's
        // whole history (a deliberate defense against any accidental
        // non-monotonic write elsewhere) — so the just-appended
        // next_attempts entry kept winning regardless, and the rollback
        // silently did nothing. The fix reports the attempt as genuinely
        // spent (matching what petition_attempts_for actually returns)
        // instead of claiming a rollback that never took effect.
        let temp = tempfile::tempdir().unwrap();
        let state_dir = temp.path();
        let store = LedgerStore::new(state_dir);
        store
            .append_entry(&crate::ledger::LedgerEntry::new_at(
                "deadbeef",
                Verdict::Reject,
                "CLAIM: rejected | verified: cargo test | evidence: tests:cargo-test",
                vec!["tests:cargo-test".to_owned()],
                crate::ledger::ReviewerConfig::new("claude", "claude-opus-4-1", false),
                vec!["unsupported claim".to_owned()],
                100,
            ))
            .unwrap();
        block_run_store_directory(state_dir);

        let error = petition_fix(&store, state_dir, "deadbeef", "HEAD").unwrap_err();
        assert!(
            error
                .to_string()
                .contains("failed to enqueue petition review"),
            "expected an enqueue-failure error, got: {error}"
        );

        let attempts = store.petition_attempts_for("deadbeef").unwrap();
        assert_eq!(
            attempts, 1,
            "the spent attempt must be honestly recorded, not silently rolled back to 0"
        );
        let entry = store.show("deadbeef").unwrap();
        assert!(
            entry.is_unresolved_rejection(),
            "with attempts remaining, the rejection must stay open for a retry"
        );
    }

    #[test]
    fn petition_enqueue_failure_escalates_when_it_exhausts_the_bound() {
        // The companion case: if the failed enqueue's attempt is the one that
        // hits MAX_PETITION_ATTEMPTS, it must escalate to needs-human exactly
        // like a REJECT verdict would — not silently leave the rejection Open
        // with an attempt count that claims the bound but no escalation.
        let temp = tempfile::tempdir().unwrap();
        let state_dir = temp.path();
        let store = LedgerStore::new(state_dir);
        store
            .append_entry(&crate::ledger::LedgerEntry::new_at(
                "deadbeef",
                Verdict::Reject,
                "CLAIM: rejected | verified: cargo test | evidence: tests:cargo-test",
                vec!["tests:cargo-test".to_owned()],
                crate::ledger::ReviewerConfig::new("claude", "claude-opus-4-1", false),
                vec!["unsupported claim".to_owned()],
                100,
            ))
            .unwrap();
        store
            .append_petition_transition(
                "deadbeef",
                crate::ledger::Disposition::Open,
                ResolutionKind::Resolved,
                "seeded prior attempt",
                MAX_PETITION_ATTEMPTS - 1,
            )
            .unwrap();
        block_run_store_directory(state_dir);

        let error = petition_fix(&store, state_dir, "deadbeef", "HEAD").unwrap_err();
        assert!(
            error.to_string().contains("escalated to needs-human"),
            "expected an escalation error, got: {error}"
        );

        let entry = store.show("deadbeef").unwrap();
        assert_eq!(entry.disposition, crate::ledger::Disposition::NeedsHuman);
        assert_eq!(
            store.petition_attempts_for("deadbeef").unwrap(),
            MAX_PETITION_ATTEMPTS
        );
    }

    #[test]
    fn stdin_tty_override_round_trip() {
        set_stdin_tty_override_for_testing(Some(true));
        assert!(stdin_is_tty());
        set_stdin_tty_override_for_testing(Some(false));
        assert!(!stdin_is_tty());
        set_stdin_tty_override_for_testing(None);
    }

    #[test]
    fn petition_accepts_pass_and_flag_but_not_reject() {
        // FLAG accepts by definition: the petition prompt defines FLAG as
        // "the fix materially addresses the findings" plus non-blocking debt.
        assert!(petition_accepts(Verdict::Pass));
        assert!(petition_accepts(Verdict::Flag));
        assert!(!petition_accepts(Verdict::Reject));
    }

    #[test]
    fn max_petition_attempts_is_two() {
        assert_eq!(MAX_PETITION_ATTEMPTS, 2);
    }

    #[test]
    fn prompt_helper_writes_default_text() {
        let mut buffer = Vec::new();
        prompt_waiver_reason_to_writer(&mut buffer, "approved exception").unwrap();
        let text = String::from_utf8(buffer).unwrap();
        assert_eq!(text, "waiver reason [approved exception]: ");
    }
}