polyc-facts 2026.10.2

Shared semantic-fold library: decode-to-fact functions reused by every consumer that reads the event log, so a payment receipt or a tool call means the same thing everywhere it's read.
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
//! `conversation-trace/v1` facts: one closed typed model for a conversation's
//! whole recorded history.
//!
//! # Why this is closed and typed
//!
//! The pre-cutover projector lived in the control plane and built
//! `serde_json::Value` for every step. That shape could carry any fact, which
//! meant nothing checked that it carried the RIGHT one: a malformed known
//! kind and an unknown kind produced the same untyped blob, a raw payload
//! could reach a column, and a reader could not tell a missing field from a
//! field that was never modelled.
//!
//! Here every step is one variant of [`TraceStepPayload`], every list is a
//! `Vec` of a typed item, every verdict and status is a closed enum, and the
//! only JSON that crosses this seam is a tool's own argument or result
//! document — the precedent `conversation-execution/v1` already set for
//! `arguments` and `result`.
//!
//! # Bounds run before allocation
//!
//! Every bound in [`polyc_projection::trace_vocabulary`] is checked on the
//! decoded value BEFORE the variant is built. A bound checked afterwards is
//! not a bound: the allocation already happened. Identifiers are never
//! truncated — a truncated identifier still looks like an identifier and
//! would name something else — so a value past [`MAX_ID_BYTES`] makes its row
//! malformed instead. Text and documents ARE truncated, at a character
//! boundary, with the row's `truncated` flag set.
//!
//! # What a malformed record becomes
//!
//! A known kind that does not decode stays a known kind. It yields a
//! `decode_failed` warning row at its position, and for a boundary kind it
//! still yields a [`TraceStepPayload::Boundary`] carrying the marker alone,
//! because a boundary's presence is structural and survives an unreadable
//! body. A malformed known kind NEVER becomes [`TraceStepPayload::Unknown`]
//! or [`TraceStepPayload::Marker`]; conflating the two would report a schema
//! gap where there is a corrupt record.
//!
//! # No committed-turn gate
//!
//! Unlike `conversation-core/v1` and `conversation-security/v1`, this family
//! folds every position, committed or not. The trace exists to show what
//! happened, including the turn that died mid-flight — gating it on
//! `turn_complete` would delete exactly the evidence an operator opens a
//! trace to find.

// The delegation family already names this vocabulary, and it is the same
// record: a handoff or its denial. A second enum with the same two variants
// would be a hand-written mirror of a closed set, which is the drift this
// design exists to remove.
mod fold;

pub use fold::fold_conversation_trace;

use crate::delegation_history::HandoffPhase;

use polyc_projection::trace_vocabulary::{
    MAX_DOCUMENT_BYTES, MAX_HASH_BYTES, MAX_ID_BYTES, MAX_LIST_ITEM_BYTES, MAX_LIST_ITEMS,
    MAX_TEXT_BYTES, MAX_WARNING_BYTES,
};

/// A bounded identifier: a turn id, tool-call id, name, or label.
///
/// Never truncated. [`TraceBoundsError::Identifier`] is what a value past the
/// bound produces, because a truncated identifier is a different identifier.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Hash)]
pub struct Id(String);

/// Bounded free text, truncated at a character boundary when it is too long.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Text {
    value: String,
    truncated: bool,
}

/// A tool's own argument or result document, as canonical JSON text.
///
/// The one JSON that crosses this seam, following
/// `conversation-execution/v1`'s accepted precedent. It is TEXT here, not a
/// `serde_json::Value`: the fact model carries what the tool recorded, and
/// re-parsing it would invite a reader to treat the document's shape as part
/// of the closed vocabulary when it is the tool's own.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ToolDocument {
    value: String,
    truncated: bool,
}

/// Why a value could not become a fact.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum TraceBoundsError {
    /// An identifier, name, or label exceeded its bound.
    #[error("`{field}` is longer than an identifier may be")]
    Identifier {
        /// The field that broke the bound.
        field: &'static str,
    },
    /// A list item exceeded its bound.
    #[error("an item of `{field}` is longer than a list item may be")]
    ListItem {
        /// The list that carried it.
        field: &'static str,
    },
    /// A hash or reference text exceeded its bound.
    #[error("`{field}` is longer than a hash may be")]
    Hash {
        /// The field that broke the bound.
        field: &'static str,
    },
}

impl Id {
    /// Builds one bounded identifier.
    ///
    /// # Errors
    ///
    /// Returns [`TraceBoundsError::Identifier`] when `value` exceeds
    /// [`MAX_ID_BYTES`]. The check runs on the borrowed input, so an
    /// over-long value is never copied into a fact.
    pub fn new(field: &'static str, value: &str) -> Result<Self, TraceBoundsError> {
        if value.len() > MAX_ID_BYTES {
            return Err(TraceBoundsError::Identifier { field });
        }
        Ok(Self(value.to_owned()))
    }

    /// Builds one bounded identifier, or the empty identifier for `None`.
    ///
    /// # Errors
    ///
    /// Returns [`TraceBoundsError::Identifier`] when a present value exceeds
    /// [`MAX_ID_BYTES`].
    pub fn optional(field: &'static str, value: Option<&str>) -> Result<Self, TraceBoundsError> {
        value.map_or_else(|| Ok(Self::default()), |value| Self::new(field, value))
    }

    /// Returns the identifier.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns true when this identifier names nothing.
    ///
    /// The empty value is how an absent identifier is stored: every artifact
    /// column is non-nullable, and an absent value holds its type's empty
    /// value rather than a null.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl Text {
    /// Builds bounded text, truncating at a character boundary.
    #[must_use]
    pub fn new(value: &str) -> Self {
        let (value, truncated) = truncate_at_char_boundary(value, MAX_TEXT_BYTES);
        Self { value, truncated }
    }

    /// Returns the text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.value
    }

    /// Returns true when the text was cut to fit its bound.
    #[must_use]
    pub const fn truncated(&self) -> bool {
        self.truncated
    }

    /// Returns true when the text is empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.value.is_empty()
    }
}

impl ToolDocument {
    /// Builds one bounded tool document, truncating at a character boundary.
    #[must_use]
    pub fn new(value: &str) -> Self {
        let (value, truncated) = truncate_at_char_boundary(value, MAX_DOCUMENT_BYTES);
        Self { value, truncated }
    }

    /// Returns the document text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.value
    }

    /// Returns true when the document was cut to fit its bound.
    #[must_use]
    pub const fn truncated(&self) -> bool {
        self.truncated
    }
}

/// Builds a bounded hash or reference text.
///
/// # Errors
///
/// Returns [`TraceBoundsError::Hash`] when `value` exceeds
/// [`MAX_HASH_BYTES`]. A hash is an identifier of content; truncating one
/// would name different content.
pub fn bounded_hash(field: &'static str, value: &str) -> Result<Id, TraceBoundsError> {
    if value.len() > MAX_HASH_BYTES {
        return Err(TraceBoundsError::Hash { field });
    }
    Ok(Id(value.to_owned()))
}

/// Builds a bounded list of identifiers.
///
/// Returns the clipped list and whether anything was dropped. The caller
/// emits a `list_clipped` warning row when the flag is set, so a clipped
/// list is visible rather than silently short.
///
/// # Errors
///
/// Returns [`TraceBoundsError::ListItem`] when any RETAINED item exceeds
/// [`MAX_LIST_ITEM_BYTES`]. Items past the count bound are never inspected,
/// because they are never carried.
pub fn bounded_id_list(
    field: &'static str,
    values: impl IntoIterator<Item = String>,
) -> Result<(Vec<Id>, bool), TraceBoundsError> {
    let mut out = Vec::new();
    let mut clipped = false;
    for value in values {
        if out.len() >= MAX_LIST_ITEMS {
            clipped = true;
            break;
        }
        if value.len() > MAX_LIST_ITEM_BYTES {
            return Err(TraceBoundsError::ListItem { field });
        }
        out.push(Id(value));
    }
    Ok((out, clipped))
}

/// Truncates `value` to at most `limit` bytes on a character boundary.
fn truncate_at_char_boundary(value: &str, limit: usize) -> (String, bool) {
    if value.len() <= limit {
        return (value.to_owned(), false);
    }
    let mut end = limit;
    while end > 0 && !value.is_char_boundary(end) {
        end -= 1;
    }
    (value[..end].to_owned(), true)
}

/// Bounded warning text.
#[must_use]
pub fn bounded_warning(value: &str) -> String {
    truncate_at_char_boundary(value, MAX_WARNING_BYTES).0
}

/// Which boundary a [`TraceStepPayload::Boundary`] records.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoundaryMarker {
    /// `turn_start`.
    Start,
    /// `turn_dispatched`.
    Dispatched,
    /// `turn_complete`.
    Complete,
    /// `turn_failed`.
    Failed,
    /// `turn_ambiguous`: the writer recorded that it does not know.
    Ambiguous,
    /// `step_commit`.
    StepCommit,
    /// `turn_text_withheld`.
    TextWithheld,
    /// `ingress_directive`.
    IngressDirective,
}

/// The three audience labels a dispatch records.
///
/// Three labels, not one choice among three. The writer records what the
/// audience WAS, where that came from, and what the edge asserted, and the
/// three can disagree — which is the whole reason all three are kept. A
/// single field would have to pick one and silently drop the disagreement.
///
/// Each is rendered through `polyc_proto::audience_display`, the same shared
/// labels the `turn_dispatch` table uses, so one record reads as one word on
/// both surfaces.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct AudienceView {
    /// The audience as recorded on the dispatch.
    pub recorded: Id,
    /// Where the recorded audience came from.
    pub source: Id,
    /// The audience the edge asserted.
    pub edge_asserted: Id,
}

/// Which side of a conversation a message came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageRole {
    /// A user input message.
    Input,
    /// A model output message.
    Output,
}

/// Where a tool call rests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolStatus {
    /// An approval denied it.
    Denied,
    /// It waits on an approval.
    WaitingApproval,
    /// It waits on a question answer.
    WaitingQuestion,
    /// It has a recorded result.
    Completed,
    /// It has no recorded result and waits on nothing.
    MissingResult,
    /// Its state cannot be derived.
    Unknown,
}

/// Which side of an approval a row records.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalPhase {
    /// `approval_request`.
    Request,
    /// `approval_response`.
    Response,
    /// `approval_deferred`.
    Deferred,
}

/// What an approval decided.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalDecision {
    /// No response yet.
    Pending,
    /// Approved.
    Approved,
    /// Denied.
    Denied,
    /// Deferred.
    Deferred,
}

/// Which side of a question a row records.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QuestionPhase {
    /// `question_request`.
    Request,
    /// `question_response`.
    Response,
}

/// What a question answer decided.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum QuestionDecision {
    /// No answer yet.
    Pending,
    /// Answered.
    Answered,
    /// Declined.
    Declined,
    /// Resolved without a person answering.
    AutoResolved,
    /// A decision the writer recorded under a label this build does not
    /// model. Kept rather than collapsed, so an unmodelled decision is
    /// visible as itself instead of reading as `Pending`.
    Other(Id),
}

/// Which subagent record a row carries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubagentPhase {
    /// `subagent_spawn`.
    Spawn,
    /// `subagent_result`.
    Result,
    /// `subagent_model_call`.
    ModelCall,
}

/// Which way a payment moved.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaymentDirection {
    /// A receipt for money received.
    Inbound,
    /// A receipt for money sent.
    Outbound,
}

/// A signature verdict for a role-signed record.
///
/// `LegacyUnverifiable` is approval-only: a pre-binding record this build can
/// no longer re-verify. It is not a tamper signal, and collapsing it into
/// `Invalid` would report tampering that did not happen.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RoleVerdict {
    /// Signed by a key in the pinned trust set.
    Verified,
    /// Signature present and wrong.
    Invalid,
    /// Signature present, signer outside the pinned trust set.
    Untrusted,
    /// A record this build cannot re-verify.
    LegacyUnverifiable,
}

/// A conversation-level marker with no payload of its own.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MarkerKind {
    /// `incognito_set`.
    IncognitoSet,
    /// `conversation_multiparty_floor`.
    MultipartyFloor,
    /// `admission_refused`.
    AdmissionRefused,
    /// `tool_input_rewrite`.
    ToolInputRewrite,
    /// `tool_context_injection`.
    ToolContextInjection,
    /// `tool_result_redaction`.
    ToolResultRedaction,
    /// `caller`.
    Caller,
    /// `participant`.
    Participant,
    /// `enrollment`.
    Enrollment,
    /// `routine_grant`.
    RoutineGrant,
    /// `grant_revocation`.
    GrantRevocation,
    /// `grant_suspension`.
    GrantSuspension,
    /// `nudge_sent`.
    NudgeSent,
    /// `taint_excision`.
    TaintExcision,
    /// `conversation_namespace`.
    ConversationNamespace,
    /// `namespace_refused`.
    NamespaceRefused,
}

/// Where a turn rests.
///
/// `Quarantined` is new in this family: a turn that recorded an ambiguous
/// outcome and never completed. It ranks above `OrphanedDispatch` because a
/// recorded ambiguity is a stronger statement than a missing completion — the
/// writer said it does not know, rather than saying nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TurnStatus {
    /// A `turn_failed` marker.
    Failed,
    /// A `turn_ambiguous` marker with no completion.
    Quarantined,
    /// Dispatched and never completed.
    OrphanedDispatch,
    /// Waiting on an approval.
    WaitingApproval,
    /// Waiting on a question answer.
    WaitingQuestion,
    /// Completed.
    Complete,
    /// No marker derives a status.
    Unknown,
}

/// What went wrong in a turn.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FailureKind {
    /// The turn recorded a failure.
    TurnFailed,
    /// The turn recorded an ambiguous outcome and never completed.
    Quarantined,
    /// The turn dispatched and never completed.
    OrphanedDispatch,
    /// An approval is still open.
    WaitingApproval,
    /// A question is still open.
    WaitingQuestion,
    /// An approval denied a call.
    DeniedApproval,
    /// A subagent reported failure.
    SubagentFailed,
    /// A tool call has no result.
    MissingResult,
    /// A payment attempt has no matching receipt.
    PaymentAttemptUnsettled,
    /// A tool result asked for a wallet link.
    WalletLinkNeeded,
}

/// Why the fold could not represent something faithfully.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WarningCode {
    /// A known kind did not decode.
    DecodeFailed,
    /// A verified-only record failed its signature check and was dropped.
    SignatureUnverified,
    /// A kind outside the closed registry.
    UnknownKind,
    /// A list was clipped to its bound.
    ListClipped,
    /// A payment step could not be attached to a turn.
    UnresolvedPayment,
}

/// One step's typed payload.
///
/// Closed: nineteen variants, one per [`polyc_projection::trace_vocabulary::STEP_KINDS`]
/// label. `Excised` and `Unknown` are spine-only — they name a position and
/// carry no payload table row, which is what keeps an excised body and an
/// unmodelled payload out of the artifact entirely.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TraceStepPayload {
    /// A turn boundary marker.
    Boundary {
        /// Which boundary this is.
        marker: BoundaryMarker,
        /// The audience view a dispatch recorded.
        audience: Option<AudienceView>,
        /// The turn a dispatch names as its source.
        source_turn_id: Option<Id>,
        /// The failure label a `turn_failed` carries.
        failed_kind: Option<Id>,
        /// The failure message a `turn_failed` carries.
        failed_message: Option<Text>,
    },
    /// A user input or model output message shell.
    Message {
        /// Which side sent it.
        role: MessageRole,
        /// The message text.
        text: Text,
        /// The tool calls this message carried.
        tool_call_ids: Vec<Id>,
        /// Whether the message is internal-only.
        internal_only: bool,
    },
    /// One tool call inside a message.
    ToolCall {
        /// The call's own id.
        tool_call_id: Id,
        /// The tool's name.
        name: Id,
        /// The call's argument document.
        arguments: ToolDocument,
        /// Where the call rests.
        status: ToolStatus,
        /// The turn the call was made in.
        origin_turn_id: Id,
        /// The turn its result arrived in.
        result_turn_id: Option<Id>,
        /// Whether the call is internal-only.
        internal_only: bool,
    },
    /// One tool result inside a message.
    ToolResult {
        /// The call this result answers.
        tool_call_id: Id,
        /// The tool's name.
        name: Id,
        /// The result document.
        result: ToolDocument,
        /// Whether the tool is first party.
        first_party: bool,
        /// Whether the result asked for a wallet link.
        needs_wallet_link: bool,
        /// Whether the result is internal-only.
        internal_only: bool,
    },
    /// One side of an approval.
    Approval {
        /// Which side.
        phase: ApprovalPhase,
        /// The occurrence this belongs to.
        request_id: Id,
        /// The tool the approval covers.
        tool_name: Option<Id>,
        /// The arguments the approval covers.
        args: Option<ToolDocument>,
        /// What was decided.
        decision: ApprovalDecision,
        /// The reason recorded with the decision.
        reason: Option<Text>,
        /// The signature verdict on a response.
        signature: Option<RoleVerdict>,
    },
    /// One side of a question.
    Question {
        /// Which side.
        phase: QuestionPhase,
        /// The call this question belongs to.
        call_id: Id,
        /// The question's index within its call.
        index: u32,
        /// The question header.
        header: Option<Text>,
        /// The question text.
        question: Option<Text>,
        /// The question's argument document.
        args: Option<ToolDocument>,
        /// What was decided.
        decision: QuestionDecision,
        /// The option index chosen.
        selected_index: Option<u32>,
        /// The option label chosen.
        selected_label: Option<Text>,
        /// Who answered.
        answered_by: Option<Id>,
        /// The signature verdict on an answer.
        verdict: Option<RoleVerdict>,
    },
    /// One subagent record.
    Subagent {
        /// Which record.
        phase: SubagentPhase,
        /// The subagent's own id.
        sub_agent_id: Id,
        /// The agent it targets.
        target_agent_id: Id,
        /// The task it was given.
        task: Option<Text>,
        /// The provider a model call used.
        provider: Option<Id>,
        /// The model a model call used.
        model: Option<Id>,
        /// Whether a result reported success.
        succeeded: Option<bool>,
        /// The error a result reported.
        error: Option<Text>,
        /// Input tokens a model call reported.
        input_tokens: Option<u64>,
        /// Output tokens a model call reported.
        output_tokens: Option<u64>,
        /// Whether the subagent is first party.
        first_party: Option<bool>,
        /// The signature verdict.
        verdict: Option<RoleVerdict>,
    },
    /// One delegation record.
    Handoff {
        /// Which record.
        phase: HandoffPhase,
        /// The child conversation a handoff created.
        child_conversation_id: Option<Id>,
        /// The agent the handoff targets.
        child_agent_id: Id,
        /// How many records were carried across.
        carried_count: u32,
        /// The reason recorded.
        reason: Text,
        /// The parent agent a denial names.
        parent_agent_id: Option<Id>,
        /// The reason a denial recorded.
        denial_reason: Option<Text>,
        /// The agents a denial says were allowed.
        allowed: Vec<Id>,
        /// The signature verdict.
        verdict: RoleVerdict,
    },
    /// An outbound payment attempt.
    PaymentAttempt {
        /// The approval position this attempt cites.
        approval_pos: Option<u64>,
        /// The call this attempt belongs to.
        tool_call_id: Id,
        /// The hash of the approved arguments.
        approved_args_hash: Id,
        /// The merchant URL.
        url: Text,
        /// The currency.
        currency: Id,
        /// The challenge amount.
        challenge_amount: Text,
        /// The challenge id.
        challenge_id: Id,
    },
    /// A verified payment receipt.
    PaymentReceipt {
        /// Which way the money moved.
        direction: PaymentDirection,
        /// The payment reference.
        reference: Id,
        /// The amount.
        amount: Text,
        /// The currency.
        currency: Id,
        /// The recipient.
        recipient: Text,
        /// The payment method.
        method: Id,
        /// The call this receipt belongs to.
        tool_call_id: Id,
        /// The approval position this receipt cites.
        approval_pos: Option<u64>,
        /// The hash of the approved arguments.
        approved_args_hash: Id,
        /// The principal the spend is attributed to.
        subject: Id,
        /// The receipt kind.
        kind: Id,
        /// Which kind of payer paid.
        payer_kind: Id,
        /// The account that paid.
        paying_account: Id,
    },
    /// A verified payment refusal.
    PaymentRefusal {
        /// Why it was refused.
        reason: Id,
        /// The detail recorded with the reason.
        reason_detail: Text,
        /// The merchant host.
        merchant_host: Text,
        /// What was requested, in base units.
        requested_base_units: u64,
        /// What was permitted, in base units.
        permitted_base_units: u64,
        /// The call this refusal belongs to.
        tool_call_id: Id,
        /// The principal the refusal is attributed to.
        subject: Id,
        /// When it was refused.
        timestamp: u64,
    },
    /// A verified wallet-link lifecycle record.
    WalletLink {
        /// Which transition.
        transition: Id,
        /// The principal the link belongs to.
        subject: Id,
        /// The wallet address.
        wallet_address: Id,
        /// The currency.
        currency: Id,
        /// The chain.
        chain_id: u64,
        /// The limit, in base units.
        limit_base_units: u64,
        /// The limit, rendered.
        limit_human: Text,
        /// The period the limit covers.
        period_secs: u64,
        /// When the link expires.
        expiry_unix: u64,
        /// The recipients the link permits.
        recipients: Vec<Id>,
        /// The conversation the link belongs to.
        conversation_id: Id,
        /// When it was recorded.
        timestamp: u64,
    },
    /// A grant replay audit record.
    GrantReplay {
        /// The tool the grant covered.
        tool: Id,
        /// The grant this replays.
        grant_ref: Id,
        /// The capabilities the grant covered.
        covered_capabilities: Vec<Id>,
        /// The hash over that coverage.
        coverage_hash: Id,
        /// The turn it belongs to.
        turn_id: Option<Id>,
        /// The signature verdict.
        verdict: RoleVerdict,
    },
    /// An edge-observed identity.
    Identity {
        /// The identity provider.
        provider: Id,
        /// The provider-local scope.
        scope: Id,
        /// The provider-local identifier.
        external_id: Id,
        /// The display name.
        display_name: Text,
        /// The persona it resolved to.
        persona_id: Id,
    },
    /// A conversation summary.
    Summary {
        /// The summary text.
        text: Text,
        /// The last position it covers.
        covers_through_position: u64,
    },
    /// A summary retention-gate record.
    SummaryGate {
        /// Whether the candidate was rejected.
        rejected: bool,
        /// The identifiers the gate named.
        dropped_identifiers: Vec<Id>,
        /// The count the record carries.
        count: u64,
    },
    /// A conversation-level marker.
    Marker {
        /// Which marker.
        marker: MarkerKind,
        /// The state an `incognito_set` recorded.
        on: Option<bool>,
        /// When a multiparty floor escalated.
        escalated_at_ms: Option<u64>,
    },
    /// A position a verified excision stripped.
    ///
    /// Carries the excision marker's own position and nothing else. The body
    /// is gone from the prepared prefix before this fold runs, which is the
    /// reason excision exists — an administrator sees WHERE and WHAT KIND was
    /// excised, never the text.
    ///
    /// The marker position is absent when the prefix was stripped by
    /// something that did not record which marker reached this position. The
    /// tombstone still names the position; only its attribution is missing,
    /// and an absent attribution is reported as an absent list row rather
    /// than as a zero that reads like position 0.
    Excised {
        /// The position of the marker that stripped it, when it is known.
        marker_position: Option<u64>,
    },
    /// A kind outside the closed registry.
    ///
    /// Carries no payload copy. An unmodelled payload is exactly the shape
    /// this family refuses to store, so the row records that a position held
    /// an unrecognised kind and stops there.
    Unknown,
}

impl TraceStepPayload {
    /// Returns the closed `step_kind` label for this payload.
    ///
    /// Exhaustive with no wildcard: a new variant does not compile until it
    /// names its label, and `scripts/check_trace_family.py` holds these
    /// labels against `polyc_projection::trace_vocabulary::STEP_KINDS`.
    #[must_use]
    pub const fn step_kind(&self) -> &'static str {
        match self {
            Self::Boundary { .. } => "boundary",
            Self::Message { .. } => "message",
            Self::ToolCall { .. } => "tool_call",
            Self::ToolResult { .. } => "tool_result",
            Self::Approval { .. } => "approval",
            Self::Question { .. } => "question",
            Self::Subagent { .. } => "subagent",
            Self::Handoff { .. } => "handoff",
            Self::PaymentAttempt { .. } => "payment_attempt",
            Self::PaymentReceipt { .. } => "payment_receipt",
            Self::PaymentRefusal { .. } => "payment_refusal",
            Self::WalletLink { .. } => "wallet_link",
            Self::GrantReplay { .. } => "grant_replay",
            Self::Identity { .. } => "identity",
            Self::Summary { .. } => "summary",
            Self::SummaryGate { .. } => "summary_gate",
            Self::Marker { .. } => "marker",
            Self::Excised { .. } => "excised",
            Self::Unknown => "unknown",
        }
    }

    /// Returns true when this payload has no table of its own.
    #[must_use]
    pub const fn is_spine_only(&self) -> bool {
        matches!(self, Self::Excised { .. } | Self::Unknown)
    }

    /// Returns true when this payload must not reach a visible segment.
    ///
    /// The visible realm omits internal-only rows. The flag lives on the
    /// three payloads a message can carry, because that is where the writer
    /// records it.
    #[must_use]
    pub const fn internal_only(&self) -> bool {
        match self {
            Self::Message { internal_only, .. }
            | Self::ToolCall { internal_only, .. }
            | Self::ToolResult { internal_only, .. } => *internal_only,
            _ => false,
        }
    }

    /// Whether any bounded value in this payload was cut to fit.
    ///
    /// The per-table rows carry their own truncation flags, and the spine
    /// row carries this one, so a reader scanning only the spine still sees
    /// that a step holds less than the writer wrote. It used to be the
    /// constant `false`, which told that reader the opposite.
    #[must_use]
    pub fn truncated(&self) -> bool {
        match self {
            Self::Message { text, .. } | Self::Summary { text, .. } => text.truncated(),
            Self::ToolCall { arguments, .. } => arguments.truncated(),
            Self::ToolResult { result, .. } => result.truncated(),
            Self::Approval { args, reason, .. } => {
                args.as_ref().is_some_and(ToolDocument::truncated)
                    || reason.as_ref().is_some_and(Text::truncated)
            }
            Self::Question {
                header,
                question,
                args,
                selected_label,
                ..
            } => {
                header.as_ref().is_some_and(Text::truncated)
                    || question.as_ref().is_some_and(Text::truncated)
                    || args.as_ref().is_some_and(ToolDocument::truncated)
                    || selected_label.as_ref().is_some_and(Text::truncated)
            }
            Self::Subagent { task, error, .. } => {
                task.as_ref().is_some_and(Text::truncated)
                    || error.as_ref().is_some_and(Text::truncated)
            }
            Self::Handoff { reason, .. } => reason.truncated(),
            Self::Boundary { failed_message, .. } => {
                failed_message.as_ref().is_some_and(Text::truncated)
            }
            Self::PaymentReceipt {
                amount, recipient, ..
            } => amount.truncated() || recipient.truncated(),
            Self::PaymentRefusal {
                reason_detail,
                merchant_host,
                ..
            } => reason_detail.truncated() || merchant_host.truncated(),
            Self::WalletLink { limit_human, .. } => limit_human.truncated(),
            Self::PaymentAttempt { .. }
            | Self::SummaryGate { .. }
            | Self::Identity { .. }
            | Self::GrantReplay { .. }
            | Self::Marker { .. }
            | Self::Excised { .. }
            | Self::Unknown => false,
        }
    }
}

/// One step, at its source position.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraceStepFact {
    /// The journal position that produced it.
    pub position: u64,
    /// Which step of that position this is.
    pub ordinal: u64,
    /// The turn it belongs to, empty when it is conversation-level.
    pub turn_id: Id,
    /// The kind base as recorded, for a reader that wants the source word.
    pub kind_base: Id,
    /// The trust tag the source carried.
    pub trust: Id,
    /// The typed payload.
    pub payload: TraceStepPayload,
}

/// What one turn's markers and model fields say about it.
///
/// The five marker booleans are the turn's own structural record: which
/// markers the writer actually wrote. `status` is derived FROM them, and
/// carrying both is deliberate — a reader that disagrees with the derivation
/// can see the markers it was derived from, which is what makes the status
/// checkable rather than asserted.
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "each boolean is one marker the writer either wrote or did not"
)]
pub struct TraceTurnFact {
    /// The turn's id.
    pub turn_id: Id,
    /// The first position that named it.
    pub first_position: u64,
    /// Where it rests.
    pub status: TurnStatus,
    /// A `turn_start` was recorded.
    pub has_start: bool,
    /// A `turn_dispatched` was recorded.
    pub has_dispatched: bool,
    /// A `turn_complete` was recorded.
    pub has_complete: bool,
    /// A `turn_failed` was recorded.
    pub has_failed: bool,
    /// A `turn_ambiguous` was recorded.
    pub has_ambiguous: bool,
    /// The failure label, when one was recorded.
    pub failed_kind: Id,
    /// The failure message, when one was recorded.
    pub failed_message: Text,
    /// The position the failure was recorded at.
    pub failed_position: Option<u64>,
    /// The provider the turn dispatched to.
    pub model_provider: Id,
    /// The model the turn dispatched to.
    pub model_name: Id,
    /// The system configuration the turn used.
    pub system_config_ref: Id,
    /// Temperature, in micro-units.
    ///
    /// The projection kernel has four logical types and none is a float, so
    /// a decode parameter is stored as micro-units and the response encoder
    /// restores the `f64`. Storing it as text would have made a number into
    /// a string between modules, which this family refuses.
    pub temperature_micros: Option<u64>,
    /// Top-p, in micro-units.
    pub top_p_micros: Option<u64>,
    /// The token ceiling the turn dispatched under.
    pub max_tokens: Option<u64>,
    /// The reasoning level the turn dispatched under.
    pub reasoning_level: Id,
    /// The clock the dispatch captured.
    pub dispatch_clock_ms: Option<u64>,
    /// Input tokens the turn used.
    pub usage_input: Option<u64>,
    /// Output tokens the turn used.
    pub usage_output: Option<u64>,
    /// The persona the turn is attributed to.
    pub caller_persona_id: Id,
    /// Whether the turn can be replanned.
    pub plannable: bool,
    /// The positions that evidence this turn.
    pub evidence_positions: Vec<u64>,
}

/// One ranked failure signal for a turn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraceFailureFact {
    /// The turn it belongs to.
    pub turn_id: Id,
    /// Its rank within that turn, from one.
    pub rank: u32,
    /// What went wrong.
    pub kind: FailureKind,
    /// The message a reader renders.
    pub message: Text,
    /// The positions that evidence it.
    pub evidence_positions: Vec<u64>,
    /// The identifiers it names.
    pub related_ids: Vec<Id>,
}

/// Something the fold could not represent faithfully.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraceWarningFact {
    /// The position it concerns, when it concerns one.
    pub position: Option<u64>,
    /// Which warning.
    pub code: WarningCode,
    /// The bounded message.
    pub message: String,
}

/// Every fact one conversation's prepared prefix folds to.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ConversationTraceFacts {
    /// The signer of every signature that verified, Fleet-only.
    pub signers: Vec<TraceSignerFact>,
    /// Every step, in `(position, ordinal)` order.
    pub steps: Vec<TraceStepFact>,
    /// Every turn, in first-appearance order.
    pub turns: Vec<TraceTurnFact>,
    /// Every ranked failure.
    pub failures: Vec<TraceFailureFact>,
    /// Everything the fold could not represent faithfully.
    pub warnings: Vec<TraceWarningFact>,
}

/// The trust sets the trace fold classifies signatures against.
///
/// Public keys only. The fold classifies a signature and never produces one,
/// so holding these confers no authority to sign anything.
///
/// Four roles, because four different writers sign four different records and
/// a single set would let one role's key vouch for another's record.
/// Every set is REQUIRED, none is optional. `RoleTrustSet` refuses to be
/// empty by construction, which is the right rule: a fold given an empty set
/// classifies every signature the same way and still publishes, signing a
/// history-wide misreading into an authoritative artifact. Absence is
/// represented by refusing to compose the family at all, not by an empty set
/// that reads as "trust nobody".
#[derive(Debug, Clone)]
pub struct TraceTrust {
    /// Approval-role public keys, for approval responses and the
    /// verified-only payment and wallet records.
    pub approval: Vec<Vec<u8>>,
    /// The handoff role's trust set.
    pub handoff: polyc_crypto::signing_role::RoleTrustSet<polyc_crypto::signing_role::HandoffRole>,
    /// The subagent role's trust set.
    pub subagent:
        polyc_crypto::signing_role::RoleTrustSet<polyc_crypto::signing_role::SubagentRole>,
    /// The question role's public keys.
    pub question: Vec<Vec<u8>>,
}

/// The signer of one signature that verified, for the Fleet-only table.
///
/// The raw key is here and nowhere else. Every visible payload carries the
/// VERDICT instead, which is what a reader needs to judge the record; the key
/// itself is administrator material and lives in one Fleet-only table.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraceSignerFact {
    /// The position of the step this signature belongs to.
    pub position: u64,
    /// The ordinal of that step at its position.
    pub ordinal: u64,
    /// The step kind, so the table reads without a join.
    pub step_kind: &'static str,
    /// Which signing role produced it.
    pub role: SignerRole,
    /// The signer's ed25519 public key.
    pub signer_key: [u8; 32],
}

/// The signing roles whose signer this family records.
///
/// Five, not seven. The handoff and subagent records are verified against
/// their role trust sets, but the shared folds that verify them return the
/// verdict and not the key, so this family has no key to record for them.
/// Declaring a role it never writes would leave a label with no writer,
/// which `scripts/check_trace_family.py` refuses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignerRole {
    /// An approval response.
    Approval,
    /// A question answer.
    Question,
    /// A grant replay.
    GrantReplay,
    /// A payment receipt or refusal.
    Payment,
    /// A wallet-link transition.
    WalletLink,
}

/// Why a trace generation was refused.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ConversationTraceError {
    /// Two records claimed the same source position.
    ///
    /// The same refusal every family raises. A repeated position means the
    /// prefix is not what it claims, and folding it would publish an
    /// ordering that does not exist.
    #[error("the source prefix repeats position {position}")]
    RepeatedPosition {
        /// The repeated position.
        position: u64,
    },
    /// A value exceeded a bound the family enforces.
    #[error("position {position}: {source}")]
    Bounds {
        /// Where it happened.
        position: u64,
        /// Which bound.
        source: TraceBoundsError,
    },
    /// One position produced more steps than the bound allows.
    #[error("position {position} produced more steps than the bound allows")]
    OrdinalOverflow {
        /// Where it happened.
        position: u64,
    },
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs, clippy::unwrap_used)]

    use super::*;
    use polyc_projection::trace_vocabulary::STEP_KINDS;
    use std::collections::BTreeSet;

    fn every_payload() -> Vec<TraceStepPayload> {
        vec![
            TraceStepPayload::Boundary {
                marker: BoundaryMarker::Start,
                audience: None,
                source_turn_id: None,
                failed_kind: None,
                failed_message: None,
            },
            TraceStepPayload::Message {
                role: MessageRole::Input,
                text: Text::new("hello"),
                tool_call_ids: Vec::new(),
                internal_only: false,
            },
            TraceStepPayload::ToolCall {
                tool_call_id: Id::new("tool_call_id", "call-1").unwrap(),
                name: Id::new("name", "read_file").unwrap(),
                arguments: ToolDocument::new("{}"),
                status: ToolStatus::Completed,
                origin_turn_id: Id::new("origin_turn_id", "turn-1").unwrap(),
                result_turn_id: None,
                internal_only: false,
            },
            TraceStepPayload::ToolResult {
                tool_call_id: Id::new("tool_call_id", "call-1").unwrap(),
                name: Id::new("name", "read_file").unwrap(),
                result: ToolDocument::new("{}"),
                first_party: true,
                needs_wallet_link: false,
                internal_only: false,
            },
            TraceStepPayload::Approval {
                phase: ApprovalPhase::Request,
                request_id: Id::new("request_id", "call-1").unwrap(),
                tool_name: None,
                args: None,
                decision: ApprovalDecision::Pending,
                reason: None,
                signature: None,
            },
            TraceStepPayload::Question {
                phase: QuestionPhase::Request,
                call_id: Id::new("call_id", "call-1").unwrap(),
                index: 0,
                header: None,
                question: None,
                args: None,
                decision: QuestionDecision::Pending,
                selected_index: None,
                selected_label: None,
                answered_by: None,
                verdict: None,
            },
            TraceStepPayload::Subagent {
                phase: SubagentPhase::Spawn,
                sub_agent_id: Id::new("sub_agent_id", "sub-1").unwrap(),
                target_agent_id: Id::new("target_agent_id", "researcher").unwrap(),
                task: None,
                provider: None,
                model: None,
                succeeded: None,
                error: None,
                input_tokens: None,
                output_tokens: None,
                first_party: None,
                verdict: None,
            },
            TraceStepPayload::Handoff {
                phase: HandoffPhase::Handoff,
                child_conversation_id: None,
                child_agent_id: Id::new("child_agent_id", "researcher").unwrap(),
                carried_count: 0,
                reason: Text::new("delegate"),
                parent_agent_id: None,
                denial_reason: None,
                allowed: Vec::new(),
                verdict: RoleVerdict::Verified,
            },
            TraceStepPayload::PaymentAttempt {
                approval_pos: None,
                tool_call_id: Id::new("tool_call_id", "call-1").unwrap(),
                approved_args_hash: Id::default(),
                url: Text::new("https://example.test"),
                currency: Id::new("currency", "USD").unwrap(),
                challenge_amount: Text::new("1.00"),
                challenge_id: Id::new("challenge_id", "ch-1").unwrap(),
            },
            TraceStepPayload::PaymentReceipt {
                direction: PaymentDirection::Outbound,
                reference: Id::new("reference", "ref-1").unwrap(),
                amount: Text::new("1.00"),
                currency: Id::new("currency", "USD").unwrap(),
                recipient: Text::new("merchant"),
                method: Id::new("method", "card").unwrap(),
                tool_call_id: Id::new("tool_call_id", "call-1").unwrap(),
                approval_pos: None,
                approved_args_hash: Id::default(),
                subject: Id::new("subject", "persona-1").unwrap(),
                kind: Id::new("kind", "settled").unwrap(),
                payer_kind: Id::new("payer_kind", "persona").unwrap(),
                paying_account: Id::new("paying_account", "acct-1").unwrap(),
            },
            TraceStepPayload::PaymentRefusal {
                reason: Id::new("reason", "over_limit").unwrap(),
                reason_detail: Text::new("above the period cap"),
                merchant_host: Text::new("example.test"),
                requested_base_units: 200,
                permitted_base_units: 100,
                tool_call_id: Id::new("tool_call_id", "call-1").unwrap(),
                subject: Id::new("subject", "persona-1").unwrap(),
                timestamp: 1,
            },
            TraceStepPayload::WalletLink {
                transition: Id::new("transition", "linked").unwrap(),
                subject: Id::new("subject", "persona-1").unwrap(),
                wallet_address: Id::new("wallet_address", "0xabc").unwrap(),
                currency: Id::new("currency", "USD").unwrap(),
                chain_id: 1,
                limit_base_units: 100,
                limit_human: Text::new("1.00"),
                period_secs: 86_400,
                expiry_unix: 0,
                recipients: Vec::new(),
                conversation_id: Id::new("conversation_id", "conv-1").unwrap(),
                timestamp: 1,
            },
            TraceStepPayload::GrantReplay {
                tool: Id::new("tool", "paid_fetch").unwrap(),
                grant_ref: Id::new("grant_ref", "grant-1").unwrap(),
                covered_capabilities: Vec::new(),
                coverage_hash: Id::default(),
                turn_id: None,
                verdict: RoleVerdict::Verified,
            },
            TraceStepPayload::Identity {
                provider: Id::new("provider", "chat").unwrap(),
                scope: Id::new("scope", "team-a").unwrap(),
                external_id: Id::new("external_id", "U-1").unwrap(),
                display_name: Text::new("Ada"),
                persona_id: Id::new("persona_id", "persona-1").unwrap(),
            },
            TraceStepPayload::Summary {
                text: Text::new("so far"),
                covers_through_position: 9,
            },
            TraceStepPayload::SummaryGate {
                rejected: true,
                dropped_identifiers: Vec::new(),
                count: 1,
            },
            TraceStepPayload::Marker {
                marker: MarkerKind::IncognitoSet,
                on: Some(true),
                escalated_at_ms: None,
            },
            TraceStepPayload::Excised {
                marker_position: Some(4),
            },
            TraceStepPayload::Unknown,
        ]
    }

    /// Every variant names a label the vocabulary declares, and every label
    /// has a variant.
    ///
    /// This is the seam the whole design rests on. `step_kind` is exhaustive,
    /// so a new variant does not compile until it names a label — but nothing
    /// makes the LABEL list and the variant list agree in the other
    /// direction, and a label with no variant is a fact the artifact can
    /// describe and the fold can never produce.
    #[test]
    fn every_step_kind_label_has_exactly_one_variant() {
        let produced: BTreeSet<&str> = every_payload()
            .iter()
            .map(TraceStepPayload::step_kind)
            .collect();
        let declared: BTreeSet<&str> = STEP_KINDS.iter().copied().collect();
        assert_eq!(
            produced, declared,
            "the payload variants and the closed label set disagree"
        );
        assert_eq!(
            every_payload().len(),
            STEP_KINDS.len(),
            "one variant per label, no variant sharing a label"
        );
    }

    /// The two spine-only variants are the two that carry no payload table.
    #[test]
    fn only_excised_and_unknown_are_spine_only() {
        for payload in every_payload() {
            let expected = matches!(
                payload,
                TraceStepPayload::Excised { .. } | TraceStepPayload::Unknown
            );
            assert_eq!(
                payload.is_spine_only(),
                expected,
                "`{}` disagrees about carrying a payload table",
                payload.step_kind()
            );
        }
    }

    /// An identifier past its bound is refused, never truncated.
    ///
    /// A truncated identifier still looks like an identifier and would name
    /// something else. The refusal is what keeps a bounded row honest.
    #[test]
    fn an_over_long_identifier_is_refused_rather_than_cut() {
        let long = "x".repeat(MAX_ID_BYTES + 1);
        assert_eq!(
            Id::new("turn_id", &long),
            Err(TraceBoundsError::Identifier { field: "turn_id" })
        );
        let exact = "x".repeat(MAX_ID_BYTES);
        assert_eq!(Id::new("turn_id", &exact).unwrap().as_str(), exact);
    }

    /// Text past its bound is cut at a character boundary and says so.
    #[test]
    fn over_long_text_is_cut_on_a_character_boundary_and_flagged() {
        // A multi-byte character straddling the cap must not be split.
        let text = Text::new(&"é".repeat(MAX_TEXT_BYTES));
        assert!(text.truncated(), "the text was over its bound");
        assert!(
            text.as_str().len() <= MAX_TEXT_BYTES,
            "the cut respects the bound"
        );
        assert!(
            std::str::from_utf8(text.as_str().as_bytes()).is_ok(),
            "the cut leaves valid UTF-8"
        );

        let short = Text::new("fits");
        assert!(!short.truncated());
        assert_eq!(short.as_str(), "fits");
    }

    /// A list past its count bound is clipped and says so; an item past its
    /// own bound refuses the row.
    #[test]
    fn a_list_clips_by_count_and_refuses_by_item() {
        let many = (0..MAX_LIST_ITEMS + 5).map(|i| i.to_string());
        let (items, clipped) = bounded_id_list("tool_call_ids", many).unwrap();
        assert_eq!(items.len(), MAX_LIST_ITEMS);
        assert!(clipped, "a clipped list reports that it was clipped");

        let over_item = vec!["x".repeat(MAX_LIST_ITEM_BYTES + 1)];
        assert_eq!(
            bounded_id_list("tool_call_ids", over_item),
            Err(TraceBoundsError::ListItem {
                field: "tool_call_ids"
            })
        );
    }

    /// An item past the count bound is never inspected.
    ///
    /// The clip happens before the item bound is checked, so an over-long
    /// item beyond the count bound cannot refuse a row it was never going to
    /// appear in. Bounds run before allocation, and this is the same rule one
    /// level down.
    #[test]
    fn an_item_past_the_count_bound_is_never_inspected() {
        let mut values: Vec<String> = (0..MAX_LIST_ITEMS).map(|i| i.to_string()).collect();
        values.push("x".repeat(MAX_LIST_ITEM_BYTES + 1));
        let (items, clipped) = bounded_id_list("allowed", values).unwrap();
        assert_eq!(items.len(), MAX_LIST_ITEMS);
        assert!(clipped);
    }

    /// Only the three message-carried payloads can be internal-only.
    #[test]
    fn internal_only_belongs_to_the_payloads_a_message_carries() {
        for payload in every_payload() {
            let can_be_internal = matches!(
                payload,
                TraceStepPayload::Message { .. }
                    | TraceStepPayload::ToolCall { .. }
                    | TraceStepPayload::ToolResult { .. }
            );
            if !can_be_internal {
                assert!(
                    !payload.internal_only(),
                    "`{}` must never claim to be internal-only",
                    payload.step_kind()
                );
            }
        }
    }
}