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 / aien-runtime / src / objective.rs

209 lines · 7808 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
16//! sovereign-core #408: the operator's objective record, as the daemon reads it.
17//!
18//! `aien-cli objective record` (sc#388) writes `objectives/<objective_id>.json`
19//! under the provenance root (`AIEN_PROVENANCE_DIR`, default durable per-user state); the id is sha256 of [`DOMAIN_TAG`], LF, the
20//! text. The daemon never writes the record. It re-reads it when a grant is
21//! bound to it (`ComposeAuthorize` with an objective id), before every intent
22//! on such a grant, and at every reconcile of such an intent, so a record that
23//! is gone or no longer says what was approved is named, never passed over.
24use sha2::{Digest, Sha256};
25use std::path::PathBuf;
26
27pub const DOMAIN_TAG: &str = "AIEN_E2E_OBJECTIVE_V1";
28/// The record is missing, unreadable, not JSON, or the id is not 64 lowercase hex.
29pub const MISSING: &str = "ObjectiveMissing";
30/// The record does not say what the grant was approved for.
31pub const MISMATCH: &str = "ObjectiveMismatch";
32
33fn sha256_hex(b: &[u8]) -> String {
34 aien_omega_compose::hex(&Sha256::digest(b))
35}
36
37/// sha256 of `DOMAIN_TAG`, LF, `text` (lowercase hex).
38pub fn objective_id(text: &str) -> String {
39 sha256_hex(format!("{DOMAIN_TAG}\n{text}").as_bytes())
40}
41
42/// The provenance root, resolved from a variable lookup (sc#414 defect 3):
43/// `$AIEN_PROVENANCE_DIR`, else `$AIEN_RUNTIME_STATE_DIR/provenance`, else
44/// `$XDG_STATE_HOME/aien-runtime/provenance`, else
45/// `$HOME/.local/state/aien-runtime/provenance`, the same order as the compose
46/// home (`compose::compose_dir_from_env`). Never /tmp: a record that vanishes at
47/// reboot is not a durable record. With none of those set (no HOME at all), the
48/// absolute `/var/lib/aien-runtime/provenance`, so daemon and CLI still agree.
49pub fn provenance_root_with(get: impl Fn(&str) -> Option<String>) -> PathBuf {
50 let get = |k: &str| get(k).filter(|v| !v.trim().is_empty());
51 if let Some(d) = get("AIEN_PROVENANCE_DIR") {
52 return PathBuf::from(d.trim());
53 }
54 if let Some(d) = get("AIEN_RUNTIME_STATE_DIR") {
55 return PathBuf::from(d.trim()).join("provenance");
56 }
57 if let Some(d) = get("XDG_STATE_HOME") {
58 return PathBuf::from(d.trim()).join("aien-runtime/provenance");
59 }
60 if let Some(h) = get("HOME") {
61 return PathBuf::from(h.trim()).join(".local/state/aien-runtime/provenance");
62 }
63 PathBuf::from("/var/lib/aien-runtime/provenance")
64}
65
66/// [`provenance_root_with`] over the process environment. The daemon, the CLI
67/// and the effect receipts all call this one function.
68pub fn provenance_root() -> PathBuf {
69 provenance_root_with(|k| std::env::var(k).ok())
70}
71
72/// `<provenance root>/objectives`, resolved exactly as the CLI resolves it.
73pub fn dir() -> PathBuf {
74 provenance_root().join("objectives")
75}
76
77pub fn valid_id(id: &str) -> bool {
78 id.len() == 64
79 && id
80 .bytes()
81 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
82}
83
84/// What one read of a record established.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct Seen {
87 pub objective_id: String,
88 /// sha256 of the recorded text.
89 pub text_sha256: String,
90 /// sha256 of the record file's bytes.
91 pub record_sha256: String,
92}
93
94/// A refusal name ([`MISSING`] or [`MISMATCH`]) and its detail.
95pub type Refused = (&'static str, String);
96
97/// Read the record of `id` now. It must exist, name `id`, and its text must
98/// hash to both its `objective_text_sha256` and (with the tag) to `id`.
99pub fn read(id: &str) -> Result<Seen, Refused> {
100 if !valid_id(id) {
101 return Err((
102 MISSING,
103 format!("{id:?} is not a 64 character lowercase hex objective id"),
104 ));
105 }
106 let path = dir().join(format!("{id}.json"));
107 let bytes = std::fs::read(&path)
108 .map_err(|e| (MISSING, format!("objective record {}: {e}", path.display())))?;
109 let v: serde_json::Value = serde_json::from_slice(&bytes)
110 .map_err(|e| (MISSING, format!("objective record {}: {e}", path.display())))?;
111 let text = v["objective_text"].as_str().unwrap_or_default();
112 let text_sha = sha256_hex(text.as_bytes());
113 if v["objective_id"].as_str() != Some(id)
114 || v["objective_text_sha256"].as_str() != Some(text_sha.as_str())
115 || objective_id(text) != id
116 {
117 return Err((
118 MISMATCH,
119 format!(
120 "objective record {} does not hold the text of objective {id}",
121 path.display()
122 ),
123 ));
124 }
125 Ok(Seen {
126 objective_id: id.to_string(),
127 text_sha256: text_sha,
128 record_sha256: sha256_hex(&bytes),
129 })
130}
131
132/// [`read`], and the recorded text must be the one approved (`text_sha256`).
133pub fn check(id: &str, text_sha256: &str) -> Result<Seen, Refused> {
134 let s = read(id)?;
135 if s.text_sha256 != text_sha256 {
136 return Err((
137 MISMATCH,
138 format!(
139 "objective record {id} holds text sha256 {}, approved was {text_sha256}",
140 s.text_sha256
141 ),
142 ));
143 }
144 Ok(s)
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
152 let m: std::collections::HashMap<String, String> = pairs
153 .iter()
154 .map(|(k, v)| (k.to_string(), v.to_string()))
155 .collect();
156 move |k| m.get(k).cloned()
157 }
158
159 #[test]
160 fn provenance_default_is_durable_and_never_tmp() {
161 let home = provenance_root_with(env(&[("HOME", "/home/u")]));
162 assert_eq!(
163 home,
164 PathBuf::from("/home/u/.local/state/aien-runtime/provenance")
165 );
166 for p in [
167 home,
168 provenance_root_with(env(&[])),
169 provenance_root_with(env(&[("XDG_STATE_HOME", "/x")])),
170 provenance_root_with(env(&[("AIEN_RUNTIME_STATE_DIR", "/s")])),
171 ] {
172 assert!(!p.starts_with("/tmp"), "{}", p.display());
173 }
174 }
175
176 #[test]
177 fn provenance_follows_the_compose_home_order_and_override_wins() {
178 let all = [
179 ("AIEN_PROVENANCE_DIR", "/p"),
180 ("AIEN_RUNTIME_STATE_DIR", "/s"),
181 ("XDG_STATE_HOME", "/x"),
182 ("HOME", "/h"),
183 ];
184 assert_eq!(provenance_root_with(env(&all)), PathBuf::from("/p"));
185 assert_eq!(
186 provenance_root_with(env(&all[1..])),
187 PathBuf::from("/s/provenance")
188 );
189 assert_eq!(
190 provenance_root_with(env(&all[2..])),
191 PathBuf::from("/x/aien-runtime/provenance")
192 );
193 // An empty override is not an override.
194 assert_eq!(
195 provenance_root_with(env(&[("AIEN_PROVENANCE_DIR", " "), ("HOME", "/h")])),
196 PathBuf::from("/h/.local/state/aien-runtime/provenance")
197 );
198 }
199
200 #[test]
201 fn id_is_the_cli_formula() {
202 // sha256("AIEN_E2E_OBJECTIVE_V1\nx"), the sc#388 definition.
203 let want = sha256_hex(b"AIEN_E2E_OBJECTIVE_V1\nx");
204 assert_eq!(objective_id("x"), want);
205 assert!(valid_id(&want));
206 assert!(!valid_id("ABC"));
207 assert!(!valid_id(&want.to_uppercase()));
208 }
209}