vivac 0.15.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
//! `reconcile` — the diff between the tree and the anchor's history.
//!
//! `ROADMAP.md` §7 names the project's principal risk plainly: **that the
//! graph goes stale and starts to lie**. Nothing in the tool contradicts the
//! tree, so a tree that drifts drifts in silence, and a `brief` built on it
//! does not go quiet -- it keeps answering, wrongly, into every session it is
//! injected into. That is the failure mode worth a command of its own.
//!
//! It asks one question: **what changed since the tree last looked, and which
//! of it does no node claim?** The claim is `governs`, the globs a node
//! declares over the files it owns (`MODEL.md` §10).
//!
//! **The interactive menu is not here.** `INTEGRATION.md` §9 draws this as a
//! prompt -- `[t12] [t7] [new] [ignore]` -- and the DX pillar had already
//! settled that one: the CLI comes first, without exception, because the agent
//! writes through it and a feature that lives only in an interactive interface
//! leaves half the users out. So this prints the finding and the command that
//! acts on it, the way `triage` does. The menu can come later, in the TUI,
//! over exactly this data.
//!
//! **Product-wide, not lane-wide.** `f699` found the blind spot: an agent
//! sat in one folder of a product, a change landed in a sibling folder of
//! the *same* product, and every one of `anchors_of`, the working set and
//! this command's own default folder said "this lane" -- truthfully, since
//! that is where the command ran, and uselessly, since nothing said the
//! diff was being read from the wrong folder. This lane still reconciles
//! exactly as it always has; every other lane the registry can still
//! resolve is reconciled too, each against its **own** last stop
//! (`reference`'s own comment says why), so a stray edit in a sibling
//! folder shows up here instead of staying invisible until somebody
//! happens to ask from the right terminal (`d701`).
//!
//! It never writes. Reconciling is a judgement about what the work meant, and
//! the tool does not have it: it can say *nobody claims `src/util/retry.rs`*,
//! and it cannot say which thread that file belongs to.

use crate::anchor::{self, AnchorRef, Change};
use crate::args::Args;
use crate::brief::clip;
use crate::event::{Repo, RepoAnchor};
use crate::failure::R;
use crate::glob;
use crate::model::{Node, Tree, Vivac};
use crate::output::outln;
use crate::registry;
use crate::render::print_json;
use serde_json::json;
use std::path::Path;

/// How many files a section prints before it stops and says how many are left.
/// `--json` is never truncated.
const SHOWN: usize = 20;

/// The extra indent every line of a section gains when it is printed under
/// IN OTHER LANES OF THIS PRODUCT rather than for the lane in view: the
/// lane's own name sits one level under that heading, and its verdict lines
/// sit one level under the name.
const NESTED: &str = "    ";

/// A changed file, and what the tree has to say about it.
struct Verdict<'a> {
    file: String,
    times: usize,
    /// Nodes whose `governs` covers the file, open ones first.
    claimed_by: Vec<&'a Node>,
}

impl Verdict<'_> {
    fn claimed_and_open(&self) -> bool {
        self.claimed_by.iter().any(|n| n.state.is_open())
    }
}

/// A declared repository whose branch is not the one the stop anchored:
/// comparing it to that stop would be a diff across branches, which is
/// inferring whether something merged and is out of scope by `d596`
/// (§4.4). Named, not diffed.
struct Moved {
    path: String,
    from: String,
    to: String,
}

/// Every declared repository's changes, one path-prefixed batch per
/// repository still on the branch the stop anchored, and the
/// repositories that are not (§4.4). A repository the stop never
/// anchored -- declared since, or written by a version before this
/// tranche -- has nothing to compare against and contributes neither.
fn repo_changes(
    declared: &[Repo],
    since_anchors: &[RepoAnchor],
    lane_dir: &Path,
) -> (Vec<Change>, Vec<Moved>) {
    let mut changes = Vec::new();
    let mut moved = Vec::new();
    for repo in declared {
        let Some(entry) = since_anchors.iter().find(|r| r.path == repo.path) else {
            continue;
        };
        let anchor::Where::Head(h) = anchor::where_of(&lane_dir.join(&repo.path)) else {
            continue;
        };
        let differs = match (&entry.branch, &h.branch) {
            (Some(a), Some(b)) => a != b,
            _ => false,
        };
        if differs {
            moved.push(Moved {
                path: repo.path.clone(),
                from: entry.branch.clone().unwrap_or_default(),
                to: h.branch.clone().unwrap_or_default(),
            });
            continue;
        }
        let prefix = if repo.path == "." {
            String::new()
        } else {
            format!("{}/", repo.path)
        };
        let reference = AnchorRef {
            kind: "git".to_string(),
            id: entry.sha.clone(),
        };
        for c in anchor::detect(&lane_dir.join(&repo.path)).changed_since(&reference) {
            changes.push(Change {
                file_path: format!("{prefix}{}", c.file_path),
                times: c.times,
            });
        }
    }
    (changes, moved)
}

fn plural(n: usize, one: &str, many: &str) -> String {
    if n == 1 {
        format!("{n} {one}")
    } else {
        format!("{n} {many}")
    }
}

/// The tool's own store is not work. Without this, every reconcile reports
/// the log it just wrote to. Shared between this lane's own changes and
/// every other lane's, since the store lives under `.vivac/` in every one
/// of them alike.
fn without_store(changes: Vec<Change>) -> Vec<Change> {
    changes
        .into_iter()
        .filter(|c| !c.file_path.replace('\\', "/").starts_with(".vivac/"))
        .collect()
}

/// Every changed file paired with who, if anyone, claims it -- worst
/// offender first, then by path. A file's claim depends only on `governs`,
/// which is one tree-wide fact, so this is the one place that reads it,
/// used for this lane's own changes and for every other lane's alike.
fn verdicts_of<'a>(changes: &[Change], governing: &[&'a Node], a: &'a Tree) -> Vec<Verdict<'a>> {
    let mut verdicts: Vec<Verdict> = changes
        .iter()
        .map(|c| {
            let mut claimed_by: Vec<&Node> = governing
                .iter()
                .filter(|n| n.governs(a).iter().any(|g| glob::covers(g, &c.file_path)))
                .copied()
                .collect();
            claimed_by.sort_by_key(|n| (!n.state.is_open(), n.num));
            Verdict {
                file: c.file_path.clone(),
                times: c.times,
                claimed_by,
            }
        })
        .collect();
    verdicts.sort_by(|x, y| y.times.cmp(&x.times).then_with(|| x.file.cmp(&y.file)));
    verdicts
}

/// The three baskets a set of verdicts sorts into: nobody claims it, only
/// closed work claims it, and open work claims it -- the last of which
/// `print_other_lanes` never shows, only computed here so this stays the
/// one place that decides what "claimed" and "open" mean together.
fn split_baskets<'v, 'a>(
    verdicts: &'v [Verdict<'a>],
) -> (
    Vec<&'v Verdict<'a>>,
    Vec<&'v Verdict<'a>>,
    Vec<&'v Verdict<'a>>,
) {
    let unclaimed = verdicts
        .iter()
        .filter(|v| v.claimed_by.is_empty())
        .collect();
    let stale = verdicts
        .iter()
        .filter(|v| !v.claimed_by.is_empty() && !v.claimed_and_open())
        .collect();
    let live = verdicts.iter().filter(|v| v.claimed_and_open()).collect();
    (unclaimed, stale, live)
}

/// Which stop to measure from: `--since <v>` names any stop the whole tree
/// ever wrote, and stays that way -- naming one by hand is a different
/// question from the default. With no name, the default is *this* lane's
/// own last stop, not the log's: reconciling compares the git of **this**
/// folder against a stop's anchor, and another lane's last stop can point
/// at a commit this checkout does not even have (`t594`). Every other lane
/// reconciled below reads its own last stop the same way, straight off
/// `a.vivacs`, for exactly this reason.
fn reference<'a>(a: &'a Tree, args: &Args) -> Result<Option<&'a Vivac>, crate::failure::Failure> {
    match args.opt("since") {
        Some(s) => a
            .vivac(s)
            .map(Some)
            .ok_or_else(|| crate::failure::Failure::usage(format!("No such vivac: {s}."))),
        None => Ok(a.last_vivac()),
    }
}

/// One other lane's own report: named, and either unreadable from here or
/// carrying at least one file nobody claims (§4.4's own rule -- the report
/// does not grow just because a lane exists).
struct OtherLane<'a> {
    name: &'a str,
    unreadable: bool,
    verdicts: Vec<Verdict<'a>>,
}

/// Every other lane worth a line: declared repositories of its own, a
/// folder the registry can still resolve (or, failing that, named and
/// marked so it can be skipped rather than silently dropped), and -- for
/// the ones that are readable -- at least one file nobody claims since its
/// own last stop.
///
/// `lanes` is `brief::all_lanes`, the same accessor `stack --lanes` reads
/// to name every lane the tree knows of; `registry::lanes_with_missing_folder`
/// is the same check that section marks `(folder gone)` with. Both are
/// reused here rather than reading the registry's own JSON by hand.
///
/// `None` for `store_dir` or the project's own first event leaves this
/// empty rather than guessing: nothing to check another lane's folder
/// against.
fn other_lanes<'a>(
    a: &'a Tree,
    root: &Path,
    current: &str,
    governing: &[&'a Node],
    lanes: &[crate::brief::LaneRow<'a>],
) -> Vec<OtherLane<'a>> {
    let mut out = Vec::new();
    let Some(store_dir) = crate::store::store_dir() else {
        return out;
    };
    let Some(project_id) = crate::store::first_event_id(root) else {
        return out;
    };
    let gone = registry::lanes_with_missing_folder(&store_dir, &project_id);
    for row in lanes {
        if row.id == current {
            continue;
        }
        let declared: &[Repo] = a
            .lanes
            .get(row.id)
            .map(|s| s.repos.as_slice())
            .unwrap_or(&[]);
        if declared.is_empty() {
            continue;
        }
        if gone.iter().any(|g| g == row.id) {
            out.push(OtherLane {
                name: row.name,
                unreadable: true,
                verdicts: Vec::new(),
            });
            continue;
        }
        let Some(folder) = registry::lane_folder(&store_dir, &project_id, row.id) else {
            continue;
        };
        let Some(since) = a.vivacs.iter().rev().find(|v| v.lane == row.id) else {
            continue;
        };
        let (changes, _moved) = repo_changes(declared, &since.anchors, &folder);
        let changes = without_store(changes);
        let verdicts = verdicts_of(&changes, governing, a);
        // Quiet means nothing to report, not "nothing unclaimed": a lane
        // whose changes are all claimed by work that has closed fills the
        // second basket, and dropping it here would have shown less about
        // another lane than the same report shows about this one.
        if verdicts.iter().all(|v| v.claimed_and_open()) {
            continue;
        }
        out.push(OtherLane {
            name: row.name,
            unreadable: false,
            verdicts,
        });
    }
    out
}

/// IN OTHER LANES OF THIS PRODUCT, once for every qualifying lane
/// `other_lanes` found: the same two sections this lane's own report
/// prints -- NOBODY CLAIMS THESE and CLAIMED ONLY BY CLOSED WORK -- nested
/// one level under the lane's own name. Open, claimed work is never shown
/// here: it is not a finding, and a reassurance line per lane is exactly
/// the noise §4.4's own rule rules out.
fn print_other_lanes(others: &[OtherLane]) {
    if others.is_empty() {
        return;
    }
    outln!();
    outln!("  IN OTHER LANES OF THIS PRODUCT");
    for lane in others {
        outln!();
        if lane.unreadable {
            outln!("    {}   folder not readable from here, skipped", lane.name);
            continue;
        }
        outln!("    {}", lane.name);
        let (unclaimed, stale, _live) = split_baskets(&lane.verdicts);
        section(
            "NOBODY CLAIMS THESE",
            "push \"<title>\" --governs <path>",
            &unclaimed,
            |_| String::new(),
            NESTED,
        );
        section(
            "CLAIMED ONLY BY CLOSED WORK",
            "focus <id> --reopen  |  block <id>",
            &stale,
            |v| {
                v.claimed_by
                    .iter()
                    .map(|n| format!("{} [{}]", n.alias(), n.state.word(n.kind)))
                    .collect::<Vec<_>>()
                    .join(" ")
            },
            NESTED,
        );
    }
    outln!();
}

pub fn reconcile(a: &Tree, root: &Path, lane_dir: &Path, args: &Args) -> R {
    let Some(since) = reference(a, args)? else {
        outln!();
        outln!("  No stop to measure from: this tree has no vivacs yet.");
        outln!();
        outln!("      vivac save \"<label>\"");
        outln!();
        return Ok(());
    };

    let here = a.lane();
    let lanes = crate::brief::all_lanes(a);

    // A lane with declared repositories reconciles each of them (§4.4). A
    // lane with none -- every tree nobody has run `setup` in -- keeps
    // reading the single anchor this folder itself is, exactly as before
    // this tranche (`f25`).
    let declared: &[Repo] = a.lanes.get(here).map(|s| s.repos.as_slice()).unwrap_or(&[]);

    let (changes, moved) = if declared.is_empty() {
        if since.anchor.is_empty_tree() {
            outln!();
            outln!(
                "  {} has no anchor, so there is no history to read.",
                since.alias()
            );
            outln!("  Without version control the tree cannot be contradicted; that is");
            outln!("  the floor of the product and not a failure.");
            outln!();
            return Ok(());
        }
        let anchor = anchor::detect(lane_dir);
        (anchor.changed_since(&since.anchor), Vec::new())
    } else {
        repo_changes(declared, &since.anchors, lane_dir)
    };

    let changes = without_store(changes);

    let governing: Vec<&Node> = a
        .nodes_iter()
        .filter(|n| !n.governs(a).is_empty())
        .collect();

    let verdicts = verdicts_of(&changes, &governing, a);
    let (unclaimed, stale, live) = split_baskets(&verdicts);

    if args.has("json") {
        let one = |v: &Verdict, lane: &str| {
            json!({
                "file": v.file,
                "changes": v.times,
                "claimed_by": v.claimed_by.iter().map(|n| json!({
                    "alias": n.alias(),
                    "title": n.title(a),
                    "state": n.state,
                })).collect::<Vec<_>>(),
                "lane": lane,
            })
        };
        let here_name = lanes
            .iter()
            .find(|r| r.id == here)
            .map(|r| r.name)
            .unwrap_or(here);
        let mut unclaimed_json: Vec<_> = unclaimed.iter().map(|v| one(v, here_name)).collect();
        let mut stale_json: Vec<_> = stale.iter().map(|v| one(v, here_name)).collect();
        let mut live_json: Vec<_> = live.iter().map(|v| one(v, here_name)).collect();
        if args.opt("since").is_none() {
            for lane in other_lanes(a, root, here, &governing, &lanes) {
                let (u, s, l) = split_baskets(&lane.verdicts);
                unclaimed_json.extend(u.iter().map(|v| one(v, lane.name)));
                stale_json.extend(s.iter().map(|v| one(v, lane.name)));
                live_json.extend(l.iter().map(|v| one(v, lane.name)));
            }
        }
        return print_json(json!({
            "since": since.alias(),
            "since_ts": since.ts,
            "anchor": since.anchor.short(),
            "anchors": since.anchors,
            "governing_nodes": governing.len(),
            "changed": verdicts.len(),
            "unclaimed": unclaimed_json,
            "claimed_by_closed_work": stale_json,
            "claimed_and_open": live_json,
        }));
    }

    outln!();
    outln!(
        "  RECONCILE - since {} {}, {}",
        since.alias(),
        since.anchor.short(),
        plural(verdicts.len(), "file changed", "files changed")
    );

    for m in &moved {
        outln!();
        outln!("  {}   {} -> {}", m.path, m.from, m.to);
        outln!(
            "    The stop anchored {}, so what changed here belongs to",
            m.from
        );
        outln!("    another branch and not to this stop. Nothing compared.");
    }

    if verdicts.is_empty() {
        outln!();
        if moved.is_empty() {
            outln!("  Nothing changed. The tree and the work agree.");
        }
        outln!();
    } else if governing.is_empty() {
        // The case that will be true of most trees on the first run, and
        // the one where a list of every file is the least useful thing to
        // print. Say the real problem once instead of repeating a symptom
        // per line -- tree-wide, so no other lane has a different answer
        // to add, and this returns rather than going on to one.
        outln!();
        outln!("  No node declares what it governs, so nothing here can be claimed.");
        outln!("  Until some node says which files it owns, this command has nothing");
        outln!("  to compare the work against.");
        outln!();
        outln!("      vivac push \"<title>\" --why \"<reason>\" --governs \"src/auth/**\"");
        outln!();
        return Ok(());
    } else {
        section(
            "NOBODY CLAIMS THESE",
            "push \"<title>\" --governs <path>",
            &unclaimed,
            |_| String::new(),
            "",
        );
        section(
            "CLAIMED ONLY BY CLOSED WORK",
            "focus <id> --reopen  |  block <id>",
            &stale,
            |v| {
                v.claimed_by
                    .iter()
                    .map(|n| format!("{} [{}]", n.alias(), n.state.word(n.kind)))
                    .collect::<Vec<_>>()
                    .join(" ")
            },
            "",
        );

        if args.has("all") {
            section(
                "CLAIMED, AND THE WORK IS OPEN",
                "",
                &live,
                |v| {
                    v.claimed_by
                        .iter()
                        .filter(|n| n.state.is_open())
                        .map(|n| n.alias())
                        .collect::<Vec<_>>()
                        .join(" ")
                },
                "",
            );
        } else if !live.is_empty() {
            outln!();
            outln!(
                "  {} under work that is open, which is what is supposed to happen.  --all",
                plural(live.len(), "file", "files")
            );
        }

        if unclaimed.is_empty() && stale.is_empty() {
            outln!();
            outln!("  Nothing to reconcile.");
        }
        outln!();
    }

    if args.opt("since").is_some() {
        outln!();
        outln!("  Only this lane was measured: --since names one stop, and another lane's");
        outln!("  stop points at commits this folder does not have. Run reconcile with no");
        outln!("  --since to cover every lane.");
        return Ok(());
    }

    print_other_lanes(&other_lanes(a, root, here, &governing, &lanes));
    Ok(())
}

fn section(
    title: &str,
    action: &str,
    rows: &[&Verdict],
    note: impl Fn(&Verdict) -> String,
    indent: &str,
) {
    if rows.is_empty() {
        return;
    }
    outln!();
    outln!(
        "{}",
        format!(
            "{indent}  {} ({}){}{}",
            title,
            rows.len(),
            " ".repeat(38usize.saturating_sub(title.len() + 4)),
            action
        )
        .trim_end()
    );
    for v in rows.iter().take(SHOWN) {
        // Trimmed, because a row with no note would otherwise carry the
        // column padding out to the edge of the line.
        outln!(
            "{}",
            format!(
                "{indent}    {:<44} {:>3}  {}",
                clip(&v.file, 44),
                v.times,
                note(v)
            )
            .trim_end()
        );
    }
    if rows.len() > SHOWN {
        outln!("{indent}    + {} more   --json", rows.len() - SHOWN);
    }
}