knotra 0.29.0

knotra: multi-project VCS dashboard and bulk-operation tool.
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
//! History view — searchable, expandable operation log.
//!
//! RFC-038 Stage 4: operation kinds now route through
//! `super::operation_kind_label` (lifted from `activity_strip.rs` so both
//! files share one mapping, §1a) instead of `OperationKind`'s raw English
//! `Display`; the project count uses a "label: count" phrasing that needs
//! no singular/plural branching in either language (§1b); the search
//! toolbar is width-bounded, each entry's summary is a two-line hierarchy
//! (kind/status/actions, then timestamp/count) with a chevron on the
//! disclosure toggle, and both empty states sit near the content origin
//! rather than centred in a 250px dead block (H4, §2); and each entry's
//! summary/detail composition now goes through
//! `knotra_ui::widget::record_row` (D3/R6) instead of building its own
//! `column`/`container`, so RFC-039 can reuse the same collapsible-record
//! shape for per-project history rather than copying it.

use iced::{
    Alignment, Element, Length, Padding,
    widget::{Space, button, column, container, row, scrollable, text, text_input},
};
use knotra_ui::widget::{Tokens, icon, record_row};
use knotra_vcs::model::operation::{OperationLog, OperationResult, ProjectOperationOutcome};

use crate::{
    message::{HistoryMessage, Message},
    state::AppState,
};

/// Matches `view/settings.rs`'s own bounded-form width (`FORM_MAX_WIDTH`) —
/// the same "large bounded content" convention (H4's "bounded search/filter
/// toolbar" ask), not a new number invented for this screen.
const TOOLBAR_MAX_WIDTH: f32 = 680.0;

// ---------------------------------------------------------------------------
// Top-level
// ---------------------------------------------------------------------------

pub fn view(state: &AppState) -> Element<'_, Message> {
    let header = view_header(state);
    let toolbar = view_toolbar(state);
    let body = view_body(state);

    column![header, toolbar, scrollable(body).height(Length::Fill)]
        .height(Length::Fill)
        .into()
}

// ---------------------------------------------------------------------------
// Header
// ---------------------------------------------------------------------------

fn view_header(state: &AppState) -> Element<'_, Message> {
    let tokens = &state.theme.tokens;
    // RFC-034 R13: per-screen back navigation removed — Dashboard/History are
    // reached through the persistent shell now, not a screen-owned button.
    row![text(state.t("history.title")).size(snora::design::style::text::heading_size(tokens))]
        .spacing(12)
        .align_y(Alignment::Center)
        .padding(Padding::new(12.0))
        .into()
}

// ---------------------------------------------------------------------------
// Search toolbar
// ---------------------------------------------------------------------------

fn view_toolbar(state: &AppState) -> Element<'_, Message> {
    let input = text_input(state.t("history.search_hint"), &state.history_search)
        .on_input(|s| Message::History(HistoryMessage::SearchChanged(s)))
        .width(Length::Fill);

    container(input)
        .width(Length::Fill)
        .max_width(TOOLBAR_MAX_WIDTH)
        .padding(Padding {
            top: 0.0,
            bottom: 8.0,
            left: 12.0,
            right: 12.0,
        })
        .into()
}

// ---------------------------------------------------------------------------
// Body: log entry list
// ---------------------------------------------------------------------------

fn view_body(state: &AppState) -> Element<'_, Message> {
    let tokens = &state.theme.tokens;
    // RFC-047 D3: a directory that could not be read is its own state, not
    // "no history yet" — checked before the empty-list branch below, since
    // an unreadable directory always yields zero logs and would otherwise
    // be indistinguishable from a genuine first run.
    if state.history_directory_unreadable {
        return empty_state(tokens, state.t("history.directory_unreadable"));
    }

    if state.operation_logs.is_empty() {
        // RFC-047 D2: "N entries could not be read" is the more important
        // message when the list is otherwise empty — it replaces
        // `history.empty` rather than sitting beside it, since there is
        // nothing else on screen for it to sit above.
        return if state.history_unreadable_count > 0 {
            empty_state(tokens, unreadable_count_message(state))
        } else {
            empty_state(tokens, state.t("history.empty"))
        };
    }

    let q = state.history_search.to_lowercase();

    let mut entries: Vec<Element<'_, Message>> = state
        .operation_logs
        .iter()
        .filter(|log| {
            // Matches against what is now on screen (the plain-language
            // kind label, §1a) rather than `OperationKind`'s raw English
            // `Display` — a user typing part of what they see should find
            // it; matching the technical name they no longer see would not.
            q.is_empty()
                || super::operation_kind_label(state, &log.result.kind)
                    .to_lowercase()
                    .contains(&q)
                || log.result.per_project.iter().any(|p| {
                    p.project_id.to_string().contains(&q)
                        || p.stdout.to_lowercase().contains(&q)
                        || p.stderr.to_lowercase().contains(&q)
                })
        })
        .map(|log| view_log_entry(state, log))
        .collect();

    if entries.is_empty() {
        return empty_state(tokens, state.t("history.no_match"));
    }

    // RFC-047 D2: above the populated list, not replacing it — the list is
    // still the useful content here.
    if state.history_unreadable_count > 0 {
        entries.insert(
            0,
            text(unreadable_count_message(state))
                .size(snora::design::style::text::body_small_size(tokens))
                .line_height(snora::design::style::text::body_small_line_height(tokens))
                .into(),
        );
    }

    column(entries).spacing(6).padding(12).into()
}

fn unreadable_count_message(state: &AppState) -> String {
    format!(
        "{} {}",
        state.t("history.unreadable_count_label"),
        state.history_unreadable_count
    )
}

/// H4: near the content origin, not vertically centred in a large reserved
/// block. Was `container(...).height(250).center_y(250)` — the message sat
/// 125px down inside a fixed dead area regardless of how little content
/// surrounded it. Now top-of-content, ordinary padding, no reserved height.
///
/// RFC-047: takes `impl Into<String>` rather than `&str` so the two states
/// that carry a count (`unreadable_count_message`) can build an owned
/// message alongside the two that don't (`state.t(...)`), through the same
/// helper rather than a parallel one.
fn empty_state(tokens: &Tokens, message: impl Into<String>) -> Element<'static, Message> {
    container(text(message.into()).size(snora::design::style::text::label_size(tokens)))
        .width(Length::Fill)
        .padding(24)
        .into()
}

// ---------------------------------------------------------------------------
// Single log entry
// ---------------------------------------------------------------------------

fn view_log_entry<'a>(state: &'a AppState, log: &'a OperationLog) -> Element<'a, Message> {
    let tokens = &state.theme.tokens;
    let result = &log.result;
    let expanded = state.history_expanded.contains(&result.operation_id);

    let status = summarise_status(result);
    let status_label = format!("{} {}", status.glyph, state.t(status.label_key));
    let timestamp = result
        .started_at
        .format("%Y-%m-%d %H:%M:%S UTC")
        .to_string();
    let project_count = result.per_project.len();

    // RFC-050 D3: the shared disclosure vocabulary (`plain.show_details`/
    // `plain.hide_details`, already used by five other call sites) rather
    // than this file's own `history.expand`/`history.collapse` — whose
    // Japanese used 閉じる ("close") for a control that closes nothing;
    // `action.close` already owns that word for actual closing.
    let toggle_label = if expanded {
        state.t("plain.hide_details")
    } else {
        state.t("plain.show_details")
    };
    // H4: a text-only toggle read as a generic button, not a disclosure
    // control. `chevron_right`/`chevron_down` are the same idiom already
    // used for the dashboard's section headers and the workspace switcher
    // (`view/dashboard/section.rs`) — right reads as "click to open", down
    // as "already open, contents below".
    let chevron = if expanded {
        icon::chevron_down()
    } else {
        icon::chevron_right()
    };

    let op_id_toggle = result.operation_id.clone();

    // H4: a fixed metadata hierarchy — kind, status, and the two actions on
    // one primary line; timestamp and project count, both secondary, on a
    // smaller line beneath. Was one row interleaving all five with `"  "`
    // string-padding standing in for real spacing.
    let primary_row = row![
        text(super::operation_kind_label(state, &result.kind))
            .size(snora::design::style::text::body_small_size(tokens))
            .line_height(snora::design::style::text::body_small_line_height(tokens)),
        Space::new().width(Length::Fill),
        text(status_label)
            .size(snora::design::style::text::body_small_size(tokens))
            .line_height(snora::design::style::text::body_small_line_height(tokens)),
        button(
            row![
                text(toggle_label)
                    .size(snora::design::style::text::body_small_size(tokens))
                    .line_height(snora::design::style::text::body_small_line_height(tokens)),
                icon::icon_element(&chevron)
            ]
            .spacing(4)
            .align_y(Alignment::Center)
        )
        .on_press(Message::History(HistoryMessage::EntryToggled(op_id_toggle))),
        button(
            text(state.t("history.copy_log"))
                .size(snora::design::style::text::body_small_size(tokens))
                .line_height(snora::design::style::text::body_small_line_height(tokens))
        )
        .on_press(Message::CopyToClipboard(export_text(result))),
    ]
    .spacing(8)
    .align_y(Alignment::Center);

    let secondary_row = row![
        text(timestamp)
            .size(snora::design::style::text::body_small_size(tokens))
            .line_height(snora::design::style::text::body_small_line_height(tokens)),
        text(format!(
            "{} {}",
            state.t("history.project_count_label"),
            project_count
        ))
        .size(snora::design::style::text::body_small_size(tokens))
        .line_height(snora::design::style::text::body_small_line_height(tokens)),
    ]
    .spacing(12);

    let summary = column![primary_row, secondary_row].spacing(2);
    let detail = expanded.then(|| view_log_detail(state, log));

    // D3/R6: the summary-always/detail-when-expanded composition this file
    // and RFC-039's per-project rows both need — `_op_id_copy` (a second,
    // unused clone of `operation_id`) is gone here as a natural consequence
    // of this rewrite, not a separate cleanup.
    record_row(summary.into(), detail)
}

// ---------------------------------------------------------------------------
// Expanded detail
// ---------------------------------------------------------------------------

fn view_log_detail<'a>(state: &'a AppState, log: &'a OperationLog) -> Element<'a, Message> {
    let tokens = &state.theme.tokens;
    let result = &log.result;
    let mut rows: Vec<Element<'a, Message>> = Vec::new();

    // Rollback status.
    //
    // Found and fixed alongside `summarise_status` (RFC-038 Stage 1) rather
    // than left as-is — the handoff named `summarise_status` specifically,
    // but this pair sits on the same on-screen "visible path" (rendered
    // whenever a rolled-back entry is expanded), is the identical class of
    // defect, and both halves already had a same-shaped key to reuse
    // (`plain.activity.succeeded`/`plain.activity.failed`, already used the
    // same way in `activity_strip.rs`), so no new catalog entries were
    // needed for this part. The pre-existing "FAILED" (uppercase) vs.
    // "succeeded" (lowercase) inconsistency is also gone as a side effect of
    // routing both through the same existing key pair — not a rewording
    // decision, since neither string's wording changed, only its casing
    // normalized to match the key it now reuses.
    if result.rollback_attempted {
        let rb_text = format!(
            "{}  {}",
            state.t("history.rollback_note"),
            if result.rollback_succeeded == Some(true) {
                state.t("plain.activity.succeeded")
            } else {
                state.t("plain.activity.failed")
            }
        );
        rows.push(
            text(rb_text)
                .size(snora::design::style::text::body_small_size(tokens))
                .line_height(snora::design::style::text::body_small_line_height(tokens))
                .into(),
        );
    }

    // Per-project results.
    for pr in &result.per_project {
        let icon = match pr.effective_outcome() {
            ProjectOperationOutcome::Succeeded => "✓",
            ProjectOperationOutcome::Failed => "✗",
            ProjectOperationOutcome::Skipped => "-",
        };
        rows.push(
            text(format!("  {icon} {}", pr.project_id))
                .size(snora::design::style::text::body_small_size(tokens))
                .line_height(snora::design::style::text::body_small_line_height(tokens))
                .into(),
        );
        if let Some(reason) = &pr.skip_reason {
            rows.push(
                text(format!("    {}", super::skip_reason_display(state, reason)))
                    .size(snora::design::style::text::body_small_size(tokens))
                    .line_height(snora::design::style::text::body_small_line_height(tokens))
                    .into(),
            );
        }

        // Commands (transparency).
        if !pr.commands_executed.is_empty() {
            rows.push(
                text(state.t("history.commands_header"))
                    .size(snora::design::style::text::body_small_size(tokens))
                    .line_height(snora::design::style::text::body_small_line_height(tokens))
                    .into(),
            );
            for cmd in &pr.commands_executed {
                rows.push(
                    text(format!("    $ {cmd}"))
                        .size(snora::design::style::text::body_small_size(tokens))
                        .line_height(snora::design::style::text::body_small_line_height(tokens))
                        .into(),
                );
            }
        }

        // Stderr excerpt on failure.
        if pr.is_failed() && !pr.stderr.is_empty() {
            let preview: String = pr.stderr.lines().take(3).collect::<Vec<_>>().join("\n");
            rows.push(
                text(format!("    {preview}"))
                    .size(snora::design::style::text::body_small_size(tokens))
                    .line_height(snora::design::style::text::body_small_line_height(tokens))
                    .into(),
            );
        }
    }

    // Recovery hints.
    if !log.recovery_hints.is_empty() {
        rows.push(
            text(state.t("history.recovery_header"))
                .size(snora::design::style::text::body_small_size(tokens))
                .line_height(snora::design::style::text::body_small_line_height(tokens))
                .into(),
        );
        for hint in &log.recovery_hints {
            rows.push(
                text(format!("  {}", hint.situation))
                    .size(snora::design::style::text::body_small_size(tokens))
                    .line_height(snora::design::style::text::body_small_line_height(tokens))
                    .into(),
            );
            for cmd in &hint.suggested_commands {
                rows.push(
                    text(format!("    $ {cmd}"))
                        .size(snora::design::style::text::body_small_size(tokens))
                        .line_height(snora::design::style::text::body_small_line_height(tokens))
                        .into(),
                );
            }
        }
    }

    column(rows).spacing(2).padding([4, 12]).into()
}

// ---------------------------------------------------------------------------
// Clipboard/export text — RFC-038 A1
// ---------------------------------------------------------------------------

/// Builds this operation's clipboard/export text. RFC-038 A1: the export is
/// English by design — it leaves the app and lands in issue trackers and
/// search boxes where the reader is frequently not the localised user, and
/// each catalog lookup here would be a *variable*-keyed one, the one shape
/// `every_literal_t_call_names_an_existing_key` cannot check; a missing key
/// in a release build would paste the raw catalog key straight into the
/// user's pasted report (`Catalog::t()` is `debug_assert!` then
/// `unwrap_or(key)`). Taking `&OperationResult` rather than `&AppState`
/// makes that guarantee structural: `t()` is a method on `AppState`, so this
/// function cannot regain a catalog lookup without the parameter coming
/// back — R7a is enforced by the signature, not merely followed by the
/// body.
///
/// `skip_reason` is emitted verbatim, not translated: for the stable
/// `RetryExclusionReason` codes (`retry:not_in_active_workspace` and
/// friends, `knotra-vcs/src/model/operation.rs:93`) this is the canonical,
/// greppable identifier — stable across users and locales, needing no
/// second English mapping that could drift from the code. RFC-046 D1 made
/// this the only shape `skip_reason` is ever written in going forward
/// (`app/sync.rs`'s prior locale-baked-text writer was fixed at the source,
/// not papered over here); a log entry written before that fix still holds
/// rendered prose, and this export inherits whatever locale was active when
/// such an entry was logged, same as the on-screen path's
/// `skip_reason_display` fallback (`view.rs`) — RFC-046 D4's deliberate
/// compatibility with pre-fix records, not a live defect.
fn export_text(result: &OperationResult) -> String {
    let kind = result.kind.to_string();
    let ts = result
        .started_at
        .format("%Y-%m-%d %H:%M:%S UTC")
        .to_string();
    let status = summarise_status(result);
    let status_text = format!("{} {}", status.glyph, status.label_en);
    let mut text_parts = vec![format!("# {} — {} — {}", kind, ts, status_text)];
    for pr in &result.per_project {
        let ok = match pr.effective_outcome() {
            ProjectOperationOutcome::Succeeded => "ok",
            ProjectOperationOutcome::Failed => "FAILED",
            ProjectOperationOutcome::Skipped => "SKIPPED",
        };
        text_parts.push(format!("  {} [{}]", pr.project_id, ok));
        if let Some(reason) = &pr.skip_reason {
            text_parts.push(format!("    {}", reason));
        }
        for cmd in &pr.commands_executed {
            text_parts.push(format!("    $ {}", cmd));
        }
        if !pr.stderr.is_empty() {
            for line in pr.stderr.lines().take(5) {
                text_parts.push(format!("    {}", line));
            }
        }
    }
    text_parts.join("\n")
}

// ---------------------------------------------------------------------------
// Status label helper
// ---------------------------------------------------------------------------

/// A history entry's overall status: a stable glyph, the i18n key for its
/// translated on-screen label, and the fixed English label the export uses
/// (RFC-038 A1) — all three set in the same match arm so they cannot drift
/// apart. The glyph is a status signal, not language — composing it in the
/// view keeps a translator from being able to drop or reorder it, and keeps
/// it from being duplicated across both catalogs. `label_en` exists so the
/// export never has to call `t()` to get English text; it must read the same
/// as the English catalog entry named beside it, but nothing enforces that
/// mechanically — if you retext a `history.status_*`/`history.rollback_note`
/// English value, update the matching `label_en` here too.
struct StatusSummary {
    glyph: &'static str,
    label_key: &'static str,
    label_en: &'static str,
}

fn summarise_status(result: &OperationResult) -> StatusSummary {
    let succeeded = result.successful_projects().len();
    let failed = result.failed_projects().len();
    let skipped = result.skipped_projects().len();

    if result.rollback_attempted {
        if result.rollback_succeeded == Some(true) {
            // Reuses the existing `history.rollback_note` key — the same
            // "Rolled back" text `view_log_detail` already renders below.
            StatusSummary {
                glyph: "↩",
                label_key: "history.rollback_note",
                label_en: "Rolled back",
            }
        } else {
            StatusSummary {
                glyph: "✗",
                label_key: "history.status_rollback_failed",
                label_en: "Rollback failed",
            }
        }
    } else if succeeded > 0 && failed == 0 && skipped == 0 {
        StatusSummary {
            glyph: "✓",
            label_key: "history.status_success",
            label_en: "Success",
        }
    } else if failed > 0 && (succeeded > 0 || skipped > 0) {
        StatusSummary {
            glyph: "⚠",
            label_key: "history.status_partial",
            label_en: "Partial",
        }
    } else if skipped > 0 && failed == 0 {
        StatusSummary {
            glyph: "-",
            label_key: "history.status_skipped",
            label_en: "Skipped",
        }
    } else {
        StatusSummary {
            glyph: "✗",
            label_key: "history.status_failed",
            label_en: "Failed",
        }
    }
}

#[cfg(test)]
mod tests {
    use knotra_vcs::model::{
        operation::{OperationId, OperationKind, ProjectOperationResult},
        project::ProjectId,
    };

    use super::*;

    fn sample_result(
        per_project: Vec<ProjectOperationResult>,
        rollback_attempted: bool,
        rollback_succeeded: Option<bool>,
    ) -> OperationResult {
        let now = chrono::Utc::now();
        OperationResult {
            operation_id: OperationId::new(),
            kind: OperationKind::Fetch,
            started_at: now,
            finished_at: now,
            per_project,
            rollback_attempted,
            rollback_succeeded,
        }
    }

    fn succeeded_project(id: ProjectId) -> ProjectOperationResult {
        ProjectOperationResult {
            project_id: id,
            outcome: ProjectOperationOutcome::Succeeded,
            success: true,
            skip_reason: None,
            commands_executed: vec!["git fetch".to_owned()],
            stdout: String::new(),
            stderr: String::new(),
            exit_code: Some(0),
            error_message: None,
        }
    }

    fn failed_project(id: ProjectId) -> ProjectOperationResult {
        ProjectOperationResult {
            project_id: id,
            outcome: ProjectOperationOutcome::Failed,
            success: false,
            skip_reason: None,
            commands_executed: Vec::new(),
            stdout: String::new(),
            stderr: String::new(),
            exit_code: Some(1),
            error_message: None,
        }
    }

    fn skipped_project(id: ProjectId, skip_reason: Option<String>) -> ProjectOperationResult {
        ProjectOperationResult {
            project_id: id,
            outcome: ProjectOperationOutcome::Skipped,
            success: true,
            skip_reason,
            commands_executed: Vec::new(),
            stdout: String::new(),
            stderr: String::new(),
            exit_code: None,
            error_message: None,
        }
    }

    /// RFC-038 A1's core guarantee: the export names the operation and its
    /// status in fixed English, never through `t()` — `export_text` cannot
    /// call it, since it does not take `&AppState`.
    #[test]
    fn export_text_reports_a_successful_entry_in_english() {
        let id = ProjectId::new();
        let result = sample_result(vec![succeeded_project(id.clone())], false, None);

        let text = export_text(&result);

        assert!(
            text.starts_with("# Fetch — "),
            "expected an English kind label, got: {text}"
        );
        assert!(
            text.contains("✓ Success"),
            "expected the fixed English status label, got: {text}"
        );
        assert!(
            text.contains(&format!("{id} [ok]")),
            "expected the project id with its outcome tag, got: {text}"
        );
        assert!(
            text.contains("$ git fetch"),
            "expected the executed command, got: {text}"
        );
    }

    /// A skip reason is emitted verbatim — the stable `RetryExclusionReason`
    /// code, not a translated (or mistranslated) sentence — so a maintainer
    /// reading a pasted log sees the same greppable identifier regardless of
    /// the reporting user's locale.
    #[test]
    fn export_text_emits_the_skip_reason_code_verbatim() {
        let id = ProjectId::new();
        let skipped = skipped_project(id, Some("retry:not_in_active_workspace".to_owned()));
        let result = sample_result(vec![skipped], false, None);

        let text = export_text(&result);

        assert!(
            text.contains("retry:not_in_active_workspace"),
            "expected the raw code, untranslated, got: {text}"
        );
    }

    /// Stderr lines are copied through unchanged (already raw command
    /// output, not catalog-sourced), capped at 5 lines as the on-screen path
    /// caps at 3 — both existing behaviour, unaffected by this stage.
    #[test]
    fn export_text_includes_stderr_lines() {
        let id = ProjectId::new();
        let failed = ProjectOperationResult {
            project_id: id,
            outcome: ProjectOperationOutcome::Failed,
            success: false,
            skip_reason: None,
            commands_executed: Vec::new(),
            stdout: String::new(),
            stderr: "fatal: could not read remote\nauthentication failed".to_owned(),
            exit_code: Some(1),
            error_message: Some("fatal: could not read remote".to_owned()),
        };
        let result = sample_result(vec![failed], false, None);

        let text = export_text(&result);

        assert!(
            text.contains("fatal: could not read remote"),
            "expected the first stderr line, got: {text}"
        );
        assert!(
            text.contains("authentication failed"),
            "expected the second stderr line, got: {text}"
        );
        assert!(
            text.contains("[FAILED]"),
            "expected the failed outcome tag, got: {text}"
        );
    }

    /// Handoff 061/062: nothing keeps `StatusSummary::label_en` agreeing
    /// with the English catalog entry `label_key` names — if they drift, the
    /// export and the on-screen UI disagree about what a status is called,
    /// silently. Driving `summarise_status` for each of its six arms (rather
    /// than asserting a table of six literal pairs) is the point only if
    /// each fixture is also checked to land on the arm it claims to —
    /// otherwise a fixture that fell through to a neighbouring arm would
    /// still pass, since that arm's own pairing holds too. Each case
    /// therefore carries its own expected `label_key` and is checked twice:
    /// coverage (the fixture reached the arm it names) before pairing
    /// (`label_en` agrees with the catalog for whichever arm that was).
    #[test]
    fn label_en_matches_the_english_catalog_for_every_status_arm() {
        let en = knotra_ui::i18n::Catalog::for_locale(knotra_ui::i18n::Locale::En);
        let id = ProjectId::new();

        let cases: Vec<(&str, OperationResult, &str)> = vec![
            (
                "rolled back",
                sample_result(vec![succeeded_project(id.clone())], true, Some(true)),
                "history.rollback_note",
            ),
            (
                "rollback failed",
                sample_result(vec![succeeded_project(id.clone())], true, Some(false)),
                "history.status_rollback_failed",
            ),
            (
                "success",
                sample_result(vec![succeeded_project(id.clone())], false, None),
                "history.status_success",
            ),
            (
                "partial",
                sample_result(
                    vec![succeeded_project(id.clone()), failed_project(id.clone())],
                    false,
                    None,
                ),
                "history.status_partial",
            ),
            (
                "skipped",
                sample_result(vec![skipped_project(id.clone(), None)], false, None),
                "history.status_skipped",
            ),
            (
                "failed",
                sample_result(vec![failed_project(id.clone())], false, None),
                "history.status_failed",
            ),
        ];

        for (case, result, expected_key) in cases {
            let summary = summarise_status(&result);
            assert_eq!(
                summary.label_key, expected_key,
                "the `{case}` fixture no longer reaches the `{expected_key}` arm of \
                 summarise_status — it landed on `{}` instead",
                summary.label_key
            );
            assert_eq!(
                summary.label_en,
                en.t(summary.label_key),
                "label_en drifted from the English catalog for the `{case}` status arm \
                 (label_key = `{}`)",
                summary.label_key
            );
        }
    }
}