artifactize-core 0.31.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! A Run on its code: the definition files the Run read, each `artf` and `eval` line with the
//! Run's verdict where it is declared, and the explorer's folders and files, each with the
//! first light of the evals declared in it or under it. Pure: it reads the files the Run saved
//! (`store::read_run_sources`), the environment they were read with, and the Run's tree.
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},
};

/// The Run's code: the explorer's rows and the files they show.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Code {
    /// Folders before files at each level, each level by name; a folder's rows follow it.
    pub entries: Vec<Entry>,
    /// Every file, in the order the explorer lists them.
    pub files: Vec<File>,
}

/// A row of the explorer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    pub path: PathBuf,
    /// How many folders hold it.
    pub depth: usize,
    pub folder: bool,
    /// The first light of the Run's evals declared in it or under it, and how many of them are
    /// GREEN; none when it declares no eval of the Run.
    pub light: Option<Light>,
    pub tally: Option<Tally>,
}

/// A definition file as the Run read it, with the lines that declare something.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct File {
    pub path: PathBuf,
    pub text: String,
    /// By line number, from 1.
    pub lines: Vec<Line>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Line {
    /// From 1, as in the file.
    pub number: usize,
    pub declares: Declares,
}

/// What a line declares, with the Run's verdict on it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Declares {
    /// An `artf` binding: its node's light and tally; a macro call's line also lists the evals
    /// the call expands to, which are written in the macro.
    Artifact {
        name: ArtifactName,
        light: Option<Light>,
        tally: Option<Tally>,
        made: Vec<Mark>,
    },
    /// An `eval` written for one Artifact.
    Eval(Mark),
    /// An `eval` written in a macro: one eval for each Artifact the macro made.
    Shared {
        light: Option<Light>,
        tally: Option<Tally>,
        evals: Vec<Mark>,
    },
}

/// An eval and its verdict in the Run; none when the Run did not select it.
#[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,
    /// What the eval's status says after its word, then its time, such as `exit 101` or
    /// `reused`; empty when the word says it all.
    pub detail: String,
}

/// The word a verdict is read by.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Word {
    Green,
    Red,
    Error,
    Running,
    /// Waiting for a person: a Human review.
    Human,
    Waiting,
    Blocked,
}

/// The Run's code: `sources` read again with `environment`, lit by `tree` as of `now`.
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();
    // Each eval site's evals, one for each Artifact written there.
    let mut sites: BTreeMap<(PathBuf, usize), (bool, Vec<EvalId>)> = BTreeMap::new();
    // Where the code binds them, so a macro's evals list its calls in the order written.
    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))
}

/// A macro's eval line: the first light of its evals and how many are GREEN.
fn shared(evals: Vec<Mark>) -> Declares {
    let (light, tally) = lit(&evals);
    Declares::Shared {
        light,
        tally,
        evals,
    }
}

/// The first light of `marks` in the Run and how many are GREEN; none when none is in it.
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)
}

/// Every eval a file shows: its own, those its macro calls expand to, and its macros'.
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(),
    })
}

/// The explorer over `files`: folders before files at each level, each level by name.
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);
    }

    /// Walk `folder`, adding its rows; returns the evals declared under it.
    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(),
    }
}

/// Each eval's verdict in `tree`, as of `now`.
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()
}

/// What a status says after its word: `RED · 2 issues` says `2 issues`, `blocked by core`
/// says `by core`, and a status that is its word alone says nothing more.
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(),
        }
    }

    /// A Run of `core` and `cli` only, `core/tests` GREEN and `cli/tests` RED.
    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)
    }

    /// Each line as `number kind light tally evals`, a mark as `eval:word` or `eval:-`.
    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();

        // The explorer: the folder first, then its files by name, each lit by its evals.
        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);
        // A call's line lists the evals it expands to; an Artifact the Run left out has no
        // light, and its eval is not part of the Run.
        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:-]",
            ]
        );
        // The macro's eval line stands for every Artifact the macro made.
        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!()
        };
        // The status after its word, then its time, as the Run tree says them.
        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"
        );
    }
}