Skip to main content

vitrify_cli/run/
worker.rs

1//! Worker dispatch and report extraction. One worker = one
2//! OS process: recorded argv template + generated prompt as the final
3//! argument, cwd = the unit worktree, its own Unix process group, a private
4//! `TMPDIR`, stdout/stderr written straight to
5//! `.vitrify/logs/<job>/worker-<holder>.{out,err}` as the harness produces
6//! them — with a streaming spelling, a worker that is killed leaves its
7//! session up to that point.
8
9use std::os::unix::process::CommandExt;
10use std::path::{Path, PathBuf};
11use std::process::{Child, Command, Stdio};
12
13use vitrify_core::CoreError;
14
15/// The C-004 worker report line.
16#[derive(Debug, Clone, PartialEq)]
17pub struct Report {
18    pub unit: String,
19    pub outcome: String, // built | blocked | released
20    pub branch: String,
21    pub claim_seq: i64,
22    pub q: Option<String>,
23    pub notes: String,
24}
25
26/// A spawned worker: child process (own process group), log paths.
27pub struct WorkerHandle {
28    pub holder: String,
29    pub unit: String,
30    pub child: Child,
31    pub pid: u32,
32    pub out_path: PathBuf,
33    pub err_path: PathBuf,
34}
35
36/// Spawn one worker per C-003. A missing template binary is a named error —
37/// never guess a spelling.
38pub fn spawn(
39    argv_template: &[String],
40    prompt: &str,
41    cwd: &Path,
42    logs_dir: &Path,
43    holder: &str,
44    unit: &str,
45) -> Result<WorkerHandle, CoreError> {
46    spawn_in(argv_template, prompt, cwd, logs_dir, holder, unit, None)
47}
48
49/// [`spawn`] with a private temp directory: workers build side by side, and
50/// test runners that share one temp root trip over each other.
51pub fn spawn_in(
52    argv_template: &[String],
53    prompt: &str,
54    cwd: &Path,
55    logs_dir: &Path,
56    holder: &str,
57    unit: &str,
58    tmpdir: Option<&Path>,
59) -> Result<WorkerHandle, CoreError> {
60    if argv_template.is_empty() {
61        return Err(CoreError::refusal(
62            2,
63            "error: empty worker argv template: ~/.vitrify/config.toml records no headless spelling → vitrify probe",
64        ));
65    }
66    std::fs::create_dir_all(logs_dir).map_err(|source| CoreError::Io {
67        path: logs_dir.to_path_buf(),
68        source,
69    })?;
70    let out_path = logs_dir.join(format!("worker-{holder}.out"));
71    let err_path = logs_dir.join(format!("worker-{holder}.err"));
72    let out_file = std::fs::File::create(&out_path).map_err(|source| CoreError::Io {
73        path: out_path.clone(),
74        source,
75    })?;
76    let err_file = std::fs::File::create(&err_path).map_err(|source| CoreError::Io {
77        path: err_path.clone(),
78        source,
79    })?;
80
81    let mut cmd = Command::new(&argv_template[0]);
82    cmd.args(&argv_template[1..])
83        .arg(prompt)
84        .current_dir(cwd)
85        .stdin(Stdio::null())
86        .stdout(Stdio::from(out_file))
87        .stderr(Stdio::from(err_file))
88        .process_group(0);
89    if let Some(tmp) = tmpdir {
90        cmd.env("TMPDIR", tmp);
91    }
92    let child = cmd.spawn().map_err(|e| {
93        if e.kind() == std::io::ErrorKind::NotFound {
94            CoreError::refusal(
95                2,
96                format!(
97                    "error: probed worker binary not found: {} — re-run `vitrify probe`",
98                    argv_template[0]
99                ),
100            )
101        } else {
102            CoreError::refusal(1, format!("error: failed to spawn worker: {e}"))
103        }
104    })?;
105    let pid = child.id();
106    Ok(WorkerHandle {
107        holder: holder.to_string(),
108        unit: unit.to_string(),
109        child,
110        pid,
111        out_path,
112        err_path,
113    })
114}
115
116/// SIGKILL a worker's whole process group (`kill(2)`, declared in
117/// `signals.rs` — no shell, no subprocess, no crate).
118pub fn kill_group(pid: u32) {
119    crate::gate::kill_group(pid);
120}
121
122/// The extraction rule: if the output is the
123/// probed JSON envelope/event stream, extract the assistant's final text;
124/// else raw stdout; in either case parse the LAST NON-EMPTY LINE against
125/// the schema — models habitually wrap the line in a markdown code fence,
126/// so fence-delimiter lines don't count as content. `None` =
127/// missing/unparseable (treated as released + failed).
128pub fn extract_report(stdout_text: &str) -> Option<Report> {
129    let text = extract_final_text(stdout_text);
130    if let Some(report) = last_content_line(&text).and_then(parse_report_line) {
131        return Some(report);
132    }
133    // An event stream with a line that is not an event (a truncated final
134    // write, a stray warning) is still an event stream: take the last event
135    // whose text ends in a report line.
136    stdout_text
137        .lines()
138        .rev()
139        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l.trim()).ok())
140        .filter_map(|v| envelope_text(&v))
141        .find_map(|t| last_content_line(&t).and_then(parse_report_line))
142}
143
144/// The last non-empty line that is not a code-fence delimiter (``` / ~~~,
145/// with or without an info string).
146pub(crate) fn last_content_line(text: &str) -> Option<&str> {
147    text.lines()
148        .rev()
149        .map(str::trim)
150        .find(|l| !l.is_empty() && !l.starts_with("```") && !l.starts_with("~~~"))
151}
152
153/// Shared with the escalation client: verdict replies arrive through the
154/// same recorded spellings and need the same unwrapping.
155pub(crate) fn extract_final_text(stdout_text: &str) -> String {
156    // the whole output one JSON value: a single envelope, or a bare reply
157    if let Ok(v) = serde_json::from_str::<serde_json::Value>(stdout_text) {
158        if let Some(t) = envelope_text(&v) {
159            return t;
160        }
161        return stdout_text.to_string();
162    }
163    // NDJSON event stream: every non-empty line is JSON
164    let lines: Vec<&str> = stdout_text
165        .lines()
166        .filter(|l| !l.trim().is_empty())
167        .collect();
168    if lines.len() > 1 {
169        let parsed: Vec<Option<serde_json::Value>> = lines
170            .iter()
171            .map(|l| serde_json::from_str(l.trim()).ok())
172            .collect();
173        if parsed.iter().all(Option::is_some) {
174            // the assistant's final text: last event carrying one
175            for v in parsed.iter().rev().flatten() {
176                if let Some(t) = envelope_text(v) {
177                    return t;
178                }
179            }
180        }
181    }
182    stdout_text.to_string()
183}
184
185/// Text payload of a harness JSON envelope/event, across the probed
186/// formats' spellings.
187fn envelope_text(v: &serde_json::Value) -> Option<String> {
188    for key in ["result", "text", "last_agent_message", "content"] {
189        if let Some(s) = v.get(key).and_then(|x| x.as_str()) {
190            return Some(s.to_string());
191        }
192    }
193    // claude stream-json: {"type":"assistant","message":{"content":[{"type":"text","text":...}]}}
194    if let Some(content) = v.pointer("/message/content").and_then(|c| c.as_array()) {
195        let mut out = String::new();
196        for item in content {
197            if let Some(t) = item.get("text").and_then(|x| x.as_str()) {
198                out.push_str(t);
199            }
200        }
201        if !out.is_empty() {
202            return Some(out);
203        }
204    }
205    None
206}
207
208fn parse_report_line(line: &str) -> Option<Report> {
209    let v: serde_json::Value = serde_json::from_str(line).ok()?;
210    let outcome = v.get("outcome")?.as_str()?.to_string();
211    if !["built", "blocked", "released"].contains(&outcome.as_str()) {
212        return None;
213    }
214    Some(Report {
215        unit: v.get("unit")?.as_str()?.to_string(),
216        outcome,
217        branch: v
218            .get("branch")
219            .and_then(|x| x.as_str())
220            .unwrap_or("")
221            .to_string(),
222        claim_seq: v.get("claim_seq").and_then(|x| x.as_i64()).unwrap_or(0),
223        q: v.get("q").and_then(|x| x.as_str()).map(str::to_string),
224        notes: v
225            .get("notes")
226            .and_then(|x| x.as_str())
227            .unwrap_or("")
228            .to_string(),
229    })
230}
231
232/// The missing/unparseable-report rule: treated as `released` with
233/// `notes: "unparseable report"`; the unit counts failed for the wave.
234pub fn report_or_released(stdout_text: &str, unit: &str) -> (Report, bool) {
235    match extract_report(stdout_text) {
236        Some(r) => (r, true),
237        None => (
238            Report {
239                unit: unit.to_string(),
240                outcome: "released".to_string(),
241                branch: String::new(),
242                claim_seq: 0,
243                q: None,
244                notes: "unparseable report".to_string(),
245            },
246            false,
247        ),
248    }
249}