kian-core 0.5.0

Concept model, session state machine, six-invariant assertions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
//! The reserved control-envelope convention (ADR-014).
//!
//! Interrupt intent is *durable*: the control plane admits a reserved
//! inbox row instead of only flipping an in-memory flag, so the intent
//! survives a crash of the draining replica and crosses replicas as
//! data. The row's payload is exactly `{"kian": {...}}` — a row-level
//! convention like the steer wrapper and the spill envelope before
//! it: a plain payload of that precise single-key shape is read as an
//! envelope, never as message content.
//!
//! The layering is untouched (constraint 9): the control plane still
//! only writes the inbox — it never appends events. The owning drain
//! recognizes the envelope at consumption time, appends the
//! [`crate::events::EventKind::ControlInterrupt`] event (the audit
//! record), marks the row consumed, and honors the intent at its next
//! safe boundary. No wake is needed: a drain in flight consumes the row
//! at its next boundary take; a crashed owner's successor reaches it
//! through the takeover path (recovery sweep / startup inbox scan).
//!
//! Epoch targeting: the envelope carries `target_epoch` — the epoch of
//! the last event in the stream at admit time, i.e. The episode the
//! interrupt intends to stop (best-effort; `null` when unreadable).
//! Consumption compares it against the stream to decide staleness (see
//! ADR-014): a row whose target episode already *settled* (the stream
//! carries a `session/ended` at that epoch) is consumed for audit only
//! (`"stale": true`, ends nothing); a row for the current episode —
//! including one resumed by a takeover claim after the original owner
//! died mid-episode — always interrupts.

use serde_json::{Value, json};

use crate::model::SessionId;

/// The reserved envelope's single top-level key.
const ENVELOPE_KEY: &str = "kian";
/// The reserved control type discriminator.
const CONTROL_TYPE: &str = "control";
/// The interrupt action discriminator.
const INTERRUPT_ACTION: &str = "interrupt";
/// The confirmation action discriminator.
const CONFIRM_ACTION: &str = "confirm";
const EFFECT_ASSUMPTION_ACTION: &str = "effect-assumption";
/// The budget-raise action discriminator.
const BUDGET_ACTION: &str = "budget";

/// A parsed interrupt intent from a reserved control-envelope row.
///
/// Pure data: the same intent serializes to the envelope (row payload)
/// and to the [`crate::events::EventKind::ControlInterrupt`] event
/// payload, so the audit event reproduces exactly what was requested.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterruptIntent {
    /// Free-form operator reason, or `null`.
    pub reason: Option<String>,
    /// Who requested the interrupt (holder/replica identity), or `null`.
    pub requested_by: Option<String>,
    /// Unix epoch milliseconds at admit time.
    pub requested_at_ms: u64,
    /// The episode (fencing epoch of the last event) the intent targets;
    /// `null` when the stream was unreadable at admit time.
    pub target_epoch: Option<u64>,
    /// Whether consuming this intent terminates the target session rather
    /// than leaving it resumable. Absent on the wire means `false`.
    pub terminal: bool,
    /// The closed terminal cause. Present exactly when `terminal` is true.
    pub cause: Option<String>,
}

impl InterruptIntent {
    /// The only terminal interrupt cause in this phase.
    pub const JOB_CHILD_CANCEL: &'static str = "job_child_cancel";

    /// Whether `payload` is the reserved control envelope (a single
    /// `{"kian": {"type": "control", "action": "interrupt",...}}` key).
    /// Like the steer wrapper and the spill envelope, the exact shape is
    /// reserved: any other payload — including a `kian` object that is
    /// not an interrupt control — is plain content.
    #[must_use]
    pub fn is_control_envelope(payload: &Value) -> bool {
        Self::parse(payload).is_some()
    }

    /// Parses the reserved control envelope, or `None` for any payload
    /// that is not exactly it. Fields the writer omitted default
    /// honestly (`reason`/`requested_by`/`requested_by` → null,
    /// `requested_at_ms` → 0) so cross-replica rows with older writers
    /// still consume.
    #[must_use]
    pub fn parse(payload: &Value) -> Option<Self> {
        let obj = payload.as_object()?;
        if obj.len() != 1 {
            return None;
        }
        let inner = obj.get(ENVELOPE_KEY)?.as_object()?;
        if inner.get("type").and_then(Value::as_str) != Some(CONTROL_TYPE)
            || inner.get("action").and_then(Value::as_str) != Some(INTERRUPT_ACTION)
        {
            return None;
        }
        let terminal = match inner.get("terminal") {
            None => false,
            Some(value) => value.as_bool()?,
        };
        let has_cause = inner.contains_key("cause");
        let cause = inner.get("cause").and_then(Value::as_str);
        let cause = match (terminal, has_cause, cause) {
            (false, false, None) => None,
            (true, true, Some(Self::JOB_CHILD_CANCEL)) => Some(Self::JOB_CHILD_CANCEL.to_string()),
            _ => return None,
        };
        Some(Self {
            reason: inner
                .get("reason")
                .and_then(Value::as_str)
                .map(str::to_owned),
            requested_by: inner
                .get("requested_by")
                .and_then(Value::as_str)
                .map(str::to_owned),
            requested_at_ms: inner
                .get("requested_at_ms")
                .and_then(Value::as_u64)
                .unwrap_or(0),
            target_epoch: inner.get("target_epoch").and_then(Value::as_u64),
            terminal,
            cause,
        })
    }

    /// Validates the terminal/cause pairing before an adapter admits a row.
    pub fn validate(&self) -> Result<(), String> {
        match (self.terminal, self.cause.as_deref()) {
            (false, None) => Ok(()),
            (true, Some(Self::JOB_CHILD_CANCEL)) => Ok(()),
            (true, Some(cause)) => Err(format!("unknown terminal interrupt cause `{cause}`")),
            (true, None) => Err("terminal interrupt requires cause `job_child_cancel`".to_string()),
            (false, Some(_)) => Err("interrupt cause requires terminal:true".to_string()),
        }
    }

    /// The reserved envelope payload for this intent (the inbox row's
    /// `payload`).
    #[must_use]
    pub fn envelope(&self) -> Value {
        let mut inner = json!({
            "type": CONTROL_TYPE,
            "action": INTERRUPT_ACTION,
            "requested_at_ms": self.requested_at_ms,
        });
        let map = inner.as_object_mut().expect("literal object");
        match &self.reason {
            Some(r) => map.insert("reason".into(), json!(r)),
            None => map.insert("reason".into(), Value::Null),
        };
        match &self.requested_by {
            Some(r) => map.insert("requested_by".into(), json!(r)),
            None => map.insert("requested_by".into(), Value::Null),
        };
        map.insert(
            "target_epoch".into(),
            self.target_epoch.map_or(Value::Null, |e| json!(e)),
        );
        if self.terminal {
            map.insert("terminal".into(), json!(true));
            map.insert(
                "cause".into(),
                self.cause
                    .as_ref()
                    .map_or(Value::Null, |cause| json!(cause)),
            );
        }
        json!({ ENVELOPE_KEY: inner })
    }

    /// The `control/interrupt` event payload for this intent. `stale`
    /// rides only when set (additive key — legacy payloads never carry
    /// it, and a live intent never does).
    #[must_use]
    pub fn event_payload(&self, stale: bool) -> Value {
        let mut payload = json!({
            "action": INTERRUPT_ACTION,
            "requested_at_ms": self.requested_at_ms,
        });
        let map = payload.as_object_mut().expect("literal object");
        match &self.reason {
            Some(r) => map.insert("reason".into(), json!(r)),
            None => map.insert("reason".into(), Value::Null),
        };
        match &self.requested_by {
            Some(r) => map.insert("requested_by".into(), json!(r)),
            None => map.insert("requested_by".into(), Value::Null),
        };
        map.insert(
            "target_epoch".into(),
            self.target_epoch.map_or(Value::Null, |e| json!(e)),
        );
        if self.terminal {
            map.insert("terminal".into(), json!(true));
            map.insert(
                "cause".into(),
                self.cause
                    .as_ref()
                    .map_or(Value::Null, |cause| json!(cause)),
            );
        }
        if stale {
            map.insert("stale".into(), json!(true));
        }
        payload
    }

    /// The inbox idempotency key: repeated interrupts against the same
    /// episode (`target_epoch`) dedupe to exactly one row.
    #[must_use]
    pub fn idempotency_key(session: &SessionId, target_epoch: Option<u64>) -> String {
        match target_epoch {
            Some(e) => format!("interrupt:{}:{}", session.0, e),
            None => format!("interrupt:{}:null", session.0),
        }
    }

    /// The job-child cutoff inbox key (ADR-091 §4.4).
    #[must_use]
    pub fn job_child_cancel_idempotency_key(
        run: &str,
        step: &str,
        attempt: u32,
        target_epoch: Option<u64>,
    ) -> String {
        match target_epoch {
            Some(epoch) => {
                format!("kian:job:child-cancel:{run}:{step}:{attempt}:{epoch}")
            }
            None => format!("kian:job:child-cancel:{run}:{step}:{attempt}:null"),
        }
    }
}

/// Whether `payload` is **any** reserved control envelope shape
/// (`{"kian": {"type": "control", ...}}`, any action). The public wire
/// refuses it: clients may never mint a control row, even one carrying
/// an action this build does not know.
#[must_use]
pub fn is_reserved_control_shape(payload: &Value) -> bool {
    let Some(obj) = payload.as_object() else {
        return false;
    };
    if obj.len() != 1 {
        return false;
    }
    let Some(inner) = obj.get(ENVELOPE_KEY).and_then(Value::as_object) else {
        return false;
    };
    inner.get("type").and_then(Value::as_str) == Some(CONTROL_TYPE)
}

/// A parsed confirmation intent from a reserved control-envelope row
/// (CONFIRMATION-MODEL §5, ADR-033): one human decision on one pending
/// ask. Pure data — the same intent serializes to the inbox row
/// (envelope), to the `control/confirm` audit event (event payload), and
/// to the `tool/result` provenance that records the applied decision.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfirmIntent {
    /// The pending call this decision answers (`tool/call.content.id`).
    pub call_id: String,
    /// The decision.
    pub decision: ConfirmDecision,
    /// Free-form human reason, or `null`.
    pub reason: Option<String>,
    /// Who answered (operator label), or `null`.
    pub requested_by: Option<String>,
    /// Unix epoch milliseconds at admit time (server-stamped).
    pub answered_at_ms: u64,
    /// The pending call had lapsed under `confirmation.ttl_ms`; the
    /// server transformed the answer into a durable reject so the
    /// session resumes honestly.
    pub expired: bool,
}

/// The closed decision vocabulary of the confirmation plane.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfirmDecision {
    Approve,
    Reject,
}

impl ConfirmDecision {
    /// The wire/event spelling (`approve` | `reject`).
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Approve => "approve",
            Self::Reject => "reject",
        }
    }

    /// Parses the closed vocabulary; anything else is `None`.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "approve" => Some(Self::Approve),
            "reject" => Some(Self::Reject),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EffectAssumption {
    NoEffect,
}

impl EffectAssumption {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NoEffect => "no_effect",
        }
    }

    #[must_use]
    pub fn parse(raw: &str) -> Option<Self> {
        match raw {
            "no_effect" => Some(Self::NoEffect),
            _ => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EffectAssumptionIntent {
    pub run: SessionId,
    pub step: String,
    pub prior_attempt: u32,
    pub assumed: EffectAssumption,
    pub reason: String,
    pub requested_by: Option<String>,
    pub requested_at_ms: u64,
}

impl EffectAssumptionIntent {
    #[must_use]
    pub fn is_action(payload: &Value) -> bool {
        payload
            .as_object()
            .filter(|obj| obj.len() == 1)
            .and_then(|obj| obj.get(ENVELOPE_KEY))
            .and_then(Value::as_object)
            .is_some_and(|inner| {
                inner.get("type").and_then(Value::as_str) == Some(CONTROL_TYPE)
                    && inner.get("action").and_then(Value::as_str) == Some(EFFECT_ASSUMPTION_ACTION)
            })
    }

    pub fn parse(payload: &Value) -> Result<Option<Self>, String> {
        if !Self::is_action(payload) {
            return Ok(None);
        }
        let inner = payload
            .get(ENVELOPE_KEY)
            .and_then(Value::as_object)
            .expect("is_action checked the envelope");
        Self::parse_inner(inner, true).map(Some)
    }

    pub fn from_event_payload(payload: &Value) -> Result<Option<Self>, String> {
        let Some(inner) = payload.as_object() else {
            return Ok(None);
        };
        if inner.get("action").and_then(Value::as_str) != Some(EFFECT_ASSUMPTION_ACTION) {
            return Ok(None);
        }
        Self::parse_inner(inner, false).map(Some)
    }

    fn parse_inner(inner: &serde_json::Map<String, Value>, envelope: bool) -> Result<Self, String> {
        let allowed = [
            "type",
            "action",
            "run",
            "step",
            "prior_attempt",
            "assumed",
            "reason",
            "requested_by",
            "requested_at_ms",
        ];
        if inner.keys().any(|key| !allowed.contains(&key.as_str())) {
            return Err("effect-assumption payload carries an unknown key".to_string());
        }
        let required = [
            "action",
            "run",
            "step",
            "prior_attempt",
            "assumed",
            "reason",
            "requested_at_ms",
        ];
        if required.iter().any(|key| !inner.contains_key(*key)) {
            return Err("effect-assumption payload is missing a required key".to_string());
        }
        if envelope
            && (inner.get("type").and_then(Value::as_str) != Some(CONTROL_TYPE)
                || inner.get("action").and_then(Value::as_str) != Some(EFFECT_ASSUMPTION_ACTION))
        {
            return Err("effect-assumption envelope has invalid discriminators".to_string());
        }
        if !envelope && inner.get("type").is_some() {
            return Err("effect-assumption event payload carries the row envelope".to_string());
        }
        let run = inner
            .get("run")
            .and_then(Value::as_str)
            .and_then(|raw| uuid::Uuid::parse_str(raw).ok())
            .map(SessionId)
            .ok_or_else(|| "effect-assumption run is not a canonical session id".to_string())?;
        let step = inner
            .get("step")
            .and_then(Value::as_str)
            .filter(|step| !step.trim().is_empty())
            .map(str::to_owned)
            .ok_or_else(|| "effect-assumption step is empty".to_string())?;
        let prior_attempt = inner
            .get("prior_attempt")
            .and_then(Value::as_u64)
            .and_then(|attempt| u32::try_from(attempt).ok())
            .filter(|attempt| *attempt > 0)
            .ok_or_else(|| {
                "effect-assumption prior_attempt is not a positive attempt".to_string()
            })?;
        let assumed = inner
            .get("assumed")
            .and_then(Value::as_str)
            .and_then(EffectAssumption::parse)
            .ok_or_else(|| "effect-assumption assumed value is not `no_effect`".to_string())?;
        let reason = inner
            .get("reason")
            .and_then(Value::as_str)
            .filter(|reason| !reason.trim().is_empty())
            .map(str::to_owned)
            .ok_or_else(|| "effect-assumption reason is empty".to_string())?;
        let requested_by = match inner.get("requested_by") {
            None => None,
            Some(Value::String(value)) if !value.trim().is_empty() => Some(value.clone()),
            Some(_) => {
                return Err(
                    "effect-assumption requested_by must be a non-empty string when present"
                        .to_string(),
                );
            }
        };
        let requested_at_ms = inner
            .get("requested_at_ms")
            .and_then(Value::as_u64)
            .ok_or_else(|| "effect-assumption requested_at_ms is not a u64".to_string())?;
        Ok(Self {
            run,
            step,
            prior_attempt,
            assumed,
            reason,
            requested_by,
            requested_at_ms,
        })
    }

    #[must_use]
    pub fn envelope(&self) -> Value {
        let mut inner = self.payload_inner();
        inner.insert("type".into(), json!(CONTROL_TYPE));
        json!({ ENVELOPE_KEY: Value::Object(inner) })
    }

    #[must_use]
    pub fn event_payload(&self) -> Value {
        Value::Object(self.payload_inner())
    }

    fn payload_inner(&self) -> serde_json::Map<String, Value> {
        let mut inner = serde_json::Map::new();
        inner.insert("action".into(), json!(EFFECT_ASSUMPTION_ACTION));
        inner.insert("run".into(), json!(self.run.0.to_string()));
        inner.insert("step".into(), json!(self.step));
        inner.insert("prior_attempt".into(), json!(self.prior_attempt));
        inner.insert("assumed".into(), json!(self.assumed.as_str()));
        inner.insert("reason".into(), json!(self.reason));
        if let Some(requested_by) = &self.requested_by {
            inner.insert("requested_by".into(), json!(requested_by));
        }
        inner.insert("requested_at_ms".into(), json!(self.requested_at_ms));
        inner
    }

    #[must_use]
    pub fn idempotency_key(run: &SessionId, step: &str, prior_attempt: u32) -> String {
        format!("effect-assumption:{}:{step}:{prior_attempt}", run.0)
    }
}

impl ConfirmIntent {
    /// Whether `payload` is the reserved confirmation envelope (a single
    /// `{"kian": {"type": "control", "action": "confirm", ...}}` key).
    #[must_use]
    pub fn is_control_envelope(payload: &Value) -> bool {
        Self::parse(payload).is_some()
    }

    /// Whether `payload` is **any** reserved control envelope shape
    /// (`{"kian": {"type": "control", ...}}`, any action). Used by the
    /// public wire guard: clients may never mint a control row, even one
    /// carrying an action this build does not know.
    #[must_use]
    pub fn is_reserved_shape(payload: &Value) -> bool {
        is_reserved_control_shape(payload)
    }

    /// Parses the reserved confirmation envelope, or `None` for any
    /// payload that is not exactly it. A missing/empty `call_id` or an
    /// unknown decision is not an envelope (it stays plain content).
    #[must_use]
    pub fn parse(payload: &Value) -> Option<Self> {
        let obj = payload.as_object()?;
        if obj.len() != 1 {
            return None;
        }
        let inner = obj.get(ENVELOPE_KEY)?.as_object()?;
        if inner.get("type").and_then(Value::as_str) != Some(CONTROL_TYPE)
            || inner.get("action").and_then(Value::as_str) != Some(CONFIRM_ACTION)
        {
            return None;
        }
        let call_id = inner
            .get("call_id")
            .and_then(Value::as_str)
            .filter(|s| !s.is_empty())?
            .to_owned();
        let decision = inner
            .get("decision")
            .and_then(Value::as_str)
            .and_then(ConfirmDecision::parse)?;
        Some(Self {
            call_id,
            decision,
            reason: inner
                .get("reason")
                .and_then(Value::as_str)
                .map(str::to_owned),
            requested_by: inner
                .get("requested_by")
                .and_then(Value::as_str)
                .map(str::to_owned),
            answered_at_ms: inner
                .get("answered_at_ms")
                .and_then(Value::as_u64)
                .unwrap_or(0),
            expired: inner.get("expired").and_then(Value::as_bool) == Some(true),
        })
    }

    /// Parses the `control/confirm` **event** payload (the inner object,
    /// without the row envelope wrapper) — the audit record the drain
    /// appends on consumption.
    #[must_use]
    pub fn from_event_payload(payload: &Value) -> Option<Self> {
        let inner = payload.as_object()?;
        if inner.get("action").and_then(Value::as_str) != Some(CONFIRM_ACTION) {
            return None;
        }
        let call_id = inner
            .get("call_id")
            .and_then(Value::as_str)
            .filter(|s| !s.is_empty())?
            .to_owned();
        let decision = inner
            .get("decision")
            .and_then(Value::as_str)
            .and_then(ConfirmDecision::parse)?;
        Some(Self {
            call_id,
            decision,
            reason: inner
                .get("reason")
                .and_then(Value::as_str)
                .map(str::to_owned),
            requested_by: inner
                .get("requested_by")
                .and_then(Value::as_str)
                .map(str::to_owned),
            answered_at_ms: inner
                .get("answered_at_ms")
                .and_then(Value::as_u64)
                .unwrap_or(0),
            expired: inner.get("expired").and_then(Value::as_bool) == Some(true),
        })
    }

    /// The reserved envelope payload for this intent (the inbox row's
    /// `payload`).
    #[must_use]
    pub fn envelope(&self) -> Value {
        let mut inner = json!({
            "type": CONTROL_TYPE,
            "action": CONFIRM_ACTION,
            "call_id": self.call_id,
            "decision": self.decision.as_str(),
            "reason": self.reason,
            "requested_by": self.requested_by,
            "answered_at_ms": self.answered_at_ms,
        });
        if self.expired {
            inner["expired"] = json!(true);
        }
        json!({ ENVELOPE_KEY: inner })
    }

    /// The `control/confirm` event payload for this intent.
    #[must_use]
    pub fn event_payload(&self) -> Value {
        let mut payload = json!({
            "action": CONFIRM_ACTION,
            "call_id": self.call_id,
            "decision": self.decision.as_str(),
            "reason": self.reason,
            "requested_by": self.requested_by,
            "answered_at_ms": self.answered_at_ms,
        });
        if self.expired {
            payload["expired"] = json!(true);
        }
        payload
    }

    /// The inbox idempotency key: repeated answers for the same call
    /// dedupe to exactly one row.
    #[must_use]
    pub fn idempotency_key(session: &SessionId, call_id: &str) -> String {
        format!("confirm:{}:{}", session.0, call_id)
    }
}

/// A parsed budget-raise intent from a reserved control-envelope row
/// (ADR-055): one durable addition to the session's token/wall-clock
/// allowance. Pure data — the same intent serializes to the inbox row
/// (envelope) and to the `budget/raised` audit event payload, so the event
/// reproduces exactly what was requested.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BudgetIntent {
    /// Tokens added to the session budget.
    pub tokens: Option<u64>,
    /// Wall-clock milliseconds added to the session budget (recorded, not
    /// enforced while a drain is idle — ADR-055).
    pub wall_clock_ms: Option<u64>,
    /// Free-form operator reason, or `null`.
    pub reason: Option<String>,
    /// Who requested the raise (operator/replica identity), or `null`.
    pub requested_by: Option<String>,
    /// Unix epoch milliseconds at admit time.
    pub requested_at_ms: u64,
}

impl BudgetIntent {
    /// Whether `payload` is the reserved budget envelope (a single
    /// `{"kian": {"type": "control", "action": "budget", ...}}` key).
    #[must_use]
    pub fn is_control_envelope(payload: &Value) -> bool {
        Self::parse(payload).is_some()
    }

    /// Parses the reserved budget envelope, or `None` for any payload that
    /// is not exactly it. Omitted quantities parse as `None`; the engine
    /// validates "at least one positive amount" before minting a row.
    #[must_use]
    pub fn parse(payload: &Value) -> Option<Self> {
        let obj = payload.as_object()?;
        if obj.len() != 1 {
            return None;
        }
        let inner = obj.get(ENVELOPE_KEY)?.as_object()?;
        if inner.get("type").and_then(Value::as_str) != Some(CONTROL_TYPE)
            || inner.get("action").and_then(Value::as_str) != Some(BUDGET_ACTION)
        {
            return None;
        }
        Some(Self {
            tokens: inner.get("tokens").and_then(Value::as_u64),
            wall_clock_ms: inner.get("wall_clock_ms").and_then(Value::as_u64),
            reason: inner
                .get("reason")
                .and_then(Value::as_str)
                .map(str::to_owned),
            requested_by: inner
                .get("requested_by")
                .and_then(Value::as_str)
                .map(str::to_owned),
            requested_at_ms: inner
                .get("requested_at_ms")
                .and_then(Value::as_u64)
                .unwrap_or(0),
        })
    }

    /// The reserved envelope payload for this intent (the inbox row's
    /// `payload`).
    #[must_use]
    pub fn envelope(&self) -> Value {
        let mut inner = json!({
            "type": CONTROL_TYPE,
            "action": BUDGET_ACTION,
            "requested_at_ms": self.requested_at_ms,
        });
        let map = inner.as_object_mut().expect("literal object");
        map.insert(
            "tokens".into(),
            self.tokens.map_or(Value::Null, |tokens| json!(tokens)),
        );
        map.insert(
            "wall_clock_ms".into(),
            self.wall_clock_ms.map_or(Value::Null, |ms| json!(ms)),
        );
        map.insert(
            "reason".into(),
            self.reason
                .as_ref()
                .map_or(Value::Null, |reason| json!(reason)),
        );
        map.insert(
            "requested_by".into(),
            self.requested_by
                .as_ref()
                .map_or(Value::Null, |by| json!(by)),
        );
        json!({ ENVELOPE_KEY: inner })
    }

    /// The `budget/raised` event payload for this intent.
    #[must_use]
    pub fn event_payload(&self) -> Value {
        let mut payload = json!({
            "action": BUDGET_ACTION,
            "requested_at_ms": self.requested_at_ms,
        });
        let map = payload.as_object_mut().expect("literal object");
        if let Some(tokens) = self.tokens {
            map.insert("tokens".into(), json!(tokens));
        }
        if let Some(ms) = self.wall_clock_ms {
            map.insert("wall_clock_ms".into(), json!(ms));
        }
        map.insert(
            "reason".into(),
            self.reason
                .as_ref()
                .map_or(Value::Null, |reason| json!(reason)),
        );
        map.insert(
            "requested_by".into(),
            self.requested_by
                .as_ref()
                .map_or(Value::Null, |by| json!(by)),
        );
        payload
    }

    /// The fallback inbox idempotency key: a caller-supplied key wins;
    /// this one dedupes an exact replay of the same amount at the same
    /// millisecond.
    #[must_use]
    pub fn idempotency_key(
        session: &SessionId,
        tokens: Option<u64>,
        wall_clock_ms: Option<u64>,
        requested_at_ms: u64,
    ) -> String {
        format!(
            "budget:{}:{}:{}:{}",
            session.0,
            tokens.unwrap_or(0),
            wall_clock_ms.unwrap_or(0),
            requested_at_ms
        )
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;
    use uuid::Uuid;

    use super::{
        BudgetIntent, ConfirmDecision, ConfirmIntent, EffectAssumption, EffectAssumptionIntent,
        InterruptIntent,
    };
    use crate::model::SessionId;

    fn intent() -> InterruptIntent {
        InterruptIntent {
            reason: Some("stop the deploy".into()),
            requested_by: Some("replica-a".into()),
            requested_at_ms: 1_762_000_000_000,
            target_epoch: Some(3),
            terminal: false,
            cause: None,
        }
    }

    /// The envelope is exactly the reserved single-key shape and parses
    /// back to the same intent.
    #[test]
    fn envelope_round_trips_through_parse() {
        let i = intent();
        let envelope = i.envelope();
        assert_eq!(
            envelope,
            json!({
                "kian": {
                    "type": "control",
                    "action": "interrupt",
                    "reason": "stop the deploy",
                    "requested_by": "replica-a",
                    "requested_at_ms": 1_762_000_000_000_u64,
                    "target_epoch": 3
                }
            })
        );
        assert_eq!(InterruptIntent::parse(&envelope), Some(i));
        assert!(InterruptIntent::is_control_envelope(&envelope));
    }

    /// Null fields survive the round trip as nulls; a null target epoch
    /// (unreadable stream at admit) stays null.
    #[test]
    fn null_fields_round_trip() {
        let i = InterruptIntent {
            reason: None,
            requested_by: None,
            requested_at_ms: 7,
            target_epoch: None,
            terminal: false,
            cause: None,
        };
        assert_eq!(InterruptIntent::parse(&i.envelope()), Some(i));
    }

    /// Omitted fields default honestly — a writer that sends only the
    /// discriminators still parses.
    #[test]
    fn minimal_envelope_parses_with_defaults() {
        let minimal = json!({"kian": {"type": "control", "action": "interrupt"}});
        assert_eq!(
            InterruptIntent::parse(&minimal),
            Some(InterruptIntent {
                reason: None,
                requested_by: None,
                requested_at_ms: 0,
                target_epoch: None,
                terminal: false,
                cause: None,
            })
        );
    }

    /// Anything that is not exactly the reserved envelope is plain
    /// content: extra top-level keys, a non-control type, a non-interrupt
    /// action, a bare `kian` string, the steer wrapper, the spill
    /// envelope.
    #[test]
    fn only_the_exact_reserved_shape_is_an_envelope() {
        for payload in [
            json!({"kian": {"type": "control", "action": "interrupt"}, "extra": 1}),
            json!({"kian": {"type": "user", "action": "interrupt"}}),
            json!({"kian": {"type": "control", "action": "cancel"}}),
            json!({"kian": "not an object"}),
            json!({"synthetic": true, "content": "steer"}),
            json!({"content": "x", "spill": "y"}),
            json!("plain string"),
            json!({"role": "user", "content": "hi"}),
        ] {
            assert!(
                !InterruptIntent::is_control_envelope(&payload),
                "{payload} must be plain content"
            );
        }
    }

    /// The event payload carries the intent verbatim; `stale` rides only
    /// when set.
    #[test]
    fn event_payload_shape_and_stale_marker() {
        let live = intent().event_payload(false);
        assert_eq!(
            live,
            json!({
                "action": "interrupt",
                "reason": "stop the deploy",
                "requested_by": "replica-a",
                "requested_at_ms": 1_762_000_000_000_u64,
                "target_epoch": 3
            })
        );
        assert!(live.get("stale").is_none());
        let stale = intent().event_payload(true);
        assert_eq!(stale.get("stale"), Some(&json!(true)));
        // Everything else is unchanged by the marker.
        let mut without = stale.clone();
        without.as_object_mut().unwrap().remove("stale");
        assert_eq!(without, live);
    }

    /// The idempotency key is stable per (session, epoch) and spells a
    /// null target honestly.
    #[test]
    fn idempotency_key_is_deterministic() {
        let sid = SessionId(Uuid::nil());
        assert_eq!(
            InterruptIntent::idempotency_key(&sid, Some(3)),
            format!("interrupt:{}:3", sid.0)
        );
        assert_eq!(
            InterruptIntent::idempotency_key(&sid, None),
            format!("interrupt:{}:null", sid.0)
        );
        assert_eq!(
            InterruptIntent::job_child_cancel_idempotency_key(
                "digest@manual:T1",
                "fetch",
                2,
                Some(9),
            ),
            "kian:job:child-cancel:digest@manual:T1:fetch:2:9"
        );
        assert_ne!(
            InterruptIntent::job_child_cancel_idempotency_key(
                "digest@manual:T1",
                "fetch",
                2,
                Some(9),
            ),
            InterruptIntent::idempotency_key(&sid, Some(9))
        );
    }

    #[test]
    fn terminal_job_child_cancel_round_trips_and_keeps_legacy_bytes() {
        let legacy = intent();
        assert!(legacy.envelope()["kian"].get("terminal").is_none());
        assert!(legacy.envelope()["kian"].get("cause").is_none());
        assert!(legacy.event_payload(false).get("terminal").is_none());
        assert!(legacy.event_payload(false).get("cause").is_none());

        let terminal = InterruptIntent {
            reason: Some("step timed out".into()),
            requested_by: Some("job:digest@manual:T1:fetch:1".into()),
            requested_at_ms: 17,
            target_epoch: Some(4),
            terminal: true,
            cause: Some(InterruptIntent::JOB_CHILD_CANCEL.to_string()),
        };
        assert_eq!(terminal.validate(), Ok(()));
        assert_eq!(
            terminal.envelope()["kian"],
            json!({
                "type": "control",
                "action": "interrupt",
                "reason": "step timed out",
                "requested_by": "job:digest@manual:T1:fetch:1",
                "requested_at_ms": 17,
                "target_epoch": 4,
                "terminal": true,
                "cause": "job_child_cancel"
            })
        );
        assert_eq!(
            InterruptIntent::parse(&terminal.envelope()),
            Some(terminal.clone())
        );
        assert_eq!(
            InterruptIntent::parse(&json!({
                "kian": {
                    "type": "control",
                    "action": "interrupt",
                    "terminal": true,
                    "cause": "unknown"
                }
            })),
            None
        );
        assert_eq!(
            InterruptIntent::parse(&json!({
                "kian": {
                    "type": "control",
                    "action": "interrupt",
                    "terminal": false,
                    "cause": null
                }
            })),
            None
        );
        assert_eq!(
            InterruptIntent::parse(&json!({
                "kian": {
                    "type": "control",
                    "action": "interrupt",
                    "cause": "job_child_cancel"
                }
            })),
            None
        );
        assert_eq!(
            InterruptIntent::parse(&json!({
                "kian": {
                    "type": "control",
                    "action": "interrupt",
                    "terminal": false,
                    "cause": "job_child_cancel"
                }
            })),
            None
        );
        assert_eq!(
            InterruptIntent::parse(&json!({
                "kian": {
                    "type": "control",
                    "action": "interrupt",
                    "terminal": true
                }
            })),
            None
        );

        let bad = InterruptIntent {
            terminal: true,
            cause: None,
            ..terminal.clone()
        };
        assert!(bad.validate().is_err());
        let bad = InterruptIntent {
            terminal: false,
            cause: Some(InterruptIntent::JOB_CHILD_CANCEL.to_string()),
            ..terminal
        };
        assert!(bad.validate().is_err());
    }

    /// The confirmation envelope round-trips; the reserved-shape guard
    /// also recognizes the interrupt shape and refuses nothing else.
    #[test]
    fn confirm_envelope_round_trips_and_reserved_shape_covers_both_actions() {
        let i = ConfirmIntent {
            call_id: "call-1".into(),
            decision: ConfirmDecision::Approve,
            reason: Some("looks right".into()),
            requested_by: Some("alice".into()),
            answered_at_ms: 1_762_000_000_000,
            expired: false,
        };
        let envelope = i.envelope();
        assert_eq!(
            envelope,
            json!({"kian": {"type": "control", "action": "confirm", "call_id": "call-1",
                            "decision": "approve", "reason": "looks right",
                            "requested_by": "alice", "answered_at_ms": 1_762_000_000_000_u64}})
        );
        assert_eq!(ConfirmIntent::parse(&envelope), Some(i));
        assert!(ConfirmIntent::is_control_envelope(&envelope));
        assert!(ConfirmIntent::is_reserved_shape(&envelope));

        let expired = ConfirmIntent {
            expired: true,
            decision: ConfirmDecision::Reject,
            reason: None,
            requested_by: None,
            answered_at_ms: 5,
            call_id: "call-2".into(),
        };
        assert_eq!(
            ConfirmIntent::parse(&expired.envelope()),
            Some(expired.clone())
        );
        assert_eq!(expired.event_payload()["expired"], json!(true));
        assert_eq!(expired.event_payload()["decision"], json!("reject"));

        // The interrupt envelope is a reserved control shape too (the
        // wire guard is action-agnostic), but not a confirmation.
        let interrupt = InterruptIntent {
            reason: None,
            requested_by: None,
            requested_at_ms: 1,
            target_epoch: None,
            terminal: false,
            cause: None,
        }
        .envelope();
        assert!(ConfirmIntent::is_reserved_shape(&interrupt));
        assert!(!ConfirmIntent::is_control_envelope(&interrupt));

        for plain in [
            json!({"kian": {"type": "control", "action": "confirm"}}),
            json!({"kian": {"type": "control", "action": "confirm", "call_id": "c",
                            "decision": "maybe"}}),
            json!({"kian": {"type": "async_result", "job_id": "j"}}),
            json!({"kian": {"type": "control", "action": "confirm"}, "extra": 1}),
            json!({"kian": "string"}),
        ] {
            assert!(!ConfirmIntent::is_control_envelope(&plain), "{plain}");
        }
        assert!(!ConfirmIntent::is_reserved_shape(
            &json!({"kian": {"type": "async_result"}})
        ));
        assert!(!ConfirmIntent::is_reserved_shape(&json!("plain")));
    }

    /// The idempotency key is stable per (session, call).
    #[test]
    fn confirm_idempotency_key_is_deterministic() {
        let sid = SessionId(Uuid::nil());
        assert_eq!(
            ConfirmIntent::idempotency_key(&sid, "call-1"),
            format!("confirm:{}:call-1", sid.0)
        );
    }

    #[test]
    fn effect_assumption_round_trips_with_the_exact_additive_payload() {
        let run = SessionId(Uuid::from_u128(7));
        let intent = EffectAssumptionIntent {
            run,
            step: "publish".into(),
            prior_attempt: 2,
            assumed: EffectAssumption::NoEffect,
            reason: "checked the remote branch".into(),
            requested_by: Some("alice".into()),
            requested_at_ms: 1_762_000_000_123,
        };
        assert_eq!(
            intent.envelope(),
            json!({
                "kian": {
                    "type": "control",
                    "action": "effect-assumption",
                    "run": run.0.to_string(),
                    "step": "publish",
                    "prior_attempt": 2,
                    "assumed": "no_effect",
                    "reason": "checked the remote branch",
                    "requested_by": "alice",
                    "requested_at_ms": 1_762_000_000_123_u64
                }
            })
        );
        assert_eq!(
            intent.event_payload(),
            json!({
                "action": "effect-assumption",
                "run": run.0.to_string(),
                "step": "publish",
                "prior_attempt": 2,
                "assumed": "no_effect",
                "reason": "checked the remote branch",
                "requested_by": "alice",
                "requested_at_ms": 1_762_000_000_123_u64
            })
        );
        assert_eq!(
            EffectAssumptionIntent::parse(&intent.envelope()),
            Ok(Some(intent.clone()))
        );
        assert_eq!(
            EffectAssumptionIntent::from_event_payload(&intent.event_payload()),
            Ok(Some(intent.clone()))
        );
        assert_eq!(
            EffectAssumptionIntent::idempotency_key(&run, "publish", 2),
            format!("effect-assumption:{}:publish:2", run.0)
        );

        let without_requester = EffectAssumptionIntent {
            requested_by: None,
            ..intent
        };
        assert!(
            without_requester
                .event_payload()
                .get("requested_by")
                .is_none()
        );
        assert_eq!(
            EffectAssumptionIntent::parse(&without_requester.envelope()),
            Ok(Some(without_requester))
        );
    }

    #[test]
    fn malformed_effect_assumptions_are_refused_not_plain_content() {
        let run = Uuid::nil().to_string();
        let valid = json!({
            "kian": {
                "type": "control",
                "action": "effect-assumption",
                "run": run,
                "step": "publish",
                "prior_attempt": 1,
                "assumed": "no_effect",
                "reason": "checked",
                "requested_at_ms": 1
            }
        });
        assert!(EffectAssumptionIntent::parse(&valid).unwrap().is_some());

        for malformed in [
            json!({"kian": {"type": "control", "action": "effect-assumption"}}),
            json!({
                "kian": {
                    "type": "control",
                    "action": "effect-assumption",
                    "run": "not-a-session",
                    "step": "publish",
                    "prior_attempt": 1,
                    "assumed": "no_effect",
                    "reason": "checked",
                    "requested_at_ms": 1
                }
            }),
            json!({
                "kian": {
                    "type": "control",
                    "action": "effect-assumption",
                    "run": run,
                    "step": "",
                    "prior_attempt": 1,
                    "assumed": "no_effect",
                    "reason": "checked",
                    "requested_at_ms": 1
                }
            }),
            json!({
                "kian": {
                    "type": "control",
                    "action": "effect-assumption",
                    "run": run,
                    "step": "publish",
                    "prior_attempt": 0,
                    "assumed": "no_effect",
                    "reason": "checked",
                    "requested_at_ms": 1
                }
            }),
            json!({
                "kian": {
                    "type": "control",
                    "action": "effect-assumption",
                    "run": run,
                    "step": "publish",
                    "prior_attempt": 1,
                    "assumed": "effect_landed",
                    "reason": "checked",
                    "requested_at_ms": 1
                }
            }),
            json!({
                "kian": {
                    "type": "control",
                    "action": "effect-assumption",
                    "run": run,
                    "step": "publish",
                    "prior_attempt": 1,
                    "assumed": "no_effect",
                    "reason": " ",
                    "requested_at_ms": 1
                }
            }),
            json!({
                "kian": {
                    "type": "control",
                    "action": "effect-assumption",
                    "run": run,
                    "step": "publish",
                    "prior_attempt": 1,
                    "assumed": "no_effect",
                    "reason": "checked",
                    "requested_by": null,
                    "requested_at_ms": 1
                }
            }),
            json!({
                "kian": {
                    "type": "control",
                    "action": "effect-assumption",
                    "run": run,
                    "step": "publish",
                    "prior_attempt": 1,
                    "assumed": "no_effect",
                    "reason": "checked",
                    "requested_at_ms": 1,
                    "extra": true
                }
            }),
        ] {
            assert!(
                EffectAssumptionIntent::parse(&malformed).is_err(),
                "{malformed}"
            );
            assert!(EffectAssumptionIntent::is_action(&malformed));
        }

        let confirm = json!({
            "kian": {
                "type": "control",
                "action": "confirm",
                "call_id": "c",
                "decision": "approve"
            }
        });
        assert_eq!(EffectAssumptionIntent::parse(&confirm), Ok(None));
    }

    #[test]
    fn effect_assumption_event_parser_rejects_envelope_bytes_and_wrong_actions() {
        let envelope = json!({
            "kian": {
                "type": "control",
                "action": "effect-assumption",
                "run": Uuid::nil().to_string(),
                "step": "publish",
                "prior_attempt": 1,
                "assumed": "no_effect",
                "reason": "checked",
                "requested_at_ms": 1
            }
        });
        assert_eq!(
            EffectAssumptionIntent::from_event_payload(&envelope),
            Ok(None)
        );
        assert_eq!(
            EffectAssumptionIntent::from_event_payload(&json!({
                "action": "confirm",
                "call_id": "c",
                "decision": "approve"
            })),
            Ok(None)
        );
    }

    /// The budget envelope round-trips, carries nulls honestly, and the
    /// action-agnostic reserved-shape guard recognizes it.
    #[test]
    fn budget_envelope_round_trips_and_is_a_reserved_control_shape() {
        let i = BudgetIntent {
            tokens: Some(2_000_000),
            wall_clock_ms: Some(60_000),
            reason: Some("long-horizon task".into()),
            requested_by: Some("alice".into()),
            requested_at_ms: 1_762_000_000_000,
        };
        let envelope = i.envelope();
        assert_eq!(
            envelope,
            json!({"kian": {"type": "control", "action": "budget",
                            "tokens": 2_000_000_u64, "wall_clock_ms": 60_000_u64,
                            "reason": "long-horizon task", "requested_by": "alice",
                            "requested_at_ms": 1_762_000_000_000_u64}})
        );
        assert_eq!(BudgetIntent::parse(&envelope), Some(i.clone()));
        assert!(BudgetIntent::is_control_envelope(&envelope));
        assert!(ConfirmIntent::is_reserved_shape(&envelope));

        let minimal = json!({"kian": {"type": "control", "action": "budget"}});
        assert_eq!(
            BudgetIntent::parse(&minimal),
            Some(BudgetIntent {
                tokens: None,
                wall_clock_ms: None,
                reason: None,
                requested_by: None,
                requested_at_ms: 0,
            })
        );
        // The event payload omits absent quantities instead of spelling
        // them as null.
        let event = i.event_payload();
        assert_eq!(event["action"], json!("budget"));
        assert_eq!(event["tokens"], json!(2_000_000_u64));
        assert_eq!(event.get("stale"), None);
        assert_eq!(
            BudgetIntent::parse(&json!({"kian": {"type": "control", "action": "cancel"}})),
            None
        );
        assert!(!BudgetIntent::is_control_envelope(
            &json!({"kian": {"type": "control", "action": "interrupt"}})
        ));
    }

    /// The fallback idempotency key dedupes an exact amount replay.
    #[test]
    fn budget_idempotency_key_is_deterministic() {
        let sid = SessionId(Uuid::nil());
        assert_eq!(
            BudgetIntent::idempotency_key(&sid, Some(10), Some(20), 30),
            format!("budget:{}:10:20:30", sid.0)
        );
        assert_eq!(
            BudgetIntent::idempotency_key(&sid, None, None, 0),
            format!("budget:{}:0:0:0", sid.0)
        );
    }
}