car-ir 0.52.0

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

use crate::reversibility::{Compensation, Reversibility};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use uuid::Uuid;

/// What kind of action this is.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ActionType {
    ToolCall,
    StateWrite,
    StateRead,
    Assertion,
}

/// What to do when an action fails.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum FailureBehavior {
    #[default]
    Abort,
    Retry,
    Skip,
}

/// Lifecycle status of an action.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ActionStatus {
    Proposed,
    Validated,
    Rejected,
    Executing,
    Succeeded,
    Failed,
    Skipped,
}

/// A condition that must hold before an action can execute.
///
/// Valid operators: `eq`, `neq`, `exists`, `not_exists`, `gt`, `lt`, `gte`, `lte`, `contains`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Precondition {
    pub key: String,
    /// Comparison operator. One of: eq, neq, exists, not_exists, gt, lt, gte, lte, contains.
    #[serde(default = "default_operator")]
    pub operator: String,
    #[serde(default)]
    pub value: Value,
    #[serde(default)]
    pub description: String,
}

fn default_operator() -> String {
    "eq".to_string()
}

/// Generate a short unique ID (12 hex chars from UUIDv4).
fn short_id() -> String {
    Uuid::new_v4().simple().to_string()[..12].to_string()
}

/// A single unit of agent intent compiled into IR.
///
/// This is the core primitive. Models produce these (directly or via compilation),
/// and the runtime validates and executes them.
///
/// # Construction
///
/// `#[non_exhaustive]`, so from outside `car-ir` this must be built with
/// [`Action::new`] (or [`Action::tool_call`] / [`Action::state_write`] /
/// [`Action::state_read`]) and then mutated — struct-literal syntax, including
/// functional update (`..other`), is rejected in other crates.
///
/// That is the point. `car-ir` is published on crates.io and re-exported by
/// `car-runtime`, so while the *wire* format tolerates new fields (they carry
/// `#[serde(default)]`, and a proposal authored before a field existed still
/// deserializes), the *Rust API* previously did not: every added field was a
/// source-breaking `error[E0063]` for every out-of-tree consumer building an
/// `Action` literal, and cost ~20 files of churn in-tree the last time it
/// happened. Adding a field is now backwards-compatible in both directions.
/// Parslee-ai/car#855.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Action {
    #[serde(default = "short_id")]
    pub id: String,

    #[serde(rename = "type")]
    pub action_type: ActionType,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool: Option<String>,

    #[serde(default)]
    pub parameters: HashMap<String, Value>,

    #[serde(default)]
    pub preconditions: Vec<Precondition>,

    #[serde(default)]
    pub expected_effects: HashMap<String, Value>,

    #[serde(default)]
    pub state_dependencies: Vec<String>,

    /// Explicit transactional **read set** — the state keys this action
    /// reads (survey §5.2.4: "each action should declare its read set,
    /// write set, assumptions, version dependencies"). When empty, the
    /// effective read set falls back to [`Action::effective_read_set`]
    /// (derived from `state_dependencies` + assumption keys), so existing
    /// proposals keep working. Used to detect read-write conflicts and
    /// stale reads across concurrent actions/agents.
    #[serde(default)]
    pub read_set: Vec<String>,

    /// Explicit transactional **write set** — the state keys this action
    /// writes. When empty, falls back to [`Action::effective_write_set`]
    /// (derived from `expected_effects` + a `StateWrite`'s `key` param).
    #[serde(default)]
    pub write_set: Vec<String>,

    /// Assumptions this action makes about shared state it did not itself
    /// produce — the basis for belief-divergence / stale-read detection in
    /// a multi-agent transaction (§5.2.4). An assumption can pin an
    /// expected value, a version the action read at, or both.
    #[serde(default)]
    pub assumptions: Vec<StateAssumption>,

    /// How a `ToolCall` runs: `one_shot` (default — dispatch awaits the
    /// result inline), or a detached mode (`streaming` / `long_running`)
    /// where dispatch *starts* the tool, returns a [`crate::ToolHandle`]
    /// as the action's output, and the DAG proceeds without blocking on
    /// completion. Chunks/status are consumed via the handle (C2).
    /// Ignored for non-ToolCall actions.
    #[serde(default)]
    pub invocation_mode: crate::tool_stream::ToolInvocationMode,

    /// The rollback contract for this action's effects — **can this be
    /// undone?** Orthogonal to `car_policy::PermissionTier`, which answers the
    /// separate question of *who may authorize this*; the two were conflated
    /// in a single ladder until this field existed. See [`Reversibility`] for
    /// the axis, and for why the `#[serde(default)]` is the conservative
    /// [`Reversibility::Irreversible`] rather than the quiet-failing
    /// [`Reversibility::Reversible`].
    ///
    /// Nothing in the runtime gates on this yet — it is typed and audited, not
    /// enforced (see the [`reversibility`](crate::reversibility) module docs).
    #[serde(default)]
    pub reversibility: Reversibility,

    /// How to undo this action once it has already run. Meaningful only when
    /// `reversibility` is [`Reversibility::Compensable`]: a reversible action
    /// is undone by restoring its scope, and an irreversible one cannot be
    /// undone at all.
    ///
    /// The pairing is not enforced by the type system — `Compensable` is a
    /// bare variant, not `Compensable { compensation }`, so
    /// `Compensable` + `None` is representable. That is a deliberate trade,
    /// argued in [`Compensation`]'s docs: making the state unrepresentable
    /// costs `Reversibility` its plain C-like shape, which every FFI surface
    /// mirrors as a string enum. [`Action::missing_required_compensation`] is
    /// the check that stands in for the type.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compensation: Option<Compensation>,

    #[serde(default)]
    pub idempotent: bool,

    #[serde(default = "default_max_retries")]
    pub max_retries: u32,

    #[serde(default)]
    pub failure_behavior: FailureBehavior,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,

    #[serde(default)]
    pub metadata: HashMap<String, Value>,
}

fn default_max_retries() -> u32 {
    3
}

/// An assumption an action makes about shared state it did not produce —
/// the unit of belief-divergence detection in a multi-agent transaction
/// (survey "Code as Agent Harness" §5.2.4). Synchronizing artifacts is not
/// enough; agents must also agree on *assumptions*. An action that planned
/// against `config@v3` should be flagged when `config` has since advanced
/// to `v4`, even if no file diff conflicts.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StateAssumption {
    /// The state key the assumption is about.
    pub key: String,
    /// The value the action expects `key` to hold, if it pinned one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expected_value: Option<Value>,
    /// The version of `key` the action read when it planned, if known.
    /// Compared against the current version to detect stale reads.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub read_version: Option<u64>,
}

impl Action {
    /// A new action of `action_type`, with every optional field at its
    /// default and a freshly generated [`Action::id`].
    ///
    /// **This is the only way to build an `Action` from outside `car-ir`.**
    /// The struct is `#[non_exhaustive]` (see its docs), so struct-literal
    /// syntax — including functional update, `..other` — is rejected in other
    /// crates. Set the fields you need afterwards; they are all public:
    ///
    /// ```
    /// # use car_ir::{Action, ActionType};
    /// let mut a = Action::new(ActionType::ToolCall);
    /// a.tool = Some("deploy".into());
    /// a.idempotent = true;
    /// ```
    ///
    /// There is deliberately **no** `Default for Action`. An action's type
    /// decides what the rest of it means, and defaulting it would let
    /// `Action::default()` produce a `ToolCall` naming no tool — a value that
    /// is invalid the moment it exists, and that the validator would have to
    /// reject. Requiring the type at construction makes that unrepresentable.
    pub fn new(action_type: ActionType) -> Self {
        Self {
            id: short_id(),
            action_type,
            tool: None,
            parameters: HashMap::new(),
            preconditions: Vec::new(),
            expected_effects: HashMap::new(),
            state_dependencies: Vec::new(),
            read_set: Vec::new(),
            write_set: Vec::new(),
            assumptions: Vec::new(),
            invocation_mode: crate::tool_stream::ToolInvocationMode::default(),
            reversibility: Reversibility::default(),
            compensation: None,
            idempotent: false,
            max_retries: default_max_retries(),
            failure_behavior: FailureBehavior::default(),
            timeout_ms: None,
            metadata: HashMap::new(),
        }
    }

    /// An [`ActionType::ToolCall`] naming `tool`.
    pub fn tool_call(tool: impl Into<String>) -> Self {
        let mut a = Self::new(ActionType::ToolCall);
        a.tool = Some(tool.into());
        a
    }

    /// An [`ActionType::StateWrite`] of `value` to `key`, carrying both the
    /// `key`/`value` parameters the executor reads and the `expected_effects`
    /// entry the static verifier reads.
    pub fn state_write(key: impl Into<String>, value: Value) -> Self {
        let key = key.into();
        let mut a = Self::new(ActionType::StateWrite);
        a.parameters
            .insert("key".to_string(), Value::String(key.clone()));
        a.parameters.insert("value".to_string(), value.clone());
        a.expected_effects.insert(key, value);
        a
    }

    /// An [`ActionType::StateRead`] of `key`.
    pub fn state_read(key: impl Into<String>) -> Self {
        let mut a = Self::new(ActionType::StateRead);
        a.parameters
            .insert("key".to_string(), Value::String(key.into()));
        a
    }

    /// Replace the generated [`Action::id`]. Chainable, so a caller that cares
    /// about the id can still write one expression.
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = id.into();
        self
    }

    /// Set one parameter. Chainable.
    pub fn with_param(mut self, key: impl Into<String>, value: Value) -> Self {
        self.parameters.insert(key.into(), value);
        self
    }

    /// The keys this action writes — the **union** of the explicit
    /// `write_set` with the keys derived from `expected_effects` and a
    /// `StateWrite` action's `key` parameter. Union, not replacement: a
    /// partial `write_set` must never *narrow* the real write footprint, or
    /// a conflict on an unlisted side-effect key would go undetected (a
    /// false negative in the soundness-critical path). Proposals authored
    /// before the transactional fields existed still participate via the
    /// derived keys.
    pub fn effective_write_set(&self) -> Vec<String> {
        let mut keys: Vec<String> = self.write_set.clone();
        let push = |k: String, keys: &mut Vec<String>| {
            if !keys.contains(&k) {
                keys.push(k);
            }
        };
        for k in self.expected_effects.keys() {
            push(k.clone(), &mut keys);
        }
        if self.action_type == ActionType::StateWrite {
            if let Some(k) = self.parameters.get("key").and_then(|v| v.as_str()) {
                push(k.to_string(), &mut keys);
            }
        }
        keys
    }

    /// The keys this action reads — the **union** of the explicit `read_set`
    /// with `state_dependencies`, assumption keys, and a `StateRead`
    /// action's `key` parameter. Union for the same soundness reason as
    /// [`Action::effective_write_set`].
    pub fn effective_read_set(&self) -> Vec<String> {
        let mut keys: Vec<String> = self.read_set.clone();
        let push = |k: String, keys: &mut Vec<String>| {
            if !keys.contains(&k) {
                keys.push(k);
            }
        };
        for k in &self.state_dependencies {
            push(k.clone(), &mut keys);
        }
        for a in &self.assumptions {
            push(a.key.clone(), &mut keys);
        }
        if self.action_type == ActionType::StateRead {
            if let Some(k) = self.parameters.get("key").and_then(|v| v.as_str()) {
                push(k.to_string(), &mut keys);
            }
        }
        keys
    }

    /// Whether this action claims [`Reversibility::Compensable`] but declares
    /// no [`Action::compensation`] — the one incoherent combination the enum
    /// could not exclude by construction (see [`Compensation`] for why the
    /// compensation is a sibling field rather than a variant payload).
    ///
    /// It is a *check*, not a guarantee: it catches the missing declaration,
    /// not a declaration that names a tool which cannot actually reverse the
    /// effect. Nothing here can establish that a compensating call is a true
    /// inverse — that remains the author's claim, exactly as
    /// `expected_effects` is.
    pub fn missing_required_compensation(&self) -> bool {
        self.reversibility.requires_compensation() && self.compensation.is_none()
    }
}

/// A batch of actions proposed by a model for runtime validation and execution.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionProposal {
    #[serde(default = "short_id")]
    pub id: String,

    #[serde(default = "default_source")]
    pub source: String,

    pub actions: Vec<Action>,

    #[serde(default = "Utc::now")]
    pub timestamp: DateTime<Utc>,

    #[serde(default)]
    pub context: HashMap<String, Value>,
}

fn default_source() -> String {
    "unknown".to_string()
}

impl ActionProposal {
    /// The rollback contract of the batch as a whole: the **least** reversible
    /// contract any of its actions carries, via the severity ordering on
    /// [`Reversibility`]. A plan is only as recoverable as its least
    /// recoverable step — one irreversible action in an otherwise reversible
    /// batch makes the batch irreversible, because partial execution is a real
    /// outcome (it is exactly the failure mode `StaticVerificationGate` exists
    /// to prevent on multi-action proposals).
    ///
    /// An empty proposal is [`Reversibility::Reversible`], not the
    /// `Irreversible` default: the default answers "the author did not say",
    /// which warrants assuming the worst, whereas an empty batch has no
    /// effects at all and there is nothing to be pessimistic about.
    pub fn rollback_contract(&self) -> Reversibility {
        self.actions
            .iter()
            .map(|a| a.reversibility)
            .max()
            .unwrap_or(Reversibility::Reversible)
    }
}

/// A state mutation recorded in [`ActionResult::state_changes`].
///
/// The tagged envelope distinguishes deleting a key from setting it to JSON
/// `null`. `ActionResult` keeps its existing `HashMap<String, Value>` field so
/// the public Rust and serialized wire shapes remain backward compatible;
/// callers use this type at the encode/decode boundary instead of rebuilding
/// or hand-parsing the envelope.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum StateMutation {
    Set {
        /// Missing values from older hand-written envelopes retain the runtime's
        /// historical set-to-null interpretation.
        #[serde(default)]
        value: Value,
    },
    Delete,
}

impl StateMutation {
    /// Convert an observed post-execution value into its typed mutation.
    pub fn from_new_value(new_value: Option<Value>) -> Self {
        match new_value {
            Some(value) => Self::Set { value },
            None => Self::Delete,
        }
    }

    /// Encode this mutation into the stable `ActionResult.state_changes` value.
    pub fn encode(self) -> Value {
        serde_json::to_value(self)
            .expect("StateMutation contains only infallibly serializable JSON values")
    }

    /// Decode one `ActionResult.state_changes` value as a tagged mutation.
    pub fn decode(value: &Value) -> Result<Self, serde_json::Error> {
        serde_json::from_value(value.clone())
    }
}

/// The outcome of executing a single action.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionResult {
    pub action_id: String,
    pub status: ActionStatus,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<Value>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,

    #[serde(default)]
    pub state_changes: HashMap<String, Value>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<f64>,

    #[serde(default = "Utc::now")]
    pub timestamp: DateTime<Utc>,
}

/// Rate limit configuration for a tool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolRateLimit {
    pub max_calls: u32,
    pub interval_secs: f64,
}

/// Rich schema describing a tool's interface and runtime configuration.
///
/// Carries everything the runtime needs: parameter validation via JSON Schema,
/// idempotency hints, caching policy, and rate limiting.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolSchema {
    pub name: String,
    #[serde(default)]
    pub description: String,
    /// JSON Schema for parameters (e.g. `{"type": "object", "properties": {...}, "required": [...]}`)
    #[serde(default = "default_parameters_schema")]
    pub parameters: Value,
    /// JSON Schema for return value (optional)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub returns: Option<Value>,
    /// Whether this tool is idempotent (safe to cache/retry)
    #[serde(default)]
    pub idempotent: bool,
    /// If set, results are cached with this TTL in seconds
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_ttl_secs: Option<u64>,
    /// If set, rate limited to this many calls per interval
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rate_limit: Option<ToolRateLimit>,
}

fn default_parameters_schema() -> Value {
    Value::Object(Default::default())
}

/// Cost summary for a proposal execution.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct CostSummary {
    pub tool_calls: u32,
    /// Actions that actually ran — `Succeeded` plus `Failed`. A failed action
    /// executed and consumed real work (the tool ran and errored), so it counts;
    /// a *rejected* one never started and is counted in
    /// [`Self::actions_rejected`] instead. Rejections used to land here, which
    /// reported "2 actions executed" for a proposal where nothing ran at all
    /// (Parslee-ai/car#624).
    pub actions_executed: u32,
    /// Actions blocked before execution — by the validator (unknown tool,
    /// unsatisfied dependency) or by policy. Nothing ran, so these cost nothing
    /// beyond the check itself.
    ///
    /// `#[serde(default)]` so a payload written by an older CAR still
    /// deserializes; it simply reports 0.
    #[serde(default)]
    pub actions_rejected: u32,
    pub actions_skipped: u32,
    pub total_duration_ms: f64,
    pub retries: u32,
}

/// Soft optimization targets for proposal cost.
///
/// Unlike `CostBudget` (hard limits that reject proposals), `CostTarget` is used
/// by the planner to score proposals on a cost-vs-success curve. The `cost_weight`
/// controls how aggressively the planner favors cheaper proposals.
///
/// score = success_likelihood * (1 - cost_weight) + cost_efficiency * cost_weight
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CostTarget {
    /// Target number of tool calls (proposals below this get full cost score).
    pub target_tool_calls: u32,
    /// Target total duration in milliseconds.
    pub target_duration_ms: f64,
    /// Target number of actions.
    pub target_actions: u32,
    /// Weight for cost in scoring (0.0–1.0). 0 = ignore cost, 1 = only cost.
    pub cost_weight: f64,
}

impl Default for CostTarget {
    fn default() -> Self {
        Self {
            target_tool_calls: 5,
            target_duration_ms: 5000.0,
            target_actions: 10,
            cost_weight: 0.2,
        }
    }
}

/// Admission/execution disposition for one proposal generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProposalLineageStatus {
    Accepted,
    Rejected,
}

/// Immutable ordered identity receipt for one original or replanned proposal.
/// `proposal_digest` is absent only when the proposal itself could not be
/// represented as repository JCS/I-JSON, so no truthful digest exists.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProposalLineageEntry {
    pub generation: u32,
    pub proposal_id: String,
    pub proposal_digest: Option<String>,
    pub status: ProposalLineageStatus,
    pub rejection_reason: Option<String>,
}

impl ProposalLineageEntry {
    fn validate(&self) -> Result<(), String> {
        let digest_is_lowercase_sha256 = |digest: &str| {
            digest.len() == 64
                && digest
                    .bytes()
                    .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
        };

        match self.status {
            ProposalLineageStatus::Accepted => {
                let digest = self.proposal_digest.as_deref().ok_or_else(|| {
                    "accepted proposal lineage requires a lowercase JCS SHA-256 digest".to_string()
                })?;
                if !digest_is_lowercase_sha256(digest) {
                    return Err(
                        "accepted proposal lineage requires a lowercase JCS SHA-256 digest"
                            .to_string(),
                    );
                }
                if self.rejection_reason.is_some() {
                    return Err(
                        "accepted proposal lineage cannot include a rejection reason".to_string(),
                    );
                }
            }
            ProposalLineageStatus::Rejected => {
                if let Some(digest) = self.proposal_digest.as_deref() {
                    if !digest_is_lowercase_sha256(digest) {
                        return Err(
                            "rejected proposal lineage digest must be lowercase JCS SHA-256"
                                .to_string(),
                        );
                    }
                }
                let reason = self
                    .rejection_reason
                    .as_deref()
                    .filter(|reason| !reason.trim().is_empty())
                    .ok_or_else(|| {
                        "rejected proposal lineage requires an exact rejection reason".to_string()
                    })?;
                if self.proposal_digest.is_none()
                    && !reason.starts_with("RFC 8785 canonicalization failed")
                    && !reason.starts_with("proposal serialization failed")
                {
                    return Err(
                        "undigested rejected proposal lineage must identify a JCS/I-JSON failure"
                            .to_string(),
                    );
                }
            }
        }
        Ok(())
    }
}

impl Serialize for ProposalLineageEntry {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::{Error as _, SerializeStruct};
        self.validate().map_err(S::Error::custom)?;
        let mut state = serializer.serialize_struct("ProposalLineageEntry", 5)?;
        state.serialize_field("generation", &self.generation)?;
        state.serialize_field("proposal_id", &self.proposal_id)?;
        if let Some(digest) = &self.proposal_digest {
            state.serialize_field("proposal_digest", digest)?;
        }
        state.serialize_field("status", &self.status)?;
        if let Some(reason) = &self.rejection_reason {
            state.serialize_field("rejection_reason", reason)?;
        }
        state.end()
    }
}

impl<'de> Deserialize<'de> for ProposalLineageEntry {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Wire {
            generation: u32,
            proposal_id: String,
            #[serde(default)]
            proposal_digest: Option<String>,
            status: ProposalLineageStatus,
            #[serde(default)]
            rejection_reason: Option<String>,
        }

        let wire = Wire::deserialize(deserializer)?;
        let entry = Self {
            generation: wire.generation,
            proposal_id: wire.proposal_id,
            proposal_digest: wire.proposal_digest,
            status: wire.status,
            rejection_reason: wire.rejection_reason,
        };
        entry.validate().map_err(serde::de::Error::custom)?;
        Ok(entry)
    }
}

/// Exact accepted proposal input retained independently of the mutable event
/// log. Entries are returned in generation order so lifecycle persistence can
/// authenticate every proposal the runtime admitted, including replans whose
/// event rows have already been evicted by retention.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AcceptedProposalPreimage {
    pub generation: u32,
    pub proposal_digest: String,
    pub proposal: ActionProposal,
}

/// The complete result of processing a proposal through the runtime.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ProposalResult {
    /// The final proposal generation that actually executed. When no replan
    /// was accepted this remains the original proposal id.
    pub proposal_id: String,

    /// The caller-submitted proposal id, unchanged across every replan.
    pub original_proposal_id: String,

    /// Exact normal-serde preimage of the final proposal generation selected
    /// for execution. Legacy payloads may omit this field; every active
    /// runtime execution populates it so consumers can authenticate the final
    /// id, actions, parameters, dependencies, and declared effects against the
    /// accepted lineage digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub final_proposal: Option<ActionProposal>,

    /// Generation-ordered proposal identities and admission dispositions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub replan_lineage: Vec<ProposalLineageEntry>,

    /// Generation-ordered exact preimages for accepted lineage entries. This
    /// is result-owned evidence, not an EventLog projection, so configured log
    /// retention cannot remove it before a caller persists the run.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub accepted_proposal_preimages: Vec<AcceptedProposalPreimage>,

    #[serde(default)]
    pub results: Vec<ActionResult>,

    #[serde(default)]
    pub cost: CostSummary,
}

impl<'de> Deserialize<'de> for ProposalResult {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Wire {
            proposal_id: String,
            #[serde(default)]
            original_proposal_id: Option<String>,
            #[serde(default)]
            final_proposal: Option<ActionProposal>,
            #[serde(default)]
            replan_lineage: Vec<ProposalLineageEntry>,
            #[serde(default)]
            accepted_proposal_preimages: Vec<AcceptedProposalPreimage>,
            #[serde(default)]
            results: Vec<ActionResult>,
            #[serde(default)]
            cost: CostSummary,
        }

        let wire = Wire::deserialize(deserializer)?;
        let original_proposal_id = wire
            .original_proposal_id
            .unwrap_or_else(|| wire.proposal_id.clone());
        Ok(Self {
            proposal_id: wire.proposal_id,
            original_proposal_id,
            final_proposal: wire.final_proposal,
            replan_lineage: wire.replan_lineage,
            accepted_proposal_preimages: wire.accepted_proposal_preimages,
            results: wire.results,
            cost: wire.cost,
        })
    }
}

impl ProposalResult {
    pub fn new(
        proposal_id: impl Into<String>,
        results: Vec<ActionResult>,
        cost: CostSummary,
    ) -> Self {
        let proposal_id = proposal_id.into();
        Self {
            original_proposal_id: proposal_id.clone(),
            proposal_id,
            final_proposal: None,
            replan_lineage: Vec::new(),
            accepted_proposal_preimages: Vec::new(),
            results,
            cost,
        }
    }

    /// Construct an active runtime result bound to its exact final proposal
    /// preimage. Use [`Self::new`] only for legacy or synthetic results that
    /// did not pass through proposal execution.
    pub fn for_proposal(
        proposal: &ActionProposal,
        results: Vec<ActionResult>,
        cost: CostSummary,
    ) -> Self {
        Self {
            proposal_id: proposal.id.clone(),
            original_proposal_id: proposal.id.clone(),
            final_proposal: Some(proposal.clone()),
            replan_lineage: Vec::new(),
            accepted_proposal_preimages: Vec::new(),
            results,
            cost,
        }
    }

    pub fn all_succeeded(&self) -> bool {
        self.results
            .iter()
            .all(|r| r.status == ActionStatus::Succeeded)
    }

    pub fn summary(&self) -> HashMap<ActionStatus, usize> {
        let mut counts = HashMap::new();
        for r in &self.results {
            *counts.entry(r.status.clone()).or_insert(0) += 1;
        }
        counts
    }
}

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

    #[test]
    fn constructors_fill_defaults_and_leave_the_wire_unchanged() {
        // The migration's contract (Parslee-ai/car#855): `Action::new` must
        // produce exactly what a full struct literal produced, so converting
        // ~100 call sites off literals changed no behaviour. If a future field
        // is added to the struct but not to `new`, this stops compiling —
        // which is the point.
        let a = Action::new(ActionType::ToolCall);
        assert_eq!(a.action_type, ActionType::ToolCall);
        assert!(a.tool.is_none());
        assert!(a.parameters.is_empty());
        assert!(a.preconditions.is_empty());
        assert!(a.expected_effects.is_empty());
        assert!(a.state_dependencies.is_empty());
        assert!(a.read_set.is_empty());
        assert!(a.write_set.is_empty());
        assert!(a.assumptions.is_empty());
        assert_eq!(a.reversibility, Reversibility::default());
        assert!(a.compensation.is_none());
        assert!(!a.idempotent);
        assert_eq!(a.max_retries, default_max_retries());
        assert_eq!(a.failure_behavior, FailureBehavior::Abort);
        assert!(a.timeout_ms.is_none());
        assert!(a.metadata.is_empty());
        assert_eq!(a.id.len(), 12, "id is a generated short id");

        // The typed shortcuts agree with the long form.
        assert_eq!(Action::tool_call("deploy").tool.as_deref(), Some("deploy"));

        let sw = Action::state_write("k", Value::from(1));
        assert_eq!(sw.action_type, ActionType::StateWrite);
        assert_eq!(sw.parameters["key"], Value::from("k"));
        assert_eq!(sw.parameters["value"], Value::from(1));
        // The verifier reads the effect, the executor reads the parameters —
        // a `state_write` that set only one of them would silently defeat
        // write-conflict detection.
        assert_eq!(sw.expected_effects["k"], Value::from(1));
        assert_eq!(sw.effective_write_set(), vec!["k".to_string()]);

        let sr = Action::state_read("k");
        assert_eq!(sr.action_type, ActionType::StateRead);
        assert_eq!(sr.parameters["key"], Value::from("k"));

        // Chainable setters.
        let c = Action::tool_call("t")
            .with_id("fixed")
            .with_param("p", Value::from(2));
        assert_eq!(c.id, "fixed");
        assert_eq!(c.parameters["p"], Value::from(2));
    }

    #[test]
    fn action_type_serializes_snake_case() {
        assert_eq!(
            serde_json::to_string(&ActionType::ToolCall).unwrap(),
            "\"tool_call\""
        );
        assert_eq!(
            serde_json::to_string(&ActionType::StateWrite).unwrap(),
            "\"state_write\""
        );
    }

    #[test]
    fn failure_behavior_serializes_snake_case() {
        assert_eq!(
            serde_json::to_string(&FailureBehavior::Abort).unwrap(),
            "\"abort\""
        );
        assert_eq!(
            serde_json::to_string(&FailureBehavior::Retry).unwrap(),
            "\"retry\""
        );
    }

    #[test]
    fn action_roundtrip_json() {
        let action = Action {
            id: "abc123".to_string(),
            action_type: ActionType::ToolCall,
            tool: Some("add".to_string()),
            parameters: [
                ("a".to_string(), Value::from(1)),
                ("b".to_string(), Value::from(2)),
            ]
            .into(),
            preconditions: vec![Precondition {
                key: "auth".to_string(),
                operator: "eq".to_string(),
                value: Value::Bool(true),
                description: String::new(),
            }],
            expected_effects: [("sum".to_string(), Value::from(3))].into(),
            state_dependencies: vec!["auth".to_string()],
            read_set: vec![],
            write_set: vec![],
            assumptions: vec![],
            invocation_mode: Default::default(),
            reversibility: Reversibility::Compensable,
            compensation: Some(Compensation::Tool {
                tool: "subtract".to_string(),
                parameters: [("sum".to_string(), Value::from(3))].into(),
            }),
            idempotent: true,
            max_retries: 3,
            failure_behavior: FailureBehavior::Retry,
            timeout_ms: Some(5000),
            metadata: HashMap::new(),
        };

        let json = serde_json::to_string_pretty(&action).unwrap();
        let roundtripped: Action = serde_json::from_str(&json).unwrap();

        assert_eq!(action.id, roundtripped.id);
        assert_eq!(action.action_type, roundtripped.action_type);
        assert_eq!(action.tool, roundtripped.tool);
        assert_eq!(action.idempotent, roundtripped.idempotent);
        assert_eq!(action.failure_behavior, roundtripped.failure_behavior);
        assert_eq!(action.timeout_ms, roundtripped.timeout_ms);
        assert_eq!(action.reversibility, roundtripped.reversibility);
        assert_eq!(action.compensation, roundtripped.compensation);
        assert_eq!(action, roundtripped);
    }

    #[test]
    fn proposal_roundtrip_json() {
        let proposal = ActionProposal {
            id: "prop1".to_string(),
            source: "test".to_string(),
            actions: vec![Action {
                id: "a1".to_string(),
                action_type: ActionType::StateWrite,
                tool: None,
                parameters: [
                    ("key".to_string(), Value::from("x")),
                    ("value".to_string(), Value::from(42)),
                ]
                .into(),
                preconditions: vec![],
                expected_effects: HashMap::new(),
                state_dependencies: vec![],
                read_set: vec![],
                write_set: vec![],
                assumptions: vec![],
                invocation_mode: Default::default(),
                reversibility: Reversibility::Reversible,
                compensation: None,
                idempotent: false,
                max_retries: 3,
                failure_behavior: FailureBehavior::Abort,
                timeout_ms: None,
                metadata: HashMap::new(),
            }],
            timestamp: Utc::now(),
            context: HashMap::new(),
        };

        let json = serde_json::to_string(&proposal).unwrap();
        let roundtripped: ActionProposal = serde_json::from_str(&json).unwrap();

        assert_eq!(proposal.id, roundtripped.id);
        assert_eq!(proposal.source, roundtripped.source);
        assert_eq!(proposal.actions.len(), roundtripped.actions.len());
    }

    #[test]
    fn state_mutation_round_trips_the_stable_wire_shape() {
        let set = StateMutation::Set {
            value: Value::from(42),
        };
        let set_wire = set.clone().encode();
        assert_eq!(set_wire, serde_json::json!({"op": "set", "value": 42}));
        assert_eq!(StateMutation::decode(&set_wire).unwrap(), set);

        let delete = StateMutation::Delete;
        let delete_wire = delete.clone().encode();
        assert_eq!(delete_wire, serde_json::json!({"op": "delete"}));
        assert_eq!(StateMutation::decode(&delete_wire).unwrap(), delete);

        assert_eq!(
            StateMutation::decode(&serde_json::json!({"op": "set"})).unwrap(),
            StateMutation::Set { value: Value::Null },
            "a missing set value retains the previous set-to-null interpretation"
        );
        assert!(StateMutation::decode(&serde_json::json!({"legacy": true})).is_err());
    }

    #[test]
    fn action_result_serializes() {
        let result = ActionResult {
            action_id: "a1".to_string(),
            status: ActionStatus::Succeeded,
            output: Some(Value::from(42)),
            error: None,
            state_changes: HashMap::new(),
            duration_ms: Some(1.5),
            timestamp: Utc::now(),
        };

        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("\"succeeded\""));
    }

    #[test]
    fn proposal_result_all_succeeded() {
        let pr = ProposalResult {
            proposal_id: "p1".to_string(),
            original_proposal_id: "p1".to_string(),
            final_proposal: None,
            replan_lineage: vec![],
            accepted_proposal_preimages: vec![],
            results: vec![
                ActionResult {
                    action_id: "a1".to_string(),
                    status: ActionStatus::Succeeded,
                    output: None,
                    error: None,
                    state_changes: HashMap::new(),
                    duration_ms: None,
                    timestamp: Utc::now(),
                },
                ActionResult {
                    action_id: "a2".to_string(),
                    status: ActionStatus::Succeeded,
                    output: None,
                    error: None,
                    state_changes: HashMap::new(),
                    duration_ms: None,
                    timestamp: Utc::now(),
                },
            ],
            cost: CostSummary::default(),
        };
        assert!(pr.all_succeeded());
    }

    #[test]
    fn proposal_result_not_all_succeeded() {
        let pr = ProposalResult {
            proposal_id: "p1".to_string(),
            original_proposal_id: "p1".to_string(),
            final_proposal: None,
            replan_lineage: vec![],
            accepted_proposal_preimages: vec![],
            results: vec![
                ActionResult {
                    action_id: "a1".to_string(),
                    status: ActionStatus::Succeeded,
                    output: None,
                    error: None,
                    state_changes: HashMap::new(),
                    duration_ms: None,
                    timestamp: Utc::now(),
                },
                ActionResult {
                    action_id: "a2".to_string(),
                    status: ActionStatus::Failed,
                    output: None,
                    error: Some("boom".to_string()),
                    state_changes: HashMap::new(),
                    duration_ms: None,
                    timestamp: Utc::now(),
                },
            ],
            cost: CostSummary::default(),
        };
        assert!(!pr.all_succeeded());
    }

    #[test]
    fn cost_summary_default_is_zero() {
        let cost = CostSummary::default();
        assert_eq!(cost.tool_calls, 0);
        assert_eq!(cost.actions_executed, 0);
        assert_eq!(cost.actions_rejected, 0);
        assert_eq!(cost.actions_skipped, 0);
        assert_eq!(cost.total_duration_ms, 0.0);
        assert_eq!(cost.retries, 0);
    }

    /// A summary written before `actions_rejected` existed must still load.
    #[test]
    fn cost_summary_deserializes_without_actions_rejected() {
        let legacy = r#"{"tool_calls":1,"actions_executed":2,"actions_skipped":0,
                         "total_duration_ms":5.0,"retries":0}"#;
        let cost: CostSummary = serde_json::from_str(legacy).unwrap();
        assert_eq!(cost.actions_executed, 2);
        assert_eq!(cost.actions_rejected, 0);
    }

    #[test]
    fn cost_summary_serde_roundtrip() {
        let cost = CostSummary {
            tool_calls: 3,
            actions_executed: 5,
            actions_rejected: 2,
            actions_skipped: 1,
            total_duration_ms: 42.5,
            retries: 2,
        };
        let json = serde_json::to_string(&cost).unwrap();
        let roundtripped: CostSummary = serde_json::from_str(&json).unwrap();
        assert_eq!(cost, roundtripped);
    }

    #[test]
    fn proposal_result_deserializes_without_cost() {
        // Backward compatibility: old JSON without cost field should still deserialize
        let json = r#"{"proposal_id": "p1", "results": []}"#;
        let pr: ProposalResult = serde_json::from_str(json).unwrap();
        assert_eq!(pr.cost, CostSummary::default());
        assert_eq!(pr.original_proposal_id, "p1");
        assert_eq!(pr.final_proposal, None);
        assert!(pr.replan_lineage.is_empty());
        assert!(pr.accepted_proposal_preimages.is_empty());
    }

    #[test]
    fn proposal_result_lineage_has_exact_tagged_wire_shape() {
        let original_digest = "a".repeat(64);
        let candidate_digest = "b".repeat(64);
        let accepted_digest = "c".repeat(64);
        let final_proposal = ActionProposal {
            id: "accepted-replan".to_string(),
            source: "replanner".to_string(),
            actions: vec![],
            timestamp: Utc::now(),
            context: HashMap::new(),
        };
        let pr = ProposalResult {
            proposal_id: "accepted-replan".to_string(),
            original_proposal_id: "original".to_string(),
            final_proposal: Some(final_proposal.clone()),
            replan_lineage: vec![
                ProposalLineageEntry {
                    generation: 0,
                    proposal_id: "original".to_string(),
                    proposal_digest: Some(original_digest.clone()),
                    status: ProposalLineageStatus::Accepted,
                    rejection_reason: None,
                },
                ProposalLineageEntry {
                    generation: 1,
                    proposal_id: "duplicate-candidate".to_string(),
                    proposal_digest: Some(candidate_digest.clone()),
                    status: ProposalLineageStatus::Rejected,
                    rejection_reason: Some("duplicate action id 'same'".to_string()),
                },
                ProposalLineageEntry {
                    generation: 2,
                    proposal_id: "accepted-replan".to_string(),
                    proposal_digest: Some(accepted_digest.clone()),
                    status: ProposalLineageStatus::Accepted,
                    rejection_reason: None,
                },
            ],
            accepted_proposal_preimages: vec![AcceptedProposalPreimage {
                generation: 2,
                proposal_digest: accepted_digest.clone(),
                proposal: final_proposal.clone(),
            }],
            results: vec![],
            cost: CostSummary::default(),
        };
        let value = serde_json::to_value(&pr).unwrap();
        assert_eq!(value["proposal_id"], "accepted-replan");
        assert_eq!(value["original_proposal_id"], "original");
        assert_eq!(value["final_proposal"], serde_json::json!(final_proposal));
        assert_eq!(
            value["replan_lineage"],
            serde_json::json!([
                {
                    "generation": 0,
                    "proposal_id": "original",
                    "proposal_digest": original_digest,
                    "status": "accepted"
                },
                {
                    "generation": 1,
                    "proposal_id": "duplicate-candidate",
                    "proposal_digest": candidate_digest,
                    "status": "rejected",
                    "rejection_reason": "duplicate action id 'same'"
                },
                {
                    "generation": 2,
                    "proposal_id": "accepted-replan",
                    "proposal_digest": accepted_digest,
                    "status": "accepted"
                }
            ])
        );
        assert_eq!(
            value["accepted_proposal_preimages"],
            serde_json::json!([{
                "generation": 2,
                "proposal_digest": accepted_digest,
                "proposal": final_proposal,
            }])
        );
    }

    #[test]
    fn proposal_lineage_rejects_missing_or_noncanonical_accepted_digest() {
        for digest in [Value::Null, Value::from("A".repeat(64)), Value::from("abc")] {
            let value = serde_json::json!({
                "generation": 0,
                "proposal_id": "p",
                "proposal_digest": digest,
                "status": "accepted"
            });
            let error = serde_json::from_value::<ProposalLineageEntry>(value).unwrap_err();
            assert!(
                error
                    .to_string()
                    .contains("accepted proposal lineage requires a lowercase JCS SHA-256 digest"),
                "unexpected error: {error}"
            );
        }
    }

    #[test]
    fn rejected_lineage_without_digest_requires_exact_reason() {
        let valid: ProposalLineageEntry = serde_json::from_value(serde_json::json!({
            "generation": 1,
            "proposal_id": "not-jcs",
            "status": "rejected",
            "rejection_reason": "RFC 8785 canonicalization failed: number is outside the I-JSON safe integer range"
        }))
        .unwrap();
        assert!(valid.proposal_digest.is_none());

        let error = serde_json::from_value::<ProposalLineageEntry>(serde_json::json!({
            "generation": 1,
            "proposal_id": "not-jcs",
            "status": "rejected"
        }))
        .unwrap_err();
        assert!(error
            .to_string()
            .contains("rejected proposal lineage requires an exact rejection reason"));

        let wrong_reason = serde_json::from_value::<ProposalLineageEntry>(serde_json::json!({
            "generation": 1,
            "proposal_id": "not-jcs",
            "status": "rejected",
            "rejection_reason": "duplicate action id"
        }))
        .unwrap_err();
        assert!(wrong_reason
            .to_string()
            .contains("undigested rejected proposal lineage must identify a JCS/I-JSON failure"));
    }

    #[test]
    fn deserialize_from_python_compatible_json() {
        // This JSON must match what Python's model_dump_json() produces
        let json = r#"{
            "id": "test123",
            "type": "tool_call",
            "tool": "add",
            "parameters": {"a": 1, "b": 2},
            "preconditions": [],
            "expected_effects": {"sum": 3},
            "state_dependencies": [],
            "idempotent": true,
            "max_retries": 3,
            "failure_behavior": "retry",
            "timeout_ms": 5000,
            "metadata": {}
        }"#;

        let action: Action = serde_json::from_str(json).unwrap();
        assert_eq!(action.id, "test123");
        assert_eq!(action.action_type, ActionType::ToolCall);
        assert_eq!(action.tool, Some("add".to_string()));
        assert!(action.idempotent);
        assert_eq!(action.failure_behavior, FailureBehavior::Retry);
        assert_eq!(action.timeout_ms, Some(5000));
    }

    /// The backward-compatibility contract the rest of the runtime depends on:
    /// a proposal authored before `reversibility` / `compensation` existed —
    /// including one that predates the transactional and streaming fields —
    /// must still deserialize, landing on the conservative default rather than
    /// failing.
    #[test]
    fn action_deserializes_without_reversibility_fields() {
        let legacy = r#"{
            "id": "legacy1",
            "type": "tool_call",
            "tool": "send_email",
            "parameters": {"to": "a@b.c"},
            "preconditions": [],
            "expected_effects": {},
            "state_dependencies": [],
            "idempotent": false,
            "max_retries": 3,
            "failure_behavior": "abort",
            "metadata": {}
        }"#;

        let action: Action = serde_json::from_str(legacy).unwrap();
        assert_eq!(action.id, "legacy1");
        assert_eq!(action.reversibility, Reversibility::Irreversible);
        assert_eq!(action.compensation, None);
        // The default is not the incoherent state — `Irreversible` needs no
        // compensation, so an un-annotated legacy action never trips the check.
        assert!(!action.missing_required_compensation());
    }

    /// The same contract one level up: a whole proposal written by an older
    /// CAR (or an older binding) still loads, and every action in it defaults.
    #[test]
    fn proposal_deserializes_without_reversibility_fields() {
        let legacy = r#"{
            "id": "prop-legacy",
            "source": "python",
            "actions": [
                {"id": "a1", "type": "state_write", "parameters": {"key": "x", "value": 1}},
                {"id": "a2", "type": "tool_call", "tool": "add", "parameters": {}}
            ],
            "context": {}
        }"#;

        let proposal: ActionProposal = serde_json::from_str(legacy).unwrap();
        assert_eq!(proposal.actions.len(), 2);
        for action in &proposal.actions {
            assert_eq!(action.reversibility, Reversibility::Irreversible);
            assert!(action.compensation.is_none());
        }
        assert_eq!(proposal.rollback_contract(), Reversibility::Irreversible);
    }

    /// `compensation` is `skip_serializing_if = "Option::is_none"`, so an
    /// action that declares no compensation emits no key at all — an older
    /// consumer sees exactly the payload shape it saw before.
    #[test]
    fn absent_compensation_is_omitted_from_the_wire_form() {
        let mut action: Action =
            serde_json::from_str(r#"{"id":"a1","type":"tool_call","tool":"noop"}"#).unwrap();
        action.reversibility = Reversibility::Reversible;

        let json = serde_json::to_value(&action).unwrap();
        assert_eq!(json["reversibility"], "reversible");
        assert!(
            json.get("compensation").is_none(),
            "compensation should be skipped when None, got {json}"
        );
    }

    #[test]
    fn compensable_without_compensation_is_flagged() {
        let mut action: Action =
            serde_json::from_str(r#"{"id":"a1","type":"tool_call","tool":"db.insert"}"#).unwrap();

        action.reversibility = Reversibility::Compensable;
        assert!(action.missing_required_compensation());

        action.compensation = Some(Compensation::ActionRef {
            action_id: "undo-a1".to_string(),
        });
        assert!(!action.missing_required_compensation());

        // A compensation declared alongside a non-compensable contract is
        // pointless but not incoherent — the check stays quiet about it.
        action.reversibility = Reversibility::Reversible;
        assert!(!action.missing_required_compensation());
    }

    #[test]
    fn rollback_contract_is_the_worst_action_in_the_batch() {
        let mut proposal: ActionProposal = serde_json::from_str(
            r#"{"id":"p1","source":"test","actions":[
                {"id":"a1","type":"state_write","parameters":{"key":"x"},"reversibility":"reversible"},
                {"id":"a2","type":"tool_call","tool":"db.insert","reversibility":"compensable",
                 "compensation":{"type":"tool","tool":"db.delete","parameters":{"id":1}}}
            ]}"#,
        )
        .unwrap();
        assert_eq!(proposal.rollback_contract(), Reversibility::Compensable);

        proposal.actions[0].reversibility = Reversibility::Irreversible;
        assert_eq!(proposal.rollback_contract(), Reversibility::Irreversible);

        // Nothing to undo is not the same as "unclassified", so an empty
        // batch does not inherit the pessimistic default.
        proposal.actions.clear();
        assert_eq!(proposal.rollback_contract(), Reversibility::Reversible);
    }
}