car-verify 0.32.0

Formal verification for Agent IR — the novel contribution
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
//! Code World Models — trajectory-validated effect models (Slice 1).
//!
//! Applies *Code World Models for General Game Playing* (arXiv 2510.04542)
//! to CAR. The paper's recipe: have an LLM emit an executable world model
//! (`apply(state, action) -> state'`) instead of acting as the policy, then
//! **unit-test that model against recorded trajectories** and **feed failing
//! cases back** until transition accuracy reaches 1.0. See
//! `docs/proposals/code-world-models.md`.
//!
//! This module is Slice 1 of that proposal: the *verification harness* and
//! the *self-repair loop*, with no change to the live execution path.
//!
//! - [`Transition`] is the paper's unit-test record:
//!   `(state_before, action, state_after)`. The bridge that rebuilds these
//!   from a `car_eventlog` JSONL tail — the supervised signal CAR already
//!   records but never used to validate a model — lives in
//!   `car_ffi_common::cwm` (which already depends on the event log), keeping
//!   this crate dependency-light.
//! - [`score`] / [`score_predictions`] compute **transition accuracy** (the
//!   paper's central metric) over held-out transitions, with structured
//!   per-case failures so a repair agent can act on them.
//! - [`synthesize_cwm`] is the prompt→generate→run→repair loop, generic over
//!   the model (`generate`) and the code runner (`run`) — exactly the
//!   injection pattern `car_builder::build_workflow` uses for inference, so
//!   neither inference nor a code sandbox is a dependency of this crate.
//!
//! Nothing here executes real tools or generated code itself: a CWM is a
//! *predictor* for planning/pre-flight checks (Slices 2–3), never a
//! substitute for running the tool. Execution of candidate code is the
//! caller's responsibility (e.g. a Python sandbox), injected as a closure.

use crate::{apply_action_effects, StaticState};
use car_ir::{build_dag, Action, ActionProposal, ActionType};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

/// A state map — the same shape `car_verify::simulate` returns.
pub type State = HashMap<String, Value>;

/// One recorded transition: the paper's `(state_before, action, state_after)`
/// unit-test record. `action` is an arbitrary JSON value (a full action
/// object with `tool`/`parameters`, or a bare id when that's all the log
/// resolves) so a model has whatever the trajectory captured to predict from.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Transition {
    pub state_before: State,
    pub action: Value,
    pub state_after: State,
}

/// A single mismatch found by scoring — enough for a human or a repair agent
/// to act on (the paper feeds the analogous failing case + stack trace back
/// to the model).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Failure {
    /// Index of the failing transition in the scored slice.
    pub index: usize,
    /// The action that was predicted from.
    pub action: Value,
    /// The recorded ground-truth post-state.
    pub expected: State,
    /// What the model predicted (absent when the predictor errored).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub predicted: Option<State>,
    /// The predictor's error/stack trace, when running the model threw rather
    /// than returning a state (the paper's "feed the stack trace back").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// The result of scoring a model against a set of transitions — the paper's
/// transition-accuracy report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScoreReport {
    /// Transitions scored (the sample size — report it so consumers don't
    /// trust an accuracy of 1.0 computed over three examples).
    pub total: usize,
    /// Transitions the model reproduced exactly.
    pub correct: usize,
    /// Transitions where the predictor errored instead of returning a state.
    pub errored: usize,
    /// `correct / total` (the paper's transition accuracy); `0.0` when empty.
    pub accuracy: f64,
    /// Per-case mismatches (correct cases are omitted).
    pub failures: Vec<Failure>,
}

impl ScoreReport {
    /// True when every scored transition was reproduced exactly (the paper's
    /// refinement target). `false` for an empty set — nothing was proven.
    pub fn is_perfect(&self) -> bool {
        self.total > 0 && self.correct == self.total
    }
}

/// Numeric-aware deep equality. Mirrors the rationale in
/// [`crate::transaction`]'s `values_equal` (JSON that round-trips through a
/// system which floatifies integers must not read as a mismatch), but
/// recurses through arrays and objects so a *nested* `1` vs `1.0` — common in
/// a state map — compares equal too.
fn values_equal(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
            (Some(fx), Some(fy)) => fx == fy,
            _ => x == y,
        },
        (Value::Array(xs), Value::Array(ys)) => {
            xs.len() == ys.len() && xs.iter().zip(ys).all(|(x, y)| values_equal(x, y))
        }
        (Value::Object(xs), Value::Object(ys)) => {
            xs.len() == ys.len()
                && xs
                    .iter()
                    .all(|(k, x)| ys.get(k).is_some_and(|y| values_equal(x, y)))
        }
        _ => a == b,
    }
}

/// Two state maps are equal when they have the same keys with numeric-aware
/// equal values.
fn states_equal(a: &State, b: &State) -> bool {
    a.len() == b.len()
        && a.iter()
            .all(|(k, av)| b.get(k).is_some_and(|bv| values_equal(av, bv)))
}

/// Score a predictor against `transitions` — the paper's transition-accuracy
/// metric. `predict(state_before, action)` returns the model's predicted
/// post-state, or `Err(stack_trace)` if running it threw. Generic over the
/// predictor so the same metric serves an in-process model, a sandboxed
/// Python CWM, or a test fake.
pub fn score<P>(transitions: &[Transition], mut predict: P) -> ScoreReport
where
    P: FnMut(&State, &Value) -> Result<State, String>,
{
    let mut correct = 0;
    let mut errored = 0;
    let mut failures = Vec::new();
    for (index, t) in transitions.iter().enumerate() {
        match predict(&t.state_before, &t.action) {
            Ok(predicted) => {
                if states_equal(&predicted, &t.state_after) {
                    correct += 1;
                } else {
                    failures.push(Failure {
                        index,
                        action: t.action.clone(),
                        expected: t.state_after.clone(),
                        predicted: Some(predicted),
                        error: None,
                    });
                }
            }
            Err(e) => {
                errored += 1;
                failures.push(Failure {
                    index,
                    action: t.action.clone(),
                    expected: t.state_after.clone(),
                    predicted: None,
                    error: Some(e),
                });
            }
        }
    }
    let total = transitions.len();
    ScoreReport {
        total,
        correct,
        errored,
        accuracy: if total == 0 {
            0.0
        } else {
            correct as f64 / total as f64
        },
        failures,
    }
}

/// Score *precomputed* predictions against `transitions`, aligned by index.
/// The stateless path for callers that ran the generated code themselves
/// (e.g. in a sandbox) and just want the paper's accuracy metric + structured
/// failures. `predictions[i]` is the model's post-state for `transitions[i]`,
/// or `Err(stack_trace)`. A length mismatch is an error rather than a silent
/// truncation.
pub fn score_predictions(
    transitions: &[Transition],
    predictions: &[Result<State, String>],
) -> Result<ScoreReport, String> {
    if transitions.len() != predictions.len() {
        return Err(format!(
            "transitions ({}) and predictions ({}) differ in length",
            transitions.len(),
            predictions.len()
        ));
    }
    let mut iter = predictions.iter();
    Ok(score(transitions, |_, _| {
        iter.next().expect("length checked above").clone()
    }))
}

/// What `synthesize_cwm` returns. On success `code` holds the model that
/// reached perfect train accuracy and `test_accuracy` its held-out score; on
/// failure it holds the best attempt with its measured accuracy, honest about
/// not reaching 1.0 (the paper's Gin Rummy at ~0.74) — mirrors
/// `car_builder::BuildResult`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CwmResult {
    /// The best candidate code produced (`None` if nothing ever parsed/ran).
    pub code: Option<String>,
    /// Whether `code` reached 1.0 transition accuracy on the train split.
    pub perfect: bool,
    /// Best train-split transition accuracy seen.
    pub train_accuracy: f64,
    /// Held-out test-split accuracy — only measured for a perfect model.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_accuracy: Option<f64>,
    /// Attempts made (1..=max_attempts).
    pub attempts: u32,
    /// Remaining failures from the best attempt (empty when perfect).
    pub failures: Vec<Failure>,
}

/// Inputs to a synthesis run.
pub struct CwmRequest {
    /// Natural-language rules and/or the tool schema the model compiles into a
    /// world model — the paper's "rule specification".
    pub spec: String,
    /// Transitions to fit against (train split).
    pub train: Vec<Transition>,
    /// Held-out transitions, scored only once a perfect model is found.
    pub test: Vec<Transition>,
    /// Maximum generate→run→repair attempts (clamped to ≥ 1).
    pub max_attempts: u32,
}

/// Build the per-attempt prompt: spec + a sample of transitions to fit + the
/// failing cases from the previous attempt (the repair signal). Kept small
/// and provider-agnostic; the actual model call is injected.
fn build_prompt(spec: &str, train: &[Transition], prior: &[Failure]) -> String {
    let mut p = String::new();
    p.push_str(
        "Write a deterministic world model as a single function `apply(state, action)` \
         returning the next state. Return ONLY the code.\n\n",
    );
    p.push_str("# Rules / tool schema\n");
    p.push_str(spec);
    p.push_str("\n\n# Transitions to reproduce exactly\n");
    // A bounded sample keeps the prompt small; the run loop scores against all.
    for t in train.iter().take(8) {
        if let Ok(line) = serde_json::to_string(t) {
            p.push_str(&line);
            p.push('\n');
        }
    }
    if !prior.is_empty() {
        p.push_str("\n# Your previous model failed these cases — fix them:\n");
        for f in prior.iter().take(8) {
            if let Ok(line) = serde_json::to_string(f) {
                p.push_str(&line);
                p.push('\n');
            }
        }
    }
    p
}

/// Synthesize a Code World Model by the paper's loop: generate code, run it
/// over the train transitions, and on imperfect accuracy feed the failing
/// cases back and retry — up to `max_attempts`, stopping early on a perfect
/// model and then scoring the held-out split.
///
/// `generate(prompt) -> code` is the model call (async, fallible — a transport
/// error is recorded but not treated as a repairable model mistake, matching
/// `build_workflow`). `run(code, state_before, action) -> state_after` runs a
/// candidate model on one transition, returning its prediction or an error
/// string (a stack trace) that becomes repair feedback. Neither inference nor
/// a code sandbox is a dependency of this crate; both are injected.
pub async fn synthesize_cwm<G, GFut, R>(
    generate: G,
    mut run: R,
    req: &CwmRequest,
) -> CwmResult
where
    G: Fn(String) -> GFut,
    GFut: std::future::Future<Output = Result<String, String>>,
    R: FnMut(&str, &State, &Value) -> Result<State, String>,
{
    let max = req.max_attempts.max(1);
    let mut prior: Vec<Failure> = Vec::new();
    let mut best: Option<(String, ScoreReport)> = None;
    let mut attempts = 0;

    for attempt in 1..=max {
        attempts = attempt;
        let prompt = build_prompt(&req.spec, &req.train, &prior);
        let code = match generate(prompt).await {
            Ok(c) => c,
            // Transport/model error — not something the model can "repair".
            // Re-send the same prompt next attempt rather than a fake hint.
            Err(_) => continue,
        };

        let report = score(&req.train, |s, a| run(&code, s, a));

        if report.is_perfect() {
            let test = score(&req.test, |s, a| run(&code, s, a));
            return CwmResult {
                code: Some(code),
                perfect: true,
                train_accuracy: report.accuracy,
                test_accuracy: Some(test.accuracy),
                attempts,
                failures: Vec::new(),
            };
        }

        prior = report.failures.clone();
        let better = best
            .as_ref()
            .map(|(_, b)| report.accuracy > b.accuracy)
            .unwrap_or(true);
        if better {
            best = Some((code, report));
        }
    }

    match best {
        Some((code, report)) => CwmResult {
            code: Some(code),
            perfect: false,
            train_accuracy: report.accuracy,
            test_accuracy: None,
            attempts,
            failures: report.failures,
        },
        None => CwmResult {
            code: None,
            perfect: false,
            train_accuracy: 0.0,
            test_accuracy: None,
            attempts,
            failures: Vec::new(),
        },
    }
}

// --- Slice 2: predictive simulation ---------------------------------------
//
// `simulate` (car-verify) is static — it propagates each action's *declared*
// `expected_effects`. A verified Code World Model predicts what a tool *actually*
// writes. Slice 2 lets a model contribute those predictions to simulation,
// behind an accuracy gate, while keeping car-verify pure: the model is an
// injected trait object, so executing generated code stays the caller's job
// (the same split as `synthesize_cwm`'s `run` closure). See
// `docs/proposals/code-world-models.md`.

/// A predictive effect model consulted during [`simulate_with_model`]: given an
/// action and the state *before* it runs, predict the state keys it will write.
/// Returning `None` means *abstain* — the simulator falls back to the action's
/// declared `expected_effects`, i.e. the static [`crate::simulate`] behavior.
/// So a model that always abstains reproduces `simulate` exactly.
pub trait EffectModel {
    fn predict(&self, action: &Action, state_before: &State) -> Option<State>;
}

/// One action's predicted post-effect plus the measured transition accuracy of
/// the model that produced it (from [`score`] / [`synthesize_cwm`]).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GatedPrediction {
    /// The state keys/values the model predicts this action writes.
    pub effects: State,
    /// The producing model's measured transition accuracy in `[0,1]`.
    pub accuracy: f64,
}

/// An [`EffectModel`] backed by precomputed per-action predictions, used only
/// when the producing model's accuracy clears `min_accuracy` — the paper's
/// "plan against the model only once it's verified" gate. Predictions for
/// actions with no entry, or a sub-threshold one, abstain (fall back to static
/// effects), so an under-accurate model can never *worsen* simulation: at worst
/// it's ignored. Caller computes each prediction by running the generated code;
/// the gate lives here so it's uniform and testable.
pub struct GatedEffectModel {
    /// Keyed by `Action::id`.
    pub predictions: HashMap<String, GatedPrediction>,
    /// Minimum accuracy a prediction must have to be applied.
    pub min_accuracy: f64,
}

impl EffectModel for GatedEffectModel {
    fn predict(&self, action: &Action, _state_before: &State) -> Option<State> {
        self.predictions
            .get(&action.id)
            .filter(|p| p.accuracy >= self.min_accuracy)
            .map(|p| p.effects.clone())
    }
}

/// Simulate a proposal's final state like [`crate::simulate`], but consult
/// `model` for each action's effects in topological order: where the model
/// predicts (`Some`), apply the prediction instead of the action's declared
/// `expected_effects`; where it abstains (`None`), fall back to the static
/// effects. A `StateWrite`'s deterministic key/value is always applied (it is
/// fully known statically — not something a model needs to predict). Passing a
/// model that always abstains yields byte-identical output to `simulate`.
pub fn simulate_with_model(
    proposal: &ActionProposal,
    initial_state: Option<&State>,
    model: &dyn EffectModel,
) -> State {
    let mut state = match initial_state {
        Some(s) => StaticState::from_map(s.clone()),
        None => StaticState::new(),
    };

    for level in build_dag(&proposal.actions) {
        for idx in level {
            let action = &proposal.actions[idx];
            // Predict from the pre-action state (before this action's own write).
            let predicted = model.predict(action, &state.known);

            // Deterministic builtin write always applies.
            if action.action_type == ActionType::StateWrite {
                if let Some(key) = action.parameters.get("key").and_then(|v| v.as_str()) {
                    let value = action
                        .parameters
                        .get("value")
                        .cloned()
                        .unwrap_or(Value::Null);
                    state.set(key, value);
                }
            }

            match predicted {
                Some(delta) => {
                    for (k, v) in delta {
                        state.set(&k, v);
                    }
                }
                // No prediction → identical to `simulate`'s static effects.
                // Re-applies the StateWrite key above harmlessly (same value).
                None => apply_action_effects(action, &mut state),
            }
        }
    }
    state.known
}

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

    fn st(pairs: &[(&str, Value)]) -> State {
        pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
    }

    fn counter_transitions() -> Vec<Transition> {
        // A tiny world: action {"inc": n} adds n to state["count"].
        vec![
            Transition {
                state_before: st(&[("count", json!(0))]),
                action: json!({ "inc": 1 }),
                state_after: st(&[("count", json!(1))]),
            },
            Transition {
                state_before: st(&[("count", json!(1))]),
                action: json!({ "inc": 2 }),
                state_after: st(&[("count", json!(3))]),
            },
        ]
    }

    // A "model" that correctly implements the counter world.
    fn good_model(s: &State, a: &Value) -> Result<State, String> {
        let cur = s.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
        let inc = a.get("inc").and_then(|v| v.as_i64()).unwrap_or(0);
        Ok(st(&[("count", json!(cur + inc))]))
    }

    #[test]
    fn perfect_model_scores_1() {
        let r = score(&counter_transitions(), good_model);
        assert_eq!(r.total, 2);
        assert_eq!(r.correct, 2);
        assert!(r.is_perfect());
        assert_eq!(r.accuracy, 1.0);
        assert!(r.failures.is_empty());
    }

    #[test]
    fn wrong_model_reports_failures() {
        // Off-by-one: always adds 1 regardless of action.
        let r = score(&counter_transitions(), |s, _| {
            let cur = s.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
            Ok(st(&[("count", json!(cur + 1))]))
        });
        assert_eq!(r.correct, 1); // first case (inc:1) happens to match
        assert_eq!(r.failures.len(), 1);
        assert_eq!(r.failures[0].index, 1);
        assert!(r.failures[0].error.is_none());
        assert_eq!(r.failures[0].predicted, Some(st(&[("count", json!(2))])));
    }

    #[test]
    fn throwing_model_is_counted_as_errored() {
        let r = score(&counter_transitions(), |_, _| Err("boom".to_string()));
        assert_eq!(r.errored, 2);
        assert_eq!(r.correct, 0);
        assert_eq!(r.failures[0].error.as_deref(), Some("boom"));
    }

    #[test]
    fn numeric_equality_int_vs_float() {
        // Recorded post-state has an int; model returns a float — must match.
        let trs = vec![Transition {
            state_before: st(&[]),
            action: json!({}),
            state_after: st(&[("x", json!(2))]),
        }];
        let r = score(&trs, |_, _| Ok(st(&[("x", json!(2.0))])));
        assert!(r.is_perfect());
    }

    #[test]
    fn nested_numeric_equality() {
        let trs = vec![Transition {
            state_before: st(&[]),
            action: json!({}),
            state_after: st(&[("v", json!({ "items": [1, 2] }))]),
        }];
        let r = score(&trs, |_, _| Ok(st(&[("v", json!({ "items": [1.0, 2.0] }))])));
        assert!(r.is_perfect());
    }

    #[test]
    fn score_predictions_length_mismatch_errs() {
        let trs = counter_transitions();
        let preds = vec![Ok(st(&[("count", json!(1))]))]; // too short
        assert!(score_predictions(&trs, &preds).is_err());
    }

    #[test]
    fn score_predictions_matches_closure_path() {
        let trs = counter_transitions();
        let preds: Vec<Result<State, String>> =
            trs.iter().map(|t| Ok(t.state_after.clone())).collect();
        let r = score_predictions(&trs, &preds).unwrap();
        assert!(r.is_perfect());
    }

    #[test]
    fn empty_set_is_not_perfect() {
        let r = score(&[], good_model);
        assert!(!r.is_perfect());
        assert_eq!(r.accuracy, 0.0);
    }

    #[tokio::test]
    async fn synthesize_repairs_then_succeeds() {
        use std::cell::Cell;
        // First attempt returns a broken model, second returns a good one.
        let attempt = Cell::new(0u32);
        let generate = |_prompt: String| {
            let n = attempt.get();
            attempt.set(n + 1);
            async move { Ok(format!("model-v{n}")) }
        };
        // The runner interprets the code tag: v0 is broken, v1+ is correct.
        let run = |code: &str, s: &State, a: &Value| -> Result<State, String> {
            if code == "model-v0" {
                return Ok(st(&[("count", json!(999))])); // wrong
            }
            good_model(s, a)
        };
        let req = CwmRequest {
            spec: "counter world".to_string(),
            train: counter_transitions(),
            test: counter_transitions(),
            max_attempts: 5,
        };
        let res = synthesize_cwm(generate, run, &req).await;
        assert!(res.perfect, "should repair to a perfect model");
        assert_eq!(res.code.as_deref(), Some("model-v1"));
        assert_eq!(res.attempts, 2);
        assert_eq!(res.test_accuracy, Some(1.0));
    }

    #[tokio::test]
    async fn synthesize_returns_best_when_never_perfect() {
        let generate = |_p: String| async { Ok("stuck".to_string()) };
        let run = |_c: &str, s: &State, _a: &Value| -> Result<State, String> {
            // Always returns state unchanged: matches no counter transition.
            Ok(s.clone())
        };
        let req = CwmRequest {
            spec: "counter".to_string(),
            train: counter_transitions(),
            test: counter_transitions(),
            max_attempts: 3,
        };
        let res = synthesize_cwm(generate, run, &req).await;
        assert!(!res.perfect);
        assert_eq!(res.attempts, 3);
        assert!(res.test_accuracy.is_none());
        assert!(!res.failures.is_empty());
    }

    // --- Slice 2: predictive simulation tests ---

    /// A tool-call action `id` declaring `expected_effects` (built from JSON so
    /// it tracks the IR's serde defaults rather than a brittle field list).
    fn tool_action(id: &str, effects: &[(&str, Value)]) -> Action {
        let eff: serde_json::Map<String, Value> = effects
            .iter()
            .map(|(k, v)| (k.to_string(), v.clone()))
            .collect();
        serde_json::from_value(json!({
            "type": "tool_call", "id": id, "tool": "t", "expected_effects": eff
        }))
        .unwrap()
    }

    fn proposal(actions: Vec<Action>) -> ActionProposal {
        serde_json::from_value(json!({ "actions": actions })).unwrap()
    }

    /// A model that always abstains — must reproduce `simulate` exactly.
    struct Abstain;
    impl EffectModel for Abstain {
        fn predict(&self, _a: &Action, _s: &State) -> Option<State> {
            None
        }
    }

    #[test]
    fn abstaining_model_matches_static_simulate() {
        let p = proposal(vec![
            tool_action("a1", &[("x", json!(1))]),
            tool_action("a2", &[("y", json!(2))]),
        ]);
        let with_model = simulate_with_model(&p, None, &Abstain);
        let static_sim = crate::simulate(&p, None);
        assert_eq!(with_model, static_sim);
        assert_eq!(with_model.get("x"), Some(&json!(1)));
        assert_eq!(with_model.get("y"), Some(&json!(2)));
    }

    #[test]
    fn gated_model_overrides_declared_effect_when_accurate() {
        // Declared effect says x=1; the verified model predicts x=42.
        let p = proposal(vec![tool_action("a1", &[("x", json!(1))])]);
        let mut predictions = HashMap::new();
        predictions.insert(
            "a1".to_string(),
            GatedPrediction {
                effects: st(&[("x", json!(42))]),
                accuracy: 0.99,
            },
        );
        let model = GatedEffectModel {
            predictions,
            min_accuracy: 0.9,
        };
        let out = simulate_with_model(&p, None, &model);
        assert_eq!(out.get("x"), Some(&json!(42)), "prediction should win");
    }

    #[test]
    fn gated_model_abstains_below_threshold() {
        let p = proposal(vec![tool_action("a1", &[("x", json!(1))])]);
        let mut predictions = HashMap::new();
        predictions.insert(
            "a1".to_string(),
            GatedPrediction {
                effects: st(&[("x", json!(42))]),
                accuracy: 0.50, // below gate
            },
        );
        let model = GatedEffectModel {
            predictions,
            min_accuracy: 0.9,
        };
        let out = simulate_with_model(&p, None, &model);
        // Falls back to the declared effect — an under-accurate model never
        // worsens simulation.
        assert_eq!(out.get("x"), Some(&json!(1)));
    }

    #[test]
    fn gated_model_abstains_for_unknown_action() {
        let p = proposal(vec![tool_action("a1", &[("x", json!(1))])]);
        let model = GatedEffectModel {
            predictions: HashMap::new(), // no entry for a1
            min_accuracy: 0.9,
        };
        let out = simulate_with_model(&p, None, &model);
        assert_eq!(out.get("x"), Some(&json!(1)));
    }

    #[test]
    fn statewrite_deterministic_value_always_applies() {
        // A StateWrite is fully known statically; the model abstaining must
        // still produce the write.
        let sw: Action = serde_json::from_value(json!({
            "type": "state_write", "id": "w",
            "parameters": { "key": "k", "value": "v" }
        }))
        .unwrap();
        let out = simulate_with_model(&proposal(vec![sw]), None, &Abstain);
        assert_eq!(out.get("k"), Some(&json!("v")));
    }
}