dirge-agent 0.7.7

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
use chrono::Datelike;
use compact_str::CompactString;
use crossterm::style::Color;

use crate::cli::Cli;
use crate::config::Config;
use crate::context::ContextFiles;
use crate::session::{MessageRole, Session};
use crate::ui::markdown;
use crate::ui::renderer::Renderer;
use crate::ui::theme;

/// dirge-jhky — derive a one-line preview describing what a
/// session was about, for the `/sessions` listing.
///
/// Order of preference:
/// 1. The Active Task / Goal line from the most recent
///    compaction summary, if any — that's the model's own one-
///    sentence answer to "what is the user trying to do here".
/// 2. The first user message (truncated to `max_chars`). User
///    prompts are typically a clear statement of intent; the
///    last assistant message often isn't.
/// 3. The last message content (truncated). Fall-back when
///    neither of the above applies — e.g., a fresh session with
///    only one assistant turn.
/// 4. Empty string for empty sessions.
///
/// The returned string is at most `max_chars` characters, with a
/// trailing ellipsis when truncation happened. Single line only —
/// newlines are replaced with spaces.
pub fn session_preview(session: &crate::session::Session, max_chars: usize) -> String {
    if session.messages.is_empty() && session.compactions.is_empty() {
        return String::new();
    }
    let raw = compaction_active_task(session)
        .or_else(|| first_user_message(session))
        .or_else(|| last_message_content(session))
        .unwrap_or_default();
    truncate_oneline(&raw, max_chars)
}

/// Extract the "## Active Task" or "## Goal" section's first
/// line from the most recent compaction summary. Returns `None`
/// when there's no compaction or no recognised section.
fn compaction_active_task(session: &crate::session::Session) -> Option<String> {
    let summary = session.compactions.last()?.summary.as_str();
    // Look for a section heading then take its first non-empty
    // content line. Active Task wins over Goal because it
    // identifies what the session is currently doing.
    for heading in ["## Active Task", "## Goal"] {
        if let Some(start) = summary.find(heading) {
            let rest = &summary[start + heading.len()..];
            // Skip blank lines after the heading, return the
            // first content line.
            for line in rest.lines() {
                let t = line.trim();
                if t.is_empty() {
                    continue;
                }
                if t.starts_with('#') {
                    // Hit the next section without finding content.
                    break;
                }
                return Some(t.to_string());
            }
        }
    }
    None
}

fn first_user_message(session: &crate::session::Session) -> Option<String> {
    session
        .messages
        .iter()
        .find(|m| matches!(m.role, MessageRole::User))
        .map(|m| m.content.to_string())
        .filter(|s| !s.is_empty())
}

fn last_message_content(session: &crate::session::Session) -> Option<String> {
    session
        .messages
        .last()
        .map(|m| m.content.to_string())
        .filter(|s| !s.is_empty())
}

fn truncate_oneline(s: &str, max_chars: usize) -> String {
    // Collapse newlines + tabs to spaces so the preview stays
    // single-line. Trim runs of spaces so a wrapped prompt
    // doesn't render with double spaces in the middle.
    let mut collapsed = String::with_capacity(s.len());
    let mut prev_space = false;
    for c in s.chars() {
        let mapped = if c == '\n' || c == '\r' || c == '\t' {
            ' '
        } else {
            c
        };
        if mapped == ' ' {
            if prev_space {
                continue;
            }
            prev_space = true;
        } else {
            prev_space = false;
        }
        collapsed.push(mapped);
    }
    let trimmed = collapsed.trim();
    if trimmed.chars().count() <= max_chars {
        trimmed.to_string()
    } else {
        let prefix: String = trimmed.chars().take(max_chars.saturating_sub(1)).collect();
        format!("{prefix}")
    }
}

pub fn format_time(rfc3339: &str) -> CompactString {
    let dt = chrono::DateTime::parse_from_rfc3339(rfc3339).ok();
    let dt = match dt {
        Some(dt) => dt,
        None => return CompactString::new(rfc3339),
    };
    let local = dt.with_timezone(&chrono::Local);
    let now = chrono::Local::now();
    if local.date_naive() == now.date_naive() {
        CompactString::new(local.format("%H:%M").to_string())
    } else if local.year() == now.year() {
        CompactString::new(local.format("%b %d %H:%M").to_string())
    } else {
        CompactString::new(local.format("%Y-%m-%d %H:%M").to_string())
    }
}

/// Internal finalization nudges (critic / verifier / todo) are injected as
/// user-role messages so the model acts on them, but they are NOT the user's
/// input. If `content` is one of these tagged nudges, return its body with the
/// tag stripped (to be shown under the `<critic>` handle); otherwise `None`.
/// Single source of truth for both the live view (`run_handlers::notices`) and
/// scrollback (`render_session`) [dirge-i75f].
pub(crate) fn finalization_nudge_body(content: &str) -> Option<&str> {
    use crate::agent::agent_loop::{critic::CRITIC_TAG, run::TODO_NUDGE_TAG, verifier::VERIFY_TAG};
    let trimmed = content.trim_start();
    [CRITIC_TAG, VERIFY_TAG, TODO_NUDGE_TAG]
        .into_iter()
        .find_map(|tag| trimmed.strip_prefix(tag).map(str::trim_start))
}

pub fn render_session(
    renderer: &mut Renderer,
    session: &Session,
    cli: &Cli,
    cfg: &Config,
    context: &ContextFiles,
) -> anyhow::Result<()> {
    renderer.clear_content()?;
    let provider = cli.resolve_provider(cfg);
    let config_model = cfg
        .resolve_role(crate::config::ConfigRole::Default)
        .and_then(|(_, e)| e.model);
    let model = if cli.model.is_none() && config_model.is_none() {
        // dirge-j3jd: resolve the alias's provider TYPE so a custom alias
        // doesn't fall back to the OpenRouter default model id.
        compact_str::CompactString::new(crate::provider::default_model_for_alias(
            &provider,
            &cfg.providers_map(),
        ))
    } else {
        cli.resolve_model(cfg)
    };
    // Top padding rows. Without this, when the user scrolls all the
    // way up, the banner's top border `╭───╮` sits pressed against
    // the terminal's top edge, which reads as "cut off." Two blank
    // rows give the eye breathing room above the banner.
    renderer.write_line("", Color::Reset)?;
    renderer.write_line("", Color::Reset)?;
    render_banner(renderer, &provider, &model)?;
    if context.agents.is_some() {
        renderer.write_line("░ loaded AGENTS.md", theme::dim())?;
        renderer.write_line("", Color::Reset)?;
    }
    if !session.compactions.is_empty() {
        renderer.write_line(
            &format!(
                "░ compacted {} times (saved ~{} tokens)",
                session.compactions.len(),
                session
                    .compactions
                    .last()
                    .map(|c| c.token_savings)
                    .unwrap_or(0),
            ),
            theme::dim(),
        )?;
        renderer.write_line("", Color::Reset)?;
    }
    let total = session.messages.len();
    for (idx, msg) in session.messages.iter().enumerate() {
        // IRC-style angle-bracketed handle. All three handles padded
        // to 8 columns so multi-role chats stay visually aligned.
        // Continuation lines are indented to that same width so the
        // handle isn't repeated on every wrap.
        // dirge-i75f: the finalization nudges (critic / verifier / todo) are
        // persisted as User-role messages so the model acts on them, but
        // they're system steering, not user input — render them under the
        // `<critic>` handle/color in scrollback too, matching the live view.
        let nudge_body = if msg.role == MessageRole::User {
            finalization_nudge_body(&msg.content)
        } else {
            None
        };
        let (handle, line_color) = if nudge_body.is_some() {
            ("<critic> ", theme::critic())
        } else {
            match msg.role {
                MessageRole::User => ("<you> ", theme::user()),
                MessageRole::Assistant => ("<dirge> ", theme::agent()),
                MessageRole::System => ("<sys> ", theme::system()),
            }
        };
        // Strip the tag from the displayed body (the handle conveys the role).
        let body: &str = nudge_body.unwrap_or(&msg.content);
        let cont_indent = " ".repeat(handle.chars().count());

        if msg.role == MessageRole::Assistant {
            // Prose first — but only when there's text. A turn that was
            // pure tool calls has empty content; rendering it anyway left
            // a bare `<dirge>` handle with nothing after it on reload.
            if !msg.content.is_empty() {
                // Wrap chat to the same width tool chambers use so chat
                // and chamber blocks line up visually. The 8-col handle
                // prefix is subtracted so wrapped continuation text fits
                // beneath the handle position.
                let max_width = renderer
                    .content_width()
                    .saturating_sub(handle.chars().count() + 1);
                let mut styled = markdown::markdown_to_styled(&msg.content, max_width, line_color);
                for (i, entry) in styled.iter_mut().enumerate() {
                    if i == 0 {
                        entry.text = CompactString::from(format!("{} {}", handle, entry.text));
                    } else {
                        entry.text = CompactString::from(format!("{}{}", cont_indent, entry.text));
                    }
                }
                for entry in styled {
                    renderer.write_line(&entry.text, entry.color)?;
                }
            }
            // Then reconstruct the turn's tool chambers from the persisted
            // calls so reloading a session keeps its edits/bash/reads.
            render_tool_calls_replay(
                renderer,
                &msg.tool_calls,
                cfg.resolve_tool_result_max_chars(),
                cfg.resolve_tool_result_max_lines(),
            )?;
        } else {
            for (i, line) in body.lines().enumerate() {
                let prefix = if i == 0 {
                    handle.to_string()
                } else {
                    cont_indent.clone()
                };
                renderer.write_line(&format!("{} {}", prefix, line), line_color)?;
            }
        }
        // Thin chamber-bar divider between turns. Single character,
        // not a full-width gradient — the bar runs flush against the
        // left margin like an IRC log's timeline.
        if idx + 1 < total {
            renderer.write_line("·", theme::divider())?;
        } else {
            renderer.write_line("", Color::Reset)?;
        }
    }
    Ok(())
}

/// Reconstruct an assistant turn's persisted tool calls as chambers, so a
/// reloaded session shows the edits/bash/reads/results — not just prose.
/// Mirrors the live view by reusing the same `tool_display` rendering
/// (header + collapsed body + chamber bottom). `max_chars`/`max_lines` are
/// the caller's resolved tool-result display caps.
pub(crate) fn render_tool_calls_replay(
    renderer: &mut Renderer,
    tool_calls: &[crate::session::ToolCallEntry],
    max_chars: usize,
    max_lines: usize,
) -> anyhow::Result<()> {
    use crate::session::ToolCallState;
    use crate::ui::tool_display::{
        chamber_widths, fit_banner_header, format_tool_banner_value, render_tool_output,
    };
    for tc in tool_calls {
        let banner_value = format_tool_banner_value(&tc.name, &tc.args);
        let (frame_w, _) = chamber_widths(renderer);
        let header = fit_banner_header(&tc.name.to_ascii_uppercase(), &banner_value, frame_w);
        renderer.write_line("", Color::Reset)?;
        renderer.write_line(&header, theme::tool())?;
        // Body mirrors `convert_history`'s state→text mapping so the replayed
        // chamber matches what the model re-sees on resume.
        let body = match &tc.state {
            ToolCallState::Completed { result } => result.clone(),
            ToolCallState::Interrupted => "[Tool execution was interrupted]".to_string(),
            ToolCallState::Failed { error } => format!("[Tool error: {error}]"),
        };
        render_tool_output(
            renderer,
            &tc.name,
            &banner_value,
            &body,
            max_chars,
            max_lines,
        )?;
    }
    Ok(())
}

/// Block-letter "DIRGE" in the ANSI Shadow figlet style. Period-correct
/// 80s BBS aesthetic. Six lines tall, 38 chars wide.
const DIRGE_BLOCK_ART: &[&str] = &[
    "██████╗ ██╗██████╗  ██████╗ ███████╗",
    "██╔══██╗██║██╔══██╗██╔════╝ ██╔════╝",
    "██║  ██║██║██████╔╝██║  ███╗█████╗  ",
    "██║  ██║██║██╔══██╗██║   ██║██╔══╝  ",
    "██████╔╝██║██║  ██║╚██████╔╝███████╗",
    "╚═════╝ ╚═╝╚═╝  ╚═╝ ╚═════╝ ╚══════╝",
];

/// Welcome banner — block-letter "DIRGE" wordmark inside a rounded
/// frame with the theme/version/provider/model on the bottom border.
/// Mirrors the btop / cool-retro-term reference: every UI region is a
/// rounded panel with its label sitting on the border, no heavy
/// gradient stripes. Falls back to a single-line text banner on
/// terminals narrower than 50 cols.
fn render_banner(renderer: &mut Renderer, provider: &str, model: &str) -> anyhow::Result<()> {
    let label = theme::current().label;
    let version = env!("CARGO_PKG_VERSION");
    let term_w = renderer.line_width().max(20);

    if term_w < 50 {
        renderer.write_line(
            &format!("╭─ DIRGE · {} · v{} ", label, version),
            theme::banner_primary(),
        )?;
        renderer.write_line(
            &format!("│ provider: {} · model: {}", provider, model),
            theme::banner_secondary(),
        )?;
        renderer.write_line("╰─", theme::banner_secondary())?;
        renderer.write_line("", Color::Reset)?;
        return Ok(());
    }

    // Frame width: cap at 78 so the banner doesn't sprawl on wide
    // monitors, and so it sits visually proportionate to the chat.
    let frame_w = term_w.min(78);
    let inner_w = frame_w.saturating_sub(2);

    // Top border with the wordmark label sitting on it.
    let top_label = format!(" DIRGE · {} ", label);
    let top_label_len = top_label.chars().count();
    let top_filler = inner_w.saturating_sub(top_label_len + 2);
    let top_left = "".repeat(2);
    let top_right = "".repeat(top_filler);
    let top_border = format!("{}{}{}", top_left, top_label, top_right);

    // Bottom border with the status label.
    let bot_label = format!(" v{} · {} · {} ", version, provider, model);
    let bot_label_len = bot_label.chars().count();
    let bot_left = "".repeat(inner_w.saturating_sub(bot_label_len + 2));
    let bot_right = "".repeat(2);
    let bot_border = format!("{}{}{}", bot_left, bot_label, bot_right);

    renderer.write_line(&top_border, theme::banner_secondary())?;
    // Padding row above the art.
    renderer.write_line(
        &format!("{}", " ".repeat(inner_w)),
        theme::banner_secondary(),
    )?;
    // Block-letter art, padded on both sides to fill the frame.
    // The whole line renders in the bright banner_primary tone so the
    // wordmark glows; the surrounding empty padding rows + borders
    // stay dim, giving the eye a clear focal point.
    for art_line in DIRGE_BLOCK_ART {
        let art_len = art_line.chars().count();
        let total_pad = inner_w.saturating_sub(art_len);
        let left = total_pad / 2;
        let right = total_pad - left;
        let line = format!("{}{}{}", " ".repeat(left), art_line, " ".repeat(right),);
        renderer.write_line(&line, theme::banner_primary())?;
    }
    // Padding row below the art.
    renderer.write_line(
        &format!("{}", " ".repeat(inner_w)),
        theme::banner_secondary(),
    )?;
    renderer.write_line(&bot_border, theme::banner_secondary())?;
    renderer.write_line("", Color::Reset)?;
    Ok(())
}

pub fn sanitize_output(text: &str) -> CompactString {
    // Two-pass: first strip orphan SGR mouse reports of the form
    // `[<digits;digits;digits(M|m)` (no leading escape). These can leak into
    // tool output when a shell command captures terminal input bytes, and
    // without this guard they smear `[<65;79;32M…` through the chamber. Then
    // run the shared ANSI/control-char sanitizer over the cleaned text —
    // `KEEP_BOTH` preserves `\n` + `\t` (this output flows through markdown).
    //
    // The escape-stripping state machine lives once in [`crate::ui::ansi`]
    // ([`strip_escapes`]) so the two terminal-output guards (this and the
    // bash/markdown/slash paths) can never drift apart — a security-relevant
    // invariant, since both gate untrusted LLM / bash bytes to the terminal.
    use crate::ui::ansi::{StripPolicy, strip_escapes};
    let stripped = strip_orphan_mouse_reports(text);
    CompactString::from(strip_escapes(&stripped, StripPolicy::KEEP_BOTH))
}

/// Strip orphan SGR mouse-report sequences (e.g. `[<65;79;32M`) that
/// arrive without their leading `\x1b`. Walks the input scanning for
/// the literal pattern `[<` followed by digits and semicolons ending
/// in `M` or `m`; matched runs are dropped. Anything else passes
/// through unchanged.
fn strip_orphan_mouse_reports(text: &str) -> String {
    let bytes: Vec<char> = text.chars().collect();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == '[' && i + 1 < bytes.len() && bytes[i + 1] == '<' {
            // Try to match `[<digits;digits;digits(M|m)`.
            let mut j = i + 2;
            let mut saw_digit_or_semi = false;
            while j < bytes.len() {
                let c = bytes[j];
                if c.is_ascii_digit() || c == ';' {
                    saw_digit_or_semi = true;
                    j += 1;
                } else if (c == 'M' || c == 'm') && saw_digit_or_semi {
                    i = j + 1;
                    break;
                } else {
                    // Not a mouse report — pass `[` through and resume
                    // scanning at the next position.
                    out.push(bytes[i]);
                    i += 1;
                    break;
                }
            }
            if j >= bytes.len() {
                // Truncated input — pass through what we have.
                out.push(bytes[i]);
                i += 1;
            }
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::{MessageRole, Session};

    /// All three finalization nudges (critic / verifier / todo) are recognized
    /// and their tags stripped; a genuine user message is left as-is so it
    /// still renders under `<you>` [dirge-i75f].
    #[test]
    fn finalization_nudge_body_recognizes_all_tags() {
        use crate::agent::agent_loop::{
            critic::CRITIC_TAG, run::TODO_NUDGE_TAG, verifier::VERIFY_TAG,
        };
        assert_eq!(
            finalization_nudge_body(&format!("{CRITIC_TAG} not done yet")),
            Some("not done yet")
        );
        assert_eq!(
            finalization_nudge_body(&format!("{VERIFY_TAG} run the tests")),
            Some("run the tests")
        );
        assert_eq!(
            finalization_nudge_body(&format!(
                "{TODO_NUDGE_TAG} You still have 6 unfinished todos"
            )),
            Some("You still have 6 unfinished todos")
        );
        // Genuine user input is not a nudge.
        assert_eq!(finalization_nudge_body("fix the parser bug"), None);
        // A bracketed-but-unknown prefix is not a nudge either.
        assert_eq!(finalization_nudge_body("[note] just a note"), None);
    }

    fn make_session() -> Session {
        Session::new("openrouter", "gpt-5", 200_000)
    }

    #[test]
    fn session_preview_empty_session_is_empty() {
        let s = make_session();
        assert_eq!(session_preview(&s, 60), "");
    }

    #[test]
    fn session_preview_uses_first_user_message_when_no_compaction() {
        let mut s = make_session();
        s.add_message(
            MessageRole::User,
            "Implement session_search exclusion for current session",
        );
        s.add_message(MessageRole::Assistant, "ok done");
        let p = session_preview(&s, 60);
        assert!(
            p.starts_with("Implement session_search"),
            "preview should lead with the user prompt: {p:?}"
        );
        assert!(!p.contains("ok done"));
    }

    #[test]
    fn session_preview_truncates_long_prompts_with_ellipsis() {
        let mut s = make_session();
        let long = "x".repeat(200);
        s.add_message(MessageRole::User, &long);
        let p = session_preview(&s, 30);
        assert_eq!(p.chars().count(), 30, "preview must respect max_chars");
        assert!(p.ends_with(''));
    }

    #[test]
    fn session_preview_collapses_newlines_to_single_line() {
        let mut s = make_session();
        s.add_message(MessageRole::User, "first line\n\nsecond line\nthird\ttab");
        let p = session_preview(&s, 80);
        assert!(!p.contains('\n'), "preview must be single-line: {p:?}");
        assert!(!p.contains('\t'));
        // Multiple consecutive whitespace collapses to one.
        assert!(!p.contains("  "), "double-space remained: {p:?}");
        assert!(p.contains("first line second line third tab"));
    }

    #[test]
    fn session_preview_skips_system_messages_for_first_user() {
        let mut s = make_session();
        s.add_message(MessageRole::System, "system bootstrap");
        s.add_message(MessageRole::User, "user intent");
        s.add_message(MessageRole::Assistant, "reply");
        let p = session_preview(&s, 60);
        assert!(p.contains("user intent"));
        assert!(!p.contains("system bootstrap"));
        assert!(!p.contains("reply"));
    }

    #[test]
    fn session_preview_falls_back_to_last_when_no_user_message() {
        // Session containing only assistant/system messages — no
        // user prompt to anchor on. Fall back to the last
        // message content.
        let mut s = make_session();
        s.add_message(MessageRole::Assistant, "spontaneous greeting");
        s.add_message(MessageRole::Assistant, "follow-up reply");
        let p = session_preview(&s, 60);
        assert!(
            p.contains("follow-up reply"),
            "fallback should be last message: {p:?}"
        );
    }

    #[test]
    fn session_preview_prefers_compaction_active_task() {
        let mut s = make_session();
        s.add_message(MessageRole::User, "old prompt that got compacted");
        s.compactions.push(crate::session::Compaction {
            summary: compact_str::CompactString::new(
                "## Active Task\nWire session_search current-session exclusion\n\n## Goal\nFix the bug",
            ),
            first_kept_index: 1,
            summarized_count: 1,
            token_savings: 100,
            created_at: compact_str::CompactString::new("2026-05-28T00:00:00Z"),
        });
        let p = session_preview(&s, 80);
        assert!(
            p.contains("Wire session_search current-session exclusion"),
            "preview must use compaction Active Task: {p:?}"
        );
        assert!(
            !p.contains("old prompt"),
            "compaction overrides first-user-message: {p:?}"
        );
    }

    #[test]
    fn session_preview_falls_back_to_goal_when_active_task_missing() {
        let mut s = make_session();
        s.add_message(MessageRole::User, "u");
        s.compactions.push(crate::session::Compaction {
            summary: compact_str::CompactString::new(
                "## Goal\nrefactor the curator into umbrella skills\n\n## Completed\n- nothing",
            ),
            first_kept_index: 1,
            summarized_count: 1,
            token_savings: 50,
            created_at: compact_str::CompactString::new("2026-05-28T00:00:00Z"),
        });
        let p = session_preview(&s, 80);
        assert!(
            p.contains("refactor the curator into umbrella skills"),
            "Goal section should be used when Active Task absent: {p:?}"
        );
    }

    #[test]
    fn session_preview_ignores_empty_active_task_section() {
        let mut s = make_session();
        s.add_message(MessageRole::User, "the user's actual intent");
        s.compactions.push(crate::session::Compaction {
            // Active Task heading present but immediately followed
            // by the next section — no content. Should fall through
            // to the first user message.
            summary: compact_str::CompactString::new("## Active Task\n\n## Goal\n\n## Notes\n"),
            first_kept_index: 1,
            summarized_count: 1,
            token_savings: 0,
            created_at: compact_str::CompactString::new("2026-05-28T00:00:00Z"),
        });
        let p = session_preview(&s, 80);
        assert!(
            p.contains("the user's actual intent"),
            "should fall through past empty sections to user message: {p:?}"
        );
    }

    /// dirge: a reloaded session must reconstruct tool chambers from the
    /// persisted `tool_calls`, not drop them. Before the fix `render_session`
    /// rendered only `msg.content`, so every edit/bash/read vanished on resume.
    #[test]
    fn replays_tool_calls_as_chambers() {
        use crate::session::{ToolCallEntry, ToolCallState};
        let mut renderer = Renderer::new().unwrap();
        renderer.set_chat_rect_for_test(ratatui::layout::Rect::new(0, 1, 100, 24));
        let calls = vec![ToolCallEntry {
            id: "call_1".into(),
            name: "bash".into(),
            args: serde_json::json!({ "command": "ls -la" }),
            state: ToolCallState::Completed {
                result: "total 4\ndrwxr-xr-x  src".into(),
            },
        }];
        render_tool_calls_replay(&mut renderer, &calls, 10_000, 100).unwrap();
        let text = renderer.buffer_lines().join("\n");
        // Header carries the upper-cased tool name + its banner value.
        assert!(text.contains("BASH"), "missing tool header: {text}");
        assert!(text.contains("ls -la"), "missing banner value: {text}");
        // Body carries the result the user saw live.
        assert!(text.contains("total 4"), "missing tool output: {text}");
    }

    /// A failed/interrupted call still renders a chamber (not nothing), so the
    /// reloaded transcript shows the call happened.
    #[test]
    fn replays_failed_tool_call_with_error_body() {
        use crate::session::{ToolCallEntry, ToolCallState};
        let mut renderer = Renderer::new().unwrap();
        renderer.set_chat_rect_for_test(ratatui::layout::Rect::new(0, 1, 100, 24));
        let calls = vec![ToolCallEntry {
            id: "call_1".into(),
            name: "read".into(),
            args: serde_json::json!({ "path": "/nope.txt" }),
            state: ToolCallState::Failed {
                error: "file not found".into(),
            },
        }];
        render_tool_calls_replay(&mut renderer, &calls, 10_000, 100).unwrap();
        let text = renderer.buffer_lines().join("\n");
        assert!(text.contains("READ"), "missing tool header: {text}");
        assert!(
            text.contains("file not found"),
            "missing error body: {text}"
        );
    }
}