Skip to main content

agent_hub_runtime/core/automation/
history.rs

1//! Local-only run evidence. Neither reads nor runtime writes enqueue Git backups.
2use super::{hermes_manage, managed, native, output, store};
3use serde::Serialize;
4use std::{fs, io::Read, path::Path};
5
6#[derive(Debug, Clone, Serialize)]
7pub struct AutomationRun {
8    pub id: String,
9    pub started_at: Option<String>,
10    pub finished_at: Option<String>,
11    pub status: String,
12    pub exit_code: Option<i32>,
13    pub has_output: bool,
14}
15#[derive(Debug, Serialize)]
16pub struct AutomationHistory {
17    pub runs: Vec<AutomationRun>,
18    pub kind: String,
19    pub limited: bool,
20}
21fn component(id: &str) -> bool {
22    !id.is_empty()
23        && id != "."
24        && id != ".."
25        && id
26            .bytes()
27            .all(|c| c.is_ascii_alphanumeric() || b"-_.".contains(&c))
28}
29fn marker(root: &Path, path: &Path) -> Result<Option<String>, String> {
30    output::checked(root, path)?;
31    match fs::metadata(path) {
32        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
33        Err(e) => return Err(e.to_string()),
34        Ok(meta) if !meta.is_file() || meta.len() > 4096 => {
35            return Err("Invalid execution marker".into())
36        }
37        _ => {}
38    }
39    let mut value = String::new();
40    fs::File::open(path)
41        .map_err(|e| e.to_string())?
42        .take(4096)
43        .read_to_string(&mut value)
44        .map_err(|e| e.to_string())?;
45    Ok(Some(value.trim().into()))
46}
47fn native_run(root: &Path, path: &Path, id: &str) -> Result<Option<AutomationRun>, String> {
48    let Some(started) = marker(root, &path.join("started"))? else {
49        return Ok(None);
50    };
51    let exit_code = marker(root, &path.join("exit"))?.and_then(|s| s.parse::<i32>().ok());
52    output::checked(root, &path.join("output.log"))?;
53    Ok(Some(AutomationRun {
54        id: id.into(),
55        started_at: Some(started),
56        finished_at: marker(root, &path.join("finished"))?,
57        status: match exit_code {
58            Some(0) => "completed",
59            Some(_) => "error",
60            None => "unknown",
61        }
62        .into(),
63        exit_code,
64        has_output: path.join("output.log").is_file(),
65    }))
66}
67fn native_history(dir: &Path, running: impl FnOnce() -> bool) -> Result<AutomationHistory, String> {
68    let current = marker(dir, &dir.join("current-run"))?;
69    let directory = dir.join("runs");
70    output::checked(dir, &directory)?;
71    let entries = match fs::read_dir(&directory) {
72        Ok(entries) => Some(entries),
73        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
74        Err(e) => return Err(e.to_string()),
75    };
76    let mut runs = vec![];
77    if let Some(entries) = entries {
78        for entry in entries {
79            let path = entry.map_err(|e| e.to_string())?.path();
80            let Some(id) = path
81                .file_name()
82                .and_then(|n| n.to_str())
83                .filter(|id| component(id))
84            else {
85                continue;
86            };
87            output::checked(dir, &path)?;
88            if path.is_dir() {
89                if let Some(run) = native_run(dir, &path, id)? {
90                    runs.push(run);
91                }
92            }
93        }
94    }
95    if runs.is_empty() && current.is_none() {
96        if let Some(run) = native_run(dir, dir, "legacy")? {
97            runs.push(run);
98        }
99    }
100    runs.sort_by(|a, b| {
101        (current.as_deref() == Some(b.id.as_str()))
102            .cmp(&(current.as_deref() == Some(a.id.as_str())))
103            .then_with(|| b.started_at.cmp(&a.started_at))
104            .then_with(|| b.id.cmp(&a.id))
105    });
106    let limited = runs.len() > 100;
107    runs.truncate(100);
108    // Finished histories are entirely local. Only the unfinished current run
109    // needs one scheduler check; older unfinished runs remain unknown.
110    if let Some(run) = runs.iter_mut().find(|run| {
111        run.exit_code.is_none()
112            && (current.as_deref() == Some(&run.id) || (current.is_none() && run.id == "legacy"))
113    }) {
114        if running() {
115            run.status = "running".into();
116        }
117    }
118    Ok(AutomationHistory {
119        runs,
120        kind: "executions".into(),
121        limited,
122    })
123}
124fn for_task(task: &super::AutomationTask) -> Result<AutomationHistory, String> {
125    if task.source == "hermes" {
126        let home = hermes_manage::root_for(task)?;
127        let outputs = output::hermes_outputs(
128            &home,
129            task.identifier.as_deref().ok_or("Missing Hermes job ID")?,
130        )?;
131        let limited = outputs.len() > 100;
132        let runs = outputs
133            .into_iter()
134            .take(100)
135            .filter_map(|path| {
136                let id = path.file_name()?.to_str()?.to_owned();
137                let saved = chrono::NaiveDateTime::parse_from_str(
138                    id.trim_end_matches(".md"),
139                    "%Y-%m-%d_%H-%M-%S",
140                )
141                .ok()?;
142                Some(AutomationRun {
143                    finished_at: Some(saved.format("%Y-%m-%d %H:%M:%S").to_string()),
144                    id,
145                    started_at: None,
146                    status: "unknown".into(),
147                    exit_code: None,
148                    has_output: true,
149                })
150            })
151            .collect();
152        Ok(AutomationHistory {
153            runs,
154            kind: "hermes_outputs".into(),
155            limited,
156        })
157    } else if let Some(dir) = output::native_directory(task)? {
158        native_history(&dir, || task.status == "running")
159    } else {
160        Ok(AutomationHistory {
161            runs: vec![],
162            kind: "unsupported".into(),
163            limited: false,
164        })
165    }
166}
167pub fn history(id: &str) -> Result<AutomationHistory, String> {
168    if let Some((record, dir)) = output::native_task_at(&store::root(), id)? {
169        return native_history(&dir, || native::is_running(&record));
170    }
171    let mut report = for_task(&managed::find(id)?)?;
172    if let Ok(record) = super::package::find(&store::root(), id) {
173        let directory = super::package::checked(&store::root(), &record)?.join(".local");
174        let actions = native_history(&directory, || false)?;
175        report.runs.extend(
176            actions
177                .runs
178                .into_iter()
179                .filter(|run| run.id.starts_with("action-")),
180        );
181        report.runs.sort_by(|a, b| {
182            b.started_at
183                .as_ref()
184                .or(b.finished_at.as_ref())
185                .cmp(&a.started_at.as_ref().or(a.finished_at.as_ref()))
186        });
187        report.limited |= report.runs.len() > 100;
188        report.runs.truncate(100);
189    }
190    Ok(report)
191}
192pub fn run_output(id: &str, run_id: &str) -> Result<output::AutomationRunOutput, String> {
193    if !component(run_id) {
194        return Err("Invalid execution ID".into());
195    }
196    if let Some((_, root)) = output::native_task_at(&store::root(), id)? {
197        // Output membership is local; reading a saved log needs no live status.
198        let report = native_history(&root, || false)?;
199        if !report.runs.iter().any(|run| run.id == run_id) {
200            return Err("Execution record is no longer available; refresh the history".into());
201        }
202        return native_output(&root, run_id);
203    }
204    if run_id.starts_with("action-") {
205        let record = super::package::find(&store::root(), id)?;
206        let root = super::package::checked(&store::root(), &record)?.join(".local");
207        let report = native_history(&root, || false)?;
208        if !report.runs.iter().any(|run| run.id == run_id) {
209            return Err("Execution record is no longer available; refresh the history".into());
210        }
211        return native_output(&root, run_id);
212    }
213    let task = managed::find(id)?;
214    let report = for_task(&task)?;
215    if !report.runs.iter().any(|run| run.id == run_id) {
216        return Err("Execution record is no longer available; refresh the history".into());
217    }
218    let (root, path, kind) = if task.source == "hermes" {
219        let root = hermes_manage::root_for(&task)?;
220        let path = output::hermes_outputs(
221            &root,
222            task.identifier.as_deref().ok_or("Missing Hermes job ID")?,
223        )?
224        .into_iter()
225        .find(|path| path.file_name().is_some_and(|name| name == run_id))
226        .ok_or("Result file is no longer available")?;
227        (root, path, "hermes")
228    } else {
229        let root = output::native_directory(&task)?.ok_or("Missing task directory")?;
230        return native_output(&root, run_id);
231    };
232    let mut result = output::read_output(&root, &path)?;
233    result.kind = kind.into();
234    Ok(result)
235}
236
237fn native_output(root: &Path, run_id: &str) -> Result<output::AutomationRunOutput, String> {
238    let path = if run_id == "legacy" && !root.join("runs/legacy").exists() {
239        root.join("output.log")
240    } else {
241        root.join("runs").join(run_id).join("output.log")
242    };
243    let mut result = output::read_output(root, &path)?;
244    result.kind = "system".into();
245    Ok(result)
246}
247
248#[cfg(test)]
249mod tests;