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

261 lines · 8925 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 #380 (lane L6, acceptance step E2 and CTRL-E2): the
17//! operator's objective is recorded, with its identity, before any work.
18//!
19//! `aien-cli objective record --text TEXT [--effect-class CLASS]` writes
20//! `objectives/<objective_id>.json` under `AIEN_PROVENANCE_DIR` (the same
21//! directory the effect receipts use). The operator declares the effect class;
22//! nothing here classifies natural language. A declared
23//! `EXTERNAL_IRREVERSIBLE` (the class name in `aien-mcp` `ToolEffects`) is
24//! refused before anything is written. `compose propose --objective-id` ties
25//! a proposal to a record by the sha256 of the goal text.
26use serde_json::{json, Value};
27use sha2::{Digest, Sha256};
28use std::path::PathBuf;
29
30pub const MAX_TEXT_BYTES: usize = 2000;
31pub const FORBIDDEN_CLASS: &str = "EXTERNAL_IRREVERSIBLE";
32pub const DEFAULT_CLASS: &str = "WORKSPACE_WRITE";
33
34/// A named refusal: `OBJECTIVE_REFUSED <name>: <detail>`.
35#[derive(Debug)]
36pub struct Refusal {
37 pub name: &'static str,
38 pub detail: String,
39}
40
41impl Refusal {
42 fn new(name: &'static str, detail: impl Into<String>) -> Self {
43 Refusal {
44 name,
45 detail: detail.into(),
46 }
47 }
48 pub fn line(&self) -> String {
49 format!("OBJECTIVE_REFUSED {}: {}", self.name, self.detail)
50 }
51}
52
53fn sha256_hex(b: &[u8]) -> String {
54 hex::encode(Sha256::digest(b))
55}
56
57pub fn objective_id(text: &str) -> String {
58 aien_runtime::objective::objective_id(text)
59}
60
61/// Tests that set or read `AIEN_PROVENANCE_DIR` hold this, so one test's
62/// `set_var` cannot land between another test's reads (the test harness runs
63/// them on parallel threads of one process).
64#[cfg(test)]
65pub(crate) static PROVENANCE_ENV: std::sync::Mutex<()> = std::sync::Mutex::new(());
66
67/// The same directory the daemon re-reads (sovereign-core #408).
68fn dir() -> PathBuf {
69 aien_runtime::objective::dir()
70}
71
72fn valid_id(id: &str) -> bool {
73 id.len() == 64
74 && id
75 .bytes()
76 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
77}
78
79/// Validate and write the record. Refuses before touching the disk.
80pub fn record(text: &str, class: Option<&str>) -> Result<Value, Refusal> {
81 let class = class.unwrap_or(DEFAULT_CLASS).trim().to_ascii_uppercase();
82 if class == FORBIDDEN_CLASS {
83 return Err(Refusal::new(
84 "ForbiddenEffectClass",
85 format!("the declared effect class {FORBIDDEN_CLASS} is never executed"),
86 ));
87 }
88 if text.trim().is_empty() {
89 return Err(Refusal::new("Empty", "the objective text is empty"));
90 }
91 if text.len() > MAX_TEXT_BYTES {
92 return Err(Refusal::new(
93 "TooLong",
94 format!("{} bytes, at most {MAX_TEXT_BYTES}", text.len()),
95 ));
96 }
97 let id = objective_id(text);
98 let text_sha = sha256_hex(text.as_bytes());
99 let utc = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
100 let rec = json!({
101 "version": 1,
102 "objective_id": id,
103 "objective_text": text,
104 "objective_text_sha256": text_sha,
105 "effect_class": class,
106 "recorded_before_work": true,
107 "operator_surface": "aien-cli",
108 "utc": utc,
109 });
110 let d = dir();
111 std::fs::create_dir_all(&d)
112 .map_err(|e| Refusal::new("RecordUnwritable", format!("{}: {e}", d.display())))?;
113 let path = d.join(format!("{id}.json"));
114 let bytes = serde_json::to_vec_pretty(&rec).expect("record is JSON");
115 std::fs::write(&path, bytes)
116 .map_err(|e| Refusal::new("RecordUnwritable", format!("{}: {e}", path.display())))?;
117 Ok(json!({
118 "ok": true,
119 "objective_id": id,
120 "path": path.display().to_string(),
121 "objective_text_sha256": text_sha,
122 "recorded_before_work": true,
123 "operator_surface": "aien-cli",
124 "utc": utc,
125 }))
126}
127
128pub fn load(id: &str) -> Result<Value, Refusal> {
129 if !valid_id(id) {
130 return Err(Refusal::new(
131 "ObjectiveMissing",
132 format!("{id:?} is not a 64 character lowercase hex objective id"),
133 ));
134 }
135 let path = dir().join(format!("{id}.json"));
136 let bytes = std::fs::read(&path).map_err(|_| {
137 Refusal::new(
138 "ObjectiveMissing",
139 format!("no objective record {}", path.display()),
140 )
141 })?;
142 serde_json::from_slice(&bytes)
143 .map_err(|e| Refusal::new("ObjectiveMissing", format!("{}: {e}", path.display())))
144}
145
146/// `compose propose --objective-id`: the record must exist and the goal must
147/// be the recorded text. Returns the id to carry in the report.
148pub fn check_binding(id: &str, goal: &str) -> Result<String, Refusal> {
149 let rec = load(id)?;
150 let want = rec["objective_text_sha256"].as_str().unwrap_or("");
151 let got = sha256_hex(goal.as_bytes());
152 if want != got {
153 return Err(Refusal::new(
154 "ObjectiveMismatch",
155 format!("sha256 of --goal is {got}, the record {id} holds {want}"),
156 ));
157 }
158 Ok(id.to_string())
159}
160
161/// Add the objective id to a propose report.
162pub fn attach(mut report: Value, id: &str) -> Value {
163 report["objective_id"] = json!(id);
164 report
165}
166
167fn refuse(r: Refusal) -> ! {
168 eprintln!("{}", r.line());
169 let v = json!({"ok": false, "refusal": r.name, "error": r.line()});
170 println!("{v}");
171 std::process::exit(1);
172}
173
174pub fn handle_objective_command(args: &[String]) {
175 let usage = || -> ! {
176 println!(
177 "{}",
178 json!({"ok": false, "error": "usage: aien-cli objective record --text TEXT [--effect-class CLASS] | objective show ID"})
179 );
180 std::process::exit(1);
181 };
182 match args.first().map(String::as_str) {
183 Some("record") => {
184 let (mut text, mut class) = (None, None);
185 let mut i = 1;
186 while i < args.len() {
187 let Some(v) = args.get(i + 1) else { usage() };
188 match args[i].as_str() {
189 "--text" => text = Some(v.clone()),
190 "--effect-class" => class = Some(v.clone()),
191 _ => usage(),
192 }
193 i += 2;
194 }
195 let Some(text) = text else { usage() };
196 match record(&text, class.as_deref()) {
197 Ok(v) => println!("{v}"),
198 Err(r) => refuse(r),
199 }
200 }
201 Some("show") if args.len() == 2 => match load(&args[1]) {
202 Ok(mut v) => {
203 v["ok"] = json!(true);
204 println!("{v}");
205 }
206 Err(r) => refuse(r),
207 },
208 _ => usage(),
209 }
210}
211
212pub fn refuse_propose(r: Refusal) -> String {
213 eprintln!("{}", r.line());
214 r.line()
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220
221 #[test]
222 fn matching_objective_id_is_accepted_and_carried() {
223 let _env = super::PROVENANCE_ENV
224 .lock()
225 .unwrap_or_else(|e| e.into_inner());
226 let t = tempfile::tempdir().unwrap();
227 std::env::set_var("AIEN_PROVENANCE_DIR", t.path());
228 let r = record("do the thing", None).unwrap();
229 let id = r["objective_id"].as_str().unwrap();
230 assert_eq!(check_binding(id, "do the thing").unwrap(), id);
231 assert_eq!(
232 check_binding(id, "other").unwrap_err().name,
233 "ObjectiveMismatch"
234 );
235 let rep = attach(json!({"step": "S3"}), id);
236 assert_eq!(rep["objective_id"], id);
237 std::env::remove_var("AIEN_PROVENANCE_DIR");
238 }
239}
240
241#[cfg(test)]
242mod default_dir_tests {
243 /// sc#414 defect 3: the CLI and the daemon must derive the same directory,
244 /// or approval refuses ObjectiveMissing. Both call the one runtime function.
245 #[test]
246 fn cli_and_daemon_agree_and_default_is_not_tmp() {
247 let _env = super::PROVENANCE_ENV
248 .lock()
249 .unwrap_or_else(|e| e.into_inner());
250 let with = |k: &str| {
251 if k == "HOME" {
252 Some("/home/op".to_string())
253 } else {
254 None
255 }
256 };
257 let root = aien_runtime::objective::provenance_root_with(with);
258 assert!(!root.starts_with("/tmp"), "{}", root.display());
259 assert_eq!(super::dir(), aien_runtime::objective::dir());
260 }
261}