koda-cli 0.2.25

A high-performance AI coding agent for macOS and Linux
Documentation
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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
//! Conversation transcript generator.
//!
//! Converts a session's `Message` slice into a Markdown document for
//! clipboard copy or file export. Two modes:
//!
//! - **Verbose** (default) — full fidelity: timestamps, token counts,
//!   all tool output (including Bash), session metadata header.
//! - **Summary** (`--summary`) — concise, human-readable: hides Bash
//!   output, omits token counts and timestamps.
//!
//! ## Verbose format
//!
//! ```text
//! # Koda Session — My Task
//!
//! | Field | Value |
//! |---|---|
//! | Session | abc123 |
//! | Model | claude-sonnet-4-20250514 |
//! | Started | 2026-04-10 10:32 UTC |
//!
//! ---
//!
//! ## 🧑 User  <sub>10:32:01</sub>
//! What does this function do?
//!
//! ## 🤖 Assistant  <sub>10:32:05</sub>
//! The function `foo()` does …
//!
//! <sub>tokens: 1234 prompt · 567 completion · 890 cache-read</sub>
//!
//! ### 📄 **Read** `src/main.rs`
//!
//! (full tool output shown)
//! ```

use koda_core::persistence::{Message, Role, SessionEvent, session_event_kind};
use koda_core::tools::{ToolEffect, classify_tool};
use std::collections::HashMap;

/// Session metadata for the verbose transcript header.
///
/// Assembled by the caller (`handle_export`) from live config — not stored
/// in the DB (see #878 design discussion).
#[derive(Debug, Default)]
pub struct SessionMeta {
    pub session_id: String,
    pub title: Option<String>,
    pub started_at: Option<String>,
    pub model: String,
    pub provider: String,
    pub project_root: String,
}

/// Maximum content lines to include per tool result in summary mode.
const SUMMARY_RESULT_LINES: usize = 10;

/// Maximum content lines to include per tool result in verbose mode.
const VERBOSE_RESULT_LINES: usize = 50;

/// Bash command truncation limit in summary mode.
const SUMMARY_BASH_CHARS: usize = 80;

/// Bash command truncation limit in verbose mode (effectively unlimited).
const VERBOSE_BASH_CHARS: usize = 500;

/// Env-var name for opting out of markdown hyperlinks in transcripts.
///
/// Default behavior: emit hyperlinks. Setting this to `"off"`, `"0"`,
/// or `"false"` disables them so paths render as plain text. Useful for
/// downstream consumers that munge markdown links into something less
/// readable than the bare path.
const HYPERLINK_KILL_SWITCH: &str = "KODA_TRANSCRIPT_HYPERLINKS";

fn hyperlinks_enabled() -> bool {
    // **#1109 F1**: read via runtime_env so tests can flip this without
    // `unsafe { std::env::set_var }`.
    !matches!(
        koda_core::runtime_env::get(HYPERLINK_KILL_SWITCH).as_deref(),
        Some("off" | "0" | "false" | "no")
    )
}

/// Format the current UTC time as `YYYY-MM-DD HH:MM UTC` for the transcript header.
fn format_utc_now() -> String {
    let dt = crate::util::utc_now();
    format!(
        "{:04}-{:02}-{:02} {:02}:{:02} UTC",
        dt.year(),
        dt.month() as u8,
        dt.day(),
        dt.hour(),
        dt.minute(),
    )
}

/// Extract `(id, function_name, arguments_json)` from one element of
/// the parsed `tool_calls` JSON array.
///
/// Production code persists tool calls via
/// `serde_json::to_string(&Vec<ToolCall>)`, which produces the FLAT
/// shape `{"id":..., "function_name":..., "arguments":...}` (see
/// `koda_core::providers::ToolCall`). Pre-#1108 the renderer here
/// looked at the OpenAI-NESTED shape `{"function": {"name":..., }}`,
/// silently fell through to defaults, and rendered every export as
/// `### 🔧 **Tool**` with no name.
///
/// Read the flat shape first; fall back to nested for any legacy
/// data or test fixtures still using the OpenAI shape. This mirrors
/// the established pattern in `microcompact.rs` and
/// `context_analysis.rs` — those modules read tool_calls JSON the
/// right way; this one was the lone offender.
fn extract_tool_call_meta(call: &serde_json::Value) -> (String, String, String) {
    let id = call
        .get("id")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    let name = call
        .get("function_name")
        .or_else(|| call.get("function").and_then(|f| f.get("name")))
        .and_then(|v| v.as_str())
        .unwrap_or("Tool")
        .to_string();
    let args = call
        .get("arguments")
        .or_else(|| call.get("function").and_then(|f| f.get("arguments")))
        .and_then(|v| v.as_str())
        .unwrap_or("{}")
        .to_string();
    (id, name, args)
}

/// Generate a Markdown transcript from a slice of session messages.
///
/// - `verbose = true` (default): full fidelity — timestamps, token counts,
///   all tool output, session metadata header.
/// - `verbose = false` (`--summary`): concise, human-readable.
///
/// `events` carries non-message engine events persisted to the
/// `session_events` table (#1108 P1b/P2a). They split into two
/// rendering buckets:
/// - **Sub-agent events** (`parent_tool_call_id = Some(id)`) are
///   folded as a collapsible `<details>` block under the matching
///   `Tool` result. Pass an empty slice for sessions with no bg
///   sub-agents.
/// - **Top-level events** (`parent_tool_call_id = None`) are appended
///   in a chronological "Background activity" section at the end,
///   so the reader can correlate microcompact / rate-limit / bg-task
///   transitions with the conversation above.
///
/// Returns the transcript as a `String`. The caller is responsible for
/// writing it to the clipboard or a file.
pub fn render(
    messages: &[Message],
    events: &[SessionEvent],
    meta: &SessionMeta,
    verbose: bool,
) -> String {
    let mut out = String::with_capacity(if verbose { 16384 } else { 4096 });

    // Header
    let title = meta.title.as_deref().unwrap_or("Koda Session");
    let now = format_utc_now();
    out.push_str(&format!("# {title}{now}\n\n"));

    if verbose {
        render_metadata_table(&mut out, meta);
    }

    // tool_call_id → tool_name mapping for result correlation, populated
    // **incrementally during the render walk below** rather than via a
    // pre-pass over all messages. The pre-pass approach (pre-#1163-followup)
    // was buggy with providers that reuse tool_call_ids across turns —
    // notably Gemini, which emits per-turn counters like `gemini_tc_1`,
    // `gemini_tc_2`, … that reset every assistant message. With a global
    // pre-pass + last-write-wins, a `WaitTask`-bearing id would get silently
    // overwritten by a later turn's `Read`, causing the Tool result lookup
    // at render time to return the wrong tool_name and skip the WaitTask
    // pretty-printer (#1162) → raw JSON dumped into a code block.
    //
    // Walking in order and inserting as we go means each Tool message sees
    // the rolling map state **as of that point in the transcript**, which
    // always reflects the most-recent prior Assistant `tool_calls` block —
    // i.e. the call that actually produced this result. Same map, same
    // O(N) cost, correct semantics for id-reusing providers.
    let mut tool_id_to_name: HashMap<String, String> = HashMap::new();

    // #1108 P2a: bucket sub-agent events by parent tool_call_id so
    // each Tool result can render its folded trace in O(1). Top-level
    // events (no parent) accumulate in a separate Vec for the
    // "Background activity" tail section. Single pass, two buckets.
    let mut events_by_parent: HashMap<&str, Vec<&SessionEvent>> = HashMap::new();
    let mut top_level_events: Vec<&SessionEvent> = Vec::new();
    for ev in events {
        match ev.parent_tool_call_id.as_deref() {
            Some(parent) => events_by_parent.entry(parent).or_default().push(ev),
            None => top_level_events.push(ev),
        }
    }

    for msg in messages {
        match msg.role {
            Role::System => {} // Skip — internal plumbing

            Role::User => {
                out.push_str("---\n\n");
                render_role_header(&mut out, "\u{1f9d1} User", msg, verbose);
                if let Some(ref content) = msg.content {
                    out.push_str(content.trim());
                    out.push_str("\n\n");
                }
            }

            Role::Assistant => {
                render_role_header(&mut out, "🤖 Assistant", msg, verbose);

                // Thinking block (Claude extended thinking) — before text
                if let Some(ref thinking) = msg.thinking_content
                    && !thinking.trim().is_empty()
                {
                    out.push_str("> 💭 **Thinking**\n");
                    for line in thinking.trim().lines() {
                        out.push_str("> ");
                        out.push_str(line);
                        out.push('\n');
                    }
                    out.push('\n');
                }

                // Text content
                if let Some(ref content) = msg.content {
                    let trimmed = content.trim();
                    if !trimmed.is_empty() {
                        out.push_str(trimmed);
                        out.push_str("\n\n");
                    }
                }

                // Tool call headers
                if let Some(ref tc_json) = msg.tool_calls
                    && let Ok(calls) = serde_json::from_str::<Vec<serde_json::Value>>(tc_json)
                {
                    let bash_limit = if verbose {
                        VERBOSE_BASH_CHARS
                    } else {
                        SUMMARY_BASH_CHARS
                    };
                    let link = hyperlinks_enabled();
                    for call in &calls {
                        let (id, name, args_json) = extract_tool_call_meta(call);
                        // Register the id→name mapping for the matching
                        // Tool result that will appear later in the walk.
                        // See the rationale comment at the top of this fn.
                        if !id.is_empty() && name != "Tool" {
                            tool_id_to_name.insert(id.clone(), name.clone());
                        }
                        let detail = tool_detail_markdown(
                            &name,
                            &args_json,
                            bash_limit,
                            &meta.project_root,
                            link,
                        );
                        let icon = tool_icon(&name);
                        out.push_str(&format!("### {icon} **{name}**"));
                        if !detail.is_empty() {
                            // Detail may already contain markdown link
                            // syntax (`[disp](uri)`); only the plain-text
                            // branches are wrapped in backticks. Linked
                            // detail is left bare so the link renders.
                            if detail.starts_with('[') {
                                out.push(' ');
                                out.push_str(&detail);
                            } else {
                                out.push_str(&format!(" `{detail}`"));
                            }
                        }
                        // P1a (#1108): surface tool_call_id so a reader
                        // can correlate parallel calls with their
                        // `Output` rows below. Skip for empty ids —
                        // older sessions may not have them.
                        if !id.is_empty() {
                            out.push_str(&format!(" `{id}`"));
                        }
                        out.push('\n');
                    }
                    out.push('\n');
                }

                // Token counts (verbose only)
                if verbose {
                    render_token_counts(&mut out, msg);
                }
            }

            Role::Tool => {
                let tool_name = msg
                    .tool_call_id
                    .as_deref()
                    .and_then(|id| tool_id_to_name.get(id))
                    .map(|s| s.as_str())
                    .unwrap_or("");

                let content = msg.content.as_deref().unwrap_or("").trim();
                let total_lines = content.lines().count();

                if !content.is_empty() {
                    let effect = classify_tool(tool_name);
                    let max_lines = if verbose {
                        VERBOSE_RESULT_LINES
                    } else {
                        SUMMARY_RESULT_LINES
                    };

                    // Verbose: show all tool output. Summary: only read-only.
                    let show_content = verbose || effect == ToolEffect::ReadOnly;

                    if show_content {
                        // #1157 follow-up: WaitTask returns aggregated multi-task
                        // JSON that's actively user-hostile when dumped as a one-line
                        // code block (escape soup, no readable structure). Detect it
                        // and pretty-print to markdown if the shape matches; fall back
                        // to the generic code-block path on any parse failure.
                        if tool_name == "WaitTask"
                            && let Some(pretty) =
                                pretty_wait_task_output(content, msg.tool_call_id.as_deref())
                        {
                            out.push_str(&pretty);
                        } else {
                            // P1a (#1108): include tool_call_id so parallel
                            // call/result pairs can be matched. The `id`
                            // appears on the matching call's `### **Tool**`
                            // header above, so the reader can grep for it.
                            let header = match msg.tool_call_id.as_deref() {
                                Some(id) if !id.is_empty() => {
                                    format!("**Output for `{id}`:**\n\n```\n")
                                }
                                _ => "**Output:**\n\n```\n".to_string(),
                            };
                            out.push_str(&header);
                            let preview_lines: Vec<&str> =
                                content.lines().take(max_lines).collect();
                            out.push_str(&preview_lines.join("\n"));
                            if total_lines > max_lines {
                                out.push_str(&format!(
                                    "\n\u{2026} ({} more lines)",
                                    total_lines - max_lines
                                ));
                            }
                            out.push_str("\n```\n\n");
                        }
                    } else if total_lines > 0 {
                        out.push_str(&format!(
                            "> _{total_lines} line(s) of output \u{2014} run tool to see full result_\n\n"
                        ));
                    }
                }

                // #1108 P2a: fold the bg sub-agent's narrative trace
                // under its `InvokeAgent` tool result. Pre-#1108 the
                // trace was sink-only and never made it into the
                // export. Use a `<details>` block so the trace is
                // hidden by default in rendered Markdown viewers but
                // still grep-able for debugging. Skipped silently if
                // no events match this tool_call_id (the common case
                // for non-`InvokeAgent` tools).
                if let Some(call_id) = msg.tool_call_id.as_deref()
                    && let Some(events) = events_by_parent.get(call_id)
                    && !events.is_empty()
                {
                    out.push_str(&format!(
                        "<details><summary>\u{1f50d} Sub-agent trace ({} event{})</summary>\n\n",
                        events.len(),
                        if events.len() == 1 { "" } else { "s" },
                    ));
                    out.push_str("```\n");
                    for ev in events {
                        out.push_str(&ev.payload);
                        out.push('\n');
                    }
                    out.push_str("```\n\n</details>\n\n");
                }
            }
        }
    }

    // #1108 P1b: append top-level engine events as a tail section
    // (microcompact, rate-limit, bg-task transitions, etc.). These
    // are the events with no `parent_tool_call_id` — sub-agent ones
    // already rendered above under their `Tool` results. Skipped if
    // empty so non-bg sessions stay visually clean.
    if !top_level_events.is_empty() {
        render_background_activity(&mut out, &top_level_events);
    }

    out
}

/// Render the trailing "Background activity" section.
///
/// One bullet per event, kind-prefixed so the reader can scan for
/// task-state transitions vs. info messages without parsing JSON.
/// Bg-task updates are pretty-printed (`agent:N: Pending → Running`)
/// because raw JSON in a transcript is illegible noise.
///
/// **Iter-heartbeat aggregation (#1158 d)**: by default, per-iteration
/// `Running { iter: N>0 }` heartbeats are dropped from the export and
/// summarised into one trailing line per task (`agent:N: ran 9
/// iterations → Completed`). The state transitions (Pending,
/// Running with iter==0, Cancelled, Completed, Errored) and the iter-0
/// "started" marker are preserved verbatim. Set `KODA_EXPORT_VERBOSE=1`
/// to disable the filter and re-emit every heartbeat (debugging).
fn render_background_activity(out: &mut String, events: &[&SessionEvent]) {
    out.push_str("---\n\n## \u{1f4ca} Background activity\n\n");
    out.push_str(
        "<sub>Engine events captured during the session (info messages, \
         bg-task state transitions). Pre-#1108 these were sink-only and \
         not exported.</sub>\n\n",
    );
    let verbose = std::env::var("KODA_EXPORT_VERBOSE")
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(false);
    // Per-task heartbeat counters — only used when not verbose. Keyed
    // by task_id so multi-agent sessions get one summary line each.
    let mut iter_counts: std::collections::BTreeMap<u64, u32> = std::collections::BTreeMap::new();
    for ev in events {
        let ts = ev.created_at.as_deref().unwrap_or("");
        match ev.kind.as_str() {
            session_event_kind::INFO => {
                out.push_str(&format!("- `{ts}` \u{2139}\u{fe0f} {}\n", ev.payload));
            }
            session_event_kind::BG_TASK_UPDATE => {
                if !verbose
                    && let Some((tid, iter)) = parse_running_iter(&ev.payload)
                    && iter > 0
                {
                    // Drop heartbeat noise; tally for summary.
                    *iter_counts.entry(tid).or_insert(0) += 1;
                    continue;
                }
                let pretty =
                    pretty_bg_task_update(&ev.payload).unwrap_or_else(|| ev.payload.clone());
                out.push_str(&format!("- `{ts}` \u{1f680} {pretty}\n"));
            }
            other => {
                out.push_str(&format!("- `{ts}` `{other}` {}\n", ev.payload));
            }
        }
    }
    // Append per-task heartbeat summary (only fires when we actually
    // dropped heartbeats — no-op for verbose mode and for sessions
    // whose tasks never emitted iter>0).
    for (tid, count) in iter_counts {
        out.push_str(&format!(
            "- \u{1f4ad} agent:{tid}: {count} iteration{plural} aggregated \
             (set `KODA_EXPORT_VERBOSE=1` to expand)\n",
            plural = if count == 1 { "" } else { "s" },
        ));
    }
    out.push('\n');
}

/// Extract `(task_id, iter)` from a `BgTaskUpdate` payload whose
/// status is `Running { iter: N }`. Returns `None` for any other
/// status (Pending, Cancelled, Completed, Errored) or malformed JSON
/// — caller falls back to the regular pretty-print path.
fn parse_running_iter(payload: &str) -> Option<(u64, u32)> {
    let v: serde_json::Value = serde_json::from_str(payload).ok()?;
    let task_id = v.get("task_id")?.as_u64()?;
    let iter = v
        .get("status")?
        .as_object()?
        .get("Running")?
        .as_object()?
        .get("iter")?
        .as_u64()?;
    Some((task_id, iter as u32))
}

/// Best-effort pretty-printer for a `BgTaskUpdate` JSON payload.
///
/// Returns `None` on any parse failure so the caller falls back to
/// rendering the raw JSON — strictly better than dropping the row.
fn pretty_bg_task_update(payload: &str) -> Option<String> {
    let v: serde_json::Value = serde_json::from_str(payload).ok()?;
    let task_id = v.get("task_id")?.as_u64()?;
    let status = v.get("status")?;
    // `AgentStatus` serializes as either a string (`"Pending"`) or
    // an object (`{"Running": {"iter": 3}}`). Handle both.
    let status_str = match status {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Object(map) => map
            .iter()
            .map(|(k, v)| format!("{k}({v})"))
            .collect::<Vec<_>>()
            .join(", "),
        _ => status.to_string(),
    };
    Some(format!("agent:{task_id}: {status_str}"))
}

/// Per-task status icon for `WaitTask` pretty-printing. Centralized so
/// the summary line and per-task headers can't drift.
///
/// Re-exported from [`crate::wait_task_format`] so the markdown export,
/// live TUI ([`crate::tui_render`]), and resumed history
/// ([`crate::history_render`]) all share one status→glyph table
/// (#1163-followup-2: pretty WaitTask in the TUI surfaces too).
use crate::wait_task_format::{first_meaningful_line, wait_status_icon};

/// Pretty-print a `WaitTask` JSON result (#1157) as readable markdown.
///
/// `WaitTask` returns `{tasks: [...], summary: {total, completed, ...}}`
/// where each task is `{task_id, status, agent_name, prompt, output, events?}`.
/// Dumping this as a single-line JSON code block (the generic tool-result
/// path) is actively user-hostile when N agents return multi-paragraph
/// reports — escape soup, no scannable structure.
///
/// Each task collapses into a `<details>` block whose `<summary>` carries
/// task id + status + a one-line preview, so a 4-agent scan renders as
/// a 4-row TOC by default and the reader expands the ones they care
/// about. Inner heading levels (`### Key Files` etc. inside the agent's
/// output) are isolated from the parent heading hierarchy by the
/// `<details>` wrapper.
///
/// Returns `None` on any parse failure or shape mismatch — the caller
/// falls back to the generic code-block render. Presentation-only;
/// the raw JSON remains the source of truth in the DB.
fn pretty_wait_task_output(payload: &str, tool_call_id: Option<&str>) -> Option<String> {
    let v: serde_json::Value = serde_json::from_str(payload).ok()?;
    let tasks = v.get("tasks")?.as_array()?;
    if tasks.is_empty() {
        return None;
    }

    // Summary tallies. We pull explicitly per status (not iter() over
    // the map) so the order in the rendered output is stable across
    // sessions — counters with zero count are simply omitted.
    let summary = v.get("summary").and_then(|s| s.as_object());
    let count = |k: &str| -> u64 {
        summary
            .and_then(|s| s.get(k))
            .and_then(|v| v.as_u64())
            .unwrap_or(0)
    };
    let total = summary
        .and_then(|s| s.get("total"))
        .and_then(|v| v.as_u64())
        .unwrap_or(tasks.len() as u64);

    let mut summary_parts: Vec<String> = Vec::new();
    for (key, label) in [
        ("completed", "completed"),
        ("timed_out", "timed out"),
        ("cancelled", "cancelled"),
        ("not_found", "not found"),
        ("forbidden", "forbidden"),
        ("parse_error", "parse error"),
    ] {
        let n = count(key);
        if n > 0 {
            summary_parts.push(format!("{} {n} {label}", wait_status_icon(key)));
        }
    }
    let summary_suffix = if summary_parts.is_empty() {
        String::new()
    } else {
        format!(" \u{2014} {}", summary_parts.join(" \u{00B7} "))
    };

    let mut out = String::new();
    let header = match tool_call_id {
        Some(id) if !id.is_empty() => format!(
            "**Output for `{id}`** \u{2014} `WaitTask` gathered {total} task(s){summary_suffix}\n\n"
        ),
        _ => format!("**Output** \u{2014} `WaitTask` gathered {total} task(s){summary_suffix}\n\n"),
    };
    out.push_str(&header);

    for task in tasks {
        let task_id = task.get("task_id").and_then(|v| v.as_str()).unwrap_or("?");
        let status = task.get("status").and_then(|v| v.as_str()).unwrap_or("?");
        let icon = wait_status_icon(status);
        let agent_name = task
            .get("agent_name")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let agent_label = if agent_name.is_empty() {
            String::new()
        } else {
            format!(" \u{2014} <code>{agent_name}</code>")
        };
        let preview = task
            .get("output")
            .and_then(|v| v.as_str())
            .map(|s| first_meaningful_line(s, 120))
            .unwrap_or_default();
        let preview_html = if preview.is_empty() {
            String::new()
        } else {
            // Escape angle brackets so a stray `<` in the agent's first
            // line doesn't open a phantom HTML tag inside <summary>.
            let safe = preview
                .replace('&', "&amp;")
                .replace('<', "&lt;")
                .replace('>', "&gt;");
            format!(" \u{2014} <i>{safe}</i>")
        };

        out.push_str(&format!(
            "<details>\n<summary><b>{task_id}</b>{agent_label} {icon} {status}{preview_html}</summary>\n\n"
        ));

        // Prompt as a single-line blockquote for context. Long prompts
        // get truncated to ~200 chars; the full version lives in the
        // raw JSON in the DB if anyone needs to dig.
        if let Some(prompt) = task.get("prompt").and_then(|v| v.as_str()) {
            let one_liner = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
            let trimmed = if one_liner.chars().count() > 200 {
                let head: String = one_liner.chars().take(200).collect();
                format!("{head}\u{2026}")
            } else {
                one_liner
            };
            out.push_str(&format!("> _Prompt:_ {trimmed}\n\n"));
        }

        // Headline content: the agent's output, or a friendly error if
        // the task didn't complete (timed_out / not_found / forbidden).
        if let Some(output) = task.get("output").and_then(|v| v.as_str()) {
            out.push_str(output.trim_end());
            out.push_str("\n\n");
        } else if let Some(err) = task.get("error").and_then(|v| v.as_str()) {
            out.push_str(&format!("> \u{26A0} _{err}_\n\n"));
        }

        // Tool events as a flat bullet list. Not nested in another
        // <details> — some Markdown renderers (and many Markdown-to-PDF
        // pipelines) get squirrelly with nested collapsibles. The
        // count is already in the parent <summary> so the reader knows
        // what's coming.
        if let Some(events) = task.get("events").and_then(|v| v.as_array())
            && !events.is_empty()
        {
            out.push_str(&format!("_Tool calls ({}):_ ", events.len()));
            let names: Vec<String> = events
                .iter()
                .filter_map(|e| e.as_str())
                .map(|s| format!("`{}`", s.trim()))
                .collect();
            out.push_str(&names.join(" \u{00B7} "));
            out.push_str("\n\n");
        }

        out.push_str("</details>\n\n");
    }

    Some(out)
}

// ── Verbose-mode helpers ─────────────────────────────────────────────

/// Render the metadata table at the top of a verbose transcript.
fn render_metadata_table(out: &mut String, meta: &SessionMeta) {
    out.push_str("| Field | Value |\n|---|---|\n");
    out.push_str(&format!("| Session | `{}` |\n", meta.session_id));
    out.push_str(&format!("| Model | {} |\n", meta.model));
    out.push_str(&format!("| Provider | {} |\n", meta.provider));
    out.push_str(&format!("| Project | `{}` |\n", meta.project_root));
    if let Some(ref started) = meta.started_at {
        out.push_str(&format!("| Started | {started} |\n"));
    }
    out.push('\n');
}

/// Render a role header with an optional timestamp (verbose mode).
fn render_role_header(out: &mut String, label: &str, msg: &Message, verbose: bool) {
    out.push_str(&format!("## {label}"));
    if verbose && let Some(ref ts) = msg.created_at {
        // Show HH:MM:SS portion if it looks like an ISO timestamp.
        let time_part = ts.split('T').nth(1).and_then(|t| t.get(..8)).unwrap_or(ts);
        out.push_str(&format!("  <sub>{time_part}</sub>"));
    }
    out.push_str("\n\n");
}

/// Render token counts after an assistant message (verbose mode).
fn render_token_counts(out: &mut String, msg: &Message) {
    let mut parts: Vec<String> = Vec::new();
    if let Some(p) = msg.prompt_tokens {
        parts.push(format!("{p} prompt"));
    }
    if let Some(c) = msg.completion_tokens {
        parts.push(format!("{c} completion"));
    }
    if let Some(cr) = msg.cache_read_tokens
        && cr > 0
    {
        parts.push(format!("{cr} cache-read"));
    }
    if let Some(cc) = msg.cache_creation_tokens
        && cc > 0
    {
        parts.push(format!("{cc} cache-write"));
    }
    if let Some(t) = msg.thinking_tokens
        && t > 0
    {
        parts.push(format!("{t} thinking"));
    }
    if !parts.is_empty() {
        out.push_str(&format!("<sub>tokens: {}</sub>\n\n", parts.join(" · ")));
    }
}

/// Human-readable icon for each tool type.
fn tool_icon(name: &str) -> &'static str {
    match name {
        "Read" => "📄",
        "Write" => "✏️",
        "Edit" => "✏️",
        "Delete" => "🗑️",
        "Bash" => "💻",
        "Grep" => "🔍",
        "List" | "Glob" => "📁",
        "WebFetch" => "🌐",
        "TodoWrite" => "📋",
        "MemoryWrite" | "MemoryRead" => "🧠",
        "InvokeAgent" => "🤖",
        "AskUser" => "💬",
        _ => "🔧",
    }
}

/// One-line summary of a tool call's arguments, with file paths and URLs
/// rendered as **markdown links** when hyperlinks are enabled.
///
/// Per-tool dispatch is delegated to [`crate::tool_header::detail_text`]
/// so the same `(name, args)` pair always produces the same human-readable
/// summary across the live TUI, history replay, and transcript export.
/// This wrapper only adds the markdown-link layer on top of the shared
/// plain-text summary.
///
/// `bash_limit` controls Bash command truncation (80 in summary, 500 in verbose).
/// `project_root` is used to resolve relative file paths into absolute
/// `file:///` URIs; if empty or the path is already absolute, no resolution
/// is performed.
fn tool_detail_markdown(
    name: &str,
    args_json: &str,
    bash_limit: usize,
    project_root: &str,
    link: bool,
) -> String {
    let args: serde_json::Value =
        serde_json::from_str(args_json).unwrap_or(serde_json::Value::Null);
    let raw = crate::tool_header::detail_text(name, &args, bash_limit);
    if !link || raw.is_empty() {
        return raw;
    }
    match name {
        "Read" | "Write" | "Edit" | "Delete" => {
            // `raw` is the file path; wrap as [path](file:///abs).
            let abs = absolute_path(&raw, project_root);
            format!("[{raw}]({})", file_uri(&abs))
        }
        "WebFetch" => format!("[{raw}]({raw})"),
        // Grep / Glob / List / Bash / generic: leave as plain text.
        // The directory portion of Grep is intentionally NOT linked
        // because the eye-catching part is the pattern, not the dir.
        _ => raw,
    }
}

/// Resolve `path` against `project_root` if relative; pass through if absolute.
///
/// We deliberately don't try to canonicalize (the file may not exist on
/// the machine viewing the transcript). The resulting string is best-effort.
fn absolute_path(path: &str, project_root: &str) -> String {
    if path.starts_with('/') || project_root.is_empty() {
        return path.to_string();
    }
    let root = project_root.trim_end_matches('/');
    format!("{root}/{path}")
}

/// Build a `file:///` URI from an absolute path with light percent-encoding.
///
/// Encodes the characters most likely to break markdown link parsing:
/// space, parenthesis, square bracket. Other characters are passed through
/// — most viewers tolerate them, and full percent-encoding would pull in a
/// dependency for marginal benefit.
fn file_uri(abs_path: &str) -> String {
    let mut out = String::with_capacity(abs_path.len() + 8);
    out.push_str("file://");
    if !abs_path.starts_with('/') {
        out.push('/');
    }
    for ch in abs_path.chars() {
        match ch {
            ' ' => out.push_str("%20"),
            '(' => out.push_str("%28"),
            ')' => out.push_str("%29"),
            '[' => out.push_str("%5B"),
            ']' => out.push_str("%5D"),
            _ => out.push(ch),
        }
    }
    out
}

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

    /// Serializes tests that depend on `HYPERLINK_KILL_SWITCH`.
    ///
    /// `kill_switch_disables_hyperlinks` mutates the env var while the
    /// other tests in this module just read it via `hyperlinks_enabled()`.
    /// Since env vars are process-global and `cargo test` runs tests in
    /// parallel by default, the writer can flip the var to "off" mid-read
    /// of any other test that calls `render()` and asserts on hyperlinks.
    /// On macOS this raced ~50% of the time and blocked PR #1107.
    ///
    /// Lock acquisition: every test that depends on the env var's value
    /// (one writer, three readers) takes this lock for its full duration.
    /// Other transcript tests don't assert on hyperlinks at all (they
    /// look at headers, paths, code blocks, etc.) so they don't need the
    /// lock and can keep running in parallel.
    static HYPERLINK_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn make_msg(role: Role, content: &str) -> Message {
        Message {
            id: 0,
            session_id: "test".into(),
            role,
            content: Some(content.into()),
            full_content: None,
            tool_calls: None,
            tool_call_id: None,
            prompt_tokens: None,
            completion_tokens: None,
            cache_read_tokens: None,
            cache_creation_tokens: None,
            thinking_tokens: None,
            thinking_content: None,
            created_at: None,
        }
    }

    fn default_meta() -> SessionMeta {
        SessionMeta {
            session_id: "test-session".into(),
            title: None,
            started_at: None,
            model: "test-model".into(),
            provider: "test-provider".into(),
            project_root: "/tmp/project".into(),
        }
    }

    #[test]
    fn empty_messages_produces_header_only() {
        let meta = SessionMeta {
            title: Some("Test Session".into()),
            ..default_meta()
        };
        let out = render(&[], &[], &meta, false);
        assert!(out.contains("# Test Session"));
        assert!(!out.contains("🧑 User"));
    }

    #[test]
    fn user_message_renders_correctly() {
        let msgs = vec![make_msg(Role::User, "hello koda")];
        let out = render(&msgs, &[], &default_meta(), false);
        assert!(out.contains("🧑 User"));
        assert!(out.contains("hello koda"));
    }

    #[test]
    fn assistant_message_renders_correctly() {
        let msgs = vec![make_msg(Role::Assistant, "I can help!")];
        let out = render(&msgs, &[], &default_meta(), false);
        assert!(out.contains("🤖 Assistant"));
        assert!(out.contains("I can help!"));
    }

    #[test]
    fn system_messages_skipped() {
        let msgs = vec![
            make_msg(Role::System, "secret prompt"),
            make_msg(Role::User, "hi"),
        ];
        let out = render(&msgs, &[], &default_meta(), false);
        assert!(!out.contains("secret prompt"));
    }

    #[test]
    fn tool_read_result_shown_as_code_block() {
        let mut result_msg = make_msg(Role::Tool, "fn main() {}\n");
        result_msg.tool_call_id = Some("call_1".into());

        let mut assistant_msg = make_msg(Role::Assistant, "");
        assistant_msg.tool_calls = Some(flat_tool_calls_json(&[(
            "call_1",
            "Read",
            r#"{"file_path":"src/main.rs"}"#,
        )]));

        let msgs = vec![assistant_msg, result_msg];
        let out = render(&msgs, &[], &default_meta(), false);
        assert!(out.contains("```"));
        assert!(out.contains("fn main()"));
    }

    #[test]
    fn bash_result_shows_summary_not_content() {
        let mut result_msg = make_msg(Role::Tool, "line1\nline2\nline3");
        result_msg.tool_call_id = Some("call_2".into());

        let mut assistant_msg = make_msg(Role::Assistant, "");
        assistant_msg.tool_calls = Some(flat_tool_calls_json(&[(
            "call_2",
            "Bash",
            r#"{"command":"ls"}"#,
        )]));

        let msgs = vec![assistant_msg, result_msg];
        let out = render(&msgs, &[], &default_meta(), false);
        // Bash is mutating → summarised in summary mode, not shown verbatim
        assert!(!out.contains("line1"));
        assert!(out.contains("3 line(s) of output"));
    }

    #[test]
    fn thinking_content_renders_as_blockquote() {
        // thinking_content is Claude's chain-of-thought — it is intentionally
        // included in the exported transcript as a blockquote so the user can
        // review the model's reasoning (#819).
        let mut msg = make_msg(Role::Assistant, "The answer is 42.");
        msg.thinking_content = Some("Let me think step by step: 6 x 7 = 42.".into());

        let out = render(&[msg], &[], &default_meta(), false);
        assert!(
            out.contains("The answer is 42."),
            "response text must appear"
        );
        assert!(
            out.contains("Thinking"),
            "thinking block header must appear in transcript"
        );
        assert!(
            out.contains("Let me think step by step"),
            "thinking content must appear in transcript",
        );
    }

    #[test]
    fn verbose_header_includes_metadata() {
        let meta = SessionMeta {
            session_id: "sess-42".into(),
            title: Some("Debug Session".into()),
            started_at: Some("2026-04-14T12:00:00Z".into()),
            model: "claude-sonnet-4-20250514".into(),
            provider: "anthropic".into(),
            project_root: "/home/user/project".into(),
        };
        let out = render(&[], &[], &meta, true);
        assert!(out.contains("sess-42"), "session ID in header");
        assert!(out.contains("claude-sonnet-4-20250514"), "model in header");
        assert!(out.contains("anthropic"), "provider in header");
        assert!(out.contains("/home/user/project"), "project root in header");
    }

    #[test]
    fn verbose_shows_token_counts() {
        let mut msg = make_msg(Role::Assistant, "The answer.");
        msg.prompt_tokens = Some(100);
        msg.completion_tokens = Some(50);
        msg.cache_read_tokens = Some(80);

        let out = render(&[msg], &[], &default_meta(), true);
        assert!(out.contains("100 prompt"), "prompt tokens shown");
        assert!(out.contains("50 completion"), "completion tokens shown");
        assert!(out.contains("80 cache-read"), "cache-read tokens shown");
    }

    #[test]
    fn summary_hides_token_counts() {
        let mut msg = make_msg(Role::Assistant, "The answer.");
        msg.prompt_tokens = Some(100);
        msg.completion_tokens = Some(50);

        let out = render(&[msg], &[], &default_meta(), false);
        assert!(!out.contains("100 prompt"));
    }

    #[test]
    fn verbose_shows_timestamps() {
        let mut msg = make_msg(Role::User, "hello");
        msg.created_at = Some("2026-04-14T09:15:30Z".into());

        let out = render(&[msg], &[], &default_meta(), true);
        assert!(out.contains("09:15:30"), "timestamp shown in verbose");
    }

    #[test]
    fn summary_hides_timestamps() {
        let mut msg = make_msg(Role::User, "hello");
        msg.created_at = Some("2026-04-14T09:15:30Z".into());

        let out = render(&[msg], &[], &default_meta(), false);
        assert!(!out.contains("09:15:30"), "timestamp hidden in summary");
    }

    #[test]
    fn bash_result_shown_in_verbose_mode() {
        let mut result_msg = make_msg(Role::Tool, "line1\nline2\nline3");
        result_msg.tool_call_id = Some("call_3".into());

        let mut assistant_msg = make_msg(Role::Assistant, "");
        assistant_msg.tool_calls = Some(flat_tool_calls_json(&[(
            "call_3",
            "Bash",
            r#"{"command":"ls"}"#,
        )]));

        let msgs = vec![assistant_msg, result_msg];
        let out = render(&msgs, &[], &default_meta(), true);
        // Verbose mode shows all tool output, including Bash
        assert!(out.contains("line1"));
        assert!(out.contains("line3"));
    }

    // ── Markdown hyperlink emission ────────────────────────────────

    /// Build a `tool_calls` JSON string the way production code does it:
    /// `serde_json::to_string(&Vec<ToolCall>)` — the FLAT shape with
    /// `function_name` and `arguments` at the top level.
    ///
    /// Pre-#1108 every transcript test built a *different* (nested OpenAI)
    /// shape via `json!({"function": {...}})`. Tests passed in CI while
    /// every real export rendered tool calls as `### 🔧 **Tool**`.
    /// New fixtures MUST go through this helper so test data matches
    /// production data and the bug class can't recur.
    fn flat_tool_calls_json(calls: &[(&str, &str, &str)]) -> String {
        use koda_core::providers::ToolCall;
        let toolcalls: Vec<ToolCall> = calls
            .iter()
            .map(|(id, name, args)| ToolCall {
                id: (*id).to_string(),
                function_name: (*name).to_string(),
                arguments: (*args).to_string(),
                thought_signature: None,
            })
            .collect();
        serde_json::to_string(&toolcalls).expect("ToolCall serializes")
    }

    /// Build an assistant message with a single tool call.
    ///
    /// Routes through [`flat_tool_calls_json`] so the resulting
    /// `tool_calls` field matches what production code persists.
    fn assistant_with_call(name: &str, args_json: &str) -> Message {
        let mut m = make_msg(Role::Assistant, "");
        m.tool_calls = Some(flat_tool_calls_json(&[("c1", name, args_json)]));
        m
    }

    #[test]
    fn read_path_emits_markdown_link_with_file_uri() {
        let _g = HYPERLINK_ENV_LOCK.lock().unwrap();
        let msg = assistant_with_call("Read", r#"{"file_path":"src/main.rs"}"#);
        let meta = SessionMeta {
            project_root: "/home/user/proj".into(),
            ..default_meta()
        };
        let out = render(&[msg], &[], &meta, false);
        assert!(
            out.contains("[src/main.rs](file:///home/user/proj/src/main.rs)"),
            "relative path should resolve under project_root, got:\n{out}"
        );
    }

    #[test]
    fn absolute_read_path_skips_root_join() {
        let _g = HYPERLINK_ENV_LOCK.lock().unwrap();
        let msg = assistant_with_call("Read", r#"{"file_path":"/etc/hosts"}"#);
        let meta = SessionMeta {
            project_root: "/home/user/proj".into(),
            ..default_meta()
        };
        let out = render(&[msg], &[], &meta, false);
        assert!(
            out.contains("[/etc/hosts](file:///etc/hosts)"),
            "absolute path should pass through, got:\n{out}"
        );
    }

    #[test]
    fn webfetch_url_becomes_self_link() {
        let _g = HYPERLINK_ENV_LOCK.lock().unwrap();
        let msg = assistant_with_call("WebFetch", r#"{"url":"https://example.com/x"}"#);
        let out = render(&[msg], &[], &default_meta(), false);
        assert!(
            out.contains("[https://example.com/x](https://example.com/x)"),
            "URL should be a markdown self-link, got:\n{out}"
        );
    }

    #[test]
    fn bash_detail_stays_plain_codespan() {
        // Bash commands aren't paths or URLs — keep them in backticks
        // so monospace formatting (and shell tokens) survive.
        let msg = assistant_with_call("Bash", r#"{"command":"git status"}"#);
        let out = render(&[msg], &[], &default_meta(), false);
        assert!(out.contains("`git status`"), "got:\n{out}");
        assert!(
            !out.contains("](git status)"),
            "bash should never be linked"
        );
    }

    #[test]
    fn grep_detail_stays_plain_codespan() {
        let msg = assistant_with_call("Grep", r#"{"search_string":"TODO","directory":"src"}"#);
        let out = render(&[msg], &[], &default_meta(), false);
        assert!(out.contains("`\"TODO\" in src`"), "got:\n{out}");
    }

    #[test]
    fn kill_switch_disables_hyperlinks() {
        let _g = HYPERLINK_ENV_LOCK.lock().unwrap();
        // **#1109 F1**: was `unsafe { std::env::set_var }` with snapshot/restore.
        // Now uses [`koda_core::runtime_env`] — thread-safe, no UB, no
        // `std::env` mutation. The HYPERLINK_ENV_LOCK still serializes us
        // against parallel reader tests in this binary.
        koda_core::runtime_env::set(HYPERLINK_KILL_SWITCH, "off");
        let msg = assistant_with_call("Read", r#"{"file_path":"/x.rs"}"#);
        let out = render(&[msg], &[], &default_meta(), false);
        koda_core::runtime_env::remove(HYPERLINK_KILL_SWITCH);
        assert!(out.contains("`/x.rs`"), "plain text expected, got:\n{out}");
        assert!(!out.contains("file:///"), "link should be suppressed");
    }

    #[test]
    fn dry_equivalence_with_tool_header_detail_text() {
        // Regression guard: transcript detail strings must agree with the
        // shared `tool_header::detail_text` for every supported tool. If
        // someone forks the dispatch back into this module, this test fails.
        use crate::tool_header::detail_text;
        let cases: Vec<(&str, serde_json::Value, usize)> = vec![
            ("Read", serde_json::json!({"file_path": "a.rs"}), 80),
            ("Bash", serde_json::json!({"command": "echo hi"}), 80),
            (
                "Grep",
                serde_json::json!({"search_string": "x", "directory": "."}),
                80,
            ),
            ("Glob", serde_json::json!({"pattern": "**/*.rs"}), 80),
            ("List", serde_json::json!({"directory": "src"}), 80),
            ("WebFetch", serde_json::json!({"url": "https://x"}), 80),
        ];
        for (name, args, bash) in cases {
            let from_helper = detail_text(name, &args, bash);
            // tool_detail_markdown with link=false is a pure pass-through.
            let from_transcript = tool_detail_markdown(name, &args.to_string(), bash, "", false);
            assert_eq!(
                from_helper, from_transcript,
                "transcript detail must match tool_header::detail_text for {name}"
            );
        }
    }

    #[test]
    fn file_uri_percent_encodes_breaking_chars() {
        // Spaces and brackets break naive markdown link parsers — percent-
        // encode the most common offenders so links survive copy/paste.
        let uri = file_uri("/My Files/[draft].md");
        assert_eq!(uri, "file:///My%20Files/%5Bdraft%5D.md");
    }

    // ── #1108 P0/P1a: tool name + args + call_id surfacing ────────────

    /// Regression test for #1108 P0: real production tool_calls JSON
    /// (the flat `function_name` shape from `serde_json::to_string(
    /// &Vec<ToolCall>)`) MUST surface the tool name in the rendered
    /// markdown header. Pre-fix this test would have failed with
    /// `### 🔧 **Tool**` — every export silently lied about which
    /// tool was called for the entire history of the export feature.
    #[test]
    fn production_tool_calls_json_renders_tool_name_in_header() {
        let mut msg = make_msg(Role::Assistant, "");
        msg.tool_calls = Some(flat_tool_calls_json(&[(
            "call_xyz",
            "InvokeAgent",
            r#"{"agent_name":"explore","prompt":"map the repo"}"#,
        )]));
        let out = render(&[msg], &[], &default_meta(), false);
        assert!(
            out.contains("**InvokeAgent**"),
            "production-shape tool_calls must render the tool NAME in the header. \
             Pre-#1108 every real export rendered `### 🔧 **Tool**` because the \
             renderer read the OpenAI-nested shape (`function.name`) while \
             persistence wrote the flat shape (`function_name`). got:\n{out}"
        );
        assert!(
            !out.contains("**Tool**"),
            "`**Tool**` is the silent fallback that masked the bug for months. \
             It should never appear when the call has a real function_name. \
             got:\n{out}"
        );
    }

    /// Companion test: production-shape tool_calls must also expose the
    /// arguments to the `tool_header::detail_text` formatter. Pre-#1108
    /// args were silently `"{}"` so detail rendered as `🔧 **Tool**`
    /// with no path/command suffix.
    #[test]
    fn production_tool_calls_json_renders_tool_args_in_header() {
        let mut msg = make_msg(Role::Assistant, "");
        msg.tool_calls = Some(flat_tool_calls_json(&[(
            "call_zzz",
            "Read",
            r#"{"file_path":"src/very_distinctive_file.rs"}"#,
        )]));
        let out = render(&[msg], &[], &default_meta(), false);
        assert!(
            out.contains("very_distinctive_file.rs"),
            "production-shape tool_calls must surface the arguments. \
             Pre-#1108 args were swallowed because the renderer read \
             `function.arguments` (nested) while persistence wrote \
             `arguments` (flat). got:\n{out}"
        );
    }

    /// Regression test for #1108 P1a: every tool call header must
    /// include the `tool_call_id` so a reader can correlate parallel
    /// calls (e.g. 3× `InvokeAgent` in one assistant turn) with their
    /// corresponding `Output` rows. Pre-fix the id only existed
    /// internally and never reached the export.
    #[test]
    fn tool_call_id_appears_in_header_for_correlation() {
        let mut msg = make_msg(Role::Assistant, "");
        msg.tool_calls = Some(flat_tool_calls_json(&[
            (
                "call_a",
                "InvokeAgent",
                r#"{"agent_name":"explore","prompt":"a"}"#,
            ),
            (
                "call_b",
                "InvokeAgent",
                r#"{"agent_name":"explore","prompt":"b"}"#,
            ),
        ]));
        let out = render(&[msg], &[], &default_meta(), false);
        assert!(
            out.contains("call_a") && out.contains("call_b"),
            "both tool_call_ids must appear in the header so parallel \
             InvokeAgent calls can be matched to their Output rows. \
             got:\n{out}"
        );
    }

    /// Regression test for #1108 P1a: when a `Tool` result message
    /// carries a `tool_call_id`, the `**Output**` header in the
    /// transcript must include it so it can be matched to its
    /// originating call.
    #[test]
    fn tool_call_id_appears_in_result_output_header() {
        let mut a = make_msg(Role::Assistant, "");
        a.tool_calls = Some(flat_tool_calls_json(&[(
            "call_corr",
            "Read",
            r#"{"file_path":"x.rs"}"#,
        )]));
        let mut t = make_msg(Role::Tool, "file contents here");
        t.tool_call_id = Some("call_corr".into());
        let out = render(&[a, t], &[], &default_meta(), false);
        assert!(
            out.contains("call_corr"),
            "the result row's Output header must mention its tool_call_id \
             so parallel call/result pairs can be matched. got:\n{out}"
        );
    }

    // ── #1108 P2a: sub-agent trace folding ────────────────────────────

    /// Helper: build a `SessionEvent` for renderer tests. The DB id
    /// and timestamp don't matter — the renderer only uses `kind`,
    /// `payload`, and `parent_tool_call_id`.
    fn ev(kind: &str, payload: &str, parent: Option<&str>) -> SessionEvent {
        SessionEvent {
            id: 0,
            session_id: "sess".into(),
            kind: kind.into(),
            payload: payload.into(),
            parent_tool_call_id: parent.map(str::to_string),
            created_at: Some("2026-04-27 06:00:00".into()),
        }
    }

    #[test]
    fn sub_agent_events_fold_under_matching_tool_result() {
        let mut a = make_msg(Role::Assistant, "");
        a.tool_calls = Some(flat_tool_calls_json(&[(
            "call_inv",
            "InvokeAgent",
            r#"{"agent_name":"explore","prompt":"go"}"#,
        )]));
        let mut t = make_msg(Role::Tool, "sub-agent finished");
        t.tool_call_id = Some("call_inv".into());

        let events = vec![
            ev(
                session_event_kind::SUB_AGENT_EVENT,
                "  \u{1f527} Read foo.rs",
                Some("call_inv"),
            ),
            ev(
                session_event_kind::SUB_AGENT_EVENT,
                "  \u{1f4ad} Looking at imports\u{2026}",
                Some("call_inv"),
            ),
        ];

        let out = render(&[a, t], &events, &default_meta(), true);
        assert!(
            out.contains("<details><summary>"),
            "sub-agent events must be folded in a <details> block. got:\n{out}"
        );
        assert!(
            out.contains("Sub-agent trace (2 events)"),
            "summary must show the folded event count"
        );
        assert!(out.contains("Read foo.rs"));
        assert!(out.contains("Looking at imports"));
    }

    #[test]
    fn sub_agent_events_skipped_when_no_matching_tool_call_id() {
        // Event has parent "call_X" but no tool result carries that
        // id — the event must be silently dropped from the per-tool
        // section (it'll surface in "Background activity" only if it
        // has no parent at all, which it does here).
        let mut t = make_msg(Role::Tool, "some output");
        t.tool_call_id = Some("call_OTHER".into());
        let events = vec![ev(
            session_event_kind::SUB_AGENT_EVENT,
            "orphan trace line",
            Some("call_X"),
        )];
        let out = render(&[t], &events, &default_meta(), true);
        assert!(
            !out.contains("orphan trace line"),
            "orphan parented events must not surface anywhere. got:\n{out}"
        );
        assert!(
            !out.contains("<details>"),
            "no details block when no events match the tool result"
        );
    }

    #[test]
    fn top_level_events_appear_in_background_activity_section() {
        let events = vec![
            ev(session_event_kind::INFO, "context compacted", None),
            ev(
                session_event_kind::BG_TASK_UPDATE,
                r#"{"task_id":7,"status":"Pending"}"#,
                None,
            ),
        ];
        let out = render(&[], &events, &default_meta(), true);
        assert!(
            out.contains("Background activity"),
            "top-level events must trigger the trailing section. got:\n{out}"
        );
        assert!(out.contains("context compacted"));
        assert!(
            out.contains("agent:7: Pending"),
            "BgTaskUpdate JSON must be pretty-printed in canonical agent:N form (#1158 e). got:\n{out}"
        );
    }

    #[test]
    fn iter_heartbeats_aggregated_into_summary_line_by_default() {
        // #1158 (d): per-iter Running heartbeats are noise in exports.
        // Default mode should drop them and emit ONE summary line per
        // task at the bottom. State transitions (Pending, Completed,
        // iter==0 "started" marker) must remain visible.
        let events = vec![
            ev(
                session_event_kind::BG_TASK_UPDATE,
                r#"{"task_id":1,"status":"Pending"}"#,
                None,
            ),
            ev(
                session_event_kind::BG_TASK_UPDATE,
                r#"{"task_id":1,"status":{"Running":{"iter":0}}}"#,
                None,
            ),
            ev(
                session_event_kind::BG_TASK_UPDATE,
                r#"{"task_id":1,"status":{"Running":{"iter":1}}}"#,
                None,
            ),
            ev(
                session_event_kind::BG_TASK_UPDATE,
                r#"{"task_id":1,"status":{"Running":{"iter":2}}}"#,
                None,
            ),
            ev(
                session_event_kind::BG_TASK_UPDATE,
                r#"{"task_id":1,"status":{"Running":{"iter":3}}}"#,
                None,
            ),
            ev(
                session_event_kind::BG_TASK_UPDATE,
                r#"{"task_id":1,"status":{"Completed":{"summary":"done"}}}"#,
                None,
            ),
        ];
        let out = render(&[], &events, &default_meta(), true);
        // State transitions must survive.
        assert!(out.contains("agent:1: Pending"), "missing Pending: {out}");
        assert!(
            out.contains("\"iter\":0"),
            "iter==0 marker must survive (treated as state transition): {out}"
        );
        assert!(out.contains("Completed"), "Completed must survive: {out}");
        // The 3 iter>0 heartbeats must NOT appear individually.
        assert!(
            !out.contains("\"iter\":1"),
            "iter=1 heartbeat should be aggregated, not shown raw: {out}"
        );
        assert!(
            !out.contains("\"iter\":2"),
            "iter=2 heartbeat should be aggregated: {out}"
        );
        // Summary line must show the count of dropped heartbeats.
        assert!(
            out.contains("agent:1: 3 iterations aggregated"),
            "missing per-task summary line: {out}"
        );
    }

    #[test]
    fn verbose_mode_re_emits_every_iter_heartbeat() {
        // #1158 (d): KODA_EXPORT_VERBOSE=1 disables aggregation so
        // operators can debug bg-agent loops post-hoc.
        // SAFETY: tests in this module run sequentially per
        // `#[cfg(test)]` defaults; we restore the var before returning.
        // SAFETY (Rust 2024): set_var/remove_var are unsafe because
        // they mutate process-global env. Documented as fine in
        // single-threaded test contexts.
        // SAFETY: tests run sequentially; mutating process env in a
        // single-threaded test context is the documented use case.
        unsafe {
            std::env::set_var("KODA_EXPORT_VERBOSE", "1");
        }
        let events = vec![
            ev(
                session_event_kind::BG_TASK_UPDATE,
                r#"{"task_id":1,"status":{"Running":{"iter":1}}}"#,
                None,
            ),
            ev(
                session_event_kind::BG_TASK_UPDATE,
                r#"{"task_id":1,"status":{"Running":{"iter":2}}}"#,
                None,
            ),
        ];
        let out = render(&[], &events, &default_meta(), true);
        unsafe {
            std::env::remove_var("KODA_EXPORT_VERBOSE");
        }
        assert!(
            out.contains("\"iter\":1") && out.contains("\"iter\":2"),
            "verbose mode must preserve all heartbeats: {out}"
        );
        assert!(
            !out.contains("aggregated"),
            "verbose mode must NOT emit summary line: {out}"
        );
    }

    #[test]
    fn no_background_activity_section_when_no_top_level_events() {
        let out = render(&[], &[], &default_meta(), true);
        assert!(
            !out.contains("Background activity"),
            "empty events must not produce a noisy empty section"
        );
    }

    #[test]
    fn pretty_bg_task_update_falls_back_to_raw_on_bad_json() {
        // Defensive: malformed payloads must round-trip to the
        // transcript untouched, never silently dropped.
        let events = vec![ev(
            session_event_kind::BG_TASK_UPDATE,
            "not json at all {{{",
            None,
        )];
        let out = render(&[], &events, &default_meta(), true);
        assert!(
            out.contains("not json at all {{{"),
            "unparseable BgTaskUpdate must surface verbatim. got:\n{out}"
        );
    }

    // ── #1157 follow-up: WaitTask pretty-printer ────────────────────

    /// Build a tool-result message carrying a WaitTask JSON payload
    /// (#1157 shape: `{tasks: [...], summary: {...}}`). Helper, not
    /// a test.
    fn wait_task_result(call_id: &str, payload: serde_json::Value) -> Message {
        let mut m = make_msg(Role::Tool, &payload.to_string());
        m.tool_call_id = Some(call_id.into());
        m
    }

    /// The `tool_id_to_name` map is keyed off the assistant message's
    /// `tool_calls` JSON. We need a matching assistant message that
    /// declares the WaitTask call so the renderer knows the tool name.
    fn assistant_calling_wait_task(call_id: &str) -> Message {
        let calls = serde_json::json!([{
            "id": call_id,
            "function": {"name": "WaitTask", "arguments": "{}"}
        }]);
        let mut m = make_msg(Role::Assistant, "");
        m.tool_calls = Some(calls.to_string());
        m
    }

    #[test]
    fn wait_task_result_renders_as_collapsible_per_task_blocks_not_json_blob() {
        // The bug from the user-reported transcript: 4 sub-agent
        // results jammed into one escape-soup line of JSON. After
        // the fix, each task is a <details> block.
        let payload = serde_json::json!({
            "summary": {"total": 2, "completed": 2},
            "tasks": [
                {
                    "task_id": "agent:1",
                    "status": "completed",
                    "agent_name": "explore",
                    "prompt": "Scan koda-core/",
                    "output": "### Key Files\n- foo.rs\n- bar.rs",
                    "events": ["  \u{1F527} Read", "  \u{1F527} Grep"],
                },
                {
                    "task_id": "agent:2",
                    "status": "completed",
                    "agent_name": "explore",
                    "prompt": "Scan koda-cli/",
                    "output": "### TUI findings\nLooks fine.",
                    "events": [],
                },
            ],
        });
        let msgs = vec![
            assistant_calling_wait_task("call_xyz"),
            wait_task_result("call_xyz", payload),
        ];
        let out = render(&msgs, &[], &default_meta(), false);

        // Header carries the call id + summary tally.
        assert!(
            out.contains("Output for `call_xyz`") && out.contains("gathered 2 task(s)"),
            "header missing/wrong: {out}"
        );
        assert!(out.contains("2 completed"), "summary tally absent: {out}");
        // One <details> block per task with task id in the summary.
        assert_eq!(
            out.matches("<details>").count(),
            2,
            "expected 2 collapsible task blocks: {out}"
        );
        assert!(out.contains("<b>agent:1</b>") && out.contains("<b>agent:2</b>"));
        // Agent's markdown headings preserved (not stuffed in a code block).
        assert!(out.contains("### Key Files"));
        assert!(out.contains("### TUI findings"));
        // Tool calls listed for tasks that have any (`agent:1`); no empty
        // line for tasks with none (`agent:2`).
        assert!(out.contains("Tool calls (2)"));
        assert!(
            !out.contains("Tool calls (0)"),
            "empty event list shouldn't render a 'Tool calls (0)' line: {out}"
        );
        // Crucial: the raw JSON code block (the BUG) MUST NOT appear.
        assert!(
            !out.contains("```\n{\"summary\"") && !out.contains("```\n{\"tasks\""),
            "raw WaitTask JSON must not be rendered as a code block: {out}"
        );
    }

    #[test]
    fn wait_task_pretty_renders_mixed_status_with_per_task_icons() {
        // Each terminal status gets a distinct icon so a reader can
        // scan a multi-task block at a glance. This test wires up the
        // 3 "interesting" statuses (the happy path is covered above).
        let payload = serde_json::json!({
            "summary": {"total": 3, "timed_out": 1, "cancelled": 1, "not_found": 1},
            "tasks": [
                {"task_id": "agent:5", "status": "timed_out", "current": {}},
                {"task_id": "agent:6", "status": "cancelled"},
                {"task_id": "agent:99", "status": "not_found", "error": "unknown task agent:99"},
            ],
        });
        let msgs = vec![
            assistant_calling_wait_task("c1"),
            wait_task_result("c1", payload),
        ];
        let out = render(&msgs, &[], &default_meta(), false);
        // Each icon must appear at least once.
        assert!(out.contains("\u{23F1}"), "timed_out icon missing: {out}");
        assert!(out.contains("\u{26D4}"), "cancelled icon missing: {out}");
        assert!(out.contains("\u{2753}"), "not_found icon missing: {out}");
        // The not_found error message must surface in the task body —
        // a typo in one of N task_ids needs to be debuggable.
        assert!(
            out.contains("unknown task agent:99"),
            "not_found error must be visible: {out}"
        );
    }

    #[test]
    fn wait_task_pretty_falls_back_to_code_block_on_unparseable_payload() {
        // Defensive: if WaitTask ever returns malformed JSON (e.g.,
        // dispatch error wrapped as a plain string), we must NOT lose
        // the content. The generic code-block path catches it.
        let mut bad = make_msg(Role::Tool, "{not valid json");
        bad.tool_call_id = Some("c1".into());
        let msgs = vec![assistant_calling_wait_task("c1"), bad];
        let out = render(&msgs, &[], &default_meta(), false);
        assert!(
            out.contains("{not valid json"),
            "unparseable WaitTask payload must surface verbatim: {out}"
        );
        // And critically: not as a half-formed pretty render.
        assert!(
            !out.contains("<details>"),
            "pretty path must abort cleanly on parse failure: {out}"
        );
    }

    #[test]
    fn wait_task_pretty_survives_gemini_style_tool_id_reuse_across_turns() {
        // Regression for #1163-followup: providers like Gemini emit
        // per-turn tool_call_ids (`gemini_tc_1`, `gemini_tc_2`, …)
        // that **reset every assistant message**, so the same id
        // legitimately means different tools across turns. The old
        // pre-pass-then-render approach built `tool_id_to_name` with
        // last-write-wins semantics across the whole transcript, so a
        // later `Read` call would silently overwrite the WaitTask
        // mapping — and the WaitTask result rendered as raw JSON.
        //
        // Shape (mirrors the user-reported transcript):
        //   T1: assistant calls WaitTask  (id=tc_1) → result: WaitTask JSON
        //   T2: assistant calls Read      (id=tc_1, REUSED) → result: file body
        //
        // After the fix, T1's WaitTask result must still pretty-print.
        let payload = serde_json::json!({
            "summary": {"total": 1, "completed": 1},
            "tasks": [{
                "task_id": "agent:1",
                "status": "completed",
                "agent_name": "explore",
                "output": "All clear.",
            }],
        });

        let read_call = serde_json::json!([{
            "id": "tc_1",
            "function": {"name": "Read", "arguments": "{\"file_path\":\"a.rs\"}"}
        }]);
        let mut read_assistant = make_msg(Role::Assistant, "");
        read_assistant.tool_calls = Some(read_call.to_string());
        let mut read_result = make_msg(Role::Tool, "fn main() {}\n");
        read_result.tool_call_id = Some("tc_1".into());

        let msgs = vec![
            assistant_calling_wait_task("tc_1"),
            wait_task_result("tc_1", payload),
            read_assistant,
            read_result,
        ];
        let out = render(&msgs, &[], &default_meta(), false);

        // Must pretty-print the WaitTask result — the per-task block.
        assert!(
            out.contains("<details>") && out.contains("agent:1"),
            "WaitTask must pretty-print despite later id reuse: {out}"
        );
        // Must NOT regress to the raw-JSON code block.
        assert!(
            !out.contains("```\n{\"summary\"") && !out.contains("```\n{\"tasks\""),
            "raw WaitTask JSON must never appear: {out}"
        );
        // Sanity: the later Read result is unaffected.
        assert!(
            out.contains("fn main()"),
            "Read result must still render: {out}"
        );
    }
}