interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / cortex-rs / src / promotion.rs

372 lines · 14709 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use serde::{Deserialize, Serialize};
17use std::sync::Arc;
18
19use crate::db::Database;
20use crate::models::{MemoryCandidate, PromoteCandidateInput, PromotionReceipt, VerificationTier};
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub enum PromotionDecision {
24 Promote,
25 Hold { reason: String },
26 Reject { reason: String },
27}
28
29pub fn enforce_promotion_policy(candidate: &MemoryCandidate) -> Result<(), String> {
30 match PromotionEngine::evaluate_candidate(candidate) {
31 PromotionDecision::Promote => Ok(()),
32 PromotionDecision::Hold { reason } | PromotionDecision::Reject { reason } => Err(reason),
33 }
34}
35
36pub struct PromotionEngine {
37 db: Arc<Database>,
38}
39
40impl PromotionEngine {
41 pub fn new(db: Arc<Database>) -> Self {
42 Self { db }
43 }
44
45 pub fn evaluate_candidate(candidate: &MemoryCandidate) -> PromotionDecision {
46 if candidate.state == "promoted" {
47 return PromotionDecision::Reject {
48 reason: "Candidate already promoted".to_string(),
49 };
50 }
51 if candidate.state == "rejected" || candidate.state == "retracted" {
52 return PromotionDecision::Reject {
53 reason: format!("Candidate is in terminal state: {}", candidate.state),
54 };
55 }
56
57 match candidate.verification_tier {
58 VerificationTier::T0Direct => {
59 // T0: Direct assertion (e.g. user preference) requires at least 1 valid evidence reference
60 if candidate.evidence_ids.is_empty() {
61 PromotionDecision::Hold {
62 reason: "T0 Direct requires at least one source evidence reference"
63 .to_string(),
64 }
65 } else if candidate.confidence < 0.80 {
66 PromotionDecision::Hold {
67 reason: format!(
68 "Confidence {} below T0 threshold 0.80",
69 candidate.confidence
70 ),
71 }
72 } else {
73 PromotionDecision::Promote
74 }
75 }
76 VerificationTier::T1Corroborated => {
77 // T1: Corroborated knowledge requires >= 2 independent evidence references
78 if candidate.evidence_ids.len() < 2 {
79 PromotionDecision::Hold {
80 reason: format!(
81 "T1 Corroborated requires at least 2 independent observations, found {}",
82 candidate.evidence_ids.len()
83 ),
84 }
85 } else if candidate.confidence < 0.85 {
86 PromotionDecision::Hold {
87 reason: format!(
88 "Confidence {} below T1 threshold 0.85",
89 candidate.confidence
90 ),
91 }
92 } else {
93 PromotionDecision::Promote
94 }
95 }
96 VerificationTier::T2Verified => {
97 // T2: Technical/empirical claim requires tool evidence or verifier receipt
98 if candidate.evidence_ids.is_empty() {
99 PromotionDecision::Hold {
100 reason: "T2 Verified requires tool evidence or benchmark proof".to_string(),
101 }
102 } else if candidate.confidence < 0.90 {
103 PromotionDecision::Hold {
104 reason: format!(
105 "Confidence {} below T2 threshold 0.90",
106 candidate.confidence
107 ),
108 }
109 } else {
110 PromotionDecision::Promote
111 }
112 }
113 VerificationTier::T3Controlled => {
114 // T3: Controlled/authority claims always require explicit administrative sign-off
115 PromotionDecision::Hold {
116 reason: "T3 Controlled knowledge requires explicit manual authorization"
117 .to_string(),
118 }
119 }
120 }
121 }
122
123 /// Automatically evaluate and promote eligible candidates for a space.
124 pub fn auto_promote_eligible(
125 &self,
126 space: Option<&str>,
127 ) -> Result<Vec<PromotionReceipt>, rusqlite::Error> {
128 let candidates = self.db.get_memory_candidates(space, Some("pending"), 50)?;
129 let mut receipts = Vec::new();
130
131 for cand in candidates {
132 match Self::evaluate_candidate(&cand) {
133 PromotionDecision::Promote => {
134 let input = PromoteCandidateInput {
135 candidate_id: cand.id.clone(),
136 policy_id: Some("auto-promotion-policy-v1".to_string()),
137 verifier_receipt: Some(format!(
138 "Auto-verified tier {:?}",
139 cand.verification_tier
140 )),
141 };
142 if let Ok(receipt) = self.db.promote_candidate(&input) {
143 receipts.push(receipt);
144 }
145 }
146 PromotionDecision::Hold { reason } => {
147 // Update candidate state to 'held' with reason
148 let _ = self.db.update_candidate_state(&cand.id, "held");
149 tracing::debug!("Holding candidate {}: {}", cand.id, reason);
150 }
151 PromotionDecision::Reject { reason } => {
152 let _ = self.db.update_candidate_state(&cand.id, "rejected");
153 tracing::debug!("Rejecting candidate {}: {}", cand.id, reason);
154 }
155 }
156 }
157
158 Ok(receipts)
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use super::*;
165 use crate::models::{CandidateWriteInput, CreateSessionInput};
166 use serde_json::json;
167
168 #[test]
169 fn test_promotion_policy_evaluation_tiers() {
170 // T0 without evidence -> Hold
171 let t0_no_ev = MemoryCandidate {
172 id: "c1".to_string(),
173 space_slug: "atlas-memory".to_string(),
174 session_id: "s1".to_string(),
175 branch_id: "main".to_string(),
176 memory_type: "workflow_preference".to_string(),
177 subject: "user".to_string(),
178 predicate: "preferred_language".to_string(),
179 object_value: json!("Rust"),
180 scope: "global".to_string(),
181 confidence: 0.95,
182 verification_tier: VerificationTier::T0Direct,
183 state: "pending".to_string(),
184 extractor_version: "0.2.0".to_string(),
185 created_at: "2026-09-21".to_string(),
186 evidence_ids: vec![],
187 };
188 assert!(matches!(
189 PromotionEngine::evaluate_candidate(&t0_no_ev),
190 PromotionDecision::Hold { .. }
191 ));
192
193 // T0 with evidence -> Promote
194 let mut t0_with_ev = t0_no_ev.clone();
195 t0_with_ev.evidence_ids.push("ev-1".to_string());
196 assert_eq!(
197 PromotionEngine::evaluate_candidate(&t0_with_ev),
198 PromotionDecision::Promote
199 );
200
201 // T1 with 1 evidence -> Hold
202 let mut t1 = t0_with_ev.clone();
203 t1.verification_tier = VerificationTier::T1Corroborated;
204 assert!(matches!(
205 PromotionEngine::evaluate_candidate(&t1),
206 PromotionDecision::Hold { .. }
207 ));
208
209 // T1 with 2 evidence -> Promote
210 t1.evidence_ids.push("ev-2".to_string());
211 assert_eq!(
212 PromotionEngine::evaluate_candidate(&t1),
213 PromotionDecision::Promote
214 );
215
216 // T3 -> Always Hold (manual authorization)
217 let mut t3 = t1.clone();
218 t3.verification_tier = VerificationTier::T3Controlled;
219 assert!(matches!(
220 PromotionEngine::evaluate_candidate(&t3),
221 PromotionDecision::Hold { .. }
222 ));
223 }
224
225 #[test]
226 fn test_atomic_promotion_and_temporal_supersession() {
227 let db = Arc::new(Database::open_in_memory().unwrap());
228 db.create_session(&CreateSessionInput {
229 id: Some("sess-promo".to_string()),
230 space: "atlas-memory".to_string(),
231 agent_id: Some("atlas".to_string()),
232 world_id: None,
233 parent_session_id: None,
234 fork_event_id: None,
235 retention_class: "standard".to_string(),
236 metadata: json!({}),
237 })
238 .unwrap();
239
240 db.batch_append_events(
241 "sess-promo",
242 "main",
243 &[
244 crate::models::SessionEventInput {
245 id: Some("ev-001".to_string()),
246 branch_id: Some("main".to_string()),
247 parent_event_id: None,
248 event_type: "user_message".to_string(),
249 role: Some("user".to_string()),
250 content: Some("I prefer Python for scripts.".to_string()),
251 payload: json!({}),
252 sensitivity: None,
253 },
254 crate::models::SessionEventInput {
255 id: Some("ev-002".to_string()),
256 branch_id: Some("main".to_string()),
257 parent_event_id: None,
258 event_type: "user_message".to_string(),
259 role: Some("user".to_string()),
260 content: Some("I prefer Rust for the runtime.".to_string()),
261 payload: json!({}),
262 sensitivity: None,
263 },
264 ],
265 )
266 .unwrap();
267
268 let bare = db
269 .insert_memory_candidate(&CandidateWriteInput {
270 id: Some("cand-bare".to_string()),
271 space: "atlas-memory".to_string(),
272 session_id: "sess-promo".to_string(),
273 branch_id: "main".to_string(),
274 memory_type: "workflow_preference".to_string(),
275 subject: "developer".to_string(),
276 predicate: "editor".to_string(),
277 object_value: json!("vim"),
278 scope: "global".to_string(),
279 confidence: 0.99,
280 verification_tier: Some(VerificationTier::T0Direct),
281 extractor_version: "0.2.0".to_string(),
282 evidence_ids: vec![],
283 })
284 .unwrap();
285 assert!(db
286 .promote_candidate(&PromoteCandidateInput {
287 candidate_id: bare.id,
288 policy_id: Some("p1".to_string()),
289 verifier_receipt: None,
290 })
291 .is_err());
292
293 // 1. Insert candidate C1: User prefers Python
294 let cand1 = db
295 .insert_memory_candidate(&CandidateWriteInput {
296 id: Some("cand-01".to_string()),
297 space: "atlas-memory".to_string(),
298 session_id: "sess-promo".to_string(),
299 branch_id: "main".to_string(),
300 memory_type: "workflow_preference".to_string(),
301 subject: "developer".to_string(),
302 predicate: "preferred_language".to_string(),
303 object_value: json!("Python"),
304 scope: "global".to_string(),
305 confidence: 0.95,
306 verification_tier: Some(VerificationTier::T0Direct),
307 extractor_version: "0.2.0".to_string(),
308 evidence_ids: vec!["ev-001".to_string()],
309 })
310 .unwrap();
311
312 // Promote C1
313 let receipt1 = db
314 .promote_candidate(&PromoteCandidateInput {
315 candidate_id: cand1.id.clone(),
316 policy_id: Some("p1".to_string()),
317 verifier_receipt: None,
318 })
319 .unwrap();
320 assert_eq!(receipt1.candidate_id, "cand-01");
321
322 // Verify claim is active
323 let claims_after_1 = db
324 .traverse_claims("developer", Some("atlas-memory"))
325 .unwrap();
326 assert_eq!(claims_after_1.len(), 1);
327 assert_eq!(claims_after_1[0].literal_value, Some(json!("Python")));
328 assert_eq!(
329 claims_after_1[0].verification_tier,
330 VerificationTier::T0Direct
331 );
332 assert_eq!(claims_after_1[0].evidence_count, 1);
333 assert_eq!(claims_after_1[0].status, crate::models::ClaimStatus::Active);
334
335 // 2. Insert candidate C2: User now prefers Rust (contradiction & temporal update)
336 let cand2 = db
337 .insert_memory_candidate(&CandidateWriteInput {
338 id: Some("cand-02".to_string()),
339 space: "atlas-memory".to_string(),
340 session_id: "sess-promo".to_string(),
341 branch_id: "main".to_string(),
342 memory_type: "workflow_preference".to_string(),
343 subject: "developer".to_string(),
344 predicate: "preferred_language".to_string(),
345 object_value: json!("Rust"),
346 scope: "global".to_string(),
347 confidence: 0.99,
348 verification_tier: Some(VerificationTier::T0Direct),
349 extractor_version: "0.2.0".to_string(),
350 evidence_ids: vec!["ev-002".to_string()],
351 })
352 .unwrap();
353
354 // Promote C2
355 let receipt2 = db
356 .promote_candidate(&PromoteCandidateInput {
357 candidate_id: cand2.id.clone(),
358 policy_id: Some("p1".to_string()),
359 verifier_receipt: None,
360 })
361 .unwrap();
362 assert_eq!(receipt2.candidate_id, "cand-02");
363
364 // Verify temporal supersession: only 1 active claim remains and it's "Rust"!
365 let claims_after_2 = db
366 .traverse_claims("developer", Some("atlas-memory"))
367 .unwrap();
368 assert_eq!(claims_after_2.len(), 1);
369 assert_eq!(claims_after_2[0].literal_value, Some(json!("Rust")));
370 assert_eq!(claims_after_2[0].evidence_count, 1);
371 }
372}