vivac 0.15.7

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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
//! The `brief`: a deterministic render bounded in tokens.
//!
//! `BRIEF-SPEC.md`. It answers three questions in order of importance: where
//! we are and how we got here, what governs this point, and **what is out of
//! scope right now**. The third is the one no other tool emits: every memory
//! tool dumps what is relevant, and the problem in agentic development is the
//! opposite one, bounding.
//!
//! Two rules override everything else:
//!
//! - **Same log + same `--now` + same anchor state -> same bytes.** Without
//!   `--now` determinism would be impossible, because ages are relative to
//!   the moment.
//! - **The spine is never truncated.** If it does not fit, the budget is
//!   wrong and it says so, but it comes out whole: it is the answer to
//!   question 1, and without it the brief has no reason to exist.

use crate::args::Args;
use crate::event::{Kind, State, WhereRepo};
use crate::failure::R;
use crate::model::{Node, Tree};
use crate::style;
use std::collections::HashSet;
use std::path::Path;

const BUDGET: usize = 1500;
/// The whole brief is pure ASCII.
///
/// `BRIEF-SPEC.md` §7 draws the spine with box-drawing characters, but the DX
/// pillar demands it degrade without breaking "in cmd.exe as well as Windows
/// Terminal", and there any code page that is not UTF-8 turns them into
/// garbage. What is normative in §7 are the markers --that the focus be
/// visible, that a flag carry its reason, that an empty section not show--
const RULE: &str = "------------------------------------------------------------";

/// One section of the brief. The vector order is the one in §3, which is both
/// render order and priority order: truncation starts from the bottom.
struct Section {
    lines: Vec<String>,
    truncable: bool,
}

impl Section {
    fn fixed(lines: Vec<String>) -> Section {
        Section {
            lines,
            truncable: false,
        }
    }
    fn loose(lines: Vec<String>) -> Section {
        Section {
            lines,
            truncable: true,
        }
    }
}

/// Token estimator. It is an estimate and the ceiling is indicative: what
/// matters is that it be **deterministic**, so two runs of the same log
/// truncate the same way.
fn tokens(s: &str) -> usize {
    s.chars().count().div_ceil(4)
}

fn tokens_of(sections: &[Section]) -> usize {
    sections
        .iter()
        .flat_map(|s| s.lines.iter())
        .map(|l| tokens(l) + 1)
        .sum()
}

/// Truncates a list of items, each carrying one or more lines of its own, to
/// at most `max_lines` lines. An item is never split across the cut: it
/// either comes out whole or it does not come out at all, and the first item
/// always comes out, even when it alone is longer than `max_lines` (`f61`).
///
/// What is left out is counted in items, not lines: a park with an outcome
/// costs two lines and a park without one costs one, so counting lines would
/// call one missing item "2 more".
fn trim_list(groups: Vec<Vec<String>>, max_lines: usize, which: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut used = 0;
    let mut taken = 0;
    for group in &groups {
        if taken > 0 && used + group.len() > max_lines {
            break;
        }
        used += group.len();
        out.extend(group.iter().cloned());
        taken += 1;
    }
    let left_over = groups.len() - taken;
    if left_over > 0 {
        out.push(format!("      ... and {left_over} more (vivac {which})"));
    }
    out
}

fn heading(title: &str, body: Vec<String>) -> Vec<String> {
    // Empty sections are omitted whole, heading included: a brief with nothing
    // parked does not say "DO NOT TOUCH NOW: (empty)".
    if body.is_empty() {
        return vec![];
    }
    let mut v = vec![String::new(), format!(" {title}")];
    v.extend(body);
    v
}

/// Constraints that govern the path.
///
/// **By `spawns` only.** Inheriting through `depends_on` as well would turn
/// the computation from O(depth) into O(graph), and would lose the property
/// that inheritance is legible by looking at the stack on screen.
pub(crate) fn constraints<'a>(a: &'a Tree, lineage: &[&Node]) -> Vec<&'a Node> {
    let on_lineage: HashSet<u64> = lineage.iter().map(|n| n.num).collect();
    let mut v: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| n.kind == Kind::Constraint && n.state.is_open())
        .filter(|n| {
            // Project-wide, or reachable from the path. Project-wide means
            // hanging off a root **or being one**: `MODEL.md` §9.5 blesses
            // `parent: PROJECT`, and a node with no parent at all is the
            // strongest form of that, not a weaker one.
            let project_wide = n.parent.is_none()
                || n.parent
                    .and_then(|p| a.node_by_num(p))
                    .is_some_and(|p| p.parent.is_none());
            project_wide
                || a.ancestors(n.num)
                    .iter()
                    .any(|p| on_lineage.contains(&p.num))
        })
        .collect();
    // At risk first --the ones carrying a flag-- and then by alias.
    v.sort_by_key(|n| (n.flags.is_empty(), n.num));
    v
}

/// `t533` piece (c) (`f134`, `f55`): a node whose state is not open carries
/// its word, in brackets, right after the title -- the same word `why` and
/// `tree` already show (`render.rs`, `label`). Title and mark share the 44
/// columns the title alone used to have, so the two fit together; the mark
/// is never the part that gives. An open node keeps exactly the bytes it
/// always has.
fn spine_label(a: &Tree, n: &Node) -> String {
    if n.state.is_open() {
        return clip(n.title(a), 44);
    }
    let mark = format!("  [{}]", n.state.word(n.kind));
    let budget = 44usize.saturating_sub(mark.chars().count());
    format!("{}{mark}", clip(n.title(a), budget))
}

fn spine(a: &Tree, lineage: &[&Node]) -> Vec<String> {
    let mut v = Vec::new();
    for (i, n) in lineage.iter().enumerate() {
        let first = i == 0;
        let is_last = i == lineage.len() - 1;
        // Continuation: the trunk carries on while anything is left below.
        let cont = if is_last { "        " } else { "  |     " };

        let branch = if first {
            " GOAL ".to_string()
        } else if is_last {
            "  `-- ".to_string()
        } else {
            "  |-- ".to_string()
        };
        let flags: Vec<&str> = n.flags.keys().map(|b| b.word()).collect();
        let flag = if flags.is_empty() {
            String::new()
        } else {
            format!("  ! {}", flags.join(" "))
        };
        let here_mark = if is_last { "   <== HERE" } else { "" };
        v.push(format!(
            "{branch}{:<6} {}{flag}{here_mark}",
            n.alias(),
            spine_label(a, n)
        ));
        let why = n.why(a);
        if !first && !why.is_empty() {
            v.push(format!("{cont}why: {}", clip(why, 52)));
        }
        let governs = n.governs(a);
        if !governs.is_empty() {
            v.push(format!("{cont}governs: {}", governs.join(" ")));
        }
        if !is_last {
            v.push("  |".to_string());
        }
    }
    v
}

/// Cuts on a word boundary without exceeding `n`, **counting the ellipsis**.
/// Budgeting for it matters: otherwise the cut overruns on exactly the
/// tightest lines of the brief, which are the ones being truncated.
pub(crate) fn clip(s: &str, n: usize) -> String {
    if s.chars().count() <= n {
        return s.to_string();
    }
    let t: String = s.chars().take(n.saturating_sub(3)).collect();
    match t.rsplit_once(' ') {
        Some((a, _)) if !a.is_empty() => format!("{a}..."),
        _ => format!("{t}..."),
    }
}

/// Project level: hanging off nothing, or off a node that itself hangs off
/// nothing. `MODEL.md` §9.5 blesses `parent: PROJECT`, and a node with no
/// parent at all is the strongest form of that, not a weaker one.
/// `constraints()` above has drawn the line this way from the start; `t533`
/// piece (b) widens `standing()`'s own clause to the same shape, and the
/// no-focus path in `to_text` stands on nothing else.
fn project_wide(a: &Tree, n: &Node) -> bool {
    n.parent.is_none()
        || n.parent
            .and_then(|p| a.node_by_num(p))
            .is_some_and(|p| p.parent.is_none())
}

/// Standing decisions that reach the focus: project-level, on the path, or
/// with a `governs` overlapping the focus's own. Superseded ones never
/// appear. Always called with a real focus; with none, `to_text` reads
/// `project_wide` on its own instead, since there is neither a path nor a
/// `governs` to overlap.
pub(crate) fn standing<'a>(a: &'a Tree, focus: &Node, on_lineage: &HashSet<u64>) -> Vec<&'a Node> {
    let mut dec: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| n.kind == Kind::Decision && n.state.is_open())
        .filter(|n| {
            project_wide(a, n)
                || on_lineage.contains(&n.num)
                || n.parent.is_some_and(|p| on_lineage.contains(&p))
                || n.governs(a)
                    .iter()
                    .any(|g| focus.governs(a).iter().any(|f| crate::glob::covers(g, f)))
        })
        .collect();
    dec.sort_by_key(|n| n.num);
    dec
}

/// Whether a node could ever show up in `OPEN GOALS`, kind-wise: a goal, or a
/// node with no parent at all, and never a pillar, a rule, a decision or a
/// constraint -- the same governance kinds `Node::is_front` already keeps out
/// of pending work. `t533` §3.6 (`f73`, `f456`).
fn is_goal_shaped(n: &Node) -> bool {
    !matches!(
        n.kind,
        Kind::Decision | Kind::Constraint | Kind::Pillar | Kind::Rule
    ) && (n.kind == Kind::Goal || n.parent.is_none())
}

/// What `BORN FROM HERE` lists: `focus`'s own open, front children, plus how
/// many more open fronts hang further down without being listed one by one.
///
/// `f49`: a blocking question is left out here, because `BLOCKS` already
/// lists it -- showing it twice says the same thing in two places for no
/// reason. A blocking task still shows, asterisk and all: only a question is
/// also a row of its own in `BLOCKS`.
fn born_from_here(a: &Tree, focus: &Node) -> Vec<String> {
    let mut children: Vec<String> = a
        .children(focus.num)
        .into_iter()
        .filter(|c| c.is_front())
        .filter(|c| !(c.kind == Kind::Question && c.blocks))
        .map(|c| {
            format!(
                "  {} {:<6} {}",
                if c.blocks { '*' } else { ' ' },
                c.alias(),
                c.title(a)
            )
        })
        .collect();
    // Closing a parent cannot make its open children invisible. They are
    // counted and the place to look is named; listing them here would drag in
    // the whole tree, which is exactly the noise the focus exists to keep
    // out.
    let direct: std::collections::HashSet<&str> = a
        .children(focus.num)
        .iter()
        .map(|c| c.id.as_str())
        .collect();
    let deep = a
        .descendants(focus.num)
        .into_iter()
        .filter(|n| n.is_front() && !direct.contains(n.id.as_str()))
        .filter(|n| !a.children(n.num).iter().any(|c| c.is_front()))
        .count();
    if deep > 0 {
        children.push(format!(
            "    + {deep} further down, outside this level   vivac open"
        ));
    }
    children
}

/// The fixed block that takes the spine's place with no focus (`t533`
/// §3.6). Never truncated, the same as the spine.
fn no_focus_block(a: &Tree) -> Vec<String> {
    let mut v = vec![" No active focus.".to_string()];

    let mut goals: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| n.state.is_open() && is_goal_shaped(n))
        .collect();
    goals.sort_by_key(|n| n.num);

    if !goals.is_empty() {
        v.push(String::new());
        v.push(" OPEN GOALS".to_string());
        for m in &goals {
            v.push(format!(
                "  {:<6} {:<40} {} open below",
                m.alias(),
                clip(m.title(a), 40),
                a.counts(m.num).open_count
            ));
        }
    }

    v.push(String::new());
    if a.is_empty_tree() {
        v.push(" Start with:  vivac push \"<title>\" --why \"<reason>\"".to_string());
    } else if let Some(first) = goals.first() {
        v.push(format!(" Pick up with:  vivac focus {}", first.alias()));
        v.push(" Or open another:  vivac push \"<title>\" --why \"<reason>\"".to_string());
    } else {
        // Nothing open of that shape, but something parked would qualify if
        // it were open. `f50`: the action names a real id, never `<id>`.
        let mut parked: Vec<&Node> = a
            .nodes_iter()
            .filter(|n| n.state == State::Suspended && is_goal_shaped(n))
            .collect();
        parked.sort_by_key(|n| n.num);
        match parked.first() {
            Some(p) => {
                v.push(format!(" Pick up with:  vivac focus {}", p.alias()));
                v.push(" Or open another:  vivac push \"<title>\" --why \"<reason>\"".to_string());
            }
            None => {
                v.push(" Open the next one:  vivac push \"<title>\" --why \"<reason>\"".to_string())
            }
        }
    }
    v
}

pub fn brief(a: &Tree, root: &Path, lane_dir: &Path, args: &Args, project: &str) -> R {
    let text = to_text(a, root, lane_dir, args, project, false)?;
    print!("{}", style_text(&text));
    Ok(())
}

/// The exact heading titles `to_text` prints on a line of their own -- a
/// single leading space and nothing else, blank lines around it, built
/// either by [`heading`] or, for the no-focus block's own `OPEN GOALS`, by
/// hand in the same shape. Matched literally rather than by a pattern such
/// as "all caps", which `BRANCH MOVED since this lane last wrote` and
/// `REPEATED NUMBERS ...` also satisfy without being one of these: both
/// carry more than a bare title on their own line, and neither is in this
/// list.
const BRIEF_HEADINGS: &[&str] = &[
    "BORN FROM HERE",
    "INVARIANTS",
    "BLOCKS",
    "FLAGGED",
    "DO NOT TOUCH NOW",
    "STANDING DECISIONS",
    "LAST VIVAC",
    "UNTOUCHED FOR A WHILE",
    OTHER_LANES_TITLE,
    "WRITE AT THESE SEAMS",
    "OPEN GOALS",
];

/// The three branch markers [`spine`] opens a row with, each six columns
/// wide: a goal has no line above it to draw from, and every step after it
/// is either the last of the path or not.
const SPINE_BRANCHES: [&str; 3] = [" GOAL ", "  `-- ", "  |-- "];

/// The `Kind` an alias's own prefix letter names, the inverse of
/// [`crate::event::Kind::prefix`]. Only [`style_spine_row`] needs this: it
/// styles a spine row it can no longer ask a `Node` about, since `to_text`
/// has already folded the whole brief down to plain lines by the time
/// [`style_text`] ever sees one.
fn kind_from_alias_prefix(alias: &str) -> Option<Kind> {
    match alias.chars().next()? {
        'g' => Some(Kind::Goal),
        't' => Some(Kind::Task),
        'd' => Some(Kind::Decision),
        'q' => Some(Kind::Question),
        'c' => Some(Kind::Constraint),
        'f' => Some(Kind::Finding),
        'a' => Some(Kind::Assumption),
        'p' => Some(Kind::Pillar),
        'r' => Some(Kind::Rule),
        _ => None,
    }
}

/// Colours a spine row's own alias by kind, the same nine colours `tree`,
/// `open` and `why` already read one by (`d795`) -- `None` for a line that
/// does not open with one of [`SPINE_BRANCHES`], which is every line here
/// but the path from the root to the focus.
fn style_spine_row(out: style::Stream, line: &str) -> Option<String> {
    let branch = SPINE_BRANCHES.iter().find(|b| line.starts_with(*b))?;
    let rest = &line[branch.len()..];
    if rest.len() < 6 {
        return None;
    }
    let (alias_field, tail) = rest.split_at(6);
    let alias = alias_field.trim_end();
    let kind = kind_from_alias_prefix(alias)?;
    let coloured = style::kind_id(out, kind, alias);
    let pad = &alias_field[alias.len()..];
    Some(format!("{branch}{coloured}{pad}{tail}"))
}

/// One already-assembled line of [`to_text`]'s own output, styled for a
/// person at a terminal. Never asked to decide whether it should: that is
/// [`style_text`]'s call alone, made once for the whole text rather than
/// once per line, so a plain run never even reaches this function.
fn style_line(out: style::Stream, line: &str) -> String {
    if line == RULE {
        return style::dim(out, line);
    }
    if line.contains(" tokens \u{b7} depth ") {
        return style::dim(out, line);
    }
    if let Some(rest) = line.strip_prefix(' ') {
        if BRIEF_HEADINGS.contains(&rest) {
            return style::bold(out, line);
        }
    }
    let mut styled = style_spine_row(out, line).unwrap_or_else(|| line.to_string());
    if styled.contains("<== HERE") {
        styled = styled.replacen(
            "<== HERE",
            &style::bold(out, &style::warn(out, "<== HERE")),
            1,
        );
    }
    styled
}

/// Styles the brief's already-finished plain text for a person reading
/// `vivac brief` at a terminal -- never for `to_text`'s own two other
/// readers, a hook and the MCP server, which print or return its plain
/// return value directly and never reach this function at all.
///
/// A pure pass over the string `to_text` already decided every byte of:
/// the budget, the truncation and the token count in the footer are all
/// computed on the plain text before this ever runs, so styling a line can
/// only ever add invisible bytes to it, never move where a cut landed.
/// `to_text` keeps its own clipping rather than `style::wrap_title`'s, and
/// this pass never wraps anything either -- the same rows the plain read
/// prints, on the same lines, with an escape code added on top of some of
/// them.
fn style_text(text: &str) -> String {
    let out = style::Stream::Out;
    if !style::enabled(out) {
        return text.to_string();
    }
    let mut styled = String::with_capacity(text.len());
    for line in text.split_inclusive('\n') {
        let (body, newline) = match line.strip_suffix('\n') {
            Some(b) => (b, "\n"),
            None => (line, ""),
        };
        styled.push_str(&style_line(out, body));
        styled.push_str(newline);
    }
    styled
}

/// Whether `root` is a copy of a tree living somewhere else on this
/// machine, laid out for the brief's own shape (`t594` §4.7). Read only,
/// through `copy_of`, never `note`: the brief is a read and must never
/// write (`c319`).
///
/// `copy_notice`'s heading and body are the one thing shared with `check`'s
/// own block -- indentation is each caller's own, the words are not, so
/// nobody has to keep two paragraphs saying the same thing in agreement by
/// hand.
fn copy_block(root: &Path) -> Vec<String> {
    let Some(project_id) = crate::store::first_event_id(root) else {
        return vec![];
    };
    let Some(store_dir) = crate::store::store_dir() else {
        return vec![];
    };
    let (first, rest) = match crate::registry::copy_of(&store_dir, &project_id, root) {
        crate::registry::Noted::Copy { first, rest } => (first, rest),
        crate::registry::Noted::Fine => return vec![],
    };
    // `session start` reaches this before it ever writes anything
    // (`t594`): marking here, rather than after the block is
    // printed, is what lets `registry::warn_if_wrote` see that the very
    // same words already reached whoever is reading before it decides
    // whether to say them again on `stderr`.
    crate::store::mark_shown();
    let notice = crate::registry::copy_notice(first.as_deref(), &rest);
    let mut v = vec![format!(" {}", notice.heading), String::new()];
    v.extend(notice.body.lines().map(|l| format!("  {l}")));
    v.push(String::new());
    v
}

/// How one repository's checkout reads on a BRANCH MOVED line: a branch by
/// its bare name, a detached `HEAD` as `@<short sha>`, and a rebase in
/// progress as `@<branch> (rebasing)` -- the branch git is replaying onto,
/// not the tip it detached from (§5.2, the four forms). `None` when there
/// is nothing knowable at all, which BRANCH MOVED has nothing to say about.
fn head_repr(branch: Option<&str>, sha: Option<&str>, rebasing: bool) -> Option<String> {
    match branch {
        Some(b) if rebasing => Some(format!("@{b} (rebasing)")),
        Some(b) => Some(b.to_string()),
        None => sha.map(|s| format!("@{}", &s[..s.len().min(7)])),
    }
}

/// The redaction guard's own phrase for a branch name it kept out (`d600`,
/// §2.4), reused here rather than invented again: a withheld branch reads
/// the same way whether it is `why` naming where a node was born or
/// BRANCH MOVED naming where a repository moved to.
const BRANCH_WITHHELD: &str = "branch name withheld: it looked like a secret";

/// A declared repository's last known checkout, as `where.changed` wrote
/// it. A withheld branch (§2.4) reads with the guard's own phrase, since
/// what reached the log was already redacted; a repository the lane last
/// saw as gone has nothing to compare with.
fn last_known_repr(r: &WhereRepo) -> Option<String> {
    if r.missing {
        return None;
    }
    if r.withheld {
        return Some(BRANCH_WITHHELD.to_string());
    }
    head_repr(r.branch.as_deref(), r.sha.as_deref(), r.rebasing)
}

/// A repository's checkout right now, read straight off the working tree
/// and never through the log: the redaction guard has not seen this name
/// yet, so it is run past it here -- the same check `ops::snapshot_of` runs
/// before anything reaches the log at all.
fn now_repr(w: &crate::anchor::Where) -> Option<String> {
    let crate::anchor::Where::Head(h) = w else {
        return None;
    };
    if let Some(b) = &h.branch {
        if crate::redact::check_field("branch", b).is_some() {
            return Some(BRANCH_WITHHELD.to_string());
        }
    }
    head_repr(h.branch.as_deref(), h.sha.as_deref(), h.rebasing)
}

/// The branch to look a candidate up for: the checkout's own branch, only
/// when it is not withheld and no rebase is under way -- a rebase's own
/// branch is what it is replaying onto, not a place work was last focused.
fn candidate_branch(w: &crate::anchor::Where) -> Option<String> {
    let crate::anchor::Where::Head(h) = w else {
        return None;
    };
    if h.rebasing {
        return None;
    }
    let b = h.branch.as_ref()?;
    (crate::redact::check_field("branch", b).is_none()).then(|| b.clone())
}

/// One of the lane's declared repositories whose checkout no longer reads
/// the way the lane's own last `where.changed` said it did.
struct Moved {
    path: String,
    before: String,
    now: String,
    /// The branch to offer a candidate for, when there is one to look up.
    candidate_branch: Option<String>,
    root: Option<String>,
}

/// BRANCH MOVED (`t594` §5.2): shows only when today's `HEAD` of some
/// repository of the lane differs from the lane's own last `where.changed`.
/// `[]` covers every tree this never applies to -- no lane, no
/// repositories declared, or no `where.changed` yet to compare against --
/// which is every tree before `setup` ran (§2.6) and reads byte for byte
/// as it always has.
fn branch_moved_block(a: &Tree, lane_dir: &Path) -> Vec<String> {
    let lane = a.lane();
    let Some(state) = a.lanes.get(lane) else {
        return vec![];
    };
    if state.repos.is_empty() {
        return vec![];
    }
    let Some(last) = a.wheres.iter().rev().find(|w| w.lane == lane) else {
        return vec![];
    };

    let mut moved: Vec<Moved> = state
        .repos
        .iter()
        .filter_map(|r| {
            let before_repo = last.repos.iter().find(|w| w.path == r.path)?;
            let before = last_known_repr(before_repo)?;
            let now = crate::anchor::where_of(&lane_dir.join(&r.path));
            let now_line = now_repr(&now)?;
            if before == now_line {
                return None;
            }
            Some(Moved {
                path: r.path.clone(),
                before,
                now: now_line,
                candidate_branch: candidate_branch(&now),
                root: r.root.clone(),
            })
        })
        .collect();
    if moved.is_empty() {
        return vec![];
    }
    moved.sort_by(|x, y| x.path.cmp(&y.path));

    let mut lines = vec![" BRANCH MOVED since this lane last wrote".to_string()];
    for m in &moved {
        lines.push(format!("   {}   {} -> {}", m.path, m.before, m.now));
    }

    // Candidates: this lane's own last focus on the new branch, else
    // another lane's crossed by root commit, else "no earlier work" --
    // capped at three and ordered by `seq` descending (§5.2).
    struct Candidate {
        seq: u64,
        line: String,
        target: Option<String>,
    }
    let mut candidates: Vec<Candidate> = moved
        .iter()
        .filter_map(|m| {
            let branch = m.candidate_branch.as_deref()?;
            Some(
                match a.branch_candidate(lane, &m.path, m.root.as_deref(), branch) {
                    Some(c) => {
                        let node = a.node_by_num(c.node)?;
                        let who = match &c.lane {
                            Some(other) => format!(" (lane {other})"),
                            None => String::new(),
                        };
                        Candidate {
                            seq: c.seq,
                            line: format!(
                                "   last focus on {branch}{who}:   {}   {}",
                                node.alias(),
                                node.title(a)
                            ),
                            target: Some(node.alias()),
                        }
                    }
                    None => Candidate {
                        seq: 0,
                        line: format!("   no earlier work on {branch}"),
                        target: None,
                    },
                },
            )
        })
        .collect();
    candidates.sort_by_key(|x| std::cmp::Reverse(x.seq));
    candidates.truncate(3);
    for c in &candidates {
        lines.push(c.line.clone());
    }

    let mut targets: Vec<&str> = candidates
        .iter()
        .filter_map(|c| c.target.as_deref())
        .collect();
    targets.sort_unstable();
    targets.dedup();
    if let [only] = targets[..] {
        lines.push(format!("   to resume:  vivac focus {only}"));
    }
    // A trailing blank, the same spacer `REPEATED NUMBERS` ends its own
    // block with: this section sits right after the header and relies on
    // nothing after it to open with one of its own.
    lines.push(String::new());

    lines
}

/// One lane's own thread: which lane, what it is focused on, and the
/// `seq` its last write sits at. The shared starting point of OTHER
/// LANES (`t594` §5.3) and `stack --lanes` (§5.5): the first keeps only
/// the lanes that wrote after this one's own last write and are not this
/// one; the second keeps every one of them, this lane included.
pub(crate) struct LaneFocus<'t> {
    pub(crate) id: &'t str,
    pub(crate) name: &'t str,
    pub(crate) focus: &'t Node,
    pub(crate) seq: u64,
}

/// Every lane with something on its own stack to name (`t594` §5.3 and
/// §5.5 alike).
///
/// `[]` covers a tree with one lane that has never written here itself,
/// and every lane whose only events were declaring itself or moving a
/// branch: `Tree::apply` gives *every* event a `lanes` entry, context
/// events included, so an empty `stack` is what tells a lane that
/// actually worked apart from one of those defaults (`t594` tramo 5,
/// task 2's own warning).
pub(crate) fn lanes_with_a_stack(a: &Tree) -> Vec<LaneFocus<'_>> {
    a.lanes
        .iter()
        .filter_map(|(id, s)| {
            let focus = a.node_by_num(*s.stack.last()?)?;
            Some(LaneFocus {
                id: id.as_str(),
                name: if s.name.is_empty() {
                    id.as_str()
                } else {
                    s.name.as_str()
                },
                focus,
                seq: s.seq_wrote,
            })
        })
        .collect()
}

/// One row of `stack --lanes` (`f668`): every lane the tree knows of,
/// focus optional. `LaneFocus` cannot grow an optional focus without
/// touching every reader that already assumes one -- `other_lanes` and
/// `last_writer` among them -- so this is its own, narrower struct
/// instead.
pub(crate) struct LaneRow<'t> {
    pub(crate) id: &'t str,
    pub(crate) name: &'t str,
    pub(crate) focus: Option<&'t Node>,
    pub(crate) seq: u64,
}

/// Every lane the tree knows of, whether it has ever pushed or not
/// (`f668`): `stack --lanes` exists to name every folder of the product,
/// and `lanes_with_a_stack` -- kept exactly as it was for OTHER LANES,
/// which still only wants the ones with a front of their own -- filters
/// out precisely the ones a brand new lane still is.
pub(crate) fn all_lanes(a: &Tree) -> Vec<LaneRow<'_>> {
    a.lanes
        .iter()
        .map(|(id, s)| LaneRow {
            id: id.as_str(),
            name: if s.name.is_empty() {
                id.as_str()
            } else {
                s.name.as_str()
            },
            focus: s.stack.last().and_then(|&num| a.node_by_num(num)),
            seq: s.seq_wrote,
        })
        .collect()
}

/// Which lane wrote to this tree most recently, among the ones with
/// something on their own stack to name: the lane the web treats as
/// "the" focus once there is more than one to pick from (`t594` §5.6).
/// Sorted the same way `other_lanes` already sorts its own rows -- `seq`
/// descending, the lane id breaking a tie -- so the two agree on what
/// "most recent" means even though the log's own counter never actually
/// hands two different lanes the same `seq` to disagree over.
pub(crate) fn last_writer(a: &Tree) -> Option<LaneFocus<'_>> {
    let mut rows = lanes_with_a_stack(a);
    rows.sort_by(|x, y| y.seq.cmp(&x.seq).then_with(|| x.id.cmp(y.id)));
    rows.into_iter().next()
}

/// Which of this tree's lanes have a folder the registry no longer finds
/// on disk, checked with `exists()` right now and never written down
/// (`t594` §5.3/§5.5, decision 2 of this task): a disk that disconnects
/// and comes back changes the answer both ways, so this is read at the
/// moment of showing the list, never cached.
///
/// `None` when this tree's project id or the registry's own store
/// directory cannot be resolved -- nothing to check a folder against.
/// What that means to a caller differs by feature, so it is left to
/// decide: OTHER LANES treats it as "vouch for none of them", and
/// `stack --lanes` treats it as "mark none of them", because unlike
/// OTHER LANES, that list exists to be shown regardless.
pub(crate) fn gone_lane_ids(root: &Path) -> Option<Vec<String>> {
    let project_id = crate::store::first_event_id(root)?;
    let store_dir = crate::store::store_dir()?;
    Some(crate::registry::lanes_with_missing_folder(
        &store_dir,
        &project_id,
    ))
}

/// Every lane but this one that wrote after this lane's own last write,
/// has something on its own stack to name, and whose folder the registry
/// still finds on disk (`t594` §5.3, decisions 1, 2 and 4 of this task).
///
/// `exists()` runs at most once per lane the registry knows of, and only
/// this far: nothing reaches the registry until there is at least one
/// lane with a stack and a `seq_wrote` newer than this one's own
/// (`f623`).
fn other_lanes<'t>(a: &'t Tree, root: &Path) -> Vec<LaneFocus<'t>> {
    let here = a.lane();
    let own_seq = a.lanes.get(here).map(|s| s.seq_wrote).unwrap_or(0);
    let mut rows: Vec<LaneFocus> = lanes_with_a_stack(a)
        .into_iter()
        .filter(|r| r.id != here && r.seq > own_seq)
        .collect();
    if rows.is_empty() {
        return rows;
    }
    let Some(gone) = gone_lane_ids(root) else {
        // Nothing to check a folder against: a lane this cannot vouch for
        // as still there does not get shown as one that is.
        return Vec::new();
    };
    rows.retain(|r| !gone.iter().any(|g| g == r.id));
    rows.sort_by(|x, y| y.seq.cmp(&x.seq).then_with(|| x.id.cmp(y.id)));
    rows
}

const OTHER_LANES_TITLE: &str = "OTHER LANES since you last wrote here";

/// OTHER LANES's own rows: three spaces, the lane, three spaces, its
/// focus's alias and title, three spaces, the date that focus was opened
/// -- the same three-space separator BRANCH MOVED already writes with,
/// rather than a fixed-width table nothing in the spec asks for.
fn other_lanes_rows(a: &Tree, rows: &[LaneFocus]) -> Vec<String> {
    rows.iter()
        .map(|r| {
            format!(
                "   {}   {}   {}   {}",
                r.name,
                r.focus.alias(),
                r.focus.title(a),
                crate::clock::date_of(r.focus.opened(a))
            )
        })
        .collect()
}

/// The trace OTHER LANES leaves when the budget trims its rows away
/// (`t594` §5.3): the heading stays, and one line says how many lanes
/// there were and where to read them in full. Falling silent would say
/// nothing happened here, and something did.
fn other_lanes_fallback(n: usize) -> Vec<String> {
    // One lane reaches this line as easily as several: the trace is only
    // shorter than the rows it replaces when a row is long, and a single
    // long row is the cheapest way to get here.
    let lanes = if n == 1 { "lane" } else { "lanes" };
    heading(
        OTHER_LANES_TITLE,
        vec![format!(
            "   {n} {lanes} wrote here since you did (vivac stack --lanes)"
        )],
    )
}

/// The four lines ahead of the table (`d757`, `d779`): look at what the tree
/// already holds before writing, hang new work from what it continues --
/// the focus is wherever work was left, maybe by another session and about
/// something else -- and, last, the rule the whole block exists to teach:
/// what gets told out loud belongs in the tree before it belongs in the
/// answer, not after.
const CAPTURE_SEAMS_HEAD: &[&str] = &[
    "  Look first: vivac find \"<words>\". Work the tree already holds goes under",
    "  its node, never into a second one. The focus above is where work was",
    "  left, maybe not by you: hang new work from what it continues.",
    "  Write before you answer: what you tell the person goes in the tree first.",
];

/// The capture seams (`d738`, `d757`): one row per place work is supposed to
/// land, its label, the CLI shown for it, the hint lines under that row --
/// zero, one or two of them -- and the MCP tool that does the same thing.
/// `f737` measured the gap this closes -- an agent with no project doctrine
/// of its own only wrote to the tree when the person asked, because nothing
/// it received unasked said when to -- and `f755`/`f756` measured that once
/// it does write there, it still does not look first or say where a new
/// line of work hangs from.
///
/// Single source: [`capture_seams_block`] renders every row of this table,
/// so the label column, the command, the hints and the tool name can never
/// drift out of step with each other.
const CAPTURE_SEAMS: &[(&str, &str, &[&str], &str)] = &[
    (
        "new line of work",
        "vivac push \"<title>\" --why \"<why>\" --parent <id>",
        &["or --root, when it continues nothing in the tree"],
        "vivac_push",
    ),
    (
        "a choice is settled",
        "vivac decide \"<t>\" --reason \"<r>\" --alternative \"<x>\"",
        &[],
        "vivac_decide",
    ),
    (
        "you report findings",
        "vivac add \"<t>\" --type finding --why \"<where>\"",
        &[
            "as you tell the person, one for each thing found",
            "asks nothing? close it: vivac done <id> \"Record: ...\"",
        ],
        "vivac_add",
    ),
    (
        "told \"not now\"",
        "vivac park <id> \"<their words>\"",
        &["nothing to park yet? vivac add it, then park it"],
        "vivac_park",
    ),
    (
        "changed outside git",
        "vivac note <id> \"<what changed, where>\"",
        &["CI, a tracker, the cloud: the tree is its only record"],
        "vivac_note",
    ),
    (
        "the work is done",
        "vivac pop \"<outcome>\"",
        &["and again if that settles the node it returns to"],
        "vivac_pop",
    ),
];

/// Renders [`CAPTURE_SEAMS_HEAD`] and [`CAPTURE_SEAMS`] into the block the
/// hook brief shows. The label column is padded to the longest label plus
/// two spaces, from the table itself, so a longer label added later keeps
/// the columns lined up rather than needing a hand-picked width kept in
/// step by hand; a row's own hint, when it has one, is indented to that
/// same column.
fn capture_seams_block() -> Vec<String> {
    let width = CAPTURE_SEAMS
        .iter()
        .map(|(label, _, _, _)| label.chars().count())
        .max()
        .unwrap_or(0)
        + 2;
    let mut body: Vec<String> = CAPTURE_SEAMS_HEAD.iter().map(|l| l.to_string()).collect();
    for (label, command, hints, _) in CAPTURE_SEAMS {
        body.push(format!("  {label:<width$}{command}"));
        for hint in hints.iter() {
            body.push(format!("{}{hint}", " ".repeat(2 + width)));
        }
    }
    body.push("  Or the same moves through the vivac_* tools.".to_string());
    heading("WRITE AT THESE SEAMS", body)
}

/// The brief as text. `session start --hook` prints it straight to stdout
/// (`f403`, `f404`): Claude Code turns plain-text stdout on `SessionStart`
/// into context the agent can see and act on, so there is nothing further to
/// wrap it in.
///
/// `for_hook` is the only thing that tells the hook's own call apart from
/// `vivac brief`, read by a person, and the MCP `vivac_brief` tool. Only it
/// gets the capture-seams block (`d738`, `d757`): a person reading `vivac brief`
/// learns nothing from being told when to write, and the block belongs here,
/// appended once, rather than being built twice by callers that would have
/// to agree on it by hand.
pub fn to_text(
    a: &Tree,
    root: &Path,
    lane_dir: &Path,
    args: &Args,
    project: &str,
    for_hook: bool,
) -> Result<String, crate::failure::Failure> {
    let today = args.opt("now").unwrap_or("").to_string();
    let today = if today.is_empty() {
        crate::clock::now_rfc3339()
    } else {
        today
    };
    let date = crate::clock::date_of(&today);
    let budget: usize = args
        .opt("budget")
        .and_then(|s| s.parse().ok())
        .unwrap_or(BUDGET);

    let lineage: Vec<&Node> = match a.stack().last() {
        Some(&num) => a.ancestors(num),
        None => vec![],
    };
    let focus: Option<&Node> = lineage.last().copied();

    let mut s: Vec<Section> = Vec::new();

    // 0. The copy warning, ahead of everything else (`t594` §4.7): if this
    // folder is a copy, the lineage below may have diverged from whatever
    // this same first event looks like in the other folder, without either
    // side knowing. Fixed, like the header it sits in front of -- this is
    // the one section whose absence would make the rest of the brief a
    // silent lie.
    let block = copy_block(root);
    if !block.is_empty() {
        s.push(Section::fixed(block));
    }

    // 1. Header. 2. Spine, or -- with no focus -- the fixed block that takes
    // its place (`t533` §3.6). Neither is ever truncated. `lane_name` reads
    // `main` for the founding lane and its own declared name for any other,
    // so a tree with one lane prints the exact bytes it always has (`t594`
    // §5.1).
    s.push(Section::fixed(vec![
        format!(
            "vivac · project: {project} · lane: {} · {date}",
            a.lane_name()
        ),
        RULE.to_string(),
        String::new(),
    ]));
    // BRANCH MOVED (`t594` §5.2): right behind the header, so it is the
    // last thing the budget would ever reach. `Section::fixed` and never
    // truncated -- it is bounded by construction, one line per repository
    // moved, three candidates at most, one `to resume` (`t427`).
    let branch_moved = branch_moved_block(a, lane_dir);
    if !branch_moved.is_empty() {
        s.push(Section::fixed(branch_moved));
    }
    // `t429`'s second fix: repeated numbers are named, never hidden. One
    // line, bounded, and only when there are any.
    //
    // `repeated_nums` carries one entry per extra claimant, so a number
    // three nodes claim shows up twice: deduplicated here, in the order the
    // fold first met each one, so the five-wide cap counts distinct numbers
    // rather than claimants.
    if !a.repeated_nums.is_empty() {
        let mut seen = HashSet::new();
        let distinct_nums: Vec<u64> = a
            .repeated_nums
            .iter()
            .map(|d| d.num)
            .filter(|num| seen.insert(*num))
            .collect();
        let mut nums: Vec<String> = distinct_nums.iter().take(5).map(u64::to_string).collect();
        if distinct_nums.len() > 5 {
            nums.push(format!("+{}", distinct_nums.len() - 5));
        }
        s.push(Section::fixed(vec![
            format!(
                " REPEATED NUMBERS  {}  <- each names two nodes; vivac check",
                nums.join(", ")
            ),
            String::new(),
        ]));
    }
    s.push(Section::fixed(match focus {
        Some(_) => spine(a, &lineage),
        None => no_focus_block(a),
    }));

    // 3. Focus: what hangs off it unclosed. Standing decisions do not go in
    //    --they are not pending work and they have their own section (8)--,
    //    and whatever hangs further down is counted without being listed.
    //    Empty, and so omitted, with no focus to hang anything off.
    let born = focus.map(|f| born_from_here(a, f)).unwrap_or_default();
    s.push(Section::fixed(heading("BORN FROM HERE", born)));

    // 4. Invariants.
    let invariants: Vec<String> = constraints(a, &lineage)
        .iter()
        .map(|c| {
            let risk = if c.flags.is_empty() { "" } else { "   AT RISK" };
            format!("  {:<6} {}{risk}", c.alias(), c.title(a))
        })
        .collect();
    s.push(Section::fixed(heading("INVARIANTS", invariants)));

    // 5. Blocking questions: all of them, untruncated, ordered by alias
    // number ascending (`BRIEF-SPEC.md` §2, `f48`). Sorting the nodes
    // themselves is what that means -- sorting the formatted lines instead
    // sorts on the rendered text, so q10 reads before q2.
    let on_lineage: HashSet<u64> = lineage.iter().map(|n| n.num).collect();
    let mut question_nodes: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| n.kind == Kind::Question && n.state.is_open() && n.blocks)
        .filter(|n| {
            a.ancestors(n.num)
                .iter()
                .any(|p| on_lineage.contains(&p.num))
        })
        .collect();
    question_nodes.sort_by_key(|n| n.num);
    let questions: Vec<String> = question_nodes
        .iter()
        .map(|n| format!("  {:<6} {}", n.alias(), n.title(a)))
        .collect();
    s.push(Section::fixed(heading("BLOCKS", questions)));

    // 6. Flags on the path, or one hop off it.
    let mut flagged: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| !n.flags.is_empty())
        .filter(|n| {
            on_lineage.contains(&n.num) || n.parent.is_some_and(|p| on_lineage.contains(&p))
        })
        .collect();
    flagged.sort_by_key(|n| n.num);
    let flag_groups: Vec<Vec<String>> = flagged
        .iter()
        .flat_map(|n| {
            n.flags.iter().map(move |(b, reason)| {
                vec![format!(
                    "  {:<6} {:<10} {}",
                    n.alias(),
                    b.word(),
                    clip(a.text(*reason), 44)
                )]
            })
        })
        .collect();
    s.push(Section::loose(heading(
        "FLAGGED",
        trim_list(flag_groups, 3, "stats"),
    )));

    // 7. Out of scope: every parked node of the project, regardless of the
    // focus (`d536`) -- so this section and `parked`'s own count agree
    // (`f60`). **This is the product's differentiator**, and it only has
    // content if `park` costs the same as `pop`.
    let mut parked_nodes: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| n.state == State::Suspended)
        .collect();
    parked_nodes.sort_by_key(|n| n.num);
    let out_of_scope: Vec<Vec<String>> = parked_nodes
        .iter()
        .map(|n| {
            let hangs_off = n
                .parent
                .and_then(|p| a.node_by_num(p))
                .map(|p| format!("hangs off {}", p.alias()))
                .unwrap_or_default();
            let mut v = vec![format!(
                "  {:<6} {:<40} {hangs_off}",
                n.alias(),
                clip(n.title(a), 40)
            )];
            let outcome = n.outcome(a);
            if !outcome.is_empty() {
                v.push(format!("         \"{}\"", clip(outcome, 56)));
            }
            v
        })
        .collect();
    s.push(Section::loose(heading(
        "DO NOT TOUCH NOW",
        trim_list(out_of_scope, 6, "parked"),
    )));

    // 8. Standing decisions: project-level, on the path, or with a `governs`
    // overlapping the focus's own. Superseded ones never appear. With no
    // focus, only the project-level ones reach it: there is neither a path
    // nor a `governs` of the focus's own to overlap.
    //
    // **Project-level had been missing**, and it is the case that matters
    // most: a decision that governs the whole product hangs off nothing, so
    // it was on no path and reached no brief. The invariants above had the
    // clause and the decisions did not, which was an asymmetry and not a
    // choice.
    let dec: Vec<&Node> = match focus {
        Some(f) => standing(a, f, &on_lineage),
        None => {
            let mut d: Vec<&Node> = a
                .nodes_iter()
                .filter(|n| n.kind == Kind::Decision && n.state.is_open() && project_wide(a, n))
                .collect();
            d.sort_by_key(|n| n.num);
            d
        }
    };
    let decision_groups: Vec<Vec<String>> = dec
        .iter()
        .map(|n| vec![format!("  {:<6} {}", n.alias(), clip(n.title(a), 52))])
        .collect();
    s.push(Section::loose(heading(
        "STANDING DECISIONS",
        trim_list(decision_groups, 3, "tree"),
    )));

    // 9. Last vivac. What changed since it used to be answered here too, but
    // that cost two git processes -- 43 ms and 46 ms in a one-file
    // repository -- against a 50 ms ceiling for the whole brief: git alone
    // doubled the budget (`t594` task 1, `d625`, closes `f623`). `vivac
    // changes` and `vivac restore` answer it on demand, when someone
    // actually asks; the brief only names the vivac and its age.
    let vv: Vec<String> = match a.last_vivac() {
        None => vec![],
        Some(v) => {
            let mut l = vec![format!(
                "  {} · {} · {}{}",
                v.alias(),
                v.kind.word(),
                crate::clock::date_of(&v.ts),
                // A single repository reads exactly as it always has --
                // the short sha of `anchor`, root or lone declared
                // repository alike. Only two or more declared repositories
                // change the line at all, and they collapse to a count
                // rather than picking one sha to stand for all of them
                // (`t594` task 4, §4.4).
                match crate::model::anchoring(&v.anchor, &v.anchors) {
                    Some(a) => format!(" · {a}"),
                    None => String::new(),
                }
            )];
            // The last stop of this same lane that actually left an intent
            // for the relief, searching backward from `v` itself (`f67`,
            // `d652`). An automatic stop never carries one on purpose --
            // asking would be exactly the judgement of relevance the DX
            // pillar measured at zero uses -- so a hook's stop landing right
            // behind a manual one must not blank out what the manual one
            // said. May be `v` itself, an earlier stop, or nothing at all.
            let spoken = a
                .vivacs
                .iter()
                .rev()
                .find(|s| s.lane == v.lane && !s.next_intent.is_empty());
            // The label shown is always the one belonging to whichever stop
            // is being quoted: `spoken`'s own when there is one to quote,
            // `v`'s own otherwise (`f64`).
            let label = spoken.map_or(v.label.as_str(), |s| s.label.as_str());
            if !label.is_empty() {
                l.push(format!("         \"{}\"", clip(label, 52)));
            }
            if let Some(s) = spoken {
                l.push(if s.num == v.num {
                    format!("         you were about to: {}", clip(&s.next_intent, 52))
                } else {
                    format!(
                        "         {} was about to: {}",
                        s.alias(),
                        clip(&s.next_intent, 52)
                    )
                });
            }
            l
        }
    };
    s.push(Section::loose(heading("LAST VIVAC", vv)));

    // 10. Freshness.
    let stale_ones: Vec<String> = lineage
        .iter()
        .filter(|n| n.flags.contains_key(&crate::event::Flag::Stale))
        .map(|n| format!("  {:<6} {}", n.alias(), n.title(a)))
        .collect();
    s.push(Section::loose(heading("UNTOUCHED FOR A WHILE", stale_ones)));

    // 11. OTHER LANES (`t594` §5.3): the last section of the brief, so the
    // budget trims it first (`emit`'s own search runs from the bottom).
    // Decided here, ahead of `emit`, rather than by that same generic
    // clearing: every other truncable section vanishes whole when the
    // budget will not have it, and this one is not allowed to -- falling
    // in silence would be worse than not being there at all.
    let other = other_lanes(a, root);
    if !other.is_empty() {
        let full = heading(OTHER_LANES_TITLE, other_lanes_rows(a, &other));
        let full_tokens: usize = full.iter().map(|l| tokens(l) + 1).sum();
        if tokens_of(&s) + full_tokens <= budget {
            s.push(Section::loose(full));
        } else {
            let short = other_lanes_fallback(other.len());
            let short_tokens: usize = short.iter().map(|l| tokens(l) + 1).sum();
            if tokens_of(&s) + short_tokens <= budget {
                s.push(Section::loose(short));
            }
        }
    }

    // 12. Capture seams (`d738`, `d757`): the hook's own addition, last, right
    // ahead of the closing rule and the tokens/depth footer `emit` appends
    // -- and fixed, never trimmed, because the budget dropping the one
    // block that tells an agent when to write would be worse than the
    // brief running long.
    if for_hook {
        s.push(Section::fixed(capture_seams_block()));
    }

    emit(s, budget, a)
}

/// Assembles under budget. It is a **soft ceiling**: truncatable sections are
/// dropped from the bottom up until it fits; if it still does not fit, it is
/// emitted anyway with a warning. Going over budget is a sign the tree needs
/// pruning, not that the brief should lie by silent omission.
fn emit(mut s: Vec<Section>, budget: usize, a: &Tree) -> Result<String, crate::failure::Failure> {
    let requested = tokens_of(&s);
    while tokens_of(&s) > budget {
        match s.iter().rposition(|x| x.truncable && !x.lines.is_empty()) {
            Some(i) => s[i].lines.clear(),
            None => break,
        }
    }
    let spent = tokens_of(&s);

    let mut o = String::new();
    for l in s.iter().flat_map(|x| x.lines.iter()) {
        o.push_str(l);
        o.push('\n');
    }
    let parked_nodes = a
        .nodes_iter()
        .filter(|n| n.state == State::Suspended)
        .count();
    o.push_str(&format!(
        "
{RULE}
 {spent} tokens · depth {} · {parked_nodes} parked
",
        a.stack_depth()
    ));
    if spent > budget {
        o.push_str(&format!(
            "
 ! the brief is over budget ({spent}/{budget}).
   The spine is never truncated: what is left over is tree, not render.
   What can be pruned:  vivac triage
"
        ));
    } else if requested > budget {
        o.push_str(&format!(
            "
 ! {} tokens trimmed to fit in {budget}.
",
            requested - spent
        ));
    }
    Ok(o)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The trace OTHER LANES leaves behind is public prose, and one lane
    /// reaches it as easily as several (`tests/brief.rs`'s own budget test
    /// gets there with exactly one).
    #[test]
    fn the_trace_says_one_lane_and_never_one_lanes() {
        assert!(other_lanes_fallback(1)
            .iter()
            .any(|l| l.contains("1 lane wrote here since you did")));
        assert!(other_lanes_fallback(2)
            .iter()
            .any(|l| l.contains("2 lanes wrote here since you did")));
    }

    #[test]
    fn the_estimator_is_deterministic() {
        assert_eq!(tokens("same"), 1);
        assert_eq!(tokens("same tokens"), 3);
        assert_eq!(tokens(""), 0);
        // Same text, same number, always.
        assert_eq!(tokens("abcdefgh"), tokens("12345678"));
    }

    #[test]
    fn trimming_says_what_is_missing() {
        let groups: Vec<Vec<String>> = (0..10).map(|i| vec![format!("l{i}")]).collect();
        let r = trim_list(groups, 3, "parked");
        assert_eq!(r.len(), 4);
        assert_eq!(r[0], "l0");
        assert!(r[3].contains("7 more"), "{}", r[3]);
    }

    #[test]
    fn an_empty_section_leaves_no_heading() {
        assert!(heading("DO NOT TOUCH NOW", vec![]).is_empty());
        assert_eq!(heading("X", vec!["  a".into()]).len(), 3);
    }

    #[test]
    fn clipping_respects_words() {
        assert_eq!(clip("hello world", 20), "hello world");
        assert!(clip("a fairly long sentence that does not fit", 20).ends_with("..."));
        assert!(
            clip("a fairly long sentence that does not fit", 20)
                .chars()
                .count()
                <= 20
        );
    }
}