crtx-store 0.1.1

SQLite persistence: migrations, repositories, transactions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
//! Principle candidate and doctrine promotion repository operations.
//!
//! ADR 0026 §2 requires every mutation of the durable doctrine surface to
//! compose through the policy lattice. ADR 0035 §4 doubles this for principle
//! promotion: falsification evidence and supporting-memory proof closure must
//! be observable on the decision the store records. The store boundary
//! therefore takes a typed [`PolicyDecision`] on both entry points and refuses
//! callers that skipped composition.
//!
//! Required contributor rule ids:
//!
//! - [`CANDIDATE_FALSIFICATION_RULE_ID`] and
//!   [`CANDIDATE_SUPPORTING_MEMORY_PROOF_RULE_ID`] for
//!   [`PrincipleRepo::insert_candidate`]. ADR 0026 consumer punch list #6:
//!   unfalsifiable / proof-broken candidates never enter the principles table.
//! - [`PROMOTION_FALSIFICATION_RULE_ID`] for
//!   [`PrincipleRepo::promote_to_doctrine`]. ADR 0026 consumer punch list #7:
//!   the composed promotion outcome is recorded on the doctrine row for
//!   replay. ADR 0026 §4 forbids a `BreakGlass` decision from substituting for
//!   falsification evidence at this surface; the falsification contributor MUST
//!   itself vote [`PolicyOutcome::Allow`] for every composition.

use chrono::{DateTime, Utc};
use cortex_core::attestor::{verify, Attestation};
use cortex_core::canonical::{AttestationPreimage, LineageBinding, SourceIdentity};
use cortex_core::{
    AuditRecordId, DoctrineId, PolicyContribution, PolicyDecision, PolicyOutcome, PrincipleId,
};
use cortex_ledger::payload_hash;
use ed25519_dalek::VerifyingKey;
use rusqlite::{params, OptionalExtension, Row};
use serde_json::{json, Value};

use crate::{Pool, StoreError, StoreResult};

/// Required contributor rule id documenting that a principle candidate was
/// observed to carry an active falsification record (ADR 0026 §5, ADR 0035 §4).
pub const CANDIDATE_FALSIFICATION_RULE_ID: &str = "principle.candidate.falsification";
/// Required contributor rule id documenting that each supporting memory cited
/// by a principle candidate passed proof closure before the candidate row was
/// persisted (ADR 0026 §5, ADR 0036).
pub const CANDIDATE_SUPPORTING_MEMORY_PROOF_RULE_ID: &str =
    "principle.candidate.supporting_memory_proof";
/// Stable rule id for the principle promotion falsification contributor
/// composed by callers of [`PrincipleRepo::promote_to_doctrine`]. ADR 0026 §4
/// requires this contributor to vote [`PolicyOutcome::Allow`] even when the
/// final decision is `BreakGlass`; `BreakGlass` never substitutes for
/// falsification evidence at the doctrine root (ADR 0035 §4).
pub const PROMOTION_FALSIFICATION_RULE_ID: &str = "principle_promotion.falsification";

macro_rules! principle_select_sql {
    ($where_clause:literal) => {
        concat!(
            "SELECT id, statement, status, supporting_memories_json,
                    contradicting_memories_json, domains_observed_json,
                    applies_when_json, does_not_apply_when_json, confidence,
                    validation, brightness, created_by_json, created_at, updated_at
             FROM principles ",
            $where_clause,
            ";"
        )
    };
}

/// Candidate principle data accepted by [`PrincipleRepo::insert_candidate`].
#[derive(Debug, Clone, PartialEq)]
pub struct PrincipleCandidateRow {
    /// Stable principle identifier.
    pub id: PrincipleId,
    /// Proposed principle statement.
    pub statement: String,
    /// Lifecycle status, normally `candidate`.
    pub status: String,
    /// Supporting memory ids as JSON.
    pub supporting_memories_json: Value,
    /// Contradicting memory ids as JSON.
    pub contradicting_memories_json: Value,
    /// Observed domains as JSON.
    pub domains_observed_json: Value,
    /// Applicability constraints as JSON.
    pub applies_when_json: Value,
    /// Negative applicability constraints as JSON.
    pub does_not_apply_when_json: Value,
    /// Candidate confidence in `[0, 1]`.
    pub confidence: f64,
    /// Validation score in `[0, 1]`.
    pub validation: f64,
    /// Brightness score in `[0, 1]`.
    pub brightness: f64,
    /// Extractor descriptor JSON.
    pub created_by_json: Value,
    /// Creation timestamp.
    pub created_at: DateTime<Utc>,
    /// Update timestamp.
    pub updated_at: DateTime<Utc>,
}

/// Durable principle row read from the store.
pub type PrincipleRecord = PrincipleCandidateRow;

/// Doctrine row created by explicit promotion.
#[derive(Debug, Clone, PartialEq)]
pub struct DoctrineRecord {
    /// Stable doctrine identifier.
    pub id: DoctrineId,
    /// Source principle identifier.
    pub source_principle: PrincipleId,
    /// Doctrine rule text.
    pub rule: String,
    /// Doctrine force level.
    pub force: String,
    /// Operator promotion reason.
    pub promotion_reason: String,
    /// Promoting actor descriptor JSON.
    pub promoted_by_json: Value,
    /// Composed [`PolicyDecision`] recorded on the doctrine row for replay
    /// (ADR 0026 §7). Populated by [`PrincipleRepo::promote_to_doctrine`].
    pub composed_policy_decision_json: Value,
    /// Creation timestamp.
    pub created_at: DateTime<Utc>,
}

/// Atomic doctrine promotion input.
#[derive(Debug, Clone, PartialEq)]
pub struct DoctrinePromotion {
    /// Stable doctrine identifier to insert.
    pub doctrine_id: DoctrineId,
    /// Stable audit row identifier to insert.
    pub audit_id: AuditRecordId,
    /// Source principle identifier to promote.
    pub source_principle: PrincipleId,
    /// Doctrine force level.
    pub force: String,
    /// Operator promotion reason.
    pub reason: String,
    /// Promoting actor descriptor JSON.
    pub promoted_by_json: Value,
    /// Creation timestamp for doctrine and audit rows.
    pub created_at: DateTime<Utc>,
}

/// Replay verification result for a stored doctrine promotion attestation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PromotionAttestationReplay {
    /// Doctrine row that was replay-verified.
    pub doctrine_id: DoctrineId,
    /// Source principle whose promotion was replayed.
    pub source_principle: PrincipleId,
    /// Audit row paired with the doctrine promotion.
    pub audit_id: AuditRecordId,
    /// Whether replay verification succeeded.
    pub verified: bool,
}

/// Repository for principle candidates and explicit doctrine promotion.
#[derive(Debug)]
pub struct PrincipleRepo<'a> {
    pool: &'a Pool,
}

impl<'a> PrincipleRepo<'a> {
    /// Creates a principle repository over an open SQLite connection.
    #[must_use]
    pub const fn new(pool: &'a Pool) -> Self {
        Self { pool }
    }

    /// Inserts a supported principle candidate through the ADR 0026 enforcement
    /// lattice.
    ///
    /// `policy` is the composed [`PolicyDecision`] for this candidate
    /// insertion and MUST satisfy:
    ///
    /// 1. The final outcome is one of [`PolicyOutcome::Allow`],
    ///    [`PolicyOutcome::Warn`], or [`PolicyOutcome::BreakGlass`]. A
    ///    `Quarantine` or `Reject` decision fails closed and writes nothing.
    /// 2. The composition includes contributors for both
    ///    [`CANDIDATE_FALSIFICATION_RULE_ID`] and
    ///    [`CANDIDATE_SUPPORTING_MEMORY_PROOF_RULE_ID`]. The repo refuses
    ///    callers that skipped composition so unfalsifiable / proof-broken
    ///    candidates never enter the principles table (ADR 0026 consumer punch
    ///    list #6).
    /// 3. Per ADR 0026 §4, the falsification contributor MUST itself be
    ///    [`PolicyOutcome::Allow`] even when the final decision is
    ///    `BreakGlass`. Break-glass never substitutes for falsification
    ///    evidence at the principle candidate root.
    pub fn insert_candidate(
        &self,
        candidate: &PrincipleCandidateRow,
        policy: &PolicyDecision,
    ) -> StoreResult<()> {
        require_policy_final_outcome(policy, "principle.candidate.insert")?;
        require_contributor_rule(policy, CANDIDATE_FALSIFICATION_RULE_ID)?;
        require_contributor_rule(policy, CANDIDATE_SUPPORTING_MEMORY_PROOF_RULE_ID)?;
        require_contributor_not_break_glassed(
            policy,
            CANDIDATE_FALSIFICATION_RULE_ID,
            "principle.candidate.insert",
        )?;

        validate_candidate(candidate)?;

        self.pool.execute(
            "INSERT INTO principles (
                id, statement, status, supporting_memories_json, contradicting_memories_json,
                domains_observed_json, applies_when_json, does_not_apply_when_json,
                confidence, validation, brightness, created_by_json, created_at, updated_at
             ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14);",
            params![
                candidate.id.to_string(),
                candidate.statement,
                candidate.status,
                serde_json::to_string(&candidate.supporting_memories_json)?,
                serde_json::to_string(&candidate.contradicting_memories_json)?,
                serde_json::to_string(&candidate.domains_observed_json)?,
                serde_json::to_string(&candidate.applies_when_json)?,
                serde_json::to_string(&candidate.does_not_apply_when_json)?,
                candidate.confidence,
                candidate.validation,
                candidate.brightness,
                serde_json::to_string(&candidate.created_by_json)?,
                candidate.created_at.to_rfc3339(),
                candidate.updated_at.to_rfc3339(),
            ],
        )?;

        Ok(())
    }

    /// Fetches a principle row by id.
    pub fn get_by_id(&self, id: &PrincipleId) -> StoreResult<Option<PrincipleRecord>> {
        let row = self
            .pool
            .query_row(
                principle_select_sql!("WHERE id = ?1"),
                params![id.to_string()],
                principle_row,
            )
            .optional()?;

        row.map(TryInto::try_into).transpose()
    }

    /// Lists candidate principle rows in deterministic update order.
    pub fn list_candidates(&self) -> StoreResult<Vec<PrincipleRecord>> {
        let mut stmt = self.pool.prepare(principle_select_sql!(
            "WHERE status = 'candidate' ORDER BY updated_at DESC, id"
        ))?;
        let rows = stmt.query_map([], principle_row)?;

        let mut principles = Vec::new();
        for row in rows {
            principles.push(row?.try_into()?);
        }
        Ok(principles)
    }

    /// Lists all doctrine rows in creation order (oldest first).
    ///
    /// Doctrine rows are written once by [`Self::promote_to_doctrine`] and
    /// never deleted, so the full table is the active set.
    pub fn list_doctrine(&self) -> StoreResult<Vec<DoctrineRecord>> {
        let mut stmt = self.pool.prepare(
            "SELECT id, source_principle, rule, force, promotion_reason,
                    promoted_by_json, created_at, composed_policy_decision_json
             FROM doctrine
             ORDER BY created_at ASC, id;",
        )?;
        let rows = stmt.query_map([], |row| {
            let promoted_by_json: String = row.get(5)?;
            let composed_json: Option<String> = row.get(7)?;
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, String>(3)?,
                row.get::<_, String>(4)?,
                promoted_by_json,
                row.get::<_, String>(6)?,
                composed_json,
            ))
        })?;

        let mut out = Vec::new();
        for row in rows {
            let (
                id,
                source_principle,
                rule,
                force,
                promotion_reason,
                promoted_by_json,
                created_at,
                composed_json,
            ) = row?;
            out.push(DoctrineRecord {
                id: id.parse()?,
                source_principle: source_principle.parse()?,
                rule,
                force,
                promotion_reason,
                promoted_by_json: serde_json::from_str(&promoted_by_json)?,
                composed_policy_decision_json: composed_json
                    .map(|s| serde_json::from_str(&s))
                    .transpose()?
                    .unwrap_or(serde_json::Value::Null),
                created_at: DateTime::parse_from_rfc3339(&created_at)?.with_timezone(&Utc),
            });
        }
        Ok(out)
    }

    /// Atomically promotes a candidate principle to doctrine and writes audit
    /// evidence through the ADR 0026 enforcement lattice.
    ///
    /// `policy` is the composed [`PolicyDecision`] approving the promotion and
    /// MUST satisfy:
    ///
    /// 1. The final outcome is one of [`PolicyOutcome::Allow`],
    ///    [`PolicyOutcome::Warn`], or [`PolicyOutcome::BreakGlass`]. A
    ///    `Quarantine` or `Reject` decision fails closed and writes nothing
    ///    (ADR 0026 consumer punch list #7).
    /// 2. The composition includes a `principle_promotion.falsification`
    ///    contributor whose outcome is itself [`PolicyOutcome::Allow`]. ADR
    ///    0026 §4 + ADR 0035 §4 forbid `BreakGlass` from substituting for
    ///    falsification evidence at the doctrine root.
    /// 3. The serialised decision is recorded on the new doctrine row in
    ///    `composed_policy_decision_json` so replay verification can
    ///    reconstruct the policy posture that approved the promotion.
    pub fn promote_to_doctrine(
        &self,
        promotion: &DoctrinePromotion,
        policy: &PolicyDecision,
    ) -> StoreResult<DoctrineRecord> {
        require_policy_final_outcome(policy, "principle.promote")?;
        require_contributor_not_break_glassed(
            policy,
            PROMOTION_FALSIFICATION_RULE_ID,
            "principle.promote",
        )?;

        validate_promotion(promotion)?;
        let composed_policy_decision_json = serde_json::to_value(policy)?;
        let composed_policy_decision_text = serde_json::to_string(&composed_policy_decision_json)?;

        let tx = self.pool.unchecked_transaction()?;
        let row = tx
            .query_row(
                principle_select_sql!("WHERE id = ?1"),
                params![promotion.source_principle.to_string()],
                principle_row,
            )
            .optional()?;
        let Some(principle): Option<PrincipleRecord> = row.map(TryInto::try_into).transpose()?
        else {
            return Err(StoreError::Validation(format!(
                "principle {} not found",
                promotion.source_principle
            )));
        };
        if principle.status != "candidate" {
            return Err(StoreError::Validation(format!(
                "principle {} is not a candidate: {}",
                promotion.source_principle, principle.status
            )));
        }
        validate_candidate(&principle)?;
        validate_promotion_falsification(&principle)?;

        tx.execute(
            "UPDATE principles
             SET status = 'promoted_to_doctrine', updated_at = ?2
             WHERE id = ?1 AND status = 'candidate';",
            params![
                promotion.source_principle.to_string(),
                promotion.created_at.to_rfc3339(),
            ],
        )?;
        tx.execute(
            "INSERT INTO doctrine (
                id, source_principle, rule, force, promotion_reason, promoted_by_json,
                created_at, composed_policy_decision_json
             ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8);",
            params![
                promotion.doctrine_id.to_string(),
                promotion.source_principle.to_string(),
                principle.statement.as_str(),
                promotion.force.as_str(),
                promotion.reason.as_str(),
                serde_json::to_string(&promotion.promoted_by_json)?,
                promotion.created_at.to_rfc3339(),
                composed_policy_decision_text.as_str(),
            ],
        )?;
        tx.execute(
            "INSERT INTO audit_records (
                id, operation, target_ref, before_hash, after_hash, reason,
                actor_json, source_refs_json, created_at
             ) VALUES (?1, 'doctrine_promotion', ?2, ?3, ?4, ?5, ?6, ?7, ?8);",
            params![
                promotion.audit_id.to_string(),
                promotion.source_principle.to_string(),
                "principle:status:candidate",
                format!(
                    "doctrine:{}:force:{}",
                    promotion.doctrine_id, promotion.force
                ),
                promotion.reason.as_str(),
                serde_json::to_string(&promotion.promoted_by_json)?,
                serde_json::to_string(&serde_json::json!([
                    promotion.source_principle.to_string(),
                    promotion.doctrine_id.to_string(),
                    promotion.force.as_str()
                ]))?,
                promotion.created_at.to_rfc3339(),
            ],
        )?;

        let doctrine = DoctrineRecord {
            id: promotion.doctrine_id,
            source_principle: promotion.source_principle,
            rule: principle.statement,
            force: promotion.force.clone(),
            promotion_reason: promotion.reason.clone(),
            promoted_by_json: promotion.promoted_by_json.clone(),
            composed_policy_decision_json,
            created_at: promotion.created_at,
        };
        tx.commit()?;

        Ok(doctrine)
    }

    /// Replay-verifies a stored doctrine promotion attestation without trusting the original CLI.
    pub fn verify_promotion_attestation_replay(
        &self,
        source_principle: &PrincipleId,
    ) -> StoreResult<PromotionAttestationReplay> {
        let rows = self
            .pool
            .prepare(
                "SELECT d.id, d.source_principle, d.force, d.promotion_reason,
                        d.promoted_by_json, d.created_at,
                        a.id, a.reason, a.actor_json, a.after_hash, a.source_refs_json
                 FROM doctrine d
                 JOIN audit_records a
                   ON a.operation = 'doctrine_promotion'
                  AND a.target_ref = d.source_principle
                 WHERE d.source_principle = ?1;",
            )?
            .query_map([source_principle.to_string()], stored_promotion_replay_row)?
            .collect::<Result<Vec<_>, _>>()?;

        let [row] = rows.as_slice() else {
            return Err(StoreError::Validation(format!(
                "doctrine promotion replay requires exactly one doctrine/audit pair for {source_principle}; found {}",
                rows.len()
            )));
        };

        row.verify()
    }
}

#[derive(Debug, Clone)]
struct StoredPromotionReplayRow {
    doctrine_id: DoctrineId,
    source_principle: PrincipleId,
    force: String,
    promotion_reason: String,
    promoted_by_json: Value,
    audit_id: AuditRecordId,
    audit_reason: String,
    audit_actor_json: Value,
    audit_after_hash: String,
    audit_source_refs_json: Value,
}

impl StoredPromotionReplayRow {
    fn verify(&self) -> StoreResult<PromotionAttestationReplay> {
        if self.promoted_by_json != self.audit_actor_json {
            return Err(StoreError::Validation(
                "doctrine promotion replay actor_json does not match promoted_by_json".into(),
            ));
        }
        if self.audit_reason != self.promotion_reason {
            return Err(StoreError::Validation(
                "doctrine promotion replay audit reason does not match doctrine reason".into(),
            ));
        }
        let expected_after_hash = format!("doctrine:{}:force:{}", self.doctrine_id, self.force);
        if self.audit_after_hash != expected_after_hash {
            return Err(StoreError::Validation(
                "doctrine promotion replay audit after_hash does not match doctrine row".into(),
            ));
        }
        let expected_source_refs = json!([
            self.source_principle.to_string(),
            self.doctrine_id.to_string(),
            self.force.as_str()
        ]);
        if self.audit_source_refs_json != expected_source_refs {
            return Err(StoreError::Validation(
                "doctrine promotion replay source refs do not match doctrine row".into(),
            ));
        }

        let promotion = DoctrinePromotion {
            doctrine_id: self.doctrine_id,
            audit_id: self.audit_id,
            source_principle: self.source_principle,
            force: self.force.clone(),
            reason: self.promotion_reason.clone(),
            promoted_by_json: self.promoted_by_json.clone(),
            created_at: Utc::now(),
        };
        validate_promotion_attestation(&promotion)?;

        Ok(PromotionAttestationReplay {
            doctrine_id: self.doctrine_id,
            source_principle: self.source_principle,
            audit_id: self.audit_id,
            verified: true,
        })
    }
}

fn stored_promotion_replay_row(row: &Row<'_>) -> rusqlite::Result<StoredPromotionReplayRow> {
    let promoted_by_json: String = row.get(4)?;
    let actor_json: String = row.get(8)?;
    let source_refs_json: String = row.get(10)?;
    Ok(StoredPromotionReplayRow {
        doctrine_id: row.get::<_, String>(0)?.parse().map_err(parse_sql_err)?,
        source_principle: row.get::<_, String>(1)?.parse().map_err(parse_sql_err)?,
        force: row.get(2)?,
        promotion_reason: row.get(3)?,
        promoted_by_json: serde_json::from_str(&promoted_by_json).map_err(parse_sql_err)?,
        audit_id: row.get::<_, String>(6)?.parse().map_err(parse_sql_err)?,
        audit_reason: row.get(7)?,
        audit_actor_json: serde_json::from_str(&actor_json).map_err(parse_sql_err)?,
        audit_after_hash: row.get(9)?,
        audit_source_refs_json: serde_json::from_str(&source_refs_json).map_err(parse_sql_err)?,
    })
}

fn parse_sql_err(err: impl std::error::Error + Send + Sync + 'static) -> rusqlite::Error {
    rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(err))
}

#[derive(Debug)]
struct PrincipleRow {
    id: String,
    statement: String,
    status: String,
    supporting_memories_json: String,
    contradicting_memories_json: String,
    domains_observed_json: String,
    applies_when_json: String,
    does_not_apply_when_json: String,
    confidence: f64,
    validation: f64,
    brightness: f64,
    created_by_json: String,
    created_at: String,
    updated_at: String,
}

fn principle_row(row: &Row<'_>) -> rusqlite::Result<PrincipleRow> {
    Ok(PrincipleRow {
        id: row.get(0)?,
        statement: row.get(1)?,
        status: row.get(2)?,
        supporting_memories_json: row.get(3)?,
        contradicting_memories_json: row.get(4)?,
        domains_observed_json: row.get(5)?,
        applies_when_json: row.get(6)?,
        does_not_apply_when_json: row.get(7)?,
        confidence: row.get(8)?,
        validation: row.get(9)?,
        brightness: row.get(10)?,
        created_by_json: row.get(11)?,
        created_at: row.get(12)?,
        updated_at: row.get(13)?,
    })
}

impl TryFrom<PrincipleRow> for PrincipleRecord {
    type Error = StoreError;

    fn try_from(row: PrincipleRow) -> StoreResult<Self> {
        Ok(Self {
            id: row.id.parse()?,
            statement: row.statement,
            status: row.status,
            supporting_memories_json: serde_json::from_str(&row.supporting_memories_json)?,
            contradicting_memories_json: serde_json::from_str(&row.contradicting_memories_json)?,
            domains_observed_json: serde_json::from_str(&row.domains_observed_json)?,
            applies_when_json: serde_json::from_str(&row.applies_when_json)?,
            does_not_apply_when_json: serde_json::from_str(&row.does_not_apply_when_json)?,
            confidence: row.confidence,
            validation: row.validation,
            brightness: row.brightness,
            created_by_json: serde_json::from_str(&row.created_by_json)?,
            created_at: DateTime::parse_from_rfc3339(&row.created_at)?.with_timezone(&Utc),
            updated_at: DateTime::parse_from_rfc3339(&row.updated_at)?.with_timezone(&Utc),
        })
    }
}

fn validate_candidate(candidate: &PrincipleCandidateRow) -> StoreResult<()> {
    if candidate.statement.trim().is_empty() {
        return Err(StoreError::Validation(
            "principle candidate statement must not be empty".into(),
        ));
    }
    if candidate.status != "candidate" && candidate.status != "promoted_to_doctrine" {
        return Err(StoreError::Validation(format!(
            "unsupported principle status `{}`",
            candidate.status
        )));
    }
    if json_array_len(&candidate.supporting_memories_json) < 3 {
        return Err(StoreError::Validation(
            "principle candidate requires at least three supporting memories".into(),
        ));
    }
    if json_array_len(&candidate.domains_observed_json) < 2 {
        return Err(StoreError::Validation(
            "principle candidate requires at least two observed domains".into(),
        ));
    }
    validate_score(candidate.confidence, "confidence")?;
    validate_score(candidate.validation, "validation")?;
    validate_score(candidate.brightness, "brightness")?;
    Ok(())
}

fn validate_promotion(promotion: &DoctrinePromotion) -> StoreResult<()> {
    if promotion.reason.trim().is_empty() {
        return Err(StoreError::Validation(
            "doctrine promotion reason must not be empty".into(),
        ));
    }
    validate_promotion_attestation(promotion)?;
    match promotion.force.as_str() {
        "Advisory" | "Conditioning" | "Gate" => Ok(()),
        force => Err(StoreError::Validation(format!(
            "unsupported doctrine force `{force}`"
        ))),
    }
}

fn validate_promotion_attestation(promotion: &DoctrinePromotion) -> StoreResult<()> {
    let actor = &promotion.promoted_by_json;
    if actor.get("attestation_verified").and_then(Value::as_bool) != Some(true) {
        return Err(StoreError::Validation(
            "doctrine promotion requires verified actor attestation".into(),
        ));
    }

    let attestation = actor.get("attestation").ok_or_else(|| {
        StoreError::Validation("doctrine promotion requires actor attestation".into())
    })?;
    require_non_empty_str(attestation, "key_id")?;
    require_hex_len(attestation, "public_key_hex", 64)?;
    require_hex_len(attestation, "signature_hex", 128)?;
    require_non_empty_str(attestation, "signed_at")?;
    require_non_empty_str(attestation, "payload_hash")?;
    require_non_empty_str(attestation, "event_id")?;
    require_non_empty_str(attestation, "ledger_id")?;

    let schema_version = attestation
        .get("schema_version")
        .and_then(Value::as_u64)
        .ok_or_else(|| {
            StoreError::Validation(
                "doctrine promotion attestation requires numeric schema_version".into(),
            )
        })?;
    if schema_version == 0 {
        return Err(StoreError::Validation(
            "doctrine promotion attestation schema_version must be non-zero".into(),
        ));
    }

    let lineage = attestation.get("lineage").ok_or_else(|| {
        StoreError::Validation("doctrine promotion attestation requires lineage".into())
    })?;
    if lineage.get("kind").and_then(Value::as_str) != Some("chain_position")
        || lineage.get("value").and_then(Value::as_u64).is_none()
    {
        return Err(StoreError::Validation(
            "doctrine promotion attestation requires chain_position lineage".into(),
        ));
    }

    verify_promotion_attestation(promotion, attestation)?;

    Ok(())
}

fn verify_promotion_attestation(
    promotion: &DoctrinePromotion,
    attestation: &Value,
) -> StoreResult<()> {
    if string_field(attestation, "source")? != "user" {
        return Err(StoreError::Validation(
            "doctrine promotion attestation source must be user".into(),
        ));
    }
    let key_id = string_field(attestation, "key_id")?;
    let public_key_bytes = decode_hex_array::<32>(string_field(attestation, "public_key_hex")?)?;
    let public_key = VerifyingKey::from_bytes(&public_key_bytes).map_err(|err| {
        StoreError::Validation(format!(
            "doctrine promotion attestation public_key_hex is invalid: {err}"
        ))
    })?;
    let signature = decode_hex_array::<64>(string_field(attestation, "signature_hex")?)?;
    let signed_at = chrono::DateTime::parse_from_rfc3339(string_field(attestation, "signed_at")?)
        .map_err(|err| {
            StoreError::Validation(format!(
                "doctrine promotion attestation signed_at is invalid: {err}"
            ))
        })?
        .with_timezone(&Utc);
    let expected_event_id = format!("principle_promote:{}", promotion.source_principle);
    if string_field(attestation, "event_id")? != expected_event_id {
        return Err(StoreError::Validation(
            "doctrine promotion attestation event_id does not match source principle".into(),
        ));
    }
    let expected_payload_hash = payload_hash(&promotion_attestation_payload(promotion));
    if string_field(attestation, "payload_hash")? != expected_payload_hash {
        return Err(StoreError::Validation(
            "doctrine promotion attestation payload_hash does not match promotion payload".into(),
        ));
    }
    let schema_version = attestation
        .get("schema_version")
        .and_then(Value::as_u64)
        .and_then(|value| u16::try_from(value).ok())
        .ok_or_else(|| {
            StoreError::Validation(
                "doctrine promotion attestation requires supported schema_version".into(),
            )
        })?;
    let lineage_value = attestation
        .get("lineage")
        .and_then(|lineage| lineage.get("value"))
        .and_then(Value::as_u64)
        .ok_or_else(|| {
            StoreError::Validation(
                "doctrine promotion attestation requires chain_position lineage".into(),
            )
        })?;
    let preimage = AttestationPreimage {
        schema_version,
        source: SourceIdentity::User,
        event_id: string_field(attestation, "event_id")?.to_string(),
        payload_hash: expected_payload_hash,
        session_id: string_field(attestation, "session_id")?.to_string(),
        ledger_id: string_field(attestation, "ledger_id")?.to_string(),
        lineage: LineageBinding::ChainPosition(lineage_value),
        signed_at,
        key_id: key_id.to_string(),
    };
    let signature = Attestation {
        key_id: key_id.to_string(),
        signature,
        signed_at,
    };
    verify(&preimage, &signature, &public_key, key_id).map_err(|err| {
        StoreError::Validation(format!(
            "doctrine promotion attestation verification failed: {err}"
        ))
    })
}

fn promotion_attestation_payload(promotion: &DoctrinePromotion) -> Value {
    json!({
        "operation": "principle.promote",
        "principle_id": promotion.source_principle,
        "force": promotion.force,
        "reason": promotion.reason,
    })
}

fn validate_promotion_falsification(principle: &PrincipleRecord) -> StoreResult<()> {
    let falsification = principle
        .created_by_json
        .get("falsification")
        .ok_or_else(|| {
            StoreError::Validation(
                "doctrine promotion requires recorded principle falsification attempt".into(),
            )
        })?;

    if falsification.get("status").and_then(Value::as_str) != Some("attempted") {
        return Err(StoreError::Validation(
            "doctrine promotion falsification status must be attempted".into(),
        ));
    }

    let failed_attempts = falsification
        .get("failed_attempts")
        .and_then(Value::as_array)
        .ok_or_else(|| {
            StoreError::Validation(
                "doctrine promotion requires falsification failed_attempts".into(),
            )
        })?;
    if failed_attempts.is_empty()
        || failed_attempts
            .iter()
            .any(|attempt| attempt.as_str().is_none_or(|text| text.trim().is_empty()))
    {
        return Err(StoreError::Validation(
            "doctrine promotion requires at least one non-empty failed falsification attempt"
                .into(),
        ));
    }

    let unresolved_high_risk = falsification
        .get("unresolved_high_risk_counterexamples")
        .and_then(Value::as_array)
        .ok_or_else(|| {
            StoreError::Validation(
                "doctrine promotion requires unresolved_high_risk_counterexamples".into(),
            )
        })?;
    if !unresolved_high_risk.is_empty() {
        return Err(StoreError::Validation(
            "doctrine promotion blocked by unresolved high-risk counterexample".into(),
        ));
    }

    Ok(())
}

fn require_non_empty_str(value: &Value, field: &str) -> StoreResult<()> {
    string_field(value, field).map(|_| ())
}

fn string_field<'a>(value: &'a Value, field: &str) -> StoreResult<&'a str> {
    let Some(text) = value.get(field).and_then(Value::as_str) else {
        return Err(StoreError::Validation(format!(
            "doctrine promotion attestation requires {field}"
        )));
    };
    if text.trim().is_empty() {
        return Err(StoreError::Validation(format!(
            "doctrine promotion attestation {field} must not be empty"
        )));
    }
    Ok(text)
}

fn require_hex_len(value: &Value, field: &str, len: usize) -> StoreResult<()> {
    require_non_empty_str(value, field)?;
    let text = value.get(field).and_then(Value::as_str).unwrap_or_default();
    if text.len() != len || !text.chars().all(|ch| ch.is_ascii_hexdigit()) {
        return Err(StoreError::Validation(format!(
            "doctrine promotion attestation {field} must be {len} hex characters"
        )));
    }
    Ok(())
}

fn decode_hex_array<const N: usize>(text: &str) -> StoreResult<[u8; N]> {
    if text.len() != N * 2 || !text.chars().all(|ch| ch.is_ascii_hexdigit()) {
        return Err(StoreError::Validation(format!(
            "doctrine promotion attestation hex field must be {} hex characters",
            N * 2
        )));
    }
    let mut out = [0_u8; N];
    for (index, byte) in out.iter_mut().enumerate() {
        let start = index * 2;
        *byte = u8::from_str_radix(&text[start..start + 2], 16).map_err(|err| {
            StoreError::Validation(format!(
                "doctrine promotion attestation hex decode failed: {err}"
            ))
        })?;
    }
    Ok(out)
}

fn json_array_len(value: &Value) -> usize {
    value.as_array().map_or(0, Vec::len)
}

fn validate_score(value: f64, field: &str) -> StoreResult<()> {
    if value.is_finite() && (0.0..=1.0).contains(&value) {
        Ok(())
    } else {
        Err(StoreError::Validation(format!(
            "principle candidate {field} must be between 0 and 1"
        )))
    }
}

fn require_policy_final_outcome(policy: &PolicyDecision, surface: &str) -> StoreResult<()> {
    match policy.final_outcome {
        PolicyOutcome::Allow | PolicyOutcome::Warn | PolicyOutcome::BreakGlass => Ok(()),
        PolicyOutcome::Quarantine | PolicyOutcome::Reject => Err(StoreError::Validation(format!(
            "{surface} preflight: composed policy outcome {:?} blocks principle mutation",
            policy.final_outcome,
        ))),
    }
}

fn require_contributor_rule(policy: &PolicyDecision, rule_id: &str) -> StoreResult<()> {
    let contains_rule = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .any(|contribution| contribution.rule_id.as_str() == rule_id);
    if contains_rule {
        Ok(())
    } else {
        Err(StoreError::Validation(format!(
            "policy decision missing required contributor `{rule_id}`; caller skipped ADR 0026 composition",
        )))
    }
}

fn require_contributor_not_break_glassed(
    policy: &PolicyDecision,
    rule_id: &str,
    surface: &str,
) -> StoreResult<()> {
    // ADR 0026 §4: BreakGlass MUST NOT substitute for the falsification
    // contributor at the principle root. The contributor must itself have
    // voted `Allow` regardless of how the rest of the composition resolved.
    let contribution = policy
        .contributing
        .iter()
        .chain(policy.discarded.iter())
        .find(|contribution| contribution.rule_id.as_str() == rule_id)
        .ok_or_else(|| {
            StoreError::Validation(format!(
                "{surface} preflight: required contributor `{rule_id}` is absent from the policy decision",
            ))
        })?;
    if contribution.outcome == PolicyOutcome::Allow {
        Ok(())
    } else {
        Err(StoreError::Validation(format!(
            "{surface} preflight: contributor `{rule_id}` returned {:?}; ADR 0026 §4 forbids BreakGlass substituting for falsification evidence",
            contribution.outcome,
        )))
    }
}

/// Build a [`PolicyDecision`] that satisfies [`PrincipleRepo::insert_candidate`]
/// inputs for the happy path. Intended for tests and fixtures only.
///
/// Production callers MUST compose [`CANDIDATE_FALSIFICATION_RULE_ID`] from a
/// real falsification record and
/// [`CANDIDATE_SUPPORTING_MEMORY_PROOF_RULE_ID`] from real
/// store-local proof closure of each supporting memory id. This helper is
/// exposed unconditionally because integration test crates outside
/// `cortex-store` need the same fixture shape; the `_test_allow` suffix is the
/// contract that documents intent.
#[must_use]
pub fn insert_candidate_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::compose_policy_outcomes;
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                CANDIDATE_FALSIFICATION_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: falsification record present",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                CANDIDATE_SUPPORTING_MEMORY_PROOF_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: supporting memory proof closure satisfied",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}

/// Build a [`PolicyDecision`] that satisfies
/// [`PrincipleRepo::promote_to_doctrine`] inputs for the happy path. Intended
/// for tests and fixtures only.
///
/// Production callers MUST fold the real composed promotion decision (with the
/// falsification contributor as [`PolicyOutcome::Allow`]) into this call. See
/// [`insert_candidate_policy_decision_test_allow`] for the production-caller
/// contract.
#[must_use]
pub fn promote_to_doctrine_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::compose_policy_outcomes;
    compose_policy_outcomes(
        vec![PolicyContribution::new(
            PROMOTION_FALSIFICATION_RULE_ID,
            PolicyOutcome::Allow,
            "test fixture: promotion falsification record allowed",
        )
        .expect("static test contribution is valid")],
        None,
    )
}