Skip to main content

vitrify_cli/run/
escalate.rs

1//! Escalation client: assemble the evidence prompt from
2//! the resolved template, make ONE inference call through the strongest
3//! probed harness, parse the structured verdict, and return it typed. The
4//! orchestrator enforces verdicts; this module performs no state change.
5//! One malformed reply gets one re-ask with the parse error
6//! appended; a second malformed reply yields `abort`.
7
8use std::io::Read;
9use std::os::unix::process::CommandExt;
10use std::path::{Path, PathBuf};
11use std::process::{Command, Stdio};
12
13use vitrify_core::CoreError;
14
15use crate::home;
16use crate::out::J;
17
18#[derive(Debug, Clone)]
19pub struct Evidence {
20    pub unit: String,
21    pub branch: String,
22    pub fencing: String,
23    pub command: String,
24    pub output_tail: String,
25    pub journal_tail: String,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum VerdictKind {
30    Retry,
31    Release,
32    Block,
33    Abort,
34}
35
36impl VerdictKind {
37    pub fn as_str(self) -> &'static str {
38        match self {
39            VerdictKind::Retry => "retry",
40            VerdictKind::Release => "release",
41            VerdictKind::Block => "block",
42            VerdictKind::Abort => "abort",
43        }
44    }
45}
46
47#[derive(Debug, Clone)]
48pub struct Verdict {
49    pub verdict: VerdictKind,
50    pub unit: Option<String>,
51    pub q: Option<String>,
52    pub reason: String,
53}
54
55fn tail_lines(text: &str, n: usize) -> String {
56    let lines: Vec<&str> = text.lines().collect();
57    let start = lines.len().saturating_sub(n);
58    lines[start..].join("\n")
59}
60
61/// Fill the template's evidence slots: output tail truncated to the
62/// last 100 lines, journal tail to the last 20 events.
63pub fn build_prompt(
64    home_dir: &Path,
65    version: &str,
66    evidence: &Evidence,
67) -> Result<String, CoreError> {
68    let (template, _) = home::resolve(home_dir, version, "briefs/escalation.md")?;
69    Ok(template
70        .replace("{unit}", &evidence.unit)
71        .replace("{branch}", &evidence.branch)
72        .replace("{fencing}", &evidence.fencing)
73        .replace("{command}", &evidence.command)
74        .replace("{output_tail}", &tail_lines(&evidence.output_tail, 100))
75        .replace("{journal_tail}", &tail_lines(&evidence.journal_tail, 20)))
76}
77
78fn invoke(argv: &[String], prompt: &str) -> Result<String, CoreError> {
79    let mut cmd = Command::new(&argv[0]);
80    cmd.args(&argv[1..])
81        .arg(prompt)
82        .stdin(Stdio::null())
83        .stdout(Stdio::piped())
84        .stderr(Stdio::null())
85        .process_group(0);
86    let mut child = cmd.spawn().map_err(|e| {
87        CoreError::refusal(1, format!("error: failed to spawn escalation call: {e}"))
88    })?;
89    // Read on a thread, into a buffer this thread can take at any moment:
90    // an interrupt must not wait for the judge, and a process the judge
91    // left behind holding the pipe open must not hold the run.
92    let reply = std::sync::Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
93    let reader = child.stdout.take().map(|mut stdout| {
94        let reply = std::sync::Arc::clone(&reply);
95        std::thread::spawn(move || {
96            let mut chunk = [0u8; 8192];
97            while let Ok(n) = stdout.read(&mut chunk) {
98                if n == 0 {
99                    break;
100                }
101                reply
102                    .lock()
103                    .unwrap_or_else(|e| e.into_inner())
104                    .extend_from_slice(&chunk[..n]);
105            }
106        })
107    });
108    loop {
109        match child.try_wait() {
110            Ok(Some(_)) | Err(_) => break,
111            Ok(None) => {}
112        }
113        if crate::signals::interrupted() {
114            crate::gate::kill_group(child.id());
115            let _ = child.wait();
116            break;
117        }
118        std::thread::sleep(std::time::Duration::from_millis(50));
119    }
120    // the judge has exited: its output is in the pipe; give the reader a
121    // moment to drain it, no longer
122    if let Some(reader) = reader {
123        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
124        while !reader.is_finished() && std::time::Instant::now() < deadline {
125            std::thread::sleep(std::time::Duration::from_millis(20));
126        }
127    }
128    let bytes = reply.lock().unwrap_or_else(|e| e.into_inner()).clone();
129    Ok(String::from_utf8_lossy(&bytes).into_owned())
130}
131
132fn parse_verdict(reply: &str) -> Result<Verdict, String> {
133    // Replies arrive through the recorded headless spelling, so they may be
134    // wrapped in the same JSON envelope/event stream as worker reports;
135    // unwrap identically, then parse the last non-empty, non-fence line.
136    let text = super::worker::extract_final_text(reply);
137    let Some(line) = super::worker::last_content_line(&text) else {
138        return Err("empty reply".to_string());
139    };
140    let v: serde_json::Value =
141        serde_json::from_str(line.trim()).map_err(|e| format!("invalid JSON: {e}"))?;
142    let kind = match v.get("verdict").and_then(|x| x.as_str()) {
143        Some("retry") => VerdictKind::Retry,
144        Some("release") => VerdictKind::Release,
145        Some("block") => VerdictKind::Block,
146        Some("abort") => VerdictKind::Abort,
147        other => return Err(format!("unknown verdict {other:?}")),
148    };
149    let q = v
150        .get("q")
151        .and_then(|x| x.as_str())
152        .filter(|s| !s.is_empty())
153        .map(str::to_string);
154    if kind == VerdictKind::Block && q.is_none() {
155        return Err("verdict `block` requires `q`".to_string());
156    }
157    Ok(Verdict {
158        verdict: kind,
159        unit: v
160            .get("unit")
161            .and_then(|x| x.as_str())
162            .filter(|s| !s.is_empty())
163            .map(str::to_string),
164        q,
165        reason: v
166            .get("reason")
167            .and_then(|x| x.as_str())
168            .unwrap_or("")
169            .to_string(),
170    })
171}
172
173/// One escalation: prompt → call → parse; one re-ask on a malformed reply;
174/// a second malformed reply ⇒ `abort` (safe default). Evidence + replies +
175/// the verdict land in `logs_dir/escalation-<n>.json`.
176pub fn escalate(
177    home_dir: &Path,
178    version: &str,
179    argv_template: &[String],
180    evidence: &Evidence,
181    logs_dir: &Path,
182    index: u32,
183) -> Result<(Verdict, PathBuf), CoreError> {
184    let prompt = build_prompt(home_dir, version, evidence)?;
185    let mut replies: Vec<String> = Vec::new();
186
187    let first = invoke(argv_template, &prompt)?;
188    replies.push(first.clone());
189    let verdict = match parse_verdict(&first) {
190        Ok(v) => v,
191        Err(err1) => {
192            let reask = format!(
193                "{prompt}\n\nYour previous reply could not be parsed ({err1}). Reply again with ONLY the single JSON verdict object as the last non-empty line."
194            );
195            let second = invoke(argv_template, &reask)?;
196            replies.push(second.clone());
197            match parse_verdict(&second) {
198                Ok(v) => v,
199                Err(err2) => Verdict {
200                    verdict: VerdictKind::Abort,
201                    unit: Some(evidence.unit.clone()),
202                    q: None,
203                    reason: format!("malformed escalation reply twice ({err2})"),
204                },
205            }
206        }
207    };
208
209    std::fs::create_dir_all(logs_dir).map_err(|source| CoreError::Io {
210        path: logs_dir.to_path_buf(),
211        source,
212    })?;
213    let record = J::Obj(vec![
214        ("unit".into(), J::s(evidence.unit.clone())),
215        ("branch".into(), J::s(evidence.branch.clone())),
216        ("fencing".into(), J::s(evidence.fencing.clone())),
217        ("command".into(), J::s(evidence.command.clone())),
218        (
219            "output_tail".into(),
220            J::s(tail_lines(&evidence.output_tail, 100)),
221        ),
222        (
223            "journal_tail".into(),
224            J::s(tail_lines(&evidence.journal_tail, 20)),
225        ),
226        (
227            "replies".into(),
228            J::Arr(replies.iter().map(|r| J::s(r.clone())).collect()),
229        ),
230        ("verdict".into(), J::s(verdict.verdict.as_str())),
231        ("verdict_unit".into(), J::opt_str(verdict.unit.clone())),
232        ("verdict_q".into(), J::opt_str(verdict.q.clone())),
233        ("reason".into(), J::s(verdict.reason.clone())),
234    ]);
235    let path = logs_dir.join(format!("escalation-{index}.json"));
236    std::fs::write(&path, record.dumps_indent2()).map_err(|source| CoreError::Io {
237        path: path.clone(),
238        source,
239    })?;
240    Ok((verdict, path))
241}