truth-mirror 0.2.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
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
//! Ground-truth constraints and conversation-trajectory context fed into review.
//!
//! Ground truth = inviolable constraints discovered from `TRUTH.md`/`AGENTS.md`/
//! `CLAUDE.md` at any nested level plus OpenSpec specs. Trajectory = a bounded
//! window of recent user/agent messages so the reviewer judges direction, not
//! just the isolated diff.

use std::{
    fs,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use serde::Deserialize;

use crate::config::{GroundTruthConfig, HistoryConfig};

/// Directories never walked for ground-truth files.
const SKIP_DIRS: &[&str] = &[".git", "target", "node_modules", ".truth-mirror"];

/// Collect ground-truth constraints from the repo, shallowest (repo-root) first,
/// bounded by `max_bytes`. Deterministic ordering (by depth then path) for tests.
pub fn collect_ground_truth(repo_root: &Path, config: &GroundTruthConfig) -> Result<String> {
    if !config.enabled {
        return Ok(String::new());
    }

    let mut hits: Vec<(usize, PathBuf)> = Vec::new();
    collect_files(repo_root, repo_root, config, 0, &mut hits)?;
    // Shallowest first, then lexicographic — root AGENTS.md/TRUTH.md win the budget.
    hits.sort_by(|(depth_a, path_a), (depth_b, path_b)| {
        depth_a.cmp(depth_b).then_with(|| path_a.cmp(path_b))
    });

    let mut out = String::new();
    for (_, path) in hits {
        let rel = path.strip_prefix(repo_root).unwrap_or(&path);
        let body = match fs::read_to_string(&path) {
            Ok(body) => body,
            Err(_) => continue,
        };
        let section = format!("### {}\n{}\n\n", rel.display(), body.trim());
        if out.len() + section.len() > config.max_bytes {
            let remaining = config.max_bytes.saturating_sub(out.len());
            out.push_str(&truncate_on_char_boundary(&section, remaining));
            break;
        }
        out.push_str(&section);
    }

    Ok(out.trim_end().to_owned())
}

fn collect_files(
    repo_root: &Path,
    dir: &Path,
    config: &GroundTruthConfig,
    depth: usize,
    hits: &mut Vec<(usize, PathBuf)>,
) -> Result<()> {
    let entries = match fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(_) => return Ok(()),
    };

    for entry in entries.flatten() {
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().into_owned();
        let file_type = match entry.file_type() {
            Ok(file_type) => file_type,
            Err(_) => continue,
        };

        if file_type.is_dir() {
            if SKIP_DIRS.contains(&name.as_str()) {
                continue;
            }
            collect_files(repo_root, &path, config, depth + 1, hits)?;
        } else if is_ground_truth_file(repo_root, &path, &name, config) {
            hits.push((depth, path));
        }
    }

    Ok(())
}

fn is_ground_truth_file(
    repo_root: &Path,
    path: &Path,
    name: &str,
    config: &GroundTruthConfig,
) -> bool {
    if config.file_names.iter().any(|wanted| wanted == name) {
        return true;
    }

    if config.include_openspec_specs
        && name.ends_with(".md")
        && let Ok(rel) = path.strip_prefix(repo_root)
    {
        let rel = rel.to_string_lossy();
        return rel.starts_with("openspec/specs/");
    }

    false
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    User,
    Agent,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
pub struct TranscriptMessage {
    pub role: Role,
    pub text: String,
}

/// Yields recent conversation messages (oldest-first).
pub trait TrajectoryProvider {
    fn messages(&self) -> Result<Vec<TranscriptMessage>>;
}

/// Reads a `{"role":"user|agent","text":"..."}`-per-line transcript.
#[derive(Clone, Debug)]
pub struct JsonlTranscriptProvider {
    pub path: PathBuf,
}

impl TrajectoryProvider for JsonlTranscriptProvider {
    fn messages(&self) -> Result<Vec<TranscriptMessage>> {
        let contents = match fs::read_to_string(&self.path) {
            Ok(contents) => contents,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(error) => {
                return Err(error)
                    .with_context(|| format!("reading transcript {}", self.path.display()));
            }
        };

        contents
            .lines()
            .filter(|line| !line.trim().is_empty())
            .map(|line| {
                serde_json::from_str::<TranscriptMessage>(line)
                    .with_context(|| "parsing transcript line".to_string())
            })
            .collect()
    }
}

/// Recent commit subjects as agent messages — a universal trajectory proxy when
/// no explicit transcript is configured.
#[derive(Clone, Debug)]
pub struct GitLogProvider {
    pub repo_root: PathBuf,
    pub count: usize,
}

impl TrajectoryProvider for GitLogProvider {
    fn messages(&self) -> Result<Vec<TranscriptMessage>> {
        let output = std::process::Command::new("git")
            .arg("-C")
            .arg(&self.repo_root)
            .args(["log", &format!("-n{}", self.count), "--format=%s"])
            .output()
            .context("running git log for trajectory")?;
        if !output.status.success() {
            return Ok(Vec::new());
        }
        let text = String::from_utf8_lossy(&output.stdout);
        // git log is newest-first; reverse to oldest-first for chronological order.
        let mut messages: Vec<TranscriptMessage> = text
            .lines()
            .filter(|line| !line.trim().is_empty())
            .map(|line| TranscriptMessage {
                role: Role::Agent,
                text: format!("committed: {}", line.trim()),
            })
            .collect();
        messages.reverse();
        Ok(messages)
    }
}

/// Pick a trajectory provider: the configured JSONL transcript if present, else
/// recent commits.
pub fn trajectory_provider(
    repo_root: &Path,
    history: &HistoryConfig,
) -> Box<dyn TrajectoryProvider> {
    if let Some(rel) = &history.transcript_path {
        let path = repo_root.join(rel);
        if path.is_file() {
            return Box::new(JsonlTranscriptProvider { path });
        }
    }
    Box::new(GitLogProvider {
        repo_root: repo_root.to_path_buf(),
        count: history.window_user + history.window_agent + 5,
    })
}

/// Keep the last `window_user` user messages and last `window_agent` agent
/// messages, preserving chronological order, then trim oldest to `max_bytes`.
pub fn window_trajectory(
    messages: &[TranscriptMessage],
    window_user: usize,
    window_agent: usize,
    max_bytes: usize,
) -> Vec<TranscriptMessage> {
    let mut users = 0;
    let mut agents = 0;
    let mut kept: Vec<TranscriptMessage> = Vec::new();

    for message in messages.iter().rev() {
        let keep = match message.role {
            Role::User if users < window_user => {
                users += 1;
                true
            }
            Role::Agent if agents < window_agent => {
                agents += 1;
                true
            }
            _ => false,
        };
        if keep {
            kept.push(message.clone());
        }
    }
    kept.reverse();

    // Byte budget: drop oldest until under budget.
    let mut total: usize = kept.iter().map(|message| message.text.len()).sum();
    let mut start = 0;
    while start < kept.len() && total > max_bytes {
        total -= kept[start].text.len();
        start += 1;
    }
    kept[start..].to_vec()
}

pub fn render_trajectory(messages: &[TranscriptMessage]) -> String {
    if messages.is_empty() {
        return String::new();
    }
    let mut out = String::new();
    for message in messages {
        let who = match message.role {
            Role::User => "USER",
            Role::Agent => "AGENT",
        };
        out.push_str(&format!("{who}: {}\n", message.text.trim()));
    }
    out.trim_end().to_owned()
}

/// Build the combined review-context block (constraints + trajectory).
pub fn build_review_context(
    repo_root: &Path,
    ground_truth: &GroundTruthConfig,
    history: &HistoryConfig,
    provider: Option<&dyn TrajectoryProvider>,
) -> Result<String> {
    let mut out = String::new();

    let constraints = collect_ground_truth(repo_root, ground_truth)?;
    if !constraints.is_empty() {
        out.push_str(
            "INVIOLABLE CONSTRAINTS (ground truth — a change that violates these is a REJECT):\n",
        );
        out.push_str(&constraints);
        out.push_str("\n\n");
    }

    if let Some(provider) = provider {
        let messages = provider.messages()?;
        let windowed = window_trajectory(
            &messages,
            history.window_user,
            history.window_agent,
            history.max_bytes,
        );
        let rendered = render_trajectory(&windowed);
        if !rendered.is_empty() {
            out.push_str("RECENT TRAJECTORY (judge the direction of work, not just this diff):\n");
            out.push_str(&rendered);
            out.push_str("\n\n");
        }
    }

    Ok(out.trim_end().to_owned())
}

fn truncate_on_char_boundary(value: &str, max: usize) -> String {
    if value.len() <= max {
        return value.to_owned();
    }
    let mut end = max;
    while end > 0 && !value.is_char_boundary(end) {
        end -= 1;
    }
    value[..end].to_owned()
}

#[cfg(test)]
mod tests {
    use super::{
        JsonlTranscriptProvider, Role, TrajectoryProvider, TranscriptMessage, build_review_context,
        collect_ground_truth, render_trajectory, window_trajectory,
    };
    use crate::config::{GroundTruthConfig, HistoryConfig};

    fn msg(role: Role, text: &str) -> TranscriptMessage {
        TranscriptMessage {
            role,
            text: text.to_owned(),
        }
    }

    #[test]
    fn collects_nested_constraint_files() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();
        std::fs::write(root.join("AGENTS.md"), "root agents").unwrap();
        std::fs::create_dir_all(root.join("sub/dir")).unwrap();
        std::fs::write(root.join("sub/dir/TRUTH.md"), "nested truth").unwrap();
        std::fs::create_dir_all(root.join("openspec/specs/x")).unwrap();
        std::fs::write(root.join("openspec/specs/x/spec.md"), "a spec").unwrap();
        // Ignored: unrelated file and skip dir.
        std::fs::write(root.join("README.md"), "readme").unwrap();
        std::fs::create_dir_all(root.join(".git")).unwrap();
        std::fs::write(root.join(".git/AGENTS.md"), "should be skipped").unwrap();

        let out = collect_ground_truth(root, &GroundTruthConfig::default()).unwrap();

        assert!(out.contains("root agents"));
        assert!(out.contains("nested truth"));
        assert!(out.contains("a spec"));
        assert!(!out.contains("readme"));
        assert!(!out.contains("should be skipped"));
    }

    #[test]
    fn ground_truth_respects_byte_budget() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(temp.path().join("AGENTS.md"), "x".repeat(1000)).unwrap();
        let config = GroundTruthConfig {
            max_bytes: 100,
            ..GroundTruthConfig::default()
        };

        let out = collect_ground_truth(temp.path(), &config).unwrap();

        assert!(out.len() <= 100, "got {} bytes", out.len());
    }

    #[test]
    fn disabled_ground_truth_returns_empty() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(temp.path().join("TRUTH.md"), "constraints").unwrap();
        let config = GroundTruthConfig {
            enabled: false,
            ..GroundTruthConfig::default()
        };

        assert!(
            collect_ground_truth(temp.path(), &config)
                .unwrap()
                .is_empty()
        );
    }

    #[test]
    fn window_keeps_last_n_and_m_in_order() {
        let messages = vec![
            msg(Role::User, "u1"),
            msg(Role::Agent, "a1"),
            msg(Role::Agent, "a2"),
            msg(Role::User, "u2"),
            msg(Role::Agent, "a3"),
            msg(Role::User, "u3"),
        ];

        let windowed = window_trajectory(&messages, 2, 2, 10_000);

        // last 2 users (u2,u3), last 2 agents (a2,a3), chronological.
        let texts: Vec<&str> = windowed.iter().map(|m| m.text.as_str()).collect();
        assert_eq!(texts, ["a2", "u2", "a3", "u3"]);
    }

    #[test]
    fn window_never_exceeds_limits() {
        let mut messages = Vec::new();
        for i in 0..50 {
            messages.push(msg(Role::User, &format!("u{i}")));
            messages.push(msg(Role::Agent, &format!("a{i}")));
        }

        let windowed = window_trajectory(&messages, 3, 5, 10_000);

        let users = windowed.iter().filter(|m| m.role == Role::User).count();
        let agents = windowed.iter().filter(|m| m.role == Role::Agent).count();
        assert!(users <= 3);
        assert!(agents <= 5);
    }

    #[test]
    fn jsonl_provider_reads_messages() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("t.jsonl");
        std::fs::write(
            &path,
            "{\"role\":\"user\",\"text\":\"do X\"}\n{\"role\":\"agent\",\"text\":\"did Y\"}\n",
        )
        .unwrap();

        let provider = JsonlTranscriptProvider { path };
        let messages = provider.messages().unwrap();

        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].role, Role::User);
        assert_eq!(messages[1].text, "did Y");
    }

    #[test]
    fn build_context_includes_constraints_and_trajectory() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(temp.path().join("TRUTH.md"), "never fake tests").unwrap();
        let transcript = temp.path().join("t.jsonl");
        std::fs::write(
            &transcript,
            "{\"role\":\"user\",\"text\":\"add feature\"}\n",
        )
        .unwrap();
        let provider = JsonlTranscriptProvider { path: transcript };

        let out = build_review_context(
            temp.path(),
            &GroundTruthConfig::default(),
            &HistoryConfig::default(),
            Some(&provider),
        )
        .unwrap();

        assert!(out.contains("INVIOLABLE CONSTRAINTS"));
        assert!(out.contains("never fake tests"));
        assert!(out.contains("RECENT TRAJECTORY"));
        assert!(out.contains("add feature"));
    }

    #[test]
    fn render_trajectory_is_empty_for_no_messages() {
        assert!(render_trajectory(&[]).is_empty());
    }
}