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