Skip to main content

git_policy_cli/
standards_review_run.rs

1//! What:
2//!  The standards-review shadow run, end to end and in-process: classify the landed commit's names, read the commit,
3//!  build the capped input, call the gateway, and append the one log entry. Also a bounded runner that gives a caller a
4//!  hard time limit over all of it.
5//! Why:
6//!  This replaces the root `mise.toml` task `shadow-review` (its Luna route; the `SHADOW_REVIEW_ALLOW=1` route starts
7//!  `pi` and is not ported). The review must never delay or fail a landing, so nothing here panics or returns a failure
8//!  the landing would act on, and `run_within` abandons the work when the time is up. Nothing calls this yet.
9//!
10//! In TS you'd write (pseudocode):
11//! ```ts
12//! const outcome = await reviewLanded({ names, sha, subject, read, options, clock });
13//! ```
14
15use super::iso_time::format_iso_milliseconds;
16use super::standards_review_client::{Gateway, Reply, SCRIPT_DEADLINE, post_decision};
17use super::standards_review_entry::{ReviewEntry, append_entry, render_review, render_skipped};
18use super::standards_review_input::{LOG_RELATIVE, LandedCommit, Plan, ReviewInput, build_input, plan_for};
19use super::standards_review_request::{ENDPOINT, Judged, read_answer, request_body};
20use super::standards_review_text::seconds_with_tenth;
21use std::path::{Path, PathBuf};
22use std::sync::mpsc;
23use std::time::Duration;
24
25/// The environment variable that points the log at a disposable fixture.
26pub const LOG_VARIABLE: &str = "SHADOW_REVIEW_LOG";
27
28/// The variable that replays a commit other than `HEAD`.
29pub const SHA_VARIABLE: &str = "SHADOW_REVIEW_SHA";
30
31/// The variable that asks for the full review route, which this port does not run.
32pub const ALLOW_VARIABLE: &str = "SHADOW_REVIEW_ALLOW";
33
34/// The credential variable, and the stop-hook credential used when it is unset.
35pub const KEY_VARIABLES: [&str; 2] = ["SHADOW_REVIEW_LLMGATEWAY_API_KEY", "STOP_REMINDER_LLMGATEWAY_API_KEY"];
36
37/// The failure line written when no credential is set.
38pub const NO_KEY_MESSAGE: &str = "no SHADOW_REVIEW_LLMGATEWAY_API_KEY or STOP_REMINDER_LLMGATEWAY_API_KEY in the environment";
39
40/// What:
41///  What the run was told: the log, the credential, and where and how long to call.
42/// Why:
43///   Production passes `ENDPOINT` and `SCRIPT_DEADLINE`; tests pass a loopback URL and a short deadline.
44///
45/// In TS you'd write (pseudocode):
46/// ```ts
47/// type ReviewOptions = { logPath: string; apiKey?: string; endpoint: string; deadline: number };
48/// ```
49#[derive(Clone, Debug)]
50pub struct ReviewOptions {
51    /// Where entries are appended.
52    pub log_path: PathBuf,
53    /// The bearer credential; `None` writes the no-credential failure entry.
54    pub api_key: Option<String>,
55    /// The decisions endpoint.
56    pub endpoint: String,
57    /// The gateway call's total time.
58    pub deadline: Duration,
59    /// A PEM authority replacing the embedded roots (tests only).
60    pub trusted_pem: Option<Vec<u8>>,
61}
62
63/// What:
64///  The options the script's environment variables give for a repository: the log under `repo_root` unless
65///  `SHADOW_REVIEW_LOG` names another, and the first credential variable that is set, even to an empty text.
66/// Why:
67///   `??` in the script falls back only for an unset variable, so an empty first key does not fall back.
68///
69/// In TS you'd write (pseudocode):
70/// ```ts
71/// const logPath = process.env.SHADOW_REVIEW_LOG ?? `${repo}/doc/audit/standards-review-gate-shadow.md`;
72/// ```
73pub fn options_from_environment(repo_root: &Path, variable: &dyn Fn(&str) -> Option<String>) -> ReviewOptions {
74    let log_path: PathBuf = variable(LOG_VARIABLE).map_or_else(|| return repo_root.join(LOG_RELATIVE), PathBuf::from);
75    let api_key: Option<String> = variable(KEY_VARIABLES[0]).or_else(|| return variable(KEY_VARIABLES[1]));
76    return ReviewOptions { log_path, api_key, endpoint: String::from(ENDPOINT), deadline: SCRIPT_DEADLINE, trusted_pem: None };
77}
78
79/// What:
80///  Whether the environment asks for the full-review route, which this port leaves out.
81/// Why:
82///   The caller says so in a notice instead of silently running the cheap route.
83///
84/// In TS you'd write (pseudocode):
85/// ```ts
86/// process.env.SHADOW_REVIEW_ALLOW === '1'
87/// ```
88pub fn full_review_requested(variable: &dyn Fn(&str) -> Option<String>) -> bool {
89    return variable(ALLOW_VARIABLE).as_deref() == Some("1");
90}
91
92/// What:
93///  How a run ended.
94/// Why:
95///   Callers log it; none of it fails a landing.
96///
97/// In TS you'd write (pseudocode):
98/// ```ts
99/// type ReviewOutcome = 'no-entry' | 'skipped' | { reviewed: Judged } | { unread: string } | { unwritable: string };
100/// ```
101#[derive(Clone, Debug, Eq, PartialEq)]
102pub enum ReviewOutcome {
103    /// No names, or only the log: no entry, as the script exits silently.
104    NoEntry,
105    /// The no-code-files entry was appended.
106    Skipped,
107    /// A review entry was appended; the gateway's verdict, or its failure in `outcome` with an empty `top`.
108    Reviewed(Judged),
109    /// The commit could not be read; no entry.
110    Unread(String),
111    /// The entry could not be appended.
112    Unwritable(String),
113}
114
115/// What:
116///  The gateway step: the verdict, or the failure message, and the elapsed milliseconds.
117/// Why:
118///   A missing credential fails before any connection, as in the script.
119///
120/// In TS you'd write (pseudocode):
121/// ```ts
122/// try { ...fetch... } catch (error) { lunaOutcome = 'Luna failed: ' + message }
123/// ```
124fn ask_gateway(input: &ReviewInput, options: &ReviewOptions) -> Judged {
125    let failed = |message: String| return Judged { top: String::new(), outcome: format!("Luna failed: {message}") };
126    let key: &str = options.api_key.as_deref().unwrap_or("");
127    if key.is_empty() {
128        return failed(String::from(NO_KEY_MESSAGE));
129    }
130    let gateway: Gateway = Gateway { url: options.endpoint.as_str(), api_key: key, deadline: options.deadline, trusted_pem: options.trusted_pem.as_deref() };
131    let reply: Result<Reply, String> = post_decision(&gateway, request_body(input.model_input.as_str()).as_str());
132    return match reply.and_then(|answer| return read_answer(answer.status, answer.body.as_str())) {
133        Ok(judged) => judged,
134        Err(message) => failed(message),
135    };
136}
137
138/// What:
139///  Review one landed commit: `names` are the changed names the landing knows, `read` fetches the commit's patch and
140///  files (called only for a commit with code files), `now_millis` is the clock.
141/// Why:
142///   One function is the script's whole body, with the reads and the clock as parameters so tests fix both.
143///
144/// In TS you'd write (pseudocode):
145/// ```ts
146/// async function reviewLanded({ names, sha, subject, read, options, nowMillis }): Promise<ReviewOutcome>;
147/// ```
148pub fn review_landed(
149    names: &[String],
150    sha: &str,
151    subject: &str,
152    read: &dyn Fn(&[String]) -> Result<LandedCommit, String>,
153    options: &ReviewOptions,
154    now_millis: &dyn Fn() -> u64,
155) -> ReviewOutcome {
156    let code_files: Vec<String> = match plan_for(names) {
157        Plan::Silent => return ReviewOutcome::NoEntry,
158        Plan::NoCode => {
159            return match append_entry(options.log_path.as_path(), render_skipped(sha, subject).as_str()) {
160                Ok(()) => ReviewOutcome::Skipped,
161                Err(error) => ReviewOutcome::Unwritable(error.to_string()),
162            };
163        }
164        Plan::Review(files) => files,
165    };
166    let commit: LandedCommit = match read(code_files.as_slice()) {
167        Ok(read_commit) => read_commit,
168        Err(message) => return ReviewOutcome::Unread(message),
169    };
170    let input: ReviewInput = build_input(&commit, code_files.as_slice());
171    let started: u64 = now_millis();
172    let judged: Judged = ask_gateway(&input, options);
173    let finished: u64 = now_millis();
174    let entry: ReviewEntry = ReviewEntry {
175        date: format_iso_milliseconds(i64::try_from(finished).unwrap_or(i64::MAX)),
176        sha: String::from(sha),
177        subject: String::from(subject),
178        code_files: input.code_file_count,
179        diff_lines: input.diff_line_count,
180        truncated: input.truncated,
181        input_units: input.model_input_units,
182        seconds: seconds_with_tenth(finished.saturating_sub(started)),
183        top: judged.top.clone(),
184        outcome: judged.outcome.clone(),
185    };
186    return match append_entry(options.log_path.as_path(), render_review(&entry).as_str()) {
187        Ok(()) => ReviewOutcome::Reviewed(judged),
188        Err(error) => ReviewOutcome::Unwritable(error.to_string()),
189    };
190}
191
192/// What:
193///  Run `job` on a helper thread and wait at most `limit`; `None` means the time ran out and the job was abandoned.
194///  An abandoned job keeps running until the process exits, which is the end of the wrapper command.
195/// Why:
196///   This is the hard bound over the Git reads, the call and the log write together: the landing's caller waits `limit`
197///   at most. A job that panics also gives `None`.
198///
199/// In TS you'd write (pseudocode):
200/// ```ts
201/// await Promise.race([job(), wait(limit).then(() => undefined)])
202/// ```
203pub fn run_within<T: Send + 'static>(limit: Duration, job: impl FnOnce() -> T + Send + 'static) -> Option<T> {
204    let (sender, receiver) = mpsc::channel::<T>();
205    let worker = std::thread::Builder::new().name(String::from("standards-review")).spawn(move || {
206        let _ = sender.send(job());
207    });
208    if worker.is_err() {
209        return None;
210    }
211    return receiver.recv_timeout(limit).ok();
212}
213
214/// Controls stay out of the release executable.
215#[cfg(test)]
216#[path = "standards_review_run_tests.rs"]
217mod tests;