previously-on 0.1.0-alpha.1

Verifiable, local-first Codex work handoffs
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
use std::collections::{BTreeMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::process::Stdio;

use anyhow::{bail, Context, Result};
use chrono::{DateTime, Duration, TimeZone, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use tokio::io::{AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
use uuid::Uuid;

use crate::domain::{
    ChangeAttribution, ChangeStatus, CoverageStatus, CoverageV1, EventEnvelopeV1, EventKind,
    FileChangeV1, SCHEMA_VERSION_V1,
};
use crate::git::{repository_identity, RepositoryIdentity};
use crate::APP_VERSION;

pub const TESTED_CODEX_VERSION: &str = "0.144.3";
pub const SUPPORTED_CODEX_VERSIONS: [&str; 2] = ["0.144.3", "0.144.2"];
const MAX_PAGES: usize = 1_000;
pub const MAX_APP_SERVER_RPC_BYTES: usize = 8 * 1024 * 1024;
const MALFORMED_TOKEN_USAGE_WARNING: &str =
    "ignored malformed thread/tokenUsage/updated notification; token-usage coverage is degraded";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AppServerCapabilityStatus {
    Complete,
    Degraded,
    Unsupported,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppServerCapabilityReport {
    pub schema_version: u16,
    pub status: AppServerCapabilityStatus,
    pub tested_codex_version: String,
    pub detected_codex_version: Option<String>,
    pub app_server_user_agent: Option<String>,
    pub supported_methods: Vec<String>,
    pub warnings: Vec<String>,
}

impl AppServerCapabilityReport {
    pub fn unsupported(reason: impl Into<String>) -> Self {
        Self {
            schema_version: 1,
            status: AppServerCapabilityStatus::Unsupported,
            tested_codex_version: TESTED_CODEX_VERSION.to_string(),
            detected_codex_version: None,
            app_server_user_agent: None,
            supported_methods: Vec::new(),
            warnings: vec![reason.into()],
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppServerThreadSummary {
    pub id: String,
    pub session_id: String,
    pub cwd: PathBuf,
    pub cli_version: String,
    pub created_at: i64,
    pub updated_at: i64,
    pub preview: String,
    pub coverage: CoverageV1,
    pub raw: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ImportedThreadV1 {
    pub schema_version: u16,
    pub id: String,
    pub session_id: String,
    pub cwd: PathBuf,
    pub cli_version: String,
    pub created_at: i64,
    pub updated_at: i64,
    pub coverage: CoverageV1,
    /// The documented `thread/read` response. Only documented, allowlisted item variants are
    /// projected, and the raw transcript is never written to the canonical store.
    pub thread: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticThreadProjectionV1 {
    pub schema_version: u16,
    pub events: Vec<EventEnvelopeV1>,
    pub coverage: CoverageV1,
}

/// A validated `thread/tokenUsage/updated` notification payload.
///
/// The App Server client collects the latest valid notification observed while it waits for an RPC
/// response. Imports attach that bounded value to the matching thread without inferring token usage
/// from transcript size or turn count.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppServerTokenUsageNotificationV1 {
    pub thread_id: String,
    pub turn_id: String,
    pub token_usage: AppServerThreadTokenUsageV1,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppServerThreadTokenUsageV1 {
    pub last: AppServerTokenUsageBreakdownV1,
    pub total: AppServerTokenUsageBreakdownV1,
    pub model_context_window: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppServerTokenUsageBreakdownV1 {
    pub cached_input_tokens: u64,
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub reasoning_output_tokens: u64,
    pub total_tokens: u64,
}

/// Parse the documented server notification without collecting or persisting it directly.
///
/// `Ok(None)` means the JSON-RPC message is not a token-usage notification. A matching method with
/// malformed parameters is an error so callers can degrade coverage instead of silently guessing.
pub fn parse_token_usage_notification(
    message: &Value,
) -> Result<Option<AppServerTokenUsageNotificationV1>> {
    if message.get("method").and_then(Value::as_str) != Some("thread/tokenUsage/updated") {
        return Ok(None);
    }
    let params = message
        .get("params")
        .cloned()
        .context("thread/tokenUsage/updated notification omitted params")?;
    let parsed = serde_json::from_value(params)
        .context("invalid thread/tokenUsage/updated notification params")?;
    Ok(Some(parsed))
}

/// Project the documented, stable `thread/read` item variants into bounded canonical events.
///
/// This deliberately ignores reasoning, plan, image, and tool-detail payloads. Text, command
/// output, and file metadata are redacted and capped before they cross the storage boundary; the
/// raw App Server response must never be passed to the canonical store.
pub fn project_thread_events(
    thread: &ImportedThreadV1,
    repository_id: &str,
    repository_root: &Path,
) -> SemanticThreadProjectionV1 {
    let mut coverage = thread.coverage.clone();
    let mut events = Vec::new();
    let created_at = timestamp_seconds(thread.created_at);
    let updated_at = timestamp_seconds(thread.updated_at);
    let repository_path = repository_root.to_string_lossy().to_string();
    let turn_count = thread
        .thread
        .get("turns")
        .and_then(Value::as_array)
        .map(Vec::len)
        .unwrap_or_default();

    events.push(semantic_event(
        format!("codex-app-server:thread:{}:start", thread.id),
        repository_id,
        &thread.session_id,
        EventKind::SessionStarted,
        created_at,
        0,
        json!({
            "thread_id": thread.id,
            "source_thread_id": thread.id,
            "session_id": thread.session_id,
            "repository_path": repository_path,
            "thread_created_at": created_at,
            "thread_updated_at": updated_at,
            "turn_count": turn_count,
            "app_server_source": "thread/read",
            "untrusted_data": true,
            "raw_transcript_stored": false
        }),
        &coverage,
    ));

    if let Some(notification) = thread
        .thread
        .get("_previously_token_usage")
        .and_then(|value| {
            serde_json::from_value::<AppServerTokenUsageNotificationV1>(value.clone()).ok()
        })
    {
        events.push(semantic_event(
            format!(
                "codex-app-server:thread:{}:turn:{}:token-usage",
                thread.id, notification.turn_id
            ),
            repository_id,
            &thread.session_id,
            EventKind::ContextUsageUpdated,
            updated_at,
            1,
            json!({
                "thread_id": thread.id,
                "source_thread_id": thread.id,
                "turn_id": notification.turn_id,
                "session_id": thread.session_id,
                "repository_path": repository_path,
                "context_usage": {
                    "total_tokens": notification.token_usage.last.total_tokens,
                    "model_context_window": notification.token_usage.model_context_window
                },
                "app_server_source": "thread/tokenUsage/updated",
                "untrusted_data": true,
                "raw_transcript_stored": false
            }),
            &coverage,
        ));
    }

    let mut saw_prompt = false;
    let mut saw_final = false;
    let mut latest_final = None;
    let Some(turns) = thread.thread.get("turns").and_then(Value::as_array) else {
        degrade(
            &mut coverage,
            "thread turns",
            "thread/read omitted a turns array; only thread lifecycle metadata was projected",
        );
        return finish_semantic_projection(
            thread,
            repository_id,
            repository_root,
            updated_at,
            events,
            coverage,
            None,
        );
    };

    for (turn_index, turn) in turns.iter().enumerate() {
        let Some(turn_object) = turn.as_object() else {
            degrade(
                &mut coverage,
                "well-formed turn",
                format!("turn {turn_index} was not an object and was not projected"),
            );
            continue;
        };
        let Some(turn_id) = turn_object
            .get("id")
            .and_then(Value::as_str)
            .filter(|turn_id| !turn_id.is_empty())
        else {
            degrade(
                &mut coverage,
                "stable turn source ID",
                format!("turn {turn_index} omitted a stable ID and was not projected"),
            );
            continue;
        };
        let Some(items) = turn_object.get("items").and_then(Value::as_array) else {
            degrade(
                &mut coverage,
                "turn items",
                format!("turn {turn_index} omitted an items array"),
            );
            continue;
        };
        let mut turn_final: Option<(String, String, i64, DateTime<Utc>, bool)> = None;
        for (item_index, item) in items.iter().enumerate() {
            let Some(item_object) = item.as_object() else {
                degrade(
                    &mut coverage,
                    "well-formed thread item",
                    format!("turn {turn_index} item {item_index} was not an object"),
                );
                continue;
            };
            let Some(item_id) = item_object
                .get("id")
                .and_then(Value::as_str)
                .filter(|item_id| !item_id.is_empty())
            else {
                degrade(
                    &mut coverage,
                    "stable item source ID",
                    format!(
                        "turn {turn_index} item {item_index} omitted a stable ID and was not projected"
                    ),
                );
                continue;
            };
            let Some(item_type) = item_object.get("type").and_then(Value::as_str) else {
                degrade(
                    &mut coverage,
                    "known thread item schema",
                    format!("turn {turn_index} item {item_index} omitted its type"),
                );
                continue;
            };
            let sequence = 1 + (turn_index as i64 * 10_000) + item_index as i64;
            let occurred_at = item_timestamp(item)
                .unwrap_or_else(|| created_at + Duration::microseconds(sequence));
            match item_type {
                "userMessage" => {
                    if let Some(prompt) = bounded_message_content(item_object.get("content")) {
                        saw_prompt = true;
                        events.push(semantic_event(
                            format!(
                                "codex-app-server:thread:{}:item:{}:user-message",
                                thread.id, item_id
                            ),
                            repository_id,
                            &thread.session_id,
                            EventKind::UserPrompt,
                            occurred_at,
                            sequence,
                            json!({
                                "thread_id": thread.id,
                                "turn_id": turn_id,
                                "item_id": item_id,
                                "session_id": thread.session_id,
                                "repository_path": repository_path,
                                "prompt": prompt,
                                "app_server_item_type": item_type,
                                "untrusted_data": true,
                                "raw_transcript_stored": false
                            }),
                            &coverage,
                        ));
                    } else {
                        degrade(
                            &mut coverage,
                            "text user prompt",
                            format!("userMessage item `{item_id}` contained no text to project"),
                        );
                    }
                }
                "agentMessage" => {
                    if let Some(text) = item_object
                        .get("text")
                        .and_then(Value::as_str)
                        .map(crate::redaction::redact_excerpt)
                        .filter(|text| !text.trim().is_empty())
                    {
                        let explicit_final = item_object.get("phase").and_then(Value::as_str)
                            == Some("final_answer");
                        if explicit_final
                            || turn_final.as_ref().is_none_or(|candidate| !candidate.4)
                        {
                            turn_final = Some((
                                item_id.to_string(),
                                text,
                                sequence,
                                occurred_at,
                                explicit_final,
                            ));
                        }
                    }
                }
                "commandExecution" => {
                    let Some(command) = item_object
                        .get("command")
                        .and_then(Value::as_str)
                        .map(crate::redaction::redact_excerpt)
                        .filter(|command| !command.trim().is_empty())
                    else {
                        degrade(
                            &mut coverage,
                            "command execution command",
                            format!("commandExecution item `{item_id}` omitted command text"),
                        );
                        continue;
                    };
                    let output = item_object
                        .get("aggregatedOutput")
                        .and_then(Value::as_str)
                        .map(crate::redaction::redact_excerpt);
                    events.push(semantic_event(
                        format!(
                            "codex-app-server:thread:{}:item:{}:command-execution",
                            thread.id, item_id
                        ),
                        repository_id,
                        &thread.session_id,
                        EventKind::ToolFinished,
                        occurred_at,
                        sequence,
                        json!({
                            "thread_id": thread.id,
                            "turn_id": turn_id,
                            "item_id": item_id,
                            "session_id": thread.session_id,
                            "repository_path": repository_path,
                            "tool_name": "Bash",
                            "tool_use_id": item_id,
                            "tool_input": {"command": command},
                            "tool_response": {
                                "status": item_object.get("status").cloned(),
                                "exit_code": item_object.get("exitCode").cloned(),
                                "output": output
                            },
                            "app_server_item_type": item_type,
                            "untrusted_data": true,
                            "raw_transcript_stored": false
                        }),
                        &coverage,
                    ));
                }
                "fileChange" => {
                    let changes = project_file_changes(
                        item_object.get("changes"),
                        repository_id,
                        &thread.session_id,
                        repository_root,
                        &mut coverage,
                    );
                    if changes.is_empty() {
                        degrade(
                            &mut coverage,
                            "file change metadata",
                            format!("fileChange item `{item_id}` contained no usable paths"),
                        );
                        continue;
                    }
                    events.push(semantic_event(
                        format!(
                            "codex-app-server:thread:{}:item:{}:file-change",
                            thread.id, item_id
                        ),
                        repository_id,
                        &thread.session_id,
                        EventKind::ToolFinished,
                        occurred_at,
                        sequence,
                        json!({
                            "thread_id": thread.id,
                            "turn_id": turn_id,
                            "item_id": item_id,
                            "session_id": thread.session_id,
                            "repository_path": repository_path,
                            "tool_name": "CodexAppServerFileChange",
                            "tool_use_id": item_id,
                            "tool_input": {
                                "path": changes.first().map(|change| change.path.clone()),
                                "change_count": changes.len()
                            },
                            "tool_response": {"status": item_object.get("status").cloned()},
                            "file_changes": changes,
                            "attribution_policy": "observed_changed_in",
                            "app_server_item_type": item_type,
                            "untrusted_data": true,
                            "raw_transcript_stored": false
                        }),
                        &coverage,
                    ));
                }
                "contextCompaction" => {
                    events.push(semantic_event(
                        format!(
                            "codex-app-server:thread:{}:item:{}:context-compaction",
                            thread.id, item_id
                        ),
                        repository_id,
                        &thread.session_id,
                        EventKind::ContextCompaction,
                        occurred_at,
                        sequence,
                        json!({
                            "thread_id": thread.id,
                            "turn_id": turn_id,
                            "item_id": item_id,
                            "session_id": thread.session_id,
                            "repository_path": repository_path,
                            "app_server_item_type": item_type,
                            "untrusted_data": true,
                            "raw_transcript_stored": false
                        }),
                        &coverage,
                    ));
                }
                item_type if !is_known_thread_item_type(item_type) => degrade(
                    &mut coverage,
                    "known thread item schema",
                    format!(
                        "turn {turn_index} item {item_index} has unknown type `{item_type}` and was not projected"
                    ),
                ),
                _ => {}
            }
        }
        if let Some((item_id, text, sequence, occurred_at, explicit_final)) = turn_final {
            if !explicit_final {
                degrade(
                    &mut coverage,
                    "assistant final phase",
                    format!(
                        "agentMessage item `{item_id}` omitted `phase: final_answer`; the last agent message in its turn was used"
                    ),
                );
            }
            saw_final = true;
            latest_final = Some(text.clone());
            events.push(semantic_event(
                format!(
                    "codex-app-server:thread:{}:item:{}:assistant-final",
                    thread.id, item_id
                ),
                repository_id,
                &thread.session_id,
                EventKind::AssistantFinal,
                occurred_at,
                sequence,
                json!({
                    "thread_id": thread.id,
                    "turn_id": turn_id,
                    "item_id": item_id,
                    "session_id": thread.session_id,
                    "repository_path": repository_path,
                    "last_assistant_message": text,
                    "app_server_item_type": "agentMessage",
                    "untrusted_data": true,
                    "raw_transcript_stored": false
                }),
                &coverage,
            ));
        }
    }

    if !saw_prompt {
        degrade(
            &mut coverage,
            "user prompt",
            "no text userMessage item was available for semantic reconstruction",
        );
    }
    if !saw_final {
        degrade(
            &mut coverage,
            "assistant final",
            "no agentMessage item was available for semantic reconstruction",
        );
    }
    finish_semantic_projection(
        thread,
        repository_id,
        repository_root,
        updated_at,
        events,
        coverage,
        latest_final,
    )
}

fn finish_semantic_projection(
    thread: &ImportedThreadV1,
    repository_id: &str,
    repository_root: &Path,
    updated_at: DateTime<Utc>,
    mut events: Vec<EventEnvelopeV1>,
    coverage: CoverageV1,
    latest_final: Option<String>,
) -> SemanticThreadProjectionV1 {
    let sequence = i64::MAX - 1;
    let turn_count = thread
        .thread
        .get("turns")
        .and_then(Value::as_array)
        .map(Vec::len)
        .unwrap_or_default();
    let created_at = timestamp_seconds(thread.created_at);
    events.push(semantic_event(
        format!("codex-app-server:thread:{}:stop", thread.id),
        repository_id,
        &thread.session_id,
        EventKind::SessionStopped,
        updated_at,
        sequence,
        json!({
            "thread_id": thread.id,
            "source_thread_id": thread.id,
            "session_id": thread.session_id,
            "repository_path": repository_root.to_string_lossy(),
            "thread_created_at": created_at,
            "thread_updated_at": updated_at,
            "turn_count": turn_count,
            "last_assistant_message": latest_final,
            "app_server_source": "thread/read",
            "untrusted_data": true,
            "raw_transcript_stored": false
        }),
        &coverage,
    ));
    for event in &mut events {
        event.coverage = CoverageV1::merge([&event.coverage, &coverage]);
        event.coverage.captured.extend([
            "thread/read semantic projection".to_string(),
            "stable source id".to_string(),
        ]);
        event.coverage.captured.sort();
        event.coverage.captured.dedup();
    }
    SemanticThreadProjectionV1 {
        schema_version: SCHEMA_VERSION_V1,
        events,
        coverage,
    }
}

#[allow(clippy::too_many_arguments)]
fn semantic_event(
    source_id: String,
    repository_id: &str,
    session_id: &str,
    kind: EventKind,
    occurred_at: DateTime<Utc>,
    sequence: i64,
    payload: Value,
    coverage: &CoverageV1,
) -> EventEnvelopeV1 {
    let mut event = EventEnvelopeV1::new(
        &source_id,
        repository_id,
        session_id,
        kind,
        occurred_at,
        payload,
    );
    event.dedupe_key = source_id.clone();
    event.event_id = format!(
        "evt-{}",
        &hex::encode(Sha256::digest(source_id.as_bytes()))[..24]
    );
    event.sequence = Some(sequence);
    event.coverage = coverage.clone();
    event
}

fn timestamp_seconds(seconds: i64) -> DateTime<Utc> {
    Utc.timestamp_opt(seconds, 0)
        .single()
        .unwrap_or(DateTime::<Utc>::UNIX_EPOCH)
}

fn item_timestamp(item: &Value) -> Option<DateTime<Utc>> {
    for key in ["createdAt", "updatedAt", "timestamp"] {
        if let Some(seconds) = item.get(key).and_then(Value::as_i64) {
            return Utc.timestamp_opt(seconds, 0).single();
        }
        if let Some(timestamp) = item.get(key).and_then(Value::as_str) {
            if let Ok(timestamp) = DateTime::parse_from_rfc3339(timestamp) {
                return Some(timestamp.with_timezone(&Utc));
            }
        }
    }
    None
}

fn bounded_message_content(content: Option<&Value>) -> Option<String> {
    let content = content?;
    let text = match content {
        Value::String(text) => text.clone(),
        Value::Array(parts) => parts
            .iter()
            .filter_map(|part| {
                let object = part.as_object()?;
                (object.get("type").and_then(Value::as_str) == Some("text"))
                    .then(|| object.get("text").and_then(Value::as_str))
                    .flatten()
            })
            .collect::<Vec<_>>()
            .join("\n"),
        _ => return None,
    };
    (!text.trim().is_empty()).then(|| crate::redaction::redact_excerpt(&text))
}

fn project_file_changes(
    changes: Option<&Value>,
    repository_id: &str,
    session_id: &str,
    repository_root: &Path,
    coverage: &mut CoverageV1,
) -> Vec<FileChangeV1> {
    let mut projected = Vec::new();
    let mut rejected = 0_usize;
    for change in changes.and_then(Value::as_array).into_iter().flatten() {
        let Some(raw_path) = change.get("path").and_then(Value::as_str) else {
            rejected += 1;
            continue;
        };
        let Some(path) = crate::git::validated_repository_relative_path(raw_path) else {
            rejected += 1;
            continue;
        };
        if path != raw_path {
            rejected += 1;
            continue;
        }
        let previous_path = match change.get("previousPath").and_then(Value::as_str) {
            Some(raw_previous) => {
                let Some(previous) = crate::git::validated_repository_relative_path(raw_previous)
                else {
                    rejected += 1;
                    continue;
                };
                if previous != raw_previous {
                    rejected += 1;
                    continue;
                }
                Some(previous)
            }
            None => None,
        };
        // The lexical validation above is the durable storage boundary. Joining it to the
        // supplied repository root must remain contained even when the imported item refers to a
        // file that no longer exists.
        let joined = repository_root.join(&path);
        if !joined.starts_with(repository_root) {
            rejected += 1;
            continue;
        }
        let status = match change
            .get("kind")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_ascii_lowercase()
            .as_str()
        {
            "add" | "added" | "create" | "created" => ChangeStatus::Added,
            "delete" | "deleted" | "remove" | "removed" => ChangeStatus::Deleted,
            "rename" | "renamed" | "move" | "moved" => ChangeStatus::Renamed,
            "update" | "updated" | "modify" | "modified" => ChangeStatus::Modified,
            _ => ChangeStatus::Unknown,
        };
        projected.push(FileChangeV1 {
            schema_version: SCHEMA_VERSION_V1,
            repository_id: repository_id.to_string(),
            session_id: session_id.to_string(),
            task_id: None,
            path,
            previous_path,
            status,
            additions: None,
            deletions: None,
            attribution: ChangeAttribution::ObservedChangedIn,
            before_head: None,
            after_head: None,
        });
    }
    if rejected > 0 {
        degrade(
            coverage,
            "safe repository-relative file change path",
            format!(
                "ignored {rejected} imported file change path(s) that were sensitive, absolute, parent-traversing, or non-normal"
            ),
        );
    }
    projected
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppServerRpcError {
    pub method: String,
    pub code: Option<i64>,
    pub message: String,
    pub data: Option<Value>,
}

impl fmt::Display for AppServerRpcError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.code {
            Some(code) => write!(
                formatter,
                "Codex app-server {} error {code}: {}",
                self.method, self.message
            ),
            None => write!(
                formatter,
                "Codex app-server {} error: {}",
                self.method, self.message
            ),
        }
    }
}

impl std::error::Error for AppServerRpcError {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ThreadImportDisposition {
    Imported,
    Skipped,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadImportNoticeV1 {
    pub thread_id: Option<String>,
    pub disposition: ThreadImportDisposition,
    pub coverage: CoverageV1,
    pub message: String,
    pub rpc_error: Option<AppServerRpcError>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadListReportV1 {
    pub schema_version: u16,
    pub threads: Vec<AppServerThreadSummary>,
    pub coverage: CoverageV1,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadImportReportV1 {
    pub schema_version: u16,
    pub threads: Vec<ImportedThreadV1>,
    pub notices: Vec<ThreadImportNoticeV1>,
    pub coverage: CoverageV1,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ThreadPage {
    data: Vec<Value>,
    next_cursor: Option<String>,
}

pub struct AppServerClient {
    child: Child,
    stdin: ChildStdin,
    stdout: BufReader<ChildStdout>,
    next_id: u64,
    initialize_result: Value,
    token_usage_notifications: BTreeMap<String, AppServerTokenUsageNotificationV1>,
    collector_warnings: Vec<String>,
}

impl AppServerClient {
    pub async fn connect() -> Result<Self> {
        Self::connect_with_program("codex").await
    }

    pub async fn connect_with_program(program: impl AsRef<Path>) -> Result<Self> {
        let mut child = Command::new(program.as_ref())
            .arg("app-server")
            .arg("--stdio")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .with_context(|| format!("start {} app-server", program.as_ref().display()))?;
        let stdin = child
            .stdin
            .take()
            .context("Codex app-server stdin unavailable")?;
        let stdout = child
            .stdout
            .take()
            .context("Codex app-server stdout unavailable")?;
        let mut client = Self {
            child,
            stdin,
            stdout: BufReader::new(stdout),
            next_id: 1,
            initialize_result: Value::Null,
            token_usage_notifications: BTreeMap::new(),
            collector_warnings: Vec::new(),
        };
        let initialized = client
            .request_timed(
                "initialize",
                json!({
                    "clientInfo": {
                        "name": "previously-on",
                        "title": "PreviouslyOn",
                        "version": APP_VERSION
                    },
                    "capabilities": {
                        "experimentalApi": false,
                        "requestAttestation": false
                    }
                }),
            )
            .await
            .context("initialize Codex app-server")?;
        client.initialize_result = initialized;
        client.notify("initialized", json!({})).await?;
        Ok(client)
    }

    pub fn initialize_result(&self) -> &Value {
        &self.initialize_result
    }

    pub async fn capability_report(&mut self) -> AppServerCapabilityReport {
        let detected_codex_version = codex_version().await.ok();
        let app_server_user_agent = self
            .initialize_result
            .get("userAgent")
            .and_then(Value::as_str)
            .map(str::to_string);
        let mut warnings = Vec::new();
        let status = match detected_codex_version.as_deref() {
            Some(version) if SUPPORTED_CODEX_VERSIONS.contains(&version) => {
                AppServerCapabilityStatus::Complete
            }
            Some(version) => {
                warnings.push(format!(
                    "Codex {version} differs from supported schemas {}",
                    SUPPORTED_CODEX_VERSIONS.join(", ")
                ));
                AppServerCapabilityStatus::Degraded
            }
            None => {
                warnings.push("unable to determine Codex version".to_string());
                AppServerCapabilityStatus::Degraded
            }
        };
        AppServerCapabilityReport {
            schema_version: 1,
            status,
            tested_codex_version: TESTED_CODEX_VERSION.to_string(),
            detected_codex_version,
            app_server_user_agent,
            supported_methods: vec![
                "initialize".to_string(),
                "initialized".to_string(),
                "thread/list".to_string(),
                "thread/read".to_string(),
            ],
            warnings,
        }
    }

    pub async fn list_threads(
        &mut self,
        cwd: Option<&Path>,
    ) -> Result<Vec<AppServerThreadSummary>> {
        Ok(self.list_threads_report(cwd).await?.threads)
    }

    /// Lists all readable summaries while isolating schema and pagination faults.
    ///
    /// A malformed later page or repeated cursor stops pagination and marks coverage degraded;
    /// summaries already validated remain usable. This prevents one bad page from contaminating
    /// or discarding the rest of an import.
    pub async fn list_threads_report(&mut self, cwd: Option<&Path>) -> Result<ThreadListReportV1> {
        let mut cursor: Option<String> = None;
        let mut seen_cursors = HashSet::new();
        let mut threads = Vec::new();
        let mut coverage = complete_coverage(["thread/list"]);
        for _ in 0..MAX_PAGES {
            let mut params = json!({
                "limit": 100,
                "sortKey": "created_at",
                "sortDirection": "desc",
                "useStateDbOnly": false
            });
            if let Some(cursor) = &cursor {
                params["cursor"] = json!(cursor);
            }
            if let Some(cwd) = cwd {
                params["cwd"] = json!(cwd.to_string_lossy());
            }
            let response = match self.request_timed("thread/list", params).await {
                Ok(response) => response,
                Err(error) => {
                    degrade(
                        &mut coverage,
                        "thread/list page",
                        format!("Codex thread/list stopped safely: {error}"),
                    );
                    break;
                }
            };
            let page: ThreadPage = match serde_json::from_value(response) {
                Ok(page) => page,
                Err(error) => {
                    degrade(
                        &mut coverage,
                        "thread/list page",
                        format!("invalid Codex thread/list response; pagination stopped: {error}"),
                    );
                    break;
                }
            };
            for thread in page.data {
                match parse_thread_summary(thread) {
                    Ok(thread) => threads.push(thread),
                    Err(error) => degrade(
                        &mut coverage,
                        "thread/list item",
                        format!("malformed thread summary skipped: {error}"),
                    ),
                }
            }
            match page.next_cursor {
                None => {
                    self.apply_collector_warnings(&mut coverage);
                    return Ok(ThreadListReportV1 {
                        schema_version: 1,
                        threads,
                        coverage,
                    });
                }
                Some(next) if !seen_cursors.insert(next.clone()) => {
                    degrade(
                        &mut coverage,
                        "thread/list pagination",
                        format!("Codex thread/list repeated cursor `{next}`; pagination stopped"),
                    );
                    break;
                }
                Some(next) => cursor = Some(next),
            }
        }
        if coverage.status == CoverageStatus::Complete {
            degrade(
                &mut coverage,
                "thread/list pagination",
                format!("Codex thread/list exceeded {MAX_PAGES} pages"),
            );
        }
        self.apply_collector_warnings(&mut coverage);
        Ok(ThreadListReportV1 {
            schema_version: 1,
            threads,
            coverage,
        })
    }

    pub async fn read_thread(&mut self, thread_id: &str) -> Result<Value> {
        let result = self
            .request_timed(
                "thread/read",
                json!({ "threadId": thread_id, "includeTurns": true }),
            )
            .await
            .with_context(|| format!("Codex thread/read failed for {thread_id}"))?;
        result
            .get("thread")
            .cloned()
            .context("Codex thread/read response omitted `thread`")
    }

    pub async fn import_threads(&mut self, cwd: &Path) -> Result<Vec<ImportedThreadV1>> {
        Ok(self.import_threads_report(cwd).await?.threads)
    }

    pub async fn import_threads_report(&mut self, cwd: &Path) -> Result<ThreadImportReportV1> {
        let registered_repository = repository_identity(cwd).with_context(|| {
            format!(
                "identify registered Git repository before Codex App Server import: {}",
                cwd.display()
            )
        })?;
        let listed = self.list_threads_report(Some(cwd)).await?;
        let mut imported = Vec::with_capacity(listed.threads.len());
        let mut notices = Vec::new();
        let mut coverages = vec![listed.coverage.clone()];
        for summary in listed.threads {
            if let Err(warning) = validate_thread_repository(&summary.cwd, &registered_repository) {
                let mut coverage = summary.coverage.clone();
                degrade(
                    &mut coverage,
                    "matching repository cwd",
                    warning.to_string(),
                );
                coverages.push(coverage.clone());
                notices.push(ThreadImportNoticeV1 {
                    thread_id: Some(summary.id),
                    disposition: ThreadImportDisposition::Skipped,
                    message: coverage.warnings.join("; "),
                    coverage,
                    rpc_error: None,
                });
                continue;
            }
            let mut thread = match self.read_thread(&summary.id).await {
                Ok(thread) => thread,
                Err(error) => {
                    let rpc_error = error.downcast_ref::<AppServerRpcError>().cloned();
                    let deleted = rpc_error.as_ref().is_some_and(is_deleted_thread_error);
                    let mut coverage = complete_coverage(std::iter::empty::<&str>());
                    degrade(
                        &mut coverage,
                        "thread/read",
                        if deleted {
                            "thread was deleted before import and was skipped".to_string()
                        } else {
                            format!("thread/read failed; thread skipped: {error}")
                        },
                    );
                    self.apply_collector_warnings(&mut coverage);
                    coverages.push(coverage.clone());
                    notices.push(ThreadImportNoticeV1 {
                        thread_id: Some(summary.id),
                        disposition: ThreadImportDisposition::Skipped,
                        message: coverage.warnings.join("; "),
                        coverage,
                        rpc_error,
                    });
                    continue;
                }
            };
            if let Some(notification) = self.token_usage_notifications.remove(&summary.id) {
                if let Some(object) = thread.as_object_mut() {
                    object.insert(
                        "_previously_token_usage".to_string(),
                        serde_json::to_value(notification)?,
                    );
                }
            }
            let (thread, mut thread_coverage) =
                normalize_and_assess_thread(thread, &summary.cli_version);
            self.apply_collector_warnings(&mut thread_coverage);
            let coverage = CoverageV1::merge([&summary.coverage, &thread_coverage]);
            if coverage.status != CoverageStatus::Complete {
                notices.push(ThreadImportNoticeV1 {
                    thread_id: Some(summary.id.clone()),
                    disposition: ThreadImportDisposition::Imported,
                    message: coverage.warnings.join("; "),
                    coverage: coverage.clone(),
                    rpc_error: None,
                });
            }
            coverages.push(coverage.clone());
            imported.push(ImportedThreadV1 {
                schema_version: 1,
                id: summary.id,
                session_id: summary.session_id,
                cwd: summary.cwd,
                cli_version: summary.cli_version,
                created_at: summary.created_at,
                updated_at: summary.updated_at,
                coverage,
                thread,
            });
        }
        let coverage = CoverageV1::merge(coverages.iter());
        Ok(ThreadImportReportV1 {
            schema_version: 1,
            threads: imported,
            notices,
            coverage,
        })
    }

    pub async fn shutdown(mut self) -> Result<()> {
        self.stdin.shutdown().await.ok();
        match tokio::time::timeout(std::time::Duration::from_secs(2), self.child.wait()).await {
            Ok(result) => {
                result?;
            }
            Err(_) => {
                self.child.kill().await.ok();
            }
        }
        Ok(())
    }

    async fn request(&mut self, method: &str, params: Value) -> Result<Value> {
        let id = self.next_id;
        self.next_id += 1;
        self.write_message(&json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params
        }))
        .await?;
        loop {
            let line = match crate::bounded_io::read_bounded_line_async(
                &mut self.stdout,
                MAX_APP_SERVER_RPC_BYTES,
                false,
            )
            .await?
            {
                crate::bounded_io::BoundedLine::Eof => {
                    bail!("Codex app-server closed stdout while waiting for {method}")
                }
                crate::bounded_io::BoundedLine::TooLong => bail!(
                    "Codex app-server JSON-RPC frame exceeds {MAX_APP_SERVER_RPC_BYTES} byte limit"
                ),
                crate::bounded_io::BoundedLine::Line(line) => line,
            };
            let message: Value =
                serde_json::from_slice(&line).context("invalid JSON from Codex app-server")?;
            if message.get("id").and_then(Value::as_u64) != Some(id) {
                match parse_token_usage_notification(&message) {
                    Ok(Some(notification)) => {
                        self.token_usage_notifications
                            .insert(notification.thread_id.clone(), notification);
                    }
                    Ok(None) => {}
                    Err(_) => {
                        if !self
                            .collector_warnings
                            .iter()
                            .any(|warning| warning == MALFORMED_TOKEN_USAGE_WARNING)
                        {
                            self.collector_warnings
                                .push(MALFORMED_TOKEN_USAGE_WARNING.to_string());
                        }
                    }
                }
                continue;
            }
            if let Some(error) = message.get("error") {
                let rpc_error = AppServerRpcError {
                    method: method.to_string(),
                    code: error.get("code").and_then(Value::as_i64),
                    message: crate::redaction::redact_excerpt(
                        error
                            .get("message")
                            .and_then(Value::as_str)
                            .unwrap_or("unspecified JSON-RPC error"),
                    ),
                    data: error.get("data").map(crate::redaction::redact_value),
                };
                return Err(anyhow::Error::new(rpc_error));
            }
            return message
                .get("result")
                .cloned()
                .with_context(|| format!("Codex app-server {method} response omitted result"));
        }
    }

    async fn request_timed(&mut self, method: &str, params: Value) -> Result<Value> {
        tokio::time::timeout(
            std::time::Duration::from_secs(10),
            self.request(method, params),
        )
        .await
        .with_context(|| format!("Codex app-server {method} timed out"))?
    }

    fn apply_collector_warnings(&self, coverage: &mut CoverageV1) {
        for warning in &self.collector_warnings {
            degrade(coverage, "valid token-usage notification", warning.clone());
        }
    }

    async fn notify(&mut self, method: &str, params: Value) -> Result<()> {
        self.write_message(&json!({
            "jsonrpc": "2.0",
            "method": method,
            "params": params
        }))
        .await
    }

    async fn write_message(&mut self, message: &Value) -> Result<()> {
        let bytes = serde_json::to_vec(message)?;
        self.stdin.write_all(&bytes).await?;
        self.stdin.write_all(b"\n").await?;
        self.stdin.flush().await?;
        Ok(())
    }
}

fn validate_thread_repository(cwd: &Path, registered: &RepositoryIdentity) -> Result<()> {
    if !cwd.is_absolute() {
        bail!("Codex thread/list returned a non-absolute cwd; thread skipped")
    }
    let returned = repository_identity(cwd)
        .context("Codex thread/list cwd is not a readable Git worktree; thread skipped")?;
    if returned.common_dir != registered.common_dir {
        bail!(
            "Codex thread/list returned a cwd owned by a different logical Git repository; thread skipped"
        )
    }
    Ok(())
}

pub async fn inspect_capabilities() -> AppServerCapabilityReport {
    match AppServerClient::connect().await {
        Ok(mut client) => {
            let report = client.capability_report().await;
            client.shutdown().await.ok();
            report
        }
        Err(error) => AppServerCapabilityReport::unsupported(error.to_string()),
    }
}

fn parse_thread_summary(raw: Value) -> Result<AppServerThreadSummary> {
    let required_string = |key: &str| -> Result<String> {
        raw.get(key)
            .and_then(Value::as_str)
            .filter(|value| !value.is_empty())
            .map(str::to_string)
            .with_context(|| format!("Codex thread/list item omitted non-empty `{key}`"))
    };
    let required_i64 = |key: &str| -> Result<i64> {
        raw.get(key)
            .and_then(Value::as_i64)
            .with_context(|| format!("Codex thread/list item omitted `{key}`"))
    };
    let mut coverage = complete_coverage(["thread summary"]);
    let session_id = match raw.get("sessionId").and_then(Value::as_str) {
        Some(session_id) if !session_id.is_empty() => session_id.to_string(),
        _ => {
            let generated = format!("app-import-{}", Uuid::now_v7());
            degrade(
                &mut coverage,
                "stable session source ID",
                format!(
                    "thread summary omitted stable sessionId; assigned UUID `{generated}` without payload-hash deduplication"
                ),
            );
            generated
        }
    };
    Ok(AppServerThreadSummary {
        id: required_string("id")?,
        session_id,
        cwd: PathBuf::from(required_string("cwd")?),
        cli_version: required_string("cliVersion")?,
        created_at: required_i64("createdAt")?,
        updated_at: required_i64("updatedAt")?,
        preview: required_string("preview")?,
        coverage,
        raw,
    })
}

fn complete_coverage(items: impl IntoIterator<Item = impl Into<String>>) -> CoverageV1 {
    CoverageV1 {
        captured: items.into_iter().map(Into::into).collect(),
        ..CoverageV1::default()
    }
}

fn degrade(coverage: &mut CoverageV1, missing: impl Into<String>, warning: impl Into<String>) {
    coverage.status = CoverageStatus::Degraded;
    let missing = missing.into();
    if !coverage.missing.contains(&missing) {
        coverage.missing.push(missing);
    }
    let warning = warning.into();
    if !coverage.warnings.contains(&warning) {
        coverage.warnings.push(warning);
    }
}

fn is_deleted_thread_error(error: &AppServerRpcError) -> bool {
    let mut evidence = error.message.to_ascii_lowercase();
    if let Some(data) = &error.data {
        evidence.push(' ');
        evidence.push_str(&data.to_string().to_ascii_lowercase());
    }
    matches!(error.code, Some(-32001) | Some(-32004))
        || evidence.contains("not found")
        || evidence.contains("deleted")
        || evidence.contains("thread_not_found")
}

fn normalize_and_assess_thread(mut thread: Value, cli_version: &str) -> (Value, CoverageV1) {
    let mut coverage = complete_coverage(["thread/read"]);
    if !SUPPORTED_CODEX_VERSIONS.contains(&cli_version) {
        degrade(
            &mut coverage,
            "tested App Server version",
            format!(
                "thread was recorded by Codex {cli_version}; supported versions are {}",
                SUPPORTED_CODEX_VERSIONS.join(", ")
            ),
        );
    }

    if thread.get("compacted").and_then(Value::as_bool) == Some(true)
        || value_contains_marker(thread.get("status"), &["compact", "incomplete"])
    {
        degrade(
            &mut coverage,
            "complete thread history",
            "thread is compacted or incomplete; available turns were imported as untrusted data",
        );
    }

    let Some(turns) = thread.get_mut("turns").and_then(Value::as_array_mut) else {
        degrade(
            &mut coverage,
            "thread turns",
            "thread/read omitted a turns array",
        );
        return (thread, coverage);
    };

    for (turn_index, turn) in turns.iter_mut().enumerate() {
        let Some(turn_object) = turn.as_object_mut() else {
            degrade(
                &mut coverage,
                "well-formed turn",
                format!("turn {turn_index} was not an object and remains opaque"),
            );
            continue;
        };
        ensure_uuid_source_id(turn_object, "turn", turn_index, &mut coverage);
        if value_contains_marker(
            turn_object.get("status"),
            &["failed", "interrupt", "incomplete"],
        ) {
            degrade(
                &mut coverage,
                "completed turn",
                format!("turn {turn_index} is incomplete or interrupted"),
            );
        }
        let Some(items) = turn_object.get_mut("items").and_then(Value::as_array_mut) else {
            degrade(
                &mut coverage,
                "turn items",
                format!("turn {turn_index} omitted an items array"),
            );
            continue;
        };
        for (item_index, item) in items.iter_mut().enumerate() {
            let Some(item_object) = item.as_object_mut() else {
                degrade(
                    &mut coverage,
                    "well-formed thread item",
                    format!("turn {turn_index} item {item_index} was not an object"),
                );
                continue;
            };
            ensure_uuid_source_id(item_object, "item", item_index, &mut coverage);
            let item_type = item_object.get("type").and_then(Value::as_str);
            if !item_type.is_some_and(is_known_thread_item_type) {
                degrade(
                    &mut coverage,
                    "known thread item schema",
                    format!(
                        "turn {turn_index} item {item_index} has unknown type `{}` and remains opaque",
                        item_type.unwrap_or("<missing>")
                    ),
                );
            }
        }
    }
    (thread, coverage)
}

fn ensure_uuid_source_id(
    object: &mut serde_json::Map<String, Value>,
    kind: &str,
    index: usize,
    coverage: &mut CoverageV1,
) {
    let has_stable_id = object
        .get("id")
        .and_then(Value::as_str)
        .is_some_and(|value| !value.is_empty());
    if has_stable_id {
        return;
    }
    let source_id = format!("app-import-{}", Uuid::now_v7());
    object.insert("id".to_string(), Value::String(source_id.clone()));
    degrade(
        coverage,
        format!("stable {kind} source ID"),
        format!(
            "{kind} {index} omitted a stable ID; assigned UUID `{source_id}` without payload-hash deduplication"
        ),
    );
}

fn value_contains_marker(value: Option<&Value>, markers: &[&str]) -> bool {
    let Some(value) = value else {
        return false;
    };
    let rendered = value.to_string().to_ascii_lowercase();
    markers.iter().any(|marker| rendered.contains(marker))
}

fn is_known_thread_item_type(item_type: &str) -> bool {
    matches!(
        item_type,
        "userMessage"
            | "agentMessage"
            | "plan"
            | "reasoning"
            | "commandExecution"
            | "fileChange"
            | "mcpToolCall"
            | "webSearch"
            | "imageView"
            | "enteredReviewMode"
            | "exitedReviewMode"
            | "contextCompaction"
    )
}

pub async fn codex_version() -> Result<String> {
    let output = Command::new("codex")
        .arg("--version")
        .output()
        .await
        .context("run codex --version")?;
    if !output.status.success() {
        bail!("codex --version exited with {}", output.status);
    }
    let stdout = String::from_utf8(output.stdout).context("codex --version was not UTF-8")?;
    stdout
        .split_whitespace()
        .last()
        .map(str::to_string)
        .context("codex --version returned no version")
}