1use std::time::Duration;
7
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9use serde_json::{Map, Value, json};
10
11use crate::{config::Priority, runtime::Verdict};
12
13pub use artifactize_harness::verdict::AgentIssue;
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(deny_unknown_fields)]
18pub struct HumanIssue {
19 pub reason: String,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "camelCase", deny_unknown_fields)]
26pub struct RuntimeIssue {
27 pub exit_code: i32,
28 pub reason: String,
29}
30
31#[derive(Debug, Clone, PartialEq)]
32pub struct RuntimeResult {
33 pub verdict: Verdict,
34 pub issues: Vec<RuntimeIssue>,
35 pub duration: Option<Duration>,
36}
37
38impl RuntimeResult {
39 pub fn exited(exit_code: i32, reason: impl FnOnce() -> String, duration: Duration) -> Self {
41 let (verdict, issues) = if exit_code == 0 {
42 (Verdict::Green, Vec::new())
43 } else {
44 (
45 Verdict::Red,
46 vec![RuntimeIssue {
47 exit_code,
48 reason: reason(),
49 }],
50 )
51 };
52 Self {
53 verdict,
54 issues,
55 duration: Some(duration),
56 }
57 }
58
59 pub fn summary(&self) -> Self {
61 Self {
62 verdict: self.verdict,
63 issues: self
64 .issues
65 .iter()
66 .map(|issue| RuntimeIssue {
67 exit_code: issue.exit_code,
68 reason: exited_with(issue.exit_code),
69 })
70 .collect(),
71 duration: self.duration,
72 }
73 }
74}
75
76pub fn exited_with(exit_code: i32) -> String {
78 format!("Process exited with code {exit_code}.")
79}
80
81#[derive(Debug, Clone, PartialEq)]
82pub enum ExecutionResult {
83 Agent {
84 verdict: Verdict,
85 issues: Vec<AgentIssue>,
86 },
87 Human {
88 verdict: Verdict,
89 issues: Vec<HumanIssue>,
90 },
91 Runtime(RuntimeResult),
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
96#[serde(rename_all = "camelCase")]
97pub struct Issue {
98 #[serde(skip_serializing_if = "Option::is_none")]
99 pub priority: Option<Priority>,
100 #[serde(skip_serializing_if = "Option::is_none")]
101 pub exit_code: Option<i32>,
102 pub reason: String,
103}
104
105impl ExecutionResult {
106 pub fn verdict(&self) -> Verdict {
107 match self {
108 Self::Agent { verdict, .. } | Self::Human { verdict, .. } => *verdict,
109 Self::Runtime(result) => result.verdict,
110 }
111 }
112
113 pub fn kind(&self) -> crate::config::ProfileKind {
114 match self {
115 Self::Agent { .. } => crate::config::ProfileKind::Agent,
116 Self::Human { .. } => crate::config::ProfileKind::Human,
117 Self::Runtime(_) => crate::config::ProfileKind::Runtime,
118 }
119 }
120
121 pub fn issues(&self) -> Vec<Issue> {
123 match self {
124 Self::Agent { issues, .. } => {
125 let mut listed: Vec<_> = issues
126 .iter()
127 .map(|issue| Issue {
128 priority: Some(issue.priority),
129 exit_code: None,
130 reason: issue.reason.clone(),
131 })
132 .collect();
133 listed.sort_by_key(|issue| issue.priority);
134 listed
135 }
136 Self::Human { issues, .. } => issues
137 .iter()
138 .map(|issue| Issue {
139 priority: None,
140 exit_code: None,
141 reason: issue.reason.clone(),
142 })
143 .collect(),
144 Self::Runtime(result) => result
145 .issues
146 .iter()
147 .map(|issue| Issue {
148 priority: None,
149 exit_code: Some(issue.exit_code),
150 reason: issue.reason.clone(),
151 })
152 .collect(),
153 }
154 }
155
156 pub fn exit_code(&self) -> Option<i32> {
158 match self {
159 Self::Runtime(result) => Some(result.issues.first().map_or(0, |issue| issue.exit_code)),
160 Self::Agent { .. } | Self::Human { .. } => None,
161 }
162 }
163
164 pub fn summary(&self) -> Option<String> {
167 let issues = self.issues();
168 let first = issues.first()?;
169 let count = match issues.len() {
170 1 => "1 issue".to_owned(),
171 count => format!("{count} issues"),
172 };
173 let lead = match (first.priority, first.exit_code) {
174 (Some(priority), _) => format!("{priority} "),
175 (None, Some(code)) => format!("exit {code}, "),
176 (None, None) => String::new(),
177 };
178 let reason = first
179 .reason
180 .lines()
181 .find(|line| !line.trim().is_empty())
182 .unwrap_or("");
183 Some(format!("{count}: {lead}{}", reason.trim()))
184 }
185
186 pub fn to_json(&self) -> Value {
188 let verdict = serde_json::to_value(self.verdict()).expect("verdict is JSON");
189 match self {
190 Self::Agent { issues, .. } => {
191 json!({"verdict": verdict, "kind": "agent", "issues": issues})
192 }
193 Self::Human { issues, .. } => {
194 json!({"verdict": verdict, "kind": "human", "issues": issues})
195 }
196 Self::Runtime(result) => {
197 let mut value =
198 json!({"verdict": verdict, "kind": "runtime", "issues": result.issues});
199 if let Some(duration) = result.duration {
200 value["durationMs"] = json!(
201 u64::try_from(duration.as_millis())
202 .expect("a saved runtime duration fits u64 milliseconds")
203 );
204 }
205 value
206 }
207 }
208 }
209}
210
211#[derive(Deserialize)]
212#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
213enum Tagged {
214 Agent {
215 verdict: Verdict,
216 issues: Vec<AgentIssue>,
217 },
218 Human {
219 verdict: Verdict,
220 issues: Vec<HumanIssue>,
221 },
222 Runtime {
223 verdict: Verdict,
224 issues: Vec<RuntimeIssue>,
225 #[serde(rename = "durationMs", default)]
226 duration_ms: Option<u64>,
227 },
228}
229
230impl TryFrom<Value> for ExecutionResult {
231 type Error = serde_json::Error;
232 fn try_from(value: Value) -> Result<Self, Self::Error> {
233 if value.get("kind").is_some() {
234 return Ok(match serde_json::from_value(value)? {
235 Tagged::Agent { verdict, issues } => Self::Agent { verdict, issues },
236 Tagged::Human { verdict, issues } => Self::Human { verdict, issues },
237 Tagged::Runtime {
238 verdict,
239 issues,
240 duration_ms,
241 } => Self::Runtime(RuntimeResult {
242 verdict,
243 issues,
244 duration: duration_ms.map(Duration::from_millis),
245 }),
246 });
247 }
248 legacy(value)
249 }
250}
251
252const LEGACY_REASON_CHARS: usize = 2000;
254
255fn legacy(value: Value) -> Result<ExecutionResult, serde_json::Error> {
258 use serde::de::Error;
259 let mut fields: Map<String, Value> = serde_json::from_value(value)?;
260 let verdict: Verdict = serde_json::from_value(fields.remove("verdict").unwrap_or(Value::Null))?;
261 if let Some(findings) = fields.remove("findings") {
262 let issues: Vec<AgentIssue> = serde_json::from_value(findings)?;
263 return Ok(ExecutionResult::Agent { verdict, issues });
264 }
265 if ["exitCode", "durationMs", "stdout", "stderr"]
266 .iter()
267 .any(|key| fields.contains_key(*key))
268 {
269 let exit_code: Option<i32> =
270 serde_json::from_value(fields.remove("exitCode").unwrap_or(Value::Null))?;
271 let duration: Option<u64> =
272 serde_json::from_value(fields.remove("durationMs").unwrap_or(Value::Null))?;
273 let text = |key: &str| {
274 fields
275 .get(key)
276 .and_then(Value::as_str)
277 .filter(|text| !text.trim().is_empty())
278 .map(str::to_owned)
279 };
280 let issues = match (verdict, exit_code) {
281 (Verdict::Red, Some(code)) => vec![RuntimeIssue {
282 exit_code: code,
283 reason: text("stderr").or_else(|| text("stdout")).map_or_else(
284 || exited_with(code),
285 |output| tail(&output, LEGACY_REASON_CHARS),
286 ),
287 }],
288 (Verdict::Red, None) => {
289 return Err(serde_json::Error::custom(
290 "a RED runtime result without an exit code",
291 ));
292 }
293 _ => Vec::new(),
294 };
295 return Ok(ExecutionResult::Runtime(RuntimeResult {
296 verdict,
297 issues,
298 duration: duration.map(Duration::from_millis),
299 }));
300 }
301 let issues = if verdict == Verdict::Red {
302 let mut reasons: Vec<String> = fields
303 .values()
304 .flat_map(|value| match value {
305 Value::String(text) => vec![text.clone()],
306 Value::Array(items) => items
307 .iter()
308 .filter_map(|item| item.as_str().map(str::to_owned))
309 .collect(),
310 _ => Vec::new(),
311 })
312 .filter(|reason| !reason.trim().is_empty())
313 .collect();
314 if reasons.is_empty() {
315 reasons.push("RED, with no reason saved.".into());
316 }
317 reasons
318 .into_iter()
319 .map(|reason| HumanIssue { reason })
320 .collect()
321 } else {
322 Vec::new()
323 };
324 Ok(ExecutionResult::Human { verdict, issues })
325}
326
327pub fn tail(text: &str, chars: usize) -> String {
329 let text = text.trim_end();
330 let count = text.chars().count();
331 if count <= chars {
332 return text.to_owned();
333 }
334 let start = text
335 .char_indices()
336 .nth(count - chars)
337 .map_or(0, |(index, _)| index);
338 let cut = &text[start..];
339 cut.find('\n')
340 .map_or(cut, |line| &cut[line + 1..])
341 .to_owned()
342}
343
344impl Serialize for ExecutionResult {
345 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
346 self.to_json().serialize(serializer)
347 }
348}
349impl<'de> Deserialize<'de> for ExecutionResult {
350 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
351 Self::try_from(Value::deserialize(deserializer)?).map_err(serde::de::Error::custom)
352 }
353}
354
355#[cfg(test)]
356mod tests;