car-memgine 0.48.0

Memgine — graph-based memory engine for Common Agent Runtime
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
//! Agentic Harness Engineering — a governed Evolution Agent.
//!
//! Survey "Code as Agent Harness" §3.5 + §5.2.3: the harness itself (tool
//! schemas, retrieval policy, planning/retry config, workflow topology,
//! permission rules, validators) is a programmable component that can adapt
//! to new environments — but "the harder problem is whether a harness can
//! improve itself *without* overfitting, weakening safety, increasing cost,
//! hiding failures, or regressing on rare but important tasks."
//!
//! The discipline the survey prescribes, made concrete here:
//!
//! 1. **Every mutation carries a change contract** ([`ChangeContract`]):
//!    which component is modified, which failure mode it targets, what
//!    improvement it predicts, which invariants it must preserve, which
//!    evaluation can falsify it, and how it rolls back. "The goal is not a
//!    harness that changes often, but one that changes only when it can
//!    justify the change."
//! 2. **Diagnosis is telemetry-driven** ([`EvolutionAgent::diagnose`]): it
//!    reads the deep telemetry the event log records (via
//!    [`car_eventlog::harness_metrics::HarnessMetrics`]) and attributes
//!    cost/failure to specific harness components.
//! 3. **Promotion is regression-gated** ([`EvolutionAgent::evaluate`]): a
//!    candidate is promoted only if it improves its target *without*
//!    regressing guarded metrics beyond tolerance — evaluated on held-out
//!    telemetry, like a code change to a safety-critical runtime.
//! 4. **Governance is mandatory for safety-affecting changes**: a mutation
//!    to permissions, validators, or topology routes to a human decision
//!    (the §5.2.5 gate), never auto-promoted.
//!
//! This module is the *framework* — it produces governed, contract-bearing,
//! regression-gated mutation proposals and the decision to adopt them.
//! Applying an adopted mutation to the live harness config is the runtime
//! owner's integration step, deliberately kept outside the meta-agent.

use car_eventlog::harness_metrics::HarnessMetrics;
use serde::{Deserialize, Serialize};

/// A harness component a mutation can target. The *operating environment*
/// of the agent, not the task repository (the distinction §3.5 draws
/// between the Evolution Agent and a task agent).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HarnessComponent {
    ToolSchema,
    RetrievalPolicy,
    PlanningConfig,
    RetryConfig,
    ContextBudget,
    WorkflowTopology,
    PermissionRule,
    Validator,
    /// The agent's system prompt. The A/B loop repeatedly identifies prompt
    /// wording as its largest lever, and there was previously nowhere for an
    /// evolved prompt to live, so even a correct proposal had no path to being
    /// applied, measured, or rolled back (car#708).
    ///
    /// Safety-affecting on purpose: prompt text can talk a model out of rules
    /// the prose (rather than the policy layer) is holding, so it goes through
    /// the human-approval gate rather than being auto-promoted.
    Prompt,
}

impl HarnessComponent {
    /// Does changing this component affect safety boundaries? Such changes
    /// must not be auto-promoted — they require human approval (§5.2.3:
    /// "changes that alter permission boundaries … should require HITL
    /// approval before activation"; §5.2.5).
    pub fn is_safety_affecting(self) -> bool {
        matches!(
            self,
            HarnessComponent::PermissionRule
                | HarnessComponent::Validator
                | HarnessComponent::Prompt
                | HarnessComponent::WorkflowTopology
        )
    }
}

/// The contract a mutation must carry to be considered (§5.2.3). Without
/// it, "automated harness evolution" is unconstrained self-modification.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ChangeContract {
    /// Which harness component is modified.
    pub component: HarnessComponent,
    /// The failure mode this change targets (from diagnosis).
    pub target_failure: String,
    /// The improvement it predicts (the claim under test).
    pub predicted_improvement: String,
    /// Invariants that must hold after the change (what must not break).
    pub invariants: Vec<String>,
    /// The evaluation that could falsify the predicted improvement.
    pub falsifying_eval: String,
    /// How to roll the change back if it regresses.
    pub rollback: String,
}

/// A proposed change to the harness operating environment.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HarnessMutation {
    pub id: String,
    pub contract: ChangeContract,
    /// Human-readable rationale linking the diagnosis to the change.
    pub rationale: String,
    /// The concrete config change to apply, if this mutation targets a
    /// tunable [`HarnessConfig`] knob. `None` for diagnoses that only name a
    /// failure mode (e.g. validator/permission changes a human must design).
    /// Diagnosed mutations for tunable components carry a suggested patch.
    #[serde(default)]
    pub patch: Option<HarnessConfigPatch>,
}

impl HarnessMutation {
    /// True when this mutation must be approved by a human before
    /// activation (safety-affecting component). Governed promotion reuses
    /// the §5.2.5 permission discipline.
    pub fn requires_human_approval(&self) -> bool {
        self.contract.component.is_safety_affecting()
    }
}

/// The mutable harness operating config the Evolution Agent tunes — the
/// non-safety "knobs" of the operating environment that the runtime reads
/// live (§3.5; see `car_engine::Runtime::set_harness_config`). Every field
/// here is genuinely consumed by the executor: there are no aspirational
/// knobs. Permission rules, validators, and topology are deliberately NOT
/// here: those are safety-affecting and never auto-applied (human approval,
/// then a hand-authored change). Retrieval/context tuning has no single
/// auto-knob in the current runtime, so those diagnoses are patchless
/// proposals the owner addresses rather than fields here.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HarnessConfig {
    pub max_retries: u32,
    pub retry_backoff_ms: u64,
    pub planning_max_replans: u32,
    /// Additional guidance appended to the agent's system prompt.
    ///
    /// **Additive only.** The base prompt stays in source; this can add a
    /// section but cannot rewrite or delete one. That asymmetry is what makes a
    /// prompt safe to evolve at all: an overlay that could replace the prompt
    /// could remove the rules the prompt is carrying, and no regression gate
    /// reliably catches a rule that silently stopped being stated.
    ///
    /// `None` (or empty) means no overlay — the byte-identical prompt the coder
    /// used before this existed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt_overlay: Option<String>,
}

impl Default for HarnessConfig {
    fn default() -> Self {
        Self {
            max_retries: 3,
            retry_backoff_ms: 0,
            planning_max_replans: 2,
            prompt_overlay: None,
        }
    }
}

/// A sparse, applyable patch to [`HarnessConfig`] — only the fields a
/// mutation changes. The inverse patch (returned by `apply`) restores the
/// prior values, giving the contract's required rollback for free.
///
/// The field set is **deliberately the non-safety knobs only**. A patch
/// physically cannot express a change to a permission rule, validator, or
/// workflow topology — those don't live in [`HarnessConfig`]. So even the
/// `HumanApproved` path can only tune these five knobs; a safety boundary is
/// never mutated by `apply`, enforced by construction, not just by the
/// component check (a structural reinforcement of the §5.2.3 governance —
/// neo review). When a new field is added here, `apply_patch` MUST gain a
/// matching branch or rollback would silently drop it.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct HarnessConfigPatch {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_retries: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retry_backoff_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub planning_max_replans: Option<u32>,
    /// Set the prompt overlay. An empty string clears it, which is how a
    /// rollback expresses "there was no overlay before" — distinguishing that
    /// from "leave it alone" (`None`) is the whole reason the inverse patch can
    /// restore the original state.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt_overlay: Option<String>,
}

impl HarnessConfigPatch {
    pub fn is_empty(&self) -> bool {
        self == &HarnessConfigPatch::default()
    }
}

/// What authorizes applying a mutation to the live config. Apply refuses
/// unless one of these holds — the gate that keeps self-modification
/// governed (§5.2.3).
#[derive(Debug, Clone)]
pub enum Governance {
    /// The regression gate promoted it. Apply requires the decision to be
    /// `Promote` — and since a safety-affecting mutation can never reach
    /// `Promote` (it returns `NeedsApproval`), this path provably cannot
    /// auto-apply a safety change.
    Promoted(PromotionDecision),
    /// A human approved a safety-affecting mutation (the §5.2.5 HITL gate).
    /// Only this path may apply a safety-affecting mutation.
    HumanApproved,
}

impl HarnessConfig {
    /// Apply a mutation's concrete patch under an explicit [`Governance`]
    /// authorization, returning the **inverse patch** that rolls it back.
    /// Refuses (Err) when:
    /// - the mutation carries no concrete patch;
    /// - governance is `Promoted` but the decision isn't `Promote`;
    /// - governance is `Promoted` but the mutation is safety-affecting
    ///   (defense in depth — such a mutation should never have been
    ///   `Promote`, but we never auto-apply one regardless);
    /// so a safety-affecting change can only land via `HumanApproved`.
    ///
    /// Trust boundary: `apply` is stateless and **cannot re-run the
    /// regression gate** — it has no metrics. It trusts the supplied
    /// [`Governance`]. Pass the [`PromotionDecision`] actually returned by
    /// [`EvolutionAgent::evaluate`], not a synthesized one; and use
    /// `HumanApproved` only when a human really approved out of band (it is
    /// an unverifiable assertion that bypasses the gate requirement). The
    /// blast radius of a misused decision is bounded to the five reversible
    /// non-safety knobs and can never weaken a safety boundary.
    pub fn apply(
        &mut self,
        mutation: &HarnessMutation,
        governance: Governance,
    ) -> Result<HarnessConfigPatch, String> {
        let patch = mutation
            .patch
            .as_ref()
            .filter(|p| !p.is_empty())
            .ok_or("mutation has no concrete config patch to apply")?;

        match governance {
            Governance::Promoted(decision) => {
                if !decision.is_promote() {
                    return Err(
                        "mutation was not promoted by the regression gate; refusing to apply"
                            .into(),
                    );
                }
                if mutation.requires_human_approval() {
                    return Err(
                        "safety-affecting mutation cannot be auto-applied; requires human approval"
                            .into(),
                    );
                }
            }
            Governance::HumanApproved => {}
        }

        Ok(self.apply_patch(patch))
    }

    /// Apply a patch unconditionally, returning the inverse patch for
    /// rollback. The building block behind `apply` and the rollback path.
    pub fn apply_patch(&mut self, patch: &HarnessConfigPatch) -> HarnessConfigPatch {
        let mut inverse = HarnessConfigPatch::default();
        if let Some(v) = patch.max_retries {
            inverse.max_retries = Some(self.max_retries);
            self.max_retries = v;
        }
        if let Some(v) = patch.retry_backoff_ms {
            inverse.retry_backoff_ms = Some(self.retry_backoff_ms);
            self.retry_backoff_ms = v;
        }
        if let Some(v) = patch.planning_max_replans {
            inverse.planning_max_replans = Some(self.planning_max_replans);
            self.planning_max_replans = v;
        }
        if let Some(v) = &patch.prompt_overlay {
            // The inverse records the prior overlay, using "" for "there was
            // none" — so rolling back a first-ever overlay clears it rather
            // than leaving it in place.
            inverse.prompt_overlay = Some(self.prompt_overlay.clone().unwrap_or_default());
            self.prompt_overlay = if v.trim().is_empty() {
                None
            } else {
                Some(v.clone())
            };
        }
        inverse
    }
}

/// The outcome of evaluating a candidate mutation against a baseline.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "decision", rename_all = "snake_case")]
pub enum PromotionDecision {
    /// Adopt the mutation — target improved, no guarded regression, and not
    /// safety-affecting.
    Promote { reason: String },
    /// A safety-affecting mutation that otherwise passed — adopt only after
    /// a human approves (governed promotion).
    NeedsApproval { reason: String },
    /// Reject — the target didn't improve, or a guarded metric regressed.
    Reject { reason: String },
    /// The two sides are not measurable against each other, so no verdict was
    /// reached — distinct from `Reject`, which is a verdict.
    ///
    /// Today this fires when the two `task_pass_rate`s are rates over
    /// *different numbers of tasks*. That is not a close call: a candidate
    /// harness that stops being able to measure the tasks it would have failed
    /// reports a **higher** pass rate over a **smaller** denominator, and the
    /// comparison silently rewards it. Rejecting would be wrong too — nothing
    /// here says the candidate is bad — so the honest outcome is to refuse and
    /// say why, leaving a human to look at the two task sets.
    Incomparable { reason: String },
}

impl PromotionDecision {
    pub fn is_promote(&self) -> bool {
        matches!(self, PromotionDecision::Promote { .. })
    }

    /// No verdict was reached: the inputs could not be compared.
    pub fn is_incomparable(&self) -> bool {
        matches!(self, PromotionDecision::Incomparable { .. })
    }
}

/// Thresholds governing diagnosis and the regression gate.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct EvolutionConfig {
    /// Retries-per-action above which the retry policy is flagged.
    pub high_retry_ratio: f64,
    /// Attempt-level success rate below which recovery/planning is flagged.
    pub low_success_rate: f64,
    /// Tokens-per-successful-action above which retrieval/context is flagged.
    pub high_tokens_per_success: f64,
    /// Fractional regression tolerance on a guarded metric before a
    /// candidate is rejected (e.g. 0.02 = a 2% drop is tolerated).
    pub regression_tolerance: f64,
    /// Minimum improvement on the target metric to promote. The **unit
    /// depends on the target**: a *fractional* drop for cost/recovery
    /// targets (tokens, retries — e.g. 0.05 = 5% fewer) and an *absolute*
    /// delta for success-rate targets (e.g. 0.05 = +0.05 success rate).
    pub min_target_improvement: f64,
    /// Minimum failed attempts before proposing a (safety-affecting)
    /// validator strengthening — avoids a recurring no-op proposal every
    /// time a single unpredictable runtime failure occurs (neo review).
    pub min_failures_for_validator: usize,
}

impl Default for EvolutionConfig {
    fn default() -> Self {
        Self {
            high_retry_ratio: 0.5,
            low_success_rate: 0.7,
            high_tokens_per_success: 5000.0,
            regression_tolerance: 0.02,
            min_target_improvement: 0.05,
            min_failures_for_validator: 2,
        }
    }
}

/// The Evolution Agent: a meta-level agent that proposes and gates harness
/// mutations from telemetry. Stateless and deterministic — the same
/// telemetry yields the same proposals — so its decisions are auditable
/// and replayable.
#[derive(Debug, Clone, Default)]
pub struct EvolutionAgent {
    pub config: EvolutionConfig,
}

impl EvolutionAgent {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_config(config: EvolutionConfig) -> Self {
        Self { config }
    }

    /// Diagnose failure modes from a trajectory's harness metrics and
    /// propose contract-bearing mutations. Each proposal targets a specific
    /// component and failure mode; none is applied — they are candidates
    /// for the regression gate ([`Self::evaluate`]) and, where
    /// safety-affecting, human approval.
    ///
    /// The suggested `patch` on a tunable mutation uses **absolute** target
    /// values (it sees only metrics, not the current config), so it can move
    /// a knob the "wrong" way against an already-tuned config (e.g. propose
    /// `max_retries=2` to a config already at 1). That is safe *only* because
    /// the patch is a starting proposal the regression gate validates on
    /// held-out telemetry and is fully reversible — never apply a diagnosed
    /// patch without round-tripping through [`Self::evaluate`].
    pub fn diagnose(&self, m: &HarnessMetrics) -> Vec<HarnessMutation> {
        let mut out = Vec::new();
        let eff = &m.trajectory_efficiency;
        let rec = &m.recovery;

        // High retry volume relative to successes → the retry policy is
        // doing a lot of work; propose tuning it.
        if eff.actions_succeeded > 0 {
            let retry_ratio = rec.retries as f64 / eff.actions_succeeded as f64;
            if retry_ratio > self.config.high_retry_ratio {
                out.push(self.mutation(
                    HarnessComponent::RetryConfig,
                    "actions repeatedly fail-then-recover, inflating attempt cost",
                    "tune retry backoff/limit to cut wasted attempts without lowering recovery",
                    vec!["overall success rate must not drop".into()],
                    "replay held-out trajectories; promote only if attempts fall and success holds",
                    "restore the previous retry config",
                    format!(
                        "retries/success = {retry_ratio:.2} exceeds {:.2}",
                        self.config.high_retry_ratio
                    ),
                    Some(HarnessConfigPatch {
                        max_retries: Some(2),
                        retry_backoff_ms: Some(100),
                        ..Default::default()
                    }),
                ));
            }
        }

        // Low attempt-level success with replan exhaustion → planning is
        // failing to find a working trajectory.
        if let Some(sr) = eff.success_rate {
            if sr < self.config.low_success_rate && rec.replan_exhausted > 0 {
                out.push(self.mutation(
                    HarnessComponent::PlanningConfig,
                    "plans fail and replanning exhausts without recovering",
                    "adjust decomposition/replan budget to reach a working trajectory",
                    vec!["token cost must not increase beyond tolerance".into()],
                    "replay held-out tasks; promote only if success rises without cost regression",
                    "restore the previous planning config",
                    format!(
                        "success_rate {sr:.2} below {:.2} with {} replan exhaustions",
                        self.config.low_success_rate, rec.replan_exhausted
                    ),
                    Some(HarnessConfigPatch {
                        planning_max_replans: Some(4),
                        ..Default::default()
                    }),
                ));
            }
        }

        // High token cost per success → retrieval/context is over-spending.
        if eff.actions_succeeded > 0 {
            let tps = eff.total_tokens as f64 / eff.actions_succeeded as f64;
            if tps > self.config.high_tokens_per_success {
                out.push(self.mutation(
                    HarnessComponent::RetrievalPolicy,
                    "token spend per successful action is high — retrieval or context is bloated",
                    "tighten retrieval/context budget to cut tokens without lowering success",
                    vec![
                        "success rate must not drop".into(),
                        "verification strength must hold".into(),
                    ],
                    "replay held-out trajectories; promote only if tokens fall and success holds",
                    "restore the previous retrieval policy / context budget",
                    format!(
                        "tokens/success = {tps:.0} exceeds {:.0}",
                        self.config.high_tokens_per_success
                    ),
                    // No single auto-knob for retrieval/context in the
                    // current runtime — a proposal the owner addresses.
                    None,
                ));
            }
        }

        // Failures with zero verification activity → the validator let
        // problems through (a weak-oracle smell). Safety-affecting →
        // proposal will require human approval.
        if eff.failed_attempts >= self.config.min_failures_for_validator
            && m.verification_strength.actions_rejected == 0
        {
            out.push(self.mutation(
                HarnessComponent::Validator,
                "actions failed at runtime but verification rejected nothing — weak oracle",
                "add/strengthen a pre-execution check to catch this failure class earlier",
                vec!["must not raise false-rejection rate on previously-passing tasks".into()],
                "replay held-out trajectories incl. known-good ones; promote only if it catches the failure without new false rejections",
                "remove the added check",
                format!("{} failed attempts with 0 verifier rejections", eff.failed_attempts),
                None, // safety-affecting: a human designs the validator change
            ));
        }

        // Repeated permission denials → the permission rules may be
        // mis-scoped. Safety-affecting → human approval required.
        if m.safety.denials > 0 {
            out.push(self.mutation(
                HarnessComponent::PermissionRule,
                "actions are repeatedly denied by the permission gate",
                "re-scope the permission rule so legitimate actions are not blocked",
                vec!["must not widen access for genuinely high-risk actions".into()],
                "human review of the affected actions plus held-out replay",
                "restore the previous permission rule",
                format!("{} permission denials observed", m.safety.denials),
                None, // safety-affecting: re-scoping a permission rule is a human decision
            ));
        }

        out
    }

    /// Regression-gated evaluation of a candidate mutation. `baseline` and
    /// `candidate` are harness metrics measured before and after applying
    /// the mutation on held-out telemetry. Promotes only if the target
    /// metric improved by at least `min_target_improvement` and no guarded
    /// metric regressed beyond `regression_tolerance`; routes
    /// safety-affecting mutations to human approval even when they pass.
    ///
    /// Two reliability guards, not one. `task_pass_rate` (end-task success,
    /// supplied by a task-suite runner) is checked first when BOTH sides carry
    /// it; `trajectory_efficiency.success_rate` (tool-attempt success, always
    /// derivable from the log) is checked next. A candidate can hold the second
    /// perfectly while regressing the first, which is exactly the "cheaper but
    /// solves less" candidate the gate exists to stop.
    ///
    /// Ahead of both sits a comparability check, and it returns a **fourth**
    /// outcome. When both sides report `task_pass_denominator` and the two
    /// disagree, the answer is [`PromotionDecision::Incomparable`] — the pass
    /// rates are fractions over different task sets, so neither "it improved"
    /// nor "it regressed" is a claim the numbers support. That is deliberately
    /// not a rejection: nothing here says the candidate is bad, only that this
    /// evidence cannot decide it. Match it explicitly; folding it into a
    /// wildcard arm re-hides the shrinking denominator this guard exists to
    /// surface.
    pub fn evaluate(
        &self,
        mutation: &HarnessMutation,
        baseline: &HarnessMetrics,
        candidate: &HarnessMetrics,
    ) -> PromotionDecision {
        // Guard -1: the two task pass rates must be rates over the SAME number
        // of tasks, when both sides say how many.
        //
        // A pass rate is a fraction, and comparing two fractions with different
        // denominators as if they were the same measurement is the oldest
        // mistake there is. It matters here because the denominator is not
        // fixed by nature — a runner drops a task whenever it cannot measure
        // it, and what it can measure depends on the harness's own toolset,
        // which is a declared, auto-promotable mutation target
        // (`HarnessComponent::ToolSchema`). A candidate that loses file reading
        // makes the file-reading tasks unmeasurable; they leave the
        // denominator; the surviving tasks are the ones it still passes; the
        // scalar goes UP. Guard 0 below would then read an improvement and wave
        // through a harness that got strictly worse.
        //
        // Refusing is not rejecting. Nothing here says the candidate is bad —
        // it says the evidence does not support a verdict, which is a different
        // claim and deserves its own outcome rather than being folded into
        // either answer.
        //
        // Only fires when BOTH sides carry a denominator. An older document
        // predates the field, and absent means "this runner does not report
        // it", not "one task" — inventing a value to compare against would be
        // the same fabrication this guard exists to catch.
        if let (Some(base_n), Some(cand_n)) = (
            baseline.task_pass_denominator,
            candidate.task_pass_denominator,
        ) {
            if base_n != cand_n {
                return PromotionDecision::Incomparable {
                    reason: format!(
                        "task pass rates are over different task sets — baseline graded \
                         {base_n} task(s), candidate graded {cand_n}. A rate over a smaller \
                         denominator is not an improvement over a larger one, and a harness \
                         that can no longer MEASURE the tasks it would have failed produces \
                         exactly this shape. Compare the two task sets before reading either \
                         number (baseline unrunnable: {}, candidate unrunnable: {}).",
                        baseline
                            .tasks_unrunnable
                            .map_or("unreported".to_string(), |n| n.to_string()),
                        candidate
                            .tasks_unrunnable
                            .map_or("unreported".to_string(), |n| n.to_string()),
                    ),
                };
            }
        }

        // Guard 0: end-TASK success must not regress beyond tolerance, when
        // both sides measured it.
        //
        // This runs before the attempt-level guard below because the two
        // measure different things and only this one sees the failure mode that
        // matters most: a candidate that finishes fewer TASKS while every tool
        // call it makes still succeeds. Attempt-level `success_rate` is blind to
        // that — it would read 1.0 for both arms — so a token-cutting candidate
        // that quietly solves less would have promoted cleanly.
        //
        // When either side is `None` the guard does not fire at all. An
        // unmeasured pass rate is not evidence of a regression and not evidence
        // of a hold; treating absent as 0.0 would reject every caller who never
        // ran a task suite, and treating it as 1.0 would wave them through.
        if let (Some(base_tpr), Some(cand_tpr)) =
            (baseline.task_pass_rate, candidate.task_pass_rate)
        {
            if cand_tpr + self.config.regression_tolerance < base_tpr {
                return PromotionDecision::Reject {
                    reason: format!(
                        "TASK pass rate (end-task success, not tool-attempt success) regressed \
                         {base_tpr:.3} -> {cand_tpr:.3} (beyond tolerance {:.3})",
                        self.config.regression_tolerance
                    ),
                };
            }
        }

        // Guard 1: attempt-level success rate must not regress beyond tolerance
        // (always guarded — it's the load-bearing reliability metric).
        let base_sr = baseline.trajectory_efficiency.success_rate.unwrap_or(0.0);
        let cand_sr = candidate.trajectory_efficiency.success_rate.unwrap_or(0.0);
        if cand_sr + self.config.regression_tolerance < base_sr {
            return PromotionDecision::Reject {
                reason: format!(
                    "success rate regressed {base_sr:.3} -> {cand_sr:.3} (beyond tolerance {:.3})",
                    self.config.regression_tolerance
                ),
            };
        }

        // Target improvement, by component.
        // A cost/recovery win is only real if the candidate still did
        // meaningful work — otherwise a candidate that succeeds at nothing
        // trivially "saves tokens/retries" and would be promoted (neo
        // review 1b). The success guard above only catches a *drop*, not a
        // candidate that started near-zero.
        let candidate_did_work = candidate.trajectory_efficiency.actions_succeeded > 0;
        let improved = match mutation.contract.component {
            // Cost-reduction targets: fewer tokens for comparable success.
            HarnessComponent::RetrievalPolicy | HarnessComponent::ContextBudget => {
                let base = baseline.trajectory_efficiency.total_tokens as f64;
                let cand = candidate.trajectory_efficiency.total_tokens as f64;
                candidate_did_work
                    && base > 0.0
                    && (base - cand) / base >= self.config.min_target_improvement
            }
            // Recovery/efficiency targets: fewer retries for comparable success.
            HarnessComponent::RetryConfig => {
                let base = baseline.recovery.retries as f64;
                let cand = candidate.recovery.retries as f64;
                candidate_did_work
                    && base > 0.0
                    && (base - cand) / base >= self.config.min_target_improvement
            }
            // Success-improving targets. A prompt change is judged the same
            // way — the A/B identifies prompt wording as a lever precisely
            // because it moves task success, not token cost.
            HarnessComponent::PlanningConfig
            | HarnessComponent::ToolSchema
            | HarnessComponent::WorkflowTopology
            | HarnessComponent::Prompt => cand_sr - base_sr >= self.config.min_target_improvement,
            // Verification: caught more before execution without losing success.
            HarnessComponent::Validator => {
                candidate.verification_strength.actions_rejected
                    > baseline.verification_strength.actions_rejected
            }
            // Permission: fewer spurious denials without losing success.
            HarnessComponent::PermissionRule => candidate.safety.denials < baseline.safety.denials,
        };

        // Reject before the approval check is intentional and fail-safe:
        // a non-improving safety mutation is *not* surfaced for approval
        // because Reject never activates anything (more conservative than
        // NeedsApproval), and surfacing every non-improving safety proposal
        // would only add review burden. Do not reorder (neo review Nit-A).
        if !improved {
            return PromotionDecision::Reject {
                reason:
                    "target metric did not improve by the required margin on held-out telemetry"
                        .into(),
            };
        }

        if mutation.requires_human_approval() {
            return PromotionDecision::NeedsApproval {
                reason: format!(
                    "mutation passed the regression gate but targets a safety-affecting component ({:?}); human approval required",
                    mutation.contract.component
                ),
            };
        }

        PromotionDecision::Promote {
            reason: "target improved and no guarded metric regressed on held-out telemetry".into(),
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn mutation(
        &self,
        component: HarnessComponent,
        target_failure: &str,
        predicted: &str,
        invariants: Vec<String>,
        falsifying: &str,
        rollback: &str,
        rationale: String,
        patch: Option<HarnessConfigPatch>,
    ) -> HarnessMutation {
        HarnessMutation {
            id: format!(
                "mut-{}-{}",
                component_slug(component),
                mutation_digest(component, patch.as_ref(), target_failure)
            ),
            contract: ChangeContract {
                component,
                target_failure: target_failure.into(),
                predicted_improvement: predicted.into(),
                invariants,
                falsifying_eval: falsifying.into(),
                rollback: rollback.into(),
            },
            rationale,
            patch,
        }
    }
}

/// The stable content digest a mutation's id/fingerprint binds: the component
/// plus the concrete config patch (or, for patchless proposals, the
/// `target_failure` — a fixed literal naming the failure class). Deliberately
/// NOT the rationale: rationale embeds live measurements ("ratio 0.52"), so
/// hashing it would mint a fresh identity on every re-diagnosis and a standing
/// human approval could never match its mutation again (kernel review C2).
/// What a human approves is the *change* — "set max_retries=2, backoff=100ms
/// on retry config" — and that is exactly what is hashed.
fn mutation_digest(
    component: HarnessComponent,
    patch: Option<&HarnessConfigPatch>,
    target_failure: &str,
) -> String {
    let content = match patch {
        // Struct serialization has deterministic field order.
        Some(p) if !p.is_empty() => serde_json::to_string(p).unwrap_or_default(),
        _ => target_failure.to_string(),
    };
    short_hash(&format!("{}|{}", component_slug(component), content))
}

/// The durable-approval fingerprint for a harness mutation:
/// `harness:<component>:<content-digest>`. Stable across re-diagnoses of the
/// same underlying change (see [`mutation_digest`]), human-readable enough to
/// review in a ledger, and shared by the daemon's `evolution.run` HITL loop —
/// approve it once via `permission.approve` and every later cycle that
/// proposes the same patch matches it.
pub fn mutation_fingerprint(m: &HarnessMutation) -> String {
    format!(
        "harness:{}:{}",
        component_slug(m.contract.component),
        mutation_digest(
            m.contract.component,
            m.patch.as_ref(),
            &m.contract.target_failure
        )
    )
}

fn component_slug(c: HarnessComponent) -> &'static str {
    match c {
        HarnessComponent::ToolSchema => "toolschema",
        HarnessComponent::RetrievalPolicy => "retrieval",
        HarnessComponent::PlanningConfig => "planning",
        HarnessComponent::RetryConfig => "retry",
        HarnessComponent::ContextBudget => "context",
        HarnessComponent::WorkflowTopology => "topology",
        HarnessComponent::PermissionRule => "permission",
        HarnessComponent::Validator => "validator",
        HarnessComponent::Prompt => "prompt",
    }
}

/// A short, deterministic digest (no RNG, so the same content yields the same
/// mutation id/fingerprint — auditable/replayable).
fn short_hash(s: &str) -> String {
    let mut h: u64 = 1469598103934665603; // FNV-1a 64-bit offset basis
    for b in s.bytes() {
        h ^= b as u64;
        h = h.wrapping_mul(1099511628211); // FNV-1a 64-bit prime
    }
    format!("{:08x}", h & 0xffff_ffff)
}

#[cfg(test)]
mod tests {
    use super::*;
    use car_eventlog::harness_metrics::HarnessMetrics;

    fn metrics() -> HarnessMetrics {
        HarnessMetrics::default()
    }

    #[test]
    fn diagnoses_high_retry_into_retry_config() {
        let mut m = metrics();
        m.trajectory_efficiency.actions_succeeded = 4;
        m.recovery.retries = 6; // ratio 1.5 > 0.5
        let muts = EvolutionAgent::new().diagnose(&m);
        assert!(muts
            .iter()
            .any(|x| x.contract.component == HarnessComponent::RetryConfig));
    }

    #[test]
    fn diagnoses_weak_validator_as_safety_affecting() {
        let mut m = metrics();
        m.trajectory_efficiency.failed_attempts = 3;
        m.verification_strength.actions_rejected = 0;
        let muts = EvolutionAgent::new().diagnose(&m);
        let v = muts
            .iter()
            .find(|x| x.contract.component == HarnessComponent::Validator)
            .expect("validator mutation");
        assert!(v.requires_human_approval());
    }

    #[test]
    fn clean_telemetry_yields_no_mutations() {
        let mut m = metrics();
        m.trajectory_efficiency.actions_succeeded = 10;
        m.trajectory_efficiency.success_rate = Some(1.0);
        assert!(EvolutionAgent::new().diagnose(&m).is_empty());
    }

    #[test]
    fn mutation_id_is_deterministic() {
        let mut m = metrics();
        m.trajectory_efficiency.actions_succeeded = 4;
        m.recovery.retries = 6;
        let a = EvolutionAgent::new().diagnose(&m);
        let b = EvolutionAgent::new().diagnose(&m);
        assert_eq!(a[0].id, b[0].id);
    }

    #[test]
    fn fingerprint_binds_patch_content_not_live_measurements() {
        // Kernel review C2: the same underlying change diagnosed from
        // DIFFERENT live metric values (rationale embeds "retries/success =
        // 1.50" vs "5.00") must keep one identity — else an operator approval
        // never matches a re-run.
        let agent = EvolutionAgent::new();
        let mut m1 = metrics();
        m1.trajectory_efficiency.actions_succeeded = 4;
        m1.recovery.retries = 6; // ratio 1.50
        let mut m2 = metrics();
        m2.trajectory_efficiency.actions_succeeded = 2;
        m2.recovery.retries = 10; // ratio 5.00
        let a = &agent.diagnose(&m1)[0];
        let b = &agent.diagnose(&m2)[0];
        assert_ne!(a.rationale, b.rationale, "rationales differ (live floats)");
        assert_eq!(a.id, b.id, "id binds component+patch, not prose");
        assert_eq!(mutation_fingerprint(a), mutation_fingerprint(b));
        // Human-readable shape: harness:<component>:<digest>.
        let fp = mutation_fingerprint(a);
        assert!(fp.starts_with("harness:retry:"), "{fp}");
    }

    #[test]
    fn fingerprint_differs_across_distinct_changes() {
        // Different component or different patch content = different thing to
        // authorize.
        let retry = retry_mutation();
        let mut other_patch = retry_mutation();
        other_patch.patch = Some(HarnessConfigPatch {
            max_retries: Some(5),
            ..Default::default()
        });
        let mut other_component = retry_mutation();
        other_component.contract.component = HarnessComponent::PlanningConfig;
        assert_ne!(
            mutation_fingerprint(&retry),
            mutation_fingerprint(&other_patch)
        );
        assert_ne!(
            mutation_fingerprint(&retry),
            mutation_fingerprint(&other_component)
        );
    }

    fn retry_mutation() -> HarnessMutation {
        HarnessMutation {
            id: "m".into(),
            rationale: "r".into(),
            contract: ChangeContract {
                component: HarnessComponent::RetryConfig,
                target_failure: "f".into(),
                predicted_improvement: "p".into(),
                invariants: vec![],
                falsifying_eval: "e".into(),
                rollback: "rb".into(),
            },
            patch: Some(HarnessConfigPatch {
                max_retries: Some(2),
                ..Default::default()
            }),
        }
    }

    #[test]
    fn regression_gate_rejects_success_drop() {
        let agent = EvolutionAgent::new();
        let mut base = metrics();
        base.trajectory_efficiency.success_rate = Some(0.9);
        base.recovery.retries = 10;
        let mut cand = metrics();
        cand.trajectory_efficiency.success_rate = Some(0.5); // big regression
        cand.recovery.retries = 2;
        let d = agent.evaluate(&retry_mutation(), &base, &cand);
        assert!(matches!(d, PromotionDecision::Reject { .. }), "{d:?}");
    }

    #[test]
    fn regression_gate_promotes_improvement_without_regression() {
        let agent = EvolutionAgent::new();
        let mut base = metrics();
        base.trajectory_efficiency.actions_succeeded = 9;
        base.trajectory_efficiency.success_rate = Some(0.9);
        base.recovery.retries = 10;
        let mut cand = metrics();
        cand.trajectory_efficiency.actions_succeeded = 9; // still did the work
        cand.trajectory_efficiency.success_rate = Some(0.9); // held
        cand.recovery.retries = 4; // retries down 60% > 5% target
        let d = agent.evaluate(&retry_mutation(), &base, &cand);
        assert!(d.is_promote(), "{d:?}");
    }

    /// The failure the attempt-level guard cannot see: a candidate that cuts
    /// retries (its target) and keeps every tool call succeeding, while
    /// finishing fewer TASKS. Without the task-pass-rate guard this promotes.
    #[test]
    fn task_pass_rate_regression_is_rejected() {
        let agent = EvolutionAgent::new();
        let mut base = metrics();
        base.trajectory_efficiency.actions_succeeded = 9;
        base.trajectory_efficiency.success_rate = Some(1.0);
        base.recovery.retries = 10;
        base.task_pass_rate = Some(0.80);
        let mut cand = metrics();
        cand.trajectory_efficiency.actions_succeeded = 9;
        cand.trajectory_efficiency.success_rate = Some(1.0); // attempt-level: perfect
        cand.recovery.retries = 4; // target improved 60%
        cand.task_pass_rate = Some(0.60); // but it solves fewer tasks

        let d = agent.evaluate(&retry_mutation(), &base, &cand);
        match &d {
            PromotionDecision::Reject { reason } => assert!(
                reason.to_lowercase().contains("task pass rate"),
                "the reason must name it as the TASK pass rate so it is not \
                 confused with the attempt-level guard: {reason}"
            ),
            other => panic!("expected Reject, got {other:?}"),
        }

        // Proof the attempt-level guard alone would NOT have caught this: drop
        // the measured task pass rate and the same candidate promotes.
        let (mut base2, mut cand2) = (base.clone(), cand.clone());
        base2.task_pass_rate = None;
        cand2.task_pass_rate = None;
        assert!(
            agent
                .evaluate(&retry_mutation(), &base2, &cand2)
                .is_promote(),
            "without task_pass_rate this candidate promotes — which is the defect"
        );
    }

    /// A held (or improved) task pass rate must not change the outcome: the
    /// guard is a regression check, not a second improvement bar.
    #[test]
    fn held_task_pass_rate_leaves_the_decision_unchanged() {
        let agent = EvolutionAgent::new();
        let mut base = metrics();
        base.trajectory_efficiency.actions_succeeded = 9;
        base.trajectory_efficiency.success_rate = Some(0.9);
        base.recovery.retries = 10;
        let mut cand = metrics();
        cand.trajectory_efficiency.actions_succeeded = 9;
        cand.trajectory_efficiency.success_rate = Some(0.9);
        cand.recovery.retries = 4;

        let without = agent.evaluate(&retry_mutation(), &base, &cand);
        assert!(without.is_promote(), "{without:?}");

        let (mut base2, mut cand2) = (base.clone(), cand.clone());
        base2.task_pass_rate = Some(0.80);
        cand2.task_pass_rate = Some(0.80); // held
        assert_eq!(agent.evaluate(&retry_mutation(), &base2, &cand2), without);

        // A drop inside the tolerance is a hold, not a regression.
        cand2.task_pass_rate = Some(0.79);
        assert_eq!(agent.evaluate(&retry_mutation(), &base2, &cand2), without);
    }

    /// One side unmeasured means the guard does not fire — an absent pass rate
    /// must neither promote nor reject on its own.
    #[test]
    fn an_unmeasured_task_pass_rate_changes_nothing() {
        let agent = EvolutionAgent::new();
        let mut base = metrics();
        base.trajectory_efficiency.actions_succeeded = 9;
        base.trajectory_efficiency.success_rate = Some(0.9);
        base.recovery.retries = 10;
        let mut cand = metrics();
        cand.trajectory_efficiency.actions_succeeded = 9;
        cand.trajectory_efficiency.success_rate = Some(0.9);
        cand.recovery.retries = 4;
        let baseline_decision = agent.evaluate(&retry_mutation(), &base, &cand);
        assert!(baseline_decision.is_promote(), "{baseline_decision:?}");

        // Candidate measured a catastrophic pass rate, baseline never measured
        // one: there is nothing to compare, so the decision is today's.
        let (mut b1, mut c1) = (base.clone(), cand.clone());
        b1.task_pass_rate = None;
        c1.task_pass_rate = Some(0.01);
        assert_eq!(
            agent.evaluate(&retry_mutation(), &b1, &c1),
            baseline_decision
        );

        // And the mirror: baseline measured, candidate did not.
        let (mut b2, mut c2) = (base.clone(), cand.clone());
        b2.task_pass_rate = Some(0.95);
        c2.task_pass_rate = None;
        assert_eq!(
            agent.evaluate(&retry_mutation(), &b2, &c2),
            baseline_decision
        );

        // A rejecting decision is equally unchanged by an absent pass rate.
        let mut bad = cand.clone();
        bad.trajectory_efficiency.success_rate = Some(0.5);
        let rejected = agent.evaluate(&retry_mutation(), &base, &bad);
        assert!(matches!(rejected, PromotionDecision::Reject { .. }));
        let mut bad_none = bad.clone();
        bad_none.task_pass_rate = None;
        let mut base_measured = base.clone();
        base_measured.task_pass_rate = Some(0.95);
        assert_eq!(
            agent.evaluate(&retry_mutation(), &base_measured, &bad_none),
            rejected
        );
    }

    /// The exploit the denominator exists to stop, run end to end.
    ///
    /// A `ToolSchema` mutation is non-safety-affecting and auto-promotable. Take
    /// away the harness's file tools and every task whose grading criteria can
    /// only be satisfied by a file tool stops being *measurable* — so the runner
    /// drops it from the denominator. The tasks that leave are precisely the
    /// ones a file-blind harness would have failed, so the surviving rate goes
    /// UP. Read as a bare scalar, that is an improvement.
    #[test]
    fn a_pass_rate_over_a_shrunken_task_set_is_refused_not_promoted() {
        let agent = EvolutionAgent::new();
        let mut mutation = retry_mutation();
        mutation.contract.component = HarnessComponent::ToolSchema;

        let mut base = metrics();
        base.trajectory_efficiency.actions_succeeded = 9;
        base.trajectory_efficiency.success_rate = Some(0.90);
        base.task_pass_rate = Some(0.75); // 9 of 12
        base.task_pass_denominator = Some(12);
        base.tasks_unrunnable = Some(0);

        let mut cand = metrics();
        cand.trajectory_efficiency.actions_succeeded = 9;
        cand.trajectory_efficiency.success_rate = Some(0.99); // clears the improvement bar
        cand.task_pass_rate = Some(1.0); // 8 of 8 — every remaining task
        cand.task_pass_denominator = Some(8); // …because 4 became unmeasurable
        cand.tasks_unrunnable = Some(4);

        let d = agent.evaluate(&mutation, &base, &cand);
        match &d {
            PromotionDecision::Incomparable { reason } => {
                assert!(
                    reason.contains("12"),
                    "must name both denominators: {reason}"
                );
                assert!(
                    reason.contains('8'),
                    "must name both denominators: {reason}"
                );
            }
            other => {
                panic!("a pass rate over a smaller task set must not be compared; got {other:?}")
            }
        }
        assert!(!d.is_promote());
        assert!(d.is_incomparable());

        // Proof this is what did the work: give the candidate the SAME
        // denominator and the identical numbers promote.
        let mut honest = cand.clone();
        honest.task_pass_denominator = Some(12);
        honest.tasks_unrunnable = Some(0);
        assert!(
            agent.evaluate(&mutation, &base, &honest).is_promote(),
            "with comparable denominators this candidate is a genuine win"
        );
    }

    /// Absent denominators must not start refusing every existing caller. A
    /// document written before the field existed carries neither key, and
    /// "unreported" is not "different".
    #[test]
    fn an_absent_denominator_does_not_refuse_the_comparison() {
        let agent = EvolutionAgent::new();
        let mut base = metrics();
        base.trajectory_efficiency.actions_succeeded = 9;
        base.trajectory_efficiency.success_rate = Some(0.9);
        base.recovery.retries = 10;
        base.task_pass_rate = Some(0.8);
        let mut cand = metrics();
        cand.trajectory_efficiency.actions_succeeded = 9;
        cand.trajectory_efficiency.success_rate = Some(0.9);
        cand.recovery.retries = 4;
        cand.task_pass_rate = Some(0.8);

        let both_absent = agent.evaluate(&retry_mutation(), &base, &cand);
        assert!(both_absent.is_promote(), "{both_absent:?}");

        // One side reports, the other does not: still not a refusal — we cannot
        // know the sets differ, and inventing a denominator to compare against
        // would be the fabrication the guard exists to prevent.
        let mut b1 = base.clone();
        b1.task_pass_denominator = Some(12);
        assert_eq!(agent.evaluate(&retry_mutation(), &b1, &cand), both_absent);
        let mut c1 = cand.clone();
        c1.task_pass_denominator = Some(12);
        assert_eq!(agent.evaluate(&retry_mutation(), &base, &c1), both_absent);

        // Both report and agree: unchanged.
        assert_eq!(agent.evaluate(&retry_mutation(), &b1, &c1), both_absent);
    }

    /// What actually stops an evolved mutation from rewriting the toolset the
    /// bench measures against — asserted, because it was previously only
    /// asserted in a comment.
    ///
    /// `HarnessComponent::ToolSchema` is a declared, non-safety-affecting,
    /// auto-promotable target, so the component check does NOT block it. The
    /// real barrier is structural: `HarnessConfigPatch` has four fields and none
    /// of them is a toolset, so `apply` cannot express the change however the
    /// mutation is worded. If that ever weakens — someone adds a `tools` field —
    /// this test is what says so, rather than a bench comment three crates away
    /// quietly becoming false.
    #[test]
    fn a_config_patch_cannot_express_a_toolset_change() {
        // The component itself is auto-promotable. This is the part people
        // assume blocks the exploit; it does not.
        assert!(!HarnessComponent::ToolSchema.is_safety_affecting());

        // The patch's entire expressible surface.
        let full = HarnessConfigPatch {
            max_retries: Some(1),
            retry_backoff_ms: Some(1),
            planning_max_replans: Some(1),
            prompt_overlay: Some("x".into()),
        };
        // Sorted: this asserts the SET of expressible fields, not their order.
        let mut keys: Vec<String> = serde_json::to_value(&full)
            .unwrap()
            .as_object()
            .unwrap()
            .keys()
            .cloned()
            .collect();
        keys.sort();
        assert_eq!(
            keys,
            [
                "max_retries",
                "planning_max_replans",
                "prompt_overlay",
                "retry_backoff_ms",
            ],
            "a new field here can change what `apply` is able to mutate — if one \
             of them is ever a toolset, the bench's unrunnable-task set becomes \
             reachable by an auto-promoted mutation and its pass-rate \
             denominator becomes attacker-controlled"
        );

        // And a mutation that TRIES to say it, cannot. Unknown keys are dropped,
        // leaving an empty patch — not a toolset change.
        let attempted: HarnessConfigPatch = serde_json::from_str(
            r#"{"tools":["read_file"],"tool_defs":[],"tool_schema":{"name":"x"}}"#,
        )
        .unwrap();
        assert!(
            attempted.is_empty(),
            "a patch claiming to change the toolset must decode to nothing: {attempted:?}"
        );
    }

    #[test]
    fn cost_win_on_a_candidate_that_does_no_work_is_rejected() {
        // Degenerate candidate: spends fewer tokens but succeeds at nothing
        // (neo review 1b) — must not be promoted on the token drop alone.
        let agent = EvolutionAgent::new();
        let mut mutation = retry_mutation();
        mutation.contract.component = HarnessComponent::RetrievalPolicy;
        let mut base = metrics();
        base.trajectory_efficiency.actions_succeeded = 5;
        base.trajectory_efficiency.success_rate = Some(0.8);
        base.trajectory_efficiency.total_tokens = 10_000;
        let mut cand = metrics();
        cand.trajectory_efficiency.actions_succeeded = 0; // did nothing
        cand.trajectory_efficiency.total_tokens = 100; // "cheap"
        let d = agent.evaluate(&mutation, &base, &cand);
        assert!(matches!(d, PromotionDecision::Reject { .. }), "{d:?}");
    }

    #[test]
    fn single_failure_does_not_propose_validator() {
        // Below min_failures_for_validator (2): a lone unpredictable
        // failure must not generate a recurring safety proposal (neo Nit-B).
        let mut m = metrics();
        m.trajectory_efficiency.failed_attempts = 1;
        m.verification_strength.actions_rejected = 0;
        let muts = EvolutionAgent::new().diagnose(&m);
        assert!(!muts
            .iter()
            .any(|x| x.contract.component == HarnessComponent::Validator));
    }

    #[test]
    fn safety_affecting_mutation_needs_approval_even_when_passing() {
        let agent = EvolutionAgent::new();
        let mut mutation = retry_mutation();
        mutation.contract.component = HarnessComponent::Validator;
        let mut base = metrics();
        base.trajectory_efficiency.success_rate = Some(0.8);
        base.verification_strength.actions_rejected = 1;
        let mut cand = metrics();
        cand.trajectory_efficiency.success_rate = Some(0.8); // held
        cand.verification_strength.actions_rejected = 4; // caught more
        let d = agent.evaluate(&mutation, &base, &cand);
        assert!(
            matches!(d, PromotionDecision::NeedsApproval { .. }),
            "{d:?}"
        );
    }

    // --- applying mutations to live config (governed) ---

    #[test]
    fn apply_promoted_mutation_changes_config_and_returns_rollback() {
        let mut cfg = HarnessConfig::default();
        assert_eq!(cfg.max_retries, 3);
        let m = retry_mutation(); // patch sets max_retries=2
        let inverse = cfg
            .apply(
                &m,
                Governance::Promoted(PromotionDecision::Promote {
                    reason: "ok".into(),
                }),
            )
            .expect("apply");
        assert_eq!(cfg.max_retries, 2);
        // The inverse patch restores the prior value.
        cfg.apply_patch(&inverse);
        assert_eq!(cfg.max_retries, 3);
    }

    #[test]
    fn apply_refuses_unpromoted_mutation() {
        let mut cfg = HarnessConfig::default();
        let m = retry_mutation();
        let r = cfg.apply(
            &m,
            Governance::Promoted(PromotionDecision::Reject {
                reason: "no".into(),
            }),
        );
        assert!(r.is_err());
        assert_eq!(cfg.max_retries, 3); // unchanged
    }

    #[test]
    fn apply_refuses_safety_mutation_under_auto_promotion() {
        // Even if somehow handed a Promote decision, a safety-affecting
        // mutation can't be auto-applied (defense in depth).
        let mut cfg = HarnessConfig::default();
        let mut m = retry_mutation();
        m.contract.component = HarnessComponent::Validator;
        m.patch = Some(HarnessConfigPatch {
            max_retries: Some(1),
            ..Default::default()
        });
        let r = cfg.apply(
            &m,
            Governance::Promoted(PromotionDecision::Promote { reason: "x".into() }),
        );
        assert!(r.is_err(), "safety mutation must not auto-apply");
        assert_eq!(cfg.max_retries, 3);
    }

    #[test]
    fn human_approved_safety_mutation_applies() {
        // The post-approval path may apply a safety-affecting mutation.
        let mut cfg = HarnessConfig::default();
        let mut m = retry_mutation();
        m.contract.component = HarnessComponent::WorkflowTopology;
        m.patch = Some(HarnessConfigPatch {
            planning_max_replans: Some(5),
            ..Default::default()
        });
        cfg.apply(&m, Governance::HumanApproved)
            .expect("apply approved");
        assert_eq!(cfg.planning_max_replans, 5);
    }

    #[test]
    fn apply_refuses_mutation_without_patch() {
        let mut cfg = HarnessConfig::default();
        let mut m = retry_mutation();
        m.patch = None;
        let r = cfg.apply(&m, Governance::HumanApproved);
        assert!(r.is_err());
    }

    #[test]
    fn diagnosed_tunable_mutation_carries_a_patch() {
        // The retry diagnosis should attach a concrete, applyable patch.
        let mut mm = metrics();
        mm.trajectory_efficiency.actions_succeeded = 4;
        mm.recovery.retries = 6;
        let muts = EvolutionAgent::new().diagnose(&mm);
        let retry = muts
            .iter()
            .find(|x| x.contract.component == HarnessComponent::RetryConfig)
            .unwrap();
        assert!(retry.patch.is_some());
    }
}