eidetic-engine 0.15.1

Durable, local-first, explainable memory for coding agents.
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
//! Decision-plane tracking metadata (EE-364).
//!
//! Provides `policy_id`, `decision_id`, and `trace_id` fields for records
//! that affect ranking, packing, curation, repair ordering, or cache admission.
//! This enables shadow-run comparisons, policy replay, and audit trails.

use std::fmt;
use std::str::FromStr;

use chrono::{SecondsFormat, Utc};
use serde::{Deserialize, Serialize};

fn normalized_decision_plane_token(input: &str) -> String {
    let trimmed = input.trim();
    let mut normalized = String::with_capacity(trimmed.len());
    let mut previous_was_lowercase = false;
    let mut previous_was_separator = false;

    for character in trimmed.chars() {
        match character {
            '-' | '_' => {
                if !normalized.is_empty() && !previous_was_separator {
                    normalized.push('_');
                }
                previous_was_lowercase = false;
                previous_was_separator = true;
            }
            character if character.is_ascii_uppercase() => {
                if previous_was_lowercase && !previous_was_separator {
                    normalized.push('_');
                }
                normalized.push(character.to_ascii_lowercase());
                previous_was_lowercase = false;
                previous_was_separator = false;
            }
            character => {
                normalized.push(character.to_ascii_lowercase());
                previous_was_lowercase = character.is_ascii_lowercase();
                previous_was_separator = false;
            }
        }
    }

    normalized
}

/// Schema identifier for decision plane records.
pub const DECISION_PLANE_SCHEMA_V1: &str = "ee.decision_plane.v1";

/// Decision plane types that can be tracked.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecisionPlane {
    /// Context pack assembly decisions.
    Packing,
    /// Search result ranking decisions.
    Ranking,
    /// Memory curation decisions (promote, archive, tombstone).
    Curation,
    /// Repair task ordering decisions.
    RepairOrder,
    /// Cache admission/eviction decisions.
    CacheAdmission,
    /// Causal trace observation decisions.
    Observe,
}

impl DecisionPlane {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Packing => "packing",
            Self::Ranking => "ranking",
            Self::Curation => "curation",
            Self::RepairOrder => "repair_order",
            Self::CacheAdmission => "cache_admission",
            Self::Observe => "observe",
        }
    }

    #[must_use]
    pub const fn all() -> &'static [Self] {
        &[
            Self::Packing,
            Self::Ranking,
            Self::Curation,
            Self::RepairOrder,
            Self::CacheAdmission,
            Self::Observe,
        ]
    }
}

impl fmt::Display for DecisionPlane {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseDecisionPlaneError {
    pub invalid: String,
}

impl fmt::Display for ParseDecisionPlaneError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "invalid decision plane '{}'; expected one of: packing, ranking, curation, repair_order, cache_admission, observe",
            self.invalid
        )
    }
}

impl std::error::Error for ParseDecisionPlaneError {}

impl FromStr for DecisionPlane {
    type Err = ParseDecisionPlaneError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalized_decision_plane_token(s).as_str() {
            "packing" => Ok(Self::Packing),
            "ranking" => Ok(Self::Ranking),
            "curation" => Ok(Self::Curation),
            "repair_order" => Ok(Self::RepairOrder),
            "cache_admission" => Ok(Self::CacheAdmission),
            "observe" => Ok(Self::Observe),
            _ => Err(ParseDecisionPlaneError {
                invalid: s.to_owned(),
            }),
        }
    }
}

/// Metadata for tracking decisions in the decision plane.
///
/// Records that affect ranking, packing, curation, repair ordering, or
/// cache admission should include this metadata to enable:
/// - Shadow-run comparisons between policies
/// - Deterministic replay of decisions
/// - Audit trails linking decisions to policies
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct DecisionPlaneMetadata {
    /// The policy that governed this decision (e.g., "default", "aggressive-decay").
    /// Optional: None means the default/incumbent policy was used.
    pub policy_id: Option<String>,

    /// Unique identifier for this specific decision instance.
    /// Optional: can be generated lazily when auditing is needed.
    pub decision_id: Option<String>,

    /// Trace identifier linking related decisions across operations.
    /// Used for distributed tracing and request correlation.
    pub trace_id: Option<String>,
}

impl DecisionPlaneMetadata {
    /// Create empty metadata (all fields None).
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            policy_id: None,
            decision_id: None,
            trace_id: None,
        }
    }

    /// Create metadata with a policy ID only.
    #[must_use]
    pub fn with_policy(policy_id: impl Into<String>) -> Self {
        Self {
            policy_id: Some(policy_id.into()),
            decision_id: None,
            trace_id: None,
        }
    }

    /// Create metadata with all fields.
    #[must_use]
    pub fn full(
        policy_id: impl Into<String>,
        decision_id: impl Into<String>,
        trace_id: impl Into<String>,
    ) -> Self {
        Self {
            policy_id: Some(policy_id.into()),
            decision_id: Some(decision_id.into()),
            trace_id: Some(trace_id.into()),
        }
    }

    /// Check if this has any tracking information.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.policy_id.is_none() && self.decision_id.is_none() && self.trace_id.is_none()
    }

    /// Check if this has a policy assigned.
    #[must_use]
    pub const fn has_policy(&self) -> bool {
        self.policy_id.is_some()
    }

    /// Check if this has full audit information.
    #[must_use]
    pub const fn is_auditable(&self) -> bool {
        self.policy_id.is_some() && self.decision_id.is_some()
    }

    /// Builder-style: set policy ID.
    #[must_use]
    pub fn policy(mut self, policy_id: impl Into<String>) -> Self {
        self.policy_id = Some(policy_id.into());
        self
    }

    /// Builder-style: set decision ID.
    #[must_use]
    pub fn decision(mut self, decision_id: impl Into<String>) -> Self {
        self.decision_id = Some(decision_id.into());
        self
    }

    /// Builder-style: set trace ID.
    #[must_use]
    pub fn trace(mut self, trace_id: impl Into<String>) -> Self {
        self.trace_id = Some(trace_id.into());
        self
    }
}

/// A decision record that tracks what decision was made and why.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DecisionRecord {
    /// Schema identifier.
    pub schema: String,

    /// Which decision plane this belongs to.
    pub plane: DecisionPlane,

    /// Tracking metadata (policy, decision, trace IDs).
    pub metadata: DecisionPlaneMetadata,

    /// When the decision was made.
    pub decided_at: String,

    /// The outcome or action taken.
    pub outcome: String,

    /// Optional explanation or reasoning.
    pub reason: Option<String>,

    /// Confidence or score if applicable.
    pub confidence: Option<f64>,

    /// Whether this was a shadow decision (not actually applied).
    pub shadow: bool,

    /// If shadow, the incumbent decision it was compared against.
    pub incumbent_outcome: Option<String>,
}

impl DecisionRecord {
    #[must_use]
    pub fn builder() -> DecisionRecordBuilder {
        DecisionRecordBuilder::default()
    }
}

#[derive(Clone, Debug, Default)]
pub struct DecisionRecordBuilder {
    plane: Option<DecisionPlane>,
    metadata: DecisionPlaneMetadata,
    decided_at: Option<String>,
    outcome: Option<String>,
    reason: Option<String>,
    confidence: Option<f64>,
    shadow: bool,
    incumbent_outcome: Option<String>,
}

impl DecisionRecordBuilder {
    #[must_use]
    pub fn plane(mut self, plane: DecisionPlane) -> Self {
        self.plane = Some(plane);
        self
    }

    #[must_use]
    pub fn metadata(mut self, metadata: DecisionPlaneMetadata) -> Self {
        self.metadata = metadata;
        self
    }

    #[must_use]
    pub fn policy_id(mut self, policy_id: impl Into<String>) -> Self {
        self.metadata.policy_id = Some(policy_id.into());
        self
    }

    #[must_use]
    pub fn decision_id(mut self, decision_id: impl Into<String>) -> Self {
        self.metadata.decision_id = Some(decision_id.into());
        self
    }

    #[must_use]
    pub fn trace_id(mut self, trace_id: impl Into<String>) -> Self {
        self.metadata.trace_id = Some(trace_id.into());
        self
    }

    #[must_use]
    pub fn decided_at(mut self, decided_at: impl Into<String>) -> Self {
        self.decided_at = Some(decided_at.into());
        self
    }

    #[must_use]
    pub fn outcome(mut self, outcome: impl Into<String>) -> Self {
        self.outcome = Some(outcome.into());
        self
    }

    #[must_use]
    pub fn reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }

    #[must_use]
    pub fn confidence(mut self, confidence: f64) -> Self {
        self.confidence = Some(confidence);
        self
    }

    #[must_use]
    pub fn shadow(mut self, shadow: bool) -> Self {
        self.shadow = shadow;
        self
    }

    #[must_use]
    pub fn incumbent_outcome(mut self, incumbent_outcome: impl Into<String>) -> Self {
        self.incumbent_outcome = Some(incumbent_outcome.into());
        self
    }

    /// Build a `DecisionRecord`, auto-filling `decided_at` with the current
    /// UTC timestamp when one was not supplied.
    ///
    /// `outcome` is left empty if it was not set; callers that need to enforce
    /// a non-empty outcome should use [`try_build`](Self::try_build) instead.
    /// Historically `build` silently substituted `String::default()` for both
    /// `decided_at` and `outcome`, which let production code emit
    /// timestamp-less audit records by accident — auto-filling the timestamp
    /// closes that hole without breaking existing test fixtures that do not
    /// inspect `decided_at`.
    #[must_use]
    pub fn build(self) -> DecisionRecord {
        DecisionRecord {
            schema: DECISION_PLANE_SCHEMA_V1.to_owned(),
            plane: self.plane.unwrap_or(DecisionPlane::Packing),
            metadata: self.metadata,
            decided_at: self.decided_at.unwrap_or_else(now_rfc3339),
            outcome: self.outcome.unwrap_or_default(),
            reason: self.reason,
            confidence: self.confidence,
            shadow: self.shadow,
            incumbent_outcome: self.incumbent_outcome,
        }
    }

    /// Build a `DecisionRecord`, requiring `outcome` to be set explicitly and
    /// contain at least one non-whitespace character.
    ///
    /// `decided_at` is still auto-filled with the current UTC timestamp when
    /// not supplied; the timestamp is determinable from context (the build
    /// site is, by definition, "now"), but the outcome is a load-bearing
    /// audit field that callers must commit to.
    pub fn try_build(self) -> Result<DecisionRecord, DecisionBuildError> {
        let outcome = match self.outcome {
            // Trim BEFORE storing so the `outcome` field on the
            // persisted DecisionRecord is in canonical form. A value
            // like " approved\n" would otherwise round-trip through
            // export/replay distinct from the trimmed "approved" and
            // silently fork the audit chain on equality checks. Same
            // defensive pattern as src/cass/import.rs (a135ab06).
            Some(value) if !value.trim().is_empty() => value.trim().to_owned(),
            Some(_) => return Err(DecisionBuildError::EmptyOutcome),
            None => return Err(DecisionBuildError::MissingOutcome),
        };
        Ok(DecisionRecord {
            schema: DECISION_PLANE_SCHEMA_V1.to_owned(),
            plane: self.plane.unwrap_or(DecisionPlane::Packing),
            metadata: self.metadata,
            decided_at: self.decided_at.unwrap_or_else(now_rfc3339),
            outcome,
            reason: self.reason,
            confidence: self.confidence,
            shadow: self.shadow,
            incumbent_outcome: self.incumbent_outcome,
        })
    }
}

fn now_rfc3339() -> String {
    Utc::now().to_rfc3339_opts(SecondsFormat::Nanos, true)
}

/// Errors returned by [`DecisionRecordBuilder::try_build`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DecisionBuildError {
    /// `outcome` was never set on the builder.
    MissingOutcome,
    /// `outcome` was set but to an empty or whitespace-only string.
    EmptyOutcome,
}

impl fmt::Display for DecisionBuildError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingOutcome => f.write_str("DecisionRecord requires outcome to be set"),
            Self::EmptyOutcome => f.write_str("DecisionRecord outcome must not be empty"),
        }
    }
}

impl std::error::Error for DecisionBuildError {}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    type TestResult = Result<(), String>;

    fn ensure<T: std::fmt::Debug + PartialEq>(actual: T, expected: T, ctx: &str) -> TestResult {
        if actual == expected {
            Ok(())
        } else {
            Err(format!("{ctx}: expected {expected:?}, got {actual:?}"))
        }
    }

    #[test]
    fn decision_plane_roundtrip() -> TestResult {
        for plane in DecisionPlane::all() {
            let s = plane.as_str();
            let parsed: DecisionPlane = s
                .parse()
                .map_err(|e: ParseDecisionPlaneError| e.to_string())?;
            ensure(parsed, *plane, &format!("roundtrip {s}"))?;
        }
        Ok(())
    }

    #[test]
    fn decision_plane_accepts_operator_spelling_variants() {
        assert_eq!(
            DecisionPlane::from_str(" Repair-Order ").expect("hyphenated plane parses"),
            DecisionPlane::RepairOrder
        );
        assert_eq!(
            DecisionPlane::from_str("CACHE_ADMISSION").expect("uppercase plane parses"),
            DecisionPlane::CacheAdmission
        );
        assert_eq!(
            DecisionPlane::from_str("repairOrder").expect("camelCase plane parses"),
            DecisionPlane::RepairOrder
        );
        assert_eq!(
            DecisionPlane::from_str("CacheAdmission").expect("PascalCase plane parses"),
            DecisionPlane::CacheAdmission
        );
    }

    #[test]
    fn decision_plane_display() {
        assert_eq!(DecisionPlane::Packing.to_string(), "packing");
        assert_eq!(DecisionPlane::Ranking.to_string(), "ranking");
        assert_eq!(DecisionPlane::Curation.to_string(), "curation");
        assert_eq!(DecisionPlane::RepairOrder.to_string(), "repair_order");
        assert_eq!(DecisionPlane::CacheAdmission.to_string(), "cache_admission");
    }

    #[test]
    fn decision_plane_metadata_empty() {
        let meta = DecisionPlaneMetadata::empty();
        assert!(meta.is_empty());
        assert!(!meta.has_policy());
        assert!(!meta.is_auditable());
    }

    #[test]
    fn decision_plane_metadata_with_policy() {
        let meta = DecisionPlaneMetadata::with_policy("aggressive-decay");
        assert!(!meta.is_empty());
        assert!(meta.has_policy());
        assert!(!meta.is_auditable());
        assert_eq!(meta.policy_id, Some("aggressive-decay".to_owned()));
    }

    #[test]
    fn decision_plane_metadata_full() {
        let meta = DecisionPlaneMetadata::full("policy-1", "dec-001", "trace-abc");
        assert!(!meta.is_empty());
        assert!(meta.has_policy());
        assert!(meta.is_auditable());
        assert_eq!(meta.policy_id, Some("policy-1".to_owned()));
        assert_eq!(meta.decision_id, Some("dec-001".to_owned()));
        assert_eq!(meta.trace_id, Some("trace-abc".to_owned()));
    }

    #[test]
    fn decision_plane_metadata_builder_pattern() {
        let meta = DecisionPlaneMetadata::empty()
            .policy("my-policy")
            .decision("dec-123")
            .trace("trace-xyz");

        assert_eq!(meta.policy_id, Some("my-policy".to_owned()));
        assert_eq!(meta.decision_id, Some("dec-123".to_owned()));
        assert_eq!(meta.trace_id, Some("trace-xyz".to_owned()));
    }

    #[test]
    fn decision_record_builder() {
        let record = DecisionRecord::builder()
            .plane(DecisionPlane::Curation)
            .policy_id("curation-v2")
            .decision_id("dec-456")
            .trace_id("trace-req-1")
            .decided_at("2026-04-30T12:00:00Z")
            .outcome("archive")
            .reason("Low confidence, no recent access")
            .confidence(0.3)
            .shadow(false)
            .build();

        assert_eq!(record.schema, DECISION_PLANE_SCHEMA_V1);
        assert_eq!(record.plane, DecisionPlane::Curation);
        assert_eq!(record.metadata.policy_id, Some("curation-v2".to_owned()));
        assert_eq!(record.outcome, "archive");
        assert_eq!(record.confidence, Some(0.3));
        assert!(!record.shadow);
    }

    #[test]
    fn decision_record_shadow_comparison() {
        let record = DecisionRecord::builder()
            .plane(DecisionPlane::Ranking)
            .policy_id("experimental-ranker")
            .decided_at("2026-04-30T12:00:00Z")
            .outcome("rank-3")
            .shadow(true)
            .incumbent_outcome("rank-1")
            .build();

        assert!(record.shadow);
        assert_eq!(record.incumbent_outcome, Some("rank-1".to_owned()));
    }

    #[test]
    fn decision_record_serializes_to_json() {
        let record = DecisionRecord::builder()
            .plane(DecisionPlane::Packing)
            .policy_id("budget-tight")
            .decided_at("2026-04-30T12:00:00Z")
            .outcome("include")
            .build();

        let json = serde_json::to_string(&record).expect("serialize");
        assert!(json.contains(r#""schema":"ee.decision_plane.v1""#));
        assert!(json.contains(r#""plane":"packing""#));
        assert!(json.contains(r#""policy_id":"budget-tight""#));
    }

    #[test]
    fn decision_plane_metadata_serializes() {
        let meta = DecisionPlaneMetadata::full("pol-1", "dec-1", "trace-1");
        let json = serde_json::to_string(&meta).expect("serialize");
        assert!(json.contains(r#""policy_id":"pol-1""#));
        assert!(json.contains(r#""decision_id":"dec-1""#));
        assert!(json.contains(r#""trace_id":"trace-1""#));
    }

    #[test]
    fn parse_invalid_decision_plane_error() {
        let result: Result<DecisionPlane, _> = "invalid".parse();
        assert!(result.is_err());
        let err = result.expect_err("avoid unwrap_err in production code");
        assert!(err.to_string().contains("invalid decision plane"));
    }

    #[test]
    fn build_autofills_decided_at_when_unset() -> TestResult {
        let record = DecisionRecord::builder()
            .plane(DecisionPlane::Curation)
            .outcome("archive")
            .build();

        if record.decided_at.is_empty() {
            return Err(format!(
                "build() must auto-fill decided_at; got {:?}",
                record.decided_at
            ));
        }
        // Sanity-check the format roughly matches RFC3339 (e.g. 2026-05-05T04:08:25.123456789Z).
        if !record.decided_at.ends_with('Z') || record.decided_at.len() < 30 {
            return Err(format!(
                "auto-filled decided_at should be RFC3339 with Z suffix; got {:?}",
                record.decided_at
            ));
        }
        Ok(())
    }

    #[test]
    fn build_autofills_decided_at_with_nanosecond_precision() -> TestResult {
        let record = DecisionRecord::builder()
            .plane(DecisionPlane::Curation)
            .outcome("archive")
            .build();

        chrono::DateTime::parse_from_rfc3339(&record.decided_at)
            .map_err(|error| error.to_string())?;
        let Some(fraction) = record
            .decided_at
            .strip_suffix('Z')
            .and_then(|value| value.rsplit_once('.').map(|(_, fraction)| fraction))
        else {
            return Err(format!(
                "auto-filled decided_at should include nanoseconds; got {:?}",
                record.decided_at
            ));
        };
        if fraction.len() != 9 || !fraction.chars().all(|ch| ch.is_ascii_digit()) {
            return Err(format!(
                "auto-filled decided_at should have 9 fractional digits; got {:?}",
                record.decided_at
            ));
        }
        Ok(())
    }

    #[test]
    fn build_preserves_explicit_decided_at() -> TestResult {
        let record = DecisionRecord::builder()
            .plane(DecisionPlane::Curation)
            .decided_at("2026-04-30T12:00:00Z")
            .outcome("archive")
            .build();
        ensure(
            record.decided_at,
            "2026-04-30T12:00:00Z".to_owned(),
            "explicit decided_at must round-trip unchanged",
        )
    }

    #[test]
    fn try_build_rejects_missing_outcome() -> TestResult {
        let result = DecisionRecord::builder()
            .plane(DecisionPlane::Curation)
            .try_build();
        ensure(
            result,
            Err(DecisionBuildError::MissingOutcome),
            "try_build with no outcome must fail",
        )
    }

    #[test]
    fn try_build_rejects_empty_outcome() -> TestResult {
        let result = DecisionRecord::builder()
            .plane(DecisionPlane::Curation)
            .outcome("")
            .try_build();
        ensure(
            result,
            Err(DecisionBuildError::EmptyOutcome),
            "try_build with empty outcome must fail",
        )
    }

    #[test]
    fn try_build_rejects_whitespace_only_outcome() -> TestResult {
        let result = DecisionRecord::builder()
            .plane(DecisionPlane::Curation)
            .outcome("   ")
            .try_build();
        ensure(
            result,
            Err(DecisionBuildError::EmptyOutcome),
            "try_build with whitespace-only outcome must fail",
        )
    }

    #[test]
    fn try_build_returns_record_when_outcome_set() -> TestResult {
        let record = DecisionRecord::builder()
            .plane(DecisionPlane::Curation)
            .outcome("archive")
            .try_build()
            .map_err(|err| err.to_string())?;
        ensure(
            record.outcome,
            "archive".to_owned(),
            "outcome must round-trip",
        )?;
        if record.decided_at.is_empty() {
            return Err("try_build must auto-fill decided_at".to_owned());
        }
        Ok(())
    }

    #[test]
    fn all_decision_planes_covered() {
        let all = DecisionPlane::all();
        assert_eq!(all.len(), 6);
        assert!(all.contains(&DecisionPlane::Packing));
        assert!(all.contains(&DecisionPlane::Ranking));
        assert!(all.contains(&DecisionPlane::Curation));
        assert!(all.contains(&DecisionPlane::RepairOrder));
        assert!(all.contains(&DecisionPlane::CacheAdmission));
        assert!(all.contains(&DecisionPlane::Observe));
    }
}