truth-mirror 0.9.0

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
//! Integration tests for the queue-tied watcher lifecycle: `watch --until-empty`,
//! `ensure-watcher` (spawn / no-op / stale recovery / race), and the end-to-end
//! enqueue → watcher appears → queue drains → watcher exits after grace path.
//!
//! Every test uses a temporary state dir; none touch any real `.truth` state.
//! The spawn/liveness tests are unix-gated (they rely on process-group detach and
//! the pid liveness probe); the Windows spawn shim is compile-checked via cfg but
//! not exercised here.

mod common;

use std::{
    fs,
    path::Path,
    process::Command as StdCommand,
    time::{Duration, Instant},
};

use common::{git, git_stdout, make_executable, truth_mirror};
use predicates::prelude::*;

/// Write an executable mock `codex` reviewer that always REJECTs into `bin_dir`
/// and return a `PATH` value with that dir prepended.
fn mock_reviewer_path(bin_dir: &Path) -> String {
    let fake_codex = bin_dir.join("codex");
    fs::write(
        &fake_codex,
        r#"#!/usr/bin/env python3
import json
print(json.dumps({
    "verdict": "REJECT",
    "summary": "The claim is not substantiated.",
    "findings": [{
        "severity": "high",
        "title": "claim not substantiated",
        "body": "The cited evidence does not prove the claim.",
        "file": "file.txt",
        "line_start": 1,
        "line_end": 1,
        "confidence": 95,
        "recommendation": "Add evidence that directly proves the claim."
    }],
    "next_steps": ["Re-run the verification command."],
    "memory_skill": {
        "kind": "anti_pattern_skill",
        "learning_source": "claim not substantiated",
        "reasoning": "The rejection identifies a reusable unsupported-claim pattern."
    }
}))
"#,
    )
    .unwrap();
    make_executable(&fake_codex);
    format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    )
}

/// Create a git repo with one claim-bearing commit and enqueue it for review the
/// same way the post-commit hook does. Returns the committed SHA.
fn repo_with_one_queued_commit(repo: &Path, state_dir_name: &str) -> String {
    git(repo, &["init"]);
    git(repo, &["config", "user.email", "truth@example.invalid"]);
    git(repo, &["config", "user.name", "Truth Mirror Test"]);
    fs::write(repo.join("file.txt"), "hello\n").unwrap();
    git(repo, &["add", "file.txt"]);
    git(
        repo,
        &[
            "commit",
            "-m",
            "feat: add file",
            "-m",
            "CLAIM: add file | verified: cargo test | evidence: tests:watcher-e2e",
        ],
    );
    let sha = git_stdout(repo, &["rev-parse", "HEAD"]);

    let state = repo.join(state_dir_name);
    fs::create_dir_all(&state).unwrap();
    // Pin the reviewer pair so the detached watcher — which is spawned with no
    // reviewer flags and resolves its pair from config — deterministically calls
    // the mock `codex` reviewer instead of the built-in default (`claude`).
    fs::write(
        state.join("config.toml"),
        r#"default_writer = "claude"

[pairs.claude]
reviewer = { harness = "codex", model = "gpt-5.5" }
arbiter  = { harness = "gemini", model = "gemini-2.5-pro" }
"#,
    )
    .unwrap();
    fs::write(
        state.join("review-queue.jsonl"),
        format!("{{\"commit_sha\":\"{sha}\",\"enqueued_at_unix\":100}}\n"),
    )
    .unwrap();
    sha
}

fn queue_path(state: &Path) -> std::path::PathBuf {
    state.join("review-queue.jsonl")
}

fn queue_is_empty(state: &Path) -> bool {
    fs::read_to_string(queue_path(state))
        .unwrap_or_default()
        .trim()
        .is_empty()
}

fn ledger_contains_reject(state: &Path) -> bool {
    fs::read_to_string(state.join("ledger.jsonl"))
        .unwrap_or_default()
        .contains("\"verdict\":\"REJECT\"")
}

fn wait_until(mut predicate: impl FnMut() -> bool, timeout: Duration) -> bool {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if predicate() {
            return true;
        }
        std::thread::sleep(Duration::from_millis(50));
    }
    predicate()
}

#[test]
fn watch_until_empty_drains_queued_commit_and_exits_after_grace() {
    let temp = tempfile::tempdir().unwrap();
    let repo = temp.path().join("repo");
    let bin = temp.path().join("bin");
    fs::create_dir_all(&repo).unwrap();
    fs::create_dir_all(&bin).unwrap();

    let sha = repo_with_one_queued_commit(&repo, ".truth-mirror");
    let state = repo.join(".truth-mirror");
    let path = mock_reviewer_path(&bin);

    // `--until-empty` with a zero grace window drains the one queued commit and
    // exits 0 immediately (no daemon left running).
    let started = Instant::now();
    truth_mirror(&repo)
        .env("PATH", path)
        .args([
            "--state-dir",
            ".truth-mirror",
            "watch",
            "--until-empty",
            "--grace",
            "1",
            "--poll-secs",
            "1",
            "--watched-agent",
            "claude",
            "--watched-model",
            "model-a",
            "--reviewer-harness",
            "codex",
            "--reviewer-model",
            "model-b",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("reviewed 1 commit"));
    assert!(
        started.elapsed() >= Duration::from_millis(900),
        "watcher should linger through the configured grace window"
    );

    assert!(ledger_contains_reject(&state), "verdict should be recorded");
    assert!(
        fs::read_to_string(state.join("ledger.jsonl"))
            .unwrap()
            .contains(&sha)
    );
    assert!(queue_is_empty(&state), "queue should be drained on exit");
    // The watcher released its single-flight lock on exit.
    assert!(
        !state.join("watcher.lock").exists(),
        "lock should be released after until-empty exit"
    );
}

#[test]
fn watch_until_empty_picks_up_late_enqueue_during_grace_window() {
    let temp = tempfile::tempdir().unwrap();
    let repo = temp.path().join("repo");
    let bin = temp.path().join("bin");
    fs::create_dir_all(&repo).unwrap();
    fs::create_dir_all(&bin).unwrap();

    let _first = repo_with_one_queued_commit(&repo, ".truth-mirror");
    let state = repo.join(".truth-mirror");
    let path = mock_reviewer_path(&bin);

    // Second claim-bearing commit that we will enqueue LATE, after the first has
    // drained but while the watcher is still inside its grace window.
    fs::write(repo.join("file.txt"), "second\n").unwrap();
    git(&repo, &["add", "file.txt"]);
    git(
        &repo,
        &[
            "commit",
            "-m",
            "feat: second change",
            "-m",
            "CLAIM: second change | verified: cargo test | evidence: tests:watcher-late",
        ],
    );
    let second_sha = git_stdout(&repo, &["rev-parse", "HEAD"]);

    // A grace window long enough to reliably win the enqueue race, with fast
    // polling so the late arrival is drained quickly once it lands.
    let exe = assert_cmd::cargo::cargo_bin("truth-mirror");
    let mut child = StdCommand::new(exe)
        .current_dir(&repo)
        .env("PATH", path)
        .args([
            "--state-dir",
            ".truth-mirror",
            "watch",
            "--until-empty",
            "--grace",
            "2",
            "--poll-secs",
            "1",
            "--watched-agent",
            "claude",
            "--watched-model",
            "model-a",
            "--reviewer-harness",
            "codex",
            "--reviewer-model",
            "model-b",
        ])
        .spawn()
        .unwrap();

    // Wait until the first commit has drained (queue empties), proving the watcher
    // is now inside its grace window rather than still working.
    assert!(
        wait_until(|| queue_is_empty(&state), Duration::from_secs(10)),
        "first commit should drain and empty the queue"
    );

    // Enqueue the late arrival while the watcher lingers in the grace window.
    fs::write(
        queue_path(&state),
        format!("{{\"commit_sha\":\"{second_sha}\",\"enqueued_at_unix\":200}}\n"),
    )
    .unwrap();

    // The watcher must pick it up, drain it, and only then exit 0 after a fresh
    // grace window with the queue staying empty.
    let status = wait_child(&mut child, Duration::from_secs(30));
    assert!(
        status.success(),
        "watcher should exit 0 after draining late arrival"
    );

    let ledger = fs::read_to_string(state.join("ledger.jsonl")).unwrap();
    assert!(
        ledger.contains(&second_sha),
        "late-enqueued commit should have been reviewed; ledger:\n{ledger}"
    );
    assert!(queue_is_empty(&state), "queue should be empty on exit");
}

#[test]
fn ensure_watcher_spawns_when_none_then_is_a_noop_when_alive() {
    let temp = tempfile::tempdir().unwrap();
    let repo = temp.path().join("repo");
    let bin = temp.path().join("bin");
    fs::create_dir_all(&repo).unwrap();
    fs::create_dir_all(&bin).unwrap();

    let _sha = repo_with_one_queued_commit(&repo, ".truth-mirror");
    let state = repo.join(".truth-mirror");
    let path = mock_reviewer_path(&bin);

    // First ensure-watcher: nothing running, so it spawns a detached watcher and
    // announces it started.
    truth_mirror(&repo)
        .env("PATH", &path)
        .args(["--state-dir", ".truth-mirror", "ensure-watcher"])
        .assert()
        .success()
        .stdout(predicate::str::contains("watcher started"));

    // A lock file appears, owned by the live watcher.
    assert!(
        wait_until(
            || state.join("watcher.lock").exists(),
            Duration::from_secs(5)
        ),
        "a watcher lock should appear"
    );

    // The detached watcher drains the queued commit and eventually exits after its
    // (default 60s) grace window — we only assert the queue drains, then move on.
    assert!(
        wait_until(|| queue_is_empty(&state), Duration::from_secs(20)),
        "detached watcher should drain the queued commit"
    );
    assert!(ledger_contains_reject(&state));

    // While the watcher is still alive (inside its grace window), a second
    // ensure-watcher is a quiet no-op: it does NOT announce a new start.
    truth_mirror(&repo)
        .env("PATH", &path)
        .args(["--state-dir", ".truth-mirror", "ensure-watcher"])
        .assert()
        .success()
        .stdout(predicate::str::is_empty());
}

#[test]
fn ensure_watcher_recovers_from_a_stale_lock() {
    let temp = tempfile::tempdir().unwrap();
    let repo = temp.path().join("repo");
    let bin = temp.path().join("bin");
    fs::create_dir_all(&repo).unwrap();
    fs::create_dir_all(&bin).unwrap();

    let _sha = repo_with_one_queued_commit(&repo, ".truth-mirror");
    let state = repo.join(".truth-mirror");
    let path = mock_reviewer_path(&bin);

    // Plant a stale lock owned by a pid that is not alive, with a start token so
    // the liveness probe cannot pass on the empty-token fallback.
    fs::write(
        state.join("watcher.lock"),
        r#"{"identity":{"pid":4000000000,"start_token":"definitely-dead"},"created_at_unix":1}"#,
    )
    .unwrap();

    // ensure-watcher must reclaim the stale lock and spawn a fresh watcher rather
    // than wedging on the dead owner.
    truth_mirror(&repo)
        .env("PATH", &path)
        .args(["--state-dir", ".truth-mirror", "ensure-watcher"])
        .assert()
        .success()
        .stdout(predicate::str::contains("watcher started"));

    assert!(
        wait_until(|| queue_is_empty(&state), Duration::from_secs(20)),
        "recovered watcher should drain the queued commit"
    );
    assert!(ledger_contains_reject(&state));
}

#[test]
fn two_racing_ensure_watchers_yield_exactly_one_watcher() {
    let temp = tempfile::tempdir().unwrap();
    let repo = temp.path().join("repo");
    let bin = temp.path().join("bin");
    fs::create_dir_all(&repo).unwrap();
    fs::create_dir_all(&bin).unwrap();

    let _sha = repo_with_one_queued_commit(&repo, ".truth-mirror");
    let state = repo.join(".truth-mirror");
    let path = mock_reviewer_path(&bin);
    let exe = assert_cmd::cargo::cargo_bin("truth-mirror");

    // Fire two ensure-watcher invocations concurrently, as two racing pushes would.
    let spawn_one = || {
        let exe = exe.clone();
        let repo = repo.clone();
        let path = path.clone();
        std::thread::spawn(move || {
            let output = StdCommand::new(exe)
                .current_dir(&repo)
                .env("PATH", path)
                .args(["--state-dir", ".truth-mirror", "ensure-watcher"])
                .output()
                .unwrap();
            assert!(output.status.success());
            String::from_utf8_lossy(&output.stdout).contains("watcher started")
        })
    };
    let a = spawn_one();
    let b = spawn_one();
    let a_started = a.join().unwrap();
    let b_started = b.join().unwrap();

    // Exactly one of the two racing calls may claim to have started a watcher.
    assert!(
        a_started ^ b_started,
        "exactly one ensure-watcher should start a watcher (a={a_started}, b={b_started})"
    );

    // And that single watcher drains the queue.
    assert!(
        wait_until(|| queue_is_empty(&state), Duration::from_secs(20)),
        "the single watcher should drain the queued commit"
    );
}

/// Wait up to `timeout` for `child` to exit, returning its status. Panics (killing
/// the child) if it outlives the timeout so a hung watcher fails loudly.
fn wait_child(child: &mut std::process::Child, timeout: Duration) -> std::process::ExitStatus {
    let deadline = Instant::now() + timeout;
    loop {
        match child.try_wait().unwrap() {
            Some(status) => return status,
            None if Instant::now() >= deadline => {
                let _ = child.kill();
                let _ = child.wait();
                panic!("watcher did not exit within {timeout:?}");
            }
            None => std::thread::sleep(Duration::from_millis(100)),
        }
    }
}