aion-core 0.31.0

Pure domain model and shared vocabulary for Aion durable workflows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
//! The assistant-session vocabulary: identity, state, the summary a listing
//! carries, the context a turn is asked with, and the frames a session streams.
//!
//! An assistant session is ONE live agent-harness process the server owns on a
//! caller's behalf — not a workflow run. It has no history to replay and no
//! determinism boundary; what it has is a durable transcript (every request and
//! every event, in order) and a process that dies with the server.
//!
//! These types live in `aion-core` rather than in `aion-server` for the reason
//! every other wire record does: the store persists them, the server serves
//! them, and the ops console's TypeScript types are generated from this crate.
//! One declaration, three consumers, no hand-kept copy.
//!
//! # The frames are the transcript
//!
//! [`AssistantSessionEvent`] is exactly what the WebSocket streams AND exactly
//! what is appended to the durable transcript, so replaying the transcript and
//! watching live are the same stream seen at two times. The index a frame
//! carries ([`AssistantSessionFrame`]) is assigned by the store, densely, and is
//! what a reconnecting client passes back as `?after=`.

use chrono::{DateTime, Utc};

use crate::assistant_document::{
    AssistantDocumentEditError, AssistantDocumentEditOp, apply_document_edits,
};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// Identifier for one assistant session.
///
/// A UUID rather than an operator-chosen name: a session is minted by the
/// server, is never addressed by a name a human types, and a UUID keys a
/// fixed-width durable record without an escaping rule.
#[derive(
    Serialize, Deserialize, ts_rs::TS, Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord,
)]
pub struct AssistantSessionId(Uuid);

impl AssistantSessionId {
    /// Creates a session identifier from an existing UUID.
    #[must_use]
    pub const fn new(id: Uuid) -> Self {
        Self(id)
    }

    /// Mints a fresh session identifier.
    #[must_use]
    pub fn new_v4() -> Self {
        Self(Uuid::new_v4())
    }

    /// Returns the UUID backing this identifier.
    #[must_use]
    pub const fn as_uuid(&self) -> Uuid {
        self.0
    }

    /// Parses a session identifier from its canonical textual form.
    ///
    /// # Errors
    ///
    /// Returns [`AssistantSessionIdError`] naming the text that is not a UUID.
    /// A caller-supplied path segment is parsed here rather than pattern-matched
    /// somewhere downstream, so a malformed id is one refusal with one message.
    pub fn parse(text: &str) -> Result<Self, AssistantSessionIdError> {
        Uuid::parse_str(text)
            .map(Self)
            .map_err(|_source| AssistantSessionIdError {
                text: text.to_owned(),
            })
    }
}

impl std::fmt::Display for AssistantSessionId {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(formatter)
    }
}

/// A session identifier that could not be parsed from its textual form.
#[derive(thiserror::Error, Clone, Debug, PartialEq, Eq)]
#[error("`{text}` is not an assistant session id (session ids are UUIDs minted by the server)")]
pub struct AssistantSessionIdError {
    /// The text that was offered as a session id.
    pub text: String,
}

/// What a session is, as the wire reports it — three answers and no more.
///
/// A PROJECTION, never a stored field, exactly as `WorkflowStatus` is: it is
/// derived from the session's appended transcript records plus the live-process
/// registry. Nothing writes a state; things append records, and this is read off
/// them.
///
/// The states a UI might expect and will not find here are deliberate:
///
/// - **"busy" is not a state.** Whether a turn is open is what the transcript
///   already says, so a session cannot be busy on the wire and idle in its
///   frames. The refusal a caller needs — a second turn while one is open — is
///   a `409` on the turn, not a state to render.
/// - **"not logged in" is not a state.** It is the `auth_required` code on the
///   turn that hit it, which names the turn it failed on; a session-wide state
///   would claim the whole conversation was unusable when one turn was.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum AssistantSessionState {
    /// A harness process is running for this session right now.
    Live,
    /// No process — but the harness advertised `loadSession`, so the
    /// conversation is the harness's OWN and can be reopened. The next turn
    /// respawns it and opens with `session/load`, so a dormant session is
    /// continuable and is never an error.
    Dormant,
    /// Shut by the caller, and reopenable: the harness advertised
    /// `loadSession` and the conversation has a handle to load, so the next
    /// turn respawns it exactly as a dormant one — but the caller chose to put
    /// it away, so it is never the operator's *current* session. Opening it
    /// from history and typing is what brings it back.
    Closed,
    /// Terminal and read-only: its harness cannot reload a prior conversation,
    /// so there is nothing left to return to — whether the process went on its
    /// own or the caller shut it.
    Ended,
}

impl AssistantSessionState {
    /// Whether a process is running for this session.
    #[must_use]
    pub const fn is_live(self) -> bool {
        matches!(self, Self::Live)
    }

    /// Whether another turn can be taken — now, or after a resume.
    #[must_use]
    pub const fn is_continuable(self) -> bool {
        matches!(self, Self::Live | Self::Dormant | Self::Closed)
    }

    /// Whether this session may be the operator's *current* one: continuable
    /// AND not put away. A closed session can still be reopened, but only by
    /// the operator choosing it — it never becomes current on its own.
    #[must_use]
    pub const fn is_current_candidate(self) -> bool {
        matches!(self, Self::Live | Self::Dormant)
    }
}

/// One row of the session list.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Debug, PartialEq, Eq)]
pub struct AssistantSessionSummary {
    /// The session's identity.
    pub session_id: AssistantSessionId,
    /// The configured harness name this session runs.
    pub harness: String,
    /// The configured account name, when the harness declares any.
    pub account: Option<String>,
    /// What the session is, right now.
    pub state: AssistantSessionState,
    /// Why it is in that state, in the server's own words, or `None`.
    ///
    /// An ended session carries the reason it ended; a dormant one carries why
    /// its process went away. A live one carries nothing, because nothing
    /// decided it.
    pub reason: Option<String>,
    /// When the session was created.
    pub created_at: DateTime<Utc>,
    /// The last time anything about the session changed.
    pub updated_at: DateTime<Utc>,
    /// How many turns have been submitted on it.
    pub turns: u64,
    /// The first 80 characters of the first prompt, or `None` before one.
    pub title: Option<String>,
    /// The commands the HARNESS most recently advertised, in the order it
    /// advertised them. Empty when it has advertised none.
    ///
    /// A projection over the transcript's
    /// [`AssistantSessionEvent::AvailableCommands`] records, never a stored
    /// field, and never a list this server composes: a command a client offers
    /// that the agent never advertised is a refusal waiting to happen, so the
    /// only honest source is what the agent itself said.
    pub commands: Vec<AssistantCommand>,

    /// The configuration options the HARNESS most recently advertised — the
    /// model picker among them. Same rule and same reasons as `commands`: a
    /// projection over the transcript's
    /// [`AssistantSessionEvent::ConfigOptions`] records, replaced whole by
    /// each advertisement, never a list this server composes.
    pub config_options: Vec<AssistantConfigOption>,
}

/// One command the harness advertised on this session.
///
/// The three fields ACP's `AvailableCommand` carries that a client needs to
/// OFFER one: what to send, what it does, and — when the command takes input —
/// the hint to show before any has been typed. ACP's only input form is
/// `unstructured` ("all text that was typed after the command name is provided
/// as input"), so a hint is the whole of what there is to publish about it.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Debug, PartialEq, Eq)]
pub struct AssistantCommand {
    /// The command's name, as sent on a turn.
    pub name: String,
    /// What the agent says it does.
    pub description: String,
    /// The hint to show while the command's input is empty, when it takes one.
    pub input_hint: Option<String>,
}

/// One value a select-style configuration option offers.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Debug, PartialEq, Eq)]
pub struct AssistantConfigChoice {
    /// The value's identifier — what `session/set_config_option` is sent.
    pub id: String,
    /// Human-readable label.
    pub name: String,
    /// What the agent says about this value, when it says anything.
    pub description: Option<String>,
    /// The label of the group the agent listed it under, when it grouped them.
    /// Kept so a surface can render the agent's own grouping; flat rendering
    /// may ignore it without losing a choice.
    pub group: Option<String>,
}

/// The type-specific half of one configuration option.
///
/// Exactly the two shapes ACP's `SessionConfigKind` publishes today. An option
/// of a kind this server cannot represent is skipped with a log line — the
/// rest of the advertisement stands, exactly as a malformed command entry is
/// handled — so this enum never carries a value it is guessing about.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Debug, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AssistantConfigValue {
    /// Pick exactly one of the listed choices.
    Select {
        /// Every choice the agent offers, in the order it listed them.
        choices: Vec<AssistantConfigChoice>,
        /// The id of the currently selected choice.
        current: String,
    },
    /// An on/off switch.
    Toggle {
        /// The current value.
        current: bool,
    },
}

/// One configuration option the harness advertised on this session.
///
/// The published mirror of ACP's `SessionConfigOption`: what an operator may
/// configure about the running agent, the model selector chief among them
/// (`category` is ACP's own semantic label — `"model"`, `"mode"`,
/// `"thought_level"`, or whatever a future agent says, verbatim). The only
/// honest source is what the agent itself advertised, exactly as with
/// [`AssistantCommand`]: an option a client offers that the agent never
/// advertised is a refusal waiting to happen.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Debug, PartialEq, Eq)]
pub struct AssistantConfigOption {
    /// The option's identifier, as sent when setting it.
    pub id: String,
    /// Human-readable label.
    pub name: String,
    /// What the agent says it does, when it says anything.
    pub description: Option<String>,
    /// ACP's semantic category, verbatim, when the agent gave one. UX only:
    /// nothing decides behaviour on it.
    pub category: Option<String>,
    /// The option's shape and current state.
    pub value: AssistantConfigValue,
}

/// A harness command a turn invokes.
///
/// ACP delivers a command as ORDINARY PROMPT TEXT — `/name` followed by
/// whatever input was typed after it, which is exactly what the schema's
/// `unstructured` input form says the agent receives. So this is not an
/// alternative transport; it is a statement of intent the server turns into the
/// spec's own delivery form, checks against what the agent advertised, and
/// records verbatim so the transcript says a command was invoked rather than
/// leaving a reader to infer it from a leading slash.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Debug, PartialEq, Eq)]
pub struct AssistantCommandInvocation {
    /// The advertised command's name, without the leading `/`.
    pub name: String,
    /// The text typed after the command name, when any was.
    pub input: Option<String>,
}

impl AssistantCommandInvocation {
    /// The prompt line ACP delivers this invocation as.
    ///
    /// `/name` alone, or `/name input` — the one place the delivery form is
    /// spelled, so the wire tests and the turn path cannot disagree about it.
    #[must_use]
    pub fn prompt_line(&self) -> String {
        match self
            .input
            .as_deref()
            .map(str::trim)
            .filter(|input| !input.is_empty())
        {
            Some(input) => format!("/{} {input}", self.name),
            None => format!("/{}", self.name),
        }
    }
}

/// A position in a document, in editor coordinates.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Copy, Debug, PartialEq, Eq)]
pub struct AssistantDocumentPosition {
    /// Zero-based line number, as the editor's own model holds it.
    ///
    /// ZERO-based on the wire and ONE-based in the prose: the numbers a
    /// document model uses and the numbers an operator reads off a gutter are
    /// different numbers, and converting once — where the prose is composed —
    /// is what keeps them from drifting.
    pub line: u32,
    /// Zero-based column, counted in UTF-16 code units (the editor's own unit).
    pub column: u32,
}

/// A selected range in a document.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Copy, Debug, PartialEq, Eq)]
pub struct AssistantDocumentSelection {
    /// Where the selection starts.
    pub from: AssistantDocumentPosition,
    /// Where the selection ends.
    pub to: AssistantDocumentPosition,
}

/// The document a turn is asked about.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Debug, PartialEq, Eq)]
pub struct AssistantDocumentContext {
    /// The document's workspace-relative path.
    pub path: String,
    /// The document's current text, as the editor holds it.
    pub text: String,
    /// The selection that scopes the request, when there is one.
    pub selection: Option<AssistantDocumentSelection>,
    /// Where the caret is, when the document came from a live editor.
    ///
    /// NOT a zero-width selection: a caret is where the operator IS and a
    /// selection is what they CHOSE, and an agent told a region was selected
    /// when none was edits the wrong thing. Carried as its own field so the
    /// prose can say "cursor on line 4" with no selection at all — and so the
    /// operator's own words never have to carry it (nothing is appended to
    /// what they typed; Tom, 2026-08-30).
    pub cursor: Option<AssistantDocumentPosition>,
}

/// What was on the operator's screen when they asked.
///
/// Composed into the prompt as prose by the server, and SHOWN to the operator
/// before it is sent — the console renders the same prefix the server will
/// build, and the operator may opt out of it.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Debug, Default, PartialEq, Eq)]
pub struct AssistantTurnContext {
    /// The console URL the operator was on.
    pub url: Option<String>,
    /// The titles of the explain concepts declared on that screen.
    pub concepts: Vec<String>,
    /// The document under the editor's cursor, when the turn came from there.
    pub document: Option<AssistantDocumentContext>,
}

/// How a tool call is going.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AssistantToolCallStatus {
    /// The agent has begun the call.
    Started,
    /// The call finished and its output is on the frame.
    Completed,
    /// The call failed; the failure is on the frame's output.
    Failed,
}

/// How a permission request was decided.
///
/// There is no console prompt in this cut: the configured policy decides, and
/// the decision is recorded so an operator can see what was asked and what was
/// answered.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AssistantPermissionDecision {
    /// The policy allowed the call, once.
    AllowOnce,
    /// The policy denied the call.
    Deny,
}

/// One event on a session's transcript, and one frame on its WebSocket.
///
/// The SAME value is durably appended and streamed live, so replay and live are
/// one stream read at two times rather than two encodings that could disagree.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Debug, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AssistantSessionEvent {
    /// A harness process opened (or reopened) the conversation.
    ///
    /// Appended once per spawn — so a resumed session has two of these, and the
    /// LAST one carries the capabilities of the process that is running now. It
    /// is what makes the resume decision a fact read off the transcript rather
    /// than a guess: `load_session` is what the agent ACTUALLY advertised at
    /// `initialize`, not what its kind is assumed to support.
    SessionOpened {
        /// The harness's own session handle — what `session/load` resumes.
        acp_session_ref: String,
        /// Whether this agent advertised `loadSession` at `initialize`.
        load_session: bool,
        /// When it opened.
        at: DateTime<Utc>,
        /// Whether this open was a resume of a prior conversation.
        resumed: bool,
    },
    /// The operator's on-screen context, as it stood.
    ///
    /// Appended by every turn and by an explicit context push, so the LATEST one
    /// is the shared context both surfaces read — and the one the harness's
    /// `assistant_context` tool answers with. The transcript IS the shared
    /// context; there is no second store.
    ContextShared {
        /// What was on screen.
        context: AssistantTurnContext,
        /// What put it there: `turn` or `push`.
        source: String,
    },
    /// What the OPERATOR asked, appended the moment the turn was accepted and
    /// before any frame the harness produces for it.
    ///
    /// The record of the question. Without it a reloaded conversation is answers
    /// with no questions, and the transcript — which is the shared context both
    /// surfaces read — could not say what was asked. It carries the context the
    /// turn was sent with, so the request and the screen it was asked from are
    /// ONE record rather than two that could be appended out of order.
    Request {
        /// The turn this frame belongs to.
        turn_id: String,
        /// The operator's own words, without the composed context prefix.
        text: String,
        /// What was on the operator's screen, when they sent any.
        context: Option<AssistantTurnContext>,
        /// The harness command this turn invokes, when it invokes one.
        ///
        /// Recorded beside the text rather than folded into it, because a
        /// transcript that showed only the composed `/compact …` line could not
        /// say whether the operator pressed a command control or typed a line
        /// that happened to begin with a slash.
        command: Option<AssistantCommandInvocation>,
    },
    /// A turn was accepted and the prompt was sent.
    TurnStarted {
        /// The turn this frame belongs to.
        turn_id: String,
        /// When the turn started.
        at: DateTime<Utc>,
        /// The prompt exactly as it was sent, context prefix included.
        ///
        /// Recorded so the transcript answers "what was the agent actually
        /// asked" — a transcript that showed only the operator's typing would
        /// hide the composed context the answer was really shaped by. The
        /// operator's own words are on the [`Self::Request`] frame that precedes
        /// this one; they are not repeated here.
        prompt: String,
    },
    /// The harness advertised the commands it serves.
    ///
    /// A COMPLETE replacement of whatever it advertised before, exactly as ACP's
    /// `available_commands_update` is: an agent that drops a command stops
    /// listing it, and a merge would keep offering a command that would now be
    /// refused.
    AvailableCommands {
        /// Every command the harness serves, in the order it listed them.
        commands: Vec<AssistantCommand>,
    },
    /// The harness advertised its configuration options — the model picker
    /// among them.
    ///
    /// A COMPLETE replacement of whatever it advertised before, exactly as
    /// ACP's `config_option_update` and its `session/set_config_option`
    /// response both are: an agent that drops an option stops listing it, and
    /// a merge would keep offering a value that would now be refused.
    ConfigOptions {
        /// Every option, in the order the agent listed them.
        options: Vec<AssistantConfigOption>,
    },
    /// An agent text chunk, in order.
    Delta {
        /// The turn this frame belongs to.
        turn_id: String,
        /// The chunk.
        text: String,
    },
    /// An agent thought chunk.
    Thought {
        /// The turn this frame belongs to.
        turn_id: String,
        /// The thought fragment.
        text: String,
    },
    /// A tool call the agent made.
    ToolCall {
        /// The turn this frame belongs to.
        turn_id: String,
        /// The agent's own id for the call, so updates join to one row.
        call_id: String,
        /// The tool's name.
        name: String,
        /// How the call is going.
        status: AssistantToolCallStatus,
        /// The call's input, when the agent reported one.
        #[ts(type = "unknown")]
        input: Option<serde_json::Value>,
        /// The call's output, when the agent reported one.
        #[ts(type = "unknown")]
        output: Option<serde_json::Value>,
    },
    /// A permission request, recorded with the decision the policy made.
    PermissionAsk {
        /// The turn this frame belongs to.
        turn_id: String,
        /// The agent's request, verbatim.
        #[ts(type = "unknown")]
        request: serde_json::Value,
        /// What the configured policy answered.
        decided: AssistantPermissionDecision,
    },
    /// The agent edited the shared document through its
    /// `assistant_document_edit` tool.
    ///
    /// Appended by the assistant MCP route AFTER validating the batch against
    /// the shared document as the transcript then held it, so a recorded batch
    /// always applied cleanly in full. The projection folds it into
    /// `latest_context` — which is how the agent's own next `assistant_context`
    /// read sees its edits — and the console applies the same operations to the
    /// live editor buffer, where the operator keeps or reverts them.
    DocumentEdit {
        /// The operations, in application order.
        edits: Vec<AssistantDocumentEditOp>,
        /// The shared document's revision AFTER this batch — monotonic per
        /// session and never reset, so a client replaying frames after a
        /// reconnect can skip batches it already applied.
        revision: u64,
    },
    /// The turn ended with an answer.
    TurnCompleted {
        /// The turn this frame belongs to.
        turn_id: String,
        /// The agent's last completed message.
        final_message: String,
        /// The canonical stop reason.
        stop_reason: String,
        /// The harness's own session handle, when it reported one.
        session_ref: Option<String>,
    },
    /// The turn ended without an answer.
    TurnFailed {
        /// The turn this frame belongs to.
        turn_id: String,
        /// `auth_required` for a `-32000`, otherwise the typed harness-error
        /// variant name in `snake_case`.
        code: String,
        /// The failure, in the harness's own words.
        message: String,
    },
    /// A frame the neutral vocabulary above cannot represent, passed through
    /// verbatim.
    ///
    /// The adapter's own rule — nothing is ever silently dropped — reaching this
    /// surface. A console renders what it knows and ignores the rest; an
    /// operator reconstructing what an agent actually did still has every frame.
    Raw {
        /// The turn it belongs to, when it belongs to one.
        turn_id: Option<String>,
        /// Where the frame came from, as the adapter labelled it.
        source: String,
        /// The frame, verbatim.
        #[ts(type = "unknown")]
        value: serde_json::Value,
    },
    /// The session's state changed.
    State {
        /// The state it changed to.
        state: AssistantSessionState,
        /// Why — `process_exited`, `deleted`,
        /// `resume_refused: loadSession not advertised`, `load_failed: …`.
        /// `None` when nothing decided it.
        reason: Option<String>,
    },
    /// The session is over; nothing further will arrive on this stream.
    Ended {
        /// Why it ended.
        reason: String,
    },
}

impl AssistantSessionEvent {
    /// The turn this event belongs to, when it belongs to one.
    ///
    /// `State` and `Ended` are session-wide and belong to no turn; saying so
    /// with `None` is what keeps a caller from inventing an attribution.
    #[must_use]
    pub fn turn_id(&self) -> Option<&str> {
        match self {
            Self::Request { turn_id, .. }
            | Self::TurnStarted { turn_id, .. }
            | Self::Delta { turn_id, .. }
            | Self::Thought { turn_id, .. }
            | Self::ToolCall { turn_id, .. }
            | Self::PermissionAsk { turn_id, .. }
            | Self::TurnCompleted { turn_id, .. }
            | Self::TurnFailed { turn_id, .. } => Some(turn_id),
            Self::Raw { turn_id, .. } => turn_id.as_deref(),
            Self::SessionOpened { .. }
            | Self::ContextShared { .. }
            | Self::AvailableCommands { .. }
            | Self::ConfigOptions { .. }
            | Self::DocumentEdit { .. }
            | Self::State { .. }
            | Self::Ended { .. } => None,
        }
    }

    /// The state and cause this record SETTLES the session to, if it settles it
    /// at all.
    ///
    /// The lifecycle projection is exactly "the last record for which this
    /// returns `Some`, unless a process is running". A record that decides
    /// nothing returns `None`, which is what lets the scan walk backwards and
    /// stop at the first decision it meets.
    #[must_use]
    pub fn settles(&self) -> Option<(AssistantSessionState, Option<String>)> {
        match self {
            Self::State { state, reason } if !state.is_live() => Some((*state, reason.clone())),
            Self::Ended { reason } => Some((AssistantSessionState::Ended, Some(reason.clone()))),
            _ => None,
        }
    }
}

/// One event with the durable index the store assigned it.
///
/// The index is what a reconnecting client passes back as `?after=`, so it is on
/// every frame rather than only on replayed ones: a client that watched live and
/// then dropped its socket must be able to resume from what it last saw without
/// having read the transcript endpoint first.
#[derive(Serialize, Deserialize, ts_rs::TS, Clone, Debug, PartialEq, Eq)]
pub struct AssistantSessionFrame {
    /// The event's dense, store-assigned position in the session's transcript.
    pub index: u64,
    /// The event itself, flattened so the frame reads as one object.
    #[serde(flatten)]
    #[ts(flatten)]
    pub event: AssistantSessionEvent,
}

/// Everything a session's transcript says about it.
///
/// The one place the projection rules live, so the list surface, the detail
/// surface, the resume decision and the `assistant_context` tool all read the
/// same facts off the same records. Nothing here reads a stored status: there
/// is none.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AssistantSessionProjection {
    /// The last state a record settled the session to, with its cause. `None`
    /// when no record has settled it — which, for a session with no running
    /// process, is a transcript the boot sweep has not yet written back to.
    pub settled: Option<(AssistantSessionState, Option<String>)>,
    /// The harness's own session handle from the most recent open.
    pub acp_session_ref: Option<String>,
    /// Whether the agent advertised `loadSession` at its most recent open.
    /// `false` until an open has been recorded: a session that never opened
    /// cannot be resumed either.
    pub load_session: bool,
    /// How many turns have started.
    pub turns: u64,
    /// What the operator typed on the first turn — the fallback title.
    pub first_turn_text: Option<String>,
    /// The turn a `Request` opened that no `TurnCompleted`/`TurnFailed` has
    /// closed yet. `None` when every asked turn has been answered.
    ///
    /// This is how a settle path knows there is a turn to close: a session
    /// whose process died mid-turn must have that turn FAILED on the record
    /// before the session settles, or every reader of the transcript folds an
    /// open turn forever — the console reads it as busy, and a later edit
    /// batch would be attributed to a turn that ended long ago.
    pub open_turn_id: Option<String>,
    /// The most recently shared on-screen context.
    pub latest_context: Option<AssistantTurnContext>,
    /// The shared document's revision: how many edit batches have folded into
    /// `latest_context`. Monotonic and never reset — a fresh context share
    /// rebases the text but does not rewind the count — so a client can use it
    /// as an idempotency guard when replaying frames.
    pub document_revision: u64,
    /// The commands the harness advertised most recently. A later advertisement
    /// REPLACES an earlier one whole, as ACP's own update does.
    pub commands: Vec<AssistantCommand>,

    /// The configuration options the harness advertised most recently. The
    /// same replacement rule as `commands`, for the same reason.
    pub config_options: Vec<AssistantConfigOption>,
}

impl AssistantSessionProjection {
    /// Project a whole transcript, oldest event first.
    #[must_use]
    pub fn of<'events>(events: impl IntoIterator<Item = &'events AssistantSessionEvent>) -> Self {
        let mut projection = Self::default();
        for event in events {
            projection.apply(event);
        }
        projection
    }

    /// Fold one event in, in transcript order.
    fn apply(&mut self, event: &AssistantSessionEvent) {
        match event {
            AssistantSessionEvent::SessionOpened {
                acp_session_ref,
                load_session,
                ..
            } => {
                self.acp_session_ref = Some(acp_session_ref.clone());
                self.load_session = *load_session;
                // An open un-settles the session: a process is running again —
                // unless the session has ENDED, which is terminal. An open
                // recorded after an ended record is a resurrection the server
                // refuses at the door; a transcript that carries one anyway
                // (written before that refusal existed) still reads `ended`.
                if !self.is_ended() {
                    self.settled = None;
                }
            }
            AssistantSessionEvent::ContextShared { context, .. } => {
                self.latest_context = Some(context.clone());
            }
            AssistantSessionEvent::AvailableCommands { commands } => {
                // REPLACED, not merged: the agent's advertisement is complete,
                // and a merge would keep offering a command it has dropped.
                self.commands.clone_from(commands);
            }
            AssistantSessionEvent::ConfigOptions { options } => {
                // REPLACED, not merged — see `AvailableCommands` above.
                self.config_options.clone_from(options);
            }
            // The REQUEST is what counts a turn, not the start: it is appended
            // at acceptance and carries the operator's own words, so a turn that
            // was accepted and then failed to reach the agent is still a turn
            // that was asked.
            AssistantSessionEvent::Request {
                turn_id,
                text,
                context,
                ..
            } => {
                self.turns = self.turns.saturating_add(1);
                self.open_turn_id = Some(turn_id.clone());
                if self.first_turn_text.is_none() {
                    self.first_turn_text = Some(text.clone());
                }
                if let Some(context) = context {
                    self.latest_context = Some(context.clone());
                }
            }
            AssistantSessionEvent::TurnCompleted { turn_id, .. }
            | AssistantSessionEvent::TurnFailed { turn_id, .. } => {
                if self.open_turn_id.as_deref() == Some(turn_id.as_str()) {
                    self.open_turn_id = None;
                }
                if let Some(settled) = event.settles() {
                    self.settle_to(settled);
                }
            }
            AssistantSessionEvent::DocumentEdit { edits, revision } => {
                // `max`, not assignment: revisions are minted monotonically at
                // append, so on an in-order transcript this IS assignment — the
                // `max` only guards the fold against a stream a caller hands it
                // out of order, where a rewind would break every client using
                // the revision as an idempotency cursor.
                self.document_revision = self.document_revision.max(*revision);
                if let Some(document) = self
                    .latest_context
                    .as_mut()
                    .and_then(|context| context.document.as_mut())
                {
                    match apply_document_edits(&document.text, edits) {
                        Ok(applied) => document.text = applied,
                        // Reachable, and benign. The append path validated this
                        // batch against the projection AS IT THEN STOOD, but a
                        // `ContextShared` recorded between validation and this
                        // fold can rebase `latest_context` to bytes the batch
                        // no longer matches. The projection stays TOTAL — an
                        // unappliable batch leaves the text as it stands rather
                        // than poisoning the fold — and the very next context
                        // share carries the console's own buffer, edits
                        // included, so the folded document converges on the
                        // operator's truth rather than drifting from it.
                        Err(
                            AssistantDocumentEditError::EmptyOldString { .. }
                            | AssistantDocumentEditError::Absent { .. }
                            | AssistantDocumentEditError::Ambiguous { .. },
                        ) => {}
                    }
                }
            }
            other => {
                if let Some(settled) = other.settles() {
                    self.settle_to(settled);
                }
            }
        }
    }

    /// Whether the session has settled `ended`.
    #[must_use]
    pub fn is_ended(&self) -> bool {
        matches!(self.settled, Some((AssistantSessionState::Ended, _)))
    }

    /// Apply a settling record. Ended is absorbing: once a session has ended,
    /// a later record may restate `ended` (refreshing the cause) but can never
    /// move it to another state — the caller who put it down for good must be
    /// able to trust that it stays down.
    fn settle_to(&mut self, settled: (AssistantSessionState, Option<String>)) {
        if self.is_ended() && settled.0 != AssistantSessionState::Ended {
            return;
        }
        self.settled = Some(settled);
    }

    /// The state and cause to report, given whether a process is running.
    ///
    /// A running process ALWAYS wins: it is the one fact a transcript cannot
    /// contradict. With no process, the last settling record decides. With no
    /// process and no settling record — a state the boot sweep exists to
    /// prevent — the answer is [`AssistantSessionState::Ended`] with a cause
    /// that says exactly that, because a session with no process and no record
    /// of stopping must never be presented as running.
    #[must_use]
    pub fn state(
        &self,
        live: Option<AssistantSessionState>,
    ) -> (AssistantSessionState, Option<String>) {
        if let Some(state) = live
            && !self.is_ended()
        {
            return (state, None);
        }
        match &self.settled {
            Some((state, cause)) => (*state, cause.clone()),
            None => (
                AssistantSessionState::Ended,
                Some(NO_SETTLING_RECORD.to_owned()),
            ),
        }
    }

    /// Whether a dormant session can be reopened: it has a handle to load and
    /// the agent said it can load one.
    #[must_use]
    pub fn is_resumable(&self) -> bool {
        self.load_session && self.acp_session_ref.is_some()
    }

    /// The title a listing shows: the first 80 characters of the first turn's
    /// own text, when the caller named no title of their own.
    #[must_use]
    pub fn derived_title(&self) -> Option<String> {
        self.first_turn_text.as_ref().map(|text| {
            let trimmed = text.trim();
            trimmed.chars().take(TITLE_CHARACTERS).collect()
        })
    }
}

/// How many characters of the first prompt become a session's title.
pub const TITLE_CHARACTERS: usize = 80;

/// The cause reported for a session with no process and no record of stopping.
///
/// Reachable only if the boot sweep did not run or could not write; naming it
/// keeps that state distinguishable from a session that was genuinely closed.
pub const NO_SETTLING_RECORD: &str =
    "no process is running and the transcript records no stop; treated as ended";

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

    fn instant() -> Result<DateTime<Utc>, String> {
        use chrono::TimeZone;

        Utc.with_ymd_and_hms(2026, 8, 29, 6, 0, 0)
            .single()
            .ok_or_else(|| "the test instant must be valid".to_owned())
    }

    #[test]
    fn a_frame_carries_its_index_beside_the_event_discriminator() -> Result<(), String> {
        let frame = AssistantSessionFrame {
            index: 3,
            event: AssistantSessionEvent::Delta {
                turn_id: "t-1".to_owned(),
                text: "hello".to_owned(),
            },
        };
        let wire = serde_json::to_value(&frame).map_err(|error| error.to_string())?;
        assert_eq!(wire["index"], serde_json::json!(3));
        assert_eq!(wire["type"], serde_json::json!("delta"));
        assert_eq!(wire["turn_id"], serde_json::json!("t-1"));
        assert_eq!(wire["text"], serde_json::json!("hello"));
        Ok(())
    }

    #[test]
    fn every_event_shape_round_trips_through_its_wire_form() -> Result<(), String> {
        let events = vec![
            AssistantSessionEvent::SessionOpened {
                acp_session_ref: "sess-1".to_owned(),
                load_session: true,
                at: instant()?,
                resumed: false,
            },
            AssistantSessionEvent::ContextShared {
                context: AssistantTurnContext::default(),
                source: "turn".to_owned(),
            },
            AssistantSessionEvent::Request {
                turn_id: "t-1".to_owned(),
                text: "fix this".to_owned(),
                context: Some(AssistantTurnContext::default()),
                command: Some(AssistantCommandInvocation {
                    name: "compact".to_owned(),
                    input: Some("keep the plan".to_owned()),
                }),
            },
            AssistantSessionEvent::TurnStarted {
                turn_id: "t-1".to_owned(),
                at: instant()?,
                prompt: "On screen: /studio\n\nfix this".to_owned(),
            },
            AssistantSessionEvent::AvailableCommands {
                commands: vec![AssistantCommand {
                    name: "compact".to_owned(),
                    description: "compact the conversation".to_owned(),
                    input_hint: Some("what to keep".to_owned()),
                }],
            },
            AssistantSessionEvent::DocumentEdit {
                edits: vec![crate::assistant_document::AssistantDocumentEditOp {
                    old_string: "step one".to_owned(),
                    new_string: "step first".to_owned(),
                }],
                revision: 1,
            },
            AssistantSessionEvent::Delta {
                turn_id: "t-1".to_owned(),
                text: "part".to_owned(),
            },
            AssistantSessionEvent::Thought {
                turn_id: "t-1".to_owned(),
                text: "considering".to_owned(),
            },
            AssistantSessionEvent::ToolCall {
                turn_id: "t-1".to_owned(),
                call_id: "c-1".to_owned(),
                name: "check_document".to_owned(),
                status: AssistantToolCallStatus::Completed,
                input: Some(serde_json::json!({ "path": "a.awl" })),
                output: None,
            },
            AssistantSessionEvent::PermissionAsk {
                turn_id: "t-1".to_owned(),
                request: serde_json::json!({ "toolCall": { "toolCallId": "c-1" } }),
                decided: AssistantPermissionDecision::Deny,
            },
            AssistantSessionEvent::TurnCompleted {
                turn_id: "t-1".to_owned(),
                final_message: "done".to_owned(),
                stop_reason: "end_turn".to_owned(),
                session_ref: Some("sess-1".to_owned()),
            },
            AssistantSessionEvent::TurnFailed {
                turn_id: "t-2".to_owned(),
                code: "auth_required".to_owned(),
                message: "the agent requires authentication".to_owned(),
            },
            AssistantSessionEvent::State {
                state: AssistantSessionState::Dormant,
                reason: Some("process_exited".to_owned()),
            },
            AssistantSessionEvent::Ended {
                reason: "the operator closed the session".to_owned(),
            },
        ];
        for event in events {
            let bytes = serde_json::to_vec(&event).map_err(|error| error.to_string())?;
            let decoded: AssistantSessionEvent =
                serde_json::from_slice(&bytes).map_err(|error| error.to_string())?;
            assert_eq!(decoded, event);
        }
        Ok(())
    }

    #[test]
    fn a_session_id_parses_from_its_own_display_form() {
        let id = AssistantSessionId::new(Uuid::from_u128(7));
        assert_eq!(AssistantSessionId::parse(&id.to_string()), Ok(id));
        let error = AssistantSessionId::parse("not-a-uuid");
        assert!(
            matches!(&error, Err(failure) if failure.text == "not-a-uuid"),
            "a malformed id must be refused naming the text: {error:?}"
        );
    }

    #[test]
    fn only_a_running_process_is_live_and_a_dormant_session_is_still_continuable() {
        assert!(AssistantSessionState::Live.is_live());
        assert!(!AssistantSessionState::Dormant.is_live());
        assert!(!AssistantSessionState::Closed.is_live());
        assert!(!AssistantSessionState::Ended.is_live());
        // The distinction the whole resume path rests on: dormant is not
        // running and is not over.
        assert!(AssistantSessionState::Live.is_continuable());
        assert!(AssistantSessionState::Dormant.is_continuable());
        assert!(AssistantSessionState::Closed.is_continuable());
        assert!(!AssistantSessionState::Ended.is_continuable());

        // Closed is the one state that is continuable yet never current: the
        // whole point of the state is that putting a conversation away takes
        // it out of the operator's way without taking it away from them.
        assert!(AssistantSessionState::Live.is_current_candidate());
        assert!(AssistantSessionState::Dormant.is_current_candidate());
        assert!(!AssistantSessionState::Closed.is_current_candidate());
        assert!(!AssistantSessionState::Ended.is_current_candidate());
    }

    #[test]
    fn the_three_wire_states_spell_exactly_what_the_console_parses() {
        // A parser on the other side refuses anything but these three words, so
        // a renamed variant must fail HERE rather than at a running console.
        for (state, spelling) in [
            (AssistantSessionState::Live, "\"live\""),
            (AssistantSessionState::Dormant, "\"dormant\""),
            (AssistantSessionState::Closed, "\"closed\""),
            (AssistantSessionState::Ended, "\"ended\""),
        ] {
            assert_eq!(
                serde_json::to_string(&state).unwrap_or_default(),
                spelling,
                "{state:?} must spell {spelling} on the wire"
            );
        }
    }

    #[test]
    fn session_wide_events_belong_to_no_turn() {
        assert_eq!(
            AssistantSessionEvent::State {
                state: AssistantSessionState::Live,
                reason: None,
            }
            .turn_id(),
            None
        );
        assert_eq!(
            AssistantSessionEvent::Ended {
                reason: "stopped".to_owned(),
            }
            .turn_id(),
            None
        );
        assert_eq!(
            AssistantSessionEvent::Delta {
                turn_id: "t-9".to_owned(),
                text: String::new(),
            }
            .turn_id(),
            Some("t-9")
        );
    }

    fn opened(load_session: bool, resumed: bool) -> Result<AssistantSessionEvent, String> {
        Ok(AssistantSessionEvent::SessionOpened {
            acp_session_ref: "sess-1".to_owned(),
            load_session,
            at: instant()?,
            resumed,
        })
    }

    /// The frame a turn is ACCEPTED with — the record of what was asked, which
    /// is also what the projection counts and titles from.
    fn turn(text: &str) -> AssistantSessionEvent {
        AssistantSessionEvent::Request {
            turn_id: "t-1".to_owned(),
            text: text.to_owned(),
            context: None,
            command: None,
        }
    }

    #[test]
    fn a_running_process_wins_over_every_settling_record() -> Result<(), String> {
        let events = vec![
            opened(true, false)?,
            AssistantSessionEvent::State {
                state: AssistantSessionState::Dormant,
                reason: Some("process_exited".to_owned()),
            },
            opened(true, true)?,
        ];
        let projection = AssistantSessionProjection::of(&events);
        // The second open cleared the settlement: a reopened session is not
        // dormant because it once was.
        assert_eq!(projection.settled, None);
        assert_eq!(
            projection.state(Some(AssistantSessionState::Live)),
            (AssistantSessionState::Live, None)
        );
        Ok(())
    }

    #[test]
    fn with_no_process_the_last_settling_record_decides() -> Result<(), String> {
        let events = vec![
            opened(true, false)?,
            turn("fix the check"),
            AssistantSessionEvent::State {
                state: AssistantSessionState::Dormant,
                reason: Some("process_exited".to_owned()),
            },
        ];
        let projection = AssistantSessionProjection::of(&events);
        assert_eq!(
            projection.state(None),
            (
                AssistantSessionState::Dormant,
                Some("process_exited".to_owned())
            )
        );
        assert!(projection.is_resumable());
        assert_eq!(projection.turns, 1);
        assert_eq!(projection.derived_title(), Some("fix the check".to_owned()));
        Ok(())
    }

    #[test]
    fn an_agent_that_never_advertised_load_session_is_not_resumable() -> Result<(), String> {
        let projection = AssistantSessionProjection::of(&[opened(false, false)?]);
        assert!(
            !projection.is_resumable(),
            "resume is gated on what the agent ACTUALLY advertised"
        );
        Ok(())
    }

    #[test]
    fn no_process_and_no_settling_record_reads_ended_not_running() -> Result<(), String> {
        let projection = AssistantSessionProjection::of(&[opened(true, false)?, turn("hello")]);
        let (state, cause) = projection.state(None);
        assert_eq!(state, AssistantSessionState::Ended);
        assert_eq!(cause.as_deref(), Some(NO_SETTLING_RECORD));
        Ok(())
    }

    /// Ended is terminal, both directions: an open recorded after an ended
    /// record does not un-settle it, a later `live` state record does not
    /// replace it, and a live process reported beside it does not outrank it.
    /// The transcript this pins is real — a session the caller deleted before
    /// its first turn, whose turn then spawned an agent and wrote `live`.
    #[test]
    fn ended_is_absorbing_no_later_open_or_live_record_resurrects_it() -> Result<(), String> {
        let events = vec![
            AssistantSessionEvent::State {
                state: AssistantSessionState::Ended,
                reason: Some("deleted by the caller".to_owned()),
            },
            AssistantSessionEvent::Ended {
                reason: "deleted by the caller".to_owned(),
            },
            opened(true, false)?,
            AssistantSessionEvent::State {
                state: AssistantSessionState::Live,
                reason: None,
            },
            turn("hello"),
        ];
        let projection = AssistantSessionProjection::of(&events);
        assert!(
            projection.is_ended(),
            "an ended session stays ended: {projection:?}"
        );
        let (state, cause) = projection.state(None);
        assert_eq!(state, AssistantSessionState::Ended);
        assert_eq!(cause.as_deref(), Some("deleted by the caller"));
        let (state, _) = projection.state(Some(AssistantSessionState::Live));
        assert_eq!(
            state,
            AssistantSessionState::Ended,
            "a live process beside an ended record does not outrank it"
        );
        // Restating `ended` with a fresh cause is allowed: same state, newer word.
        let restated = AssistantSessionProjection::of(&[
            AssistantSessionEvent::State {
                state: AssistantSessionState::Ended,
                reason: Some("first".to_owned()),
            },
            AssistantSessionEvent::State {
                state: AssistantSessionState::Ended,
                reason: Some("second".to_owned()),
            },
        ]);
        assert_eq!(restated.state(None).1.as_deref(), Some("second"));
        Ok(())
    }

    #[test]
    fn the_latest_shared_context_is_the_one_the_tool_answers_with() {
        let first = AssistantTurnContext {
            url: Some("/studio".to_owned()),
            concepts: vec!["awl.step".to_owned()],
            document: None,
        };
        let second = AssistantTurnContext {
            url: Some("/runs".to_owned()),
            concepts: Vec::new(),
            document: None,
        };
        let events = vec![
            AssistantSessionEvent::ContextShared {
                context: first,
                source: "turn".to_owned(),
            },
            AssistantSessionEvent::ContextShared {
                context: second.clone(),
                source: "push".to_owned(),
            },
        ];
        assert_eq!(
            AssistantSessionProjection::of(&events).latest_context,
            Some(second)
        );
    }

    /// The console parses `request { turn_id, text, context }` by those exact
    /// names (`wire.ts:161`). A renamed field is a frame it drops, and a
    /// transcript with no request block claims nothing rather than being wrong —
    /// which is precisely why the drift has to fail HERE.
    #[test]
    fn a_request_frame_spells_what_the_console_parses() -> Result<(), String> {
        let wire = serde_json::to_value(AssistantSessionEvent::Request {
            turn_id: "t-7".to_owned(),
            text: "fix the check".to_owned(),
            context: Some(AssistantTurnContext {
                url: Some("/studio".to_owned()),
                concepts: vec!["awl.step".to_owned()],
                document: None,
            }),
            command: None,
        })
        .map_err(|error| error.to_string())?;
        assert_eq!(wire["type"], serde_json::json!("request"));
        assert_eq!(wire["turn_id"], serde_json::json!("t-7"));
        assert_eq!(wire["text"], serde_json::json!("fix the check"));
        assert_eq!(wire["context"]["url"], serde_json::json!("/studio"));
        Ok(())
    }

    /// A later advertisement REPLACES an earlier one whole. A merge would keep
    /// offering a command the agent has dropped, and the turn invoking it would
    /// be refused by the agent instead of by the surface that offered it.
    #[test]
    fn a_later_command_advertisement_replaces_the_earlier_one_whole() {
        let command = |name: &str| AssistantCommand {
            name: name.to_owned(),
            description: format!("{name} does something"),
            input_hint: None,
        };
        let events = vec![
            AssistantSessionEvent::AvailableCommands {
                commands: vec![command("compact"), command("plan")],
            },
            AssistantSessionEvent::AvailableCommands {
                commands: vec![command("compact")],
            },
        ];
        let projection = AssistantSessionProjection::of(&events);
        assert_eq!(
            projection
                .commands
                .iter()
                .map(|entry| entry.name.as_str())
                .collect::<Vec<_>>(),
            vec!["compact"],
            "`plan` was withdrawn and must not survive as an offer"
        );
    }

    /// The exact rule `commands` follows, pinned separately for options: a
    /// later advertisement replaces the earlier one whole.
    #[test]
    fn a_later_config_advertisement_replaces_the_earlier_one_whole() {
        let option = |id: &str| AssistantConfigOption {
            id: id.to_owned(),
            name: id.to_owned(),
            description: None,
            category: Some("model".to_owned()),
            value: AssistantConfigValue::Select {
                choices: vec![AssistantConfigChoice {
                    id: "opus".to_owned(),
                    name: "Opus".to_owned(),
                    description: None,
                    group: None,
                }],
                current: "opus".to_owned(),
            },
        };
        let events = vec![
            AssistantSessionEvent::ConfigOptions {
                options: vec![option("model"), option("thinking")],
            },
            AssistantSessionEvent::ConfigOptions {
                options: vec![option("model")],
            },
        ];
        let projection = AssistantSessionProjection::of(&events);
        assert_eq!(
            projection
                .config_options
                .iter()
                .map(|entry| entry.id.as_str())
                .collect::<Vec<_>>(),
            vec!["model"],
            "`thinking` was withdrawn and must not survive as an offer"
        );
    }

    /// The frame's wire tag and field shape, pinned where every other frame's
    /// is: the console parses this by hand, so the tag is a published contract.
    #[test]
    fn a_config_options_frame_serialises_under_its_published_tag() -> Result<(), String> {
        let wire = serde_json::to_value(AssistantSessionEvent::ConfigOptions {
            options: vec![AssistantConfigOption {
                id: "model".to_owned(),
                name: "Model".to_owned(),
                description: None,
                category: Some("model".to_owned()),
                value: AssistantConfigValue::Select {
                    choices: vec![AssistantConfigChoice {
                        id: "opus".to_owned(),
                        name: "Opus".to_owned(),
                        description: Some("the main one".to_owned()),
                        group: None,
                    }],
                    current: "opus".to_owned(),
                },
            }],
        })
        .map_err(|error| error.to_string())?;
        assert_eq!(wire["type"], serde_json::json!("config_options"));
        assert_eq!(wire["options"][0]["id"], serde_json::json!("model"));
        assert_eq!(wire["options"][0]["category"], serde_json::json!("model"));
        assert_eq!(
            wire["options"][0]["value"]["kind"],
            serde_json::json!("select")
        );
        assert_eq!(
            wire["options"][0]["value"]["current"],
            serde_json::json!("opus")
        );
        assert_eq!(
            wire["options"][0]["value"]["choices"][0]["name"],
            serde_json::json!("Opus")
        );
        Ok(())
    }

    /// A session nobody has advertised commands on offers none — the negative
    /// control for the cell above, which an always-populated list would pass.
    #[test]
    fn a_session_with_no_advertisement_offers_no_commands() {
        assert!(
            AssistantSessionProjection::default().commands.is_empty(),
            "a command list must come from the agent, never from this server"
        );
    }

    /// ACP delivers a command as ordinary prompt text: `/name` and the input
    /// after it. One spelling, here, so the turn path and the wire pins cannot
    /// disagree about the form the agent actually receives.
    #[test]
    fn a_command_is_delivered_as_the_slash_line_the_acp_spec_describes() {
        assert_eq!(
            AssistantCommandInvocation {
                name: "compact".to_owned(),
                input: Some("keep the plan".to_owned()),
            }
            .prompt_line(),
            "/compact keep the plan"
        );
        assert_eq!(
            AssistantCommandInvocation {
                name: "compact".to_owned(),
                input: None,
            }
            .prompt_line(),
            "/compact"
        );
        // Whitespace-only input is no input: a trailing space on the wire must
        // not become a trailing space in what the agent parses.
        assert_eq!(
            AssistantCommandInvocation {
                name: "compact".to_owned(),
                input: Some("   ".to_owned()),
            }
            .prompt_line(),
            "/compact"
        );
    }

    /// A turn's context reaches the shared-context projection through the
    /// REQUEST frame, so a turn asked from a screen updates what the
    /// `assistant_context` tool answers with without a second record.
    #[test]
    fn a_turns_own_context_becomes_the_shared_context() {
        let context = AssistantTurnContext {
            url: Some("/studio/a.awl".to_owned()),
            concepts: Vec::new(),
            document: None,
        };
        let projection = AssistantSessionProjection::of(&[AssistantSessionEvent::Request {
            turn_id: "t-1".to_owned(),
            text: "explain".to_owned(),
            context: Some(context.clone()),
            command: None,
        }]);
        assert_eq!(projection.latest_context, Some(context));
        assert_eq!(projection.turns, 1);
    }

    #[test]
    fn a_title_is_bounded_at_eighty_characters() -> Result<(), String> {
        let long = "x".repeat(200);
        let projection = AssistantSessionProjection::of(&[turn(&long)]);
        let title = projection
            .derived_title()
            .ok_or_else(|| "a started turn has a derivable title".to_owned())?;
        assert_eq!(title.chars().count(), TITLE_CHARACTERS);
        Ok(())
    }

    /// A `Request` opens a turn and only ITS `TurnCompleted`/`TurnFailed`
    /// closes it — this is what a settle path reads to know a dying process
    /// leaves a question on the record that will never be answered.
    #[test]
    fn a_request_opens_a_turn_and_its_ending_closes_it() {
        let mut projection = AssistantSessionProjection::of(&[turn("first ask")]);
        assert_eq!(projection.open_turn_id.as_deref(), Some("t-1"));
        // An ending for a DIFFERENT turn does not close this one.
        projection.apply(&AssistantSessionEvent::TurnFailed {
            turn_id: "t-0".to_owned(),
            code: "stale".to_owned(),
            message: "an earlier turn's ending arrives late".to_owned(),
        });
        assert_eq!(projection.open_turn_id.as_deref(), Some("t-1"));
        projection.apply(&AssistantSessionEvent::TurnCompleted {
            turn_id: "t-1".to_owned(),
            final_message: "answered".to_owned(),
            stop_reason: "end_turn".to_owned(),
            session_ref: None,
        });
        assert_eq!(projection.open_turn_id, None);
    }

    /// The projection folds a recorded edit batch into the shared document, so
    /// the agent's next `assistant_context` read sees its own edits — the
    /// transcript IS the shared document, with no second store to catch up.
    #[test]
    fn a_document_edit_folds_into_the_latest_context() {
        let events = vec![
            AssistantSessionEvent::ContextShared {
                context: AssistantTurnContext {
                    url: Some("/studio/pipeline.awl".to_owned()),
                    concepts: Vec::new(),
                    document: Some(AssistantDocumentContext {
                        path: "pipeline.awl".to_owned(),
                        text: "workflow demo\nstep one\n".to_owned(),
                        selection: None,
                        cursor: None,
                    }),
                },
                source: "turn".to_owned(),
            },
            AssistantSessionEvent::DocumentEdit {
                edits: vec![crate::assistant_document::AssistantDocumentEditOp {
                    old_string: "step one".to_owned(),
                    new_string: "step first".to_owned(),
                }],
                revision: 1,
            },
        ];
        let projection = AssistantSessionProjection::of(&events);
        assert_eq!(projection.document_revision, 1);
        let text = projection
            .latest_context
            .and_then(|context| context.document)
            .map(|document| document.text);
        assert_eq!(text, Some("workflow demo\nstep first\n".to_owned()));
    }

    /// An edit recorded with no shared document still advances the revision —
    /// the batch was appended, and a client's idempotency guard counts appended
    /// batches, not applicable ones — and the fold stays total rather than
    /// failing over a document that is not there.
    #[test]
    fn a_document_edit_with_no_shared_document_still_advances_the_revision() {
        let events = vec![AssistantSessionEvent::DocumentEdit {
            edits: vec![crate::assistant_document::AssistantDocumentEditOp {
                old_string: "anything".to_owned(),
                new_string: "else".to_owned(),
            }],
            revision: 1,
        }];
        let projection = AssistantSessionProjection::of(&events);
        assert_eq!(projection.document_revision, 1);
        assert_eq!(projection.latest_context, None);
    }

    /// The console parses `document_edit { edits, revision }` by those exact
    /// names. A renamed field is a frame the editor never applies, so the drift
    /// has to fail HERE.
    #[test]
    fn a_document_edit_frame_spells_what_the_console_parses() -> Result<(), String> {
        let wire = serde_json::to_value(AssistantSessionEvent::DocumentEdit {
            edits: vec![crate::assistant_document::AssistantDocumentEditOp {
                old_string: "a".to_owned(),
                new_string: "b".to_owned(),
            }],
            revision: 4,
        })
        .map_err(|error| error.to_string())?;
        assert_eq!(wire["type"], serde_json::json!("document_edit"));
        assert_eq!(wire["revision"], serde_json::json!(4));
        assert_eq!(wire["edits"][0]["old_string"], serde_json::json!("a"));
        assert_eq!(wire["edits"][0]["new_string"], serde_json::json!("b"));
        Ok(())
    }
}