vivac 0.12.0

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
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! `changes` — what a stretch of work moved: opened, closed, flagged, moved.
//!
//! `t148`: the log already has every event and no read hands them back
//! grouped by what happened, so answering "what did this stretch move" meant
//! opening `events` by hand. The boundary is a stop and never a raw
//! timestamp, because a timestamp ties within the same second and a stop's
//! `seq` does not.
//!
//! `t155`: the log's last stop is not the boundary anybody wants. The `Stop`
//! hook writes one on every turn that moves the tree -- 23 in a single day on
//! this project's own tree, 19 of them automatic -- so "since the last stop"
//! answers "since my last action" where the question was "since the last time
//! I looked". `--since manual` measures from the last stop somebody sat down
//! and made, which is the only one of the five kinds a person chooses to
//! write.

use crate::args::Args;
use crate::event::{Body, Event, Flag, State};
use crate::failure::Failure;
use crate::model::{Node, Tree, Vivac};
use crate::output::outln;
use crate::render::{print_json, wrap, WIDTH};
use serde_json::json;

/// Where a stretch is measured from, and how that place was chosen. Both live
/// in one type because the sentence the header prints depends on the two: the
/// same stop reads differently when it is merely the log's most recent one and
/// when it is the last one somebody sat down and made.
pub enum Boundary<'a> {
    Stop {
        vivac: &'a Vivac,
        /// Picked by `--since manual`, rather than being the log's last stop
        /// or one named outright.
        manual: bool,
    },
    /// The whole log. `asked_for_manual` tells the two ways of arriving here
    /// apart: a log with no stops at all, and `--since manual` on a log where
    /// every stop was written by the hook. Same stretch, different sentence.
    Beginning { asked_for_manual: bool },
}

pub struct Changed<'a> {
    /// The boundary the stretch is measured from.
    pub since: Boundary<'a>,
    pub opened: Vec<Opened<'a>>,
    pub closed: Vec<Closed<'a>>,
    pub flagged: Vec<Flagged<'a>>,
    pub moved: Vec<Moved<'a>>,
    pub tail: Tail,
}

/// A node born in this stretch, and the lane whose event bore it: `changes`
/// stays the whole tree's own reading, and `lane` is what lets a line from
/// another lane carry its name (`t594` §4.3).
pub struct Opened<'a> {
    pub node: &'a Node,
    pub lane: String,
}

pub struct Closed<'a> {
    pub node: &'a Node,
    pub outcome: String,
    pub forced: bool,
    pub lane: String,
}

pub struct Flagged<'a> {
    pub node: &'a Node,
    pub flag: Flag,
    pub reason: String,
    pub lane: String,
}

pub struct Moved<'a> {
    pub node: &'a Node,
    /// The word this state goes by for this kind: `State::word` already
    /// knows it, and a second spelling here would drift from the first.
    pub state: State,
    pub lane: String,
}

/// What moved the tree without naming a node movement. It is counted and
/// never dropped: a stretch that only moved the focus must not read as a
/// stretch where nothing happened.
#[derive(Default)]
pub struct Tail {
    pub focus_moves: usize,
    pub notes: usize,
    pub flags_cleared: usize,
    pub edges: usize,
    /// A rule armed or disarmed: `arm.added` or `arm.removed`.
    pub arms: usize,
    /// A `declare` call: one `against.added`, however many declarations it
    /// carried. `t426` §3.3.
    pub declarations: usize,
    /// Stops inside the stretch. Not printed in the tail: it goes in the
    /// header, where it says how far back the boundary is, which is the one
    /// place the number means something.
    pub stops: usize,
    /// Events naming a node this log cannot read. `vivac check` is the
    /// surface that explains why; dropping them without a count would be
    /// omitting in silence.
    pub unreadable: usize,
}

/// Everything in the log after `since_seq`, grouped by what happened.
///
/// Ordered by the log within each group, not by node number: a stretch reads
/// as a story, not as a lookup, and the log already comes in the order it
/// was written.
pub fn collect<'a>(tree: &'a Tree, log: &[Event], since_seq: u64) -> Changed<'a> {
    let mut result = Changed {
        since: Boundary::Beginning {
            asked_for_manual: false,
        },
        opened: Vec::new(),
        closed: Vec::new(),
        flagged: Vec::new(),
        moved: Vec::new(),
        tail: Tail::default(),
    };

    for e in log {
        if e.seq <= since_seq {
            continue;
        }
        match &e.payload {
            // Opening a session says something about the session and
            // nothing about the tree; `Tree::apply` already treats it that
            // way.
            Body::SessionStarted { .. } => {}
            Body::NodeCreated { node, .. } => match tree.node(node) {
                Some(n) => result.opened.push(Opened {
                    node: n,
                    lane: e.lane.clone(),
                }),
                None => result.tail.unreadable += 1,
            },
            Body::StateChanged {
                node,
                state,
                outcome,
                forced,
            } => match tree.node(node) {
                Some(n) if *state == State::Done => result.closed.push(Closed {
                    node: n,
                    outcome: outcome.clone(),
                    forced: *forced,
                    lane: e.lane.clone(),
                }),
                Some(n) => result.moved.push(Moved {
                    node: n,
                    state: *state,
                    lane: e.lane.clone(),
                }),
                None => result.tail.unreadable += 1,
            },
            Body::FlagRaised { node, flag, reason } => match tree.node(node) {
                Some(n) => result.flagged.push(Flagged {
                    node: n,
                    flag: *flag,
                    reason: reason.clone(),
                    lane: e.lane.clone(),
                }),
                None => result.tail.unreadable += 1,
            },
            Body::FlagCleared { node, .. } => match tree.node(node) {
                Some(_) => result.tail.flags_cleared += 1,
                None => result.tail.unreadable += 1,
            },
            Body::NodeNoted { node, .. } => match tree.node(node) {
                Some(_) => result.tail.notes += 1,
                None => result.tail.unreadable += 1,
            },
            Body::BlockChanged { node, .. } => match tree.node(node) {
                Some(_) => result.tail.edges += 1,
                None => result.tail.unreadable += 1,
            },
            Body::Pushed { node } | Body::Popped { node } | Body::Promoted { node } => {
                match tree.node(node) {
                    Some(_) => result.tail.focus_moves += 1,
                    None => result.tail.unreadable += 1,
                }
            }
            Body::ArmAdded { node, .. } | Body::ArmRemoved { node, .. } => match tree.node(node) {
                Some(_) => result.tail.arms += 1,
                None => result.tail.unreadable += 1,
            },
            Body::AgainstAdded { node, .. } => match tree.node(node) {
                Some(_) => result.tail.declarations += 1,
                None => result.tail.unreadable += 1,
            },
            // Not naming a node: nothing to check against the tree.
            Body::VivacCreated { .. } => result.tail.stops += 1,
            // Neither names a node, and `Tree::apply` already keeps either
            // one from counting as work: joining or being claimed is not a
            // change, so there is nothing here for it to add. `where.changed`
            // is the same family: it says where the work happens, not that
            // it happened (§4.3).
            Body::LaneDeclared { .. } | Body::LaneClaimed { .. } | Body::WhereChanged { .. } => {}
        }
    }

    result
}

impl Boundary<'_> {
    /// The seq a stretch starts after. Exclusive: the stop itself belongs to
    /// the stretch before it.
    pub(crate) fn seq(&self) -> u64 {
        match self {
            Boundary::Stop { vivac, .. } => vivac.seq,
            Boundary::Beginning { .. } => 0,
        }
    }
}

/// The boundary `--since manual` measures from: the last stop somebody sat
/// down and made, or the whole log if there has never been one.
///
/// Its own function so a caller that is not the CLI -- `t160`'s Today page,
/// which owes its "what changed" block this same limit -- asks the tree for
/// it directly instead of re-deriving it, and the two can never disagree.
pub(crate) fn manual_boundary(tree: &Tree) -> Boundary<'_> {
    match tree.last_manual_vivac() {
        Some(v) => Boundary::Stop {
            vivac: v,
            manual: true,
        },
        None => Boundary::Beginning {
            asked_for_manual: true,
        },
    }
}

/// `changes` — what a stretch of work moved, printed with `triage`'s style.
///
/// Always exits `0` when the command itself was well formed: this is a
/// reading, not a check, and an empty stretch is answered with a sentence
/// rather than a non-zero code.
pub fn changes(tree: &Tree, log: &[Event], args: &Args) -> Result<i32, Failure> {
    let boundary = match args.opt("since") {
        Some("manual") => manual_boundary(tree),
        Some(s) => Boundary::Stop {
            vivac: tree.vivac(s).ok_or_else(|| {
                Failure::usage(format!(
                    "No such vivac: {s}. Give a stop's alias, or `manual` for the last stop you made."
                ))
            })?,
            manual: false,
        },
        None => match tree.last_vivac() {
            Some(v) => Boundary::Stop {
                vivac: v,
                manual: false,
            },
            None => Boundary::Beginning {
                asked_for_manual: false,
            },
        },
    };
    let mut result = collect(tree, log, boundary.seq());
    result.since = boundary;

    if args.has("json") {
        return print_json(as_json(tree, &result)).map(|_| 0);
    }
    print_text(tree, &result);
    Ok(0)
}

/// A trailing "s" where the count calls for one, and none where it does not.
fn plural(n: usize) -> &'static str {
    if n == 1 {
        ""
    } else {
        "s"
    }
}

/// `CHANGES SINCE ...`, in one of six forms and never a seventh: the log's
/// last stop, an older one with how many stops lie between it and now, the
/// last stop somebody made with how many the hook wrote after it, or the
/// beginning of the log, which itself splits in two depending on whether a
/// stop made by hand was asked for and not found. It carries no clock time on
/// purpose: `now_rfc3339` writes in UTC, and a bare hour would read as local
/// to whoever is looking at it.
fn header(since: &Boundary, stops_since: usize) -> String {
    match since {
        Boundary::Beginning {
            asked_for_manual: false,
        } => "  CHANGES SINCE THE BEGINNING - no stops yet".to_string(),
        Boundary::Beginning {
            asked_for_manual: true,
        } => "  CHANGES SINCE THE BEGINNING - no stop here was made by hand".to_string(),
        Boundary::Stop { vivac, manual } => {
            let date = crate::clock::date_of(&vivac.ts);
            match (manual, stops_since) {
                (false, 0) => format!("  CHANGES SINCE {}, the last stop - {date}", vivac.alias()),
                (false, n) => format!(
                    "  CHANGES SINCE {} - {date}, {n} stop{} ago",
                    vivac.alias(),
                    plural(n)
                ),
                (true, 0) => format!(
                    "  CHANGES SINCE {}, the last stop you made - {date}",
                    vivac.alias()
                ),
                (true, n) => format!(
                    "  CHANGES SINCE {}, the last stop you made - {date}, {n} stop{} since",
                    vivac.alias(),
                    plural(n)
                ),
            }
        }
    }
}

/// The tail line, naming only what is not zero, in a fixed order. `stops`
/// never appears here: it already spoke in the header.
pub(crate) fn tail_phrase(tail: &Tail) -> Option<String> {
    let mut parts = Vec::new();
    if tail.focus_moves > 0 {
        parts.push(format!(
            "{} focus move{}",
            tail.focus_moves,
            plural(tail.focus_moves)
        ));
    }
    if tail.notes > 0 {
        parts.push(format!("{} note{}", tail.notes, plural(tail.notes)));
    }
    if tail.flags_cleared > 0 {
        parts.push(format!(
            "{} flag{} cleared",
            tail.flags_cleared,
            plural(tail.flags_cleared)
        ));
    }
    if tail.edges > 0 {
        parts.push(format!("{} edge change{}", tail.edges, plural(tail.edges)));
    }
    if tail.arms > 0 {
        parts.push(format!("{} arm change{}", tail.arms, plural(tail.arms)));
    }
    if tail.declarations > 0 {
        parts.push(format!(
            "{} late declaration{}",
            tail.declarations,
            plural(tail.declarations)
        ));
    }
    if tail.unreadable > 0 {
        parts.push(format!(
            "{} unreadable event{}",
            tail.unreadable,
            plural(tail.unreadable)
        ));
    }
    (!parts.is_empty()).then(|| parts.join(", "))
}

/// The name to show for `lane`: its own declared name when it has one, and
/// the bare lane otherwise -- the same rule `Tree::lane_name` uses for the
/// lane a tree is looked at from, applied here to a lane that only ever
/// wrote one line of this stretch.
fn lane_label(tree: &Tree, lane: &str) -> String {
    match tree.lanes.get(lane) {
        Some(s) if !s.name.is_empty() => s.name.clone(),
        _ => lane.to_string(),
    }
}

/// Whether `lane` is not the one this stretch is being read from -- the one
/// condition both the text mark and the `--json` field share. Always false
/// on a single-lane tree, since `lane` never differs from `tree.lane()`
/// there, which is what keeps both outputs printing the exact bytes they
/// always have (`t594` §4.3).
fn is_foreign(tree: &Tree, lane: &str) -> bool {
    lane != tree.lane()
}

/// What a line signed by `lane` carries: nothing when it is the lane this
/// stretch is being read from, and the other lane's own name, bracketed,
/// otherwise. Goes between the alias and the title -- `format!("[{}] ")`
/// used to sit in front of the alias instead, and that shifted the `{:<6}`
/// column every other line in the same group still reads by.
fn foreign_mark(tree: &Tree, lane: &str) -> String {
    if is_foreign(tree, lane) {
        format!("[{}] ", lane_label(tree, lane))
    } else {
        String::new()
    }
}

fn print_text(tree: &Tree, result: &Changed) {
    outln!();
    outln!("{}", header(&result.since, result.tail.stops));

    let mut said_something = false;

    if !result.opened.is_empty() {
        said_something = true;
        outln!();
        outln!("  OPENED ({})", result.opened.len());
        for o in &result.opened {
            outln!(
                "    {:<6} {}{}",
                o.node.alias(),
                foreign_mark(tree, &o.lane),
                o.node.title(tree)
            );
        }
    }

    if !result.closed.is_empty() {
        said_something = true;
        outln!();
        outln!("  CLOSED ({})", result.closed.len());
        for c in &result.closed {
            outln!(
                "    {:<6} {}{}",
                c.node.alias(),
                foreign_mark(tree, &c.lane),
                c.node.title(tree)
            );
            let line = if c.forced {
                if c.outcome.is_empty() {
                    "forced".to_string()
                } else {
                    format!("forced: {}", c.outcome)
                }
            } else {
                c.outcome.clone()
            };
            for l in wrap(&line, WIDTH, "           ") {
                outln!("{l}");
            }
        }
    }

    if !result.flagged.is_empty() {
        said_something = true;
        outln!();
        outln!("  FLAGGED ({})", result.flagged.len());
        for f in &result.flagged {
            outln!(
                "    {:<6} {}{}",
                f.node.alias(),
                foreign_mark(tree, &f.lane),
                f.node.title(tree)
            );
            for l in wrap(
                &format!("{}: {}", f.flag.word(), f.reason),
                WIDTH,
                "           ",
            ) {
                outln!("{l}");
            }
        }
    }

    if !result.moved.is_empty() {
        said_something = true;
        outln!();
        outln!("  MOVED ({})", result.moved.len());
        for m in &result.moved {
            outln!(
                "    {:<6} {}{}",
                m.node.alias(),
                foreign_mark(tree, &m.lane),
                m.node.title(tree)
            );
            let word = m.state.word(m.node.kind);
            for l in wrap(
                &format!("{word}: {}", m.node.outcome(tree)),
                WIDTH,
                "           ",
            ) {
                outln!("{l}");
            }
        }
    }

    if let Some(t) = tail_phrase(&result.tail) {
        said_something = true;
        outln!();
        outln!("  + {t}");
    }

    if !said_something {
        outln!();
        match &result.since {
            Boundary::Stop { vivac, .. } => {
                outln!("  Nothing has moved since {}.", vivac.alias())
            }
            Boundary::Beginning { .. } => outln!("  Nothing has moved."),
        }
    }
    outln!();
}

/// Adds `"lane"` to `obj`, and only when `lane` is foreign -- the same
/// condition `foreign_mark` uses for the text. An agent reading `--json`
/// has no other way to tell a line came from another folder (DX pillar):
/// the mark used to live only in the text, and the shape here follows
/// `Repo.root`'s own `skip_serializing_if` (task 5) -- present only when
/// there is something to say, so a single-lane tree's JSON never gains
/// the key at all.
fn with_lane_if_foreign(tree: &Tree, lane: &str, mut obj: serde_json::Value) -> serde_json::Value {
    if is_foreign(tree, lane) {
        if let serde_json::Value::Object(map) = &mut obj {
            map.insert("lane".to_string(), json!(lane));
        }
    }
    obj
}

fn as_json(tree: &Tree, result: &Changed) -> serde_json::Value {
    json!({
        // `kind` says how the boundary was chosen, not what kind of stop it
        // is: `--since v122` on a stop somebody made still reads `stop`,
        // because naming it outright is not the same question as asking for
        // the last one made by hand.
        "since": match &result.since {
            Boundary::Stop { vivac, manual } => json!({
                "kind": if *manual { "manual" } else { "stop" },
                "alias": vivac.alias(),
                "ts": vivac.ts,
                "stops_since": result.tail.stops,
            }),
            Boundary::Beginning { .. } => serde_json::Value::Null,
        },
        "opened": result.opened.iter().map(|o| with_lane_if_foreign(tree, &o.lane, json!({
            "alias": o.node.alias(),
            "title": o.node.title(tree),
            "kind": o.node.kind,
        }))).collect::<Vec<_>>(),
        "closed": result.closed.iter().map(|c| with_lane_if_foreign(tree, &c.lane, json!({
            "alias": c.node.alias(),
            "title": c.node.title(tree),
            "outcome": c.outcome,
            "forced": c.forced,
        }))).collect::<Vec<_>>(),
        "flagged": result.flagged.iter().map(|f| with_lane_if_foreign(tree, &f.lane, json!({
            "alias": f.node.alias(),
            "title": f.node.title(tree),
            "flag": f.flag.word(),
            "reason": f.reason,
        }))).collect::<Vec<_>>(),
        "moved": result.moved.iter().map(|m| with_lane_if_foreign(tree, &m.lane, json!({
            "alias": m.node.alias(),
            "title": m.node.title(tree),
            "state": m.state.word(m.node.kind),
        }))).collect::<Vec<_>>(),
        "tail": {
            "focus_moves": result.tail.focus_moves,
            "notes": result.tail.notes,
            "flags_cleared": result.tail.flags_cleared,
            "edge_changes": result.tail.edges,
            "arm_changes": result.tail.arms,
            "late_declarations": result.tail.declarations,
            "unreadable": result.tail.unreadable,
        },
    })
}

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

    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 node_created(seq: u64, node: &str, num: u64, title: &str) -> Event {
        ev(
            seq,
            Body::NodeCreated {
                node: node.to_string(),
                num,
                kind: Kind::Task,
                title: title.to_string(),
                why: "it is needed".to_string(),
                parent: None,
                blocks: false,
                refs: vec![],
                governs: vec![],
                arms: vec![],
                against: None,
            },
        )
    }

    fn state_changed(seq: u64, node: &str, state: State, outcome: &str, forced: bool) -> Event {
        ev(
            seq,
            Body::StateChanged {
                node: node.to_string(),
                state,
                outcome: outcome.to_string(),
                forced,
            },
        )
    }

    fn session_started(seq: u64) -> Event {
        ev(
            seq,
            Body::SessionStarted {
                source: "test".to_string(),
                focus: None,
                vivac: None,
                session: None,
            },
        )
    }

    fn flag_cleared(seq: u64, node: &str, flag: Flag) -> Event {
        ev(
            seq,
            Body::FlagCleared {
                node: node.to_string(),
                flag,
            },
        )
    }

    fn flag_raised(seq: u64, node: &str, flag: Flag, reason: &str) -> Event {
        ev(
            seq,
            Body::FlagRaised {
                node: node.to_string(),
                flag,
                reason: reason.to_string(),
            },
        )
    }

    fn pushed(seq: u64, node: &str) -> Event {
        ev(
            seq,
            Body::Pushed {
                node: node.to_string(),
            },
        )
    }

    /// The limit is exclusive: the event at `since_seq` itself is the stop
    /// being measured from, not part of the stretch.
    #[test]
    fn the_limit_is_exclusive() {
        let events = vec![
            node_created(1, "n1", 1, "Old"),
            node_created(2, "n2", 2, "New"),
        ];
        let tree = fold(&events, 0);
        let result = collect(&tree, &events, 1);
        assert_eq!(result.opened.len(), 1);
        assert_eq!(result.opened[0].node.id, "n2");
    }

    /// `SessionStarted` says something about the session and nothing about
    /// the tree: it must not land in any group, nor in the tail.
    #[test]
    fn a_session_start_counts_for_nothing() {
        let events = vec![node_created(1, "n1", 1, "Node"), session_started(2)];
        let tree = fold(&events, 0);
        let result = collect(&tree, &events, 0);
        assert_eq!(result.opened.len(), 1);
        assert_eq!(result.tail.focus_moves, 0);
        assert_eq!(result.tail.notes, 0);
        assert_eq!(result.tail.flags_cleared, 0);
        assert_eq!(result.tail.edges, 0);
        assert_eq!(result.tail.stops, 0);
        assert_eq!(result.tail.unreadable, 0);
    }

    /// A node born and closed in the same stretch is what happened: it comes
    /// out in both groups, not deduplicated into one.
    #[test]
    fn a_node_born_and_closed_in_the_same_stretch_appears_in_both_groups() {
        let events = vec![
            node_created(1, "n1", 1, "Fixed fast"),
            state_changed(2, "n1", State::Done, "shipped", false),
        ];
        let tree = fold(&events, 0);
        let result = collect(&tree, &events, 0);
        assert_eq!(result.opened.len(), 1);
        assert_eq!(result.closed.len(), 1);
        assert_eq!(result.closed[0].node.id, "n1");
        assert_eq!(result.closed[0].outcome, "shipped");
        assert!(!result.closed[0].forced);
    }

    /// `FlagCleared` is a tail count, not a group of its own: clearing a flag
    /// is not the same kind of event as raising one.
    #[test]
    fn a_cleared_flag_goes_to_the_tail_and_not_to_a_group() {
        let events = vec![
            node_created(1, "n1", 1, "Node"),
            flag_cleared(2, "n1", Flag::Stale),
        ];
        let tree = fold(&events, 0);
        let result = collect(&tree, &events, 0);
        assert!(result.flagged.is_empty());
        assert_eq!(result.tail.flags_cleared, 1);
    }

    /// A stretch that only moved the focus has to say so: `tail.focus_moves`
    /// climbs and the four groups stay empty, so it does not read as if
    /// nothing happened.
    #[test]
    fn a_stretch_that_only_moved_the_focus_has_no_group_entries() {
        let events = vec![node_created(1, "n1", 1, "Node"), pushed(2, "n1")];
        let tree = fold(&events, 0);
        let result = collect(&tree, &events, 1);
        assert_eq!(result.tail.focus_moves, 1);
        assert!(result.opened.is_empty());
        assert!(result.closed.is_empty());
        assert!(result.flagged.is_empty());
        assert!(result.moved.is_empty());
    }

    /// An event naming a node the tree does not have sums in `unreadable`
    /// rather than being dropped in silence.
    #[test]
    fn an_event_naming_an_unknown_node_counts_as_unreadable() {
        let events = vec![
            node_created(1, "n1", 1, "Node"),
            flag_raised(2, "ghost", Flag::Suspect, "reason"),
        ];
        let tree = fold(&events, 0);
        let result = collect(&tree, &events, 0);
        assert!(result.flagged.is_empty());
        assert_eq!(result.tail.unreadable, 1);
    }

    /// Like `ev`, signed by a lane other than `main`: the fixture the
    /// marking tests below need, since every other helper in this module
    /// hardcodes the single lane `changes` used to be the whole of.
    fn ev_lane(seq: u64, lane: &str, payload: Body) -> Event {
        Event {
            seq,
            id: format!("e{seq}"),
            ts: "2026-09-03T10:00:00Z".to_string(),
            actor: "a".to_string(),
            lane: lane.to_string(),
            payload,
        }
    }

    /// `t594` §4.3: a line born from another lane carries that lane, so a
    /// renderer can mark it -- and one born from this stretch's own lane
    /// carries that one, indistinguishable from every line `changes` has
    /// always shown.
    #[test]
    fn each_group_carries_the_lane_its_event_was_signed_with() {
        let events = vec![
            node_created(1, "n1", 1, "Mine"),
            ev_lane(
                2,
                "b",
                Body::NodeCreated {
                    node: "n2".to_string(),
                    num: 2,
                    kind: Kind::Task,
                    title: "B's own".to_string(),
                    why: "it is needed".to_string(),
                    parent: None,
                    blocks: false,
                    refs: vec![],
                    governs: vec![],
                    arms: vec![],
                    against: None,
                },
            ),
            ev_lane(
                3,
                "b",
                Body::StateChanged {
                    node: "n2".to_string(),
                    state: State::Done,
                    outcome: "shipped".to_string(),
                    forced: false,
                },
            ),
            ev_lane(
                5,
                "b",
                Body::FlagRaised {
                    node: "n1".to_string(),
                    flag: Flag::Suspect,
                    reason: "from over there".to_string(),
                },
            ),
        ];
        let tree = fold(&events, 0);
        let result = collect(&tree, &events, 0);
        assert_eq!(result.opened[0].lane, "main");
        assert_eq!(result.opened[1].lane, "b");
        assert_eq!(result.closed[0].lane, "b");
        assert_eq!(result.flagged[0].lane, "b");
    }

    /// A single-lane tree marks nothing: every entry's `lane` equals the
    /// lane the tree is looked at from, which is the byte-for-byte
    /// guarantee `foreign_mark` exists to keep.
    #[test]
    fn a_single_lane_carries_no_foreign_mark() {
        let events = vec![node_created(1, "n1", 1, "Node")];
        let tree = fold(&events, 0);
        assert_eq!(foreign_mark(&tree, "main"), "");
    }

    /// A line from another lane is marked with that lane's own name, and
    /// falls back to the bare lane when it was never declared.
    #[test]
    fn a_foreign_lane_is_marked_with_its_name() {
        let events = vec![node_created(1, "n1", 1, "Node")];
        let tree = fold(&events, 0);
        assert_eq!(foreign_mark(&tree, "b"), "[b] ");
    }

    /// The DX pillar: an agent reading `--json` has no other way to learn a
    /// line came from another folder. `lane` carries the opaque id, not the
    /// declared name the text mark shows -- the two surfaces answer to
    /// different readers and are allowed to differ in value, never in
    /// whether they say anything at all.
    #[test]
    fn json_carries_lane_only_when_it_is_foreign() {
        let events = vec![
            node_created(1, "n1", 1, "Mine"),
            ev_lane(
                2,
                "b",
                Body::NodeCreated {
                    node: "n2".to_string(),
                    num: 2,
                    kind: Kind::Task,
                    title: "B's own".to_string(),
                    why: "it is needed".to_string(),
                    parent: None,
                    blocks: false,
                    refs: vec![],
                    governs: vec![],
                    arms: vec![],
                    against: None,
                },
            ),
        ];
        let tree = fold(&events, 0);
        let result = collect(&tree, &events, 0);
        let v = as_json(&tree, &result);
        assert!(
            v["opened"][0].get("lane").is_none(),
            "the context's own lane gained a lane field: {v}"
        );
        assert_eq!(v["opened"][1]["lane"], "b");
    }

    /// A single-lane tree's `--json` gains no `lane` key anywhere: the
    /// condition is never true when there is only one lane to be.
    #[test]
    fn a_single_lane_json_never_gains_the_lane_key() {
        let events = vec![node_created(1, "n1", 1, "Node")];
        let tree = fold(&events, 0);
        let result = collect(&tree, &events, 0);
        let v = as_json(&tree, &result);
        assert!(v["opened"][0].get("lane").is_none(), "{v}");
    }
}