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
//! ADR 0026 enforcement-lattice tests for
//! `MemoryRepo::insert_candidate_with_v2_fields`.
//!
//! Slice #4 of `docs/design/ADR_0026_consumer_punch_list.md`. The schema-v2
//! summary-span / cross-session-salience opt-in write composes through the
//! ADR 0026 lattice before the SQLite INSERT. These tests cover:
//!
//!   1. Summary spans that violate ADR 0015's structural invariants
//!      (uncovered non-whitespace text, authority-cache mismatch, UTF-8
//!      boundary violations) fail closed.
//!   2. Cross-session salience metadata pre-populated on a candidate row
//!      (ADR 0017 says salience must be earned, never minted at insert) fails
//!      closed.
//!   3. Compositions missing either required contributor rule id fail closed.
//!   4. A properly composed `Allow` decision with valid v2 fields succeeds.

use chrono::{DateTime, TimeZone, Utc};
use cortex_core::{
    compose_policy_outcomes, CrossSessionSalience, EventId, MemoryId, PolicyContribution,
    PolicyOutcome, SourceAuthority, SummarySpan,
};
use cortex_store::migrate::apply_pending;
use cortex_store::migrate_v2::apply_expand_backfill_skeleton;
use cortex_store::repo::memories::{
    cross_session_salience_contribution, insert_candidate_v2_policy_decision_test_allow,
    summary_span_proof_contribution, V2_CROSS_SESSION_SALIENCE_RULE_ID,
    V2_SUMMARY_SPAN_PROOF_RULE_ID,
};
use cortex_store::repo::{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");
    apply_expand_backfill_skeleton(&pool, "2026-05-04T13:00:00Z".parse().unwrap())
        .expect("expand/backfill skeleton before v2 inserts");
    pool
}

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

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

fn source_event_id() -> EventId {
    "evt_01ARZ3NDEKTSV4RRFFQ69G5V60".parse().unwrap()
}

fn summary_claim() -> &'static str {
    "v2 summary memory claim."
}

fn valid_span() -> SummarySpan {
    let len: u32 = u32::try_from(summary_claim().len()).expect("claim fits u32");
    SummarySpan {
        byte_start: 0,
        byte_end: len,
        derived_from_event_ids: vec![source_event_id()],
        max_source_authority: SourceAuthority::Derived,
    }
}

fn candidate() -> MemoryCandidate {
    MemoryCandidate {
        id: memory_id(),
        memory_type: "summary".into(),
        claim: summary_claim().into(),
        source_episodes_json: json!([]),
        source_events_json: json!([source_event_id().to_string()]),
        domains_json: json!(["v2"]),
        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 fresh_salience() -> CrossSessionSalience {
    CrossSessionSalience {
        cross_session_use_count: 0,
        first_used_at: None,
        last_cross_session_use_at: None,
        last_validation_at: None,
        validation_epoch: 0,
        blessed_until: None,
    }
}

fn count_memories(pool: &Pool) -> i64 {
    pool.query_row("SELECT COUNT(*) FROM memories;", [], |row| row.get(0))
        .expect("count memories")
}

// -----------------------------------------------------------------------------
// Summary span validation fails closed
// -----------------------------------------------------------------------------

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

    // The summary text "v2 summary memory claim." (24 bytes) is partially
    // covered by a span ending at byte 5. ADR 0015 requires every
    // non-whitespace byte to fall inside exactly one span.
    let invalid_span = SummarySpan {
        byte_start: 0,
        byte_end: 5,
        derived_from_event_ids: vec![source_event_id()],
        max_source_authority: SourceAuthority::Derived,
    };
    let memory = candidate();
    let salience = fresh_salience();

    // Compose a real summary_span_proof contribution; it must surface Reject.
    let span_contribution =
        summary_span_proof_contribution(&memory, std::slice::from_ref(&invalid_span), |_| {
            SourceAuthority::Derived
        });
    assert_eq!(span_contribution.outcome, PolicyOutcome::Reject);
    let salience_contribution = cross_session_salience_contribution(&salience);
    let decision = compose_policy_outcomes(vec![span_contribution, salience_contribution], None);
    assert_eq!(decision.final_outcome, PolicyOutcome::Reject);

    let err = repo
        .insert_candidate_with_v2_fields(
            &memory,
            std::slice::from_ref(&invalid_span),
            &salience,
            &decision,
        )
        .expect_err("Reject policy must fail closed for invalid summary spans");
    assert!(
        err.to_string().contains("Reject"),
        "error must name the blocking outcome: {err}"
    );
    assert_eq!(
        count_memories(&pool),
        0,
        "no memory row may be written when summary spans fail validation"
    );
}

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

    // Cached `max_source_authority` claims `User` but the recomputed fold of
    // the source events maps to `Derived`. ADR 0015 says the cache MUST match
    // the recomputed authority or the write fails closed.
    let uplifted_span = SummarySpan {
        byte_start: 0,
        byte_end: u32::try_from(summary_claim().len()).unwrap(),
        derived_from_event_ids: vec![source_event_id()],
        max_source_authority: SourceAuthority::User,
    };
    let memory = candidate();
    let salience = fresh_salience();

    let span_contribution =
        summary_span_proof_contribution(&memory, std::slice::from_ref(&uplifted_span), |_| {
            SourceAuthority::Derived
        });
    assert_eq!(span_contribution.outcome, PolicyOutcome::Reject);
    let decision = compose_policy_outcomes(
        vec![
            span_contribution,
            cross_session_salience_contribution(&salience),
        ],
        None,
    );

    let err = repo
        .insert_candidate_with_v2_fields(
            &memory,
            std::slice::from_ref(&uplifted_span),
            &salience,
            &decision,
        )
        .expect_err("Reject policy must fail closed for authority uplift");
    assert!(err.to_string().contains("Reject"));
    assert_eq!(count_memories(&pool), 0);
}

// -----------------------------------------------------------------------------
// ADR 0017 salience invariants fail closed at candidate insert
// -----------------------------------------------------------------------------

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

    let mut salience = fresh_salience();
    salience.cross_session_use_count = 5;
    let memory = candidate();
    let spans = vec![valid_span()];

    let salience_contribution = cross_session_salience_contribution(&salience);
    assert_eq!(salience_contribution.outcome, PolicyOutcome::Reject);
    let decision = compose_policy_outcomes(
        vec![
            summary_span_proof_contribution(&memory, &spans, |_| SourceAuthority::Derived),
            salience_contribution,
        ],
        None,
    );

    let err = repo
        .insert_candidate_with_v2_fields(&memory, &spans, &salience, &decision)
        .expect_err("Reject policy must fail closed for pre-populated salience");
    assert!(
        err.to_string().contains("Reject"),
        "error must name the blocking outcome: {err}"
    );
    assert_eq!(count_memories(&pool), 0);
}

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

    // Even if the operator sets `last_validation_at` to a past time, ADR 0017
    // says only a `Validated` outcome edge may advance it. Minting it at
    // insert would let the candidate skip the rolling-validation gate.
    let mut salience = fresh_salience();
    salience.last_validation_at = Some(at(0));
    let memory = candidate();
    let spans = vec![valid_span()];

    let decision = compose_policy_outcomes(
        vec![
            summary_span_proof_contribution(&memory, &spans, |_| SourceAuthority::Derived),
            cross_session_salience_contribution(&salience),
        ],
        None,
    );

    let err = repo
        .insert_candidate_with_v2_fields(&memory, &spans, &salience, &decision)
        .expect_err("Reject policy must fail closed for minted validation freshness");
    assert!(err.to_string().contains("Reject"));
    assert_eq!(count_memories(&pool), 0);
}

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

    // `blessed_until` is the operator-attested waiver from ADR 0017's bless
    // command. A candidate cannot mint its own bless window at insert time.
    let mut salience = fresh_salience();
    salience.blessed_until = Some(at(7));
    let memory = candidate();
    let spans = vec![valid_span()];

    let decision = compose_policy_outcomes(
        vec![
            summary_span_proof_contribution(&memory, &spans, |_| SourceAuthority::Derived),
            cross_session_salience_contribution(&salience),
        ],
        None,
    );

    let err = repo
        .insert_candidate_with_v2_fields(&memory, &spans, &salience, &decision)
        .expect_err("Reject policy must fail closed for minted bless window");
    assert!(err.to_string().contains("Reject"));
    assert_eq!(count_memories(&pool), 0);
}

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

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

    let memory = candidate();
    let spans = vec![valid_span()];
    let salience = fresh_salience();

    let decision = compose_policy_outcomes(
        vec![PolicyContribution::new(
            V2_CROSS_SESSION_SALIENCE_RULE_ID,
            PolicyOutcome::Allow,
            "salience matches candidate-row invariants",
        )
        .unwrap()],
        None,
    );

    let err = repo
        .insert_candidate_with_v2_fields(&memory, &spans, &salience, &decision)
        .expect_err("missing summary span contributor must fail closed");
    assert!(
        err.to_string().contains(V2_SUMMARY_SPAN_PROOF_RULE_ID),
        "error must name the missing contributor: {err}"
    );
    assert_eq!(count_memories(&pool), 0);
}

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

    let memory = candidate();
    let spans = vec![valid_span()];
    let salience = fresh_salience();

    let decision = compose_policy_outcomes(
        vec![PolicyContribution::new(
            V2_SUMMARY_SPAN_PROOF_RULE_ID,
            PolicyOutcome::Allow,
            "summary spans validated",
        )
        .unwrap()],
        None,
    );

    let err = repo
        .insert_candidate_with_v2_fields(&memory, &spans, &salience, &decision)
        .expect_err("missing cross-session salience contributor must fail closed");
    assert!(
        err.to_string().contains(V2_CROSS_SESSION_SALIENCE_RULE_ID),
        "error must name the missing contributor: {err}"
    );
    assert_eq!(count_memories(&pool), 0);
}

// -----------------------------------------------------------------------------
// Stale Allow vs regressed invariant: the repo must independently re-validate
// -----------------------------------------------------------------------------

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

    // A caller could in principle pass `insert_candidate_v2_policy_decision_test_allow`
    // alongside corrupted salience. The repo MUST NOT trust a stale `Allow`
    // verdict: it re-runs `validate_candidate_cross_session_salience` after
    // the contributor check. This guards against the ADR 0026 ยง2 fuse-outside-
    // the-engine failure mode.
    let mut salience = fresh_salience();
    salience.validation_epoch = 9;
    let memory = candidate();
    let spans = vec![valid_span()];

    let stale_allow_decision = insert_candidate_v2_policy_decision_test_allow();
    assert_eq!(stale_allow_decision.final_outcome, PolicyOutcome::Allow);

    let err = repo
        .insert_candidate_with_v2_fields(&memory, &spans, &salience, &stale_allow_decision)
        .expect_err("repo must independently re-validate ADR 0017 invariants");
    assert!(
        err.to_string().contains("validation_epoch"),
        "error must name the regressed invariant: {err}"
    );
    assert_eq!(count_memories(&pool), 0);
}

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

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

    let memory = candidate();
    let spans = vec![valid_span()];
    let salience = fresh_salience();

    let span_contribution =
        summary_span_proof_contribution(&memory, &spans, |_| SourceAuthority::Derived);
    assert_eq!(span_contribution.outcome, PolicyOutcome::Allow);
    let salience_contribution = cross_session_salience_contribution(&salience);
    assert_eq!(salience_contribution.outcome, PolicyOutcome::Allow);
    let decision = compose_policy_outcomes(vec![span_contribution, salience_contribution], None);
    assert_eq!(decision.final_outcome, PolicyOutcome::Allow);

    repo.insert_candidate_with_v2_fields(&memory, &spans, &salience, &decision)
        .expect("Allow decision with valid v2 fields must be accepted");

    assert_eq!(count_memories(&pool), 1);
    let (cross_session_use_count, validation_epoch): (u32, u32) = pool
        .query_row(
            "SELECT cross_session_use_count, validation_epoch
             FROM memories WHERE id = ?1;",
            [memory_id().to_string()],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .expect("read v2 salience columns");
    assert_eq!(cross_session_use_count, 0);
    assert_eq!(validation_epoch, 0);
}