Skip to main content

artifactize_core/monitor/model/
code.rs

1//! A Run on its code: the definition files the Run read, each `artf` and `eval` line with the
2//! Run's verdict where it is declared, and the explorer's folders and files, each with the
3//! first light of the evals declared in it or under it. Pure: it reads the files the Run saved
4//! (`store::read_run_sources`), the environment they were read with, and the Run's tree.
5use std::{
6    collections::BTreeMap,
7    ffi::OsString,
8    path::{Path, PathBuf},
9};
10
11use time::OffsetDateTime;
12
13use super::{
14    Target,
15    graph::{Light, eval_light, graph},
16    states::{Activity, EvalView},
17    tree::{Kind, Node, Tally},
18};
19use crate::{
20    config::lang,
21    store::definitions::Source,
22    types::{ArtifactName, EvalId},
23};
24
25/// The Run's code: the explorer's rows and the files they show.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Code {
28    /// Folders before files at each level, each level by name; a folder's rows follow it.
29    pub entries: Vec<Entry>,
30    /// Every file, in the order the explorer lists them.
31    pub files: Vec<File>,
32}
33
34/// A row of the explorer.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Entry {
37    pub path: PathBuf,
38    /// How many folders hold it.
39    pub depth: usize,
40    pub folder: bool,
41    /// The first light of the Run's evals declared in it or under it, and how many of them are
42    /// GREEN; none when it declares no eval of the Run.
43    pub light: Option<Light>,
44    pub tally: Option<Tally>,
45}
46
47/// A definition file as the Run read it, with the lines that declare something.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct File {
50    pub path: PathBuf,
51    pub text: String,
52    /// By line number, from 1.
53    pub lines: Vec<Line>,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Line {
58    /// From 1, as in the file.
59    pub number: usize,
60    pub declares: Declares,
61}
62
63/// What a line declares, with the Run's verdict on it.
64#[derive(Debug, Clone, PartialEq, Eq)]
65pub enum Declares {
66    /// An `artf` binding: its node's light and tally; a macro call's line also lists the evals
67    /// the call expands to, which are written in the macro.
68    Artifact {
69        name: ArtifactName,
70        light: Option<Light>,
71        tally: Option<Tally>,
72        made: Vec<Mark>,
73    },
74    /// An `eval` written for one Artifact.
75    Eval(Mark),
76    /// An `eval` written in a macro: one eval for each Artifact the macro made.
77    Shared {
78        light: Option<Light>,
79        tally: Option<Tally>,
80        evals: Vec<Mark>,
81    },
82}
83
84/// An eval and its verdict in the Run; none when the Run did not select it.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct Mark {
87    pub eval: EvalId,
88    pub verdict: Option<Verdict>,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq)]
92pub struct Verdict {
93    pub light: Light,
94    pub word: Word,
95    /// What the eval's status says after its word, then its time, such as `exit 101` or
96    /// `reused`; empty when the word says it all.
97    pub detail: String,
98}
99
100/// The word a verdict is read by.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum Word {
103    Green,
104    Red,
105    Error,
106    Running,
107    /// Waiting for a person: a Human review.
108    Human,
109    Waiting,
110    Blocked,
111}
112
113/// The Run's code: `sources` read again with `environment`, lit by `tree` as of `now`.
114pub fn code(
115    sources: &[Source],
116    environment: &BTreeMap<String, Option<String>>,
117    tree: &[Node],
118    now: OffsetDateTime,
119) -> Result<Code, String> {
120    let read = |name: &str| environment.get(name).cloned().flatten();
121    let program = lang::read(sources.iter().map(Source::file).collect(), &read)
122        .map_err(|(sources, error)| sources.error(error).to_string())?;
123    let verdicts = verdicts(tree, now);
124    let nodes: BTreeMap<_, _> = graph(tree)
125        .nodes
126        .into_iter()
127        .map(|node| (node.name, (node.light, node.tally)))
128        .collect();
129    let mark = |eval: EvalId| Mark {
130        verdict: verdicts.get(&eval).cloned(),
131        eval,
132    };
133    let at = |span: lang::Span| {
134        (
135            program.sources.file(span.file).path.clone(),
136            program.sources.line_column(span).0,
137        )
138    };
139
140    let mut lines: BTreeMap<PathBuf, Vec<Line>> = BTreeMap::new();
141    // Each eval site's evals, one for each Artifact written there.
142    let mut sites: BTreeMap<(PathBuf, usize), (bool, Vec<EvalId>)> = BTreeMap::new();
143    // Where the code binds them, so a macro's evals list its calls in the order written.
144    let mut artifacts: Vec<_> = program.artifacts.iter().collect();
145    artifacts.sort_by_cached_key(|artifact| at(artifact.binding));
146    for artifact in artifacts {
147        let name: ArtifactName = artifact.name.parse()?;
148        let ids = artifact
149            .evals
150            .iter()
151            .map(|eval| format!("{name}/{}", eval.id).parse::<EvalId>())
152            .collect::<Result<Vec<_>, _>>()?;
153        let made = artifact.macro_name.is_some();
154        for (eval, id) in artifact.evals.iter().zip(&ids) {
155            let site = sites.entry(at(eval.id_span)).or_default();
156            site.0 |= made;
157            site.1.push(id.clone());
158        }
159        let (light, tally) = nodes.get(&name).copied().unzip();
160        let (path, number) = at(artifact.binding);
161        lines.entry(path).or_default().push(Line {
162            number,
163            declares: Declares::Artifact {
164                name,
165                light,
166                tally: tally.flatten(),
167                made: if made {
168                    ids.into_iter().map(mark).collect()
169                } else {
170                    Vec::new()
171                },
172            },
173        });
174    }
175    for ((path, number), (made, evals)) in sites {
176        let declares = match <[EvalId; 1]>::try_from(evals) {
177            Ok([eval]) if !made => Declares::Eval(mark(eval)),
178            Ok(evals) => shared(evals.into_iter().map(mark).collect()),
179            Err(evals) => shared(evals.into_iter().map(mark).collect()),
180        };
181        lines
182            .entry(path)
183            .or_default()
184            .push(Line { number, declares });
185    }
186
187    let files: Vec<File> = program
188        .sources
189        .ids()
190        .map(|(_, file)| {
191            let mut lines = lines.remove(&file.path).unwrap_or_default();
192            lines.sort_by_key(|line| line.number);
193            File {
194                path: file.path.clone(),
195                text: file.text.clone(),
196                lines,
197            }
198        })
199        .collect();
200    Ok(explorer(files))
201}
202
203/// A macro's eval line: the first light of its evals and how many are GREEN.
204fn shared(evals: Vec<Mark>) -> Declares {
205    let (light, tally) = lit(&evals);
206    Declares::Shared {
207        light,
208        tally,
209        evals,
210    }
211}
212
213/// The first light of `marks` in the Run and how many are GREEN; none when none is in it.
214fn lit<'a>(marks: impl IntoIterator<Item = &'a Mark>) -> (Option<Light>, Option<Tally>) {
215    let verdicts: Vec<_> = marks
216        .into_iter()
217        .filter_map(|mark| mark.verdict.as_ref())
218        .collect();
219    let light = verdicts.iter().map(|verdict| verdict.light).min();
220    let tally = light.map(|_| Tally {
221        passed: verdicts
222            .iter()
223            .filter(|verdict| verdict.word == Word::Green)
224            .count(),
225        of: verdicts.len(),
226    });
227    (light, tally)
228}
229
230/// Every eval a file shows: its own, those its macro calls expand to, and its macros'.
231fn shown(file: &File) -> impl Iterator<Item = &Mark> {
232    file.lines.iter().flat_map(|line| match &line.declares {
233        Declares::Artifact { made, .. } => made.as_slice(),
234        Declares::Eval(mark) => std::slice::from_ref(mark),
235        Declares::Shared { evals, .. } => evals.as_slice(),
236    })
237}
238
239/// The explorer over `files`: folders before files at each level, each level by name.
240fn explorer(files: Vec<File>) -> Code {
241    #[derive(Default)]
242    struct Folder {
243        folders: BTreeMap<OsString, Folder>,
244        files: BTreeMap<OsString, usize>,
245    }
246    let mut root = Folder::default();
247    for (index, file) in files.iter().enumerate() {
248        let mut folder = &mut root;
249        let mut parts: Vec<_> = file.path.iter().collect();
250        let Some(name) = parts.pop() else { continue };
251        for part in parts {
252            folder = folder.folders.entry(part.to_owned()).or_default();
253        }
254        folder.files.insert(name.to_owned(), index);
255    }
256
257    /// Walk `folder`, adding its rows; returns the evals declared under it.
258    fn walk<'a>(
259        folder: &Folder,
260        at: &Path,
261        depth: usize,
262        files: &'a [File],
263        entries: &mut Vec<Entry>,
264        order: &mut Vec<usize>,
265    ) -> BTreeMap<&'a EvalId, &'a Mark> {
266        let mut under = BTreeMap::new();
267        for (name, inner) in &folder.folders {
268            let path = at.join(name);
269            let row = entries.len();
270            entries.push(Entry {
271                path: path.clone(),
272                depth,
273                folder: true,
274                light: None,
275                tally: None,
276            });
277            let marks = walk(inner, &path, depth + 1, files, entries, order);
278            (entries[row].light, entries[row].tally) = lit(marks.values().copied());
279            under.extend(marks);
280        }
281        for &index in folder.files.values() {
282            let file = &files[index];
283            let marks: BTreeMap<_, _> = shown(file).map(|mark| (&mark.eval, mark)).collect();
284            let (light, tally) = lit(marks.values().copied());
285            entries.push(Entry {
286                path: file.path.clone(),
287                depth,
288                folder: false,
289                light,
290                tally,
291            });
292            order.push(index);
293            under.extend(marks);
294        }
295        under
296    }
297
298    let (mut entries, mut order) = (Vec::new(), Vec::new());
299    walk(&root, Path::new(""), 0, &files, &mut entries, &mut order);
300    let mut files: Vec<Option<File>> = files.into_iter().map(Some).collect();
301    Code {
302        entries,
303        files: order
304            .into_iter()
305            .filter_map(|index| files[index].take())
306            .collect(),
307    }
308}
309
310/// Each eval's verdict in `tree`, as of `now`.
311fn verdicts(tree: &[Node], now: OffsetDateTime) -> BTreeMap<EvalId, Verdict> {
312    tree.iter()
313        .flat_map(|artifact| &artifact.children)
314        .filter_map(|node| {
315            let Kind::Eval(view) = &node.kind else {
316                return None;
317            };
318            let Target::Eval(eval) = Target::from(&node.id) else {
319                return None;
320            };
321            let light = eval_light(node, view);
322            let word = match light {
323                Light::Red => Word::Red,
324                Light::Error => Word::Error,
325                Light::Active if matches!(view, EvalView::InProgress(Activity::Human(_))) => {
326                    Word::Human
327                }
328                Light::Active => Word::Running,
329                Light::Blocked => Word::Blocked,
330                Light::Waiting => Word::Waiting,
331                Light::Green => Word::Green,
332            };
333            let detail = [detail(&node.status()), node.right_at(now, false)]
334                .into_iter()
335                .filter(|part| !part.is_empty())
336                .collect::<Vec<_>>()
337                .join(" · ");
338            Some((
339                eval,
340                Verdict {
341                    light,
342                    word,
343                    detail,
344                },
345            ))
346        })
347        .collect()
348}
349
350/// What a status says after its word: `RED · 2 issues` says `2 issues`, `blocked by core`
351/// says `by core`, and a status that is its word alone says nothing more.
352fn detail(status: &str) -> String {
353    if let Some((_, rest)) = status.split_once(" · ") {
354        return rest.to_owned();
355    }
356    match status.split_once(' ') {
357        None => String::new(),
358        Some(("blocked" | "waits", rest)) => rest.to_owned(),
359        Some(_) => status.to_owned(),
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366    use crate::{store::RunView, test_request::request};
367    use serde_json::json;
368
369    const MACRO: &str = "artf! krate(dir) = {\n  path = \"@{param dir}\"\n\n  eval tests : runtime(command = \"true\", args = []) = {\n    title = \"Tests pass\"\n  }\n}\n";
370    const APP: &str = "artf core = krate!(dir = \"core\")\nartf cli = krate!(dir = \"cli\")\n\nartf docs = {\n  path = \"docs\"\n\n  eval reads : runtime(command = \"true\", args = []) = {\n    title = \"Docs read\"\n  }\n}\n";
371
372    fn source(path: &str, text: &str) -> Source {
373        Source {
374            path: path.into(),
375            plugin: None,
376            text: text.into(),
377        }
378    }
379
380    /// A Run of `core` and `cli` only, `core/tests` GREEN and `cli/tests` RED.
381    fn run() -> (RunView, Vec<crate::store::RequestView>) {
382        let result = |verdict: &str| json!({"result":{"verdict":verdict,"kind":"agent","issues":[{"priority":"P1","reason":"It fails."}]}});
383        let requests = vec![
384            request("core/tests", "GREEN", result("GREEN")),
385            request("cli/tests", "RED", result("RED")),
386        ];
387        let run = serde_json::from_value(json!({
388            "id":"run-1",
389            "repoPath":crate::test_os::temp_root().join("repo"),
390            "stateDir":crate::test_os::temp_root().join("state"),
391            "status":"RED",
392            "createdAt":"2026-01-01T00:00:00Z",
393            "completedAt":"2026-01-01T00:00:01Z",
394            "selection":{"kind":"all"},
395            "definitions":{
396                "artifacts":{"core":{"name":"core","path":"core"},"cli":{"name":"cli","path":"cli"}},
397                "evals":[
398                    {"id":"core/tests","target":"core","deps":[],"declaration":{"title":"Tests pass"}},
399                    {"id":"cli/tests","target":"cli","deps":[],"declaration":{"title":"Tests pass"}}
400                ]
401            },
402            "validation":null,
403            "requests":requests.iter().map(|view| view.request.clone()).collect::<Vec<_>>()
404        }))
405        .unwrap();
406        (run, requests)
407    }
408
409    /// Each line as `number kind light tally evals`, a mark as `eval:word` or `eval:-`.
410    fn shown(file: &File) -> Vec<String> {
411        let marks = |marks: &[Mark]| {
412            marks
413                .iter()
414                .map(|mark| {
415                    let word = mark
416                        .verdict
417                        .as_ref()
418                        .map_or("-".to_owned(), |verdict| format!("{:?}", verdict.word));
419                    format!("{}:{word}", mark.eval)
420                })
421                .collect::<Vec<_>>()
422                .join(",")
423        };
424        let lit = |light: &Option<Light>, tally: &Option<Tally>| {
425            format!(
426                "{} {}",
427                light.map_or("-".to_owned(), |light| format!("{light:?}")),
428                tally.map_or("-".to_owned(), |tally| tally.to_string())
429            )
430        };
431        file.lines
432            .iter()
433            .map(|line| match &line.declares {
434                Declares::Artifact {
435                    name,
436                    light,
437                    tally,
438                    made,
439                } => format!(
440                    "{} artf {name} {} [{}]",
441                    line.number,
442                    lit(light, tally),
443                    marks(made)
444                ),
445                Declares::Eval(mark) => format!(
446                    "{} eval [{}]",
447                    line.number,
448                    marks(std::slice::from_ref(mark))
449                ),
450                Declares::Shared {
451                    light,
452                    tally,
453                    evals,
454                } => format!(
455                    "{} shared {} [{}]",
456                    line.number,
457                    lit(light, tally),
458                    marks(evals)
459                ),
460            })
461            .collect()
462    }
463
464    #[test]
465    fn a_run_s_verdicts_stand_on_the_lines_that_declare_them() {
466        let (run, requests) = run();
467        let now = run.run.created_at.time();
468        let tree = super::super::tree(&run, &requests, now);
469        let sources = [
470            source(".artifactize/rust.artf", MACRO),
471            source(".artifactize/app.artf", APP),
472        ];
473        let code = code(&sources, &BTreeMap::new(), &tree, now).unwrap();
474
475        // The explorer: the folder first, then its files by name, each lit by its evals.
476        let entries: Vec<_> = code
477            .entries
478            .iter()
479            .map(|entry| {
480                format!(
481                    "{} {} {} {:?} {}",
482                    entry.depth,
483                    entry.path.display(),
484                    entry.folder,
485                    entry.light,
486                    entry
487                        .tally
488                        .map_or("-".to_owned(), |tally| tally.to_string())
489                )
490            })
491            .collect();
492        assert_eq!(
493            entries,
494            [
495                "0 .artifactize true Some(Red) 1/2",
496                "1 .artifactize/app.artf false Some(Red) 1/2",
497                "1 .artifactize/rust.artf false Some(Red) 1/2",
498            ]
499        );
500        assert_eq!(code.files[0].path, Path::new(".artifactize/app.artf"));
501        assert_eq!(code.files[0].text, APP);
502        // A call's line lists the evals it expands to; an Artifact the Run left out has no
503        // light, and its eval is not part of the Run.
504        assert_eq!(
505            shown(&code.files[0]),
506            [
507                "1 artf core Green 1/1 [core/tests:Green]",
508                "2 artf cli Red 0/1 [cli/tests:Red]",
509                "4 artf docs - - []",
510                "7 eval [docs/reads:-]",
511            ]
512        );
513        // The macro's eval line stands for every Artifact the macro made.
514        assert_eq!(
515            shown(&code.files[1]),
516            ["4 shared Red 1/2 [core/tests:Green,cli/tests:Red]"]
517        );
518        let Declares::Shared { evals, .. } = &code.files[1].lines[0].declares else {
519            unreachable!()
520        };
521        // The status after its word, then its time, as the Run tree says them.
522        assert_eq!(
523            evals[1].verdict.as_ref().unwrap().detail,
524            "1 issue: P1 It fails. · 1s"
525        );
526    }
527
528    #[test]
529    fn a_status_says_what_follows_its_word() {
530        assert_eq!(detail("RED · 2 issues"), "2 issues");
531        assert_eq!(detail("GREEN · reused"), "reused");
532        assert_eq!(detail("Human sign-off · claimed by ana"), "claimed by ana");
533        assert_eq!(detail("blocked by core"), "by core");
534        assert_eq!(detail("waits for core"), "for core");
535        assert_eq!(detail("GREEN"), "");
536        assert_eq!(
537            detail("not run: blocked by core"),
538            "not run: blocked by core"
539        );
540    }
541}