crtx-memory 0.1.1

Memory lifecycle, salience, decay policies, and contradiction objects.
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
//! Memory candidate acceptance rules.
//!
//! The store layer owns durable writes; this module owns the memory-domain gate
//! before those writes are attempted.

use std::error::Error;
use std::fmt;

use chrono::{DateTime, Utc};
use cortex_core::{MemoryId, PolicyDecision, ProofClosureReport, ProofState};
use cortex_store::repo::{MemoryAcceptanceAudit, MemoryCandidate, MemoryRepo};
use cortex_store::StoreError;

/// Stable invariant key surfaced when the lifecycle layer refuses an accept
/// because the supplied [`ProofClosureReport`] is not fully verified.
///
/// ADR 0036 forbids a durable candidate -> active mutation when the proof
/// closure is `Partial` or `Broken`. The lifecycle layer fails closed before
/// any store boundary work happens, so any caller (CLI, future API, tests)
/// inherits the gate.
pub const LIFECYCLE_ACCEPT_PROOF_CLOSURE_INVARIANT: &str =
    "cortex_memory.lifecycle.accept.proof_closure";

/// Result type for memory lifecycle operations.
pub type LifecycleResult<T> = Result<T, LifecycleError>;

/// Errors raised by memory lifecycle domain logic.
#[derive(Debug)]
pub enum LifecycleError {
    /// Store boundary failed.
    Store(StoreError),
    /// Candidate lineage or state is invalid.
    Validation(String),
    /// ADR 0036 proof closure refusal: the supplied [`ProofClosureReport`]
    /// was not [`ProofState::FullChainVerified`] and the lifecycle layer
    /// will not promote a partial- or broken-proof candidate to Active.
    /// The associated [`ProofState`] is the observed state.
    ProofClosureRefusal(ProofState),
}

impl fmt::Display for LifecycleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Store(err) => write!(f, "store error: {err}"),
            Self::Validation(message) => write!(f, "validation failed: {message}"),
            Self::ProofClosureRefusal(state) => write!(
                f,
                "invariant={LIFECYCLE_ACCEPT_PROOF_CLOSURE_INVARIANT} proof closure must be FullChainVerified for durable accept; observed {state:?}"
            ),
        }
    }
}

impl Error for LifecycleError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Store(err) => Some(err),
            Self::Validation(_) | Self::ProofClosureRefusal(_) => None,
        }
    }
}

impl From<StoreError> for LifecycleError {
    fn from(err: StoreError) -> Self {
        Self::Store(err)
    }
}

/// Request to accept a candidate already materialized by the caller.
///
/// ADR 0026 §2 requires every candidate -> active mutation to compose through
/// the policy lattice. The composed [`PolicyDecision`] is supplied by the
/// caller (lifecycle layer assembles AXIOM admission, proof closure, conflict
/// resolution, and operator temporal-authority contributors) and forwarded to
/// the store boundary.
///
/// ADR 0036 also requires the caller to supply a typed
/// [`ProofClosureReport`] for the candidate's lineage. The lifecycle layer
/// refuses durable promotion when the report is not
/// [`ProofState::FullChainVerified`]; the gate fires under the stable
/// invariant [`LIFECYCLE_ACCEPT_PROOF_CLOSURE_INVARIANT`].
#[derive(Debug, Clone, Copy)]
pub struct AcceptCandidateRequest<'a> {
    /// Candidate row to insert and activate.
    pub candidate: &'a MemoryCandidate,
    /// Required audit row supplied by the caller.
    pub audit: &'a MemoryAcceptanceAudit,
    /// Composed acceptance policy decision (ADR 0026 §2). Must satisfy
    /// [`MemoryRepo::accept_candidate`]'s contributor envelope.
    pub policy: &'a PolicyDecision,
    /// Typed proof closure report (ADR 0036 §3). The lifecycle layer fails
    /// closed when this is not [`ProofState::FullChainVerified`]. The
    /// caller is responsible for computing the report from real lineage
    /// (e.g. `cortex_store::verify_memory_proof_closure`) — the lifecycle
    /// layer never invents a "trusted" report on the caller's behalf.
    pub proof_closure: &'a ProofClosureReport,
}

/// Accept a previously persisted candidate by id after validating stored
/// lineage and composing the ADR 0026 acceptance policy.
///
/// `proof_closure` MUST be [`ProofState::FullChainVerified`]; the lifecycle
/// layer refuses with [`LifecycleError::ProofClosureRefusal`] otherwise and
/// no store boundary call is made. The stable invariant
/// [`LIFECYCLE_ACCEPT_PROOF_CLOSURE_INVARIANT`] documents the refusal.
pub fn accept(
    memories: &MemoryRepo<'_>,
    candidate_id: &MemoryId,
    updated_at: DateTime<Utc>,
    audit: &MemoryAcceptanceAudit,
    policy: &PolicyDecision,
    proof_closure: &ProofClosureReport,
) -> LifecycleResult<MemoryId> {
    require_full_proof_closure(proof_closure)?;

    let candidate = memories.get_candidate_by_id(candidate_id)?.ok_or_else(|| {
        LifecycleError::Validation(format!("memory {candidate_id} is not a candidate"))
    })?;

    if candidate
        .source_episodes_json
        .as_array()
        .is_some_and(|items| !items.is_empty())
        || candidate
            .source_events_json
            .as_array()
            .is_some_and(|items| !items.is_empty())
    {
        let accepted = memories.accept_candidate(candidate_id, updated_at, audit, policy)?;
        return Ok(accepted.id);
    }

    Err(LifecycleError::Validation(
        "memory candidate requires non-empty episode or event lineage".into(),
    ))
}

/// Accept a candidate after validating lineage before any store write.
///
/// The durable candidate -> active transition and audit write are delegated to
/// `cortex-store` so the two effects occur in one transaction, and the
/// composed [`PolicyDecision`] is forwarded to the store boundary so the
/// ADR 0026 contributor envelope fails closed on `Reject` / `Quarantine`.
///
/// `request.proof_closure` MUST be [`ProofState::FullChainVerified`]; the
/// lifecycle layer refuses with [`LifecycleError::ProofClosureRefusal`]
/// otherwise and no insert or accept is attempted. The stable invariant
/// [`LIFECYCLE_ACCEPT_PROOF_CLOSURE_INVARIANT`] documents the refusal.
pub fn accept_candidate(
    memories: &MemoryRepo<'_>,
    request: AcceptCandidateRequest<'_>,
) -> LifecycleResult<MemoryId> {
    require_full_proof_closure(request.proof_closure)?;
    validate_candidate_lineage(request.candidate)?;

    memories.insert_candidate(request.candidate)?;
    memories.accept_candidate(
        &request.candidate.id,
        request.candidate.updated_at,
        request.audit,
        request.policy,
    )?;

    Ok(request.candidate.id)
}

/// Fail closed before any durable write if the proof closure is not
/// [`ProofState::FullChainVerified`]. The lifecycle layer is the
/// fail-closed line for ADR 0036 at the memory candidate -> active surface.
fn require_full_proof_closure(report: &ProofClosureReport) -> LifecycleResult<()> {
    if report.is_full_chain_verified() {
        Ok(())
    } else {
        Err(LifecycleError::ProofClosureRefusal(report.state()))
    }
}

/// Validate the minimum lineage invariant for a memory candidate.
///
/// At least one of `source_episodes_json` or `source_events_json` must be a
/// non-empty JSON array. Missing (`null`) or empty lineage fails closed.
pub fn validate_candidate_lineage(candidate: &MemoryCandidate) -> LifecycleResult<()> {
    if candidate
        .source_episodes_json
        .as_array()
        .is_some_and(|items| !items.is_empty())
        || candidate
            .source_events_json
            .as_array()
            .is_some_and(|items| !items.is_empty())
    {
        return Ok(());
    }

    Err(LifecycleError::Validation(
        "memory candidate requires non-empty episode or event lineage".into(),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use cortex_core::{
        AuditRecordId, FailingEdge, ProofClosureReport, ProofEdgeFailure, ProofEdgeKind,
    };
    use cortex_store::repo::memories::accept_candidate_policy_decision_test_allow;
    use cortex_store::{Pool, INITIAL_MIGRATION_SQL};
    use serde_json::json;

    fn full_proof_closure() -> ProofClosureReport {
        // Test fixture: a fully-verified report with no failing edges.
        // Production callers compute this via
        // `cortex_store::verify_memory_proof_closure`.
        ProofClosureReport::full_chain_verified(Vec::new())
    }

    fn partial_proof_closure() -> ProofClosureReport {
        ProofClosureReport::from_edges(
            Vec::new(),
            vec![FailingEdge::missing(
                ProofEdgeKind::LineageClosure,
                "memory:test",
                "test fixture: lineage axis observed but unresolved",
            )],
        )
    }

    fn broken_proof_closure() -> ProofClosureReport {
        ProofClosureReport::from_edges(
            Vec::new(),
            vec![FailingEdge::broken(
                ProofEdgeKind::HashChain,
                "event:a",
                "event:b",
                ProofEdgeFailure::Mismatch,
                "test fixture: hash chain mismatch",
            )],
        )
    }

    fn test_pool() -> Pool {
        let pool = Pool::open_in_memory().expect("open in-memory sqlite");
        pool.execute_batch(INITIAL_MIGRATION_SQL)
            .expect("run initial migration");
        pool
    }

    fn candidate(has_event_lineage: bool) -> MemoryCandidate {
        MemoryCandidate {
            id: "mem_01ARZ3NDEKTSV4RRFFQ69G5FAV".parse().unwrap(),
            memory_type: "semantic".into(),
            claim: "Cortex memories require lineage.".into(),
            source_episodes_json: Default::default(),
            source_events_json: if has_event_lineage {
                "[\"evt_01ARZ3NDEKTSV4RRFFQ69G5FAV\"]".parse().unwrap()
            } else {
                Default::default()
            },
            domains_json: Default::default(),
            salience_json: Default::default(),
            confidence: 0.7,
            authority: "candidate".into(),
            applies_when_json: Default::default(),
            does_not_apply_when_json: Default::default(),
            created_at: "1970-01-01T00:00:00Z".parse().unwrap(),
            updated_at: "1970-01-01T00:00:00Z".parse().unwrap(),
        }
    }

    #[test]
    fn lineage_validation_rejects_missing_or_empty_sources() {
        assert!(validate_candidate_lineage(&candidate(false)).is_err());
        assert!(validate_candidate_lineage(&candidate(true)).is_ok());
    }

    #[test]
    fn accept_candidate_rejects_empty_lineage_before_any_write() {
        let pool = test_pool();
        let memories = MemoryRepo::new(&pool);
        let policy = accept_candidate_policy_decision_test_allow();
        let proof_closure = full_proof_closure();
        let request = AcceptCandidateRequest {
            candidate: &candidate(false),
            audit: &acceptance_audit(),
            policy: &policy,
            proof_closure: &proof_closure,
        };

        assert!(accept_candidate(&memories, request).is_err());

        let count: i64 = pool
            .query_row("SELECT COUNT(*) FROM memories;", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0);
    }

    fn acceptance_audit() -> MemoryAcceptanceAudit {
        MemoryAcceptanceAudit {
            id: AuditRecordId::new(),
            actor_json: json!({"kind": "test"}),
            reason: "unit test accept".into(),
            source_refs_json: json!(["evt_01ARZ3NDEKTSV4RRFFQ69G5FAV"]),
            created_at: "1970-01-01T00:00:05Z".parse().unwrap(),
        }
    }

    #[test]
    fn accept_candidate_inserts_active_memory_and_optional_audit() {
        let pool = test_pool();
        let memories = MemoryRepo::new(&pool);
        let mut candidate = candidate(true);
        candidate.updated_at = "1970-01-01T00:00:05Z".parse().unwrap();
        let audit = acceptance_audit();
        let policy = accept_candidate_policy_decision_test_allow();
        let proof_closure = full_proof_closure();

        let accepted = accept_candidate(
            &memories,
            AcceptCandidateRequest {
                candidate: &candidate,
                audit: &audit,
                policy: &policy,
                proof_closure: &proof_closure,
            },
        )
        .expect("accept candidate with lineage");

        assert_eq!(accepted, candidate.id);
        let status: String = pool
            .query_row(
                "SELECT status FROM memories WHERE id = ?1;",
                [candidate.id.to_string()],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(status, "active");
        let audit_count: i64 = pool
            .query_row(
                "SELECT COUNT(*) FROM audit_records WHERE target_ref = ?1;",
                [candidate.id.to_string()],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(audit_count, 1);
    }

    #[test]
    fn id_only_accept_uses_stored_candidate_and_audit_transaction() {
        let pool = test_pool();
        let memories = MemoryRepo::new(&pool);
        let mut candidate = candidate(true);
        candidate.updated_at = "1970-01-01T00:00:03Z".parse().unwrap();
        memories
            .insert_candidate(&candidate)
            .expect("insert candidate");
        let audit = acceptance_audit();
        let proof_closure = full_proof_closure();

        let accepted = accept(
            &memories,
            &candidate.id,
            "1970-01-01T00:00:06Z".parse().unwrap(),
            &audit,
            &accept_candidate_policy_decision_test_allow(),
            &proof_closure,
        )
        .expect("accept stored candidate by id");

        assert_eq!(accepted, candidate.id);
        assert_eq!(
            memories
                .get_by_id(&candidate.id)
                .unwrap()
                .expect("accepted memory exists")
                .status,
            "active"
        );
    }

    // =========================================================================
    // Commit B — ADR 0036 library-level proof closure gate (lifecycle::accept)
    //
    // The lifecycle layer is the fail-closed line for ADR 0036 at the
    // candidate -> active surface. Any caller (CLI, future API, tests) that
    // routes through `accept` or `accept_candidate` MUST supply a
    // `ProofClosureReport`; the lifecycle layer refuses with the stable
    // invariant `LIFECYCLE_ACCEPT_PROOF_CLOSURE_INVARIANT` when the report
    // is not FullChainVerified, and no store boundary call is attempted.
    // =========================================================================

    #[test]
    fn accept_candidate_refuses_partial_proof_closure_before_any_write() {
        let pool = test_pool();
        let memories = MemoryRepo::new(&pool);
        let candidate = candidate(true);
        let policy = accept_candidate_policy_decision_test_allow();
        let proof_closure = partial_proof_closure();

        let err = accept_candidate(
            &memories,
            AcceptCandidateRequest {
                candidate: &candidate,
                audit: &acceptance_audit(),
                policy: &policy,
                proof_closure: &proof_closure,
            },
        )
        .expect_err("partial proof closure must refuse");

        match err {
            LifecycleError::ProofClosureRefusal(state) => {
                assert_eq!(state, ProofState::Partial);
                assert!(err
                    .to_string()
                    .contains(LIFECYCLE_ACCEPT_PROOF_CLOSURE_INVARIANT));
            }
            other => panic!("expected ProofClosureRefusal, got {other:?}"),
        }

        let count: i64 = pool
            .query_row("SELECT COUNT(*) FROM memories;", [], |row| row.get(0))
            .unwrap();
        assert_eq!(count, 0, "no row may be written on proof closure refusal");
    }

    #[test]
    fn accept_candidate_refuses_broken_proof_closure_before_any_write() {
        let pool = test_pool();
        let memories = MemoryRepo::new(&pool);
        let candidate = candidate(true);
        let policy = accept_candidate_policy_decision_test_allow();
        let proof_closure = broken_proof_closure();

        let err = accept_candidate(
            &memories,
            AcceptCandidateRequest {
                candidate: &candidate,
                audit: &acceptance_audit(),
                policy: &policy,
                proof_closure: &proof_closure,
            },
        )
        .expect_err("broken proof closure must refuse");

        match err {
            LifecycleError::ProofClosureRefusal(state) => {
                assert_eq!(state, ProofState::Broken);
            }
            other => panic!("expected ProofClosureRefusal, got {other:?}"),
        }
    }

    #[test]
    fn id_only_accept_refuses_partial_proof_closure_before_any_write() {
        let pool = test_pool();
        let memories = MemoryRepo::new(&pool);
        let candidate = candidate(true);
        memories
            .insert_candidate(&candidate)
            .expect("insert candidate");
        let audit = acceptance_audit();
        let proof_closure = partial_proof_closure();

        let err = accept(
            &memories,
            &candidate.id,
            "1970-01-01T00:00:06Z".parse().unwrap(),
            &audit,
            &accept_candidate_policy_decision_test_allow(),
            &proof_closure,
        )
        .expect_err("partial proof closure must refuse");

        match err {
            LifecycleError::ProofClosureRefusal(state) => {
                assert_eq!(state, ProofState::Partial);
            }
            other => panic!("expected ProofClosureRefusal, got {other:?}"),
        }
        assert_eq!(
            memories
                .get_by_id(&candidate.id)
                .unwrap()
                .expect("candidate still exists")
                .status,
            "candidate",
            "candidate must remain in candidate state after refusal"
        );
    }

    #[test]
    fn lifecycle_accept_proof_closure_invariant_key_is_stable() {
        assert_eq!(
            LIFECYCLE_ACCEPT_PROOF_CLOSURE_INVARIANT,
            "cortex_memory.lifecycle.accept.proof_closure"
        );
    }
}