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
//! Contradiction repository operations.
//!
//! ADR 0024 makes contradictions a first-class durable surface, and ADR 0026
//! §2 requires every mutation of that surface to compose through the policy
//! lattice. Every state-changing entry point on [`ContradictionRepo`] now
//! requires the caller to pass a composed [`PolicyDecision`] whose contributing
//! rules name the ADR 0024 invariants being asserted.
//!
//! Required contributor rule ids:
//!
//! - [`INSERT_SCOPE_VALIDITY_RULE_ID`] and [`INSERT_UNRESOLVED_STATE_RULE_ID`]
//!   for [`ContradictionRepo::insert`].
//! - [`TRANSITION_ACTOR_AUTHORITY_RULE_ID`] and
//!   [`TRANSITION_RESOLUTION_EVIDENCE_RULE_ID`] for every transition
//!   ([`ContradictionRepo::interpret`], [`ContradictionRepo::resolve`],
//!   [`ContradictionRepo::delete`]).
//! - [`TRANSITION_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID`] additionally on
//!   [`ContradictionRepo::resolve`] and [`ContradictionRepo::delete`] — these
//!   close the ADR 0024 slot and ADR 0023 §3 requires the operator carrying the
//!   resolution to currently hold the authority.

use chrono::{DateTime, Utc};
use cortex_core::{
    ContradictionId, PolicyContribution, PolicyDecision, PolicyOutcome, TemporalAuthorityReport,
};
use rusqlite::{params, OptionalExtension, Row};

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

macro_rules! contradiction_select_sql {
    ($where_clause:literal) => {
        concat!(
            "SELECT id, left_ref, right_ref, contradiction_type, status, interpretation,
                    created_at, updated_at
             FROM contradictions ",
            $where_clause,
            ";"
        )
    };
}

/// Required contributor rule id documenting that the contradiction scope
/// (left/right refs + contradiction kind) was validated by the caller before
/// the row was persisted (ADR 0024 §3 `claim_key` framing, ADR 0026 §5).
pub const INSERT_SCOPE_VALIDITY_RULE_ID: &str = "contradictions.insert.scope_validity";
/// Required contributor rule id documenting that the caller asserted the
/// initial lifecycle state for a newly inserted contradiction (ADR 0024 §3
/// `ConflictUnresolved`, ADR 0026 §5).
pub const INSERT_UNRESOLVED_STATE_RULE_ID: &str = "contradictions.insert.unresolved_state";
/// Required contributor rule id documenting the actor authority backing a
/// contradiction lifecycle transition (ADR 0024 §4 operator path, ADR 0026 §4).
pub const TRANSITION_ACTOR_AUTHORITY_RULE_ID: &str = "contradictions.transition.actor_authority";
/// Required contributor rule id documenting the evidence backing a resolution
/// or interpretation note (ADR 0024 §4 `audit_records`, ADR 0026 §7).
pub const TRANSITION_RESOLUTION_EVIDENCE_RULE_ID: &str =
    "contradictions.transition.resolution_evidence";
/// Required contributor rule id documenting that the operator carrying a
/// closing transition (`resolve` / `delete`) currently holds the required
/// temporal authority (ADR 0023 §3 current-use, ADR 0026 §4).
pub const TRANSITION_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID: &str =
    "contradictions.transition.operator_temporal_authority";

/// Durable contradiction status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContradictionStatus {
    /// Detected, not yet interpreted.
    Unresolved,
    /// Interpreted, but still open.
    Interpreted,
    /// Closed by an explicit resolution.
    Resolved,
}

impl ContradictionStatus {
    /// Returns the stable SQLite wire value.
    #[must_use]
    pub const fn wire(self) -> &'static str {
        match self {
            Self::Unresolved => "unresolved",
            Self::Interpreted => "interpreted",
            Self::Resolved => "resolved",
        }
    }

    /// Whether this status still represents an open conflict.
    #[must_use]
    pub const fn is_open(self) -> bool {
        matches!(self, Self::Unresolved | Self::Interpreted)
    }
}

/// Durable contradiction row matching the current store schema.
#[derive(Debug, Clone, PartialEq)]
pub struct ContradictionRecord {
    /// Stable contradiction identifier.
    pub id: ContradictionId,
    /// Left memory/principle/reference.
    pub left_ref: String,
    /// Right memory/principle/reference.
    pub right_ref: String,
    /// Conflict kind.
    pub contradiction_type: String,
    /// Current lifecycle status.
    pub status: ContradictionStatus,
    /// Interpretation or resolution note.
    pub interpretation: Option<String>,
    /// Creation timestamp.
    pub created_at: DateTime<Utc>,
    /// Last update timestamp.
    pub updated_at: DateTime<Utc>,
}

/// Repository for first-class contradiction rows.
#[derive(Debug)]
pub struct ContradictionRepo<'a> {
    pool: &'a Pool,
}

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

    /// Inserts one unresolved/interpreted/resolved contradiction row through
    /// the ADR 0026 enforcement lattice.
    ///
    /// `policy` is the composed [`PolicyDecision`] for this 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
    ///    [`INSERT_SCOPE_VALIDITY_RULE_ID`] and
    ///    [`INSERT_UNRESOLVED_STATE_RULE_ID`]. The repo refuses callers that
    ///    skipped composition.
    pub fn insert(
        &self,
        contradiction: &ContradictionRecord,
        policy: &PolicyDecision,
    ) -> StoreResult<()> {
        require_policy_final_outcome(policy, "contradictions.insert")?;
        require_contributor_rule(policy, INSERT_SCOPE_VALIDITY_RULE_ID)?;
        require_contributor_rule(policy, INSERT_UNRESOLVED_STATE_RULE_ID)?;

        validate_record(contradiction)?;
        self.pool.execute(
            "INSERT INTO contradictions (
                id, left_ref, right_ref, contradiction_type, status, interpretation,
                created_at, updated_at
             ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8);",
            params![
                contradiction.id.to_string(),
                contradiction.left_ref,
                contradiction.right_ref,
                contradiction.contradiction_type,
                contradiction.status.wire(),
                contradiction.interpretation,
                contradiction.created_at.to_rfc3339(),
                contradiction.updated_at.to_rfc3339(),
            ],
        )?;

        Ok(())
    }

    /// Fetches a contradiction by id.
    pub fn get_by_id(&self, id: &ContradictionId) -> StoreResult<Option<ContradictionRecord>> {
        let row = self
            .pool
            .query_row(
                contradiction_select_sql!("WHERE id = ?1"),
                params![id.to_string()],
                contradiction_row,
            )
            .optional()?;

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

    /// Lists all contradiction rows in deterministic creation order.
    pub fn list(&self) -> StoreResult<Vec<ContradictionRecord>> {
        let mut stmt = self
            .pool
            .prepare(contradiction_select_sql!("ORDER BY created_at, id"))?;
        let rows = stmt.query_map([], contradiction_row)?;
        collect_records(rows)
    }

    /// Lists contradictions with the requested status.
    pub fn list_by_status(
        &self,
        status: ContradictionStatus,
    ) -> StoreResult<Vec<ContradictionRecord>> {
        let mut stmt = self.pool.prepare(contradiction_select_sql!(
            "WHERE status = ?1 ORDER BY created_at, id"
        ))?;
        let rows = stmt.query_map(params![status.wire()], contradiction_row)?;
        collect_records(rows)
    }

    /// Lists unresolved and interpreted contradictions.
    pub fn list_open(&self) -> StoreResult<Vec<ContradictionRecord>> {
        let mut stmt = self.pool.prepare(contradiction_select_sql!(
            "WHERE status IN ('unresolved', 'interpreted') ORDER BY created_at, id"
        ))?;
        let rows = stmt.query_map([], contradiction_row)?;
        collect_records(rows)
    }

    /// Marks a contradiction interpreted but still open through the ADR 0026
    /// enforcement lattice.
    ///
    /// `policy` must compose [`TRANSITION_ACTOR_AUTHORITY_RULE_ID`] and
    /// [`TRANSITION_RESOLUTION_EVIDENCE_RULE_ID`] contributors. Interpretation
    /// leaves the slot open per ADR 0024 §3 so it does NOT require a temporal
    /// authority contributor — that gate fires only on closing transitions.
    pub fn interpret(
        &self,
        id: &ContradictionId,
        interpretation: &str,
        updated_at: DateTime<Utc>,
        policy: &PolicyDecision,
    ) -> StoreResult<()> {
        require_transition_policy(policy, "contradictions.interpret", false)?;
        update_status(
            self.pool,
            id,
            ContradictionStatus::Interpreted,
            interpretation,
            updated_at,
        )
    }

    /// Marks a contradiction resolved through the ADR 0026 enforcement lattice.
    ///
    /// `policy` must compose
    /// [`TRANSITION_ACTOR_AUTHORITY_RULE_ID`],
    /// [`TRANSITION_RESOLUTION_EVIDENCE_RULE_ID`], and
    /// [`TRANSITION_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID`] contributors.
    /// Resolution closes the ADR 0024 `claim_key` slot, and ADR 0023 §3
    /// requires the operator carrying the close to currently hold the
    /// authority. See [`contradiction_resolve_policy_from_temporal_report`].
    pub fn resolve(
        &self,
        id: &ContradictionId,
        resolution: &str,
        updated_at: DateTime<Utc>,
        policy: &PolicyDecision,
    ) -> StoreResult<()> {
        require_transition_policy(policy, "contradictions.resolve", true)?;
        update_status(
            self.pool,
            id,
            ContradictionStatus::Resolved,
            resolution,
            updated_at,
        )
    }

    /// Deletes a contradiction row through the ADR 0026 enforcement lattice.
    ///
    /// `policy` must compose
    /// [`TRANSITION_ACTOR_AUTHORITY_RULE_ID`],
    /// [`TRANSITION_RESOLUTION_EVIDENCE_RULE_ID`], and
    /// [`TRANSITION_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID`] contributors. Delete
    /// is destructive — ADR 0024 §1 prefers tombstoning — so the operator path
    /// must carry both attestation and current temporal authority before the
    /// row leaves the table.
    pub fn delete(&self, id: &ContradictionId, policy: &PolicyDecision) -> StoreResult<bool> {
        require_transition_policy(policy, "contradictions.delete", true)?;
        let changed = self.pool.execute(
            "DELETE FROM contradictions WHERE id = ?1;",
            params![id.to_string()],
        )?;
        Ok(changed > 0)
    }
}

#[derive(Debug)]
struct ContradictionRow {
    id: String,
    left_ref: String,
    right_ref: String,
    contradiction_type: String,
    status: String,
    interpretation: Option<String>,
    created_at: String,
    updated_at: String,
}

fn contradiction_row(row: &Row<'_>) -> rusqlite::Result<ContradictionRow> {
    Ok(ContradictionRow {
        id: row.get(0)?,
        left_ref: row.get(1)?,
        right_ref: row.get(2)?,
        contradiction_type: row.get(3)?,
        status: row.get(4)?,
        interpretation: row.get(5)?,
        created_at: row.get(6)?,
        updated_at: row.get(7)?,
    })
}

impl TryFrom<ContradictionRow> for ContradictionRecord {
    type Error = StoreError;

    fn try_from(row: ContradictionRow) -> StoreResult<Self> {
        Ok(Self {
            id: row.id.parse()?,
            left_ref: row.left_ref,
            right_ref: row.right_ref,
            contradiction_type: row.contradiction_type,
            status: parse_status(&row.status)?,
            interpretation: row.interpretation,
            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 collect_records<F>(rows: rusqlite::MappedRows<'_, F>) -> StoreResult<Vec<ContradictionRecord>>
where
    F: FnMut(&Row<'_>) -> rusqlite::Result<ContradictionRow>,
{
    let mut records = Vec::new();
    for row in rows {
        records.push(row?.try_into()?);
    }
    Ok(records)
}

fn parse_status(status: &str) -> StoreResult<ContradictionStatus> {
    match status {
        "unresolved" => Ok(ContradictionStatus::Unresolved),
        "interpreted" => Ok(ContradictionStatus::Interpreted),
        "resolved" => Ok(ContradictionStatus::Resolved),
        other => Err(StoreError::Validation(format!(
            "invalid contradiction status {other}"
        ))),
    }
}

fn validate_record(record: &ContradictionRecord) -> StoreResult<()> {
    validate_not_empty("left_ref", &record.left_ref)?;
    validate_not_empty("right_ref", &record.right_ref)?;
    validate_not_empty("contradiction_type", &record.contradiction_type)?;
    if matches!(
        record.status,
        ContradictionStatus::Interpreted | ContradictionStatus::Resolved
    ) && record
        .interpretation
        .as_deref()
        .is_none_or(|value| value.trim().is_empty())
    {
        return Err(StoreError::Validation(
            "interpreted/resolved contradiction requires interpretation".into(),
        ));
    }
    Ok(())
}

fn update_status(
    pool: &Pool,
    id: &ContradictionId,
    status: ContradictionStatus,
    note: &str,
    updated_at: DateTime<Utc>,
) -> StoreResult<()> {
    validate_not_empty("interpretation", note)?;
    let changed = pool.execute(
        "UPDATE contradictions
         SET status = ?2, interpretation = ?3, updated_at = ?4
         WHERE id = ?1;",
        params![id.to_string(), status.wire(), note, updated_at.to_rfc3339()],
    )?;

    if changed == 0 {
        return Err(StoreError::Validation(format!(
            "contradiction {id} not found"
        )));
    }

    Ok(())
}

fn validate_not_empty(field: &str, value: &str) -> StoreResult<()> {
    if value.trim().is_empty() {
        return Err(StoreError::Validation(format!("{field} must not be empty")));
    }
    Ok(())
}

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 contradiction 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_transition_policy(
    policy: &PolicyDecision,
    surface: &str,
    require_operator_temporal_authority: bool,
) -> StoreResult<()> {
    require_policy_final_outcome(policy, surface)?;
    require_contributor_rule(policy, TRANSITION_ACTOR_AUTHORITY_RULE_ID)?;
    require_contributor_rule(policy, TRANSITION_RESOLUTION_EVIDENCE_RULE_ID)?;
    if require_operator_temporal_authority {
        require_contributor_rule(policy, TRANSITION_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID)?;
    }
    Ok(())
}

/// Build the `contradictions.transition.operator_temporal_authority`
/// contributor for a closing transition (`resolve` / `delete`) from an
/// ADR 0023 [`TemporalAuthorityReport`].
///
/// The contributor outcome mirrors the temporal authority's own
/// [`TemporalAuthorityReport::policy_decision`] outcome:
///
/// - `valid_now` → [`PolicyOutcome::Allow`]
/// - `valid_at_event_time && !valid_now` → [`PolicyOutcome::Quarantine`]
///   (historical signature, current use blocked)
/// - otherwise → [`PolicyOutcome::Reject`]
///
/// Callers should fold this contributor into the closing transition's
/// composition alongside the actor-authority and resolution-evidence
/// contributors.
#[must_use]
pub fn contradiction_transition_temporal_authority_contribution(
    report: &TemporalAuthorityReport,
) -> PolicyContribution {
    let outcome = if report.valid_now {
        PolicyOutcome::Allow
    } else if report.valid_at_event_time {
        PolicyOutcome::Quarantine
    } else {
        PolicyOutcome::Reject
    };
    let reason = if report.valid_now {
        "operator temporal authority is currently valid"
    } else if report.valid_at_event_time {
        "operator temporal authority is historical only; current use blocked"
    } else {
        "operator temporal authority was invalid at event time"
    };
    PolicyContribution::new(
        TRANSITION_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID,
        outcome,
        reason,
    )
    .expect("static contradiction temporal authority contribution is valid")
}

/// Build a [`PolicyDecision`] that satisfies [`ContradictionRepo::insert`] for
/// the happy path. Intended for tests and fixtures only.
///
/// Production callers MUST compose [`INSERT_SCOPE_VALIDITY_RULE_ID`] and
/// [`INSERT_UNRESOLVED_STATE_RULE_ID`] from real ADR 0024 evidence. 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_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::compose_policy_outcomes;
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                INSERT_SCOPE_VALIDITY_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: contradiction scope validated",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                INSERT_UNRESOLVED_STATE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: initial lifecycle state asserted",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}

/// Build a [`PolicyDecision`] that satisfies [`ContradictionRepo::interpret`]
/// for the happy path. Intended for tests and fixtures only; see
/// [`insert_policy_decision_test_allow`] for the production-caller contract.
#[must_use]
pub fn interpret_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::compose_policy_outcomes;
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                TRANSITION_ACTOR_AUTHORITY_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: actor authority present",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                TRANSITION_RESOLUTION_EVIDENCE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: interpretation evidence supplied",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}

/// Build a [`PolicyDecision`] that satisfies the closing-transition
/// (`resolve` / `delete`) entry points for the happy path. Intended for tests
/// and fixtures only.
///
/// Production callers MUST fold an honest
/// [`contradiction_transition_temporal_authority_contribution`] derived from a
/// real [`TemporalAuthorityReport`] into the composition instead of this
/// `Allow` placeholder.
#[must_use]
pub fn close_policy_decision_test_allow() -> PolicyDecision {
    use cortex_core::compose_policy_outcomes;
    compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                TRANSITION_ACTOR_AUTHORITY_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: actor authority present",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                TRANSITION_RESOLUTION_EVIDENCE_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: resolution evidence supplied",
            )
            .expect("static test contribution is valid"),
            PolicyContribution::new(
                TRANSITION_OPERATOR_TEMPORAL_AUTHORITY_RULE_ID,
                PolicyOutcome::Allow,
                "test fixture: operator temporal authority current",
            )
            .expect("static test contribution is valid"),
        ],
        None,
    )
}