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
aien-sovereign-core-mv / crates / aien-cli / src / compose.rs
| 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 | //! `aien compose ...`: the NEXT-PHASE-1 bounded task, one operator step per |
| 17 | //! subcommand, against the running daemon's composition home (omega |
| 18 | //! COMPOSITION-2, `RunComposeTask` / `ComposeNote` / `ComposeRecall` / |
| 19 | //! `RecoverComposeHome`). |
| 20 | //! |
| 21 | //! The daemon owns the Cortex journal; this side owns the effects. Every |
| 22 | //! workspace path goes through `SafetyEngine::validate_path` with the |
| 23 | //! authorized workspace as the only root, and every effect (inspect, |
| 24 | //! authorize, write_file) leaves a sovereign-core effect receipt |
| 25 | //! (`record_effect_receipt`) that the Cortex record then cites by sha256. |
| 26 | //! |
| 27 | //! Each subcommand prints one JSON object on stdout (`"ok": true|false`) and |
| 28 | //! exits 1 on failure. |
| 29 | //! |
| 30 | //! remember --text T [--context C] S1 constraint record + ALLEN memory item (refused when ALLEN is not engaged) |
| 31 | //! inspect --workspace W S2 read-only listing + receipt |
| 32 | //! propose --goal G --workspace W [--context personal|work|project:NAME] S3 one RunComposeTask |
| 33 | //! authorize --report S3.json --workspace W --approver NAME [--constraint ID] |
| 34 | //! S4 the one approval |
| 35 | //! [--desk 1 | --desk-key PATH | --desk-mac HEX --desk-nonce N] |
| 36 | //! optional approval-desk MAC (#297); the daemon |
| 37 | //! checks it only with AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK=1 |
| 38 | //! ON mode adds assurance only if the authorizing caller |
| 39 | //! cannot read the desk key file; a process as the same |
| 40 | //! OS user that can read it passes trivially (as in #249) |
| 41 | //! execute --report S3.json --workspace W --authorization ID |
| 42 | //! S5 the write, confined |
| 43 | //! explain --report S3.json --cite ID,.. --receipts P,.. |
| 44 | //! S6 evidence-citing explanation |
| 45 | //! recall [--ids ID,..] [--prefix N] [--context C] S8 constraints + effects + ALLEN memory state |
| 46 | //! shutdown S7 stop the daemon (control Shutdown) |
| 47 | //! recover repair a refused home |
| 48 | //! effects the effect ledger (NEXT-PHASE-2) |
| 49 | //! reconcile [--intent ID --declare done|not_done --approver NAME] |
| 50 | //! settle unsettled effects |
| 51 | //! stop --approver NAME durable operator stop |
| 52 | //! resume --approver NAME end the stop (old grants stay stale) |
| 53 | //! revoke --authorization ID --approver NAME revoke an unspent grant |
| 54 | //! desk-key [--create 1] the approval desk key (#249): |
| 55 | //! prints its id and path, never the key; |
| 56 | //! --create 1 makes one if none exists |
| 57 | //! |
| 58 | //! S5 `execute` brackets the write with a durable intent and an ack (see |
| 59 | //! `aien_runtime::effects`); it prints `"state"` and exits 3 when the effect |
| 60 | //! is UNRESOLVED. |
| 61 | use crate::safety::SafetyEngine; |
| 62 | use crate::tools::record_effect_receipt; |
| 63 | use aien_runtime::client::AienRuntimeClient; |
| 64 | use aien_runtime::compose::parse_file_proposal; |
| 65 | use aien_runtime::control::{ |
| 66 | ComposeRecallReport, ComposeTaskReport, ControlCommand, ControlResponse, ReconcileDeclare, |
| 67 | }; |
| 68 | use aien_runtime::effects; |
| 69 | use serde_json::{json, Value}; |
| 70 | use sha2::{Digest, Sha256}; |
| 71 | use std::collections::HashMap; |
| 72 | use std::path::{Path, PathBuf}; |
| 73 | |
| 74 | const INSPECT_MAX_ENTRIES: usize = 4096; |
| 75 | |
| 76 | fn sha256_hex(b: &[u8]) -> String { |
| 77 | hex::encode(Sha256::digest(b)) |
| 78 | } |
| 79 | |
| 80 | fn flags(args: &[String]) -> Result<HashMap<String, String>, String> { |
| 81 | let mut m = HashMap::new(); |
| 82 | let mut i = 0; |
| 83 | while i < args.len() { |
| 84 | let k = args[i] |
| 85 | .strip_prefix("--") |
| 86 | .ok_or_else(|| format!("expected --flag, got {:?}", args[i]))?; |
| 87 | let v = args |
| 88 | .get(i + 1) |
| 89 | .ok_or_else(|| format!("--{k} needs a value"))?; |
| 90 | m.insert(k.to_string(), v.clone()); |
| 91 | i += 2; |
| 92 | } |
| 93 | Ok(m) |
| 94 | } |
| 95 | |
| 96 | fn need<'a>(m: &'a HashMap<String, String>, k: &str) -> Result<&'a str, String> { |
| 97 | m.get(k) |
| 98 | .map(|s| s.as_str()) |
| 99 | .filter(|s| !s.trim().is_empty()) |
| 100 | .ok_or_else(|| format!("--{k} is required")) |
| 101 | } |
| 102 | |
| 103 | fn ids(s: &str) -> Result<Vec<u64>, String> { |
| 104 | s.split(',') |
| 105 | .filter(|x| !x.trim().is_empty()) |
| 106 | .map(|x| { |
| 107 | x.trim() |
| 108 | .parse::<u64>() |
| 109 | .map_err(|e| format!("bad id {x:?}: {e}")) |
| 110 | }) |
| 111 | .collect() |
| 112 | } |
| 113 | |
| 114 | async fn send(cmd: ControlCommand) -> Result<ControlResponse, String> { |
| 115 | match AienRuntimeClient::default_client() |
| 116 | .send_command(cmd) |
| 117 | .await? |
| 118 | { |
| 119 | ControlResponse::Error(e) => Err(e), |
| 120 | r => Ok(r), |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /// The authorized workspace as the only root the safety engine accepts. |
| 125 | fn confine(workspace: &str) -> Result<(SafetyEngine, PathBuf), String> { |
| 126 | let mut engine = SafetyEngine::new(); |
| 127 | engine.set_workspaces(vec![PathBuf::from(workspace)]); |
| 128 | let ws = engine |
| 129 | .validate_path(workspace) |
| 130 | .map_err(|e| format!("CONFINEMENT DENIAL: {e}"))?; |
| 131 | if !ws.is_dir() { |
| 132 | return Err(format!("workspace {} is not a directory", ws.display())); |
| 133 | } |
| 134 | Ok((engine, ws)) |
| 135 | } |
| 136 | |
| 137 | /// One effect receipt, read back: (path, sha256 of the file, its JSON). |
| 138 | fn receipt(tool: &str, args: &Value, result: &Value, success: bool) -> Result<Value, String> { |
| 139 | let path = record_effect_receipt(tool, args, result, success) |
| 140 | .ok_or_else(|| format!("effect receipt for {tool} could not be written"))?; |
| 141 | let bytes = |
| 142 | std::fs::read(&path).map_err(|e| format!("read receipt {}: {e}", path.display()))?; |
| 143 | let body: Value = |
| 144 | serde_json::from_slice(&bytes).map_err(|e| format!("receipt {}: {e}", path.display()))?; |
| 145 | Ok(json!({ |
| 146 | "path": path.display().to_string(), |
| 147 | "sha256": sha256_hex(&bytes), |
| 148 | "tool": tool, |
| 149 | "success": success, |
| 150 | "arguments_digest": body["arguments_digest"], |
| 151 | "result_digest": body["result_digest"], |
| 152 | })) |
| 153 | } |
| 154 | |
| 155 | async fn note(kind: &str, text: &str, links: Vec<u64>) -> Result<Value, String> { |
| 156 | match send(ControlCommand::ComposeNote { |
| 157 | kind: kind.into(), |
| 158 | text: text.into(), |
| 159 | links, |
| 160 | }) |
| 161 | .await? |
| 162 | { |
| 163 | ControlResponse::ComposeNoted(n) => serde_json::to_value(n).map_err(|e| e.to_string()), |
| 164 | other => Err(format!("unexpected response {other:?}")), |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | /// Put one item into ALLEN scoped memory (the existing aien-allen-memory path). A refusal |
| 169 | /// (not engaged, foreign or damaged store) is returned as `Err` with its code and plain text. |
| 170 | async fn memory_put(context: &str, text: &str) -> Result<Value, String> { |
| 171 | match send(ControlCommand::AllenMemoryPut { |
| 172 | context: context.into(), |
| 173 | kind: "fact".into(), |
| 174 | text: text.into(), |
| 175 | }) |
| 176 | .await? |
| 177 | { |
| 178 | ControlResponse::AllenMemoryResult(r) => Ok(r.result), |
| 179 | ControlResponse::AllenRefused(e) => Err(format!("{} ({})", e.message, e.code)), |
| 180 | other => Err(format!("unexpected response {other:?}")), |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | /// ALLEN scoped memory of one context, as `recall` reports it: `not_engaged` (with the |
| 185 | /// plain-language reason) rather than an empty success when there is no identity. |
| 186 | async fn memory_view(context: &str) -> Result<Value, String> { |
| 187 | match send(ControlCommand::AllenMemoryRecall { |
| 188 | context: context.into(), |
| 189 | query: None, |
| 190 | }) |
| 191 | .await? |
| 192 | { |
| 193 | ControlResponse::AllenMemoryResult(r) => Ok(json!({ |
| 194 | "state": "included", "context": context, |
| 195 | "items": r.result["items"], "omitted": r.result["omitted"], |
| 196 | "unresolved": r.result["unresolved"], |
| 197 | })), |
| 198 | ControlResponse::AllenRefused(e) => Ok(json!({ |
| 199 | "state": e.code, "context": context, "items": [], "reason": e.message, |
| 200 | })), |
| 201 | other => Err(format!("unexpected response {other:?}")), |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | async fn recall(ids: Vec<u64>, prefix: Option<u64>) -> Result<ComposeRecallReport, String> { |
| 206 | match send(ControlCommand::ComposeRecall { ids, prefix }).await? { |
| 207 | ControlResponse::ComposeRecalled(r) => Ok(*r), |
| 208 | other => Err(format!("unexpected response {other:?}")), |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | fn read_report(path: &str) -> Result<ComposeTaskReport, String> { |
| 213 | let bytes = std::fs::read(path).map_err(|e| format!("read {path}: {e}"))?; |
| 214 | let v: Value = serde_json::from_slice(&bytes).map_err(|e| format!("{path}: {e}"))?; |
| 215 | // `aien compose propose` prints {"ok":true,"report":{...}}; accept both. |
| 216 | let r = v.get("report").cloned().unwrap_or(v); |
| 217 | serde_json::from_value(r).map_err(|e| format!("{path}: not a compose report: {e}")) |
| 218 | } |
| 219 | |
| 220 | /// sovereign-core #408: the `objective_id` that `compose propose |
| 221 | /// --objective-id` put beside the report (absent: the approval names none). |
| 222 | fn report_objective_id(path: &str) -> Result<Option<String>, String> { |
| 223 | let bytes = std::fs::read(path).map_err(|e| format!("read {path}: {e}"))?; |
| 224 | let v: Value = serde_json::from_slice(&bytes).map_err(|e| format!("{path}: {e}"))?; |
| 225 | match v.get("objective_id") { |
| 226 | None | Some(Value::Null) => Ok(None), |
| 227 | Some(Value::String(s)) => Ok(Some(s.clone())), |
| 228 | Some(_) => Err(format!("{path}: objective_id is not a string")), |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | /// The committed proposal of an S3 report, re-parsed and re-hashed here. |
| 233 | fn committed_proposal(r: &ComposeTaskReport) -> Result<(String, String, String), String> { |
| 234 | if !r.committed { |
| 235 | return Err("the composition did not commit a proposal".into()); |
| 236 | } |
| 237 | let text = r.proposal.as_deref().ok_or("report holds no proposal")?; |
| 238 | let sha = sha256_hex(text.as_bytes()); |
| 239 | if r.proposal_sha256.as_deref() != Some(sha.as_str()) { |
| 240 | return Err("proposal text does not match its recorded sha256".into()); |
| 241 | } |
| 242 | let p = parse_file_proposal(text).ok_or("proposal is not one file change")?; |
| 243 | let csha = sha256_hex(p.content.as_bytes()); |
| 244 | if r.proposal_content_sha256.as_deref() != Some(csha.as_str()) |
| 245 | || r.proposal_path.as_deref() != Some(p.path.as_str()) |
| 246 | { |
| 247 | return Err("parsed proposal differs from the report".into()); |
| 248 | } |
| 249 | Ok((p.path, p.content, sha)) |
| 250 | } |
| 251 | |
| 252 | fn tree(ws: &Path) -> Result<(Vec<Value>, String), String> { |
| 253 | let mut out = Vec::new(); |
| 254 | let mut stack = vec![ws.to_path_buf()]; |
| 255 | while let Some(d) = stack.pop() { |
| 256 | let rd = std::fs::read_dir(&d).map_err(|e| format!("read {}: {e}", d.display()))?; |
| 257 | for e in rd { |
| 258 | let e = e.map_err(|e| e.to_string())?; |
| 259 | let p = e.path(); |
| 260 | let ft = e.file_type().map_err(|e| e.to_string())?; |
| 261 | let rel = p |
| 262 | .strip_prefix(ws) |
| 263 | .unwrap_or(&p) |
| 264 | .to_string_lossy() |
| 265 | .into_owned(); |
| 266 | if ft.is_dir() { |
| 267 | stack.push(p); |
| 268 | out.push(json!({"path": rel + "/", "kind": "dir"})); |
| 269 | } else if ft.is_file() { |
| 270 | let b = std::fs::read(&p).map_err(|e| format!("read {}: {e}", p.display()))?; |
| 271 | out.push(json!({"path": rel, "kind": "file", "bytes": b.len(), "sha256": sha256_hex(&b)})); |
| 272 | } else { |
| 273 | out.push(json!({"path": rel, "kind": "other"})); |
| 274 | } |
| 275 | if out.len() > INSPECT_MAX_ENTRIES { |
| 276 | return Err(format!( |
| 277 | "workspace holds more than {INSPECT_MAX_ENTRIES} entries" |
| 278 | )); |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | out.sort_by(|a, b| a["path"].as_str().cmp(&b["path"].as_str())); |
| 283 | let mut h = Sha256::new(); |
| 284 | for e in &out { |
| 285 | h.update(e["path"].as_str().unwrap_or("").as_bytes()); |
| 286 | h.update([0]); |
| 287 | h.update(e["sha256"].as_str().unwrap_or("-").as_bytes()); |
| 288 | h.update(b"\n"); |
| 289 | } |
| 290 | Ok((out, hex::encode(h.finalize()))) |
| 291 | } |
| 292 | |
| 293 | async fn step(sub: &str, m: &HashMap<String, String>) -> Result<Value, String> { |
| 294 | match sub { |
| 295 | "remember" => { |
| 296 | let text = need(m, "text")?; |
| 297 | let context = m.get("context").map_or("work", String::as_str); |
| 298 | // sc#386: memory lives with an engaged ALLEN identity. Put it there first; a refusal |
| 299 | // (not engaged) stops here and nothing is stored. |
| 300 | let mem = memory_put(context, text).await?; |
| 301 | let n = note("constraint", text, vec![]).await?; |
| 302 | Ok(json!({"step": "S1", "constraint": n, "memory": mem, "context": context})) |
| 303 | } |
| 304 | "inspect" => { |
| 305 | let (_, ws) = confine(need(m, "workspace")?)?; |
| 306 | let (entries, tree_sha) = tree(&ws)?; |
| 307 | let args = json!({"workspace": ws.display().to_string()}); |
| 308 | let result = json!({"entries": entries.len(), "tree_sha256": tree_sha}); |
| 309 | let rc = receipt("inspect", &args, &result, true)?; |
| 310 | let text = json!({"tool": "inspect", "receipt_sha256": rc["sha256"], |
| 311 | "arguments_digest": rc["arguments_digest"], "result_digest": rc["result_digest"], |
| 312 | "workspace": ws.display().to_string(), "tree_sha256": tree_sha}); |
| 313 | let n = note("effect", &text.to_string(), vec![]).await?; |
| 314 | Ok(json!({"step": "S2", "receipt": rc, "effect": n, "tree_sha256": tree_sha, |
| 315 | "entries": entries})) |
| 316 | } |
| 317 | "propose" => { |
| 318 | let goal = need(m, "goal")?.to_string(); |
| 319 | let objective = match m.get("objective-id") { |
| 320 | Some(id) => Some( |
| 321 | crate::objective::check_binding(id, &goal) |
| 322 | .map_err(crate::objective::refuse_propose)?, |
| 323 | ), |
| 324 | None => None, |
| 325 | }; |
| 326 | let (_, ws) = confine(need(m, "workspace")?)?; |
| 327 | match send(ControlCommand::RunComposeTask { |
| 328 | goal, |
| 329 | workspace: ws.display().to_string(), |
| 330 | context: m.get("context").cloned(), |
| 331 | }) |
| 332 | .await? |
| 333 | { |
| 334 | ControlResponse::ComposeTaskResult(r) => { |
| 335 | let out = json!({"step": "S3", "report": r}); |
| 336 | Ok(match objective { |
| 337 | Some(id) => crate::objective::attach(out, &id), |
| 338 | None => out, |
| 339 | }) |
| 340 | } |
| 341 | other => Err(format!("unexpected response {other:?}")), |
| 342 | } |
| 343 | } |
| 344 | "authorize" => { |
| 345 | let r = read_report(need(m, "report")?)?; |
| 346 | let (engine, ws) = confine(need(m, "workspace")?)?; |
| 347 | let approver = need(m, "approver")?; |
| 348 | let (path, content, psha) = committed_proposal(&r)?; |
| 349 | let target = engine |
| 350 | .validate_path(ws.join(&path).to_str().ok_or("path is not UTF-8")?) |
| 351 | .map_err(|e| format!("CONFINEMENT DENIAL: {e}"))?; |
| 352 | // sovereign-core #249: the grant names the canonical workspace |
| 353 | // (symlinks resolved, whatever form --workspace took) and the |
| 354 | // target must be exactly <workspace>/<path>, as the daemon checks. |
| 355 | let wsc = std::fs::canonicalize(&ws) |
| 356 | .map_err(|e| format!("workspace {}: {e}", ws.display()))?; |
| 357 | if target != wsc.join(&path) { |
| 358 | return Err(format!( |
| 359 | "CONFINEMENT DENIAL: target {} is not {}", |
| 360 | target.display(), |
| 361 | wsc.join(&path).display() |
| 362 | )); |
| 363 | } |
| 364 | let csha = sha256_hex(content.as_bytes()); |
| 365 | // sovereign-core #261: the daemon mints the grant. The CLI names |
| 366 | // the committed proposal (promotion + digest), the workspace it |
| 367 | // expects and the approver; path, content and target come from |
| 368 | // the daemon's own commit record, so nothing here is a grant the |
| 369 | // daemon has to trust. A raw `authorization` note is refused. |
| 370 | let constraints = m |
| 371 | .get("constraint") |
| 372 | .map(|s| ids(s)) |
| 373 | .transpose()? |
| 374 | .unwrap_or_default(); |
| 375 | // sovereign-core #297, #328: the approval-desk proof. The daemon |
| 376 | // requires it by default; only a dev run started with the opt-out |
| 377 | // AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK=0 ignores it. |
| 378 | let desk_proof = { |
| 379 | use aien_runtime::approved_auth::{desk_key_path, AuthorizeBinding, DeskKey}; |
| 380 | use aien_runtime::control::DeskProof; |
| 381 | match (m.get("desk-mac"), m.get("desk-key"), m.contains_key("desk")) { |
| 382 | (Some(mac), _, _) => Some(DeskProof { |
| 383 | nonce: need(m, "desk-nonce")?.to_string(), |
| 384 | mac: mac.to_string(), |
| 385 | }), |
| 386 | (None, key_path, desk) if key_path.is_some() || desk => { |
| 387 | let key_file = match key_path { |
| 388 | Some(p) => std::path::PathBuf::from(p), |
| 389 | None => desk_key_path(&aien_runtime::compose::compose_dir_from_env()?), |
| 390 | }; |
| 391 | let key = DeskKey::load(&key_file)?; |
| 392 | let mut raw = [0u8; 16]; |
| 393 | std::io::Read::read_exact(&mut std::fs::File::open("/dev/urandom").map_err(|e| e.to_string())?, &mut raw) |
| 394 | .map_err(|e| e.to_string())?; |
| 395 | let nonce = hex::encode(raw); |
| 396 | let mac = key.sign_authorize(&AuthorizeBinding { |
| 397 | cx_promotion: r.cx_promotion, |
| 398 | proposal_sha256: psha.clone(), |
| 399 | path: path.clone(), |
| 400 | content_sha256: csha.clone(), |
| 401 | workspace: wsc.display().to_string(), |
| 402 | approver: approver.trim().to_string(), |
| 403 | constraints: constraints.clone(), |
| 404 | nonce: nonce.clone(), |
| 405 | desk_key_id: key.id().to_string(), |
| 406 | }); |
| 407 | Some(DeskProof { nonce, mac }) |
| 408 | } |
| 409 | _ => None, |
| 410 | } |
| 411 | }; |
| 412 | // sovereign-core #408: the objective `compose propose --objective-id` |
| 413 | // attached; the daemon re-reads that record and binds the grant to it. |
| 414 | let objective_id = report_objective_id(need(m, "report")?)?; |
| 415 | let n = match send(ControlCommand::ComposeAuthorize { |
| 416 | cx_promotion: r.cx_promotion, |
| 417 | proposal_sha256: psha.clone(), |
| 418 | workspace: wsc.display().to_string(), |
| 419 | approver: approver.to_string(), |
| 420 | constraints: constraints.clone(), |
| 421 | desk_proof, |
| 422 | objective_id: objective_id.clone(), |
| 423 | }) |
| 424 | .await? |
| 425 | { |
| 426 | ControlResponse::ComposeNoted(n) => { |
| 427 | serde_json::to_value(n).map_err(|e| e.to_string())? |
| 428 | } |
| 429 | ControlResponse::Error(e) => return Err(e), |
| 430 | other => return Err(format!("unexpected response {other:?}")), |
| 431 | }; |
| 432 | let tgt = target.display().to_string(); |
| 433 | let mut args = json!({"proposal_sha256": psha, "path": path, "content_sha256": csha, |
| 434 | "approver": approver, "cx_promotion": r.cx_promotion, "target": tgt, |
| 435 | "constraints": constraints}); |
| 436 | if let Some(o) = &objective_id { |
| 437 | args["objective_id"] = json!(o); |
| 438 | } |
| 439 | let result = json!({"approved": true, "target": tgt, "authorization": n["id"]}); |
| 440 | let rc = receipt("authorize", &args, &result, true)?; |
| 441 | let mut out = json!({"step": "S4", "receipt": rc, "authorization": n, "approvals": 1}); |
| 442 | if let Some(o) = objective_id { |
| 443 | out["objective_id"] = json!(o); |
| 444 | } |
| 445 | Ok(out) |
| 446 | } |
| 447 | "execute" => { |
| 448 | let r = read_report(need(m, "report")?)?; |
| 449 | let (engine, ws) = confine(need(m, "workspace")?)?; |
| 450 | let auth: u64 = need(m, "authorization")? |
| 451 | .parse() |
| 452 | .map_err(|e| format!("--authorization: {e}"))?; |
| 453 | let (path, content, psha) = committed_proposal(&r)?; |
| 454 | let csha = sha256_hex(content.as_bytes()); |
| 455 | let target = engine |
| 456 | .validate_path(ws.join(&path).to_str().ok_or("path is not UTF-8")?) |
| 457 | .map_err(|e| format!("CONFINEMENT DENIAL: {e}"))?; |
| 458 | // NEXT-PHASE-2 (ACCEPTANCE-v2 2.1-2.3): the daemon checks the grant |
| 459 | // (stop, revoke, stale, spent) and records the intent durably |
| 460 | // before anything touches the world. No intent, no write. |
| 461 | fault_hold("before_intent"); |
| 462 | let (pid, start) = effects::self_executor(); |
| 463 | let intent = match send(ControlCommand::ComposeEffectIntent { |
| 464 | authorization: auth, |
| 465 | proposal_sha256: psha.clone(), |
| 466 | path: path.clone(), |
| 467 | target: target.display().to_string(), |
| 468 | content_sha256: csha.clone(), |
| 469 | executor_pid: pid, |
| 470 | executor_start: start, |
| 471 | }) |
| 472 | .await? |
| 473 | { |
| 474 | ControlResponse::ComposeNoted(n) => n, |
| 475 | other => return Err(format!("unexpected response {other:?}")), |
| 476 | }; |
| 477 | fault_hold("after_intent"); |
| 478 | if let Some(parent) = target.parent() { |
| 479 | std::fs::create_dir_all(parent) |
| 480 | .map_err(|e| format!("create {}: {e}", parent.display()))?; |
| 481 | } |
| 482 | let written = std::fs::write(&target, content.as_bytes()) |
| 483 | .map_err(|e| format!("write {}: {e}", target.display())) |
| 484 | .and_then(|_| std::fs::read(&target).map_err(|e| e.to_string())); |
| 485 | let (disk_sha, bytes) = match &written { |
| 486 | Ok(b) => (sha256_hex(b), b.len()), |
| 487 | Err(_) => (String::new(), 0), |
| 488 | }; |
| 489 | fault_hold("after_write"); |
| 490 | let reported = json!({"disk_sha256": disk_sha, "bytes": bytes, |
| 491 | "error": written.as_ref().err()}); |
| 492 | // The ack's state is the daemon's reading of the world. If the |
| 493 | // ack cannot be recorded the effect is UNRESOLVED until reconcile. |
| 494 | let ack = send(ControlCommand::ComposeEffectAck { |
| 495 | intent: intent.id, |
| 496 | reported: reported.clone(), |
| 497 | }) |
| 498 | .await; |
| 499 | // sc#408: the ack record names the objective of an objective-bound grant. |
| 500 | let mut objective: Option<String> = None; |
| 501 | let (state, ack_id, ack_err) = match &ack { |
| 502 | Ok(ControlResponse::ComposeNoted(n)) => { |
| 503 | let rec = recall(vec![n.id], None).await.ok(); |
| 504 | let v = rec |
| 505 | .and_then(|r| r.cited.into_iter().next()) |
| 506 | .and_then(|c| c.text) |
| 507 | .and_then(|t| serde_json::from_str::<Value>(&t).ok()); |
| 508 | objective = v |
| 509 | .as_ref() |
| 510 | .and_then(|v| v["objective_id"].as_str().map(str::to_string)); |
| 511 | let st = v |
| 512 | .and_then(|v| v["state"].as_str().map(str::to_string)) |
| 513 | .unwrap_or_else(|| "UNRESOLVED".into()); |
| 514 | (st, Some(n.id), None) |
| 515 | } |
| 516 | Ok(other) => ("UNRESOLVED".to_string(), None, Some(format!("{other:?}"))), |
| 517 | Err(e) => ("UNRESOLVED".to_string(), None, Some(e.clone())), |
| 518 | }; |
| 519 | let ok = state == "DONE"; |
| 520 | let mut args = json!({"path": target.display().to_string(), "content_sha256": csha, |
| 521 | "authorization": auth, "intent": intent.id}); |
| 522 | if let Some(o) = &objective { |
| 523 | args["objective_id"] = json!(o); |
| 524 | } |
| 525 | let result = json!({"bytes": bytes, "disk_sha256": disk_sha, "error": written.err(), |
| 526 | "state": state, "ack": ack_id, "ack_error": ack_err}); |
| 527 | let rc = receipt("write_file", &args, &result, ok)?; |
| 528 | let mut out = json!({"step": "S5", "receipt": rc, "intent": intent, |
| 529 | "effect": {"id": ack_id}, "state": state, "path": target.display().to_string(), |
| 530 | "content_sha256": csha, "disk_sha256": disk_sha, "bytes": bytes, |
| 531 | "ack_error": ack_err}); |
| 532 | if let Some(o) = objective { |
| 533 | out["objective_id"] = json!(o); |
| 534 | } |
| 535 | // handle_compose_command turns a state other than DONE into |
| 536 | // "ok": false (exit 3 for UNRESOLVED, 1 otherwise). |
| 537 | Ok(out) |
| 538 | } |
| 539 | "explain" => { |
| 540 | let r = read_report(need(m, "report")?)?; |
| 541 | let (path, _, _) = committed_proposal(&r)?; |
| 542 | let mut cite = ids(need(m, "cite")?)?; |
| 543 | let mut all = vec![r.cx_goal]; |
| 544 | all.extend(&r.cx_candidates); |
| 545 | all.extend([r.cx_evidence, r.cx_promotion]); |
| 546 | all.append(&mut cite); |
| 547 | let rec = recall(all.clone(), None).await?; |
| 548 | if !rec.missing.is_empty() || rec.cited.iter().any(|c| !c.verified) { |
| 549 | return Err(format!("cited records missing or unverified: {:?}", rec.missing)); |
| 550 | } |
| 551 | let mut receipts = Vec::new(); |
| 552 | for p in need(m, "receipts")?.split(',').filter(|p| !p.is_empty()) { |
| 553 | let b = std::fs::read(p).map_err(|e| format!("receipt {p}: {e}"))?; |
| 554 | let v: Value = serde_json::from_slice(&b).map_err(|e| format!("{p}: {e}"))?; |
| 555 | receipts.push(json!({"path": p, "sha256": sha256_hex(&b), "tool": v["tool"], |
| 556 | "success": v["success"]})); |
| 557 | } |
| 558 | let short = |d: &str| d.chars().take(16).collect::<String>(); |
| 559 | let mut lines = vec![format!( |
| 560 | "Result: {path} in the authorized workspace was written once, as proposed by {} \ |
| 561 | and approved by the operator. Evidence (Cortex journal {}/cortex.cx, machine {}):", |
| 562 | r.proposer, |
| 563 | rec.compose_dir, |
| 564 | short(&rec.machine_id) |
| 565 | )]; |
| 566 | for c in rec.cited.iter() { |
| 567 | let what = match (c.note.as_deref(), c.id) { |
| 568 | (Some(n), _) => n.to_string(), |
| 569 | (None, id) if id == r.cx_goal => "goal".into(), |
| 570 | (None, id) if id == r.cx_evidence => { |
| 571 | format!("AEGIS verdict (pass mask {:#x})", r.aegis_pass_mask) |
| 572 | } |
| 573 | (None, id) if id == r.cx_promotion => "promotion of the winner".into(), |
| 574 | (None, _) => "candidate".into(), |
| 575 | }; |
| 576 | let text = c |
| 577 | .text |
| 578 | .as_deref() |
| 579 | .map(|t| format!(": {}", t.chars().take(160).collect::<String>())) |
| 580 | .unwrap_or_default(); |
| 581 | lines.push(format!("- cortex.cx#{} {what} (digest {}){text}", c.id, short(&c.digest))); |
| 582 | } |
| 583 | for rc in &receipts { |
| 584 | lines.push(format!( |
| 585 | "- receipt {} {} success={} (sha256 {})", |
| 586 | rc["tool"].as_str().unwrap_or("?"), |
| 587 | rc["path"].as_str().unwrap_or("?"), |
| 588 | rc["success"], |
| 589 | short(rc["sha256"].as_str().unwrap_or("")) |
| 590 | )); |
| 591 | } |
| 592 | let text = lines.join("\n"); |
| 593 | Ok(json!({"step": "S6", "text": text, "cited": rec.cited, "receipts": receipts, |
| 594 | "machine_id": rec.machine_id})) |
| 595 | } |
| 596 | "recall" => { |
| 597 | let want = m.get("ids").map(|s| ids(s)).transpose()?.unwrap_or_default(); |
| 598 | let prefix = m |
| 599 | .get("prefix") |
| 600 | .map(|s| s.parse::<u64>().map_err(|e| format!("--prefix: {e}"))) |
| 601 | .transpose()?; |
| 602 | let rec = recall(want, prefix).await?; |
| 603 | let memory = memory_view(m.get("context").map_or("work", String::as_str)).await?; |
| 604 | let of = |k: &str| -> Vec<Value> { |
| 605 | rec.host |
| 606 | .iter() |
| 607 | .filter(|h| h.note.as_deref() == Some(k)) |
| 608 | .map(|h| json!({"id": h.id, "digest": h.digest, "verified": h.verified, |
| 609 | "text": h.text})) |
| 610 | .collect() |
| 611 | }; |
| 612 | Ok(json!({"step": "S8", "machine_id": rec.machine_id, |
| 613 | "constraints": of("constraint"), "authorizations": of("authorization"), |
| 614 | "effects": of("effect"), "repairs": of("repair_tail"), "memory": memory, "recall": rec})) |
| 615 | } |
| 616 | "shutdown" => { |
| 617 | AienRuntimeClient::default_client().shutdown().await?; |
| 618 | Ok(json!({"step": "S7", "shutdown": true})) |
| 619 | } |
| 620 | // NEXT-PHASE-2 operator commands (ACCEPTANCE-v2 2.4-2.6). |
| 621 | "effects" => { |
| 622 | let rec = recall(vec![], None).await?; |
| 623 | let ledger = effects::Ledger::from_records(&rec.host).map_err(|r| r.to_string())?; |
| 624 | Ok(json!({"machine_id": rec.machine_id, "ledger": ledger.view()})) |
| 625 | } |
| 626 | "reconcile" => { |
| 627 | let declare = match m.get("declare") { |
| 628 | None => None, |
| 629 | Some(d) => Some(ReconcileDeclare { |
| 630 | intent: need(m, "intent")? |
| 631 | .parse() |
| 632 | .map_err(|e| format!("--intent: {e}"))?, |
| 633 | state: d.clone(), |
| 634 | approver: need(m, "approver")?.to_string(), |
| 635 | }), |
| 636 | }; |
| 637 | match send(ControlCommand::ComposeReconcile { declare }).await? { |
| 638 | ControlResponse::ComposeReconciled(r) => Ok(json!({"reconcile": r})), |
| 639 | other => Err(format!("unexpected response {other:?}")), |
| 640 | } |
| 641 | } |
| 642 | "stop" | "resume" | "revoke" => { |
| 643 | let authorization = if sub == "revoke" { |
| 644 | Some( |
| 645 | need(m, "authorization")? |
| 646 | .parse::<u64>() |
| 647 | .map_err(|e| format!("--authorization: {e}"))?, |
| 648 | ) |
| 649 | } else { |
| 650 | None |
| 651 | }; |
| 652 | match send(ControlCommand::ComposeControl { |
| 653 | action: sub.to_string(), |
| 654 | approver: need(m, "approver")?.to_string(), |
| 655 | authorization, |
| 656 | }) |
| 657 | .await? |
| 658 | { |
| 659 | ControlResponse::ComposeControlled(r) => Ok(json!({"control": r})), |
| 660 | other => Err(format!("unexpected response {other:?}")), |
| 661 | } |
| 662 | } |
| 663 | "desk-key" => { |
| 664 | use aien_runtime::approved_auth::{desk_key_path, DeskKey}; |
| 665 | let dir = aien_runtime::compose::compose_dir_from_env()?; |
| 666 | let path = desk_key_path(&dir); |
| 667 | let key = match (DeskKey::load(&path), m.contains_key("create")) { |
| 668 | (Ok(k), _) => k, |
| 669 | (Err(_), true) if !path.exists() => DeskKey::create(&path)?, |
| 670 | (Err(e), _) => return Err(e), |
| 671 | }; |
| 672 | Ok(json!({"desk_key_id": key.id(), "path": path.display().to_string()})) |
| 673 | } |
| 674 | "recover" => match send(ControlCommand::RecoverComposeHome).await? { |
| 675 | ControlResponse::ComposeRecovered(r) => Ok(json!({"repair": r, "opens": r.opens})), |
| 676 | other => Err(format!("unexpected response {other:?}")), |
| 677 | }, |
| 678 | other => Err(format!( |
| 679 | "unknown compose step {other:?} (remember, inspect, propose, authorize, execute, explain, recall, shutdown, recover, effects, reconcile, stop, resume, revoke, desk-key)" |
| 680 | )), |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | pub async fn handle_compose_command(args: &[String]) { |
| 685 | let Some(sub) = args.first() else { |
| 686 | println!( |
| 687 | "{}", |
| 688 | json!({"ok": false, "error": "usage: aien compose <step> [--flag value ...]"}) |
| 689 | ); |
| 690 | std::process::exit(1); |
| 691 | }; |
| 692 | let out = match flags(&args[1..]) { |
| 693 | Ok(m) => step(sub, &m).await, |
| 694 | Err(e) => Err(e), |
| 695 | }; |
| 696 | match out { |
| 697 | Ok(mut v) => { |
| 698 | // An effect step reports its state; only DONE is success. |
| 699 | let state = v.get("state").and_then(Value::as_str).map(str::to_string); |
| 700 | let ok = state.as_deref().is_none_or(|s| s == "DONE"); |
| 701 | v["ok"] = json!(ok); |
| 702 | println!("{v}"); |
| 703 | if !ok { |
| 704 | std::process::exit(if state.as_deref() == Some("UNRESOLVED") { |
| 705 | 3 |
| 706 | } else { |
| 707 | 1 |
| 708 | }); |
| 709 | } |
| 710 | } |
| 711 | Err(e) => { |
| 712 | println!("{}", json!({"ok": false, "step": sub, "error": e})); |
| 713 | std::process::exit(1); |
| 714 | } |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | /// Test builds only (cargo feature `fault-hold`, ACCEPTANCE-v2 2.9): stop at |
| 719 | /// the named point when `AIEN_FAULT_HOLD` names it, until the harness deletes |
| 720 | /// `AIEN_FAULT_HOLD_FILE`. The default build compiles this to nothing. |
| 721 | #[cfg(feature = "fault-hold")] |
| 722 | fn fault_hold(point: &str) { |
| 723 | if std::env::var("AIEN_FAULT_HOLD").as_deref() != Ok(point) { |
| 724 | return; |
| 725 | } |
| 726 | let Ok(file) = std::env::var("AIEN_FAULT_HOLD_FILE") else { |
| 727 | eprintln!("AIEN_FAULT_HOLD={point} without AIEN_FAULT_HOLD_FILE"); |
| 728 | std::process::exit(86); |
| 729 | }; |
| 730 | if let Err(e) = std::fs::write(&file, format!("{} {point}\n", std::process::id())) { |
| 731 | eprintln!("fault hold {point}: write {file}: {e}"); |
| 732 | std::process::exit(86); |
| 733 | } |
| 734 | let t0 = std::time::Instant::now(); |
| 735 | while Path::new(&file).exists() { |
| 736 | if t0.elapsed() > std::time::Duration::from_secs(300) { |
| 737 | eprintln!("fault hold {point}: not released in 300 s"); |
| 738 | std::process::exit(86); |
| 739 | } |
| 740 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | #[cfg(not(feature = "fault-hold"))] |
| 745 | fn fault_hold(_point: &str) {} |