spoke-operations 0.18.1

SPOKE lifecycle helpers — pure functions over spoke-schemas wire types
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
//! Per-op request validators and pure policy predicates.
//!
//! Covers only the conditional wire rules the JSON-Schema codegen cannot
//! derive (draft-07 `if`/`then`/`else`), plus provider-limit-dependent
//! checks (`limit` vs `max_page_size`, content vs `max_content_bytes`) which
//! call sites parameterize from `memory.describe.limits` (§7.1):
//!
//! - list/recall page bounds (`limit ≥ 1` is type-enforced by
//!   `NonZeroU64`; the upper bound is provider-declared);
//! - `ReadSelection` / `ProvenanceFilter` conditional requirements (§6.12,
//!   §6.13) — non-empty `context_ids` / `source_context_ids` where the
//!   generated types allow programmatically-built empty vectors;
//! - `memory.subjects.fence` archive-on-context → `INVALID_INPUT` (§7.7);
//! - `memory.grants.grant` `capabilities` minItems/uniqueItems and
//!   restricted-shape `context_ids` minItems (§7.9);
//! - `memory.candidates.review` fragment minItems (§7.15);
//! - `memory.records.update` kind-update shape must not carry content (§7.18);
//! - `memory.imports.stage` header chunk ordinal must be 0 (§7.31);
//! - content byte limits for `memory.capture` / `memory.records.create` /
//!   `memory.records.update` (§7 limits; measured by [`content_serialized_bytes`]);
//! - the §8.2 freeze maintenance allowlist predicate.
//!
//! Everything else — idempotency-key presence and 1–128 shape on keyed
//! mutations (`subjects.ensure` exempt, §7.0.5), placement `context_id`
//! conditionality (§6.6), oneOf request shapes for `exports.create` /
//! `imports.stage` — is type-enforced by the generated types. Note
//! `minItems` / `uniqueItems` on plain `Vec<String>` fields are NOT enforced
//! for programmatically constructed values; validators re-check them where
//! the protocol requires (§7.9 `capabilities`, §6.12 `context_ids`, §6.13
//! `source_context_ids`).

use crate::result::{spoke_ok, spoke_reject, SpokeRejectCode, SpokeResult};
use serde_json::{Map, Value};
use spoke_schemas::{
    MemoryCandidatesListRequest, MemoryCandidatesReviewRequest, MemoryCaptureRequest,
    MemoryGrantsGrantRequest, MemoryGrantsListRequest, MemoryImportsStageRequest,
    MemoryRecallRequest, MemoryRecordsCreateRequest, MemoryRecordsListRequest,
    MemoryRecordsUpdateRequest, MemoryReflectionsGenerateRequest, MemoryReflectionsListRequest,
    MemoryReflectionsStateRequest, MemorySpacesListRequest, MemorySubjectsFenceRequest,
};
use std::num::NonZeroU64;

fn invalid_input(field: &str, message: impl Into<String>) -> SpokeResult<()> {
    let mut details = Map::new();
    details.insert("field".into(), Value::String(field.to_owned()));
    spoke_reject(SpokeRejectCode::InvalidInput, message, Some(details))
}

/// §5.2/§6.1: a malformed completed cognition record fails `INVALID_INPUT`
/// with `details.reason = "invalid_cognition_record"` — distinct from an
/// unsupported request feature and from the admission byte limit.
fn invalid_cognition(field: &str, message: impl Into<String>) -> SpokeResult<()> {
    let mut details = Map::new();
    details.insert("field".into(), Value::String(field.to_owned()));
    details.insert(
        "reason".into(),
        Value::String("invalid_cognition_record".to_owned()),
    );
    spoke_reject(SpokeRejectCode::InvalidInput, message, Some(details))
}

/// §7.0.7: limit violations fail `INVALID_INPUT` with `details.limit`
/// naming the exceeded provider limit (`field` is kept for precision).
fn invalid_limit(field: &str, limit: &str, message: impl Into<String>) -> SpokeResult<()> {
    let mut details = Map::new();
    details.insert("field".into(), Value::String(field.to_owned()));
    details.insert("limit".into(), Value::String(limit.to_owned()));
    spoke_reject(SpokeRejectCode::InvalidInput, message, Some(details))
}

fn check_page_limit(limit: Option<NonZeroU64>, max_page_size: NonZeroU64) -> SpokeResult<()> {
    if limit.is_some_and(|limit| limit > max_page_size) {
        return invalid_limit(
            "limit",
            "max_page_size",
            format!("limit exceeds the provider max_page_size ({max_page_size})"),
        );
    }
    spoke_ok(())
}

/// Counts UTF-8 bytes without retaining them: the measure needs only the
/// length, so the canonical serialization stays transient.
struct ByteCounter(usize);

impl std::io::Write for ByteCounter {
    fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
        self.0 += buffer.len();
        Ok(buffer.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

/// Byte size of a `Content` request field against `max_content_bytes`
/// (§7.1): UTF-8 bytes of the compact serialization of the complete
/// `content` value — field name, quotes, escaping, and `structured`
/// included.
///
/// The canonical form is RFC 8785 (JCS): top-level members that are `null`
/// are absent — a deserialized `null` becomes `Option::None` and is skipped
/// by the generated serializer, and a constructed `Some(Value::Null)` is
/// stripped here so admission does not depend on how the caller built the
/// value (the TS measure filters the same members). Every other member is
/// measured exactly as supplied, including an explicitly present empty
/// `cognition` array when the value carries it: admission bounds the wire
/// value the caller sent, and dropping a present member would admit bytes
/// the request still carries. A generated `Content` already omits an empty
/// `Vec` at serialization (`#[serde(skip_serializing_if = "Vec::is_empty")]`),
/// which is the carrier's absent-member rule — a typed value cannot express
/// an explicitly present empty array. Nested `null`s are content and stay.
/// Numbers use the ECMAScript form (`1.0` → `1`) that `JSON.stringify`
/// produces, so the TS measure counts identical bytes.
///
/// The canonical bytes are counted through a writer instead of materialized
/// as a `Vec`: admission only needs the length.
///
/// Unmeasurable content fails **closed**: both error arms return
/// [`usize::MAX`], which every `max_content_bytes` comparison rejects, so a
/// serialization failure can never admit a request.
#[must_use]
pub fn content_serialized_bytes(content: &impl serde::Serialize) -> usize {
    let value = match serde_json::to_value(content) {
        Ok(Value::Object(members)) => {
            Value::Object(members.into_iter().filter(|(_, member)| !member.is_null()).collect())
        }
        Ok(other) => other,
        Err(_) => return usize::MAX,
    };
    let mut counter = ByteCounter(0);
    match serde_jcs::to_writer(&mut counter, &value) {
        Ok(()) => counter.0,
        Err(_) => usize::MAX,
    }
}

fn check_content_limit(byte_len: usize, max_content_bytes: usize) -> SpokeResult<()> {
    if byte_len > max_content_bytes {
        return invalid_limit(
            "content",
            "max_content_bytes",
            format!("content exceeds the provider max_content_bytes ({max_content_bytes})"),
        );
    }
    spoke_ok(())
}

/// C5 entry-point guard (§6.1): every present `Content.cognition` entry must
/// be a closed standard cognition record with `view = "recorded_at"`. Runs
/// before byte admission so a malformed carrier fails `INVALID_INPUT` on the
/// field, never on the budget. A content value that cannot be re-serialized
/// fails closed the same way.
fn check_cognition_content(content: &impl serde::Serialize) -> SpokeResult<()> {
    let value = match serde_json::to_value(content) {
        Ok(value) => value,
        Err(_) => return invalid_input("content.cognition", "content is not serializable"),
    };
    match crate::cognition::validate_cognition_content(&value) {
        SpokeResult::Reject(_) => invalid_cognition(
            "content.cognition",
            "Content cognition entries must be recorded-at-time records",
        ),
        SpokeResult::Ok(()) => spoke_ok(()),
    }
}

/// §8.2 freeze maintenance allowlist: while a space is frozen it admits
/// exactly all read-only ops (MEM-R011), `memory.spaces.unfreeze`,
/// `memory.grants.revoke`, and the five transfer ops. `op` is the exact op
/// string (§13, e.g. `"memory.exports.create"`).
#[must_use]
pub fn is_freeze_allowlisted(op: &str) -> bool {
    matches!(
        op,
        // Read-only ops (MEM-R011).
        "memory.describe"
            | "memory.spaces.list"
            | "memory.subjects.get"
            | "memory.grants.list"
            | "memory.candidates.list"
            | "memory.candidates.get"
            | "memory.records.get"
            | "memory.records.list"
            | "memory.recall"
            | "memory.profile.get"
            | "memory.reflections.state"
            | "memory.reflections.list"
            | "memory.receipts.get"
            | "memory.exports.get"
            // §8.2 maintenance mutations.
            | "memory.spaces.unfreeze"
            | "memory.grants.revoke"
            | "memory.exports.create"
            | "memory.imports.stage"
            | "memory.imports.activate"
            | "memory.imports.discard"
    )
}

/// §7.2 `memory.spaces.list`: page limit vs the provider's `max_page_size`.
pub fn validate_memory_spaces_list(
    request: &MemorySpacesListRequest,
    max_page_size: NonZeroU64,
) -> SpokeResult<()> {
    check_page_limit(request.limit, max_page_size)
}

/// §7.8 `memory.grants.list`: page limit vs the provider's `max_page_size`.
pub fn validate_memory_grants_list(
    request: &MemoryGrantsListRequest,
    max_page_size: NonZeroU64,
) -> SpokeResult<()> {
    check_page_limit(request.limit, max_page_size)
}

/// §7.12 `memory.candidates.list`: page limit vs the provider's
/// `max_page_size`.
pub fn validate_memory_candidates_list(
    request: &MemoryCandidatesListRequest,
    max_page_size: NonZeroU64,
) -> SpokeResult<()> {
    check_page_limit(request.limit, max_page_size)
}

/// §7.7 `memory.subjects.fence`: `archive` on a context target is
/// `INVALID_INPUT` (context targets support `fence`/`unfence` only).
pub fn validate_memory_subjects_fence(request: &MemorySubjectsFenceRequest) -> SpokeResult<()> {
    use spoke_schemas::memory_subjects_fence_request::{Action, Target};
    match (&request.target, &request.action) {
        (Target::Context(_), Action::Archive) => {
            invalid_input("target", "archive is not valid on a context target")
        }
        _ => spoke_ok(()),
    }
}

/// §7.11 `memory.capture`: content byte limit vs the provider's
/// `max_content_bytes`. `capture_scope` conditionality (§6.6) is
/// type-enforced by `PlacementScope`.
pub fn validate_memory_capture(
    request: &MemoryCaptureRequest,
    max_content_bytes: usize,
) -> SpokeResult<()> {
    match check_cognition_content(&request.content) {
        SpokeResult::Reject(reject) => return SpokeResult::Reject(reject),
        SpokeResult::Ok(()) => {}
    }
    check_content_limit(
        content_serialized_bytes(&request.content),
        max_content_bytes,
    )
}

/// §7.9 `memory.grants.grant`: `capabilities` must be non-empty and unique
/// (`minItems: 1`, `uniqueItems: true` — the generated `Vec<String>` fields
/// do not enforce this for programmatically constructed values), and the
/// restricted-shape `context_ids` must be non-empty. `shared_access` without
/// `context_ids` is type-enforced (only the restricted shape carries the
/// field).
pub fn validate_memory_grants_grant(request: &MemoryGrantsGrantRequest) -> SpokeResult<()> {
    fn check_capabilities(capabilities: &[String]) -> SpokeResult<()> {
        if capabilities.is_empty() {
            return invalid_input("capabilities", "capabilities must be non-empty");
        }
        let unique = capabilities.iter().collect::<std::collections::HashSet<_>>().len();
        if unique != capabilities.len() {
            return invalid_input("capabilities", "capabilities must be unique");
        }
        spoke_ok(())
    }
    match request {
        MemoryGrantsGrantRequest::Variant0 {
            capabilities,
            context_ids,
            ..
        } => {
            match check_capabilities(capabilities) {
                SpokeResult::Reject(reject) => return SpokeResult::Reject(reject),
                SpokeResult::Ok(()) => {}
            }
            if context_ids.is_empty() {
                return invalid_input(
                    "context_ids",
                    "context_ids must be non-empty when present",
                );
            }
            spoke_ok(())
        }
        MemoryGrantsGrantRequest::Variant1 { capabilities, .. } => check_capabilities(capabilities),
    }
}

/// §7.15 `memory.candidates.review`: a fragment decision must name at least
/// one fragment (minItems 1). The oneOf decision shape is type-enforced.
pub fn validate_memory_candidates_review(
    request: &MemoryCandidatesReviewRequest,
) -> SpokeResult<()> {
    use spoke_schemas::memory_candidates_review_request::Decision;
    match &request.decision {
        Decision::Fragment { fragments } if fragments.is_empty() => {
            invalid_input("decision.fragments", "fragment decision requires at least one fragment")
        }
        _ => spoke_ok(()),
    }
}

/// §7.16 `memory.records.create`: content byte limit. Placement
/// conditionality is type-enforced by `PlacementScope`.
pub fn validate_memory_records_create(
    request: &MemoryRecordsCreateRequest,
    max_content_bytes: usize,
) -> SpokeResult<()> {
    match check_cognition_content(&request.content) {
        SpokeResult::Reject(reject) => return SpokeResult::Reject(reject),
        SpokeResult::Ok(()) => {}
    }
    check_content_limit(
        content_serialized_bytes(&request.content),
        max_content_bytes,
    )
}

/// §7.18 `memory.records.update`: at least one of `content` / `kind` is
/// required — a combined update carrying both is valid (placement is the
/// only forbidden change). The generated oneOf already guarantees at least
/// one (both-absent is unparseable), so this validator only bounds content
/// when present, on either request shape.
pub fn validate_memory_records_update(
    request: &MemoryRecordsUpdateRequest,
    max_content_bytes: usize,
) -> SpokeResult<()> {
    match request {
        MemoryRecordsUpdateRequest::Variant0 { content, .. } => {
            match check_cognition_content(content) {
                SpokeResult::Reject(reject) => return SpokeResult::Reject(reject),
                SpokeResult::Ok(()) => {}
            }
            check_content_limit(
                content_serialized_bytes(content),
                max_content_bytes,
            )
        }
        MemoryRecordsUpdateRequest::Variant1 { content: Some(content), .. } => {
            match check_cognition_content(content) {
                SpokeResult::Reject(reject) => return SpokeResult::Reject(reject),
                SpokeResult::Ok(()) => {}
            }
            check_content_limit(
                content_serialized_bytes(content),
                max_content_bytes,
            )
        }
        MemoryRecordsUpdateRequest::Variant1 { content: None, .. } => spoke_ok(()),
    }
}

/// §7.20 `memory.records.list`: selection/filter invariants (§6.12, §6.13)
/// plus the page limit.
pub fn validate_memory_records_list(
    request: &MemoryRecordsListRequest,
    max_page_size: NonZeroU64,
) -> SpokeResult<()> {
    use spoke_schemas::memory_records_list_request::ReadSelection;
    if let ReadSelection::SelectedContexts { context_ids, .. } = &request.selection {
        if context_ids.is_empty() {
            return invalid_input(
                "selection.context_ids",
                "selected_contexts requires at least one context_id",
            );
        }
    }
    if let Some(filter) = &request.filter {
        if filter.source_context_ids.is_empty() {
            return invalid_input(
                "filter.source_context_ids",
                "provenance filter requires at least one source context",
            );
        }
    }
    check_page_limit(request.limit, max_page_size)
}

/// §7.22 `memory.recall`: selection/filter invariants and the
/// `budget.max_items` hard cap (§9: ≥ 1 is type-enforced, ≤ `max_page_size`
/// is provider-declared).
pub fn validate_memory_recall(
    request: &MemoryRecallRequest,
    max_page_size: NonZeroU64,
) -> SpokeResult<()> {
    use spoke_schemas::memory_recall_request::ReadSelection;
    if let ReadSelection::SelectedContexts { context_ids, .. } = &request.selection {
        if context_ids.is_empty() {
            return invalid_input(
                "selection.context_ids",
                "selected_contexts requires at least one context_id",
            );
        }
    }
    if let Some(filter) = &request.filter {
        if filter.source_context_ids.is_empty() {
            return invalid_input(
                "filter.source_context_ids",
                "provenance filter requires at least one source context",
            );
        }
    }
    if request.budget.max_items > max_page_size {
        return invalid_limit(
            "max_items",
            "max_page_size",
            format!("budget.max_items exceeds the provider max_page_size ({max_page_size})"),
        );
    }
    spoke_ok(())
}

/// §7.25 `memory.reflections.state`: selection/filter invariants.
pub fn validate_memory_reflections_state(
    request: &MemoryReflectionsStateRequest,
) -> SpokeResult<()> {
    use spoke_schemas::memory_reflections_state_request::ReadSelection;
    if let ReadSelection::SelectedContexts { context_ids, .. } = &request.selection {
        if context_ids.is_empty() {
            return invalid_input(
                "selection.context_ids",
                "selected_contexts requires at least one context_id",
            );
        }
    }
    if let Some(filter) = &request.filter {
        if filter.source_context_ids.is_empty() {
            return invalid_input(
                "filter.source_context_ids",
                "provenance filter requires at least one source context",
            );
        }
    }
    spoke_ok(())
}

/// §7.26 `memory.reflections.list`: optional selection/filter invariants plus
/// the page limit.
pub fn validate_memory_reflections_list(
    request: &MemoryReflectionsListRequest,
    max_page_size: NonZeroU64,
) -> SpokeResult<()> {
    use spoke_schemas::memory_reflections_list_request::ReadSelection;
    if let Some(ReadSelection::SelectedContexts { context_ids, .. }) = &request.selection {
        if context_ids.is_empty() {
            return invalid_input(
                "selection.context_ids",
                "selected_contexts requires at least one context_id",
            );
        }
    }
    if let Some(filter) = &request.filter {
        if filter.source_context_ids.is_empty() {
            return invalid_input(
                "filter.source_context_ids",
                "provenance filter requires at least one source context",
            );
        }
    }
    check_page_limit(request.limit, max_page_size)
}

/// §7.27 `memory.reflections.generate`: selection/filter invariants.
pub fn validate_memory_reflections_generate(
    request: &MemoryReflectionsGenerateRequest,
) -> SpokeResult<()> {
    use spoke_schemas::memory_reflections_generate_request::ReadSelection;
    if let ReadSelection::SelectedContexts { context_ids, .. } = &request.selection {
        if context_ids.is_empty() {
            return invalid_input(
                "selection.context_ids",
                "selected_contexts requires at least one context_id",
            );
        }
    }
    if let Some(filter) = &request.filter {
        if filter.source_context_ids.is_empty() {
            return invalid_input(
                "filter.source_context_ids",
                "provenance filter requires at least one source context",
            );
        }
    }
    spoke_ok(())
}

/// §7.31 `memory.imports.stage`: the header-chunk shape (`Variant0`) must
/// carry `chunk_ordinal == 0`; tail ordinals ≥ 1 are type-enforced by
/// `NonZeroU64`. `conflict_policy` / `adopt_grants` chunk-0 scoping is
/// type-enforced by the shape split.
pub fn validate_memory_imports_stage(request: &MemoryImportsStageRequest) -> SpokeResult<()> {
    match request {
        MemoryImportsStageRequest::Variant0 { chunk, .. } if chunk.chunk_ordinal != 0 => {
            invalid_input("chunk.chunk_ordinal", "header chunk must carry chunk_ordinal 0")
        }
        _ => spoke_ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{SpokeRejectCode, SpokeResult};
    use serde_json::json;
    use spoke_schemas::{
        MemoryCandidatesReviewRequest, MemoryCaptureRequest, MemoryGrantsGrantRequest,
        MemoryImportsStageRequest, MemoryRecallRequest, MemoryRecordsCreateRequest,
        MemoryRecordsListRequest, MemoryRecordsUpdateRequest, MemorySpacesListRequest,
        MemorySubjectsFenceRequest,
    };
    use std::num::NonZeroU64;

    fn max_page() -> NonZeroU64 {
        NonZeroU64::new(100).expect("non-zero")
    }

    fn expect_invalid<T>(result: SpokeResult<T>, field: &str) {
        match result {
            SpokeResult::Reject(reject) => {
                assert_eq!(reject.code, SpokeRejectCode::InvalidInput);
                assert_eq!(
                    reject.details.as_ref().and_then(|d| d.get("field")).and_then(|v| v.as_str()),
                    Some(field)
                );
            }
            SpokeResult::Ok(_) => panic!("expected reject for field {field}"),
        }
    }

    /// §5.2/§6.1 identity: malformed completed cognition rejects with the
    /// field and `details.reason = "invalid_cognition_record"`.
    fn expect_invalid_cognition<T>(result: SpokeResult<T>) {
        match result {
            SpokeResult::Reject(reject) => {
                assert_eq!(reject.code, SpokeRejectCode::InvalidInput);
                let details = reject.details.as_ref().expect("cognition reject details");
                assert_eq!(
                    details.get("field").and_then(Value::as_str),
                    Some("content.cognition")
                );
                assert_eq!(
                    details.get("reason").and_then(Value::as_str),
                    Some("invalid_cognition_record")
                );
            }
            SpokeResult::Ok(_) => panic!("expected cognition reject"),
        }
    }

    // ---- §8.2 freeze allowlist ----

    #[test]
    fn freeze_allowlist_admits_reads_and_maintenance_ops() {
        for op in [
            "memory.describe",
            "memory.spaces.list",
            "memory.subjects.get",
            "memory.grants.list",
            "memory.candidates.list",
            "memory.candidates.get",
            "memory.records.get",
            "memory.records.list",
            "memory.recall",
            "memory.profile.get",
            "memory.reflections.state",
            "memory.reflections.list",
            "memory.receipts.get",
            "memory.exports.get",
            "memory.spaces.unfreeze",
            "memory.grants.revoke",
            "memory.exports.create",
            "memory.imports.stage",
            "memory.imports.activate",
            "memory.imports.discard",
        ] {
            assert!(is_freeze_allowlisted(op), "{op} must be allowlisted");
        }
    }

    #[test]
    fn freeze_allowlist_rejects_other_mutations_and_unknown_ops() {
        for op in [
            "memory.spaces.freeze",
            "memory.subjects.ensure",
            "memory.subjects.fence",
            "memory.grants.grant",
            "memory.capture",
            "memory.candidates.dismiss",
            "memory.candidates.review",
            "memory.records.create",
            "memory.records.update",
            "memory.records.delete",
            "memory.records.promote",
            "memory.profile.update",
            "memory.reflections.generate",
            "memory.extract",
        ] {
            assert!(!is_freeze_allowlisted(op), "{op} must not be allowlisted");
        }
    }

    // ---- page bounds ----

    #[test]
    fn spaces_list_rejects_limit_above_max_page_size() {
        let ok: MemorySpacesListRequest =
            serde_json::from_value(json!({"limit": 100})).expect("valid request");
        assert!(validate_memory_spaces_list(&ok, max_page()).is_ok());

        let too_big: MemorySpacesListRequest =
            serde_json::from_value(json!({"limit": 101})).expect("valid request");
        expect_invalid(validate_memory_spaces_list(&too_big, max_page()), "limit");
    }

    #[test]
    fn recall_rejects_budget_max_items_above_max_page_size() {
        let request: MemoryRecallRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "selection": {"mode": "shared_only"},
            "budget": {"max_items": 101},
        }))
        .expect("valid request");
        expect_invalid(validate_memory_recall(&request, max_page()), "max_items");

        let request: MemoryRecallRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "selection": {"mode": "shared_only"},
            "budget": {"max_items": 100},
        }))
        .expect("valid request");
        assert!(validate_memory_recall(&request, max_page()).is_ok());
    }

    // ---- selection / filter invariants (§6.12, §6.13) ----

    #[test]
    fn recall_rejects_empty_selected_contexts() {
        let mut request: MemoryRecallRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "selection": {"mode": "selected_contexts", "context_ids": ["c1"]},
            "budget": {"max_items": 10},
        }))
        .expect("valid request");
        request.selection = spoke_schemas::memory_recall_request::ReadSelection::SelectedContexts {
            context_ids: Vec::new(),
            include_shared: None,
        };
        expect_invalid(validate_memory_recall(&request, max_page()), "selection.context_ids");
    }

    #[test]
    fn records_list_rejects_empty_provenance_filter() {
        let mut request: MemoryRecordsListRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "selection": {"mode": "subject_all"},
            "filter": {"source_context_ids": ["c1"]},
        }))
        .expect("valid request");
        request.filter =
            Some(spoke_schemas::memory_records_list_request::ProvenanceFilter {
                source_context_ids: Vec::new(),
            });
        expect_invalid(validate_memory_records_list(&request, max_page()), "filter.source_context_ids");
    }

    #[test]
    fn reflections_state_rejects_empty_selected_contexts() {
        let mut request = serde_json::from_value::<spoke_schemas::MemoryReflectionsStateRequest>(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "selection": {"mode": "subject_all"},
        }))
        .expect("valid request");
        request.selection =
            spoke_schemas::memory_reflections_state_request::ReadSelection::SelectedContexts {
                context_ids: Vec::new(),
                include_shared: None,
            };
        expect_invalid(validate_memory_reflections_state(&request), "selection.context_ids");
    }

    #[test]
    fn reflections_generate_rejects_empty_provenance_filter() {
        let mut request = serde_json::from_value::<spoke_schemas::MemoryReflectionsGenerateRequest>(
            json!({
                "space_id": "sp_1",
                "subject_id": "s1",
                "selection": {"mode": "shared_only"},
                "expected_state_digest": "d".repeat(64),
                "idempotency_key": "k1",
            }),
        )
        .expect("valid request");
        request.filter = Some(spoke_schemas::memory_reflections_generate_request::ProvenanceFilter {
            source_context_ids: Vec::new(),
        });
        expect_invalid(validate_memory_reflections_generate(&request), "filter.source_context_ids");
    }

    #[test]
    fn reflections_list_validates_optional_selection_and_limit() {
        let mut request = serde_json::from_value::<spoke_schemas::MemoryReflectionsListRequest>(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "limit": 50,
        }))
        .expect("valid request");
        assert!(validate_memory_reflections_list(&request, max_page()).is_ok());

        request.limit = NonZeroU64::new(101);
        expect_invalid(validate_memory_reflections_list(&request, max_page()), "limit");
    }

    // ---- per-op conditionals ----

    #[test]
    fn subjects_fence_rejects_archive_on_context_target() {
        let request: MemorySubjectsFenceRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "target": {"type": "context", "context_id": "c1"},
            "action": "archive",
            "expected_revision": 1,
            "idempotency_key": "k1",
        }))
        .expect("valid request");
        expect_invalid(validate_memory_subjects_fence(&request), "target");

        let fence: MemorySubjectsFenceRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "target": {"type": "context", "context_id": "c1"},
            "action": "fence",
            "expected_revision": 1,
            "idempotency_key": "k1",
        }))
        .expect("valid request");
        assert!(validate_memory_subjects_fence(&fence).is_ok());

        let archive_subject: MemorySubjectsFenceRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "target": {"type": "subject"},
            "action": "archive",
            "expected_revision": 1,
            "idempotency_key": "k1",
        }))
        .expect("valid request");
        assert!(validate_memory_subjects_fence(&archive_subject).is_ok());
    }

    #[test]
    fn grants_grant_rejects_empty_context_ids_on_restricted_shape() {
        let mut request: MemoryGrantsGrantRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "principal_id": "p2",
            "capabilities": ["capture"],
            "context_ids": ["c1"],
            "idempotency_key": "k1",
        }))
        .expect("valid restricted-shape request");
        match &mut request {
            MemoryGrantsGrantRequest::Variant0 { context_ids, .. } => context_ids.clear(),
            MemoryGrantsGrantRequest::Variant1 { .. } => panic!("expected restricted shape"),
        }
        expect_invalid(validate_memory_grants_grant(&request), "context_ids");
    }

    #[test]
    fn grants_grant_rejects_empty_or_duplicate_capabilities() {
        // Restricted shape: empty and duplicate capabilities.
        let mut empty_caps: MemoryGrantsGrantRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "principal_id": "p2",
            "capabilities": ["capture"],
            "context_ids": ["c1"],
            "idempotency_key": "k1",
        }))
        .expect("valid restricted-shape request");
        match &mut empty_caps {
            MemoryGrantsGrantRequest::Variant0 { capabilities, .. } => capabilities.clear(),
            MemoryGrantsGrantRequest::Variant1 { .. } => panic!("expected restricted shape"),
        }
        expect_invalid(validate_memory_grants_grant(&empty_caps), "capabilities");

        let mut dup_caps: MemoryGrantsGrantRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "principal_id": "p2",
            "capabilities": ["capture"],
            "context_ids": ["c1"],
            "idempotency_key": "k1",
        }))
        .expect("valid restricted-shape request");
        match &mut dup_caps {
            MemoryGrantsGrantRequest::Variant0 { capabilities, .. } => {
                capabilities.push("capture".to_owned());
            }
            MemoryGrantsGrantRequest::Variant1 { .. } => panic!("expected restricted shape"),
        }
        expect_invalid(validate_memory_grants_grant(&dup_caps), "capabilities");

        // Unrestricted shape: empty capabilities.
        let mut unrestricted: MemoryGrantsGrantRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "principal_id": "p2",
            "capabilities": ["capture"],
            "idempotency_key": "k1",
        }))
        .expect("valid unrestricted-shape request");
        match &mut unrestricted {
            MemoryGrantsGrantRequest::Variant1 { capabilities, .. } => capabilities.clear(),
            MemoryGrantsGrantRequest::Variant0 { .. } => panic!("expected unrestricted shape"),
        }
        expect_invalid(validate_memory_grants_grant(&unrestricted), "capabilities");
    }

    /// §7.0.7: provider-limit rejections carry `details.limit` naming the
    /// exceeded limit.
    fn expect_limit<T>(result: SpokeResult<T>, limit: &str) {
        match result {
            SpokeResult::Reject(reject) => {
                assert_eq!(reject.code, SpokeRejectCode::InvalidInput);
                assert_eq!(
                    reject.details.as_ref().and_then(|d| d.get("limit")).and_then(|v| v.as_str()),
                    Some(limit)
                );
            }
            SpokeResult::Ok(_) => panic!("expected reject naming limit {limit}"),
        }
    }

    #[test]
    fn limit_rejections_name_the_exceeded_limit() {
        let too_big: MemorySpacesListRequest =
            serde_json::from_value(json!({"limit": 101})).expect("valid request");
        expect_limit(validate_memory_spaces_list(&too_big, max_page()), "max_page_size");

        let capture: MemoryCaptureRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "content": {"text": "x".repeat(2048)},
            "capture_scope": {"visibility": "shared"},
            "idempotency_key": "k1",
        }))
        .expect("valid request");
        expect_limit(validate_memory_capture(&capture, 1024), "max_content_bytes");

        let recall: MemoryRecallRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "selection": {"mode": "shared_only"},
            "budget": {"max_items": 101},
        }))
        .expect("valid request");
        expect_limit(validate_memory_recall(&recall, max_page()), "max_page_size");
    }

    #[test]
    fn candidates_review_rejects_empty_fragment_list() {
        let mut request: MemoryCandidatesReviewRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "candidate_id": "cand_1",
            "expected_revision": 1,
            "decision": {"action": "drop"},
            "idempotency_key": "k1",
        }))
        .expect("valid request");
        request.decision =
            spoke_schemas::memory_candidates_review_request::Decision::Fragment {
                fragments: Vec::new(),
            };
        expect_invalid(validate_memory_candidates_review(&request), "decision.fragments");
    }

    #[test]
    fn records_update_accepts_combined_kind_and_content() {
        // §7.18: at least one of content/kind — a combined update is valid.
        let request: MemoryRecordsUpdateRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "record_id": "r1",
            "expected_revision": 1,
            "kind": "note",
            "content": {"text": "combined update"},
            "idempotency_key": "k1",
        }))
        .expect("valid combined-update request");
        match &request {
            MemoryRecordsUpdateRequest::Variant1 { content: Some(_), .. } => {}
            other => panic!("expected kind-shape carrying content, got {other:?}"),
        }
        assert!(validate_memory_records_update(&request, 1024).is_ok());

        // Kind-only remains valid.
        let kind_only: MemoryRecordsUpdateRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "record_id": "r1",
            "expected_revision": 1,
            "kind": "note",
            "idempotency_key": "k1",
        }))
        .expect("valid kind-only request");
        assert!(validate_memory_records_update(&kind_only, 1024).is_ok());

        // Content still rides the provider byte limit on the combined shape.
        let oversize: MemoryRecordsUpdateRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "record_id": "r1",
            "expected_revision": 1,
            "kind": "note",
            "content": {"text": "x".repeat(2048)},
            "idempotency_key": "k1",
        }))
        .expect("valid combined-update request");
        match validate_memory_records_update(&oversize, 1024) {
            SpokeResult::Reject(reject) => {
                assert_eq!(reject.code, SpokeRejectCode::InvalidInput);
                assert_eq!(
                    reject
                        .details
                        .as_ref()
                        .and_then(|d| d.get("limit"))
                        .and_then(|v| v.as_str()),
                    Some("max_content_bytes")
                );
            }
            SpokeResult::Ok(_) => panic!("expected limit reject"),
        }
    }

    #[test]
    fn imports_stage_rejects_non_zero_header_chunk_ordinal() {
        let request: MemoryImportsStageRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "chunk": {
                "export_id": "e1",
                "chunk_ordinal": 1,
                "chunk_count": 2,
                "bundle_digest": "b".repeat(64),
                "chunk_digest": "c".repeat(64),
                "bytes": 10,
                "header": {
                    "schema_version": 1,
                    "bundle_format_version": 1,
                    "memory_protocol_version": 1,
                    "export_id": "e1",
                    "space_id": "sp_1",
                    "created_at": "2026-01-01T00:00:00Z",
                    "source": {
                        "authority_host_id": "host_1",
                        "authority_generation": 1,
                        "engine_policy_version": "v1",
                    },
                    "digest": "d".repeat(64),
                },
            },
            "conflict_policy": "fail",
            "idempotency_key": "k1",
        }))
        .expect("valid first-chunk-shape request");
        expect_invalid(validate_memory_imports_stage(&request), "chunk.chunk_ordinal");
    }

    // ---- content byte limits ----

    #[test]
    fn content_serialized_bytes_known_vectors() {
        use spoke_schemas::memory_capture_request::Content;
        // Same explicit byte values are pinned by the TS parity test.
        let non_ascii = Content { cognition: None, structured: None, text: "héllo".to_string() };
        assert_eq!(content_serialized_bytes(&non_ascii), 17);
        let nested = Content {
            cognition: None,
            structured: Some(json!({"nested": [true, null]})),
            text: "ab".to_string(),
        };
        assert_eq!(content_serialized_bytes(&nested), 49);
        let empty = Content { cognition: None, structured: None, text: String::new() };
        assert_eq!(content_serialized_bytes(&empty), 11);
    }

    #[test]
    fn content_serialized_bytes_canonicalizes_explicit_null() {
        use spoke_schemas::memory_capture_request::Content;
        // Explicit `structured: null` deserializes to `None` and the
        // generated serializer skips it: `{"text":""}` = 11 bytes. The TS
        // parity test pins the same value and the 10/11 admission pair.
        let explicit_null: Content =
            serde_json::from_value(json!({"text": "", "structured": null}))
                .expect("valid content");
        assert_eq!(content_serialized_bytes(&explicit_null), 11);
    }

    #[test]
    fn content_serialized_bytes_use_ecmascript_number_form() {
        use spoke_schemas::memory_capture_request::Content;
        // JCS/ES6 numbers: `1.0` → `1`, `1e2` → `100`. TS `JSON.stringify`
        // counts the same 40 bytes in its parity test.
        let numbers = Content {
            cognition: None,
            structured: Some(json!({"n": 1.0, "e": 1e2})),
            text: String::new(),
        };
        assert_eq!(content_serialized_bytes(&numbers), 40);
    }

    #[test]
    fn capture_admits_explicit_null_content_boundary() {
        // `{"text":"","structured":null}` canonicalizes to `{"text":""}`,
        // 11 bytes; the TS parity test pins the same accept/reject pair.
        let request: MemoryCaptureRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "content": {"text": "", "structured": null},
            "capture_scope": {"visibility": "shared"},
            "idempotency_key": "k1",
        }))
        .expect("valid request");
        assert!(validate_memory_capture(&request, 11).is_ok());
        expect_invalid(validate_memory_capture(&request, 10), "content");
    }

    #[test]
    fn capture_admits_constructed_explicit_null_boundary() {
        // A caller-built `Some(Value::Null)` is the same logical content as a
        // deserialized `null`: both canonicalize to `{"text":""}` = 11 bytes,
        // so admission cannot depend on how the value was constructed. The TS
        // parity test pins the same 11/10 pair.
        use spoke_schemas::memory_capture_request::Content;
        let mut request: MemoryCaptureRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "content": {"text": ""},
            "capture_scope": {"visibility": "shared"},
            "idempotency_key": "k1",
        }))
        .expect("valid request");
        request.content = Content { cognition: None, structured: Some(Value::Null), text: String::new() };
        assert_eq!(content_serialized_bytes(&request.content), 11);
        assert!(validate_memory_capture(&request, 11).is_ok());
        expect_invalid(validate_memory_capture(&request, 10), "content");
    }

    #[test]
    fn content_serialized_bytes_fails_closed() {
        // I-000030: unmeasurable content must reject. A `0` measure would make
        // every `max_content_bytes` comparison pass and admit the request.
        struct Unserializable;
        impl serde::Serialize for Unserializable {
            fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
                Err(<S::Error as serde::ser::Error>::custom("unmeasurable"))
            }
        }
        let bytes = content_serialized_bytes(&Unserializable);
        assert_eq!(bytes, usize::MAX);
        expect_invalid(check_content_limit(bytes, 1024), "content");
    }

    #[test]
    fn capture_rejects_oversize_content() {
        let request: MemoryCaptureRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "content": {"text": "x".repeat(2048)},
            "capture_scope": {"visibility": "shared"},
            "idempotency_key": "k1",
        }))
        .expect("valid request");
        expect_invalid(validate_memory_capture(&request, 1024), "content");

        let small: MemoryCaptureRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "content": {"text": "fine"},
            "capture_scope": {"visibility": "context", "context_id": "c1"},
            "idempotency_key": "k1",
        }))
        .expect("valid request");
        assert!(validate_memory_capture(&small, 1024).is_ok());
    }

    #[test]
    fn capture_admits_exact_content_byte_boundary() {
        // `{"text":"fine"}` is exactly 15 bytes under the serialized measure.
        let request: MemoryCaptureRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "content": {"text": "fine"},
            "capture_scope": {"visibility": "shared"},
            "idempotency_key": "k1",
        }))
        .expect("valid request");
        assert!(validate_memory_capture(&request, 15).is_ok());
        expect_invalid(validate_memory_capture(&request, 14), "content");
    }

    #[test]
    fn records_create_rejects_oversize_content() {
        let request: MemoryRecordsCreateRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "kind": "note",
            "content": {"text": "x".repeat(2048)},
            "scope": {"visibility": "shared"},
            "idempotency_key": "k1",
        }))
        .expect("valid request");
        expect_invalid(validate_memory_records_create(&request, 1024), "content");
    }

    /// Shared C8 lifecycle vectors: the Rust validator must observe the same
    /// exact canonical admission bytes and the same accept/reject outcome as
    /// the TS suite for every `content-admission` vector, and the cognition
    /// guard must run before byte admission.
    #[test]
    fn cognition_lifecycle_shared_admission_vectors() {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../fixtures/cognition/memory-lifecycle-vectors.json"
        );
        let raw = std::fs::read_to_string(path).expect("lifecycle vectors readable");
        let file: Value = serde_json::from_str(&raw).expect("lifecycle vectors parse");
        let vectors = file["vectors"].as_array().expect("vectors array");
        let mut ran = 0;

        for vector in vectors {
            if vector["shape"].as_str() != Some("content-admission") {
                continue;
            }
            ran += 1;
            let id = vector["id"].as_str().expect("vector id");
            let content = vector["content"].clone();
            let canonical = vector["canonical_bytes"].as_u64().expect("canonical_bytes") as usize;
            assert_eq!(
                content_serialized_bytes(&content),
                canonical,
                "{id}: canonical admission bytes"
            );
            let max = vector["max_content_bytes"].as_u64().expect("max_content_bytes") as usize;
            let capture: MemoryCaptureRequest = serde_json::from_value(json!({
                "space_id": "sp_1",
                "subject_id": "s1",
                "content": content,
                "capture_scope": {"visibility": "shared"},
                "idempotency_key": "k1",
            }))
            .expect("valid capture request");
            let outcome = validate_memory_capture(&capture, max);
            match vector["expected"].as_str().expect("expected") {
                "accept" => {
                    assert!(canonical <= max, "{id}: content within budget");
                    assert!(outcome.is_ok(), "{id}: {outcome:?}");
                }
                "reject" => match vector["reason"].as_str().expect("reason") {
                    // The admission budget bounds the complete typed wire
                    // value: the typed carrier keeps an explicitly present
                    // empty array, so the deserialized request re-serializes
                    // to the same canonical bytes and the real validator —
                    // not only the raw `Value` above — rejects it.
                    "max_content_bytes" => {
                        assert!(canonical > max, "{id}: content exceeds the admission limit");
                        let typed = serde_json::to_value(&capture.content)
                            .expect("typed content serializes");
                        assert_eq!(
                            content_serialized_bytes(&typed),
                            canonical,
                            "{id}: typed admission bytes"
                        );
                        match outcome {
                            SpokeResult::Reject(reject) => {
                                assert_eq!(reject.code, SpokeRejectCode::InvalidInput, "{id}");
                                assert_eq!(
                                    reject
                                        .details
                                        .as_ref()
                                        .and_then(|details| details.get("limit"))
                                        .and_then(Value::as_str),
                                    Some("max_content_bytes"),
                                    "{id}: admission limit"
                                );
                            }
                            other => panic!("{id}: expected rejection, got {other:?}"),
                        }
                    }
                    "invalid_cognition_record" => {
                        // Competing failure: the same content is over budget.
                        assert!(canonical > max, "{id}: content exceeds the admission limit");
                        expect_invalid_cognition(outcome);
                    }
                    other => panic!("{id}: unknown reason {other:?}"),
                },
                other => panic!("{id}: unknown expected {other:?}"),
            }
        }
        assert!(ran >= 5, "lifecycle admission vectors ran: {ran}");
    }

    #[test]
    fn cognition_lifecycle_guard_runs_before_byte_admission() {
        // A structurally complete record whose only violation is the current
        // view: with an ample budget the reject still lands on the cognition
        // field, never on max_content_bytes.
        let malformed_cognition = json!([{
            "kind": "belief",
            "record_id": "rec_belief_mem_1",
            "holder": { "kind": "principal", "namespace": "system_a", "id": "alice" },
            "target": {
                "carrier": { "kind": "knowledge_entry", "namespace": "system_a", "id": "ke_alice" },
                "target_id": "t_prop_mem_1",
                "kind": "proposition"
            },
            "assessor": { "kind": "principal", "namespace": "system_a", "id": "alice" },
            "assessor_role": "holder_self_report",
            "basis": { "kind": "evidence", "evidence": [
                { "kind": "knowledge_entry", "namespace": "system_a", "id": "ke_evt_mem_1" }
            ]},
            "assessment_context": { "context_id": "ctx_default" },
            "effective_at": "2026-07-23T06:00:00Z",
            "assessed_at": "2026-07-23T06:05:00Z",
            "view": "current",
            "order": 1,
            "q": {
                "value": 0.9,
                "assertion": "belief_attribution",
                "method": "elicitation_v1",
                "calibration": "calibrated"
            },
            "extensions": {}
        }]);
        // The same content is over the supplied budget: the cognition guard must
        // still win, so a validator that checked admission first would fail this.
        let content = json!({ "text": "fine", "cognition": malformed_cognition });
        let budget = content_serialized_bytes(&content) - 1;
        assert!(budget > 0, "content has a positive byte measure");

        let request: MemoryCaptureRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "content": content.clone(),
            "capture_scope": {"visibility": "shared"},
            "idempotency_key": "k1",
        }))
        .expect("valid capture request");
        expect_invalid_cognition(validate_memory_capture(&request, budget));

        // The same malformed record is also rejected on create and update.
        let create: MemoryRecordsCreateRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "subject_id": "s1",
            "kind": "note",
            "content": content.clone(),
            "scope": {"visibility": "shared"},
            "idempotency_key": "k1",
        }))
        .expect("valid create request");
        expect_invalid_cognition(validate_memory_records_create(&create, budget));

        let update: MemoryRecordsUpdateRequest = serde_json::from_value(json!({
            "space_id": "sp_1",
            "record_id": "r1",
            "content": content.clone(),
            "expected_revision": 1,
            "idempotency_key": "k1",
        }))
        .expect("valid update request");
        expect_invalid_cognition(validate_memory_records_update(&update, budget));
    }

    #[test]
    fn cognition_lifecycle_explicit_empty_cognition_is_measured_as_supplied() {
        // The wire measure counts the complete value: an explicitly present
        // empty array is 32 bytes, distinct from an absent member (17).
        assert_eq!(content_serialized_bytes(&json!({"text": "Memory"})), 17);
        assert_eq!(content_serialized_bytes(&json!({"text": "Memory", "cognition": []})), 32);

        // The typed `Content` carrier preserves the distinction, so the real
        // admission boundary accepts at 32 and rejects at 31 exactly like TS.
        use spoke_schemas::memory_capture_request::Content;
        let absent: Content = serde_json::from_value(json!({"text": "Memory"}))
            .expect("absent cognition decodes");
        let explicit_empty: Content =
            serde_json::from_value(json!({"text": "Memory", "cognition": []}))
                .expect("explicit empty cognition decodes");
        assert!(
            serde_json::to_value(&absent)
                .expect("absent content serializes")
                .get("cognition")
                .is_none(),
            "an absent array stays absent"
        );
        assert_eq!(
            serde_json::to_value(&explicit_empty).expect("empty content serializes")["cognition"],
            json!([]),
            "an explicit empty array stays present"
        );
        assert_eq!(content_serialized_bytes(&absent), 17);
        assert_eq!(content_serialized_bytes(&explicit_empty), 32);

        let capture = |content: Value| -> MemoryCaptureRequest {
            serde_json::from_value(json!({
                "space_id": "sp_1",
                "subject_id": "s1",
                "content": content,
                "capture_scope": {"visibility": "shared"},
                "idempotency_key": "k1",
            }))
            .expect("valid capture request")
        };
        assert!(validate_memory_capture(&capture(json!({"text": "Memory"})), 17).is_ok());
        assert!(
            validate_memory_capture(&capture(json!({"text": "Memory", "cognition": []})), 32)
                .is_ok()
        );
        expect_invalid(
            validate_memory_capture(&capture(json!({"text": "Memory", "cognition": []})), 31),
            "content",
        );

        // An explicit `null` stays invalid (the schema admits arrays only)
        // and unknown members stay rejected: both P1 wire guards survive.
        assert!(serde_json::from_value::<Content>(json!({"text": "Memory", "cognition": null})).is_err());
        assert!(serde_json::from_value::<Content>(json!({"text": "Memory", "unexpected": 1})).is_err());
    }
}