use std::{
collections::BTreeMap,
ffi::OsString,
path::{Path, PathBuf},
};
use time::OffsetDateTime;
use super::{
Target,
graph::{Light, eval_light, graph},
states::{Activity, EvalView},
tree::{Kind, Node, Tally},
};
use crate::{
config::lang,
store::definitions::Source,
types::{ArtifactName, EvalId},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Code {
pub entries: Vec<Entry>,
pub files: Vec<File>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
pub path: PathBuf,
pub depth: usize,
pub folder: bool,
pub light: Option<Light>,
pub tally: Option<Tally>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct File {
pub path: PathBuf,
pub text: String,
pub lines: Vec<Line>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Line {
pub number: usize,
pub declares: Declares,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Declares {
Artifact {
name: ArtifactName,
light: Option<Light>,
tally: Option<Tally>,
made: Vec<Mark>,
},
Eval(Mark),
Shared {
light: Option<Light>,
tally: Option<Tally>,
evals: Vec<Mark>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mark {
pub eval: EvalId,
pub verdict: Option<Verdict>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Verdict {
pub light: Light,
pub word: Word,
pub detail: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Word {
Green,
Red,
Error,
Running,
Human,
Waiting,
Blocked,
}
pub fn code(
sources: &[Source],
environment: &BTreeMap<String, Option<String>>,
tree: &[Node],
now: OffsetDateTime,
) -> Result<Code, String> {
let read = |name: &str| environment.get(name).cloned().flatten();
let program = lang::read(sources.iter().map(Source::file).collect(), &read)
.map_err(|(sources, error)| sources.error(error).to_string())?;
let verdicts = verdicts(tree, now);
let nodes: BTreeMap<_, _> = graph(tree)
.nodes
.into_iter()
.map(|node| (node.name, (node.light, node.tally)))
.collect();
let mark = |eval: EvalId| Mark {
verdict: verdicts.get(&eval).cloned(),
eval,
};
let at = |span: lang::Span| {
(
program.sources.file(span.file).path.clone(),
program.sources.line_column(span).0,
)
};
let mut lines: BTreeMap<PathBuf, Vec<Line>> = BTreeMap::new();
let mut sites: BTreeMap<(PathBuf, usize), (bool, Vec<EvalId>)> = BTreeMap::new();
let mut artifacts: Vec<_> = program.artifacts.iter().collect();
artifacts.sort_by_cached_key(|artifact| at(artifact.binding));
for artifact in artifacts {
let name: ArtifactName = artifact.name.parse()?;
let ids = artifact
.evals
.iter()
.map(|eval| format!("{name}/{}", eval.id).parse::<EvalId>())
.collect::<Result<Vec<_>, _>>()?;
let made = artifact.macro_name.is_some();
for (eval, id) in artifact.evals.iter().zip(&ids) {
let site = sites.entry(at(eval.id_span)).or_default();
site.0 |= made;
site.1.push(id.clone());
}
let (light, tally) = nodes.get(&name).copied().unzip();
let (path, number) = at(artifact.binding);
lines.entry(path).or_default().push(Line {
number,
declares: Declares::Artifact {
name,
light,
tally: tally.flatten(),
made: if made {
ids.into_iter().map(mark).collect()
} else {
Vec::new()
},
},
});
}
for ((path, number), (made, evals)) in sites {
let declares = match <[EvalId; 1]>::try_from(evals) {
Ok([eval]) if !made => Declares::Eval(mark(eval)),
Ok(evals) => shared(evals.into_iter().map(mark).collect()),
Err(evals) => shared(evals.into_iter().map(mark).collect()),
};
lines
.entry(path)
.or_default()
.push(Line { number, declares });
}
let files: Vec<File> = program
.sources
.ids()
.map(|(_, file)| {
let mut lines = lines.remove(&file.path).unwrap_or_default();
lines.sort_by_key(|line| line.number);
File {
path: file.path.clone(),
text: file.text.clone(),
lines,
}
})
.collect();
Ok(explorer(files))
}
fn shared(evals: Vec<Mark>) -> Declares {
let (light, tally) = lit(&evals);
Declares::Shared {
light,
tally,
evals,
}
}
fn lit<'a>(marks: impl IntoIterator<Item = &'a Mark>) -> (Option<Light>, Option<Tally>) {
let verdicts: Vec<_> = marks
.into_iter()
.filter_map(|mark| mark.verdict.as_ref())
.collect();
let light = verdicts.iter().map(|verdict| verdict.light).min();
let tally = light.map(|_| Tally {
passed: verdicts
.iter()
.filter(|verdict| verdict.word == Word::Green)
.count(),
of: verdicts.len(),
});
(light, tally)
}
fn shown(file: &File) -> impl Iterator<Item = &Mark> {
file.lines.iter().flat_map(|line| match &line.declares {
Declares::Artifact { made, .. } => made.as_slice(),
Declares::Eval(mark) => std::slice::from_ref(mark),
Declares::Shared { evals, .. } => evals.as_slice(),
})
}
fn explorer(files: Vec<File>) -> Code {
#[derive(Default)]
struct Folder {
folders: BTreeMap<OsString, Folder>,
files: BTreeMap<OsString, usize>,
}
let mut root = Folder::default();
for (index, file) in files.iter().enumerate() {
let mut folder = &mut root;
let mut parts: Vec<_> = file.path.iter().collect();
let Some(name) = parts.pop() else { continue };
for part in parts {
folder = folder.folders.entry(part.to_owned()).or_default();
}
folder.files.insert(name.to_owned(), index);
}
fn walk<'a>(
folder: &Folder,
at: &Path,
depth: usize,
files: &'a [File],
entries: &mut Vec<Entry>,
order: &mut Vec<usize>,
) -> BTreeMap<&'a EvalId, &'a Mark> {
let mut under = BTreeMap::new();
for (name, inner) in &folder.folders {
let path = at.join(name);
let row = entries.len();
entries.push(Entry {
path: path.clone(),
depth,
folder: true,
light: None,
tally: None,
});
let marks = walk(inner, &path, depth + 1, files, entries, order);
(entries[row].light, entries[row].tally) = lit(marks.values().copied());
under.extend(marks);
}
for &index in folder.files.values() {
let file = &files[index];
let marks: BTreeMap<_, _> = shown(file).map(|mark| (&mark.eval, mark)).collect();
let (light, tally) = lit(marks.values().copied());
entries.push(Entry {
path: file.path.clone(),
depth,
folder: false,
light,
tally,
});
order.push(index);
under.extend(marks);
}
under
}
let (mut entries, mut order) = (Vec::new(), Vec::new());
walk(&root, Path::new(""), 0, &files, &mut entries, &mut order);
let mut files: Vec<Option<File>> = files.into_iter().map(Some).collect();
Code {
entries,
files: order
.into_iter()
.filter_map(|index| files[index].take())
.collect(),
}
}
fn verdicts(tree: &[Node], now: OffsetDateTime) -> BTreeMap<EvalId, Verdict> {
tree.iter()
.flat_map(|artifact| &artifact.children)
.filter_map(|node| {
let Kind::Eval(view) = &node.kind else {
return None;
};
let Target::Eval(eval) = Target::from(&node.id) else {
return None;
};
let light = eval_light(node, view);
let word = match light {
Light::Red => Word::Red,
Light::Error => Word::Error,
Light::Active if matches!(view, EvalView::InProgress(Activity::Human(_))) => {
Word::Human
}
Light::Active => Word::Running,
Light::Blocked => Word::Blocked,
Light::Waiting => Word::Waiting,
Light::Green => Word::Green,
};
let detail = [detail(&node.status()), node.right_at(now, false)]
.into_iter()
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" · ");
Some((
eval,
Verdict {
light,
word,
detail,
},
))
})
.collect()
}
fn detail(status: &str) -> String {
if let Some((_, rest)) = status.split_once(" · ") {
return rest.to_owned();
}
match status.split_once(' ') {
None => String::new(),
Some(("blocked" | "waits", rest)) => rest.to_owned(),
Some(_) => status.to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{store::RunView, test_request::request};
use serde_json::json;
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";
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";
fn source(path: &str, text: &str) -> Source {
Source {
path: path.into(),
plugin: None,
text: text.into(),
}
}
fn run() -> (RunView, Vec<crate::store::RequestView>) {
let result = |verdict: &str| json!({"result":{"verdict":verdict,"kind":"agent","issues":[{"priority":"P1","reason":"It fails."}]}});
let requests = vec![
request("core/tests", "GREEN", result("GREEN")),
request("cli/tests", "RED", result("RED")),
];
let run = serde_json::from_value(json!({
"id":"run-1",
"repoPath":crate::test_os::temp_root().join("repo"),
"stateDir":crate::test_os::temp_root().join("state"),
"status":"RED",
"createdAt":"2026-01-01T00:00:00Z",
"completedAt":"2026-01-01T00:00:01Z",
"selection":{"kind":"all"},
"definitions":{
"artifacts":{"core":{"name":"core","path":"core"},"cli":{"name":"cli","path":"cli"}},
"evals":[
{"id":"core/tests","target":"core","deps":[],"declaration":{"title":"Tests pass"}},
{"id":"cli/tests","target":"cli","deps":[],"declaration":{"title":"Tests pass"}}
]
},
"validation":null,
"requests":requests.iter().map(|view| view.request.clone()).collect::<Vec<_>>()
}))
.unwrap();
(run, requests)
}
fn shown(file: &File) -> Vec<String> {
let marks = |marks: &[Mark]| {
marks
.iter()
.map(|mark| {
let word = mark
.verdict
.as_ref()
.map_or("-".to_owned(), |verdict| format!("{:?}", verdict.word));
format!("{}:{word}", mark.eval)
})
.collect::<Vec<_>>()
.join(",")
};
let lit = |light: &Option<Light>, tally: &Option<Tally>| {
format!(
"{} {}",
light.map_or("-".to_owned(), |light| format!("{light:?}")),
tally.map_or("-".to_owned(), |tally| tally.to_string())
)
};
file.lines
.iter()
.map(|line| match &line.declares {
Declares::Artifact {
name,
light,
tally,
made,
} => format!(
"{} artf {name} {} [{}]",
line.number,
lit(light, tally),
marks(made)
),
Declares::Eval(mark) => format!(
"{} eval [{}]",
line.number,
marks(std::slice::from_ref(mark))
),
Declares::Shared {
light,
tally,
evals,
} => format!(
"{} shared {} [{}]",
line.number,
lit(light, tally),
marks(evals)
),
})
.collect()
}
#[test]
fn a_run_s_verdicts_stand_on_the_lines_that_declare_them() {
let (run, requests) = run();
let now = run.run.created_at.time();
let tree = super::super::tree(&run, &requests, now);
let sources = [
source(".artifactize/rust.artf", MACRO),
source(".artifactize/app.artf", APP),
];
let code = code(&sources, &BTreeMap::new(), &tree, now).unwrap();
let entries: Vec<_> = code
.entries
.iter()
.map(|entry| {
format!(
"{} {} {} {:?} {}",
entry.depth,
entry.path.display(),
entry.folder,
entry.light,
entry
.tally
.map_or("-".to_owned(), |tally| tally.to_string())
)
})
.collect();
assert_eq!(
entries,
[
"0 .artifactize true Some(Red) 1/2",
"1 .artifactize/app.artf false Some(Red) 1/2",
"1 .artifactize/rust.artf false Some(Red) 1/2",
]
);
assert_eq!(code.files[0].path, Path::new(".artifactize/app.artf"));
assert_eq!(code.files[0].text, APP);
assert_eq!(
shown(&code.files[0]),
[
"1 artf core Green 1/1 [core/tests:Green]",
"2 artf cli Red 0/1 [cli/tests:Red]",
"4 artf docs - - []",
"7 eval [docs/reads:-]",
]
);
assert_eq!(
shown(&code.files[1]),
["4 shared Red 1/2 [core/tests:Green,cli/tests:Red]"]
);
let Declares::Shared { evals, .. } = &code.files[1].lines[0].declares else {
unreachable!()
};
assert_eq!(
evals[1].verdict.as_ref().unwrap().detail,
"1 issue: P1 It fails. · 1s"
);
}
#[test]
fn a_status_says_what_follows_its_word() {
assert_eq!(detail("RED · 2 issues"), "2 issues");
assert_eq!(detail("GREEN · reused"), "reused");
assert_eq!(detail("Human sign-off · claimed by ana"), "claimed by ana");
assert_eq!(detail("blocked by core"), "by core");
assert_eq!(detail("waits for core"), "for core");
assert_eq!(detail("GREEN"), "");
assert_eq!(
detail("not run: blocked by core"),
"not run: blocked by core"
);
}
}