helen 0.1.0

Repository review gate.
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
//! Read-only Codex review handling for elenchus.

use super::{
    Gate,
    error::{ElenchusError, Result},
    process::{
        combined_output_bytes, combined_output_text, command_output_allow_failure,
        git_diff_binary_to, git_hash_file, is_non_empty_file, review_transcript_file,
        same_file_bytes, status_code_text, write_binary,
    },
    review_context::ReviewContext,
    risk::RiskState,
    text::{
        first_lines, first_lines_file, last_non_empty_line, prefix_lines, version_line_for_error,
    },
};
use std::{
    fs,
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

/// Successful review status expected from the read-only reviewer.
const PASS_STATUS: &str = "REVIEW_STATUS: PASS";

/// Codex reviewer setup.
#[derive(Clone, Debug)]
struct ReviewerSetup {
    /// Resolved Codex binary path.
    codex_path: PathBuf,
    /// Review mode supported by the Codex binary.
    mode: ReviewMode,
}

/// Supported reviewer invocation strategy.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ReviewMode {
    /// Use `codex exec --sandbox read-only` with the custom prompt.
    PlainExec,
}

impl Gate {
    /// Runs a fresh read-only review or reuses an accepted cached review.
    pub(super) fn run_or_reuse_review(
        &self,
        risk: &mut RiskState,
        changed_files: &str,
        cache_paths: &super::artifacts::ReviewCachePaths,
        diff_fingerprint: &str,
    ) -> Result<()> {
        if risk.override_accepted && is_non_empty_file(&cache_paths.review) {
            risk.review_reused = true;
            let current_review_cache_hash = git_hash_file(&cache_paths.review)?;
            if current_review_cache_hash != risk.review_cache_hash {
                return Err(ElenchusError::failure(
                    "error: cached review changed after token validation\n\
                     Rerun the original elenchus command to perform a fresh review.",
                ));
            }
            let _bytes =
                fs::copy(&cache_paths.review, &self.paths.review_out).map_err(|error| {
                    ElenchusError::failure(format!("error: failed to copy cached review: {error}"))
                })?;
            self.validate_review_output(&self.paths.review_out)?;
            git_diff_binary_to(&self.paths.post_review_diff)?;
            if !same_file_bytes(&self.paths.post_checks_diff, &self.paths.post_review_diff)? {
                return Err(ElenchusError::failure(
                    "error: working tree changed before cached review reuse\n\
                     Review and rerun elenchus.",
                ));
            }
            self.write_reused_review_transcript(diff_fingerprint, &risk.acceptance_token)?;
            println!("==> elenchus: reused passing review for accepted diff");
            return Ok(());
        }

        let prompt = self.review_prompt(changed_files, risk);
        fs::write(&self.paths.review_prompt, prompt).map_err(|error| {
            ElenchusError::failure(format!("error: failed to write review prompt: {error}"))
        })?;

        let reviewer = self.prepare_codex_review()?;
        println!("==> elenchus: running read-only Codex review");
        println!(
            "==> elenchus: review can be quiet for several minutes; use a longer command wait/poll interval"
        );
        self.run_codex_review(&reviewer)?;
        self.validate_review_output(&self.paths.review_out)?;

        println!("==> elenchus: verifying reviewer did not mutate the worktree");
        git_diff_binary_to(&self.paths.post_review_diff)?;
        if !same_file_bytes(&self.paths.post_checks_diff, &self.paths.post_review_diff)? {
            return Err(ElenchusError::failure(
                "error: working tree changed during review\n\
                 The reviewer was expected to be read-only. Review and rerun elenchus.",
            ));
        }

        let _bytes = fs::copy(&self.paths.review_out, &cache_paths.review).map_err(|error| {
            ElenchusError::failure(format!("error: failed to cache review output: {error}"))
        })?;

        if !self.settings.transcript_policy.keeps_raw() {
            self.discard_review_transcript()?;
        }

        Ok(())
    }

    /// Builds the reviewer prompt.
    fn review_prompt(&self, changed_files: &str, risk: &RiskState) -> String {
        let review_context = ReviewContext::from_changed_files(changed_files);
        let changed_files_for_review = review_context.changed_files_for_prompt();
        let source_records = review_context.source_records_for_prompt();
        let test_summary = if self.settings.test_policy.skips_tests() {
            format!("{}: skipped", self.settings.test_cmd)
        } else {
            format!("{}: passed", self.settings.test_cmd)
        };

        format!(
            "You are an independent read-only reviewer for a Rust codebase.\n\n\
             You did not author these changes. Treat the diff as third-party work that may\n\
             be incorrect. Do not defend, complete, or rationalize the implementation.\n\
             Prior verification is only build/test signal; it is not evidence that the\n\
             design, invariants, or behavior are correct.\n\n\
             Do not edit files.\n\
             Do not stage files.\n\
             Do not commit files.\n\
             Do not run network commands.\n\
             Review only the current uncommitted diff.\n\n\
             The elenchus command recorded the exact diff snapshot at:\n\
             {}\n\n\
             If the native Codex review context is available, review that uncommitted diff.\n\
             If you are running through plain exec, inspect the saved diff snapshot and\n\
             surrounding source files as needed using read-only commands such as:\n\
             - git status --short\n\
             - git diff --stat\n\
             - sed -n '1,240p' \"{}\"\n\
             - sed\n\
             - rg\n\n\
             The elenchus command has already run:\n\
             - cargo fmt --all --check\n\
             - cargo clippy --workspace --all-targets --all-features -- -D warnings\n\
             - {test_summary}\n\n\
             Commit message under review:\n\
             {}\n\n\
             Changed files:\n\
             {changed_files_for_review}\n\n\
             Risk flags detected by elenchus:\n\
             {}\n\n\
             Read and follow:\n\
             - AGENTS.md, if present\n\
             - .codex/review-policy.md, if present\n\n\
             Source-record lookup guidance:\n\
             {source_records}\n\n\
             Do not bulk-read documentation at the start of the review. First inspect the\n\
             diff and nearby source. If a source record is needed to judge ownership,\n\
             authority, plugin/Wasm behavior, compatibility, or security, search/open the\n\
             smallest relevant section and cite only the records consulted in your summary.\n\n\
             Focus on:\n\
             - Rust soundness, especially unsafe, lifetimes, aliasing, Send/Sync, FFI, pinning\n\
             - concurrency issues: races, deadlocks, cancellation, async blocking, lock ordering\n\
             - error handling regressions: swallowed errors, panics in library code, misleading context\n\
             - public API compatibility and behavior changes\n\
             - missing or weak tests for changed behavior\n\
             - security-sensitive handling of input, paths, secrets, logging, auth, crypto, network boundaries\n\
             - performance regressions that are likely to matter\n\n\
             Ignore:\n\
             - pure style nits\n\
             - broad rewrites\n\
             - speculative architecture preferences\n\n\
             Return exactly one of these two result forms.\n\n\
             If there are P0 or P1 findings, start with:\n\
             REVIEW_STATUS: BLOCK\n\n\
             Then list findings with:\n\
             - Severity:\n\
             - Location:\n\
             - Evidence:\n\
             - Minimal suggested fix:\n\n\
             If there are no P0/P1 findings, start with:\n\
             REVIEW_STATUS: PASS\n\n\
             Then include:\n\
             - Any P2 observations, if useful\n\
             - A one-paragraph risk summary, including source records consulted, or \"none\"\n\
               if the diff was self-contained\n",
            self.paths.diff.display(),
            self.paths.diff.display(),
            self.message().as_str(),
            risk.reasons_for_review()
        )
    }

    /// Validates Codex CLI support for elenchus review.
    fn prepare_codex_review(&self) -> Result<ReviewerSetup> {
        let codex_path =
            super::process::resolve_on_path(&self.settings.codex_bin).ok_or_else(|| {
                ElenchusError::usage(format!(
                    "error: codex CLI is not installed or not on PATH\n\
                 Checked ELENCHUS_CODEX_BIN='{}'.\n\
                 Install/configure Codex CLI before using the elenchus reviewer.",
                    self.settings.codex_bin
                ))
            })?;

        let version_output = command_output_allow_failure(&self.settings.codex_bin, ["--version"])?;
        let codex_version = last_non_empty_line(&combined_output_text(&version_output));

        let exec_help = command_output_allow_failure(&self.settings.codex_bin, ["exec", "--help"])?;
        write_binary(
            &self.paths.codex_exec_help,
            &combined_output_bytes(&exec_help),
        )?;
        if exec_help.status.success() && combined_output_text(&exec_help).contains("--sandbox") {
            println!("==> elenchus: Codex binary: {}", codex_path.display());
            if !codex_version.is_empty() {
                println!("==> elenchus: Codex version: {codex_version}");
            }
            println!("==> elenchus: reviewer mode: plain-exec");
            return Ok(ReviewerSetup {
                codex_path,
                mode: ReviewMode::PlainExec,
            });
        }

        let exec_review_help =
            command_output_allow_failure(&self.settings.codex_bin, ["exec", "review", "--help"])?;
        write_binary(
            &self.paths.codex_exec_review_help,
            &combined_output_bytes(&exec_review_help),
        )?;
        if exec_review_help.status.success()
            && combined_output_text(&exec_review_help).contains("--uncommitted")
        {
            return Err(ElenchusError::usage(format!(
                "error: Codex CLI supports native review but not contextual elenchus review\n\
                 Checked binary: {}\n{}\n\
                 This elenchus command requires a custom read-only review prompt with source-record context.\n\
                 Install a Codex CLI with 'codex exec --sandbox read-only' support.",
                codex_path.display(),
                version_line_for_error(&codex_version)
            )));
        }

        Err(ElenchusError::usage(format!(
            "error: Codex CLI does not support a usable elenchus review mode\n\
             Checked binary: {}\n{}\n\
             Expected:\n\
               codex exec --sandbox read-only ...\n\n\
             Review help, if any:\n{}\n\n\
             Exec help, if any:\n{}",
            codex_path.display(),
            version_line_for_error(&codex_version),
            first_lines(&combined_output_text(&exec_review_help), 120),
            first_lines(&combined_output_text(&exec_help), 120)
        )))
    }

    /// Runs the Codex reviewer.
    fn run_codex_review(&self, reviewer: &ReviewerSetup) -> Result<()> {
        let ReviewMode::PlainExec = reviewer.mode;
        let prompt = fs::read(&self.paths.review_prompt).map_err(|error| {
            ElenchusError::failure(format!("error: failed to read review prompt: {error}"))
        })?;
        let transcript = review_transcript_file(&self.paths.review_transcript)?;
        let transcript_stderr = transcript.try_clone().map_err(|error| {
            ElenchusError::failure(format!(
                "error: failed to clone review transcript handle: {error}"
            ))
        })?;
        let mut child = Command::new(&self.settings.codex_bin)
            .args([
                "exec",
                "--model",
                self.settings.review_model.as_str(),
                "--sandbox",
                "read-only",
                "-c",
                &format!("model_reasoning_effort={}", self.settings.effort),
                "--ephemeral",
                "--cd",
            ])
            .arg(&self.repo_root)
            .args(["--output-last-message"])
            .arg(&self.paths.review_out)
            .arg("-")
            .stdin(Stdio::piped())
            .stdout(Stdio::from(transcript))
            .stderr(Stdio::from(transcript_stderr))
            .spawn()
            .map_err(|error| {
                ElenchusError::failure(format!(
                    "error: failed to start Codex reviewer {}: {error}",
                    reviewer.codex_path.display()
                ))
            })?;

        let mut stdin = child
            .stdin
            .take()
            .ok_or_else(|| ElenchusError::failure("error: failed to open Codex reviewer stdin"))?;
        std::io::Write::write_all(&mut stdin, &prompt).map_err(|error| {
            ElenchusError::failure(format!("error: failed to write review prompt: {error}"))
        })?;
        drop(stdin);

        let status = child.wait().map_err(|error| {
            ElenchusError::failure(format!("error: failed to wait for Codex reviewer: {error}"))
        })?;

        if !status.success() {
            return Err(ElenchusError::failure(format!(
                "error: Codex reviewer failed with status {}\n\
                 review transcript, if any:\n{}\n\
                 review output, if any:\n{}",
                status_code_text(status),
                first_lines_file(&self.paths.review_transcript, 240),
                first_lines_file(&self.paths.review_out, 240)
            )));
        }

        Ok(())
    }

    /// Validates the final review output.
    fn validate_review_output(&self, review_file: &Path) -> Result<()> {
        if !is_non_empty_file(review_file) {
            return Err(ElenchusError::failure(format!(
                "error: review produced no final output\n\
                 review transcript, if any:\n{}",
                first_lines_file(&self.paths.review_transcript, 240)
            )));
        }

        let review = fs::read_to_string(review_file).map_err(|error| {
            ElenchusError::failure(format!("error: failed to read review output: {error}"))
        })?;
        let status_lines = review
            .lines()
            .filter(|line| line.starts_with("REVIEW_STATUS: "))
            .count();
        let first_line = review.lines().next().unwrap_or_default();
        if status_lines != 1 || first_line != PASS_STATUS {
            return Err(ElenchusError::failure(format!(
                "error: review did not produce exactly one passing status line\n\n{}",
                first_lines(&review, 260)
            )));
        }

        Ok(())
    }

    /// Writes the transcript used when an accepted diff reuses a cached review.
    fn write_reused_review_transcript(&self, diff_fingerprint: &str, token: &str) -> Result<()> {
        let review_output = prefix_lines(
            &fs::read_to_string(&self.paths.review_out).map_err(|error| {
                ElenchusError::failure(format!(
                    "error: failed to read cached review output: {error}"
                ))
            })?,
            "> ",
        );
        fs::write(
            &self.paths.review_transcript,
            format!(
                "Elenchus reused a prior passing read-only review for this exact diff.\n\n\
                 Diff fingerprint: {diff_fingerprint}\n\
                 Risk token: {token}\n\
                 Cached review: {}\n\n\
                 Review output:\n{review_output}",
                self.paths.review_out.display()
            ),
        )
        .map_err(|error| {
            ElenchusError::failure(format!(
                "error: failed to write reused review transcript: {error}"
            ))
        })
    }

    /// Replaces a raw transcript with the concise successful-review artifact.
    fn discard_review_transcript(&self) -> Result<()> {
        let review_output = prefix_lines(
            &fs::read_to_string(&self.paths.review_out).map_err(|error| {
                ElenchusError::failure(format!("error: failed to read review output: {error}"))
            })?,
            "> ",
        );
        fs::write(
            &self.paths.review_transcript,
            format!(
                "Elenchus review passed. The raw reviewer stdout/stderr transcript was\n\
                 discarded to keep elenchus artifacts concise.\n\n\
                 Set ELENCHUS_KEEP_REVIEW_TRANSCRIPT=1 to preserve the full transcript.\n\n\
                 Review output:\n{review_output}"
            ),
        )
        .map_err(|error| {
            ElenchusError::failure(format!(
                "error: failed to discard review transcript: {error}"
            ))
        })
    }
}