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
//! ADR 0026 enforcement-lattice tests for `MemoryRepo::accept_candidate`.
//!
//! Slice #5 of `docs/design/ADR_0026_consumer_punch_list.md` makes the durable
//! candidate -> active transition fail closed for `PARTIAL` / `BROKEN`
//! supporting-memory proof closure and for unresolved open durable
//! contradictions. These tests cover, per ADR 0026 §5 "Rule registration and
//! evaluation," that:
//!
//!   1. A partial-proof candidate fails closed: the composed
//!      [`PolicyOutcome::Quarantine`] decision blocks the candidate -> active
//!      flip and no `memory.accept` audit row is written.
//!   2. A contradicted candidate (composed [`PolicyOutcome::Reject`]) fails
//!      closed.
//!   3. Compositions missing any of the four required contributor rule ids
//!      fail closed.
//!   4. ADR 0026 §4 holds at this surface: `BreakGlass` MUST NOT substitute
//!      for `memory.accept.operator_temporal_use`.
//!   5. A properly composed `Allow` decision succeeds and the row is active.

use chrono::{DateTime, TimeZone, Utc};
use cortex_core::{
    compose_policy_outcomes, AuditRecordId, BreakGlassAuthorization, BreakGlassReasonCode,
    BreakGlassScope, MemoryId, PolicyContribution, PolicyOutcome,
};
use cortex_store::migrate::apply_pending;
use cortex_store::repo::memories::{
    accept_candidate_policy_decision_test_allow, ACCEPT_OPEN_CONTRADICTION_RULE_ID,
    ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID, ACCEPT_PROOF_CLOSURE_RULE_ID,
    ACCEPT_SEMANTIC_TRUST_RULE_ID,
};
use cortex_store::repo::{MemoryAcceptanceAudit, MemoryCandidate, MemoryRepo};
use cortex_store::Pool;
use rusqlite::Connection;
use serde_json::json;

fn test_pool() -> Pool {
    let pool = Connection::open_in_memory().expect("open in-memory sqlite");
    apply_pending(&pool).expect("apply migrations");
    pool
}

fn at(second: u32) -> DateTime<Utc> {
    Utc.with_ymd_and_hms(2026, 1, 1, 12, 0, second).unwrap()
}

fn memory_id() -> MemoryId {
    "mem_01ARZ3NDEKTSV4RRFFQ69G5FAV".parse().unwrap()
}

fn candidate() -> MemoryCandidate {
    MemoryCandidate {
        id: memory_id(),
        memory_type: "semantic".into(),
        claim: "Candidate awaits operator-attested acceptance.".into(),
        source_episodes_json: json!([]),
        source_events_json: json!(["evt_01ARZ3NDEKTSV4RRFFQ69G5FAV"]),
        domains_json: json!(["accept-policy"]),
        salience_json: json!({"score": 0.5}),
        confidence: 0.7,
        authority: "candidate".into(),
        applies_when_json: json!([]),
        does_not_apply_when_json: json!([]),
        created_at: at(1),
        updated_at: at(1),
    }
}

fn audit_row() -> MemoryAcceptanceAudit {
    MemoryAcceptanceAudit {
        id: AuditRecordId::new(),
        actor_json: json!({"kind": "test"}),
        reason: "accept policy lattice test".into(),
        source_refs_json: json!(["evt_01ARZ3NDEKTSV4RRFFQ69G5FAV"]),
        created_at: at(2),
    }
}

fn seed_candidate(pool: &Pool) {
    MemoryRepo::new(pool)
        .insert_candidate(&candidate())
        .expect("seed candidate row");
}

fn candidate_status(pool: &Pool) -> Option<String> {
    pool.query_row(
        "SELECT status FROM memories WHERE id = ?1;",
        [memory_id().to_string()],
        |row| row.get(0),
    )
    .ok()
}

fn accept_audit_count(pool: &Pool) -> i64 {
    pool.query_row(
        "SELECT COUNT(*) FROM audit_records WHERE operation = 'memory.accept' AND target_ref = ?1;",
        [memory_id().to_string()],
        |row| row.get(0),
    )
    .expect("count memory.accept audit rows")
}

// -----------------------------------------------------------------------------
// Reject / Quarantine fail closed
// -----------------------------------------------------------------------------

#[test]
fn accept_candidate_refuses_partial_proof_closure_without_mutation() {
    let pool = test_pool();
    let repo = MemoryRepo::new(&pool);
    seed_candidate(&pool);

    // Partial proof closure for the supporting memory: the proof contributor
    // composes as `Quarantine` per ADR 0036 / ADR 0026 §3.
    let quarantine_decision = compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                ACCEPT_PROOF_CLOSURE_RULE_ID,
                PolicyOutcome::Quarantine,
                "supporting memory has partial proof closure",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_OPEN_CONTRADICTION_RULE_ID,
                PolicyOutcome::Allow,
                "no open durable contradiction on candidate slot",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_SEMANTIC_TRUST_RULE_ID,
                PolicyOutcome::Allow,
                "semantic trust posture satisfied",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID,
                PolicyOutcome::Allow,
                "operator temporal authority is currently valid",
            )
            .unwrap(),
        ],
        None,
    );
    assert_eq!(quarantine_decision.final_outcome, PolicyOutcome::Quarantine);

    let err = repo
        .accept_candidate(&memory_id(), at(3), &audit_row(), &quarantine_decision)
        .expect_err("Quarantine policy must fail closed");
    assert!(
        err.to_string().contains("Quarantine"),
        "error must name the blocking outcome: {err}"
    );

    assert_eq!(
        candidate_status(&pool).as_deref(),
        Some("candidate"),
        "candidate status must not flip when policy fails closed"
    );
    assert_eq!(
        accept_audit_count(&pool),
        0,
        "no memory.accept audit row may be written when policy fails closed"
    );
}

#[test]
fn accept_candidate_refuses_open_contradiction_without_mutation() {
    let pool = test_pool();
    let repo = MemoryRepo::new(&pool);
    seed_candidate(&pool);

    // Open contradiction on the candidate slot: the contradiction contributor
    // composes as `Reject` per ADR 0024 / ADR 0026 §3.
    let reject_decision = compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                ACCEPT_PROOF_CLOSURE_RULE_ID,
                PolicyOutcome::Allow,
                "supporting memory proof closure verified",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_OPEN_CONTRADICTION_RULE_ID,
                PolicyOutcome::Reject,
                "open durable contradiction touches candidate slot",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_SEMANTIC_TRUST_RULE_ID,
                PolicyOutcome::Allow,
                "semantic trust posture satisfied",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID,
                PolicyOutcome::Allow,
                "operator temporal authority is currently valid",
            )
            .unwrap(),
        ],
        None,
    );
    assert_eq!(reject_decision.final_outcome, PolicyOutcome::Reject);

    let err = repo
        .accept_candidate(&memory_id(), at(3), &audit_row(), &reject_decision)
        .expect_err("Reject policy must fail closed");
    assert!(
        err.to_string().contains("Reject"),
        "error must name the blocking outcome: {err}"
    );

    assert_eq!(
        candidate_status(&pool).as_deref(),
        Some("candidate"),
        "candidate status must not flip when policy fails closed"
    );
    assert_eq!(
        accept_audit_count(&pool),
        0,
        "no memory.accept audit row may be written when policy fails closed"
    );
}

// -----------------------------------------------------------------------------
// Missing-contributor compositions fail closed
// -----------------------------------------------------------------------------

#[test]
fn accept_candidate_refuses_missing_proof_closure_contributor() {
    let pool = test_pool();
    let repo = MemoryRepo::new(&pool);
    seed_candidate(&pool);

    let decision = compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                ACCEPT_OPEN_CONTRADICTION_RULE_ID,
                PolicyOutcome::Allow,
                "no open durable contradiction on candidate slot",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_SEMANTIC_TRUST_RULE_ID,
                PolicyOutcome::Allow,
                "semantic trust posture satisfied",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID,
                PolicyOutcome::Allow,
                "operator temporal authority is currently valid",
            )
            .unwrap(),
        ],
        None,
    );

    let err = repo
        .accept_candidate(&memory_id(), at(3), &audit_row(), &decision)
        .expect_err("missing proof closure contributor must fail closed");
    assert!(
        err.to_string().contains(ACCEPT_PROOF_CLOSURE_RULE_ID),
        "error must name the missing contributor: {err}"
    );
    assert_eq!(candidate_status(&pool).as_deref(), Some("candidate"));
}

#[test]
fn accept_candidate_refuses_missing_operator_temporal_use_contributor() {
    let pool = test_pool();
    let repo = MemoryRepo::new(&pool);
    seed_candidate(&pool);

    let decision = compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                ACCEPT_PROOF_CLOSURE_RULE_ID,
                PolicyOutcome::Allow,
                "proof closure verified",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_OPEN_CONTRADICTION_RULE_ID,
                PolicyOutcome::Allow,
                "no open contradiction",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_SEMANTIC_TRUST_RULE_ID,
                PolicyOutcome::Allow,
                "semantic trust satisfied",
            )
            .unwrap(),
        ],
        None,
    );

    let err = repo
        .accept_candidate(&memory_id(), at(3), &audit_row(), &decision)
        .expect_err("missing operator-temporal-use contributor must fail closed");
    assert!(
        err.to_string()
            .contains(ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID),
        "error must name the missing contributor: {err}"
    );
}

// -----------------------------------------------------------------------------
// ADR 0026 §4: BreakGlass cannot substitute for current-use temporal authority
// -----------------------------------------------------------------------------

#[test]
fn accept_candidate_refuses_break_glass_substituting_for_temporal_authority() {
    let pool = test_pool();
    let repo = MemoryRepo::new(&pool);
    seed_candidate(&pool);

    // Operator temporal use voted `Quarantine` (historical-only authority);
    // a BreakGlass contributor cannot substitute for it. The composer would
    // resolve to `Quarantine` regardless, but this test confirms the
    // repo-level §4 wall: even if the final outcome were softened, the
    // attestation contributor must itself be `Allow`.
    let scope = BreakGlassScope {
        operation_type: "memory.accept".into(),
        artifact_refs: vec![memory_id().to_string()],
        not_before: None,
        not_after: None,
    };
    let break_glass = BreakGlassAuthorization {
        permitted: true,
        attested: true,
        scope,
        reason_code: BreakGlassReasonCode::OperatorCorrection,
    };
    let decision = compose_policy_outcomes(
        vec![
            PolicyContribution::new(
                ACCEPT_PROOF_CLOSURE_RULE_ID,
                PolicyOutcome::Allow,
                "proof closure verified",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_OPEN_CONTRADICTION_RULE_ID,
                PolicyOutcome::Allow,
                "no open contradiction",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_SEMANTIC_TRUST_RULE_ID,
                PolicyOutcome::Allow,
                "semantic trust satisfied",
            )
            .unwrap(),
            PolicyContribution::new(
                ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID,
                PolicyOutcome::Quarantine,
                "operator temporal authority is historical only",
            )
            .unwrap()
            .allow_break_glass_override(),
            PolicyContribution::new(
                "operator.override",
                PolicyOutcome::BreakGlass,
                "operator override requested",
            )
            .unwrap(),
        ],
        Some(break_glass),
    );

    let err = repo
        .accept_candidate(&memory_id(), at(3), &audit_row(), &decision)
        .expect_err("BreakGlass cannot substitute for current-use temporal authority");
    let message = err.to_string();
    assert!(
        message.contains(ACCEPT_OPERATOR_TEMPORAL_USE_RULE_ID)
            || message.contains("Quarantine")
            || message.contains("BreakGlass"),
        "error must surface the §4 wall: {message}"
    );
    assert_eq!(candidate_status(&pool).as_deref(), Some("candidate"));
}

// -----------------------------------------------------------------------------
// Happy path
// -----------------------------------------------------------------------------

#[test]
fn accept_candidate_accepts_properly_composed_allow_decision() {
    let pool = test_pool();
    let repo = MemoryRepo::new(&pool);
    seed_candidate(&pool);

    let policy = accept_candidate_policy_decision_test_allow();
    let accepted = repo
        .accept_candidate(&memory_id(), at(3), &audit_row(), &policy)
        .expect("Allow decision must be accepted");

    assert_eq!(accepted.status, "active");
    assert_eq!(candidate_status(&pool).as_deref(), Some("active"));
    assert_eq!(
        accept_audit_count(&pool),
        1,
        "exactly one memory.accept audit row must be written on success"
    );
}