clustervision 0.19.2

clustervision CLI — search, read, and port AI coding-agent sessions across harnesses.
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
//! `cv workflow` — first-class workflow runs: the phase tree, the agents grouped under each
//! phase with their outcomes, the run totals, the driving script, and `--revive` (per-lane resume
//! prompts mined from the transcripts of a run that died).

use crate::util::{fmt_duration, fmt_int, short_id, Wait};
use anyhow::{bail, Context, Result};
use cv_core::ir::truncate;

/// `cv workflow <session> [run]`: render one workflow run richly — its phases, the agents grouped
/// under each phase with their outcomes, the run totals, the aggregated result, and (optionally)
/// the driving script. Without a `run`, lists every workflow the session launched. Both arguments
/// accept **names**: `run` matches a workflow name (exact, else unique prefix) as well as a run id,
/// and when `<session>` matches no session id it's resolved as a workflow name across the whole
/// catalog — session titles are auto-generated and rarely mention the workflow you remember.
pub(crate) struct WorkflowArgs<'a> {
    pub id: &'a str,
    pub run_id: Option<String>,
    pub harness: Option<String>,
    pub json: bool,
    pub script: bool,
    pub results: bool,
    pub follow: bool,
    pub for_: Option<String>,
    pub revive: bool,
    pub revive_all: bool,
}

/// How a run renders: `cv workflow`'s output flags, named once at the command boundary.
#[derive(Clone, Copy)]
struct Render {
    json: bool,
    script: bool,
    results: bool,
    revive: bool,
    revive_all: bool,
}

pub(crate) fn cmd_workflow(args: WorkflowArgs<'_>) -> Result<()> {
    let WorkflowArgs {
        id,
        run_id,
        harness,
        json,
        script,
        results,
        follow,
        for_,
        revive,
        revive_all,
    } = args;
    // Flags that act on one run: a command that lists instead of rendering a run refuses them.
    let run_flags: Vec<&str> = [
        ("--script", script),
        ("--results", results),
        ("--follow", follow),
        ("--for", for_.is_some()),
        ("--revive", revive),
        ("--revive-all", revive_all),
    ]
    .into_iter()
    .filter_map(|(name, set)| set.then_some(name))
    .collect();
    let render = Render {
        json,
        script,
        results,
        revive,
        revive_all,
    };
    let (want, id) = crate::util::split_harness_id(id, crate::util::parse_harness(&harness)?);
    // find_cheap: don't pay a full fleet re-discovery before trying the id as a workflow name —
    // the name path escalates to a full `find` itself once every cheaper reading has missed.
    let found = match cv_core::find_cheap(id, want) {
        Ok(found) => found,
        // An ambiguous prefix: the candidate lines, exit 2.
        Err(e) => return crate::util::resolve_found(Err(e), id, want).map(|_| ()),
    };
    let Some((r, _adapter)) = found else {
        // Not a session id → maybe it's a workflow name ("the stark-kill session" problem).
        return workflow_by_name_fleetwide(id, want, render, &run_flags);
    };

    // No run id → list the session's workflows (a directory of runs).
    let Some(run_id) = run_id else {
        refuse_run_flags(&run_flags, "a session's run list")?;
        return list_workflows(&r, json);
    };

    if follow || for_.is_some() {
        return follow_workflow(&r, &run_id, render, Wait::resolve(true, for_.as_deref())?);
    }

    let mut wf = cv_core::workflow_of(&r, &run_id).with_context(|| {
        let runs = cv_core::workflows_of(&r);
        let names: Vec<&str> = runs.iter().filter_map(|w| w.name.as_deref()).collect();
        format!(
            "no workflow {run_id:?} in {} — {} run(s): {}",
            short_id(&r.id),
            runs.len(),
            if names.is_empty() {
                "(unnamed)".into()
            } else {
                names.join(", ")
            },
        )
    })?;
    wf.attach_journal(&r.path);
    emit_workflow(&wf, render, Some(r.path.as_path()))
}

/// A flag that acts on one run, given where there is no single run to act on: a usage error, not a
/// silently different command.
fn refuse_run_flags(flags: &[&str], listing: &str) -> Result<()> {
    match flags {
        [] => Ok(()),
        _ => crate::util::usage(format!(
            "{} act on one run, but this prints {listing}; name the run: `cv workflow <session> <run_id> …`",
            flags.join(", ")
        )),
    }
}

/// Recorded states share glyphs; callers choose the marker for an unrecorded state.
fn state_glyph(state: Option<&str>, fallback: &'static str) -> &'static str {
    match state {
        Some("done") => "✓",
        Some("error") => "✗",
        Some("progress") => "…",
        Some("start") => "▸",
        _ => fallback,
    }
}

/// `--follow`: poll the run's state file (the harness flushes it as agents progress) and stream
/// agent state TRANSITIONS as feed lines — `12:03:41  ✓ verify:merkle → done (312,004 tok)` —
/// then, when the run reaches a terminal status or `--for` elapses, emit the full render (honoring
/// `--json`/`--script`/`--results`). Waits for the state file if the run hasn't registered yet.
fn follow_workflow(r: &cv_core::SessionRef, key: &str, render: Render, wait: Wait) -> Result<()> {
    use std::collections::HashMap;
    let mut seen: HashMap<u64, String> = HashMap::new(); // agent index → last printed state
    wait.announce("workflow", &format!("run {key:?}"));
    loop {
        let Some(wf) = cv_core::workflow_of(r, key) else {
            if !wait.pause(std::time::Duration::from_secs(2)) {
                eprintln!("cv workflow: run {key:?} never registered");
                return Ok(());
            }
            continue;
        };
        let now = crate::util::fmt_local(chrono::Utc::now(), "%H:%M:%S");
        for a in wf.phases.iter().flat_map(|p| &p.agents).chain(&wf.orphan_agents) {
            let state = a.state.clone().unwrap_or_default();
            if seen.get(&a.index).is_some_and(|s| *s == state) {
                continue;
            }
            seen.insert(a.index, state.clone());
            let glyph = state_glyph(Some(&state), "▸");
            let tok = a.tokens.map(|t| format!(" ({} tok)", fmt_int(t))).unwrap_or_default();
            let line = format!(
                "{now}  {glyph} {} → {state}{tok}",
                a.label.as_deref().unwrap_or("(agent)")
            );
            if render.json {
                eprintln!("{line}");
            } else {
                println!("{line}");
            }
        }
        let live = matches!(wf.status.as_deref(), None | Some("running") | Some("started"));
        if live && wait.pause(std::time::Duration::from_secs(2)) {
            continue;
        }
        let status = wf.status.as_deref().unwrap_or("?");
        let banner = if live {
            format!("\n── --for elapsed, run still {status} ──\n")
        } else {
            format!("\n── run reached {status} ──\n")
        };
        if render.json {
            eprintln!("{banner}");
        } else {
            println!("{banner}");
        }
        let mut wf = wf;
        wf.attach_journal(&r.path);
        let render = Render {
            revive: false,
            revive_all: false,
            ..render
        };
        return emit_workflow(&wf, render, Some(r.path.as_path()));
    }
}

/// Shared single-run output: `--json` gets the full structure (journal results included);
/// otherwise the rendered view, with `--results` appending each agent's full journaled return.
fn emit_workflow(wf: &cv_core::Workflow, render: Render, session_path: Option<&std::path::Path>) -> Result<()> {
    let Render {
        json,
        script,
        results,
        revive,
        revive_all,
    } = render;
    if revive {
        return render_revive(wf, revive_all, session_path);
    }
    if json {
        println!("{}", serde_json::to_string_pretty(wf)?);
        return Ok(());
    }
    render_workflow(wf, script)?;
    if results {
        render_journal_results(wf);
    } else if wf
        .phases
        .iter()
        .flat_map(|p| &p.agents)
        .chain(&wf.orphan_agents)
        .any(|a| a.journal_result.is_some())
    {
        println!("→ `--results` for each agent's FULL journaled return (previews above are ~400 chars)");
    }
    Ok(())
}

/// The `--results` tail: every agent's FULL journaled return value, pretty-printed.
fn render_journal_results(w: &cv_core::Workflow) {
    let agents: Vec<&cv_core::WorkflowAgent> = w
        .phases
        .iter()
        .flat_map(|p| &p.agents)
        .chain(&w.orphan_agents)
        .filter(|a| a.journal_result.is_some())
        .collect();
    if agents.is_empty() {
        println!("\n(no journaled per-agent results — the run's journal is absent or empty)");
        return;
    }
    println!("\n## full per-agent returns ({} journaled)", agents.len());
    for a in agents {
        println!(
            "\n### {}  {}",
            a.label.as_deref().unwrap_or("(agent)"),
            a.agent_id.as_deref().map(short_id).unwrap_or_default(),
        );
        let r = a.journal_result.as_ref().unwrap();
        println!("{}", serde_json::to_string_pretty(r).unwrap_or_else(|_| r.to_string()));
    }
}

/// Resolve a bare `cv workflow <name>` against every session's workflow runs. One hit renders it;
/// several list themselves with ready-to-paste commands. A miss falls through to a ghost-launch
/// scan — a name with no recorded run anywhere may still be a launch whose state was never
/// persisted (crash/power loss), and that is precisely when someone hunts it by name.
fn workflow_by_name_fleetwide(
    name: &str,
    want: Option<cv_core::ir::Harness>,
    render: Render,
    run_flags: &[&str],
) -> Result<()> {
    let hits = cv_core::find_workflows_by_name(name);
    if hits.is_empty() {
        let ghosts = cv_core::find_ghost_launches_by_name(name);
        if ghosts.is_empty() {
            // Very last reading: a session id living in the discovery probe's blind spots (what
            // the full `find` covers and `find_cheap` deliberately skipped).
            match cv_core::find(name, want) {
                Ok(Some((r, _adapter))) => {
                    refuse_run_flags(run_flags, "a session's run list")?;
                    return list_workflows(&r, render.json);
                }
                Ok(None) => {}
                Err(e) => return crate::util::resolve_found(Err(e), name, want).map(|_| ()),
            }
        } else {
            refuse_run_flags(run_flags, "ghost launches")?;
            if render.json {
                let ghost_list: Vec<_> = ghosts.iter().map(|(_, g)| g).collect();
                let sessions: Vec<_> = ghosts.iter().map(|(r, _)| &r.id).collect();
                println!(
                    "{}",
                    serde_json::to_string_pretty(
                        &serde_json::json!({"runs": [], "ghost_launches": ghost_list, "sessions": sessions})
                    )?
                );
                return Ok(());
            }
            println!(
                "no recorded run named {name:?} — but {} GHOST launch(es) match (state never persisted; crash/kill before write?):\n",
                ghosts.len()
            );
            for (r, g) in &ghosts {
                println!(
                    "   {} — session {} ({})",
                    ghost_line(g),
                    short_id(&r.id),
                    r.title.as_deref().unwrap_or("untitled"),
                );
            }
            println!("\n→ debris dirs live under the session dir's subagents/workflows/<runId>/ (`cv show <agent-id>` opens a transcript)");
            return Ok(());
        }
        bail!("no session and no workflow name matching {name:?} (try `cv ls -q 'workflow:{name}'`)");
    }
    if hits.len() == 1 {
        // One run: `--follow`/`--for` need the session-and-run form that can poll its state file.
        if run_flags.iter().any(|f| matches!(*f, "--follow" | "--for")) {
            return crate::util::usage(format!(
                "--follow/--for need the run named by session: `cv workflow {} {} --follow`",
                short_id(&hits[0].0.id),
                hits[0].1.run_id
            ));
        }
        let (r, wf) = &hits[0];
        let mut wf = wf.clone();
        wf.attach_journal(&r.path);
        if !render.json {
            println!(
                "(in session {} — {})\n",
                short_id(&r.id),
                r.title.as_deref().unwrap_or("untitled")
            );
        }
        return emit_workflow(&wf, render, Some(r.path.as_path()));
    }
    refuse_run_flags(run_flags, "the runs matching a name")?;
    if render.json {
        let runs: Vec<_> = hits.iter().map(|(_, w)| w).collect();
        let sessions: Vec<_> = hits.iter().map(|(r, _)| &r.id).collect();
        println!(
            "{}",
            serde_json::to_string_pretty(
                &serde_json::json!({"runs": runs, "ghost_launches": [], "sessions": sessions})
            )?
        );
        return Ok(());
    }
    println!("# {} workflow run(s) matching {name:?}:\n", hits.len());
    for (r, w) in &hits {
        println!(
            "cv workflow {} {}   # {} · {} · {} agent(s)",
            short_id(&r.id),
            w.run_id,
            w.name.as_deref().unwrap_or("(unnamed)"),
            w.status.as_deref().unwrap_or("?"),
            w.agent_count,
        );
    }
    Ok(())
}

/// List every workflow run a session launched, newest first — name, status, phase/agent counts,
/// and the run summary — plus any **ghost launches**: `Workflow` invocations visible in the
/// transcript whose run state was never persisted (a crash / power loss / hard kill before the
/// harness wrote `workflows/wf_*.json`). Without the ghost check, a run that died at launch is
/// simply invisible here — exactly the run whose debris most needs finding.
fn list_workflows(r: &cv_core::SessionRef, json: bool) -> Result<()> {
    let runs = cv_core::workflows_of(r);
    let ghosts = cv_core::workflow_ghosts_of(r);
    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({"runs": runs, "ghost_launches": ghosts}))?
        );
        return Ok(());
    }
    if runs.is_empty() && ghosts.is_empty() {
        println!("no workflows launched by {}", short_id(&r.id));
        return Ok(());
    }
    if runs.is_empty() {
        println!("# 0 recorded workflow(s) in {}", short_id(&r.id));
    } else {
        println!("# {} workflow(s) in {}\n", runs.len(), short_id(&r.id));
    }
    for w in &runs {
        let status = w.status.as_deref().unwrap_or("?");
        let states = w.state_counts();
        let state_str = if states.is_empty() {
            String::new()
        } else {
            let parts: Vec<String> = states.iter().map(|(k, n)| format!("{n} {k}")).collect();
            format!("  [{}]", parts.join(", "))
        };
        println!(
            "{}  {}  {} · {} phase(s) · {} agent(s){}",
            w.run_id,
            w.name.as_deref().unwrap_or("(unnamed)"),
            status,
            w.phases.len(),
            w.agent_count,
            state_str,
        );
        if let Some(s) = &w.summary {
            println!("    {}", truncate(s, 120));
        }
    }
    if !ghosts.is_empty() {
        println!(
            "\n⚠ {} launch(es) with NO recorded run — state never persisted (crash/kill before write?):",
            ghosts.len()
        );
        for g in &ghosts {
            println!("   {}", ghost_line(g));
        }
        println!("   → debris dirs live under the session dir's subagents/workflows/<runId>/ (`cv show <agent-id>` opens a transcript)");
    }
    println!("\n→ `cv workflow {} <runId>` for one run's phase tree", short_id(&r.id));
    Ok(())
}

/// One ghost launch, with everything the crash left behind: launch time, the run id recovered
/// from its orphaned script file, and the debris counts (agent transcripts + journaled results).
fn ghost_line(g: &cv_core::WorkflowLaunch) -> String {
    let when =
        g.ts.map(|t| crate::util::fmt_local(t, "%Y-%m-%d %H:%M"))
            .unwrap_or_else(|| "(no timestamp)".into());
    let mut line = format!("{}  launched {when}", g.name.as_deref().unwrap_or("(unnamed)"));
    if let Some(rid) = &g.run_id {
        line.push_str(&format!(" · run {rid}"));
    }
    match (g.debris_agents, g.journal_result_count) {
        (Some(0), Some(0)) => line.push_str(" · no debris"),
        (Some(a), Some(j)) => line.push_str(&format!(" · DEBRIS: {a} agent transcript(s), {j} journaled result(s)")),
        _ => {}
    }
    line
}

/// Render one workflow run: header (name/status/totals) → each phase with its agents and outcomes
/// → optionally the driving script.
fn render_workflow(w: &cv_core::Workflow, show_script: bool) -> Result<()> {
    println!(
        "# workflow {}  ({})",
        w.name.as_deref().unwrap_or("(unnamed)"),
        w.run_id
    );
    let dur = w
        .duration_ms
        .map(|ms| format!(" · {}", fmt_duration(ms)))
        .unwrap_or_default();
    let started = w
        .started_at
        .map(|t| format!(" · started {}", crate::util::fmt_local(t, "%Y-%m-%d %H:%M")))
        .unwrap_or_default();
    println!(
        "{} · {} agent(s) · {} phase(s) · {} tokens · {} tool calls{}{}",
        w.status.as_deref().unwrap_or("?"),
        w.agent_count,
        w.phases.len(),
        fmt_int(w.total_tokens),
        fmt_int(w.total_tool_calls),
        dur,
        started,
    );
    if let Some(m) = &w.default_model {
        println!("model: {m}");
    }
    if let Some(t) = &w.task_id {
        println!("task: {t}");
    }
    if let Some(a) = &w.args {
        println!(
            "args: {}",
            cv_core::projection::Head::of_json(cv_core::JsonView::from(a), 200)?
        );
    }
    if let Some(rf) = &w.resume_from {
        println!("resumed from: {rf}");
    }
    if let Some(e) = &w.error {
        println!("⚠ error: {}", truncate(e, 200));
    }
    if let Some(s) = &w.summary {
        println!("\n{}", truncate(s, 600));
    }

    // The phase tree: phases in order, agents under each with their state + outcome.
    for p in &w.phases {
        let title = p.title.as_deref().unwrap_or("(phase)");
        println!(
            "\n## phase {} · {}{}",
            p.index,
            title,
            p.detail
                .as_deref()
                .map(|d| format!("  — {}", truncate(d, 80)))
                .unwrap_or_default()
        );
        if p.agents.is_empty() {
            println!("   (no agents)");
        }
        for a in &p.agents {
            render_workflow_agent(a);
        }
    }
    if !w.orphan_agents.is_empty() {
        println!("\n## (agents with no matching phase)");
        for a in &w.orphan_agents {
            render_workflow_agent(a);
        }
    }

    // The run's own narration: log() lines. Tail-biased — the end is where a run explains how it
    // finished (or what was failing when it stopped).
    if !w.logs.is_empty() {
        const TAIL: usize = 8;
        println!("\n## log ({} line(s))", w.logs.len());
        if w.logs.len() > TAIL {
            println!("   … {} earlier (--json for all)", w.logs.len() - TAIL);
        }
        for l in w.logs.iter().rev().take(TAIL).rev() {
            println!("   {}", truncate(l, 160));
        }
    }

    // The aggregated return value — the harvest payload.
    match &w.result {
        Some(r) => {
            let (preview, truncated) = workflow_result_preview(r)?;
            println!("\n## result");
            if truncated {
                println!("{}\n(truncated — `--json` for the full result)", preview);
            } else {
                println!("{preview}");
            }
        }
        None => println!("\n(no result recorded — the run returned nothing or died before finishing)"),
    }

    if show_script {
        match &w.script {
            Some(src) => {
                println!(
                    "\n## script{}",
                    w.script_path
                        .as_ref()
                        .map(|p| format!(" ({})", p.display()))
                        .unwrap_or_default()
                );
                println!("```js\n{src}\n```");
            }
            None => println!("\n(no script recorded)"),
        }
    } else if w.script.is_some() {
        println!("\n→ `--script` to print the driving workflow script");
    }
    Ok(())
}

fn workflow_result_preview(value: &serde_json::Value) -> Result<(String, bool)> {
    // A Unicode scalar occupies at most four UTF8 bytes: this includes the 2001st scalar
    // needed to preserve truncate's exact ellipsis, without serializing an oversized tail.
    let (head, stopped) = cv_core::JsonView::from(value).pretty_prefix(4 * 2001)?;
    let truncated = stopped || head.len() > 2000;
    Ok((if truncated { truncate(&head, 2000) } else { head }, truncated))
}

/// One agent line inside a workflow's phase tree: state glyph, label, id, telemetry, and the head
/// of its result.
fn render_workflow_agent(a: &cv_core::WorkflowAgent) {
    let glyph = state_glyph(a.state.as_deref(), "•");
    let id = a.agent_id.as_deref().map(short_id).unwrap_or_else(|| "—".into());
    let label = a.label.as_deref().unwrap_or("(agent)");
    let mut tele = Vec::new();
    if let Some(t) = a.tokens {
        tele.push(format!("{} tok", fmt_int(t)));
    }
    if let Some(tc) = a.tool_calls {
        tele.push(format!("{tc} calls"));
    }
    if let Some(ms) = a.duration_ms {
        tele.push(fmt_duration(ms));
    }
    if a.cached {
        tele.push("cached".into());
    }
    if let Some(n) = a.attempt.filter(|n| *n > 1) {
        tele.push(format!("attempt {n}"));
    }
    let tele = if tele.is_empty() {
        String::new()
    } else {
        format!("  ({})", tele.join(", "))
    };
    println!("   {glyph} {label}  {id}{tele}");
    if let Some(e) = &a.error {
        println!("       ✗ {}", truncate(e, 120));
    }
    // A non-terminal agent (crash/kill/interrupt) — show where it was when last alive.
    if !matches!(a.state.as_deref(), Some("done")) {
        if let Some(tool) = &a.last_tool_name {
            let when = a
                .last_progress_at
                .map(|t| format!(" @ {}", crate::util::fmt_local(t, "%m-%d %H:%M")))
                .unwrap_or_default();
            println!(
                "       ↪ last: {tool} · {}{when}",
                a.last_tool_summary
                    .as_deref()
                    .map(|s| truncate(s, 100))
                    .unwrap_or_default(),
            );
        }
    }
    if let Some(rp) = &a.result_preview {
        println!("       ↩ {}", truncate(rp, 200));
    }
}

// ---------- --revive ----------

/// One lane's salvageable state: the task it was given, and what it managed to do first.
struct Revivable {
    label: String,
    agent_id: Option<String>,
    phase: u64,
    state: String,
    error: Option<String>,
    tokens: u64,
    tool_calls: u64,
    /// The FULL prompt the orchestrator handed the lane (not the ~400-char preview).
    prompt: Option<String>,
    /// Files the lane wrote or edited before it died — the concrete work worth not redoing.
    files: Vec<String>,
    /// Distinct shell commands it ran, deduped and capped.
    commands: Vec<String>,
    /// The lane's last substantive note to itself, which usually says where it had got to.
    last_note: Option<String>,
    /// Why mining stopped before the transcript's end: the log above it may be partial.
    unread: Option<String>,
}

/// `--revive`: turn a dead or interrupted workflow run into per-lane resume prompts.
///
/// A `Workflow` run that dies mid-flight (an API session limit, a kill, a crash) loses every
/// in-progress lane at once, and the orchestrator's state file keeps only a ~400-char preview of
/// each prompt — so the obvious recovery, re-running the script, restarts every lane from zero and
/// throws away whatever they had already done. That is the expensive failure: our own runs have
/// lost multi-million-token waves this way.
///
/// The lanes' transcripts survive on disk regardless. This mines each one for the full original
/// prompt plus the work it actually landed (files written, commands run, its own last note) and
/// emits a ready-to-paste prompt for a standalone `Agent` — so lanes come back individually,
/// resumed rather than restarted, without needing the workflow runtime at all.
fn render_revive(w: &cv_core::Workflow, all: bool, session_path: Option<&std::path::Path>) -> Result<()> {
    let agents: Vec<&cv_core::WorkflowAgent> = w
        .phases
        .iter()
        .flat_map(|p| &p.agents)
        .chain(&w.orphan_agents)
        .filter(|a| all || a.state.as_deref() != Some("done"))
        .collect();

    if agents.is_empty() {
        println!(
            "no revivable lanes in {} (every agent completed; `--revive --all` to include them)",
            w.run_id
        );
        return Ok(());
    }

    println!("# revive {} — {} lane(s)", w.run_id, agents.len());
    if let Some(e) = &w.error {
        println!("run died: {}", truncate(e, 160));
    }
    println!(
        "\nEach block below is a standalone Agent prompt. The lane's own transcript supplied the\n\
         full task; the work log is mined from its tool calls so the revived lane does not redo it.\n"
    );

    for a in agents {
        let rev = mine_lane(a, &w.run_id, session_path);
        print_revive_block(&rev);
    }
    Ok(())
}

/// Pull one lane's full prompt and work log out of its own transcript.
///
/// Resolved by PATH, not by id lookup: a workflow lane's transcript always lives at
/// `<session>/subagents/workflows/<run_id>/agent-<id>.jsonl`, and we already know all three parts.
/// Going through the fleet-wide id resolver instead silently returns nothing for these — which is
/// how the first cut of this command ended up emitting truncated previews and empty work logs.
fn mine_lane(a: &cv_core::WorkflowAgent, run_id: &str, session_path: Option<&std::path::Path>) -> Revivable {
    let mut rev = Revivable {
        label: a.label.clone().unwrap_or_else(|| format!("agent#{}", a.index)),
        agent_id: a.agent_id.clone(),
        phase: a.phase_index,
        state: a.state.clone().unwrap_or_else(|| "unknown".into()),
        error: a.error.clone(),
        tokens: a.tokens.unwrap_or(0),
        tool_calls: a.tool_calls.unwrap_or(0),
        // Fall back to the ~400-char preview only if the transcript is genuinely unreadable.
        prompt: a.prompt_preview.clone(),
        files: Vec::new(),
        commands: Vec::new(),
        last_note: None,
        unread: None,
    };

    let (Some(id), Some(sp)) = (a.agent_id.as_deref(), session_path) else {
        return rev;
    };
    let Some(dir) = cv_core::harness::claude::sidecar::workflow_run_dir(sp, run_id) else {
        return rev;
    };
    let bare = id.strip_prefix("agent-").unwrap_or(id);
    let path = dir.join(format!("agent-{bare}.jsonl"));
    apply(cv_core::LaneWork::mine(&path), &mut rev);
    rev
}

/// The transcript-mining half of [`mine_lane`]: what the lane's transcript shows it did. A
/// mined prompt replaces the preview; with none, the preview stands.
fn apply(work: cv_core::LaneWork, rev: &mut Revivable) {
    if work.prompt.is_some() {
        rev.prompt = work.prompt;
    }
    rev.files = work.files;
    rev.commands = work.commands;
    rev.last_note = work.last_note;
    rev.unread = work.unread;
}

#[cfg(test)]
fn mine_transcript(text: &str, rev: &mut Revivable) {
    apply(cv_core::LaneWork::mine_bytes(text.as_bytes()), rev);
}

fn print_revive_block(rev: &Revivable) {
    println!("\n{}", "=".repeat(78));
    println!("## lane: {}", rev.label);
    print!(
        "state={} phase={} tokens={} tools={}",
        rev.state,
        rev.phase,
        fmt_int(rev.tokens),
        fmt_int(rev.tool_calls)
    );
    if let Some(id) = &rev.agent_id {
        print!(" agent={}", short_id(id));
    }
    println!();
    if let Some(e) = &rev.error {
        println!("died: {}", truncate(e, 200));
    }
    if let Some(why) = &rev.unread {
        println!(
            "transcript read stopped early (the work log may be partial): {}",
            truncate(why, 200)
        );
    }
    if rev.prompt.is_none() {
        println!("\n(no prompt recoverable — neither transcript nor preview; re-issue by hand)");
        return;
    }

    // The work log only earns its place when the lane actually did something.
    let did_work = !rev.files.is_empty() || !rev.commands.is_empty();
    println!("\n--- 8< --- paste the block below as an Agent prompt --- 8< ---\n");
    println!("{}", rev.prompt.as_deref().unwrap_or_default());

    if did_work {
        println!(
            "\n\n--- RESUMING AN INTERRUPTED RUN ---\n\
             A previous run of this exact lane was cut short ({}) after {} tool calls. Its work is\n\
             still on disk. Do NOT start over — verify what is listed below, then continue from there.",
            rev.error
                .as_deref()
                .map(|e| truncate(e, 90))
                .unwrap_or_else(|| rev.state.clone()),
            fmt_int(rev.tool_calls),
        );
        if !rev.files.is_empty() {
            println!("\nFiles it already wrote or edited ({}):", rev.files.len());
            for f in rev.files.iter().take(40) {
                println!("  {}", f);
            }
            if rev.files.len() > 40 {
                println!("  … and {} more", rev.files.len() - 40);
            }
        }
        if !rev.commands.is_empty() {
            println!("\nCommands it ran ({} distinct, first 15):", rev.commands.len());
            for c in rev.commands.iter().take(15) {
                println!("  $ {}", c);
            }
        }
        if let Some(note) = &rev.last_note {
            println!(
                "\nIts own last note, which usually says where it had got to:\n{}",
                truncate(note, 900)
            );
        }
        println!("\n--- END RESUME CONTEXT ---");
    }
    println!("\n--- >8 --- end prompt --- >8 ---");
}

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

    #[test]
    fn bounded_workflow_result_preview_preserves_old_byte_threshold_and_character_cut() {
        for size in [0, 499, 500, 501, 1998, 1999, 2000, 2001, 100000] {
            for text in ["x", "🌙", "\"\\\n"] {
                let value = serde_json::json!({"nested":[{},[],text.repeat(size)], "after":true});
                let old = serde_json::to_string_pretty(&value).unwrap();
                let truncated = old.len() > 2000;
                let expected = if truncated { truncate(&old, 2000) } else { old };
                assert_eq!(workflow_result_preview(&value).unwrap(), (expected, truncated));
                let args = cv_core::projection::Head::of_json(cv_core::JsonView::from(&value), 200).unwrap();
                assert_eq!(args, truncate(&value.to_string(), 200));
            }
        }
    }

    #[test]
    fn revive_reader_recovers_valid_records_after_corrupt_utf8_and_large_ignored_results() {
        let mut input = Vec::new();
        input.extend_from_slice(b"invalid-json\n\xff\n");
        let prompt = serde_json::json!({"message":{"role":"user","content":"full task"}});
        let ignored = serde_json::json!({"message":{"role":"user","content":[{"type":"tool_result","content":"x".repeat(1100000)}]}});
        let write = serde_json::json!({"message":{"role":"assistant","content":[{"type":"tool_use","name":"Write","input":{"file_path":"recovered.rs"}}]}});
        for value in [prompt, ignored, write] {
            input.extend_from_slice(format!("{value}\n").as_bytes());
        }
        let mut rev = Revivable {
            label: "reader".into(),
            agent_id: None,
            phase: 0,
            state: "error".into(),
            error: None,
            tokens: 0,
            tool_calls: 0,
            prompt: Some("preview".into()),
            files: vec![],
            commands: vec![],
            last_note: None,
            unread: None,
        };
        apply(cv_core::LaneWork::mine_bytes(&input), &mut rev);
        assert_eq!(rev.prompt.as_deref(), Some("full task"));
        assert_eq!(rev.files, vec!["recovered.rs"]);
    }

    #[test]
    fn revive_mines_prompt_files_commands_and_last_note() {
        let lines = [
            r#"{"type":"user","message":{"role":"user","content":"Full lane task: implement the widget end to end."}}"#,
            r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Starting; I will scaffold first and then wire the tests, keeping the public surface unchanged for now."},{"type":"tool_use","name":"Write","input":{"file_path":"/repo/src/widget.rs","content":"..."}}]}}"#,
            r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"ok"}]}}"#,
            r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","name":"Bash","input":{"command":"cargo test -p widget\necho done"}},{"type":"tool_use","name":"Edit","input":{"file_path":"/repo/src/widget.rs"}},{"type":"tool_use","name":"Bash","input":{"command":"cargo test -p widget"}}]}}"#,
            r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Scaffold and tests landed in widget.rs; the remaining piece is the CLI flag, which I had not started when interrupted."}]}}"#,
        ]
        .join("\n");
        let mut rev = Revivable {
            label: "widget".into(),
            agent_id: Some("agent-1".into()),
            phase: 0,
            state: "error".into(),
            error: Some("session limit".into()),
            tokens: 0,
            tool_calls: 4,
            prompt: Some("Full lane task: impl…".into()), // the ~400-char preview, to be replaced
            files: vec![],
            commands: vec![],
            last_note: None,
            unread: None,
        };
        mine_transcript(&lines, &mut rev);
        assert_eq!(
            rev.prompt.as_deref(),
            Some("Full lane task: implement the widget end to end."),
            "the FULL first user prompt replaces the preview"
        );
        assert_eq!(
            rev.files,
            vec!["/repo/src/widget.rs"],
            "Write + Edit of one file dedupe"
        );
        assert_eq!(rev.commands, vec!["cargo test -p widget"], "first line only, deduped");
        assert!(rev
            .last_note
            .as_deref()
            .is_some_and(|n| n.starts_with("Scaffold and tests landed")));
    }
}