vivac 0.12.6

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
//! What a write returns, instead of printing it.
//!
//! `t106`: the CLI is not the only caller any more, and a caller over MCP
//! cannot read stdout. Every write op is moving from printing straight to a
//! terminal to returning an `Outcome`, so a second surface can read the same
//! answer the CLI does. `main.rs` and the MCP server both turn one into
//! text through `to_text` below -- a mirror of `brief::to_text`, which
//! already proved the split works: the data is built once, and the
//! rendering into a sentence is a formatting step over it, not a second
//! source of truth.
//!
//! **A variant carries the value an operation computed, never the sentence it
//! would have printed.** Where today's code interpolates a value into a
//! string -- `r.phrase()`, `kind.prefix()`, an anchor's short hash -- the
//! field here is that value, and `to_text` does the interpolating. Where
//! today's code prints a fixed sentence that names no data of its own, the
//! field is the `bool` or `Option` that decides whether it appears, and the
//! sentence itself lives in `to_text`. A model rule such as the depth
//! threshold `push` warns past, or whether a close needed `--force`, is
//! decided once, by the operation that knows the rule; `to_text` only knows
//! how to say what was already decided.

use crate::anchor::AnchorRef;
use crate::model::Counts;

/// A node closed, win or by force. Shared by `pop` and `done`, which both
/// wrap it: closing itself is one rule (`ops::close_node`) applied from two
/// places.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Closed {
    pub alias: String,
    pub title: String,
    pub force: bool,
    /// `f552` (`t533` §2.2): the word it already was, when `pop` reaches a
    /// focus that was not open to begin with -- `done`/`park` closed it while
    /// it sat below the top of the stack, and nothing here closes it again.
    /// Always present; `None` for an ordinary close, on both `pop` and
    /// `done`.
    pub already: Option<String>,
}

/// `push`'s advice to reconsider the root, past a stack four deep. `MODEL.md`
/// §6.1: intervene, never block, so it is advice and never a refusal.
#[derive(Debug, Clone, serde::Serialize)]
pub struct DepthAdvice {
    pub depth: usize,
    pub root_alias: String,
    pub root_title: String,
    /// `t533` §2.5: the bottom of the stack can now be closed or parked --
    /// `done`/`park` no longer unstack a node that is not the top -- and the
    /// advice carries its word rather than calling it open when it is not.
    /// `None` while it is still open.
    pub root_mark: Option<String>,
}

/// Where `pop` lands: the parent that becomes the new focus, with what is
/// still open below it.
#[derive(Debug, Clone, serde::Serialize)]
pub struct PoppedTo {
    pub alias: String,
    pub title: String,
    pub counts: Counts,
}

/// The parent `add` filed a node under, when it did not land at the root.
#[derive(Debug, Clone, serde::Serialize)]
pub struct AddedUnder {
    pub alias: String,
    pub title: String,
}

/// The parent `promote` leaves behind. Provenance does not move: the node
/// promoted is still born from here, only its rank changed (`d33`'s sibling
/// rule for goals).
#[derive(Debug, Clone, serde::Serialize)]
pub struct StillBornFrom {
    pub alias: String,
    pub title: String,
}

/// A node `abandon` saved out of the fall, still born where it was.
#[derive(Debug, Clone, serde::Serialize)]
pub struct RescuedNode {
    pub alias: String,
    pub title: String,
}

/// The decision `decide --supersedes` retires.
#[derive(Debug, Clone, serde::Serialize)]
pub struct SupersededNode {
    pub alias: String,
}

/// The two shapes `flag` can leave: cleared, or raised with the reason that
/// justified it. `BRIEF-SPEC.md` §10 makes the reason mandatory on the way in;
/// this is what comes back out.
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "change")]
pub enum FlagChange {
    Off,
    Raised { title: String, reason: String },
}

/// The two shapes `arm` can leave, mirroring `FlagChange`: `d415`.
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "change")]
pub enum ArmChange {
    Added,
    Removed,
}

/// One declaration `declare` recorded: the pillar or rule's own alias and
/// the sentence on how the decision holds against it. `t426` §2.2.
#[derive(Debug, Clone, serde::Serialize)]
pub struct DeclaredPair {
    pub node: String,
    pub why: String,
}

/// `false` is never serialized: otherwise `d445`'s `no_against` would
/// change the JSON of every write that is not a decision, which `t426` §2.3
/// keeps byte for byte what it already was.
fn is_false(b: &bool) -> bool {
    !*b
}

/// A node `restore` cannot put back on the stack, and why: it closed, it was
/// abandoned, or it no longer exists at all.
#[derive(Debug, Clone, serde::Serialize)]
pub struct LostNode {
    pub alias: String,
    pub title: String,
    /// Already resolved to a word (`n.state.word(n.kind)`, or the literal
    /// `"gone"`): there is no live node left to ask, past this point, for a
    /// node that no longer resolves at all.
    pub state: String,
}

/// A node `restore` keeps on the rebuilt path even though it is not open:
/// `t533` §2.3. Same shape as [`LostNode`], because both name a node and the
/// word for the state it is in -- the difference is which one still counts
/// as part of the stack.
#[derive(Debug, Clone, serde::Serialize)]
pub struct KeptNode {
    pub alias: String,
    pub title: String,
    pub state: String,
}

/// One path that changed since a vivac's anchor, and how many times.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ChangeLine {
    pub file_path: String,
    pub times: usize,
}

/// The three shapes `restore`'s diff can take. Which one applies is a fact
/// about the anchor and the repository, decided once by the operation; the
/// render only knows how to say each of the three.
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "anchor")]
pub enum RestoreAnchor {
    /// `Null`: there was never anything to diff against (`MODEL.md` §8).
    Empty,
    NoChanges {
        anchor_short: String,
    },
    Changed {
        anchor_short: String,
        changes: Vec<ChangeLine>,
        /// The `governs` globs the stack declared at save time. Empty unless
        /// something on it declared one, and that is what decides whether
        /// the "touch what the stack governed" count is worth saying at all.
        working_set: Vec<String>,
    },
}

/// What a write handed back, instead of a line on a terminal.
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "op")]
pub enum Outcome {
    Pushed {
        alias: String,
        title: String,
        blocks: bool,
        advice: Option<DepthAdvice>,
        #[serde(skip_serializing_if = "is_false")]
        no_against: bool,
        /// `--root` (`t533` §1.4): the aliases that left the stack, bottom to
        /// top. Always present; `[]` when nothing left, `--root` or not.
        left_stack: Vec<String>,
        /// The deepest of `left_stack` that is still open or parked, the one
        /// worth naming to get back to. Always present; `null` when nothing
        /// left, or everything that did is closed or abandoned.
        back_to: Option<String>,
    },
    Popped {
        closed: Closed,
        parent: Option<PoppedTo>,
    },
    Done {
        closed: Closed,
    },
    Added {
        alias: String,
        title: String,
        parent: Option<AddedUnder>,
        blocks: bool,
        #[serde(skip_serializing_if = "is_false")]
        no_against: bool,
    },
    Noted {
        alias: String,
    },
    Blocked {
        alias: String,
        blocks: bool,
        parent_alias: String,
        parent_title: String,
    },
    Promoted {
        alias: String,
        title: String,
        parent: Option<StillBornFrom>,
    },
    Abandoned {
        alias: String,
        title: String,
        cascaded: Option<usize>,
        rescued: Vec<RescuedNode>,
    },
    Parked {
        alias: String,
        title: String,
    },
    Focused {
        alias: String,
        revived: bool,
    },
    Flagged {
        alias: String,
        flag: String,
        change: FlagChange,
    },
    Armed {
        alias: String,
        /// The folder the arm runs in, already normalized -- `.` for the
        /// tree's own folder. `d441`: a pair with no folder is exactly what
        /// it retired, so the confirmation shows both halves.
        dir: String,
        arm: String,
        change: ArmChange,
    },
    Decided {
        alias: String,
        title: String,
        superseded: Option<SupersededNode>,
        no_alternatives: bool,
        #[serde(skip_serializing_if = "is_false")]
        no_against: bool,
    },
    /// `declare`'s own write: what a decision was judged against, recorded
    /// after the fact. `t426` §2.2.
    Declared {
        alias: String,
        against: Vec<DeclaredPair>,
    },
    Saved {
        num: u64,
        label: String,
        anchor: AnchorRef,
        /// What the lane's own repositories anchored this stop to. Empty
        /// for a lane that declared none, where `anchor` still answers.
        anchors: Vec<crate::event::RepoAnchor>,
        next: String,
    },
    Restored {
        alias: String,
        kind: String,
        ts: String,
        label: String,
        next_intent: String,
        /// Closed or parked nodes the rebuilt path still runs through:
        /// `t533` §2.3. Always present; `[]` when the whole path is open.
        kept: Vec<KeptNode>,
        lost: Vec<LostNode>,
        anchor: RestoreAnchor,
    },
    /// The end-of-session hook's automatic stop. Silent today, the same way
    /// `auto_vivac` prints nothing: a segment nobody was asked to summarize
    /// is not a place to start inventing prose.
    AutoStopped,
    /// A session opened, for the start hook. Silent for the same reason: the
    /// brief is what the hook actually shows, and this is not it.
    SessionOpened,
}

/// `d445`'s warning: a pillar or a rule judged in silence reads the same
/// as one nobody checked at all, so a decision born while something governs
/// and declaring nothing says so, and says how to fix it. `t426` §2.3.
fn no_against_lines(out: &mut Vec<String>, alias: &str) {
    out.push(
        "        no --against: a pillar judged in silence reads the same as one skipped"
            .to_string(),
    );
    out.push(format!("        vivac declare {alias} adds one"));
}

fn closed_lines(out: &mut Vec<String>, c: &Closed) {
    if let Some(word) = &c.already {
        // `f552` (`t533` §2.2): nothing closed here, so there is nothing to
        // say about `--force` either.
        out.push(format!(
            "  {}  {}  -> already {word}, left as it was",
            c.alias, c.title
        ));
        return;
    }
    out.push(format!(
        "  {}  {}  -> {}",
        c.alias,
        c.title,
        if c.force { "closed BY FORCE" } else { "closed" }
    ));
    if c.force {
        out.push("        recorded as a false close in every render".to_string());
    }
}

/// The `Outcome` as plain text, the way the CLI has always printed it.
///
/// A mirror of `brief::to_text`: the data is already final by the time it
/// gets here, so this only ever formats, never decides.
pub fn to_text(o: &Outcome) -> String {
    let mut lines: Vec<String> = Vec::new();
    match o {
        Outcome::Pushed {
            alias,
            title,
            blocks,
            advice,
            no_against,
            left_stack,
            back_to,
        } => {
            lines.push(format!("  {alias}  {title}"));
            if *blocks {
                lines.push("        blocks its parent from closing".to_string());
            }
            // `--root` (`t533` §1.4): what the stack held before is reported
            // here, right after the node born and what it blocks.
            if let [bottom, .., top] = left_stack.as_slice() {
                lines.push(format!(
                    "        at the root: {} left the stack, {bottom} to {top}, none closed by this",
                    left_stack.len()
                ));
            } else if let [only] = left_stack.as_slice() {
                lines.push(format!(
                    "        at the root: {only} left the stack, not closed by this"
                ));
            }
            if let Some(b) = back_to {
                lines.push(format!("        back there with:  vivac focus {b}"));
            }
            if let Some(a) = advice {
                lines.push(String::new());
                let mark = a
                    .root_mark
                    .as_deref()
                    .map(|w| format!(" [{w}]"))
                    .unwrap_or_default();
                lines.push(format!(
                    "  You are {} levels away from {} \"{}\"{mark}.",
                    a.depth, a.root_alias, a.root_title
                ));
                lines.push("  Is this still a detour, or did the real goal move?".to_string());
                lines.push("  If it moved:  vivac promote".to_string());
            }
            if *no_against {
                no_against_lines(&mut lines, alias);
            }
        }
        Outcome::Popped { closed, parent } => {
            closed_lines(&mut lines, closed);
            match parent {
                Some(p) => {
                    lines.push(format!("  back to {}  {}", p.alias, p.title));
                    let f = p.counts.phrase();
                    if !f.is_empty() {
                        lines.push(format!("        ({f} below it)"));
                    }
                }
                None => lines.push("  empty stack".to_string()),
            }
        }
        Outcome::Done { closed } => closed_lines(&mut lines, closed),
        Outcome::Added {
            alias,
            title,
            parent,
            blocks,
            no_against,
        } => {
            let where_at = match parent {
                Some(p) => format!(" under {}", p.alias),
                None => " (root)".to_string(),
            };
            lines.push(format!("  {alias}  {title}{where_at}"));
            if *blocks {
                lines.push("        blocks its parent from closing".to_string());
            }
            if *no_against {
                no_against_lines(&mut lines, alias);
            }
        }
        Outcome::Noted { alias } => lines.push(format!("  {alias} noted")),
        Outcome::Blocked {
            alias,
            blocks,
            parent_alias,
            parent_title,
        } => {
            let verb = if *blocks {
                "blocks"
            } else {
                "no longer blocks"
            };
            lines.push(format!(
                "  {alias} {verb} the close of {parent_alias}  {parent_title}"
            ));
        }
        Outcome::Promoted {
            alias,
            title,
            parent,
        } => {
            lines.push(format!("  {alias}  {title}  -> a goal of its own"));
            if let Some(p) = parent {
                lines.push(format!("        still born from {}  {}", p.alias, p.title));
            }
        }
        Outcome::Abandoned {
            alias,
            title,
            cascaded,
            rescued,
        } => {
            lines.push(format!("  {alias}  {title}  -> abandoned"));
            if let Some(n) = cascaded {
                lines.push(format!("        and {n} descendant(s) with it"));
            }
            if !rescued.is_empty() {
                lines.push(String::new());
                lines.push(format!("  Rescued, and still born from {alias}:"));
                for r in rescued {
                    lines.push(format!("      {:<6} {}", r.alias, r.title));
                }
                lines.push(String::new());
                lines.push(
                    "  Their lineage crosses an abandoned node on purpose: where they".to_string(),
                );
                lines.push("  were born does not change because it got discarded.".to_string());
            }
        }
        Outcome::Parked { alias, title } => {
            lines.push(format!("  {alias}  {title}  -> parked"));
            lines.push("        shows up in:  vivac parked".to_string());
        }
        Outcome::Focused { alias, revived } => {
            if *revived {
                lines.push(format!("  {alias} is open again"));
            }
        }
        Outcome::Flagged {
            alias,
            flag,
            change,
        } => match change {
            FlagChange::Off => lines.push(format!("  {alias}  is no longer {flag}")),
            FlagChange::Raised { title, reason } => {
                lines.push(format!("  {alias}  {title}  -> {flag}"));
                lines.push(format!("        {reason}"));
            }
        },
        Outcome::Armed {
            alias,
            dir,
            arm,
            change,
        } => match change {
            ArmChange::Added => lines.push(format!("  {alias}  armed in {dir}/: {arm}")),
            ArmChange::Removed => {
                lines.push(format!("  {alias}  no longer armed in {dir}/: {arm}"))
            }
        },
        Outcome::Decided {
            alias,
            title,
            superseded,
            no_alternatives,
            no_against,
        } => {
            lines.push(format!("  {alias}  {title}"));
            if let Some(s) = superseded {
                lines.push(format!("        {} becomes superseded", s.alias));
            }
            if *no_alternatives {
                lines.push(
                    "        no alternatives recorded: in a month they get proposed again"
                        .to_string(),
                );
            }
            if *no_against {
                no_against_lines(&mut lines, alias);
            }
        }
        Outcome::Declared { alias, against } => {
            for a in against {
                lines.push(format!("  {alias}  judged against {}: {}", a.node, a.why));
            }
        }
        Outcome::Saved {
            num,
            label,
            anchor,
            anchors,
            next,
        } => {
            let shown = if label.is_empty() { "no label" } else { label };
            lines.push(format!("  v{num}  {shown}"));
            if let Some(a) = crate::model::anchoring(anchor, anchors) {
                lines.push(format!("        anchored to {a}"));
            } else {
                lines.push("        no anchor: there is no version control here".to_string());
            }
            if next.is_empty() {
                lines.push(
                    "        no --next: coming back there will be nothing to pick up".to_string(),
                );
            }
        }
        Outcome::Restored {
            alias,
            kind,
            ts,
            label,
            next_intent,
            kept,
            lost,
            anchor,
        } => {
            lines.push(String::new());
            lines.push(format!(
                "  {alias} · {kind} · {}",
                crate::clock::date_of(ts)
            ));
            if !label.is_empty() {
                lines.push(format!("  {label}"));
            }
            lines.push(String::new());
            if !next_intent.is_empty() {
                lines.push(format!("  you were about to:  {next_intent}"));
                lines.push(String::new());
            }
            // `t533` §2.3: closed or parked, but still part of the rebuilt
            // path -- reported apart from what actually left the stack.
            for k in kept {
                lines.push(format!(
                    "  still on the path:  {} {} [{}]",
                    k.alias, k.title, k.state
                ));
            }
            if !kept.is_empty() {
                lines.push(String::new());
            }
            for p in lost {
                lines.push(format!(
                    "  no longer on the stack:  {} {} [{}]",
                    p.alias, p.title, p.state
                ));
            }
            if !lost.is_empty() {
                lines.push(String::new());
            }
            match anchor {
                RestoreAnchor::Empty => {
                    lines.push(
                        "  No anchor: there is no diff to show, only the date above.".to_string(),
                    );
                    lines.push(String::new());
                }
                RestoreAnchor::NoChanges { anchor_short } => {
                    lines.push(format!("  Nothing changed since {anchor_short}."));
                    lines.push(String::new());
                }
                RestoreAnchor::Changed {
                    anchor_short,
                    changes,
                    working_set,
                } => {
                    let touching = changes
                        .iter()
                        .filter(|c| {
                            working_set
                                .iter()
                                .any(|g| crate::glob::covers(g, &c.file_path))
                        })
                        .count();
                    let suffix = if working_set.is_empty() {
                        String::new()
                    } else {
                        format!(", {touching} of them touch what the stack governed")
                    };
                    lines.push(format!(
                        "  {} changes since {anchor_short}{suffix}",
                        changes.len()
                    ));
                    for c in changes.iter().take(6) {
                        lines.push(format!("      {:<52} ({})", c.file_path, c.times));
                    }
                    if changes.len() > 6 {
                        lines.push(format!("      ... and {} more", changes.len() - 6));
                    }
                    lines.push(String::new());
                }
            }
        }
        // Neither hook op has ever printed anything: both fire from a Claude
        // Code hook, never from a terminal, so there is nobody to tell.
        Outcome::AutoStopped | Outcome::SessionOpened => {}
    }
    // `Outcome::Focused { revived: false, .. }` and the two hook outcomes
    // just above are the shapes with nothing to say: the CLI printed no
    // line at all for them, and an empty `Vec` here has to come out as an
    // empty string and not as a single blank line.
    if lines.is_empty() {
        return String::new();
    }
    let mut s = lines.join("\n");
    s.push('\n');
    s
}