vivac 0.15.3

Provenance tree for work: every node knows which node it was born from
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
//! `WEB.md` §3.2 -- the lineage, drawn.
//!
//! Its promise (`d144`): you see the shape of the path **at a glance**
//! --how deep, where it branched, what was still open at each step-- where
//! the text hands it to you one node at a time and in order.
//!
//! `d187` decided the form on a measurement, not on taste. A real lineage
//! carries around twenty-two standing decisions and thirty siblings spread
//! over six or seven steps: drawing all of it is fifty rows, which is
//! `why --full` with a stylesheet, and that is precisely what the promise
//! says the text already does. So the counts carry the silhouette and the
//! detail stays one gesture away, in `<details>` -- plain HTML, no build
//! step (§5), nothing off this machine (§7.4), and `curl` still returns the
//! content inside the page.
//!
//! The page picks no nodes of its own: every one of the three things it
//! draws per step comes from the same function `why --full` calls
//! (`WEB.md` §2).

use super::{alias_link, escape};
use crate::event::Event;
use crate::model::{Aggregates, Node, Tree};
use crate::render::{anchor_of, blocking_of, open_then_of, standing_of, Full};

/// One node as a line inside a `<details>`: the alias links to its own
/// lineage, so the drawing is also the way you walk the tree.
fn link(project: &str, tree: &Tree, n: &Node) -> String {
    format!(
        "<li><span class=\"alias\"><a href=\"/p/{p}/why/{a}\">{a}</a></span>\
         <p class=\"title\">{t}</p></li>\n",
        p = escape(project),
        a = escape(&n.alias()),
        t = escape(n.title(tree))
    )
}

/// The lists that hang off a step, and the summary that stands in for them
/// when it is closed.
///
/// A step with nothing to expand gets no `<details>` at all: the absence is
/// the answer --nothing was decided here, nothing was left open here-- and
/// a disclosure triangle that opens onto nothing teaches that the shape
/// cannot be trusted.
///
/// `blocking` is the third of them, added in `f380`: what the step is
/// waiting on, in the words `vivac why` already uses. The whole web
/// mentioned `blocks` in one place, a filter on the front page, so the one
/// edge in this tree that is **not** hierarchy -- the parent cannot close
/// until this one closes -- was drawn nowhere at all, on the page whose
/// whole subject is one node.
///
/// `notes` is the fourth, added in `d390`: every note the node was ever
/// given, oldest first. With two or more, each one carries the date it was
/// written -- `render::why`'s own rule in the terminal -- because with only
/// one, a date says nothing a lone note does not already say by being
/// there.
fn weight(
    project: &str,
    tree: &Tree,
    standing: &[&Node],
    open_then: &[&Node],
    blocking: &[&Node],
    notes: &[(&str, &str)],
) -> String {
    if standing.is_empty() && open_then.is_empty() && blocking.is_empty() && notes.is_empty() {
        return String::new();
    }
    // "waiting on 2" and not "2 waiting on": the other two count things
    // that sit at this step, and this one names what the step is stuck
    // behind. Reading it the same way round as the others would say the
    // opposite of what it means.
    let counts = [
        format!("waiting on {}", blocking.len()),
        format!("{} governing here", standing.len()),
        format!("{} open then", open_then.len()),
        format!(
            "{} note{}",
            notes.len(),
            if notes.len() == 1 { "" } else { "s" }
        ),
    ]
    .iter()
    .zip([blocking.len(), standing.len(), open_then.len(), notes.len()])
    .filter(|(_, n)| *n > 0)
    .map(|(text, _)| format!("<span class=\"count\">{text}</span>"))
    .collect::<Vec<_>>()
    .join(" ");

    let mut body = String::new();
    // First of the three, because it is the only one that says the step
    // cannot finish. The other two describe the moment; this one describes
    // a debt.
    if !blocking.is_empty() {
        body.push_str("<h3>Does not close until these close</h3>\n<ul class=\"nodes\">\n");
        for n in blocking {
            body.push_str(&link(project, tree, n));
        }
        body.push_str("</ul>\n");
    }
    if !standing.is_empty() {
        body.push_str("<h3>Decided here, still standing</h3>\n<ul class=\"nodes\">\n");
        for n in standing {
            body.push_str(&link(project, tree, n));
        }
        body.push_str("</ul>\n");
    }
    if !open_then.is_empty() {
        body.push_str("<h3>Still open at that moment</h3>\n<ul class=\"nodes\">\n");
        for n in open_then {
            body.push_str(&link(project, tree, n));
        }
        body.push_str("</ul>\n");
    }
    if !notes.is_empty() {
        body.push_str("<h3>Notes</h3>\n");
        for (at, text) in notes {
            if notes.len() > 1 {
                body.push_str(&format!(
                    "<p class=\"note\"><span class=\"when\">{}</span> {}</p>\n",
                    escape(crate::clock::date_of(at)),
                    escape(text)
                ));
            } else {
                body.push_str(&format!("<p class=\"note\">{}</p>\n", escape(text)));
            }
        }
    }
    format!(
        "<details><summary>{counts}</summary>\n<div class=\"detail\">\n{body}</div>\n</details>\n"
    )
}

/// The facts that are always visible: what this step is, what state it is
/// in, when it opened, the anchor if there is one, and how much is still
/// open underneath.
///
/// The state is a word before it is anything else. The DX pillar does not
/// allow a meaning that only a colour or a border carries, so `superseded`
/// and `parked` say so in text on a step that is neither of them by shape.
///
/// The anchor is drawn only when there is one (`f186`). Measured against
/// all three real trees on 4-Sep-2026, every stop carries an empty one,
/// because none of the three directories is under version control; a row
/// reading `anchor: --` on every step of every page would say nothing about
/// the path, only about how the directory is set up.
fn facts(tree: &Tree, ag: &Aggregates, n: &Node) -> String {
    let mut parts = vec![
        format!("<span class=\"word\">{}</span>", n.kind.word()),
        format!("<span class=\"word\">{}</span>", n.state.word(n.kind)),
        format!(
            "<span class=\"when\">opened {}</span>",
            escape(n.opened(tree))
        ),
    ];
    let anchor = anchor_of(tree, n);
    if !anchor.is_empty_tree() {
        parts.push(format!(
            "<span class=\"anchor\">{} {}</span>",
            escape(&anchor.kind),
            escape(anchor.short())
        ));
    }
    let open_below = ag.counts(n.num).open_count;
    if open_below > 0 {
        parts.push(format!(
            "<span class=\"count\">{open_below} open below</span>"
        ));
    }
    format!("<p class=\"facts\">{}</p>\n", parts.join(" "))
}

/// One step of the spine.
///
/// Every step but the one you are on links to its own lineage, so the
/// drawing is also how you walk up the path. The step you are on does not:
/// a link back to the page you are reading teaches nothing.
fn step(project: &str, tree: &Tree, ag: &Aggregates, full: &Full, n: &Node, here: bool) -> String {
    let mark = if here {
        "<span class=\"here-mark\">you are here</span>"
    } else {
        ""
    };
    let alias = if here {
        escape(&n.alias())
    } else {
        alias_link(project, &n.alias())
    };
    format!(
        "<li{cls}>\n<span class=\"alias\">{alias}</span>\n<div class=\"what\">\n\
         <p class=\"title\">{title}{mark}</p>\n{facts}{weight}</div>\n</li>\n",
        cls = if here { " class=\"here\"" } else { "" },
        title = escape(n.title(tree)),
        facts = facts(tree, ag, n),
        weight = weight(
            project,
            tree,
            &standing_of(tree, n),
            &open_then_of(tree, full, n),
            &blocking_of(tree, n),
            &n.notes(tree),
        ),
    )
}

/// The lineage of `id`, drawn. `None` when nothing resolves, which the
/// caller turns into a `404`: a page that renders an empty spine for a
/// typo teaches that the node exists.
pub(super) fn why_page(
    project: &str,
    name: &str,
    tree: &Tree,
    log: &[Event],
    id: &str,
) -> Option<String> {
    let target = tree.resolve(id)?;
    let full = Full::from_log(log);
    // Once for the page, not once per step: `aggregates` walks the whole
    // tree, and a seven-step spine would otherwise walk it seven times for
    // an answer that does not change between them.
    let ag = tree.aggregates();
    let path = tree.ancestors(target.num);
    let last = path.len().saturating_sub(1);
    let spine: String = path
        .iter()
        .enumerate()
        .map(|(i, n)| step(project, tree, &ag, &full, n, i == last))
        .collect();

    Some(format!(
        "<!doctype html>\n\
         <html lang=\"en\"><head><meta charset=\"utf-8\">\n\
         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\
         <title>Why {alias} - {name_t}</title>\n\
         <style>\n{css}</style></head>\n\
         <body><div class=\"page\">\n\
         <header><p class=\"crumb\"><a href=\"/p/{p}/\">{name_t}</a></p>\n\
         <h1>Why we are here</h1>\n\
         <p class=\"promise\">The shape of the path at a glance: how deep it goes, \
         where it branched, and what was still open at each step.</p></header>\n\
         <main>\n<ol class=\"spine\">\n{spine}</ol>\n</main>\n\
         <footer>The same reading in a terminal: \
         <code>vivac why {alias} --full</code></footer>\n\
         </div></body></html>\n",
        alias = escape(&target.alias()),
        name_t = escape(name),
        p = escape(project),
        css = super::WEB_CSS,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::{Body, Event, Kind, State};
    use crate::model::fold;

    /// A lineage needs a path to draw, so these build one: a goal, a
    /// decision under it, and a finding under that.
    fn ev(seq: u64, payload: Body) -> Event {
        Event {
            seq,
            id: format!("e{seq}"),
            ts: "2026-09-03T10:00:00Z".to_string(),
            actor: "a".to_string(),
            lane: "main".to_string(),
            payload,
        }
    }

    fn born(seq: u64, num: u64, kind: Kind, title: &str, parent: Option<&str>) -> Event {
        ev(
            seq,
            Body::NodeCreated {
                node: format!("n{num}"),
                num,
                kind,
                title: title.to_string(),
                why: "it is needed".to_string(),
                parent: parent.map(str::to_string),
                blocks: false,
                refs: vec![],
                governs: vec![],
                arms: vec![],
                against: None,
            },
        )
    }

    fn closed(seq: u64, num: u64) -> Event {
        ev(
            seq,
            Body::StateChanged {
                node: format!("n{num}"),
                state: State::Done,
                outcome: String::new(),
                forced: false,
            },
        )
    }

    fn noted(seq: u64, num: u64, note: &str) -> Event {
        ev(
            seq,
            Body::NodeNoted {
                node: format!("n{num}"),
                note: note.to_string(),
            },
        )
    }

    /// goal 1 -> decision 2 -> finding 3, with a sibling of 3 that was
    /// still open when 3 was born and closed afterwards.
    fn lineage() -> Vec<Event> {
        vec![
            born(1, 1, Kind::Goal, "ship it", None),
            born(2, 2, Kind::Decision, "the face is web", Some("n1")),
            born(3, 3, Kind::Task, "the sibling", Some("n2")),
            born(4, 4, Kind::Finding, "the anchor is empty", Some("n2")),
            closed(5, 3),
        ]
    }

    /// The promise of this page is the shape of the path, so the spine is
    /// the path: every node from the root down, and no others.
    #[test]
    fn the_spine_has_one_step_per_node_of_the_path() {
        let events = lineage();
        let tree = fold(&events, 0);
        let page = why_page("vivac", "vivac", &tree, &events, "f4").unwrap();
        // Counted on the one element a step always has and a listed node
        // never does. Counting `<li>` would count the nodes inside an open
        // `<details>` too.
        assert_eq!(
            page.matches("class=\"facts\"").count(),
            3,
            "one step per node of g1 > d2 > f4"
        );
        assert!(page.contains("ship it"));
        assert!(page.contains("the face is web"));
        assert!(page.contains("the anchor is empty"));
    }

    #[test]
    fn the_last_step_is_the_node_that_was_asked_for() {
        let events = lineage();
        let tree = fold(&events, 0);
        let page = why_page("vivac", "vivac", &tree, &events, "f4").unwrap();
        let here = page.find("you are here").expect("the step is marked");
        let target = page
            .find("the anchor is empty")
            .expect("the target is drawn");
        let middle = page
            .find("the face is web")
            .expect("the middle step is drawn");
        assert!(middle < target, "the spine runs from the root down");
        assert!(target < here, "the mark sits on the step it belongs to");
    }

    /// The DX pillar: a meaning is never carried by a colour or a class
    /// alone. Strip every attribute and the page still says where you are.
    #[test]
    fn the_step_you_are_on_is_marked_by_a_word_and_not_only_by_a_class() {
        let events = lineage();
        let tree = fold(&events, 0);
        let page = why_page("vivac", "vivac", &tree, &events, "f4").unwrap();
        assert!(page.contains("you are here"));
        assert!(page.contains("class=\"here\""));
    }

    /// The same rule the whole surface rests on: a title is prose somebody
    /// wrote, and a tree is allowed to hold a node called `<script>`.
    #[test]
    fn a_title_that_looks_like_markup_reaches_the_lineage_escaped() {
        let events = vec![born(1, 1, Kind::Goal, "<script>alert(1)</script>", None)];
        let tree = fold(&events, 0);
        let page = why_page("vivac", "vivac", &tree, &events, "g1").unwrap();
        assert!(!page.contains("<script>alert(1)</script>"));
        assert!(page.contains("&lt;script&gt;"));
    }

    /// `f186`: every stop in all three real trees carries an empty anchor,
    /// because none of the three directories is under version control. A
    /// row saying so on every step of every page describes the directory,
    /// not the path.
    #[test]
    fn a_step_with_no_anchor_draws_no_anchor_row() {
        let events = lineage();
        let tree = fold(&events, 0);
        let page = why_page("vivac", "vivac", &tree, &events, "f4").unwrap();
        assert!(!page.contains("class=\"anchor\""));
    }

    /// `d187`: a disclosure that opens onto nothing teaches that the shape
    /// cannot be trusted, so a step with nothing to expand has none.
    #[test]
    fn a_step_with_nothing_to_expand_has_no_disclosure() {
        let events = vec![born(1, 1, Kind::Goal, "ship it", None)];
        let tree = fold(&events, 0);
        let page = why_page("vivac", "vivac", &tree, &events, "g1").unwrap();
        assert!(!page.contains("<details>"));
    }

    /// `d173` renounced the list of what closed below and kept the counts.
    /// The page keeps that bargain: a number, never the nodes.
    ///
    /// The node buried here is under the target, so it is none of the three
    /// things a step does draw -- not a standing decision born on the path,
    /// not a sibling that was open at the time. If it reaches the page at
    /// all, the renounced list came back in.
    #[test]
    fn what_closed_below_a_step_is_a_count_and_never_a_list() {
        let mut events = lineage();
        events.push(born(6, 5, Kind::Task, "the buried one", Some("n4")));
        events.push(closed(7, 5));
        let tree = fold(&events, 0);
        let page = why_page("vivac", "vivac", &tree, &events, "f4").unwrap();
        assert!(page.contains("open below"), "the counts are drawn");
        assert!(
            !page.contains("the buried one"),
            "what closed below is counted, not listed"
        );
    }

    /// `d147` kept the tree only as the way you reach a lineage, so the
    /// lineage has to be a way of walking too: every step above you links
    /// to its own. The step you are on does not -- a link back to the page
    /// you are reading teaches nothing.
    #[test]
    fn every_step_but_the_one_you_are_on_links_to_its_own_lineage() {
        let events = lineage();
        let tree = fold(&events, 0);
        let page = why_page("vivac", "vivac", &tree, &events, "f4").unwrap();
        assert!(page.contains("href=\"/p/vivac/why/g1\""), "{page}");
        assert!(page.contains("href=\"/p/vivac/why/d2\""), "{page}");
        assert!(!page.contains("href=\"/p/vivac/why/f4\""), "{page}");
    }

    /// A typo must not render an empty spine: that would teach that the
    /// node exists.
    #[test]
    fn an_alias_that_resolves_to_nothing_gives_no_page() {
        let events = lineage();
        let tree = fold(&events, 0);
        assert!(why_page("vivac", "vivac", &tree, &events, "f999").is_none());
    }

    /// `WEB.md` §7.4: the page loads with no internet and makes not one
    /// request off `127.0.0.1`.
    #[test]
    fn the_lineage_asks_for_nothing_off_this_machine() {
        let events = lineage();
        let tree = fold(&events, 0);
        let page = why_page("vivac", "vivac", &tree, &events, "f4").unwrap();
        assert!(!page.contains("http://"));
        assert!(!page.contains("https://"));
        assert!(!page.contains("//cdn"));
    }

    /// `d390`: the disclosure a step already has gains the notes. With two or
    /// more, each carries the date it was written, the same rule
    /// `render::why` follows in the terminal.
    #[test]
    fn a_step_with_two_notes_lists_both_with_their_own_date() {
        let mut events = lineage();
        events.push(noted(6, 4, "first note"));
        events.push(noted(7, 4, "second note"));
        let tree = fold(&events, 0);
        let page = why_page("vivac", "vivac", &tree, &events, "f4").unwrap();
        assert!(
            page.contains("<span class=\"when\">2026-09-03</span> first note"),
            "the first note should carry its own date:\n{page}"
        );
        assert!(
            page.contains("<span class=\"when\">2026-09-03</span> second note"),
            "the second note should carry its own date:\n{page}"
        );
    }

    /// The regression the date above can introduce: a step with exactly one
    /// note carries no date, the same argument `f186` made for the lineage's
    /// anchor.
    #[test]
    fn a_step_with_one_note_carries_no_date() {
        let mut events = lineage();
        events.push(noted(6, 4, "the only note"));
        let tree = fold(&events, 0);
        let page = why_page("vivac", "vivac", &tree, &events, "f4").unwrap();
        assert!(
            page.contains("<p class=\"note\">the only note</p>"),
            "{page}"
        );
        assert!(
            !page.contains("<span class=\"when\">2026-09-03</span> the only note"),
            "a single note must not carry a date:\n{page}"
        );
    }
}