yolop 0.7.0

Yolop — a terminal coding agent built on everruns-runtime
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
// Per-session JSONL event log.
//
// Each session writes its replay-relevant events to
// `<sessions_dir>/<session_id>/events.jsonl`, one serialized `Event` per line.
// `--session <id>` reuses the same SessionId on the next run and replays
// the file: events are read back and messages derived from those events
// are seeded into the message store so the conversation history shows up
// in the next turn's context.
//
// JSONL is chosen because `Event` is already `Serialize + Deserialize`
// and the format degrades gracefully — a half-written line at the end is
// a parse error on one line, not a corrupt file. The writer flushes after
// every line so a crash mid-session loses at most the event in flight.
//
// Concerns explicitly handled below:
// * Owner-only on Unix: `events.jsonl` is created with `0o600` and the
//   file mode is re-tightened to `0o600` on every open; the per-session
//   folder is `chmod`-ed to `0o700` on open as well. The re-tightening
//   matters because `OpenOptionsExt::mode` only applies on create —
//   without it, a legacy file or one loosened out-of-band would keep
//   its prior mode on resume. Session logs contain prompts, tool
//   arguments, and tool output, plus the reasoning artifacts described
//   below.
// * Replay keeps event types that (a) round-trip into the conversation
//   (`input.message`, `output.message.completed`, `tool.completed`) and
//   (b) the agent needs to restore the live transcript view and provider
//   continuation state on resume (`reason.completed`, `reason.item`).
//   Streaming `*.delta` events have no replay value and would otherwise
//   inflate the log O(n²) for long streamed responses.
// * Assistant `thinking` / `thinking_signature` fields ARE persisted in
//   yolop's per-session JSONL. The per-session folder is the local
//   private session store (owner-only on Unix, see above) and provider
//   continuation on resume requires the signature/encrypted_content
//   (e.g. OpenAI Responses threads the encrypted reasoning context back
//   via `thinking_signature`). The contract is local-store, not
//   user-facing transcript export — see the yolop README for the
//   public/private distinction.
// * Replay rejects events whose `session_id` doesn't match the resumed
//   session — guards against accidentally merging logs across sessions.
// * On open, if the file does not end with `\n` (previous run crashed
//   mid-write), append one before any new line is added — prevents the
//   first new event from being concatenated onto a partial tail.
// * Sequence numbers continue from the replayed maximum rather than
//   restarting from 0, so `Event.sequence` stays monotonic within a
//   session across resumes.
//
// Concurrency:
// * Intra-process: the file handle sits behind a `tokio::Mutex` so emits
//   serialize even when tools fire events from many tasks.
// * Inter-process: an advisory exclusive flock (`File::try_lock`) is
//   acquired on open. A second `yolop --session <same-id>` against the
//   same JSONL file fails fast with a clear error instead of silently
//   interleaving appends.

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use everruns_core::error::{AgentLoopError, Result};
use everruns_core::events::{
    Event, EventData, EventRequest, INPUT_MESSAGE, OUTPUT_MESSAGE_COMPLETED,
    OutputMessageCompletedData, REASON_COMPLETED, REASON_ITEM, TOOL_COMPLETED,
};
use everruns_core::message::{ContentPart, Message};
use everruns_core::tools::ToolResultImage;
use everruns_core::traits::EventEmitter;
use everruns_core::typed_id::EventId;
use everruns_core::typed_id::SessionId;
use everruns_runtime::EventBus;
use serde::{Deserialize, Serialize};
use std::fs::{File, OpenOptions, TryLockError};
use std::io::{BufRead, BufReader, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock, broadcast};

/// Capacity of the live event broadcast. Sized to absorb a few hundred
/// rapid-fire delta events from one LLM turn without the TUI receiver
/// lagging; on overflow the receiver gets `Lagged` and we fall back to
/// catch-up via `runtime.events()`.
const EVENT_BROADCAST_CAPACITY: usize = 1024;

/// Default location for yolop's per-session storage folders. Resolves via
/// `dirs::data_dir()`, which is the platform-native user data directory
/// (`~/.local/share/yolop/sessions/` on Linux,
/// `~/Library/Application Support/yolop/sessions/` on macOS,
/// `%APPDATA%\yolop\sessions\` on Windows).
///
/// Returns an error when the platform data dir can't be resolved — we
/// intentionally do NOT fall back to the current working directory,
/// because the cwd for yolop is usually the user's workspace and we
/// don't want sensitive session logs landing in the repo.
pub fn default_sessions_dir() -> Result<PathBuf> {
    dirs::data_dir()
        .map(|p| p.join("yolop").join("sessions"))
        .ok_or_else(|| {
            AgentLoopError::config(
                "could not resolve a platform data directory for session logs; \
                 pass --session-dir <PATH> explicitly",
            )
        })
}

pub fn session_dir_path(sessions_dir: &Path, session_id: SessionId) -> PathBuf {
    sessions_dir.join(session_id.to_string())
}

pub fn session_log_path(session_dir: &Path) -> PathBuf {
    session_dir.join("events.jsonl")
}

fn session_workspace_path(session_dir: &Path) -> PathBuf {
    session_dir.join("workspace.json")
}

pub fn legacy_session_log_path(sessions_dir: &Path, session_id: SessionId) -> PathBuf {
    sessions_dir.join(format!("{session_id}.jsonl"))
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WorktreeMetadata {
    pub path: PathBuf,
    pub branch: String,
    pub base_ref: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub slug: String,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SessionWorkspaceMetadata {
    #[serde(alias = "workspace_root")]
    pub active_root: PathBuf,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repo_root: Option<PathBuf>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canonical_repo_root: Option<PathBuf>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub created_at: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<DateTime<Utc>>,
    #[serde(default)]
    pub session_kind: SessionKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_session_id: Option<SessionId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worktree: Option<WorktreeMetadata>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum SessionKind {
    #[default]
    Interactive,
    Print,
    Nested,
    Acp,
    Test,
    Automated,
}

impl SessionWorkspaceMetadata {
    pub fn new(active_root: PathBuf, repo_root: Option<PathBuf>) -> Self {
        let now = Utc::now();
        let canonical_repo_root = repo_root.as_ref().map(|path| canonicalize_lossy(path));
        let project_id = canonical_repo_root
            .as_ref()
            .map(|path| format!("file:{}", path.display()));

        Self {
            active_root,
            repo_root,
            canonical_repo_root,
            project_id,
            title: None,
            summary: None,
            created_at: Some(now),
            updated_at: Some(now),
            session_kind: SessionKind::Interactive,
            parent_session_id: None,
            worktree: None,
        }
    }

    pub fn apply_initial_prompt(&mut self, prompt: &str) {
        let title = prompt_title(prompt);
        if title.is_empty() {
            return;
        }
        if self.title.is_none() {
            self.title = Some(title.clone());
        }
        if self.summary.is_none() {
            self.summary = Some(title);
        }
    }
}

fn canonicalize_lossy(path: &Path) -> PathBuf {
    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

fn prompt_title(prompt: &str) -> String {
    const MAX_TITLE_CHARS: usize = 80;
    let collapsed = prompt.split_whitespace().collect::<Vec<_>>().join(" ");
    let mut chars = collapsed.chars();
    let title: String = chars.by_ref().take(MAX_TITLE_CHARS).collect();
    if chars.next().is_some() {
        format!("{title}")
    } else {
        title
    }
}

pub fn read_session_workspace_metadata(
    session_dir: &Path,
) -> Result<Option<SessionWorkspaceMetadata>> {
    let path = session_workspace_path(session_dir);
    if !path.exists() {
        return Ok(None);
    }
    let bytes = match std::fs::read(&path) {
        Ok(bytes) => bytes,
        Err(e) => {
            tracing::warn!(
                path = %path.display(),
                error = %e,
                "ignoring unreadable session workspace metadata"
            );
            return Ok(None);
        }
    };
    let metadata: SessionWorkspaceMetadata = match serde_json::from_slice(&bytes) {
        Ok(metadata) => metadata,
        Err(e) => {
            tracing::warn!(
                path = %path.display(),
                error = %e,
                "ignoring malformed session workspace metadata"
            );
            return Ok(None);
        }
    };
    Ok(Some(metadata))
}

pub fn read_session_workspace(session_dir: &Path) -> Result<Option<PathBuf>> {
    Ok(read_session_workspace_metadata(session_dir)?.map(|m| m.active_root))
}

pub fn write_session_workspace(
    session_dir: &Path,
    metadata: &SessionWorkspaceMetadata,
) -> Result<()> {
    std::fs::create_dir_all(session_dir).map_err(|e| {
        AgentLoopError::config(format!("create session dir {}: {e}", session_dir.display()))
    })?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(session_dir, std::fs::Permissions::from_mode(0o700)).map_err(
            |e| {
                AgentLoopError::config(format!(
                    "tighten session dir permissions on {}: {e}",
                    session_dir.display()
                ))
            },
        )?;
    }
    let path = session_workspace_path(session_dir);
    let mut metadata = metadata.clone();
    metadata.updated_at = Some(Utc::now());
    if metadata.created_at.is_none() {
        metadata.created_at = metadata.updated_at;
    }
    let bytes = serde_json::to_vec_pretty(&metadata)
        .map_err(|e| AgentLoopError::config(format!("serialize session workspace: {e}")))?;
    write_private_file(&path, &bytes)
}

fn write_private_file(path: &Path, bytes: &[u8]) -> Result<()> {
    let mut opts = OpenOptions::new();
    opts.create(true).write(true).truncate(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    let mut file = opts.open(path).map_err(|e| {
        AgentLoopError::config(format!("open private file {}: {e}", path.display()))
    })?;
    file.write_all(bytes).map_err(|e| {
        AgentLoopError::config(format!("write private file {}: {e}", path.display()))
    })?;
    file.write_all(b"\n").map_err(|e| {
        AgentLoopError::config(format!("write private file {}: {e}", path.display()))
    })?;
    file.flush().map_err(|e| {
        AgentLoopError::config(format!("flush private file {}: {e}", path.display()))
    })?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(|e| {
            AgentLoopError::config(format!(
                "tighten private file permissions on {}: {e}",
                path.display()
            ))
        })?;
    }
    Ok(())
}

/// Copy a pre-folder-layout session log into the current session folder.
///
/// The old layout wrote `<sessions_dir>/<session_id>.jsonl`; the current
/// layout writes `<sessions_dir>/<session_id>/events.jsonl`. Copying instead
/// of renaming keeps older yolop binaries able to read the legacy file.
pub fn migrate_legacy_session_log(
    sessions_dir: &Path,
    session_dir: &Path,
    session_id: SessionId,
) -> Result<Option<PathBuf>> {
    let current = session_log_path(session_dir);
    if current.exists() {
        return Ok(None);
    }
    let legacy = legacy_session_log_path(sessions_dir, session_id);
    if !legacy.exists() {
        return Ok(None);
    }
    std::fs::create_dir_all(session_dir).map_err(|e| {
        AgentLoopError::config(format!("create session dir {}: {e}", session_dir.display()))
    })?;
    std::fs::copy(&legacy, &current).map_err(|e| {
        AgentLoopError::config(format!(
            "migrate legacy session log {} to {}: {e}",
            legacy.display(),
            current.display()
        ))
    })?;
    Ok(Some(legacy))
}

/// Result of replaying a JSONL session log from disk.
#[derive(Debug, Default)]
pub struct ReplayedSession {
    pub events: Vec<Event>,
    pub messages: Vec<Message>,
    /// Highest `Event.sequence` value found in the file (None if no
    /// events had sequence numbers). The new emitter resumes from
    /// `max_sequence + 1`.
    pub max_sequence: Option<i32>,
}

/// Read a session log into memory. Missing files return an empty replay.
/// Malformed lines and events for a different session are skipped with
/// a tracing warning; a half-written tail line shouldn't take down the
/// next session.
pub fn replay(path: &Path, expected: SessionId) -> Result<ReplayedSession> {
    if !path.exists() {
        return Ok(ReplayedSession::default());
    }
    let file = File::open(path)
        .map_err(|e| AgentLoopError::config(format!("open session log {}: {e}", path.display())))?;
    let mut out = ReplayedSession::default();
    for (i, line) in BufReader::new(file).lines().enumerate() {
        let Ok(line) = line else {
            tracing::warn!(
                line = i + 1,
                "session log read error; stopping replay early"
            );
            break;
        };
        if line.trim().is_empty() {
            continue;
        }
        match serde_json::from_str::<Event>(&line) {
            Ok(event) => {
                if event.session_id != expected {
                    tracing::warn!(
                        line = i + 1,
                        found = %event.session_id,
                        expected = %expected,
                        "session log line belongs to a different session; skipping"
                    );
                    continue;
                }
                if let Some(seq) = event.sequence {
                    out.max_sequence = Some(out.max_sequence.map_or(seq, |m| m.max(seq)));
                }
                if let Some(message) = message_from_event(&event.data) {
                    out.messages.push(message);
                }
                out.events.push(event);
            }
            Err(e) => {
                tracing::warn!(line = i + 1, error = %e, "skipping malformed session-log line");
            }
        }
    }
    Ok(out)
}

/// Event types that are useful to keep on disk: those that replay can map
/// back into the conversation (`input.message`, `output.message.completed`,
/// `tool.completed`) plus the agent reasoning artifacts the CLI uses to
/// restore the live transcript view and provider continuation state on
/// resume (`reason.completed` carries the safe `text_preview` narration,
/// `reason.item` carries opaque/encrypted reasoning context curated by the
/// provider). Streaming `*.delta` events and pure lifecycle markers
/// (`reason.started`, `reason.thinking.*`, `output.message.started`) are
/// dropped — they are live status signals only and the delta types would
/// bloat the log O(n²) since each delta carries the accumulated text so
/// far.
fn is_replay_relevant(event_type: &str) -> bool {
    matches!(
        event_type,
        INPUT_MESSAGE | OUTPUT_MESSAGE_COMPLETED | TOOL_COMPLETED | REASON_COMPLETED | REASON_ITEM
    )
}

/// EventEmitter that appends replay-relevant events as JSONL to a file
/// and mirrors all events into an in-memory vec for `events()` queries.
///
/// Owns its own sequence counter so resumed sessions continue past the
/// max sequence found in the replayed log (rather than restarting at 1
/// and producing non-monotonic per-session sequences).
pub struct JsonlEventEmitter {
    events: Arc<RwLock<Vec<Event>>>,
    sequence: Arc<RwLock<i32>>,
    file: Arc<Mutex<File>>,
    /// Live fan-out of every emitted event (including deltas) for in-process
    /// subscribers like the TUI's streaming renderer. Filesystem persistence
    /// still filters by `is_replay_relevant`; this channel does not.
    live: broadcast::Sender<Event>,
}

impl JsonlEventEmitter {
    /// Open (or create) the session-log file and prepare the fan-out.
    /// `start_sequence` is the value `Event.sequence` should take on
    /// the next emitted event (1 for a fresh session, max_replayed + 1
    /// for a resume).
    pub fn open(path: &Path, start_sequence: i32) -> Result<Self> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                AgentLoopError::config(format!("create session log dir {}: {e}", parent.display()))
            })?;
            // Per-session folder is owner-only on Unix. The events.jsonl
            // file gets `0o600` below, but the folder may also hold tool
            // outputs (`/outputs/`) and other per-session artifacts;
            // tightening the directory keeps every file inside private
            // even if a caller later creates one without an explicit
            // mode. Idempotent — set on every open so a session folder
            // that pre-dates this change gets corrected next resume.
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)).map_err(
                    |e| {
                        AgentLoopError::config(format!(
                            "tighten session dir permissions on {}: {e}",
                            parent.display()
                        ))
                    },
                )?;
            }
        }
        let mut opts = OpenOptions::new();
        // `read(true)` is required so we can read the file's last byte
        // for the half-written tail repair below; `append(true)` keeps
        // every write at end-of-file even with concurrent appends.
        opts.create(true).append(true).read(true);
        #[cfg(unix)]
        {
            // Owner-only: session logs contain prompts and tool output
            // we don't want world-readable. `mode()` only applies on
            // create; existing files keep their mode.
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
        }
        let mut file = opts.open(path).map_err(|e| {
            AgentLoopError::config(format!("open session log {}: {e}", path.display()))
        })?;

        // Re-tighten the file mode on every open. `OpenOptionsExt::mode`
        // only applies on create, so a legacy `events.jsonl` written
        // before the owner-only contract — or one whose mode was loosened
        // out-of-band — would otherwise keep its prior permissions on
        // resume. Mirrors the directory tightening above.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(
                |e| {
                    AgentLoopError::config(format!(
                        "tighten session log permissions on {}: {e}",
                        path.display()
                    ))
                },
            )?;
        }

        // Advisory exclusive flock: prevents two `yolop --session <id>`
        // processes from interleaving writes on the same JSONL file.
        // Advisory only — another process that doesn't lock can still
        // write — but every JSONL writer here goes through this path.
        // The lock is released when the underlying `File` is dropped
        // (i.e. when the emitter is dropped at session end).
        match file.try_lock() {
            Ok(()) => {}
            Err(TryLockError::WouldBlock) => {
                return Err(AgentLoopError::config(format!(
                    "another yolop process is already writing {}; \
                     refusing to share a session log",
                    path.display()
                )));
            }
            Err(TryLockError::Error(e)) => {
                return Err(AgentLoopError::config(format!(
                    "lock session log {}: {e}",
                    path.display()
                )));
            }
        }

        // Repair half-written tail: if the file is non-empty and does
        // NOT end with '\n', the previous process crashed after writing
        // a partial JSON object. A naive append would concatenate the
        // new line onto that partial tail and produce a corrupt entry.
        // Add a leading '\n' so the partial tail becomes its own
        // (malformed, skipped) line and our new line stays clean.
        let len = file
            .seek(SeekFrom::End(0))
            .map_err(|e| AgentLoopError::config(format!("stat session log: {e}")))?;
        if len > 0 {
            let mut last = [0u8; 1];
            file.seek(SeekFrom::Start(len - 1))
                .and_then(|_| std::io::Read::read_exact(&mut file, &mut last))
                .map_err(|e| AgentLoopError::config(format!("read session log tail: {e}")))?;
            if last[0] != b'\n' {
                tracing::warn!(
                    "session log {} ends without newline; repairing tail before append",
                    path.display()
                );
                writeln!(file)
                    .map_err(|e| AgentLoopError::config(format!("repair session log tail: {e}")))?;
            }
        }

        let (live, _) = broadcast::channel(EVENT_BROADCAST_CAPACITY);
        Ok(Self {
            events: Arc::new(RwLock::new(Vec::new())),
            sequence: Arc::new(RwLock::new(start_sequence.saturating_sub(1))),
            file: Arc::new(Mutex::new(file)),
            live,
        })
    }

    /// Subscribe to live events as they are emitted. Returns a receiver
    /// that begins delivering events from this point forward — replayed
    /// history seeded via [`Self::seed_replayed`] is NOT re-broadcast.
    pub fn subscribe(&self) -> broadcast::Receiver<Event> {
        self.live.subscribe()
    }

    /// Push events read back from disk into the in-memory vec that
    /// `EventBus::collected_events()` returns. Does NOT re-write them to
    /// the JSONL file (they're already there) — purely a seeding step so
    /// `runtime.events()` after resume returns the full session history
    /// instead of starting empty.
    pub async fn seed_replayed(&self, events: Vec<Event>) {
        if events.is_empty() {
            return;
        }
        self.events.write().await.extend(events);
    }
}

#[async_trait]
impl EventEmitter for JsonlEventEmitter {
    async fn emit(&self, request: EventRequest) -> Result<Event> {
        // Assign id + sequence ourselves so we own the monotonic
        // sequence even across resumes.
        let mut seq = self.sequence.write().await;
        *seq = seq.saturating_add(1);
        let seq_val = *seq;
        drop(seq);

        let mut event = request.into_event(EventId::new(), seq_val);
        // `into_event` may have set its own timestamp; ensure we always
        // record one for replay ordering.
        if event.ts.timestamp() == 0 {
            event.ts = Utc::now();
        }
        self.events.write().await.push(event.clone());

        if is_replay_relevant(&event.event_type) {
            // yolop's per-session JSONL is the local session store; we
            // persist `thinking` / `thinking_signature` and opaque
            // `reason.item` content as-is so provider continuation
            // (e.g. OpenAI Responses replays encrypted reasoning via
            // `thinking_signature`) works after `--session <id>` resume.
            // Privacy lives in the 0o600 file mode and per-user
            // platform data dir, not in field stripping.
            let line = serde_json::to_string(&event).map_err(|e| {
                AgentLoopError::config(format!("serialize event for session log: {e}"))
            })?;
            let mut file = self.file.lock().await;
            writeln!(file, "{line}")
                .map_err(|e| AgentLoopError::config(format!("write session log line: {e}")))?;
            file.flush()
                .map_err(|e| AgentLoopError::config(format!("flush session log: {e}")))?;
        }

        // Fan out to live subscribers. `send` errors only when there are
        // no receivers, which is the common steady state — ignore.
        let _ = self.live.send(event.clone());
        Ok(event)
    }
}

// `EventBus: EventEmitter` adds the `collected_events()` query so the
// runtime can ask "what events fired this session?" through the same
// trait object that handles emissions.
#[async_trait]
impl EventBus for JsonlEventEmitter {
    async fn collected_events(&self) -> Vec<Event> {
        self.events.read().await.clone()
    }
}

// ---------- event → message mapping ----------
//
// `crates/runtime/src/runtime.rs` has the same logic in a private fn;
// copied here for the replay path. The three event types matched are
// exactly those `is_replay_relevant` lets through to disk.

fn message_from_event(data: &EventData) -> Option<Message> {
    match data {
        EventData::InputMessage(d) => Some(d.message.clone()),
        EventData::OutputMessageCompleted(OutputMessageCompletedData { message, .. }) => {
            Some(message.clone())
        }
        EventData::ToolCompleted(d) => Some(tool_completed_to_message(d.clone())),
        _ => None,
    }
}

fn tool_completed_to_message(data: everruns_core::events::ToolCompletedData) -> Message {
    let mut images: Vec<ToolResultImage> = Vec::new();
    let result = data.result.map(|parts| {
        for part in &parts {
            if let ContentPart::Image(img) = part
                && let (Some(base64), Some(media_type)) = (&img.base64, &img.media_type)
            {
                images.push(ToolResultImage {
                    base64: base64.clone(),
                    media_type: media_type.clone(),
                });
            }
        }

        let text_parts: Vec<&ContentPart> = parts
            .iter()
            .filter(|part| matches!(part, ContentPart::Text(_)))
            .collect();
        if text_parts.len() == 1
            && let ContentPart::Text(text) = text_parts[0]
        {
            return parse_structured_tool_result_text(&text.text);
        }
        if !text_parts.is_empty() {
            serde_json::to_value(&text_parts).unwrap_or_default()
        } else {
            serde_json::Value::Null
        }
    });

    if images.is_empty() {
        Message::tool_result(&data.tool_call_id, result, data.error)
    } else {
        Message::tool_result_with_images(&data.tool_call_id, result, images)
    }
}

fn parse_structured_tool_result_text(text: &str) -> serde_json::Value {
    let trimmed = text.trim_start();
    if !trimmed.starts_with('{') && !trimmed.starts_with('[') {
        return serde_json::Value::String(text.to_string());
    }

    match serde_json::from_str(text) {
        Ok(value @ (serde_json::Value::Object(_) | serde_json::Value::Array(_))) => value,
        _ => serde_json::Value::String(text.to_string()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use everruns_core::events::{
        EventContext, InputMessageData, OutputMessageCompletedData, ToolCompletedData,
    };
    use everruns_core::message::Message;

    fn input_event(session_id: SessionId, text: &str) -> Event {
        Event::new(
            session_id,
            EventContext::default(),
            InputMessageData::new(Message::user(text)),
        )
    }

    #[tokio::test]
    async fn seed_replayed_populates_collected_events_without_rewrite() {
        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(482);
        let session_dir = session_dir_path(dir.path(), session_id);
        let path = session_log_path(&session_dir);

        let emitter = JsonlEventEmitter::open(&path, 1).expect("open");
        let prior = vec![
            input_event(session_id, "first prior turn"),
            input_event(session_id, "second prior turn"),
        ];
        emitter.seed_replayed(prior.clone()).await;

        // Acceptance: collected_events() returns the seeded events.
        let collected = emitter.collected_events().await;
        assert_eq!(collected.len(), prior.len());
        assert_eq!(collected[0].id, prior[0].id);
        assert_eq!(collected[1].id, prior[1].id);

        // Acceptance: seeding must NOT re-write to the JSONL file.
        // The file was opened fresh and nothing was emitted; it should
        // still be empty on disk.
        let on_disk = std::fs::read_to_string(&path).expect("read");
        assert!(
            on_disk.is_empty(),
            "seed_replayed must not re-persist; found: {on_disk:?}"
        );
    }

    #[tokio::test]
    async fn seed_replayed_then_emit_keeps_order() {
        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(4820);
        let session_dir = session_dir_path(dir.path(), session_id);
        let path = session_log_path(&session_dir);

        let emitter = JsonlEventEmitter::open(&path, 3).expect("open");
        let prior = vec![input_event(session_id, "a"), input_event(session_id, "b")];
        emitter.seed_replayed(prior.clone()).await;

        let req = EventRequest::new(
            session_id,
            EventContext::default(),
            InputMessageData::new(Message::user("new")),
        );
        let _new = emitter.emit(req).await.expect("emit");

        let collected = emitter.collected_events().await;
        assert_eq!(collected.len(), 3, "seeded + 1 new");
        // New event sequence continues from start_sequence we opened with.
        assert_eq!(collected[2].sequence, Some(3));
    }

    #[test]
    fn migrate_legacy_session_log_copies_flat_jsonl() {
        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(48200);
        let legacy_path = legacy_session_log_path(dir.path(), session_id);
        std::fs::write(&legacy_path, "legacy event\n").expect("write legacy");

        let session_dir = session_dir_path(dir.path(), session_id);
        let migrated =
            migrate_legacy_session_log(dir.path(), &session_dir, session_id).expect("migrate");
        let current_path = session_log_path(&session_dir);

        assert_eq!(migrated.as_deref(), Some(legacy_path.as_path()));
        assert_eq!(
            std::fs::read_to_string(&current_path).expect("read migrated"),
            "legacy event\n"
        );
        assert!(
            legacy_path.exists(),
            "migration copies instead of renaming for old yolop compatibility"
        );
    }

    #[test]
    fn migrate_legacy_session_log_does_not_overwrite_current_log() {
        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(48201);
        let legacy_path = legacy_session_log_path(dir.path(), session_id);
        std::fs::write(&legacy_path, "legacy event\n").expect("write legacy");
        let session_dir = session_dir_path(dir.path(), session_id);
        std::fs::create_dir_all(&session_dir).expect("create session dir");
        let current_path = session_log_path(&session_dir);
        std::fs::write(&current_path, "current event\n").expect("write current");

        let migrated =
            migrate_legacy_session_log(dir.path(), &session_dir, session_id).expect("migrate");

        assert!(migrated.is_none());
        assert_eq!(
            std::fs::read_to_string(&current_path).expect("read current"),
            "current event\n"
        );
    }

    #[test]
    fn read_session_workspace_ignores_malformed_metadata() {
        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(48202);
        let session_dir = session_dir_path(dir.path(), session_id);
        std::fs::create_dir_all(&session_dir).expect("create session dir");
        std::fs::write(session_workspace_path(&session_dir), "{not json")
            .expect("write malformed metadata");

        let workspace = read_session_workspace(&session_dir).expect("read workspace metadata");

        assert!(workspace.is_none());
    }

    #[test]
    fn read_legacy_workspace_metadata_defaults_new_fields() {
        let json = r#"{
            "active_root": "/tmp/yolop-workspace",
            "repo_root": "/tmp/yolop-repo"
        }"#;

        let metadata: SessionWorkspaceMetadata =
            serde_json::from_str(json).expect("legacy workspace metadata deserializes");

        assert_eq!(metadata.active_root, PathBuf::from("/tmp/yolop-workspace"));
        assert_eq!(metadata.repo_root, Some(PathBuf::from("/tmp/yolop-repo")));
        assert_eq!(metadata.canonical_repo_root, None);
        assert_eq!(metadata.project_id, None);
        assert_eq!(metadata.title, None);
        assert_eq!(metadata.summary, None);
        assert_eq!(metadata.created_at, None);
        assert_eq!(metadata.updated_at, None);
        assert_eq!(metadata.session_kind, SessionKind::Interactive);
        assert_eq!(metadata.parent_session_id, None);
        assert!(metadata.worktree.is_none());
    }

    #[test]
    fn write_workspace_metadata_persists_agf_listing_fields() {
        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(48203);
        let session_dir = session_dir_path(dir.path(), session_id);
        let canonical_dir = dir.path().canonicalize().expect("canonical tempdir");
        let mut metadata = SessionWorkspaceMetadata::new(
            dir.path().join("worktree"),
            Some(dir.path().to_path_buf()),
        );
        metadata.title = Some("Implement workspace metadata".to_string());
        metadata.summary = Some("Add list-friendly Yolop session metadata.".to_string());
        metadata.session_kind = SessionKind::Nested;
        metadata.parent_session_id = Some(SessionId::from_seed(48204));
        metadata.worktree = Some(WorktreeMetadata {
            path: dir.path().join("worktree"),
            branch: "feature/agf-metadata".to_string(),
            base_ref: "origin/main".to_string(),
            slug: "agf-metadata".to_string(),
        });

        write_session_workspace(&session_dir, &metadata).expect("write workspace metadata");
        let written = read_session_workspace_metadata(&session_dir)
            .expect("read workspace metadata")
            .expect("metadata present");

        assert_eq!(
            written.title.as_deref(),
            Some("Implement workspace metadata")
        );
        assert_eq!(
            written.summary.as_deref(),
            Some("Add list-friendly Yolop session metadata.")
        );
        assert_eq!(written.session_kind, SessionKind::Nested);
        assert_eq!(written.parent_session_id, Some(SessionId::from_seed(48204)));
        assert_eq!(written.canonical_repo_root, Some(canonical_dir.clone()));
        assert_eq!(
            written.project_id.as_deref(),
            Some(format!("file:{}", canonical_dir.display()).as_str())
        );
        assert!(written.created_at.is_some(), "created_at is populated");
        assert!(written.updated_at.is_some(), "updated_at is populated");
        assert!(
            written.updated_at >= written.created_at,
            "updated_at should not precede created_at"
        );
        assert_eq!(
            written.worktree.map(|worktree| worktree.branch),
            Some("feature/agf-metadata".to_string())
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn open_tightens_session_dir_to_owner_only_on_unix() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(48222);
        let session_dir = session_dir_path(dir.path(), session_id);
        let path = session_log_path(&session_dir);

        let _emitter = JsonlEventEmitter::open(&path, 1).expect("open");

        let mode = std::fs::metadata(&session_dir)
            .expect("session dir exists")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(
            mode, 0o700,
            "per-session folder must be owner-only on Unix, got {mode:o}"
        );

        let file_mode = std::fs::metadata(&path)
            .expect("events.jsonl exists")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(
            file_mode, 0o600,
            "events.jsonl must be owner-only on Unix, got {file_mode:o}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn open_corrects_loose_events_jsonl_permissions_on_resume() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(48224);
        let session_dir = session_dir_path(dir.path(), session_id);
        let path = session_log_path(&session_dir);

        std::fs::create_dir_all(&session_dir).expect("pre-create");
        std::fs::write(&path, "").expect("pre-create file");
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644))
            .expect("loosen for test");

        let _emitter = JsonlEventEmitter::open(&path, 1).expect("open");

        let mode = std::fs::metadata(&path)
            .expect("events.jsonl exists")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(
            mode, 0o600,
            "resume must re-tighten an existing loose events.jsonl, got {mode:o}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn open_corrects_loose_session_dir_permissions_on_resume() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(48223);
        let session_dir = session_dir_path(dir.path(), session_id);
        let path = session_log_path(&session_dir);

        std::fs::create_dir_all(&session_dir).expect("pre-create");
        std::fs::set_permissions(&session_dir, std::fs::Permissions::from_mode(0o755))
            .expect("loosen for test");

        let _emitter = JsonlEventEmitter::open(&path, 1).expect("open");

        let mode = std::fs::metadata(&session_dir)
            .expect("session dir exists")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(
            mode, 0o700,
            "resume must re-tighten an existing loose session folder, got {mode:o}"
        );
    }

    #[tokio::test]
    async fn output_message_thinking_is_persisted_for_provider_continuation() {
        // yolop's per-session JSONL is the local session store: thinking
        // and thinking_signature must round-trip so providers that thread
        // encrypted reasoning context back (e.g. OpenAI Responses via
        // `thinking_signature`) can continue across `--session <id>` resume.
        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(4821);
        let session_dir = session_dir_path(dir.path(), session_id);
        let path = session_log_path(&session_dir);
        let emitter = JsonlEventEmitter::open(&path, 1).expect("open");

        let mut message = Message::assistant("I will inspect the files.");
        message.thinking = Some("private model reasoning".to_string());
        message.thinking_signature = Some("encrypted-thinking-token".to_string());
        let req = EventRequest::new(
            session_id,
            EventContext::default(),
            OutputMessageCompletedData::new(message),
        );

        emitter.emit(req).await.expect("emit");

        let on_disk = std::fs::read_to_string(&path).expect("read");
        assert!(
            on_disk.contains("private model reasoning"),
            "session log must persist assistant thinking for restore: {on_disk}"
        );
        assert!(
            on_disk.contains("encrypted-thinking-token"),
            "session log must persist thinking_signature for provider continuation: {on_disk}"
        );

        let replayed = replay(&path, session_id).expect("replay");
        let replayed_message = replayed.messages.first().expect("message replayed");
        assert_eq!(
            replayed_message.thinking.as_deref(),
            Some("private model reasoning")
        );
        assert_eq!(
            replayed_message.thinking_signature.as_deref(),
            Some("encrypted-thinking-token")
        );
    }

    #[tokio::test]
    async fn reason_completed_event_is_persisted_and_replayed() {
        use everruns_core::events::ReasonCompletedData;

        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(4822);
        let session_dir = session_dir_path(dir.path(), session_id);
        let path = session_log_path(&session_dir);
        let emitter = JsonlEventEmitter::open(&path, 1).expect("open");

        let req = EventRequest::new(
            session_id,
            EventContext::default(),
            ReasonCompletedData::success("Will read the lib.rs file", true, 1, Some(120), None),
        );
        emitter.emit(req).await.expect("emit");

        let on_disk = std::fs::read_to_string(&path).expect("read");
        assert!(
            on_disk.contains("\"reason.completed\""),
            "reason.completed should be persisted to JSONL: {on_disk}"
        );
        assert!(
            on_disk.contains("Will read the lib.rs file"),
            "text_preview narration should round-trip on disk: {on_disk}"
        );

        let replayed = replay(&path, session_id).expect("replay");
        assert_eq!(replayed.events.len(), 1);
        match &replayed.events[0].data {
            EventData::ReasonCompleted(data) => {
                assert_eq!(
                    data.text_preview.as_deref(),
                    Some("Will read the lib.rs file")
                );
                assert!(data.has_tool_calls);
                assert_eq!(data.tool_call_count, 1);
            }
            other => panic!("expected ReasonCompleted, got {other:?}"),
        }
        // reason.completed is not a conversation message — it must not
        // pollute the replayed messages vec.
        assert!(replayed.messages.is_empty());
    }

    #[tokio::test]
    async fn reason_item_event_is_persisted_and_replayed() {
        use everruns_core::events::ReasonItemData;
        use everruns_core::typed_id::TurnId;

        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(4823);
        let session_dir = session_dir_path(dir.path(), session_id);
        let path = session_log_path(&session_dir);
        let emitter = JsonlEventEmitter::open(&path, 1).expect("open");

        let req = EventRequest::new(
            session_id,
            EventContext::default(),
            ReasonItemData {
                turn_id: TurnId::new(),
                provider: "openai".to_string(),
                model: Some("gpt-5".to_string()),
                item_id: "rs_abc123".to_string(),
                encrypted_content: Some("opaque-encrypted-blob".to_string()),
                summary: vec!["Considered file structure.".to_string()],
                token_count: Some(42),
            },
        );
        emitter.emit(req).await.expect("emit");

        let on_disk = std::fs::read_to_string(&path).expect("read");
        assert!(
            on_disk.contains("\"reason.item\""),
            "reason.item should be persisted: {on_disk}"
        );
        assert!(
            on_disk.contains("opaque-encrypted-blob"),
            "encrypted_content must round-trip for provider continuation: {on_disk}"
        );

        let replayed = replay(&path, session_id).expect("replay");
        assert_eq!(replayed.events.len(), 1);
        match &replayed.events[0].data {
            EventData::ReasonItem(data) => {
                assert_eq!(data.provider, "openai");
                assert_eq!(data.item_id, "rs_abc123");
                assert_eq!(
                    data.encrypted_content.as_deref(),
                    Some("opaque-encrypted-blob")
                );
                assert_eq!(data.summary, vec!["Considered file structure.".to_string()]);
            }
            other => panic!("expected ReasonItem, got {other:?}"),
        }
        assert!(replayed.messages.is_empty());
    }

    #[tokio::test]
    async fn subscribe_receives_emitted_events_including_deltas() {
        use everruns_core::events::{
            OUTPUT_MESSAGE_DELTA, OutputMessageDeltaData, TOOL_OUTPUT_DELTA, ToolOutputDeltaData,
        };
        use everruns_core::typed_id::TurnId;

        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(99);
        let session_dir = session_dir_path(dir.path(), session_id);
        let path = session_log_path(&session_dir);
        let emitter = JsonlEventEmitter::open(&path, 1).expect("open");

        let mut rx = emitter.subscribe();

        let turn_id = TurnId::new();
        let delta_req = EventRequest::new(
            session_id,
            EventContext::default(),
            OutputMessageDeltaData {
                turn_id,
                delta: "hello".to_string(),
                accumulated: "hello".to_string(),
            },
        );
        let _ = emitter.emit(delta_req).await.expect("emit delta");

        let tool_req = EventRequest::new(
            session_id,
            EventContext::default(),
            ToolOutputDeltaData {
                tool_call_id: "call-1".to_string(),
                tool_name: "bash".to_string(),
                delta: "running...\n".to_string(),
                stream: "stdout".to_string(),
            },
        );
        let _ = emitter.emit(tool_req).await.expect("emit tool delta");

        let first = rx.recv().await.expect("first event");
        let second = rx.recv().await.expect("second event");
        assert_eq!(first.event_type, OUTPUT_MESSAGE_DELTA);
        assert_eq!(second.event_type, TOOL_OUTPUT_DELTA);

        // Streaming events should NOT have hit the JSONL file.
        let on_disk = std::fs::read_to_string(&path).expect("read");
        assert!(
            on_disk.is_empty(),
            "delta events must not be persisted: {on_disk:?}"
        );
    }

    #[tokio::test]
    async fn subscribe_does_not_replay_seeded_history() {
        let dir = tempfile::tempdir().expect("tempdir");
        let session_id = SessionId::from_seed(101);
        let session_dir = session_dir_path(dir.path(), session_id);
        let path = session_log_path(&session_dir);
        let emitter = JsonlEventEmitter::open(&path, 1).expect("open");

        emitter
            .seed_replayed(vec![input_event(session_id, "old turn")])
            .await;
        let mut rx = emitter.subscribe();

        // Without any new emissions, recv() must time out — the broadcast
        // is post-emission only, never replays seeded history.
        let drained = tokio::time::timeout(std::time::Duration::from_millis(40), rx.recv()).await;
        assert!(
            drained.is_err(),
            "no event should be delivered, got {drained:?}"
        );
    }

    #[test]
    fn tool_completed_replay_preserves_json_result_shape() {
        let data = ToolCompletedData::success(
            "call_read".to_string(),
            "read_file".to_string(),
            vec![ContentPart::text(
                serde_json::json!({
                    "path": "/repo/src/lib.rs",
                    "content": "1|fn main() {}"
                })
                .to_string(),
            )],
            Some(1),
        );

        let message = tool_completed_to_message(data);
        let result = message
            .tool_result_content()
            .and_then(|content| content.result.as_ref())
            .expect("tool result should be present");

        assert_eq!(result["path"], "/repo/src/lib.rs");
        assert_eq!(result["content"], "1|fn main() {}");
    }

    #[test]
    fn tool_completed_replay_keeps_scalar_json_as_text() {
        let data = ToolCompletedData::success(
            "call_scalar".to_string(),
            "custom_tool".to_string(),
            vec![ContentPart::text("123")],
            Some(1),
        );

        let message = tool_completed_to_message(data);
        let result = message
            .tool_result_content()
            .and_then(|content| content.result.as_ref())
            .expect("tool result should be present");

        assert_eq!(result, &serde_json::Value::String("123".to_string()));
    }

    // ====================================================================
    // replay() edge cases — partial writes, malformed lines, foreign
    // session ids, binary garbage. The contract is:
    //   * never panic
    //   * skip invalid content with a tracing warning
    //   * preserve every valid Event belonging to `expected`
    //   * track max_sequence across all valid events
    // ====================================================================

    fn serialize_event(event: &Event) -> String {
        serde_json::to_string(event).expect("serialize event")
    }

    #[test]
    fn replay_missing_file_returns_empty_session() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("nonexistent.jsonl");
        let session_id = SessionId::from_seed(70001);

        let out = replay(&path, session_id).expect("replay missing file");
        assert!(out.events.is_empty());
        assert!(out.messages.is_empty());
        assert!(out.max_sequence.is_none());
    }

    #[test]
    fn replay_empty_file_returns_empty_session() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("events.jsonl");
        std::fs::write(&path, b"").expect("write empty file");
        let session_id = SessionId::from_seed(70002);

        let out = replay(&path, session_id).expect("replay empty file");
        assert!(out.events.is_empty());
        assert!(out.messages.is_empty());
        assert!(out.max_sequence.is_none());
    }

    #[test]
    fn replay_blank_lines_in_middle_are_skipped() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("events.jsonl");
        let session_id = SessionId::from_seed(70003);

        let first = serialize_event(&input_event(session_id, "first"));
        let second = serialize_event(&input_event(session_id, "second"));
        let content = format!("{first}\n\n   \n{second}\n");
        std::fs::write(&path, content).expect("write");

        let out = replay(&path, session_id).expect("replay");
        assert_eq!(
            out.events.len(),
            2,
            "blank/whitespace-only lines must not produce events"
        );
    }

    #[test]
    fn replay_malformed_json_line_does_not_stop_replay() {
        // A single bad line in the middle must be skipped while the surrounding
        // valid lines still come back. This is the documented graceful-degrade
        // behaviour for partially-corrupt logs.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("events.jsonl");
        let session_id = SessionId::from_seed(70004);

        let good_a = serialize_event(&input_event(session_id, "alpha"));
        let good_b = serialize_event(&input_event(session_id, "beta"));
        let content = format!("{good_a}\n{{not valid json\n{good_b}\n");
        std::fs::write(&path, content).expect("write");

        let out = replay(&path, session_id).expect("replay");
        assert_eq!(out.events.len(), 2, "two good lines must survive");
    }

    #[test]
    fn replay_skips_events_for_different_session_id() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("events.jsonl");
        let expected = SessionId::from_seed(70005);
        let other = SessionId::from_seed(70006);

        let mine = serialize_event(&input_event(expected, "mine"));
        let theirs = serialize_event(&input_event(other, "theirs"));
        let content = format!("{theirs}\n{mine}\n{theirs}\n");
        std::fs::write(&path, content).expect("write");

        let out = replay(&path, expected).expect("replay");
        assert_eq!(
            out.events.len(),
            1,
            "only the line belonging to `expected` should be kept"
        );
        assert_eq!(out.events[0].session_id, expected);
    }

    #[test]
    fn replay_truncated_last_line_is_skipped_without_dropping_prior() {
        // Simulates a crash mid-write: the last line is a partial JSON
        // object with no trailing newline. Replay must skip it and keep
        // the prior fully-written events.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("events.jsonl");
        let session_id = SessionId::from_seed(70007);

        let good = serialize_event(&input_event(session_id, "kept"));
        let partial = "{\"id\":\"evt_\",\"session";
        let content = format!("{good}\n{partial}");
        std::fs::write(&path, content).expect("write");

        let out = replay(&path, session_id).expect("replay");
        assert_eq!(
            out.events.len(),
            1,
            "the partial tail must not corrupt the replay"
        );
    }

    #[test]
    fn replay_binary_garbage_stops_early_and_drops_suffix() {
        // Non-UTF-8 bytes injected into the JSONL file. `BufRead::lines()`
        // will yield Err for non-UTF-8; the documented contract is to stop
        // replay early on read errors rather than panic. A valid event is
        // sandwiched AFTER the garbage so this test fails if replay ever
        // starts trying to continue past a read error.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("events.jsonl");
        let session_id = SessionId::from_seed(70008);

        let prefix = serialize_event(&input_event(session_id, "prefix"));
        let suffix = serialize_event(&input_event(session_id, "would-be-suffix"));
        let mut bytes: Vec<u8> = Vec::new();
        bytes.extend_from_slice(prefix.as_bytes());
        bytes.push(b'\n');
        // Invalid UTF-8 sequence on its own line.
        bytes.extend_from_slice(&[0xff, 0xfe, 0xfd, b'\n']);
        bytes.extend_from_slice(suffix.as_bytes());
        bytes.push(b'\n');
        std::fs::write(&path, &bytes).expect("write");

        let out = replay(&path, session_id).expect("replay must not panic");
        assert_eq!(
            out.events.len(),
            1,
            "only the valid prefix line should survive; replay must stop early on read error"
        );
        let kept_text = match &out.events[0].data {
            EventData::InputMessage(d) => d.message.text().unwrap_or_default().to_string(),
            other => panic!("expected InputMessage, got {other:?}"),
        };
        assert!(
            kept_text.contains("prefix"),
            "expected the prefix event to be the one kept, got: {kept_text}"
        );
    }

    #[test]
    fn replay_tracks_highest_sequence_across_all_valid_events() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("events.jsonl");
        let session_id = SessionId::from_seed(70009);

        // Manually construct events with explicit sequence numbers so we
        // exercise the max-tracking branch even when sequences are not
        // monotonically written.
        let mut a = input_event(session_id, "a");
        a.sequence = Some(7);
        let mut b = input_event(session_id, "b");
        b.sequence = Some(3);
        let mut c = input_event(session_id, "c");
        c.sequence = Some(12);

        let content = format!(
            "{}\n{}\n{}\n",
            serialize_event(&a),
            serialize_event(&b),
            serialize_event(&c)
        );
        std::fs::write(&path, content).expect("write");

        let out = replay(&path, session_id).expect("replay");
        assert_eq!(out.events.len(), 3);
        assert_eq!(out.max_sequence, Some(12));
    }

    #[test]
    fn replay_only_blank_lines_returns_empty() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("events.jsonl");
        std::fs::write(&path, "\n\n   \n\t\n").expect("write");
        let session_id = SessionId::from_seed(70010);

        let out = replay(&path, session_id).expect("replay");
        assert!(out.events.is_empty());
        assert!(out.max_sequence.is_none());
    }
}