Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/bc2d34245fa7dccb # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#217 (code only) closed derived `bc2d34245fa7dccb` #217 Imported from GitHub aien-dev/aien-sovereign-core-mv#217 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `80e071a3ef700dbe31b1b081a957eebdcbf5ffc3` · Head `3c02f5cfb9b662bd79383ddb57ed9742ca865fd1` ### Fetch it A git bundle of the pull request's head, 88403 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/bc2d34245fa7dccb.bundle -o bc2d34245fa7dccb.bundle git fetch bc2d34245fa7dccb.bundle refs/pull/217/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 217 3c02f5cfb9b662bd79383ddb57ed9742ca865fd1 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":217,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/217","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:20Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 11bbe442..5a30f4f3 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:10d81c6270915316b54eee21734bb8e8f2716ffdc567100fb347a5f22ed95e24", - "compiled_at": "2026-10-06T01:17:44Z", + "compiled_at": "2026-10-06T02:53:13Z", "compiler": "crumb-compile/1", - "digest": "sha256:427b1abd06f870fb1fa9e845ab7f98055b5e4ca7c6bc5ed5ea7b58f6d026b01d", + "digest": "sha256:10d7705a26e8cc45a2e2e42ef766aaac4d7a79828d000bcf0500076e0b544f15", "evidence_files": 20, "evidence_root": "sha256:1ef4526f6fe1ba0cee21a89c3313d37bf2e94e1aa2e9bd1a364225e52882d170", - "files": 687, - "generated_at_commit": "d4d732ddfb59b90019406ad06bc65ec7d982e6f8", - "source_tree": "sha256:cc2debed81e176e7593b190a0d79414b6b351b768a22fdb91a16d2a185d394ab" + "files": 711, + "generated_at_commit": "1a745e913ee8456adf65e50fc93da8be1d4cecab", + "source_tree": "sha256:c7a91c84482f5e692432ed69c2b4e0609c12ec91a2234c08ae467d54b4fb6d6d" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 034bfdd6..e0136450 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -192,6 +192,14 @@ dependencies = [ "tokio", ] +[[package]] +name = "aien-omega-compose" +version = "0.1.0" +dependencies = [ + "sha2 0.10.9", + "tempfile", +] + [[package]] name = "aien-omega-gpu" version = "0.1.0" @@ -275,6 +283,7 @@ dependencies = [ "aien-abi-core", "aien-inference-abi", "aien-kv-cache", + "aien-omega-compose", "aien-platform", "aien-scheduler", "aien-security", diff --git a/Cargo.toml b/Cargo.toml index e30cecc4..de590494 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,6 +34,7 @@ members = [ "crates/aien-inference-runtime", "crates/cortex-path-m1", "crates/aien-omega-gpu", + "crates/aien-omega-compose", "crates/aien-campaign-verifier", "crates/aien-proof", "crates/crumbs", diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 290ea055..22beaa16 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "f524c0a6bade5bb46ce3a21920eade0b1173fcaf6d0e165c7008e6f69fb4c274", - "last_commit": "426f6a0", + "digest": "7e172306ece8e1b074de1f9375f012d5886c89993bfe7a0fa32f3c7ec0ec342f", + "last_commit": "94b1eed", "name": "src", "purpose": "" } ], - "children_root": "sha256:e1fcd79237394f633fdc4f115a0cdc68b1eb0d136b3b9811e57e6281968749d9", - "compiled_at": "2026-10-04T16:37:52Z", + "children_root": "sha256:c3356e96fd5c1cc4bcb5edaebe1e8e0dcfae3496b43602fdcf5247fdc37dd3d5", + "compiled_at": "2026-10-06T02:27:26Z", "compiler": "crumb-compile/1", - "digest": "sha256:20b911e819f59d5116b885209254a8a7031ddcf43daf9318ea5ecbad91fd41e0", + "digest": "sha256:f8352cc1a77ec1cf3bb377b96f648e4e5b6d488be85cd1a9941eb68dd757bd5c", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 27, - "generated_at_commit": "426f6a0f04b225fe719f280578fbbf2937dbc961", - "source_tree": "sha256:47a80ba4abfc31b09a82b921f72319ec2c538d88c6e3edc6dacb9beb55ee1eef" + "files": 28, + "generated_at_commit": "94b1eed8649067dda6ce75ad905d33047f5902b6", + "source_tree": "sha256:dd7f86eb35f1d49c5161867f78cc2775eff91220ff42fc758f39a8d5f10e8348" } }, "history": [ diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb index 2412f168..a309bf99 100644 --- a/crates/aien-cli/src/.crumb +++ b/crates/aien-cli/src/.crumb @@ -64,14 +64,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T16:37:52Z", + "compiled_at": "2026-10-06T02:27:26Z", "compiler": "crumb-compile/1", - "digest": "sha256:f524c0a6bade5bb46ce3a21920eade0b1173fcaf6d0e165c7008e6f69fb4c274", + "digest": "sha256:7e172306ece8e1b074de1f9375f012d5886c89993bfe7a0fa32f3c7ec0ec342f", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 24, - "generated_at_commit": "426f6a0f04b225fe719f280578fbbf2937dbc961", - "source_tree": "sha256:ae27baccfd45ba353d7959c972baeea60a10c1335621088ed8c455a21d0c64ef" + "files": 25, + "generated_at_commit": "94b1eed8649067dda6ce75ad905d33047f5902b6", + "source_tree": "sha256:f15e1c93e1b10a1ef385ad83657282ff84354898ce045ee6458e05740205b648" } }, "history": [ diff --git a/crates/aien-cli/src/compose.rs b/crates/aien-cli/src/compose.rs new file mode 100644 index 00000000..e10cc328 --- /dev/null +++ b/crates/aien-cli/src/compose.rs @@ -0,0 +1,425 @@ +//! `aien compose ...`: the NEXT-PHASE-1 bounded task, one operator step per +//! subcommand, against the running daemon's composition home (omega +//! COMPOSITION-2, `RunComposeTask` / `ComposeNote` / `ComposeRecall` / +//! `RecoverComposeHome`). +//! +//! The daemon owns the Cortex journal; this side owns the effects. Every +//! workspace path goes through `SafetyEngine::validate_path` with the +//! authorized workspace as the only root, and every effect (inspect, +//! authorize, write_file) leaves a sovereign-core effect receipt +//! (`record_effect_receipt`) that the Cortex record then cites by sha256. +//! +//! Each subcommand prints one JSON object on stdout (`"ok": true|false`) and +//! exits 1 on failure. +//! +//! remember --text T S1 constraint record +//! inspect --workspace W S2 read-only listing + receipt +//! propose --goal G --workspace W S3 one RunComposeTask +//! authorize --report S3.json --workspace W --approver NAME [--constraint ID] +//! S4 the one approval +//! execute --report S3.json --workspace W --authorization ID +//! S5 the write, confined +//! explain --report S3.json --cite ID,.. --receipts P,.. +//! S6 evidence-citing explanation +//! recall [--ids ID,..] [--prefix N] S8 constraints + effects +//! shutdown S7 stop the daemon (control Shutdown) +//! recover repair a refused home +use crate::safety::SafetyEngine; +use crate::tools::record_effect_receipt; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::{ + ComposeRecallReport, ComposeRecordView, ComposeTaskReport, ControlCommand, ControlResponse, +}; +use aien_runtime::spine::parse_file_proposal; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +const INSPECT_MAX_ENTRIES: usize = 4096; + +fn sha256_hex(b: &[u8]) -> String { + hex::encode(Sha256::digest(b)) +} + +fn flags(args: &[String]) -> Result, String> { + let mut m = HashMap::new(); + let mut i = 0; + while i < args.len() { + let k = args[i] + .strip_prefix("--") + .ok_or_else(|| format!("expected --flag, got {:?}", args[i]))?; + let v = args + .get(i + 1) + .ok_or_else(|| format!("--{k} needs a value"))?; + m.insert(k.to_string(), v.clone()); + i += 2; + } + Ok(m) +} + +fn need<'a>(m: &'a HashMap, k: &str) -> Result<&'a str, String> { + m.get(k) + .map(|s| s.as_str()) + .filter(|s| !s.trim().is_empty()) + .ok_or_else(|| format!("--{k} is required")) +} + +fn ids(s: &str) -> Result, String> { + s.split(',') + .filter(|x| !x.trim().is_empty()) + .map(|x| { + x.trim() + .parse::() + .map_err(|e| format!("bad id {x:?}: {e}")) + }) + .collect() +} + +async fn send(cmd: ControlCommand) -> Result { + match AienRuntimeClient::default_client() + .send_command(cmd) + .await? + { + ControlResponse::Error(e) => Err(e), + r => Ok(r), + } +} + +/// The authorized workspace as the only root the safety engine accepts. +fn confine(workspace: &str) -> Result<(SafetyEngine, PathBuf), String> { + let mut engine = SafetyEngine::new(); + engine.set_workspaces(vec![PathBuf::from(workspace)]); + let ws = engine + .validate_path(workspace) + .map_err(|e| format!("CONFINEMENT DENIAL: {e}"))?; + if !ws.is_dir() { + return Err(format!("workspace {} is not a directory", ws.display())); + } + Ok((engine, ws)) +} + +/// One effect receipt, read back: (path, sha256 of the file, its JSON). +fn receipt(tool: &str, args: &Value, result: &Value, success: bool) -> Result { + let path = record_effect_receipt(tool, args, result, success) + .ok_or_else(|| format!("effect receipt for {tool} could not be written"))?; + let bytes = + std::fs::read(&path).map_err(|e| format!("read receipt {}: {e}", path.display()))?; + let body: Value = + serde_json::from_slice(&bytes).map_err(|e| format!("receipt {}: {e}", path.display()))?; + Ok(json!({ + "path": path.display().to_string(), + "sha256": sha256_hex(&bytes), + "tool": tool, + "success": success, + "arguments_digest": body["arguments_digest"], + "result_digest": body["result_digest"], + })) +} + +async fn note(kind: &str, text: &str, links: Vec) -> Result { + match send(ControlCommand::ComposeNote { + kind: kind.into(), + text: text.into(), + links, + }) + .await? + { + ControlResponse::ComposeNoted(n) => serde_json::to_value(n).map_err(|e| e.to_string()), + other => Err(format!("unexpected response {other:?}")), + } +} + +async fn recall(ids: Vec, prefix: Option) -> Result { + match send(ControlCommand::ComposeRecall { ids, prefix }).await? { + ControlResponse::ComposeRecalled(r) => Ok(*r), + other => Err(format!("unexpected response {other:?}")), + } +} + +fn read_report(path: &str) -> Result { + let bytes = std::fs::read(path).map_err(|e| format!("read {path}: {e}"))?; + let v: Value = serde_json::from_slice(&bytes).map_err(|e| format!("{path}: {e}"))?; + // `aien compose propose` prints {"ok":true,"report":{...}}; accept both. + let r = v.get("report").cloned().unwrap_or(v); + serde_json::from_value(r).map_err(|e| format!("{path}: not a compose report: {e}")) +} + +/// The committed proposal of an S3 report, re-parsed and re-hashed here. +fn committed_proposal(r: &ComposeTaskReport) -> Result<(String, String, String), String> { + if !r.committed { + return Err("the composition did not commit a proposal".into()); + } + let text = r.proposal.as_deref().ok_or("report holds no proposal")?; + let sha = sha256_hex(text.as_bytes()); + if r.proposal_sha256.as_deref() != Some(sha.as_str()) { + return Err("proposal text does not match its recorded sha256".into()); + } + let p = parse_file_proposal(text).ok_or("proposal is not one file change")?; + let csha = sha256_hex(p.content.as_bytes()); + if r.proposal_content_sha256.as_deref() != Some(csha.as_str()) + || r.proposal_path.as_deref() != Some(p.path.as_str()) + { + return Err("parsed proposal differs from the report".into()); + } + Ok((p.path, p.content, sha)) +} + +fn tree(ws: &Path) -> Result<(Vec, String), String> { + let mut out = Vec::new(); + let mut stack = vec![ws.to_path_buf()]; + while let Some(d) = stack.pop() { + let rd = std::fs::read_dir(&d).map_err(|e| format!("read {}: {e}", d.display()))?; + for e in rd { + let e = e.map_err(|e| e.to_string())?; + let p = e.path(); + let ft = e.file_type().map_err(|e| e.to_string())?; + let rel = p + .strip_prefix(ws) + .unwrap_or(&p) + .to_string_lossy() + .into_owned(); + if ft.is_dir() { + stack.push(p); + out.push(json!({"path": rel + "/", "kind": "dir"})); + } else if ft.is_file() { + let b = std::fs::read(&p).map_err(|e| format!("read {}: {e}", p.display()))?; + out.push(json!({"path": rel, "kind": "file", "bytes": b.len(), "sha256": sha256_hex(&b)})); + } else { + out.push(json!({"path": rel, "kind": "other"})); + } + if out.len() > INSPECT_MAX_ENTRIES { + return Err(format!( + "workspace holds more than {INSPECT_MAX_ENTRIES} entries" + )); + } + } + } + out.sort_by(|a, b| a["path"].as_str().cmp(&b["path"].as_str())); + let mut h = Sha256::new(); + for e in &out { + h.update(e["path"].as_str().unwrap_or("").as_bytes()); + h.update([0]); + h.update(e["sha256"].as_str().unwrap_or("-").as_bytes()); + h.update(b"\n"); + } + Ok((out, hex::encode(h.finalize()))) +} + +async fn step(sub: &str, m: &HashMap) -> Result { + match sub { + "remember" => { + let text = need(m, "text")?; + let n = note("constraint", text, vec![]).await?; + Ok(json!({"step": "S1", "constraint": n})) + } + "inspect" => { + let (_, ws) = confine(need(m, "workspace")?)?; + let (entries, tree_sha) = tree(&ws)?; + let args = json!({"workspace": ws.display().to_string()}); + let result = json!({"entries": entries.len(), "tree_sha256": tree_sha}); + let rc = receipt("inspect", &args, &result, true)?; + let text = json!({"tool": "inspect", "receipt_sha256": rc["sha256"], + "arguments_digest": rc["arguments_digest"], "result_digest": rc["result_digest"], + "workspace": ws.display().to_string(), "tree_sha256": tree_sha}); + let n = note("effect", &text.to_string(), vec![]).await?; + Ok(json!({"step": "S2", "receipt": rc, "effect": n, "tree_sha256": tree_sha, + "entries": entries})) + } + "propose" => { + let (_, ws) = confine(need(m, "workspace")?)?; + match send(ControlCommand::RunComposeTask { + goal: need(m, "goal")?.to_string(), + workspace: ws.display().to_string(), + }) + .await? + { + ControlResponse::ComposeTaskResult(r) => Ok(json!({"step": "S3", "report": r})), + other => Err(format!("unexpected response {other:?}")), + } + } + "authorize" => { + let r = read_report(need(m, "report")?)?; + let (engine, ws) = confine(need(m, "workspace")?)?; + let approver = need(m, "approver")?; + let (path, content, psha) = committed_proposal(&r)?; + let target = engine + .validate_path(ws.join(&path).to_str().ok_or("path is not UTF-8")?) + .map_err(|e| format!("CONFINEMENT DENIAL: {e}"))?; + let csha = sha256_hex(content.as_bytes()); + let args = json!({"proposal_sha256": psha, "path": path, "content_sha256": csha, + "approver": approver, "cx_promotion": r.cx_promotion}); + let result = json!({"approved": true, "target": target.display().to_string()}); + let rc = receipt("authorize", &args, &result, true)?; + let constraint = m.get("constraint").map(|s| ids(s)).transpose()?; + let mut links = vec![r.cx_promotion, r.cx_evidence]; + links.extend(constraint.unwrap_or_default().into_iter().take(2)); + let text = json!({"proposal_sha256": psha, "path": path, "content_sha256": csha, + "approver": approver, "receipt_sha256": rc["sha256"]}); + let n = note("authorization", &text.to_string(), links).await?; + Ok(json!({"step": "S4", "receipt": rc, "authorization": n, "approvals": 1})) + } + "execute" => { + let r = read_report(need(m, "report")?)?; + let (engine, ws) = confine(need(m, "workspace")?)?; + let auth: u64 = need(m, "authorization")? + .parse() + .map_err(|e| format!("--authorization: {e}"))?; + let (path, content, psha) = committed_proposal(&r)?; + let csha = sha256_hex(content.as_bytes()); + // The approval is read back from the journal, never taken from argv. + let rec = recall(vec![auth], None).await?; + let a: &ComposeRecordView = rec + .cited + .first() + .filter(|a| a.verified && a.note.as_deref() == Some("authorization")) + .ok_or_else(|| format!("cortex.cx#{auth} is not a verified authorization"))?; + let at: Value = serde_json::from_str(a.text.as_deref().unwrap_or("")) + .map_err(|e| format!("authorization #{auth}: {e}"))?; + if at["proposal_sha256"] != json!(psha) + || at["content_sha256"] != json!(csha) + || at["path"] != json!(path) + { + return Err(format!("authorization #{auth} names a different proposal")); + } + let target = engine + .validate_path(ws.join(&path).to_str().ok_or("path is not UTF-8")?) + .map_err(|e| format!("CONFINEMENT DENIAL: {e}"))?; + if let Some(parent) = target.parent() { + std::fs::create_dir_all(parent) + .map_err(|e| format!("create {}: {e}", parent.display()))?; + } + let args = json!({"path": target.display().to_string(), "content_sha256": csha, + "authorization": auth}); + let written = std::fs::write(&target, content.as_bytes()) + .map_err(|e| format!("write {}: {e}", target.display())) + .and_then(|_| std::fs::read(&target).map_err(|e| e.to_string())); + let (ok, disk_sha, bytes) = match &written { + Ok(b) => (sha256_hex(b) == csha, sha256_hex(b), b.len()), + Err(_) => (false, String::new(), 0), + }; + let result = json!({"bytes": bytes, "disk_sha256": disk_sha, "error": written.err()}); + let rc = receipt("write_file", &args, &result, ok)?; + let text = json!({"tool": "write_file", "path": path, "content_sha256": csha, + "disk_sha256": disk_sha, "bytes": bytes, "success": ok, + "receipt_sha256": rc["sha256"], "authorization": auth}); + let n = note("effect", &text.to_string(), vec![auth, r.cx_promotion]).await?; + if !ok { + return Err(format!("write_file failed; receipt {}", rc["sha256"])); + } + Ok(json!({"step": "S5", "receipt": rc, "effect": n, "path": target.display().to_string(), + "content_sha256": csha, "disk_sha256": disk_sha, "bytes": bytes})) + } + "explain" => { + let r = read_report(need(m, "report")?)?; + let (path, _, _) = committed_proposal(&r)?; + let mut cite = ids(need(m, "cite")?)?; + let mut all = vec![r.cx_goal]; + all.extend(&r.cx_candidates); + all.extend([r.cx_evidence, r.cx_promotion]); + all.append(&mut cite); + let rec = recall(all.clone(), None).await?; + if !rec.missing.is_empty() || rec.cited.iter().any(|c| !c.verified) { + return Err(format!("cited records missing or unverified: {:?}", rec.missing)); + } + let mut receipts = Vec::new(); + for p in need(m, "receipts")?.split(',').filter(|p| !p.is_empty()) { + let b = std::fs::read(p).map_err(|e| format!("receipt {p}: {e}"))?; + let v: Value = serde_json::from_slice(&b).map_err(|e| format!("{p}: {e}"))?; + receipts.push(json!({"path": p, "sha256": sha256_hex(&b), "tool": v["tool"], + "success": v["success"]})); + } + let short = |d: &str| d.chars().take(16).collect::(); + let mut lines = vec![format!( + "Result: {path} in the authorized workspace was written once, as proposed by {} \ + and approved by the operator. Evidence (Cortex journal {}/cortex.cx, machine {}):", + r.proposer, + rec.compose_dir, + short(&rec.machine_id) + )]; + for c in rec.cited.iter() { + let what = match (c.note.as_deref(), c.id) { + (Some(n), _) => n.to_string(), + (None, id) if id == r.cx_goal => "goal".into(), + (None, id) if id == r.cx_evidence => { + format!("AEGIS verdict (pass mask {:#x})", r.aegis_pass_mask) + } + (None, id) if id == r.cx_promotion => "promotion of the winner".into(), + (None, _) => "candidate".into(), + }; + let text = c + .text + .as_deref() + .map(|t| format!(": {}", t.chars().take(160).collect::())) + .unwrap_or_default(); + lines.push(format!("- cortex.cx#{} {what} (digest {}){text}", c.id, short(&c.digest))); + } + for rc in &receipts { + lines.push(format!( + "- receipt {} {} success={} (sha256 {})", + rc["tool"].as_str().unwrap_or("?"), + rc["path"].as_str().unwrap_or("?"), + rc["success"], + short(rc["sha256"].as_str().unwrap_or("")) + )); + } + let text = lines.join("\n"); + Ok(json!({"step": "S6", "text": text, "cited": rec.cited, "receipts": receipts, + "machine_id": rec.machine_id})) + } + "recall" => { + let want = m.get("ids").map(|s| ids(s)).transpose()?.unwrap_or_default(); + let prefix = m + .get("prefix") + .map(|s| s.parse::().map_err(|e| format!("--prefix: {e}"))) + .transpose()?; + let rec = recall(want, prefix).await?; + let of = |k: &str| -> Vec { + rec.host + .iter() + .filter(|h| h.note.as_deref() == Some(k)) + .map(|h| json!({"id": h.id, "digest": h.digest, "verified": h.verified, + "text": h.text})) + .collect() + }; + Ok(json!({"step": "S8", "machine_id": rec.machine_id, + "constraints": of("constraint"), "authorizations": of("authorization"), + "effects": of("effect"), "repairs": of("repair_tail"), "recall": rec})) + } + "shutdown" => { + AienRuntimeClient::default_client().shutdown().await?; + Ok(json!({"step": "S7", "shutdown": true})) + } + "recover" => match send(ControlCommand::RecoverComposeHome).await? { + ControlResponse::ComposeRecovered(r) => Ok(json!({"repair": r, "opens": r.opens})), + other => Err(format!("unexpected response {other:?}")), + }, + other => Err(format!( + "unknown compose step {other:?} (remember, inspect, propose, authorize, execute, explain, recall, shutdown, recover)" + )), + } +} + +pub async fn handle_compose_command(args: &[String]) { + let Some(sub) = args.first() else { + println!( + "{}", + json!({"ok": false, "error": "usage: aien compose [--flag value ...]"}) + ); + std::process::exit(1); + }; + let out = match flags(&args[1..]) { + Ok(m) => step(sub, &m).await, + Err(e) => Err(e), + }; + match out { + Ok(mut v) => { + v["ok"] = json!(true); + println!("{v}"); + } + Err(e) => { + println!("{}", json!({"ok": false, "step": sub, "error": e})); + std::process::exit(1); + } + } +} diff --git a/crates/aien-cli/src/main.rs b/crates/aien-cli/src/main.rs index 7665e502..e4a2964f 100644 --- a/crates/aien-cli/src/main.rs +++ b/crates/aien-cli/src/main.rs @@ -2,6 +2,7 @@ mod client; mod commands; pub mod compaction; +mod compose; mod context7; pub mod cortex; mod crumbs; @@ -56,6 +57,10 @@ async fn main() { commands::handle_stop_command().await; return; } + if args[1] == "compose" { + compose::handle_compose_command(&args[2..]).await; + return; + } if args[1] == "--status" || args[1] == "status" { commands::handle_status_command().await; return; diff --git a/crates/aien-cli/src/tools.rs b/crates/aien-cli/src/tools.rs index ba450a9f..c90a6590 100644 --- a/crates/aien-cli/src/tools.rs +++ b/crates/aien-cli/src/tools.rs @@ -428,7 +428,7 @@ pub fn dispatch_tool(name: &str, args: &Value) -> Value { } } - record_effect_receipt(name, args, &final_res, success); + let _ = record_effect_receipt(name, args, &final_res, success); let elapsed = start.elapsed().as_millis(); print_tool_done(name, elapsed, success); @@ -437,7 +437,15 @@ pub fn dispatch_tool(name: &str, args: &Value) -> Value { /// Persist a content-addressed, secret-free receipt for every tool effect. /// Arguments and results are hashed, never copied into the receipt. -fn record_effect_receipt(tool: &str, args: &Value, result: &Value, success: bool) { +/// Writes one effect receipt under `$AIEN_PROVENANCE_DIR` and returns its path +/// (None when it could not be written). NEXT-PHASE-1 `aien compose` cites the +/// returned file by its sha256. +pub(crate) fn record_effect_receipt( + tool: &str, + args: &Value, + result: &Value, + success: bool, +) -> Option { let digest = |value: &Value| { let bytes = serde_json::to_vec(value).unwrap_or_default(); format!("sha256:{}", hex::encode(Sha256::digest(bytes))) @@ -455,7 +463,7 @@ fn record_effect_receipt(tool: &str, args: &Value, result: &Value, success: bool .map(std::path::PathBuf::from) .unwrap_or_else(|_| std::path::PathBuf::from("/tmp/aien-provenance")); if std::fs::create_dir_all(&dir).is_err() { - return; + return None; } let id = format!( "{}-{}", @@ -463,9 +471,9 @@ fn record_effect_receipt(tool: &str, args: &Value, result: &Value, success: bool std::process::id() ); let path = dir.join(format!("{}.json", id)); - if let Ok(bytes) = serde_json::to_vec_pretty(&receipt) { - let _ = std::fs::write(path, bytes); - } + let bytes = serde_json::to_vec_pretty(&receipt).ok()?; + std::fs::write(&path, bytes).ok()?; + Some(path) } fn validate_tool_path(path: &str) -> Result { @@ -1089,7 +1097,7 @@ mod tests { fn effect_receipt_is_hashed_and_secret_free() { let dir = tempfile::tempdir().unwrap(); std::env::set_var("AIEN_PROVENANCE_DIR", dir.path()); - record_effect_receipt( + let _ = record_effect_receipt( "write_to_file", &json!({"path":"/tmp/receipt-test","content":"secret-value"}), &json!({"status":"ok"}), diff --git a/crates/aien-omega-compose/Cargo.toml b/crates/aien-omega-compose/Cargo.toml new file mode 100644 index 00000000..1d38fde5 --- /dev/null +++ b/crates/aien-omega-compose/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "aien-omega-compose" +version = "0.1.0" +edition = "2021" +authors = ["Drake Stapleton "] +description = "FFI to omega COMPOSITION-2 (librx_compose.a, rxc_host ABI): goals through J-Space, AEGIS and Cortex" +license.workspace = true +build = "build.rs" + +[dependencies] +sha2 = "0.10" + +[dev-dependencies] +tempfile = "3.10" diff --git a/crates/aien-omega-compose/README.md b/crates/aien-omega-compose/README.md new file mode 100644 index 00000000..705da448 --- /dev/null +++ b/crates/aien-omega-compose/README.md @@ -0,0 +1,48 @@ +# aien-omega-compose + +Rust binding to omega COMPOSITION-2 through the rxc_host C ABI +(`src/runtime/rxc_host_abi.h`, archive `build/librx_compose.a`, make target +in omega `mk/rx_compose_lib.mk`). NEXT-PHASE-1 cut 1b. + +## Building against omega + +The library is built from an omega checkout whose HEAD must equal `omega.lock` +(the same pin aien-omega-gpu uses; since NEXT-PHASE-1 it is omega 62b6a28, which +contains `librx_compose.a`). Default build, no override: + +```text +AIEN_OMEGA_DIR= +AIEN_PHYSICS_DIR= +AIEN_AIENOS_LOCK_REPO= +cargo test -p aien-omega-compose +``` + +| Variable | Meaning | +|----------|---------| +| `AIEN_OMEGA_DIR` | omega checkout at `omega.lock`; shared with aien-omega-gpu | +| `AIEN_OMEGA_COMPOSE_DIR` | a different omega checkout for this crate only (takes precedence over `AIEN_OMEGA_DIR`) | +| `AIEN_OMEGA_COMPOSE_SHA` | **developer override**: full 40-hex sha the checkout must be at instead of `omega.lock`, for building against an unmerged omega branch. Prints a build warning; never used for a release build or a campaign receipt. | +| `AIEN_PHYSICS_DIR` | physics checkout at omega's `physics.lock` (default `/../physics`) | +| `AIEN_AIENOS_LOCK_REPO` | aienos clone holding omega's `aienos.lock` commit (passed as `AIENOS_LOCK_REPO`) | +| `AIEN_OMEGA_COMPOSE_LIB` | link a prebuilt `librx_compose.a` instead (not sha-checked) | +| `AIEN_FORCE_CPU_STUB=1` | stub: every call returns `ComposeError::Unavailable` | + +With no checkout and no library set the crate builds the stub and prints a warning. +Use `AIEN_OMEGA_COMPOSE_DIR` together with `AIEN_OMEGA_COMPOSE_SHA`, so an override +never changes the checkout aien-omega-gpu checks against `omega.lock`. + +The integration test (`tests/compose.rs`) is ignored in a stub build. + +## Semantics (from the C header) + +- `open` binds the directory to one AienMachineId (`machine.id`); another + machine is refused. The Cortex journal is `/cortex.cx`. +- `register_skill` before the first `run`/`recall`/`info`. At most 2 Skills. + Callbacks run on omega World worker threads. +- `run(task, now_us)`: the Skills compete on staged J-Space branches, AEGIS + checks each result with the `set_verify` callback, the winner commits. + The result carries the Cortex record ids, branch count and verdict. +- A reopen appends records; pre-restart records stay an unchanged prefix. +- Torn journal tail: `refuse_torn = true` refuses without touching the file; + otherwise it is repaired when it lies past the last commit, and refused + explicitly (stably) when it lies inside the committed record. diff --git a/crates/aien-omega-compose/build.rs b/crates/aien-omega-compose/build.rs new file mode 100644 index 00000000..ff7ef456 --- /dev/null +++ b/crates/aien-omega-compose/build.rs @@ -0,0 +1,132 @@ +//! Links omega `librx_compose.a` (COMPOSITION-2 + the rxc_host ABI facade). +//! +//! Offline: nothing is downloaded. Order: +//! 1. `AIEN_FORCE_CPU_STUB=1` -> stub (no library; every call returns +//! `ComposeError::Unavailable`). +//! 2. `AIEN_OMEGA_COMPOSE_LIB=` -> link that prebuilt archive (not sha-checked). +//! 3. `AIEN_OMEGA_COMPOSE_DIR=`, else `AIEN_OMEGA_DIR` (the checkout +//! aien-omega-gpu builds from) -> its HEAD must equal omega.lock, then +//! `make /librx_compose.a` runs in it. `AIEN_OMEGA_COMPOSE_SHA=<40-hex>` +//! replaces the expected sha: a documented developer override for building +//! against an unmerged omega branch, never used for a release or a receipt. `AIEN_PHYSICS_DIR` (default `/../physics`) is passed +//! as PHYSICS_DIR and `AIEN_AIENOS_LOCK_REPO` (if set) as AIENOS_LOCK_REPO; +//! omega's own lock checks still run. +//! 4. otherwise -> stub, with a build warning. +//! +//! `AIEN_OMEGA_COMPOSE_DIR` exists so a developer override never touches the +//! checkout aien-omega-gpu checks against omega.lock. +//! `cfg(has_omega_compose)` is set only when the real library is linked. +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn main() { + println!("cargo:rustc-check-cfg=cfg(has_omega_compose)"); + for v in [ + "AIEN_FORCE_CPU_STUB", + "AIEN_OMEGA_COMPOSE_LIB", + "AIEN_OMEGA_COMPOSE_DIR", + "AIEN_OMEGA_DIR", + "AIEN_OMEGA_COMPOSE_SHA", + "AIEN_PHYSICS_DIR", + "AIEN_AIENOS_LOCK_REPO", + ] { + println!("cargo:rerun-if-env-changed={v}"); + } + let lock_path = Path::new(&env("CARGO_MANIFEST_DIR")).join("../../omega.lock"); + println!("cargo:rerun-if-changed={}", lock_path.display()); + let pinned = std::fs::read_to_string(&lock_path) + .unwrap_or_else(|e| panic!("cannot read {}: {e}", lock_path.display())) + .trim() + .to_string(); + assert!(is_sha(&pinned), "omega.lock must hold one full 40-hex sha"); + let expected = match std::env::var("AIEN_OMEGA_COMPOSE_SHA") { + Ok(s) => { + let s = s.trim().to_string(); + assert!( + is_sha(&s), + "AIEN_OMEGA_COMPOSE_SHA must be a full 40-hex sha" + ); + println!("cargo:warning=aien-omega-compose: AIEN_OMEGA_COMPOSE_SHA={s} overrides omega.lock {pinned} (developer override, not omega.lock)"); + s + } + Err(_) => pinned.clone(), + }; + println!("cargo:rustc-env=AIEN_OMEGA_COMPOSE_EXPECTED_SHA={expected}"); + + if std::env::var("AIEN_FORCE_CPU_STUB").as_deref() == Ok("1") { + return; + } + if let Ok(lib) = std::env::var("AIEN_OMEGA_COMPOSE_LIB") { + let lib = PathBuf::from(lib); + assert!( + lib.is_file(), + "AIEN_OMEGA_COMPOSE_LIB {} is not a file", + lib.display() + ); + link(&lib); + return; + } + let Ok(dir) = + std::env::var("AIEN_OMEGA_COMPOSE_DIR").or_else(|_| std::env::var("AIEN_OMEGA_DIR")) + else { + println!("cargo:warning=aien-omega-compose: no AIEN_OMEGA_COMPOSE_DIR, AIEN_OMEGA_DIR or AIEN_OMEGA_COMPOSE_LIB, building the stub"); + return; + }; + let dir = PathBuf::from(dir); + let head = Command::new("git") + .arg("-C") + .arg(&dir) + .args(["rev-parse", "HEAD"]) + .output() + .ok() + .filter(|o| o.status.success()) + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) + .unwrap_or_default(); + assert!( + head == expected, + "omega checkout {} is at '{head}', expected {expected}", + dir.display() + ); + let physics = std::env::var("AIEN_PHYSICS_DIR") + .map(PathBuf::from) + .unwrap_or_else(|_| dir.join("../physics")); + let out = PathBuf::from(env("OUT_DIR")).join("omega-compose-build"); + std::fs::create_dir_all(&out).expect("create omega build dir"); + let mut make = Command::new("make"); + make.current_dir(&dir) + .env_remove("MAKEFLAGS") + .env_remove("MFLAGS") + .arg(format!("OUT_DIR={}", out.display())) + .arg(format!("PHYSICS_DIR={}", physics.display())); + if let Ok(repo) = std::env::var("AIEN_AIENOS_LOCK_REPO") { + make.arg(format!("AIENOS_LOCK_REPO={repo}")); + } + let status = make + .arg(out.join("librx_compose.a")) + .status() + .expect("run make"); + assert!( + status.success(), + "make librx_compose.a failed in {}", + dir.display() + ); + link(&out.join("librx_compose.a")); +} + +fn link(lib: &Path) { + let dir = lib.parent().expect("lib has a parent dir"); + println!("cargo:rustc-link-search=native={}", dir.display()); + println!("cargo:rustc-link-lib=static=rx_compose"); + println!("cargo:rustc-link-lib=dylib=pthread"); + println!("cargo:rustc-link-lib=dylib=m"); + println!("cargo:rerun-if-changed={}", lib.display()); + println!("cargo:rustc-cfg=has_omega_compose"); +} + +fn is_sha(s: &str) -> bool { + s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +fn env(k: &str) -> String { + std::env::var(k).unwrap_or_else(|_| panic!("{k} not set")) +} diff --git a/crates/aien-omega-compose/src/ffi.rs b/crates/aien-omega-compose/src/ffi.rs new file mode 100644 index 00000000..a2ce401d --- /dev/null +++ b/crates/aien-omega-compose/src/ffi.rs @@ -0,0 +1,184 @@ +//! Raw declarations of omega `src/runtime/rxc_host_abi.h` (ABI version 1). +//! Layouts are `#[repr(C)]` mirrors; `Compose::open` compares their sizes with +//! `rxc_host_abi_layout` before any other call. +#![allow(non_camel_case_types)] + +#[cfg(has_omega_compose)] +use std::os::raw::c_char; +use std::os::raw::{c_int, c_void}; + +pub const RXC_HOST_ABI_VERSION: u32 = 2; +pub const RXC_HOST_NONE: u32 = 0xFFFF_FFFF; +pub const RXC_HOST_SUBJECT_GOAL: u64 = 1; +pub const RXC_HOST_SUBJECT_STATE: u64 = 5; +/// Host records (notes, repair records): no World object. +pub const RXC_HOST_SUBJECT_HOST: u64 = 0; +pub const RXC_HOST_TAG_REPAIR_TAIL: u64 = 1; +pub const RXC_HOST_NOTE_CONSTRAINT: u32 = 2; +pub const RXC_HOST_NOTE_AUTHORIZATION: u32 = 3; +pub const RXC_HOST_NOTE_EFFECT: u32 = 4; +pub const RXC_HOST_NOTE_MAX: usize = 16384; +pub const RXC_HOST_NP_LEN: usize = 0; +pub const RXC_HOST_NP_SHA: usize = 1; +pub const RXC_HOST_NP_BYTES: usize = 5; +pub const RXC_HOST_RP_CUT_LO: usize = 0; +pub const RXC_HOST_RP_CUT_HI: usize = 1; +pub const RXC_HOST_RP_DROPPED: usize = 5; +pub const RXC_HOST_RP_CAUSE: usize = 6; + +pub const RXC_HOST_OK: c_int = 0; +pub const RXC_HOST_E_ARG: c_int = -1; +pub const RXC_HOST_E_IDENTITY: c_int = -2; +pub const RXC_HOST_E_TORN: c_int = -3; +pub const RXC_HOST_E_OPEN: c_int = -4; +pub const RXC_HOST_E_FULL: c_int = -5; +pub const RXC_HOST_E_STATE: c_int = -6; +pub const RXC_HOST_E_RUN: c_int = -7; +pub const RXC_HOST_E_NOMEM: c_int = -8; +pub const RXC_HOST_E_NOT_FOUND: c_int = -9; +pub const RXC_HOST_E_DIGEST: c_int = -10; +pub const RXC_HOST_E_REPLAY: c_int = -11; + +#[repr(C)] +pub struct RxcHost { + _private: [u8; 0], +} + +pub type RxcHostSkillFn = + unsafe extern "C" fn(ctx: *mut c_void, task: u64, result: *mut u64) -> c_int; +pub type RxcHostVerifyFn = unsafe extern "C" fn(ctx: *mut c_void, task: u64, result: u64) -> c_int; + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct RxcHostInfo { + pub abi_version: u32, + pub machine_root: u8, + pub machine_id: [u8; 32], + pub machine_id_was_stored: u32, + pub tail_torn: u32, + pub opened: u32, + pub open_rc: i32, + pub records: u64, + pub recovered_record: u64, + pub rolled_back: u32, + pub recovered_completed: u32, + pub anchor_unknown: u32, + pub n_skills: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct RxcHostResult { + pub run_rc: i32, + pub outcome: i32, + pub committed: u32, + pub n_branches: u32, + pub branches_reclaimed: u32, + pub winner: u32, + pub winner_skill: u32, + pub aegis_pass_mask: u32, + pub task: u64, + pub result: u64, + pub cx_goal: u64, + pub cx_candidate: [u64; 2], + pub cx_evidence: u64, + pub cx_promotion: u64, + pub cx_admission: [u64; 2], + pub winner_digest: [u8; 32], + pub record_digest: [u8; 32], +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct RxcHostRecord { + pub id: u64, + pub cls: u32, + pub kind: u32, + pub subject: u64, + pub t: u64, + pub generation: u64, + pub tag: u64, + pub links: [u64; 4], + pub n_payload: u32, + pub verified: u32, + pub digest: [u8; 32], +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub struct RxcHostRepair { + pub repaired: u32, + pub tail_torn: u32, + pub anchor_present: u32, + pub cause: i32, + pub opens: u32, + pub open_rc: i32, + pub rolled_back: u32, + pub recovered_completed: u32, + pub cut_lo: u64, + pub cut_hi: u64, + pub partial_records: u64, + pub anchor_records: u64, + pub records_kept: u64, + pub dropped_records: u64, + pub event_id: u64, + pub cut_bytes_kept: u64, + pub cut_sha256: [u8; 32], + pub anchor_head: [u8; 32], +} + +#[cfg(has_omega_compose)] +extern "C" { + pub fn rxc_host_abi_layout(out: *mut u32) -> u32; + pub fn rxc_host_open( + dir: *const c_char, + root_kind: u32, + root: *const u8, + root_len: usize, + session: u64, + flags: u32, + out: *mut *mut RxcHost, + info: *mut RxcHostInfo, + ) -> c_int; + pub fn rxc_host_register_skill( + h: *mut RxcHost, + name: *const c_char, + digest32: *const u8, + cost: u64, + f: RxcHostSkillFn, + ctx: *mut c_void, + ) -> c_int; + pub fn rxc_host_set_verify( + h: *mut RxcHost, + f: Option, + ctx: *mut c_void, + ) -> c_int; + pub fn rxc_host_run(h: *mut RxcHost, task: u64, now_us: u64, out: *mut RxcHostResult) -> c_int; + pub fn rxc_host_recall( + h: *mut RxcHost, + subject: u64, + out: *mut RxcHostRecord, + max: u32, + n_filled: *mut u32, + n_total: *mut u64, + ) -> c_int; + pub fn rxc_host_record(h: *mut RxcHost, id: u64, out: *mut RxcHostRecord) -> c_int; + pub fn rxc_host_payload(h: *mut RxcHost, id: u64, out: *mut u64, max: u32) -> c_int; + pub fn rxc_host_info(h: *mut RxcHost, info: *mut RxcHostInfo) -> c_int; + pub fn rxc_host_note( + h: *mut RxcHost, + note: u32, + links: *const u64, + bytes: *const u8, + len: usize, + out_id: *mut u64, + ) -> c_int; + pub fn rxc_host_recover( + dir: *const c_char, + root_kind: u32, + root: *const u8, + root_len: usize, + out: *mut RxcHostRepair, + ) -> c_int; + pub fn rxc_host_close(h: *mut RxcHost); +} diff --git a/crates/aien-omega-compose/src/lib.rs b/crates/aien-omega-compose/src/lib.rs new file mode 100644 index 00000000..7ef0cd96 --- /dev/null +++ b/crates/aien-omega-compose/src/lib.rs @@ -0,0 +1,506 @@ +//! Safe binding to omega COMPOSITION-2 through the rxc_host ABI +//! (`src/runtime/rxc_host_abi.h`, linked from `librx_compose.a`). +//! +//! One goal = one `Compose::run`: the registered Skills compete on staged +//! J-Space branches, the AEGIS verifier checks each result against the +//! contract (the `set_verify` callback), the winner is committed to the World +//! and the whole composition is recorded in the Cortex journal +//! `/cortex.cx`. Records and their digests survive a restart; the +//! directory is bound to one AienMachineId. +//! +//! Without the library (stub build, see build.rs) every constructor returns +//! [`ComposeError::Unavailable`] and [`LINKED`] is false. +pub mod ffi; + +use std::fmt; +use std::path::Path; + +/// True when `librx_compose.a` is linked (not the stub). +pub const LINKED: bool = cfg!(has_omega_compose); +/// The omega commit this build expected (omega.lock or `AIEN_OMEGA_COMPOSE_SHA`). +pub const EXPECTED_OMEGA_SHA: &str = env!("AIEN_OMEGA_COMPOSE_EXPECTED_SHA"); +pub use ffi::{RXC_HOST_SUBJECT_GOAL as SUBJECT_GOAL, RXC_HOST_SUBJECT_STATE as SUBJECT_STATE}; +/// No winner / no Skill. +pub const NONE: u32 = ffi::RXC_HOST_NONE; + +/// Composition outcomes (`RXC_HOST_OUT_*`). +pub const OUT_COMMITTED: i32 = 1; +pub const OUT_NO_WINNER: i32 = 2; +pub const OUT_NOT_COMMITTED: i32 = 3; +pub const OUT_NOT_DURABLE: i32 = 4; +pub const OUT_RECORD_FAILED: i32 = 5; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RootKind { + /// 1..4096 opaque bytes generated once at provisioning. + Provisioned = 1, + /// The 32-byte digest of the owner-enrolled key. + Hardware = 2, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ComposeError { + /// The library is not linked (stub build). + Unavailable, + /// Rust and C struct layouts differ (wrong omega commit). + Layout { c: [u32; 4], rust: [u32; 4] }, + /// An argument Rust refuses before calling C (interior NUL, empty name). + Arg(String), + /// `RXC_HOST_E_*` from the C side, with the underlying rx code when known. + Code { code: i32, detail: i32 }, +} + +impl ComposeError { + pub fn name(code: i32) -> &'static str { + match code { + ffi::RXC_HOST_E_ARG => "E_ARG", + ffi::RXC_HOST_E_IDENTITY => "E_IDENTITY", + ffi::RXC_HOST_E_TORN => "E_TORN", + ffi::RXC_HOST_E_OPEN => "E_OPEN", + ffi::RXC_HOST_E_FULL => "E_FULL", + ffi::RXC_HOST_E_STATE => "E_STATE", + ffi::RXC_HOST_E_RUN => "E_RUN", + ffi::RXC_HOST_E_NOMEM => "E_NOMEM", + ffi::RXC_HOST_E_NOT_FOUND => "E_NOT_FOUND", + ffi::RXC_HOST_E_DIGEST => "E_DIGEST", + ffi::RXC_HOST_E_REPLAY => "E_REPLAY", + _ => "E_UNKNOWN", + } + } +} + +impl fmt::Display for ComposeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ComposeError::Unavailable => write!(f, "librx_compose.a is not linked (stub build)"), + ComposeError::Layout { c, rust } => { + write!(f, "rxc_host ABI layout mismatch: C {c:?} vs Rust {rust:?}") + } + ComposeError::Arg(s) => write!(f, "invalid argument: {s}"), + ComposeError::Code { code, detail } => { + write!( + f, + "rxc_host {} ({code}), detail {detail}", + Self::name(*code) + ) + } + } + } +} + +impl std::error::Error for ComposeError {} + +pub type Info = ffi::RxcHostInfo; +pub type RunResult = ffi::RxcHostResult; +pub type Record = ffi::RxcHostRecord; +pub type Repair = ffi::RxcHostRepair; +pub use ffi::RXC_HOST_SUBJECT_HOST as SUBJECT_HOST; + +/// Host record kinds (`RXC_HOST_NOTE_*`), all on [`SUBJECT_HOST`]. The record tag +/// is the kind. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NoteKind { + /// CLAIM / CX_K_CLAIM: an operator constraint. + Constraint = 2, + /// EVIDENCE / CX_K_ADMISSION: an approval for one effect. + Authorization = 3, + /// EVIDENCE / CX_K_EVIDENCE_REF: an effect receipt. + Effect = 4, +} + +impl NoteKind { + pub fn from_tag(tag: u64) -> Option { + match tag { + 2 => Some(Self::Constraint), + 3 => Some(Self::Authorization), + 4 => Some(Self::Effect), + _ => None, + } + } + pub fn name(self) -> &'static str { + match self { + Self::Constraint => "constraint", + Self::Authorization => "authorization", + Self::Effect => "effect", + } + } +} + +/// The bytes of a host note payload (`[len, sha256 x4, bytes...]`), or None +/// when the payload is short or its sha256 does not match the bytes. +pub fn note_bytes(payload: &[u64]) -> Option> { + use sha2::{Digest, Sha256}; + let len = *payload.get(ffi::RXC_HOST_NP_LEN)? as usize; + let words = payload.get(ffi::RXC_HOST_NP_BYTES..)?; + if len > words.len() * 8 { + return None; + } + let bytes: Vec = words + .iter() + .flat_map(|w| w.to_le_bytes()) + .take(len) + .collect(); + let sha: Vec = payload + .get(ffi::RXC_HOST_NP_SHA..ffi::RXC_HOST_NP_SHA + 4)? + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + (Sha256::digest(&bytes).as_slice() == sha.as_slice()).then_some(bytes) +} + +/// Lower-case hex of a byte slice. +pub fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +type SkillFn = dyn Fn(u64) -> Option + Send + Sync; +type VerifyFn = dyn Fn(u64, u64) -> bool + Send + Sync; + +/// An open composition home. Calls take `&mut self`: one caller at a time. +/// Skill and verify callbacks run on omega World worker threads (two Skills +/// may run at once), hence `Send + Sync`. +pub struct Compose { + #[cfg_attr(not(has_omega_compose), allow(dead_code))] + h: *mut ffi::RxcHost, + // Boxed so the ctx pointers handed to C stay put; dropped after close. + #[allow(clippy::vec_box, dead_code)] + skills: Vec>>, + #[allow(dead_code)] + verify: Option>>, +} + +// SAFETY: the handle is only used through &mut self (one thread at a time); +// the C side's own worker threads only call the Send + Sync callbacks. +unsafe impl Send for Compose {} + +#[cfg(has_omega_compose)] +mod linked { + use super::*; + use std::ffi::CString; + use std::os::raw::{c_int, c_void}; + use std::panic::{catch_unwind, AssertUnwindSafe}; + + fn check(rc: c_int, detail: i32) -> Result<(), ComposeError> { + if rc == ffi::RXC_HOST_OK { + Ok(()) + } else { + Err(ComposeError::Code { code: rc, detail }) + } + } + + unsafe extern "C" fn skill_tramp(ctx: *mut c_void, task: u64, result: *mut u64) -> c_int { + let f = &*(ctx as *const Box); + match catch_unwind(AssertUnwindSafe(|| f(task))) { + Ok(Some(r)) if r != 0 => { + *result = r; + 0 + } + _ => 1, + } + } + + unsafe extern "C" fn verify_tramp(ctx: *mut c_void, task: u64, result: u64) -> c_int { + let f = &*(ctx as *const Box); + matches!(catch_unwind(AssertUnwindSafe(|| f(task, result))), Ok(true)) as c_int + } + + fn layout() -> Result<(), ComposeError> { + let mut c = [0u32; 4]; + // SAFETY: writes exactly four u32. + let v = unsafe { ffi::rxc_host_abi_layout(c.as_mut_ptr()) }; + let rust = [ + std::mem::size_of::() as u32, + std::mem::size_of::() as u32, + std::mem::size_of::() as u32, + std::mem::size_of::() as u32, + ]; + if v != ffi::RXC_HOST_ABI_VERSION || c != rust { + return Err(ComposeError::Layout { c, rust }); + } + Ok(()) + } + + impl Compose { + pub fn open( + dir: &Path, + root_kind: RootKind, + root: &[u8], + session: u64, + ) -> Result<(Self, Info), ComposeError> { + layout()?; + use std::os::unix::ffi::OsStrExt; + let d = CString::new(dir.as_os_str().as_bytes()) + .map_err(|_| ComposeError::Arg("dir holds a NUL byte".into()))?; + let mut h = std::ptr::null_mut(); + let mut info = Info::default(); + // SAFETY: valid C string, root slice, out pointers. + let rc = unsafe { + ffi::rxc_host_open( + d.as_ptr(), + root_kind as u32, + root.as_ptr(), + root.len(), + session, + 0, + &mut h, + &mut info, + ) + }; + check(rc, info.open_rc)?; + Ok(( + Compose { + h, + skills: Vec::new(), + verify: None, + }, + info, + )) + } + + pub fn register_skill( + &mut self, + name: &str, + digest: Option<[u8; 32]>, + cost: u64, + f: F, + ) -> Result + where + F: Fn(u64) -> Option + Send + Sync + 'static, + { + let n = CString::new(name) + .map_err(|_| ComposeError::Arg("name holds a NUL byte".into()))?; + let b: Box> = Box::new(Box::new(f)); + let ctx = &*b as *const Box as *mut c_void; + let dp = digest.as_ref().map_or(std::ptr::null(), |d| d.as_ptr()); + // SAFETY: ctx outlives the handle (dropped after close in Drop). + let rc = unsafe { + ffi::rxc_host_register_skill(self.h, n.as_ptr(), dp, cost, skill_tramp, ctx) + }; + if rc < 0 { + return Err(ComposeError::Code { + code: rc, + detail: 0, + }); + } + self.skills.push(b); + Ok(rc as u32) + } + + pub fn set_verify(&mut self, f: F) -> Result<(), ComposeError> + where + F: Fn(u64, u64) -> bool + Send + Sync + 'static, + { + let b: Box> = Box::new(Box::new(f)); + let ctx = &*b as *const Box as *mut c_void; + // SAFETY: as register_skill. + let rc = unsafe { ffi::rxc_host_set_verify(self.h, Some(verify_tramp), ctx) }; + check(rc, 0)?; + self.verify = Some(b); + Ok(()) + } + + pub fn run(&mut self, task: u64, now_us: u64) -> Result { + let mut r = RunResult::default(); + // SAFETY: valid handle and out pointer. + let rc = unsafe { ffi::rxc_host_run(self.h, task, now_us, &mut r) }; + check(rc, r.run_rc)?; + Ok(r) + } + + /// Records of `subject`, oldest first (at most `max`), and how many exist. + pub fn recall( + &mut self, + subject: u64, + max: u32, + ) -> Result<(Vec, u64), ComposeError> { + let mut v = vec![Record::default(); max as usize]; + let (mut n, mut total) = (0u32, 0u64); + // SAFETY: v holds max records. + let rc = unsafe { + ffi::rxc_host_recall(self.h, subject, v.as_mut_ptr(), max, &mut n, &mut total) + }; + check(rc, 0)?; + v.truncate(n as usize); + Ok((v, total)) + } + + pub fn record(&mut self, id: u64) -> Result { + let mut r = Record::default(); + // SAFETY: valid handle and out pointer. + let rc = unsafe { ffi::rxc_host_record(self.h, id, &mut r) }; + check(rc, 0)?; + Ok(r) + } + + pub fn payload(&mut self, id: u64) -> Result, ComposeError> { + // SAFETY: max 0 only asks for the count. + let n = unsafe { ffi::rxc_host_payload(self.h, id, std::ptr::null_mut(), 0) }; + if n < 0 { + return Err(ComposeError::Code { code: n, detail: 0 }); + } + let mut v = vec![0u64; n as usize]; + // SAFETY: v holds n words. + let m = unsafe { ffi::rxc_host_payload(self.h, id, v.as_mut_ptr(), n as u32) }; + if m < 0 { + return Err(ComposeError::Code { code: m, detail: 0 }); + } + Ok(v) + } + + pub fn info(&mut self) -> Result { + let mut i = Info::default(); + // SAFETY: valid handle and out pointer. + let rc = unsafe { ffi::rxc_host_info(self.h, &mut i) }; + check(rc, i.open_rc)?; + Ok(i) + } + + /// Append one host record through the composition's Cortex writer + /// (between runs). `links` name related Cortex ids (0 = none); each + /// must exist. Returns the new record id. + pub fn note( + &mut self, + kind: NoteKind, + links: [u64; 4], + bytes: &[u8], + ) -> Result { + if bytes.is_empty() || bytes.len() > ffi::RXC_HOST_NOTE_MAX { + return Err(ComposeError::Arg(format!( + "note of {} bytes (1..={})", + bytes.len(), + ffi::RXC_HOST_NOTE_MAX + ))); + } + let mut id = 0u64; + // SAFETY: valid handle, 4 links, byte slice, out pointer. + let rc = unsafe { + ffi::rxc_host_note( + self.h, + kind as u32, + links.as_ptr(), + bytes.as_ptr(), + bytes.len(), + &mut id, + ) + }; + check(rc, 0)?; + Ok(id) + } + + /// Operator repair of a refused home (no handle may be open on it). + /// `Ok` when nothing needed repair or the repair left a home that + /// opens (`opens == 1`), and also when the cut was recorded but the + /// composition still refuses (`repaired == 1, opens == 0`: the caller + /// must report it). `Err` when nothing was repaired. + pub fn recover( + dir: &Path, + root_kind: RootKind, + root: &[u8], + ) -> Result { + layout()?; + use std::os::unix::ffi::OsStrExt; + let d = CString::new(dir.as_os_str().as_bytes()) + .map_err(|_| ComposeError::Arg("dir holds a NUL byte".into()))?; + let mut r = Repair::default(); + // SAFETY: valid C string, root slice, out pointer. + let rc = unsafe { + ffi::rxc_host_recover( + d.as_ptr(), + root_kind as u32, + root.as_ptr(), + root.len(), + &mut r, + ) + }; + if rc == ffi::RXC_HOST_OK || (rc == ffi::RXC_HOST_E_REPLAY && r.repaired == 1) { + return Ok(r); + } + Err(ComposeError::Code { + code: rc, + detail: r.open_rc, + }) + } + } + + impl Drop for Compose { + fn drop(&mut self) { + // SAFETY: close stops every World worker before returning, so no + // callback runs after this; the boxes drop afterwards. + unsafe { ffi::rxc_host_close(self.h) }; + self.h = std::ptr::null_mut(); + } + } +} + +#[cfg(not(has_omega_compose))] +impl Compose { + pub fn open(_: &Path, _: RootKind, _: &[u8], _: u64) -> Result<(Self, Info), ComposeError> { + Err(ComposeError::Unavailable) + } + pub fn register_skill( + &mut self, + _: &str, + _: Option<[u8; 32]>, + _: u64, + _: F, + ) -> Result + where + F: Fn(u64) -> Option + Send + Sync + 'static, + { + Err(ComposeError::Unavailable) + } + pub fn set_verify(&mut self, _: F) -> Result<(), ComposeError> + where + F: Fn(u64, u64) -> bool + Send + Sync + 'static, + { + Err(ComposeError::Unavailable) + } + pub fn run(&mut self, _: u64, _: u64) -> Result { + Err(ComposeError::Unavailable) + } + pub fn recall(&mut self, _: u64, _: u32) -> Result<(Vec, u64), ComposeError> { + Err(ComposeError::Unavailable) + } + pub fn record(&mut self, _: u64) -> Result { + Err(ComposeError::Unavailable) + } + pub fn payload(&mut self, _: u64) -> Result, ComposeError> { + Err(ComposeError::Unavailable) + } + pub fn info(&mut self) -> Result { + Err(ComposeError::Unavailable) + } + pub fn note(&mut self, _: NoteKind, _: [u64; 4], _: &[u8]) -> Result { + Err(ComposeError::Unavailable) + } + pub fn recover(_: &Path, _: RootKind, _: &[u8]) -> Result { + Err(ComposeError::Unavailable) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stub_or_linked_is_reported() { + let dir = + std::env::temp_dir().join(format!("aien-omega-compose-unit-{}", std::process::id())); + let r = Compose::open(&dir, RootKind::Provisioned, b"unit", 1); + match &r { + Ok(_) => { + if !LINKED { + panic!("stub build opened a home"); + } + } + Err(e) => { + if LINKED { + panic!("linked build failed to open: {e}"); + } + assert_eq!(*e, ComposeError::Unavailable); + } + } + drop(r); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/aien-omega-compose/tests/compose.rs b/crates/aien-omega-compose/tests/compose.rs new file mode 100644 index 00000000..d6e89b4b --- /dev/null +++ b/crates/aien-omega-compose/tests/compose.rs @@ -0,0 +1,158 @@ +//! The omega C test (tests/runtime/rxc_host_abi_test.c) repeated from Rust: +//! run one goal, restart + recall, identity refusal, torn tail refused then +//! recovered, host notes recalled after restart. Ignored +//! unless librx_compose.a is linked (AIEN_OMEGA_COMPOSE_DIR or +//! AIEN_OMEGA_COMPOSE_LIB at build time; see build.rs / README.md). +use aien_omega_compose::*; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +const ROOT: &[u8] = b"np1-host-abi-test-machine"; +fn propose(t: u64) -> u64 { + t.wrapping_mul(3).wrapping_add(1) +} + +fn open(dir: &std::path::Path, seen: Arc) -> Result<(Compose, Info), ComposeError> { + let (mut c, info) = Compose::open(dir, RootKind::Provisioned, ROOT, 0x5E55)?; + c.register_skill("np1.echo-proposal", None, 10, move |task| { + seen.store(task, Ordering::SeqCst); + Some(propose(task)) + })?; + c.set_verify(|task, result| result == propose(task))?; + Ok((c, info)) +} + +#[test] +#[cfg_attr( + not(has_omega_compose), + ignore = "needs librx_compose.a (AIEN_OMEGA_COMPOSE_DIR)" +)] +fn run_restart_recall_torn_tail() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let seen = Arc::new(AtomicU64::new(0)); + + // T1: one goal + let (mut c, i1) = open(&home, seen.clone()).unwrap(); + assert_eq!(i1.abi_version, 2); + assert_eq!(i1.machine_id_was_stored, 0); + let task = 0x4E50_3100_0000_0001u64; + let r = c.run(task, 1_000_000).unwrap(); + assert_eq!(r.outcome, OUT_COMMITTED); + assert_eq!(r.committed, 1); + assert_eq!(seen.load(Ordering::SeqCst), task); + assert_eq!(r.result, propose(task)); + assert_eq!((r.n_branches, r.winner, r.winner_skill), (1, 0, 0)); + assert_eq!(r.aegis_pass_mask & 1, 1); + let cited = [r.cx_goal, r.cx_candidate[0], r.cx_evidence, r.cx_promotion]; + assert!(cited.iter().all(|&id| id != 0), "{cited:?}"); + let cited_digests: Vec<[u8; 32]> = cited + .iter() + .map(|&id| c.record(id).unwrap().digest) + .collect(); + let (before, total) = c.recall(SUBJECT_STATE, 64).unwrap(); + assert!(!before.is_empty() && before.len() as u64 == total); + let mid = c.info().unwrap().machine_id; + drop(c); + + // T2: restart + recall (pre-restart records are an unchanged prefix) + let (mut c, i2) = open(&home, seen.clone()).unwrap(); + assert_eq!(i2.machine_id_was_stored, 1); + assert_eq!(i2.machine_id, mid); + assert_eq!(i2.tail_torn, 0); + let (after, _) = c.recall(SUBJECT_STATE, 64).unwrap(); + assert!(after.len() >= before.len()); + for (a, b) in after.iter().zip(before.iter()) { + assert_eq!((a.id, a.digest, a.verified), (b.id, b.digest, 1)); + } + for (id, d) in cited.iter().zip(cited_digests.iter()) { + assert_eq!(&c.record(*id).unwrap().digest, d); + } + drop(c); + + // T3: another machine is refused on this home + let other = Compose::open(&home, RootKind::Provisioned, b"np1-some-other-machine", 1); + assert!(matches!( + other.err(), + Some(ComposeError::Code { code: -2, .. }) + )); + + // T5: a run's own tail torn: open refuses (E_TORN) without writing, stably; + // recover cuts the torn record, records the cut, re-anchors; open succeeds + // with the old records an unchanged prefix; a goal commits. + let (mut c, _) = open(&home, seen.clone()).unwrap(); + let r = c.run(0x4E50_3100_0000_0003, 3_000_000).unwrap(); + assert_eq!(r.committed, 1); + let n0 = c.info().unwrap().records; + let all: Vec = (1..=n0).map(|id| c.record(id).unwrap()).collect(); + drop(c); + let cx = home.join("cortex.cx"); + let len = std::fs::metadata(&cx).unwrap().len(); + let f = std::fs::OpenOptions::new().write(true).open(&cx).unwrap(); + f.set_len(len - 5).unwrap(); + drop(f); + for _ in 0..2 { + let refused = open(&home, seen.clone()); + assert!(matches!( + refused.err(), + Some(ComposeError::Code { code: -3, .. }) + )); + assert_eq!( + std::fs::metadata(&cx).unwrap().len(), + len - 5, + "refusal wrote" + ); + } + let rep = Compose::recover(&home, RootKind::Provisioned, ROOT).unwrap(); + assert_eq!( + (rep.repaired, rep.tail_torn, rep.cause, rep.opens), + (1, 1, -8, 1) + ); + assert_eq!(rep.cut_hi, len - 5); + assert_eq!(rep.cut_bytes_kept, rep.cut_hi - rep.cut_lo); + assert!(rep.dropped_records >= 1); + assert_eq!(rep.event_id, rep.records_kept + 1); + let again = Compose::recover(&home, RootKind::Provisioned, ROOT).unwrap(); + assert_eq!(again.repaired, 0, "second recover is a no-op"); + let (mut c, ir) = open(&home, seen.clone()).unwrap(); + assert_eq!(ir.tail_torn, 0); + c.info().unwrap(); + for rec in &all[..rep.records_kept as usize] { + assert_eq!(c.record(rec.id).unwrap().digest, rec.digest); + } + let ev = c.record(rep.event_id).unwrap(); + assert_eq!( + (ev.subject, ev.tag), + (SUBJECT_HOST, ffi::RXC_HOST_TAG_REPAIR_TAIL) + ); + let p = c.payload(rep.event_id).unwrap(); + assert_eq!(p[ffi::RXC_HOST_RP_CUT_LO], rep.cut_lo); + assert_eq!(p[ffi::RXC_HOST_RP_DROPPED], rep.dropped_records); + let r = c.run(0x4E50_3100_0000_0004, 4_000_000).unwrap(); + assert_eq!(r.committed, 1); + + // T7: host notes through the composition writer, recalled after restart + let text = b"constraint: only touch files under the workspace"; + let cid = c.note(NoteKind::Constraint, [0; 4], text).unwrap(); + let eid = c + .note( + NoteKind::Effect, + [r.cx_promotion, cid, 0, 0], + b"effect: wrote a.txt", + ) + .unwrap(); + assert!(eid > cid); + assert!(c.note(NoteKind::Effect, [1 << 40, 0, 0, 0], b"x").is_err()); + let (before, _) = c.recall(SUBJECT_HOST, 64).unwrap(); + drop(c); + let (mut c, i7) = open(&home, seen.clone()).unwrap(); + assert_eq!(i7.machine_id, mid); + let (after, _) = c.recall(SUBJECT_HOST, 64).unwrap(); + assert_eq!(after.len(), before.len()); + for (a, b) in after.iter().zip(before.iter()) { + assert_eq!((a.id, a.digest, a.verified), (b.id, b.digest, 1)); + } + let got = note_bytes(&c.payload(cid).unwrap()).unwrap(); + assert_eq!(got, text); + assert_eq!(c.record(eid).unwrap().links[..2], [r.cx_promotion, cid]); +} diff --git a/crates/aien-runtime/Cargo.toml b/crates/aien-runtime/Cargo.toml index ae7bdc35..596ae00a 100644 --- a/crates/aien-runtime/Cargo.toml +++ b/crates/aien-runtime/Cargo.toml @@ -15,6 +15,7 @@ aien-abi-core = { path = "../aien-abi-core" } aien-inference-abi = { path = "../aien-inference-abi" } aien-security = { path = "../aien-security" } cortex-rs = { path = "../cortex-rs" } +aien-omega-compose = { path = "../aien-omega-compose" } tokio = { version = "1.37", features = ["full"] } parking_lot = "0.12" diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index d92ebe27..93ccee31 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -59,6 +59,35 @@ pub enum ControlCommand { max_tokens: usize, temperature: f32, }, + /// NEXT-PHASE-1 cut 1b: one goal through omega COMPOSITION-2 (J-Space + /// alternatives, AEGIS verification, World commit, Cortex record) with a + /// "model" Skill that proposes one file change for `workspace`. Handled on + /// the socket connection (it runs inference). Nothing is written to + /// `workspace` in this cut: the committed result is the proposal record. + RunComposeTask { + goal: String, + workspace: String, + }, + /// NEXT-PHASE-1 cut 2: append one operator record (`kind` = "constraint", + /// "authorization" or "effect") to the composition's Cortex journal through + /// its own writer. `links` name related Cortex ids (each must exist). + ComposeNote { + kind: String, + text: String, + links: Vec, + }, + /// NEXT-PHASE-1 cut 2: recall every host record (constraints, authorizations, + /// effects, repair records) plus the records named in `ids`, each digest + /// re-checked; `prefix` (records 1..=prefix) gets a digest over their digests + /// so a restart can be compared byte for byte. + ComposeRecall { + ids: Vec, + prefix: Option, + }, + /// NEXT-PHASE-1 cut 2: operator repair of a compose home that refuses to open + /// (torn journal tail, or a journal behind its J-Space anchor). Closes this + /// process's handle first; the cut is recorded in the journal. + RecoverComposeHome, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -84,12 +113,30 @@ pub struct RuntimeStatusReport { #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ControlResponse { - SwarmAccepted { swarm_id: u64, operation_id: u128 }, - SwarmCancelled { swarm_id: u64 }, + SwarmAccepted { + swarm_id: u64, + operation_id: u128, + }, + SwarmCancelled { + swarm_id: u64, + }, Status(RuntimeStatusReport), ShutdownAck, - TurnDelta { text: String }, - TurnFinished { text: String, total_tokens: usize }, + TurnDelta { + text: String, + }, + TurnFinished { + text: String, + total_tokens: usize, + }, + /// Result record of `RunComposeTask`. + ComposeTaskResult(Box), + /// Result of `ComposeNote`. + ComposeNoted(ComposeNoteReport), + /// Result of `ComposeRecall`. + ComposeRecalled(Box), + /// Result of `RecoverComposeHome`. + ComposeRecovered(Box), Error(String), } @@ -193,3 +240,136 @@ mod tests { assert!(prompt.ends_with("<|assistant|>\n")); } } + +/// The record of one `RunComposeTask` (omega rxc_host result, NEXT-PHASE-1). +/// Cortex ids name records in `/cortex.cx`; digests are hex. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ComposeTaskReport { + /// Composition home (holds machine.id, cortex.cx, jspace). + pub compose_dir: String, + /// AienMachineId (32 bytes, hex) the home is bound to. + pub machine_id: String, + pub task: u64, + /// RXC_OUT_*: 1 committed, 2 no winner, 3 not committed, 4 not durable, 5 record failed. + pub outcome: i32, + pub committed: bool, + /// Staged J-Space branches forked (one per routed Skill alternative). + pub branch_count: u32, + pub branches_reclaimed: u32, + /// AEGIS verdict: index of the winning alternative (None = no winner) + /// and the pass mask (bit k = alternative k met the contract). + pub winner: Option, + pub aegis_pass_mask: u32, + pub cx_goal: u64, + pub cx_candidates: Vec, + pub cx_evidence: u64, + pub cx_promotion: u64, + pub cx_admissions: Vec, + pub winner_digest: String, + pub record_digest: String, + /// The committed proposal (the model Skill's output) and its sha256. + pub proposal: Option, + pub proposal_sha256: Option, + /// The proposal parsed as one file change (AEGIS contract): relative path + /// and the sha256 of the new content. + pub proposal_path: Option, + pub proposal_content_sha256: Option, + /// When nothing committed: the model text AEGIS rejected (it did not + /// parse as one file change), or why the model Skill returned nothing. + #[serde(default)] + pub uncommitted_proposal: Option, + #[serde(default)] + pub proposer_error: Option, + /// Every proposal the model Skill made for this task (ACCEPTANCE-v2 3b). + #[serde(default)] + pub proposal_attempts: Vec, + /// "model" when the Skill ran inference, or the stub label. + pub proposer: String, +} + +/// One proposal the compose "model" Skill made (ACCEPTANCE-v2 3b). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProposalAttempt { + /// 1-based. + pub attempt: u32, + /// Wall time of the model call. + pub ms: u64, + /// Generated tokens (0 when the call failed). + pub tokens: usize, + /// "parsed" | "refused" (template parser) | "timeout" | "error". + pub outcome: String, + /// Why the attempt was refused or failed. + pub reason: Option, + pub text_sha256: Option, + pub text: Option, + /// For the attempt handed to AEGIS: "pass" or "fail". + pub aegis: Option, +} + +/// The record `ComposeNote` appended. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ComposeNoteReport { + pub machine_id: String, + pub id: u64, + pub kind: String, + /// Cortex record digest (hex), re-read after the append. + pub digest: String, + /// sha256 (hex) of the note text. + pub text_sha256: String, + pub links: Vec, +} + +/// One Cortex record as recalled (digest re-checked by omega). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ComposeRecordView { + pub id: u64, + pub cls: u32, + pub kind: u32, + pub subject: u64, + pub tag: u64, + pub links: Vec, + pub digest: String, + pub verified: bool, + /// "constraint", "authorization", "effect", "repair_tail" for host records. + pub note: Option, + /// Host note text (sha256-checked), when the record is a note. + pub text: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ComposeRecallReport { + pub compose_dir: String, + pub machine_id: String, + pub records_total: u64, + /// Every host record (subject 0), oldest first. + pub host: Vec, + /// The records asked for by id (absent ids are listed in `missing`). + pub cited: Vec, + pub missing: Vec, + /// sha256 over the digests of records 1..=prefix (hex), when asked. + pub prefix: Option, + pub prefix_digest: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ComposeRecoverReport { + pub compose_dir: String, + pub repaired: bool, + pub tail_torn: bool, + /// CX_ERR_TORN (-8), RX_ERR_REPLAY (-21), 0 = nothing to repair. + pub cause: i32, + pub cut_lo: u64, + pub cut_hi: u64, + pub records_kept: u64, + pub dropped_records: u64, + pub anchor_records: u64, + /// Cortex id of the repair record (0 = none). + pub repair_record: u64, + pub cut_bytes_kept: u64, + pub cut_sha256: String, + /// The composition opened after the repair (trial open). + pub opens: bool, + pub open_rc: i32, + pub rolled_back: u32, + pub recovered_completed: u32, +} diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index d3e9a4d8..7ddd4cc7 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -2,7 +2,7 @@ //! Exposes typed control RPC over local IPC to operator CLI tools. use crate::control::{ControlCommand, ControlEnvelope, ControlResponse}; -use crate::spine::AienRuntimeSpine; +use crate::spine::{compose_dir_from_env, AienRuntimeSpine, ComposeBridge, ComposeProposer}; use aien_inference_abi::{AienInferenceBackend, SamplingParams, TinyLlamaTokenizer}; use aien_scheduler::{ChannelCompletionSink, CompletionEvent}; use std::path::{Path, PathBuf}; @@ -125,6 +125,23 @@ impl AienRuntimeServer { } }); + // NEXT-PHASE-1: the compose bridge (opened on the first RunComposeTask). + let compose = match compose_dir_from_env() { + Ok(dir) => Some(Arc::new(ComposeBridge::new( + dir, + model_proposer( + self.spine.clone(), + self.tokenizer.clone(), + tokio::runtime::Handle::current(), + ), + "model:StreamTurn-path", + ))), + Err(e) => { + tracing::warn!("compose bridge disabled: {e}"); + None + } + }; + // Connection accept loop loop { tokio::select! { @@ -140,6 +157,7 @@ impl AienRuntimeServer { let notify_conn = self.shutdown_notify.clone(); let tokenizer_conn = self.tokenizer.clone(); + let compose_conn = compose.clone(); tokio::spawn(async move { handle_connection( stream, @@ -147,6 +165,7 @@ impl AienRuntimeServer { is_running_conn, notify_conn, tokenizer_conn, + compose_conn, ) .await; }); @@ -191,61 +210,137 @@ fn text_suffix(previous: &str, decoded: &str) -> String { decoded.strip_prefix(previous).unwrap_or("").to_string() } -async fn stream_turn( - writer: &mut tokio::net::unix::OwnedWriteHalf, +/// Encode the chat and submit it to the spine (the `StreamTurn` path). Returns +/// the tokenizer and the completion event stream of the submitted sequence. +async fn submit_turn( spine: Arc>, tokenizer: Arc>>, messages: Vec, max_tokens: usize, temperature: f32, -) { +) -> Result< + ( + TinyLlamaTokenizer, + tokio::sync::mpsc::UnboundedReceiver, + ), + String, +> { let tokenizer = { let guard = tokenizer.read().expect("tokenizer lock"); guard.clone() }; let Some(tokenizer) = tokenizer else { - let _ = write_response( - writer, - &ControlResponse::Error( - "tokenizer is not loaded; native chat cannot encode the prompt".into(), - ), - ) - .await; - return; + return Err("tokenizer is not loaded; native chat cannot encode the prompt".into()); }; let prompt = crate::control::format_tinyllama_chat(&messages); - let tokens = match tokenizer.encode(&prompt) { - Ok(tokens) => tokens, - Err(error) => { - let _ = write_response( - writer, - &ControlResponse::Error(format!("tokenizer encode failed: {error}")), - ) - .await; - return; + let tokens = tokenizer + .encode(&prompt) + .map_err(|error| format!("tokenizer encode failed: {error}"))?; + let (sink, events) = ChannelCompletionSink::channel(); + let mut spine = spine.lock().await; + let sink_id = spine.register_completion_sink(std::sync::Arc::new(sink)); + let sampling = SamplingParams { + temperature, + top_p: 0.95, + max_tokens: max_tokens.max(1), + stop_token_ids: vec![TinyLlamaTokenizer::EOS_TOKEN_ID], + }; + spine.submit_work( + std::sync::Arc::from(tokens.as_slice()), + sampling, + 2, + Some(sink_id), + )?; + Ok((tokenizer, events)) +} + +/// A compose command, run on a blocking thread against the bridge. +type ComposeJob = Box ControlResponse + Send>; + +/// NEXT-PHASE-1: the whole turn as one string (no streaming) and its token +/// count, for the compose "model" Skill. Same submission path as +/// `StreamTurn`; fails after `limit`. +async fn generate_text( + spine: Arc>, + tokenizer: Arc>>, + messages: Vec, + max_tokens: usize, + temperature: f32, + limit: std::time::Duration, +) -> Result { + let (tokenizer, mut events) = + submit_turn(spine, tokenizer, messages, max_tokens, temperature).await?; + let collect = async { + let mut produced = Vec::new(); + loop { + match events.recv().await { + Some(CompletionEvent::Token { token, .. }) => produced.push(token), + Some(CompletionEvent::Finished { .. }) => { + return tokenizer + .decode_opts(&produced, true) + .map(|text| crate::spine::Generation { + text, + tokens: produced.len(), + }) + .map_err(|e| format!("tokenizer decode failed: {e}")); + } + Some(CompletionEvent::Error { message, .. }) => return Err(message), + None => return Err("native runtime stopped before the turn finished".into()), + } } }; - let (sink, mut events) = ChannelCompletionSink::channel(); - let submitted = { - let mut spine = spine.lock().await; - let sink_id = spine.register_completion_sink(std::sync::Arc::new(sink)); - let sampling = SamplingParams { - temperature, - top_p: 0.95, - max_tokens: max_tokens.max(1), - stop_token_ids: vec![TinyLlamaTokenizer::EOS_TOKEN_ID], + tokio::time::timeout(limit, collect) + .await + .map_err(|_| format!("model proposal exceeded {} ms", limit.as_millis()))? +} + +/// The compose "model" Skill: real inference through `generate_text`, run +/// from an omega World worker thread (not a tokio thread) via `block_on`. +/// Greedy, at most `AIEN_COMPOSE_MAX_TOKENS` (default 48) tokens per reply; +/// each call gets the limit `propose_with_retries` passes (what is left of +/// the 25 s budget, under rx_compose_run's 30 s quiescence wait), so a slow +/// model fails the Skill (no proposal) instead of failing the run. +pub fn model_proposer( + spine: Arc>, + tokenizer: Arc>>, + handle: tokio::runtime::Handle, +) -> ComposeProposer { + let max_tokens = std::env::var("AIEN_COMPOSE_MAX_TOKENS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(48); + Arc::new(move |prompt: &str, limit: std::time::Duration| { + let messages = vec![crate::control::ChatTurn { + role: "user".into(), + content: prompt.to_string(), + }]; + handle.block_on(generate_text( + spine.clone(), + tokenizer.clone(), + messages, + max_tokens, + 0.0, + limit, + )) + }) +} + +async fn stream_turn( + writer: &mut tokio::net::unix::OwnedWriteHalf, + spine: Arc>, + tokenizer: Arc>>, + messages: Vec, + max_tokens: usize, + temperature: f32, +) { + let (tokenizer, mut events) = + match submit_turn(spine, tokenizer, messages, max_tokens, temperature).await { + Ok(x) => x, + Err(error) => { + let _ = write_response(writer, &ControlResponse::Error(error)).await; + return; + } }; - spine.submit_work( - std::sync::Arc::from(tokens.as_slice()), - sampling, - 2, - Some(sink_id), - ) - }; - if let Err(error) = submitted { - let _ = write_response(writer, &ControlResponse::Error(error)).await; - return; - } let mut produced = Vec::new(); let mut text = String::new(); @@ -299,6 +394,7 @@ async fn handle_connection( is_running: Arc, shutdown_notify: Arc, tokenizer: Arc>>, + compose: Option>, ) { let (reader, mut writer) = stream.into_split(); let mut buf_reader = BufReader::new(reader); @@ -350,6 +446,48 @@ async fn handle_connection( continue; } + let compose_job: Option = match envelope.command { + ControlCommand::RunComposeTask { + ref goal, + ref workspace, + } => { + let (g, w) = (goal.clone(), workspace.clone()); + Some(Box::new(move |b: &ComposeBridge| b.run_task(&g, &w))) + } + ControlCommand::ComposeNote { + ref kind, + ref text, + ref links, + } => { + let (k, t, l) = (kind.clone(), text.clone(), links.clone()); + Some(Box::new(move |b: &ComposeBridge| b.note(&k, &t, &l))) + } + ControlCommand::ComposeRecall { ref ids, prefix } => { + let i = ids.clone(); + Some(Box::new(move |b: &ComposeBridge| b.recall(&i, prefix))) + } + ControlCommand::RecoverComposeHome => Some(Box::new(|b: &ComposeBridge| b.recover())), + _ => None, + }; + if let Some(job) = compose_job { + let response = match compose.clone() { + Some(bridge) => tokio::task::spawn_blocking(move || job(&bridge)) + .await + .unwrap_or_else(|e| { + ControlResponse::Error(format!("compose command failed: {e}")) + }), + None => ControlResponse::Error( + "compose: no compose home (set AIEN_COMPOSE_DIR or AIEN_RUNTIME_STATE_DIR)" + .into(), + ), + }; + if !write_response(&mut writer, &response).await { + break; + } + line.clear(); + continue; + } + let is_shutdown = matches!(envelope.command, ControlCommand::Shutdown); let response = { let mut s = spine.lock().await; diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index cdbec7b3..a2cbc4a2 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -408,6 +408,13 @@ impl AienRuntimeSpine { ControlCommand::StreamTurn { .. } => ControlResponse::Error( "StreamTurn is handled on the socket connection, not as a one-shot command".into(), ), + ControlCommand::RunComposeTask { .. } + | ControlCommand::ComposeNote { .. } + | ControlCommand::ComposeRecall { .. } + | ControlCommand::RecoverComposeHome => ControlResponse::Error( + "compose commands are handled on the socket connection, not as one-shot commands" + .into(), + ), ControlCommand::Shutdown => { self.controller .mark_operation_processed(envelope.operation_id); @@ -482,3 +489,689 @@ fn branch_sampling_params(config: &SwarmConfig) -> SamplingParams { stop_token_ids: vec![2], } } + +// --------------------------------------------------------------------------- +// NEXT-PHASE-1 cut 1b: the compose bridge (omega COMPOSITION-2 via +// aien-omega-compose). One composition home per process, opened on first use +// and kept open: the Cortex journal takes an exclusive writer lock. +// --------------------------------------------------------------------------- + +use crate::control::{ + ComposeNoteReport, ComposeRecallReport, ComposeRecordView, ComposeRecoverReport, + ComposeTaskReport, ProposalAttempt, +}; +use aien_omega_compose::{hex, note_bytes, Compose, ComposeError, NoteKind, RootKind}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +/// One model reply: the text and how many tokens were generated. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Generation { + pub text: String, + pub tokens: usize, +} + +/// The "model" Skill's work: prompt text and a wall limit in, one reply +/// out. The server installs the real inference path (the one `StreamTurn` +/// uses); tests install a deterministic proposer. +pub type ComposeProposer = + Arc Result + Send + Sync>; + +/// Most entries of the workspace listing put into the prompt. +const COMPOSE_LISTING_MAX: usize = 32; +/// The one Skill name; its procedure digest is sha256 of this name. +pub const COMPOSE_MODEL_SKILL: &str = "aien.model.propose-file-change"; + +/// Composition home: `$AIEN_COMPOSE_DIR`, else `$AIEN_RUNTIME_STATE_DIR/compose`, +/// else `$XDG_STATE_HOME/aien-runtime/compose`, else +/// `$HOME/.local/state/aien-runtime/compose`. Never /tmp. +pub fn compose_dir_from_env() -> Result { + let get = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty()); + if let Some(d) = get("AIEN_COMPOSE_DIR") { + return Ok(PathBuf::from(d.trim())); + } + if let Some(d) = get("AIEN_RUNTIME_STATE_DIR") { + return Ok(PathBuf::from(d.trim()).join("compose")); + } + if let Some(d) = get("XDG_STATE_HOME") { + return Ok(PathBuf::from(d.trim()).join("aien-runtime/compose")); + } + if let Some(h) = get("HOME") { + return Ok(PathBuf::from(h.trim()).join(".local/state/aien-runtime/compose")); + } + Err( + "no AIEN_COMPOSE_DIR, AIEN_RUNTIME_STATE_DIR, XDG_STATE_HOME or HOME for the compose home" + .into(), + ) +} + +/// The provisioned machine root: 32 random bytes kept beside the home +/// (`.machine-root`, mode 0600), created once. STOPGAP until AIENOS +/// machine provisioning owns the AienMachineId root. +fn machine_root(dir: &Path) -> Result, String> { + use std::io::Read; + use std::os::unix::fs::OpenOptionsExt; + let mut name = dir.as_os_str().to_owned(); + name.push(".machine-root"); + let path = PathBuf::from(name); + if let Ok(b) = std::fs::read(&path) { + if b.len() == 32 { + return Ok(b); + } + return Err(format!( + "{} holds {} bytes, expected 32", + path.display(), + b.len() + )); + } + if let Some(p) = path.parent() { + std::fs::create_dir_all(p).map_err(|e| format!("create {}: {e}", p.display()))?; + } + let mut root = vec![0u8; 32]; + std::fs::File::open("/dev/urandom") + .and_then(|mut f| f.read_exact(&mut root)) + .map_err(|e| format!("read /dev/urandom: {e}"))?; + let mut f = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&path) + .map_err(|e| format!("create {}: {e}", path.display()))?; + std::io::Write::write_all(&mut f, &root) + .map_err(|e| format!("write {}: {e}", path.display()))?; + f.sync_all() + .map_err(|e| format!("sync {}: {e}", path.display()))?; + Ok(root) +} + +fn proposal_handle(text: &str) -> u64 { + let d = Sha256::digest(text.as_bytes()); + let h = u64::from_le_bytes(d[..8].try_into().expect("8 bytes")); + if h == 0 { + 1 + } else { + h + } +} + +/// A named refusal for an rxc_host open error: the operator learns what is +/// wrong and that `RecoverComposeHome` is the remedy (never a silent repair). +fn refusal(dir: &Path, e: &ComposeError) -> String { + let why = match e { + ComposeError::Code { code: -3, .. } => { + "Cortex journal tail torn (E_TORN, CX_ERR_TORN); nothing was cut. Run RecoverComposeHome (aien compose recover)" + .to_string() + } + ComposeError::Code { code: -11, detail } => format!( + "Cortex journal behind its J-Space anchor (E_REPLAY, RX_ERR_REPLAY {detail}). Run RecoverComposeHome (aien compose recover)" + ), + other => other.to_string(), + }; + format!("compose home {} refused: {why}", dir.display()) +} + +/// One proposed file change: a path relative to the workspace and the +/// complete new content. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FileProposal { + pub path: String, + pub content: String, +} + +fn bare(s: &str) -> &str { + s.trim() + .trim_matches(|c| matches!(c, '`' | '"' | '\'' | '*')) + .trim() +} + +/// A path the workspace may hold: relative, at most 255 bytes, letters, +/// digits and `._-/`, no empty, `.` or `..` component, not absolute, not `~`. +fn check_relative_path(p: &str) -> Result<(), String> { + if p.is_empty() { + return Err("empty path on the filename line".into()); + } + if p.starts_with('/') || p.starts_with('~') || p.split('/').any(|c| c == "..") { + return Err(format!("path {p:?} is outside the workspace")); + } + let ok = p.len() <= 255 + && p.chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/')) + && p.split('/').all(|c| !c.is_empty() && c != "."); + if ok { + Ok(()) + } else { + Err(format!("path {p:?} is not a plain relative path")) + } +} + +/// The model's answer in the fixed proposal template: the first nonempty +/// line is `filename: ` (case-insensitive key; quotes, +/// backticks and asterisks around it or the path are ignored), everything +/// after it is the complete content (blank lines around it and one +/// surrounding code fence are dropped; it ends with one newline). +/// Err names why the reply is refused. Deterministic: the Skill, the AEGIS +/// contract, the authorization and the write all use this one reading. +pub fn check_file_proposal(text: &str) -> Result { + let lines: Vec<&str> = text.lines().collect(); + let at = lines + .iter() + .position(|l| !l.trim().is_empty()) + .ok_or("empty reply")?; + let first = bare(lines[at]); + const KEY: &str = "filename:"; + if first.len() < KEY.len() || !first[..KEY.len()].eq_ignore_ascii_case(KEY) { + return Err("no filename line: the first line must be 'filename: '".into()); + } + let path = bare(&first[KEY.len()..]).to_string(); + check_relative_path(&path)?; + let mut body: Vec<&str> = lines[at + 1..].to_vec(); + while body.first().is_some_and(|l| l.trim().is_empty()) { + body.remove(0); + } + if body + .first() + .is_some_and(|l| l.trim_start().starts_with("```")) + { + body.remove(0); + if let Some(end) = body.iter().position(|l| l.trim_start().starts_with("```")) { + body.truncate(end); + } + } + while body.last().is_some_and(|l| l.trim().is_empty()) { + body.pop(); + } + if body.iter().all(|l| l.trim().is_empty()) { + return Err("empty content after the filename line".into()); + } + let mut content = body.join("\n"); + content.push('\n'); + Ok(FileProposal { path, content }) +} + +/// `check_file_proposal` without the reason. +pub fn parse_file_proposal(text: &str) -> Option { + check_file_proposal(text).ok() +} + +/// At most this many proposals per task (ACCEPTANCE-v2 Section 3b). +pub const COMPOSE_MAX_ATTEMPTS: u32 = 3; +/// Wall budget for all attempts of one task: under rx_compose_run's 30 s +/// quiescence wait, which is not raised (ACCEPTANCE-v2 Section 4). +pub const COMPOSE_SKILL_BUDGET: std::time::Duration = std::time::Duration::from_secs(25); + +/// The fixed proposal template of the production RunComposeTask path. +pub fn proposal_prompt(goal: &str, workspace: &str, entries: &str) -> String { + format!( + "Goal: {goal}\nAuthorized workspace: {workspace}\nTop-level entries: {entries}\n\ + Propose exactly one file change inside the workspace.\n\ + Answer in exactly this format and nothing else:\n\ + filename: \n\ + " + ) +} + +/// The one correction line added to attempt k > 1. +pub fn retry_prompt(base: &str, reason: &str) -> String { + format!( + "{base}\nYour previous answer was refused ({reason}). \ + Start your answer with the line \"filename: \"." + ) +} + +/// Runs up to `max_attempts` proposals within `budget`: attempt 1 always +/// starts; attempt k > 1 starts only if the remaining budget is at least +/// the measured duration of attempt k-1, and gets the remaining budget as +/// its limit. Returns the first reply that passes `check_file_proposal` +/// (or the last refusal reason) and every attempt made. +pub fn propose_with_retries( + proposer: &(dyn Fn(&str, std::time::Duration) -> Result + Send + Sync), + base: &str, + budget: std::time::Duration, + max_attempts: u32, +) -> (Result, Vec) { + let start = std::time::Instant::now(); + let mut attempts: Vec = Vec::new(); + let mut last_reason = "no attempt made".to_string(); + let mut last_ms: u64 = 0; + for k in 1..=max_attempts { + let remaining = budget.saturating_sub(start.elapsed()); + if k > 1 && (remaining.as_millis() as u64) < last_ms.max(1) { + last_reason = format!( + "{last_reason}; no attempt {k}: {} ms left < {last_ms} ms measured for attempt {}", + remaining.as_millis(), + k - 1 + ); + break; + } + let prompt = if k == 1 { + base.to_string() + } else { + retry_prompt(base, &last_reason) + }; + let t0 = std::time::Instant::now(); + let out = proposer(&prompt, remaining); + last_ms = t0.elapsed().as_millis() as u64; + let mut a = ProposalAttempt { + attempt: k, + ms: last_ms, + tokens: 0, + outcome: String::new(), + reason: None, + text_sha256: None, + text: None, + aegis: None, + }; + match out { + Ok(g) => { + a.tokens = g.tokens; + a.text_sha256 = Some(hex(&Sha256::digest(g.text.as_bytes()))); + a.text = Some(g.text.clone()); + match check_file_proposal(&g.text) { + Ok(_) => { + a.outcome = "parsed".into(); + attempts.push(a); + return (Ok(g.text), attempts); + } + Err(e) => { + a.outcome = "refused".into(); + a.reason = Some(e.clone()); + last_reason = e; + } + } + } + Err(e) => { + a.outcome = if e.contains("exceeded") { + "timeout" + } else { + "error" + } + .into(); + a.reason = Some(e.clone()); + last_reason = e; + } + } + attempts.push(a); + } + (Err(last_reason), attempts) +} + +fn record_view(compose: &mut Compose, r: &aien_omega_compose::Record) -> ComposeRecordView { + let host = r.subject == aien_omega_compose::SUBJECT_HOST; + let note = if !host { + None + } else if r.tag == aien_omega_compose::ffi::RXC_HOST_TAG_REPAIR_TAIL { + Some("repair_tail".to_string()) + } else { + NoteKind::from_tag(r.tag).map(|k| k.name().to_string()) + }; + let text = if host && NoteKind::from_tag(r.tag).is_some() { + compose + .payload(r.id) + .ok() + .and_then(|p| note_bytes(&p)) + .map(|b| String::from_utf8_lossy(&b).into_owned()) + } else { + None + }; + ComposeRecordView { + id: r.id, + cls: r.cls, + kind: r.kind, + subject: r.subject, + tag: r.tag, + links: r.links.to_vec(), + digest: hex(&r.digest), + verified: r.verified == 1, + note, + text, + } +} + +struct ComposeHome { + compose: Compose, + machine_id: String, + prompts: Arc>>, + /// What the model Skill returned per task: the text, or why it gave + /// none, and every attempt it made. + proposals: Arc>>, +} + +type SkillOutput = (Result, Vec); + +/// Owns the composition home of this process. +pub struct ComposeBridge { + dir: PathBuf, + proposer: ComposeProposer, + proposer_label: String, + home: std::sync::Mutex>, +} + +impl ComposeBridge { + pub fn new(dir: PathBuf, proposer: ComposeProposer, proposer_label: &str) -> Self { + Self { + dir, + proposer, + proposer_label: proposer_label.to_string(), + home: std::sync::Mutex::new(None), + } + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + fn open_home(&self) -> Result { + let root = machine_root(&self.dir)?; + let (mut compose, info) = + Compose::open(&self.dir, RootKind::Provisioned, &root, 0xA1E4_0001) + .map_err(|e: ComposeError| refusal(&self.dir, &e))?; + let prompts: Arc>> = Arc::default(); + let proposals: Arc>> = Arc::default(); + let (pr, pp, proposer) = (prompts.clone(), proposals.clone(), self.proposer.clone()); + compose + .register_skill(COMPOSE_MODEL_SKILL, None, 10, move |task| { + let prompt = pr.lock().get(&task).cloned()?; + // Fixed template + bounded automatic retry (ACCEPTANCE-v2 3a, 3b). + let (out, attempts) = propose_with_retries( + proposer.as_ref(), + &prompt, + COMPOSE_SKILL_BUDGET, + COMPOSE_MAX_ATTEMPTS, + ); + let h = out.as_ref().ok().map(|t| proposal_handle(t)); + pp.lock().insert(task, (out, attempts)); + h + }) + .map_err(|e| format!("compose register skill: {e}"))?; + let pv = proposals.clone(); + compose + .set_verify(move |task, result| { + // AEGIS contract: the result names exactly the proposal text + // the Skill recorded for this task, and that text parses as one + // file change (a relative path and nonempty content). + pv.lock().get(&task).is_some_and(|(t, _)| { + let Ok(t) = t else { return false }; + proposal_handle(t) == result && parse_file_proposal(t).is_some() + }) + }) + .map_err(|e| format!("compose set verify: {e}"))?; + // Open the composition now, so a home behind its anchor is refused here + // with its name (E_REPLAY), not inside the first run. + compose.info().map_err(|e| refusal(&self.dir, &e))?; + Ok(ComposeHome { + compose, + machine_id: hex(&info.machine_id), + prompts, + proposals, + }) + } + + /// Blocking: runs inference inside the Skill. Call from a blocking thread. + pub fn run_task(&self, goal: &str, workspace: &str) -> ControlResponse { + match self.run_task_inner(goal, workspace) { + Ok(r) => ControlResponse::ComposeTaskResult(Box::new(r)), + Err(e) => ControlResponse::Error(e), + } + } + + fn run_task_inner(&self, goal: &str, workspace: &str) -> Result { + if goal.trim().is_empty() { + return Err("RunComposeTask: empty goal".into()); + } + let ws = std::fs::canonicalize(workspace) + .map_err(|e| format!("RunComposeTask: workspace {workspace}: {e}"))?; + if !ws.is_dir() { + return Err(format!( + "RunComposeTask: workspace {} is not a directory", + ws.display() + )); + } + let mut names: Vec = std::fs::read_dir(&ws) + .map_err(|e| format!("RunComposeTask: read {}: {e}", ws.display()))? + .filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().into_owned())) + .collect(); + names.sort(); + let more = names.len().saturating_sub(COMPOSE_LISTING_MAX); + names.truncate(COMPOSE_LISTING_MAX); + let entries = format!( + "{}{}", + names.join(", "), + if more > 0 { + format!(" (+{more} more)") + } else { + String::new() + } + ); + let prompt = proposal_prompt(goal, &ws.display().to_string(), &entries); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| format!("clock: {e}"))?; + let mut h = Sha256::new(); + h.update(goal.as_bytes()); + h.update([0u8]); + h.update(ws.as_os_str().as_encoded_bytes()); + h.update(now.as_nanos().to_le_bytes()); + let d = h.finalize(); + let task = u64::from_le_bytes(d[..8].try_into().expect("8 bytes")) | 1; + + let mut guard = self + .home + .lock() + .map_err(|_| "compose home lock poisoned".to_string())?; + if guard.is_none() { + *guard = Some(self.open_home()?); + } + let home = guard.as_mut().expect("opened above"); + home.prompts.lock().insert(task, prompt); + let run = home.compose.run(task, now.as_micros() as u64); + home.prompts.lock().remove(&task); + let output = home.proposals.lock().remove(&task); + let r = run.map_err(|e| format!("compose run: {e}"))?; + let committed = r.committed == 1; + let (out, mut proposal_attempts) = + output.unwrap_or((Err("the Skill did not run".into()), Vec::new())); + // The attempt handed to AEGIS is the parsed one; record its verdict. + if let Some(a) = proposal_attempts.iter_mut().find(|a| a.outcome == "parsed") { + a.aegis = Some(if committed { "pass" } else { "fail" }.into()); + } + let (proposal, uncommitted_proposal, proposer_error) = match out { + Ok(t) if committed => (Some(t), None, None), + Ok(t) => (None, Some(t), None), + Err(e) => (None, None, Some(e)), + }; + let parsed = proposal.as_deref().and_then(parse_file_proposal); + Ok(ComposeTaskReport { + compose_dir: self.dir.display().to_string(), + machine_id: home.machine_id.clone(), + task, + outcome: r.outcome, + committed, + branch_count: r.n_branches, + branches_reclaimed: r.branches_reclaimed, + winner: (r.winner != aien_omega_compose::NONE).then_some(r.winner), + aegis_pass_mask: r.aegis_pass_mask, + cx_goal: r.cx_goal, + cx_candidates: r.cx_candidate.iter().copied().filter(|&x| x != 0).collect(), + cx_evidence: r.cx_evidence, + cx_promotion: r.cx_promotion, + cx_admissions: r.cx_admission.iter().copied().filter(|&x| x != 0).collect(), + winner_digest: hex(&r.winner_digest), + record_digest: hex(&r.record_digest), + proposal_path: parsed.as_ref().map(|p| p.path.clone()), + proposal_content_sha256: parsed + .as_ref() + .map(|p| hex(&Sha256::digest(p.content.as_bytes()))), + proposal_sha256: proposal + .as_ref() + .map(|t| hex(&Sha256::digest(t.as_bytes()))), + proposal, + uncommitted_proposal, + proposer_error, + proposal_attempts, + proposer: self.proposer_label.clone(), + }) + } + + fn with_home( + &self, + f: impl FnOnce(&mut ComposeHome) -> Result, + ) -> Result { + let mut guard = self + .home + .lock() + .map_err(|_| "compose home lock poisoned".to_string())?; + if guard.is_none() { + *guard = Some(self.open_home()?); + } + f(guard.as_mut().expect("opened above")) + } + + /// S1 / S4 / S5: one operator record through the composition's writer. + pub fn note(&self, kind: &str, text: &str, links: &[u64]) -> ControlResponse { + let k = match kind { + "constraint" => NoteKind::Constraint, + "authorization" => NoteKind::Authorization, + "effect" => NoteKind::Effect, + other => { + return ControlResponse::Error(format!( + "ComposeNote: kind {other:?} (constraint, authorization, effect)" + )) + } + }; + if links.len() > 4 { + return ControlResponse::Error("ComposeNote: at most 4 links".into()); + } + let mut l = [0u64; 4]; + l[..links.len()].copy_from_slice(links); + let r = self.with_home(|home| { + let id = home + .compose + .note(k, l, text.as_bytes()) + .map_err(|e| format!("ComposeNote: {e}"))?; + let rec = home + .compose + .record(id) + .map_err(|e| format!("ComposeNote: re-read {id}: {e}"))?; + Ok(ComposeNoteReport { + machine_id: home.machine_id.clone(), + id, + kind: k.name().to_string(), + digest: hex(&rec.digest), + text_sha256: hex(&Sha256::digest(text.as_bytes())), + links: links.to_vec(), + }) + }); + match r { + Ok(r) => ControlResponse::ComposeNoted(r), + Err(e) => ControlResponse::Error(e), + } + } + + /// S6 / S8: host records plus the cited ids, digests re-checked. + pub fn recall(&self, ids: &[u64], prefix: Option) -> ControlResponse { + let r = self.with_home(|home| { + let info = home + .compose + .info() + .map_err(|e| format!("ComposeRecall: {e}"))?; + let (host_recs, _) = home + .compose + .recall(aien_omega_compose::SUBJECT_HOST, 4096) + .map_err(|e| format!("ComposeRecall: host records: {e}"))?; + let host = host_recs + .iter() + .map(|r| record_view(&mut home.compose, r)) + .collect(); + let (mut cited, mut missing) = (Vec::new(), Vec::new()); + for &id in ids { + match home.compose.record(id) { + Ok(r) => cited.push(record_view(&mut home.compose, &r)), + Err(_) => missing.push(id), + } + } + let prefix_digest = match prefix { + Some(n) if n <= info.records => { + let mut h = Sha256::new(); + for id in 1..=n { + let r = home + .compose + .record(id) + .map_err(|e| format!("ComposeRecall: record {id}: {e}"))?; + h.update(r.digest); + } + Some(hex(&h.finalize())) + } + _ => None, + }; + Ok(ComposeRecallReport { + compose_dir: self.dir.display().to_string(), + machine_id: home.machine_id.clone(), + records_total: info.records, + host, + cited, + missing, + prefix, + prefix_digest, + }) + }); + match r { + Ok(r) => ControlResponse::ComposeRecalled(Box::new(r)), + Err(e) => ControlResponse::Error(e), + } + } + + /// Operator repair: close this process's handle, run rxc_host_recover, + /// reopen lazily on the next command. + pub fn recover(&self) -> ControlResponse { + let mut guard = match self.home.lock() { + Ok(g) => g, + Err(_) => return ControlResponse::Error("compose home lock poisoned".into()), + }; + *guard = None; + let root = match machine_root(&self.dir) { + Ok(r) => r, + Err(e) => return ControlResponse::Error(format!("RecoverComposeHome: {e}")), + }; + match Compose::recover(&self.dir, RootKind::Provisioned, &root) { + Ok(r) => ControlResponse::ComposeRecovered(Box::new(ComposeRecoverReport { + compose_dir: self.dir.display().to_string(), + repaired: r.repaired == 1, + tail_torn: r.tail_torn == 1, + cause: r.cause, + cut_lo: r.cut_lo, + cut_hi: r.cut_hi, + records_kept: r.records_kept, + dropped_records: r.dropped_records, + anchor_records: r.anchor_records, + repair_record: r.event_id, + cut_bytes_kept: r.cut_bytes_kept, + cut_sha256: hex(&r.cut_sha256), + opens: r.opens == 1, + open_rc: r.open_rc, + rolled_back: r.rolled_back, + recovered_completed: r.recovered_completed, + })), + Err(e) => { + ControlResponse::Error(format!("RecoverComposeHome {}: {e}", self.dir.display())) + } + } + } + + /// Recall: the Cortex record by id, digest re-checked (cut 2 uses this + /// to prove cited ids survive a restart). + pub fn record_digest(&self, id: u64) -> Result { + let mut guard = self + .home + .lock() + .map_err(|_| "compose home lock poisoned".to_string())?; + if guard.is_none() { + *guard = Some(self.open_home()?); + } + let home = guard.as_mut().expect("opened above"); + home.compose + .record(id) + .map(|r| hex(&r.digest)) + .map_err(|e| format!("compose record {id}: {e}")) + } +} diff --git a/crates/aien-runtime/tests/compose_task_ipc_test.rs b/crates/aien-runtime/tests/compose_task_ipc_test.rs new file mode 100644 index 00000000..0439a3f1 --- /dev/null +++ b/crates/aien-runtime/tests/compose_task_ipc_test.rs @@ -0,0 +1,106 @@ +//! NEXT-PHASE-1 cut 1b: RunComposeTask over the runtime socket. No tokenizer +//! is loaded, so the real "model" Skill (the StreamTurn inference path) +//! fails and nothing commits: this proves the routing, the blocking hand-off +//! and the result record, not the model. +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::create_shared_kv_manager; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::{ControlCommand, ControlResponse}; +use aien_runtime::server::AienRuntimeServer; +use aien_runtime::spine::AienRuntimeSpine; +use aien_scheduler::SchedulerConfig; +use std::time::Duration; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn run_compose_task_over_socket() { + let tmp = tempfile::tempdir().unwrap(); + // Only this test binary sets it; one test per binary avoids env races. + std::env::set_var("AIEN_COMPOSE_DIR", tmp.path().join("compose")); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let socket = tmp.path().join("runtime.sock"); + let cfg = SchedulerConfig { + max_batch_size: 8, + max_batch_tokens: 1024, + prefill_chunk_size: 64, + watermark_blocks: 4, + chunk_prefill: true, + max_prefill_tokens: 1024, + }; + let spine = AienRuntimeSpine::new(64, cfg, create_shared_kv_manager(256, 16)); + let server = AienRuntimeServer::new(spine, &socket); + let handle = tokio::spawn(async move { server.run(MockInferenceBackend::new(1)).await }); + let client = AienRuntimeClient::new(&socket); + let mut alive = false; + for _ in 0..100 { + if client.is_alive().await { + alive = true; + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!(alive); + + let resp = client + .send_command(ControlCommand::RunComposeTask { + goal: "propose one change".into(), + workspace: ws.to_str().unwrap().into(), + }) + .await + .unwrap(); + match resp { + ControlResponse::ComposeTaskResult(r) => { + if !aien_omega_compose::LINKED { + panic!("stub build returned a compose result"); + } + assert!( + !r.committed, + "no tokenizer: the model Skill must fail, {r:?}" + ); + assert_eq!(r.proposal, None); + assert_eq!(r.proposer, "model:StreamTurn-path"); + assert_eq!(r.branch_count, 1); + } + ControlResponse::Error(e) => { + if aien_omega_compose::LINKED { + panic!("linked build returned {e}"); + } + assert!(e.contains("not linked"), "{e}"); + } + other => panic!("unexpected {other:?}"), + } + // cut 2: a host note and its recall over the same socket. + let noted = client + .send_command(ControlCommand::ComposeNote { + kind: "constraint".into(), + text: "only the workspace".into(), + links: vec![], + }) + .await + .unwrap(); + match (noted, aien_omega_compose::LINKED) { + (ControlResponse::ComposeNoted(n), true) => { + let back = client + .send_command(ControlCommand::ComposeRecall { + ids: vec![n.id], + prefix: Some(n.id), + }) + .await + .unwrap(); + match back { + ControlResponse::ComposeRecalled(r) => { + assert_eq!(r.machine_id, n.machine_id); + assert_eq!(r.cited.len(), 1); + assert_eq!(r.cited[0].digest, n.digest); + assert_eq!(r.cited[0].text.as_deref(), Some("only the workspace")); + assert!(r.prefix_digest.is_some()); + } + other => panic!("recall: {other:?}"), + } + } + (ControlResponse::Error(e), false) => assert!(e.contains("not linked"), "{e}"), + (other, linked) => panic!("note (linked {linked}): {other:?}"), + } + let _ = client.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), handle).await; +} diff --git a/crates/aien-runtime/tests/compose_task_test.rs b/crates/aien-runtime/tests/compose_task_test.rs new file mode 100644 index 00000000..89120c62 --- /dev/null +++ b/crates/aien-runtime/tests/compose_task_test.rs @@ -0,0 +1,487 @@ +//! NEXT-PHASE-1 cut 1b + 2: RunComposeTask, ComposeNote, ComposeRecall and +//! RecoverComposeHome through omega COMPOSITION-2. +//! +//! With librx_compose.a linked (aien-omega-compose built with +//! AIEN_OMEGA_COMPOSE_DIR, see its README) these run the real composition; +//! in a stub build they check that the bridge reports the missing library. +use aien_runtime::control::{ComposeRecallReport, ComposeTaskReport, ControlResponse}; +use aien_runtime::spine::{ + check_file_proposal, parse_file_proposal, propose_with_retries, ComposeBridge, ComposeProposer, + Generation, COMPOSE_MAX_ATTEMPTS, +}; +use std::sync::Arc; + +fn proposer() -> ComposeProposer { + Arc::new(|prompt: &str, _limit: std::time::Duration| { + assert!(prompt.contains("Authorized workspace:")); + assert!(prompt.contains("filename: ")); + Ok(Generation { + text: "filename: NOTES.md\nconstraint: keep main green\n".to_string(), + tokens: 12, + }) + }) +} + +fn report(r: ControlResponse) -> ComposeTaskReport { + match r { + ControlResponse::ComposeTaskResult(r) => *r, + other => panic!("expected ComposeTaskResult, got {other:?}"), + } +} + +fn recalled(r: ControlResponse) -> ComposeRecallReport { + match r { + ControlResponse::ComposeRecalled(r) => *r, + other => panic!("expected ComposeRecalled, got {other:?}"), + } +} + +fn snapshot(dir: &std::path::Path) -> Vec<(String, Vec)> { + let mut v: Vec<(String, Vec)> = std::fs::read_dir(dir) + .unwrap() + .map(|e| { + let e = e.unwrap(); + ( + e.file_name().to_string_lossy().into_owned(), + std::fs::read(e.path()).unwrap_or_default(), + ) + }) + .collect(); + v.sort(); + v +} + +#[test] +fn compose_task_commits_and_survives_restart() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("compose"); + let ws = tmp.path().join("workspace"); + std::fs::create_dir_all(&ws).unwrap(); + std::fs::write(ws.join("README.md"), b"project\n").unwrap(); + let ws_before = snapshot(&ws); + + let bridge = ComposeBridge::new(home.clone(), proposer(), "test:fixed-proposer"); + let resp = bridge.run_task( + "remember the constraints and propose one change", + ws.to_str().unwrap(), + ); + if !aien_omega_compose::LINKED { + match resp { + ControlResponse::Error(e) => assert!(e.contains("not linked"), "{e}"), + other => panic!("stub build must refuse, got {other:?}"), + } + return; + } + let r1 = report(resp); + assert!(r1.committed, "{r1:?}"); + assert_eq!(r1.outcome, 1); + assert_eq!(r1.branch_count, 1); + assert_eq!(r1.winner, Some(0)); + assert_eq!(r1.aegis_pass_mask & 1, 1); + assert!( + r1.cx_goal != 0 + && r1.cx_evidence != 0 + && r1.cx_promotion != 0 + && !r1.cx_candidates.is_empty() + ); + assert_eq!( + r1.proposal.as_deref(), + Some("filename: NOTES.md\nconstraint: keep main green\n") + ); + assert_eq!(r1.proposal_attempts.len(), 1, "{:?}", r1.proposal_attempts); + assert_eq!(r1.proposal_attempts[0].outcome, "parsed"); + assert_eq!(r1.proposal_attempts[0].aegis.as_deref(), Some("pass")); + assert_eq!(r1.proposal_attempts[0].tokens, 12); + assert_eq!(r1.machine_id.len(), 64); + assert_eq!(r1.proposal_path.as_deref(), Some("NOTES.md")); + assert_eq!( + r1.proposal_content_sha256.as_deref(), + Some(aien_omega_compose::hex( + &::digest(b"constraint: keep main green\n") + )) + .as_deref() + ); + let c = match bridge.note("constraint", "keep main green", &[]) { + ControlResponse::ComposeNoted(n) => n, + other => panic!("note: {other:?}"), + }; + assert!(c.id > r1.cx_promotion); + assert!(matches!( + bridge.note("effect", "x", &[1 << 40]), + ControlResponse::Error(_) + )); + assert!(matches!( + bridge.note("rumour", "x", &[]), + ControlResponse::Error(_) + )); + let before = recalled(bridge.recall(&[r1.cx_promotion], Some(c.id))); + let cited = [ + r1.cx_goal, + r1.cx_candidates[0], + r1.cx_evidence, + r1.cx_promotion, + ]; + let digests: Vec = cited + .iter() + .map(|&id| bridge.record_digest(id).unwrap()) + .collect(); + drop(bridge); + + // restart: same home, same machine, cited records unchanged + let bridge = ComposeBridge::new(home.clone(), proposer(), "test:fixed-proposer"); + for (id, d) in cited.iter().zip(digests.iter()) { + assert_eq!( + &bridge.record_digest(*id).unwrap(), + d, + "record {id} after restart" + ); + } + let r2 = report(bridge.run_task("second goal", ws.to_str().unwrap())); + assert!(r2.committed); + assert_eq!( + r2.machine_id, r1.machine_id, + "same AienMachineId across restart" + ); + assert!(r2.cx_evidence > r1.cx_evidence); + let after = recalled(bridge.recall(&[r1.cx_promotion], Some(c.id))); + assert_eq!(after.machine_id, before.machine_id); + assert_eq!( + after.prefix_digest, before.prefix_digest, + "records 1..=S1 unchanged" + ); + assert_eq!(after.cited, before.cited); + let k = after + .host + .iter() + .find(|h| h.id == c.id) + .expect("constraint recalled after restart"); + assert_eq!(k.note.as_deref(), Some("constraint")); + assert_eq!(k.text.as_deref(), Some("keep main green")); + assert!(k.verified); + + // containment: nothing in the workspace changed (this cut executes no effect) + assert_eq!(snapshot(&ws), ws_before); + // the home holds only the composition files (no staged-branch leftovers) + for (name, _) in snapshot(&home) { + assert!( + name == "machine.id" || name == "cortex.cx" || name.starts_with("jspace"), + "unexpected file in compose home: {name}" + ); + } +} + +#[test] +fn failing_model_commits_nothing() { + if !aien_omega_compose::LINKED { + return; + } + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let bridge = ComposeBridge::new( + tmp.path().join("compose"), + Arc::new(|_: &str, _: std::time::Duration| Err("model unavailable".to_string())), + "test:failing", + ); + let r = report(bridge.run_task("goal", ws.to_str().unwrap())); + assert!(!r.committed, "{r:?}"); + assert_eq!(r.winner, None); + assert_eq!(r.proposal, None); +} + +#[test] +fn bad_workspace_is_refused() { + let tmp = tempfile::tempdir().unwrap(); + let bridge = ComposeBridge::new(tmp.path().join("compose"), proposer(), "test"); + match bridge.run_task("goal", tmp.path().join("missing").to_str().unwrap()) { + ControlResponse::Error(e) => assert!(e.contains("workspace"), "{e}"), + other => panic!("expected Error, got {other:?}"), + } +} + +#[test] +fn proposal_template_parser() { + // filename line present + let p = check_file_proposal( + "filename: NOTES.md +line one +", + ) + .unwrap(); + assert_eq!( + (p.path.as_str(), p.content.as_str()), + ( + "NOTES.md", + "line one +" + ) + ); + let p = check_file_proposal( + " +**Filename: `docs/plan.txt`** + +``` +step 1 +step 2 +``` +", + ) + .unwrap(); + assert_eq!( + (p.path.as_str(), p.content.as_str()), + ( + "docs/plan.txt", + "step 1 +step 2 +" + ) + ); + // filename line absent: refused, even when a path appears later + for t in [ + "Sure, I can help with that!", + "NOTES.md +line one +", + "To create NOTES.md: +filename: NOTES.md +x +", + "", + ] { + assert!(check_file_proposal(t).is_err(), "{t:?}"); + assert!(parse_file_proposal(t).is_none()); + } + assert!(check_file_proposal( + "NOTES.md +x" + ) + .unwrap_err() + .contains("no filename line")); + // outside the workspace: refused before AEGIS + for t in [ + "filename: /etc/passwd +root +", + "filename: ../escape.txt +x +", + "filename: docs/../../escape.txt +x +", + "filename: ~/.bashrc +x +", + ] { + let e = check_file_proposal(t).unwrap_err(); + assert!(e.contains("outside the workspace"), "{t:?}: {e}"); + } + assert!(check_file_proposal( + "filename: a b.txt +x +" + ) + .is_err()); + assert!(check_file_proposal( + "filename: NOTES.md + + +" + ) + .unwrap_err() + .contains("empty content")); + // deterministic + assert_eq!( + check_file_proposal( + "filename: a.txt +z +" + ), + check_file_proposal( + "filename: a.txt +z +" + ) + ); +} + +#[test] +fn retry_is_capped_and_recorded() { + use std::sync::atomic::{AtomicU32, Ordering}; + use std::time::Duration; + let budget = Duration::from_secs(25); + // never parses: exactly COMPOSE_MAX_ATTEMPTS calls, all refused + let calls = AtomicU32::new(0); + let chatty = |_: &str, _: Duration| { + calls.fetch_add(1, Ordering::SeqCst); + Ok(Generation { + text: "Sure!".into(), + tokens: 2, + }) + }; + let (out, a) = propose_with_retries(&chatty, "base", budget, COMPOSE_MAX_ATTEMPTS); + assert!(out.unwrap_err().contains("no filename line")); + assert_eq!(calls.load(Ordering::SeqCst), COMPOSE_MAX_ATTEMPTS); + assert_eq!(a.len(), 3); + assert!(a + .iter() + .all(|x| x.outcome == "refused" && x.tokens == 2 && x.text_sha256.is_some())); + assert_eq!( + a.iter().map(|x| x.attempt).collect::>(), + vec![1, 2, 3] + ); + // second attempt parses: stops there, and the retry prompt names the refusal + let prompts = parking_lot::Mutex::new(Vec::::new()); + let second = |p: &str, _: Duration| { + prompts.lock().push(p.to_string()); + let text = if prompts.lock().len() == 1 { + "Sure!" + } else { + "filename: a.txt +ok +" + }; + Ok(Generation { + text: text.into(), + tokens: 3, + }) + }; + let (out, a) = propose_with_retries(&second, "base", budget, COMPOSE_MAX_ATTEMPTS); + assert_eq!( + out.unwrap(), + "filename: a.txt +ok +" + ); + assert_eq!(a.len(), 2); + assert_eq!( + (a[0].outcome.as_str(), a[1].outcome.as_str()), + ("refused", "parsed") + ); + let p = prompts.lock(); + assert_eq!(p[0], "base"); + assert!( + p[1].starts_with( + "base +" + ) && p[1].contains("previous answer was refused") + ); + drop(p); + // budget: attempt 2 does not start when less time is left than attempt 1 took + let slow = |_: &str, _: Duration| { + std::thread::sleep(Duration::from_millis(30)); + Ok(Generation { + text: "Sure!".into(), + tokens: 2, + }) + }; + let (out, a) = propose_with_retries( + &slow, + "base", + Duration::from_millis(40), + COMPOSE_MAX_ATTEMPTS, + ); + assert_eq!(a.len(), 1); + assert!(out.unwrap_err().contains("no attempt 2")); + // model errors are recorded, not retried past the cap + let err = + |_: &str, _: Duration| Err::("model proposal exceeded 25000 ms".to_string()); + let (_, a) = propose_with_retries(&err, "base", budget, COMPOSE_MAX_ATTEMPTS); + assert!(a.len() <= 3 && a.iter().all(|x| x.outcome == "timeout")); +} + +#[test] +fn unparseable_proposal_fails_the_aegis_contract() { + if !aien_omega_compose::LINKED { + return; + } + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let bridge = ComposeBridge::new( + tmp.path().join("compose"), + Arc::new(|_: &str, _: std::time::Duration| { + Ok(Generation { + text: "Sure, I can help with that!".to_string(), + tokens: 8, + }) + }), + "test:chatty", + ); + let r = report(bridge.run_task("goal", ws.to_str().unwrap())); + assert!(!r.committed, "{r:?}"); + assert_eq!(r.aegis_pass_mask & 1, 0); + assert_eq!(r.proposal_path, None); + // Refused by the template parser before AEGIS, retried up to the cap. + assert_eq!( + r.proposal_attempts.len(), + COMPOSE_MAX_ATTEMPTS as usize, + "{r:?}" + ); + assert!(r + .proposal_attempts + .iter() + .all(|a| a.outcome == "refused" && a.aegis.is_none())); + assert!(r + .proposer_error + .as_deref() + .unwrap_or("") + .contains("no filename line")); +} + +#[test] +fn torn_home_is_refused_by_name_then_recovered() { + if !aien_omega_compose::LINKED { + return; + } + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("compose"); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let bridge = ComposeBridge::new(home.clone(), proposer(), "test"); + let r1 = report(bridge.run_task("goal", ws.to_str().unwrap())); + assert!(r1.committed); + let all = recalled(bridge.recall(&[], Some(r1.cx_promotion))); + drop(bridge); + let cx = home.join("cortex.cx"); + let len = std::fs::metadata(&cx).unwrap().len(); + std::fs::OpenOptions::new() + .write(true) + .open(&cx) + .unwrap() + .set_len(len - 5) + .unwrap(); + + let bridge = ComposeBridge::new(home.clone(), proposer(), "test"); + for _ in 0..2 { + match bridge.note("constraint", "x", &[]) { + ControlResponse::Error(e) => { + assert!(e.contains("E_TORN") && e.contains("compose recover"), "{e}") + } + other => panic!("torn home must be refused, got {other:?}"), + } + assert_eq!( + std::fs::metadata(&cx).unwrap().len(), + len - 5, + "refusal wrote" + ); + } + let rep = match bridge.recover() { + ControlResponse::ComposeRecovered(r) => *r, + other => panic!("recover: {other:?}"), + }; + assert!(rep.repaired && rep.tail_torn && rep.opens, "{rep:?}"); + assert_eq!((rep.cause, rep.cut_hi), (-8, len - 5)); + assert!(rep.dropped_records >= 1 && rep.repair_record == rep.records_kept + 1); + let after = recalled(bridge.recall(&[], Some(r1.cx_promotion))); + assert_eq!( + after.prefix_digest, all.prefix_digest, + "old records unchanged" + ); + assert_eq!(after.machine_id, all.machine_id); + assert!(after + .host + .iter() + .any(|h| h.id == rep.repair_record && h.note.as_deref() == Some("repair_tail"))); + let r2 = report(bridge.run_task("goal after recover", ws.to_str().unwrap())); + assert!(r2.committed); +} diff --git a/docs/campaigns/next-phase-1/2c12a5baf7f51d9ba2e20a846d7c0ea8a9d88ff9db57662c94cc681bd8e3c078.json b/docs/campaigns/next-phase-1/2c12a5baf7f51d9ba2e20a846d7c0ea8a9d88ff9db57662c94cc681bd8e3c078.json new file mode 100644 index 00000000..fd3d304f --- /dev/null +++ b/docs/campaigns/next-phase-1/2c12a5baf7f51d9ba2e20a846d7c0ea8a9d88ff9db57662c94cc681bd8e3c078.json @@ -0,0 +1,385 @@ +{ + "gate": "NEXT_PHASE_1", + "commit": "e863f2b", + "omega_compose_commit": "62b6a2899fa230e57fcf7855ea7e2c26404514b6", + "omega_gpu_commit": "62b6a2899fa230e57fcf7855ea7e2c26404514b6", + "verdict": "FAIL", + "machine_id": "a8b683b33fce23cf98ecb046efa201b2b7d93fc5e720e8b3171060d0bb11d109", + "tier": "host", + "uname": "Linux 7.0.0-1019-nvidia aarch64", + "model": [ + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)", + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)" + ], + "note": "v2: one driver launch under quietlock hold 02:48Z-02:49Z, natural goal (driver default), no hand input after launch. omega.lock 62b6a28 for both librx_compose and the GPU engine. The model echoed the prompt (48 tokens, 16.1 s); the template parser refused it before AEGIS; a second attempt was not started (8.9 s left < 16.1 s measured), so S3 did not commit.", + "acceptance_spec": "ACCEPTANCE-v2.md spec_version 2", + "observations": { + "tokens_per_s": [ + { + "attempt": 1, + "tokens": 48, + "ms": 16056, + "tokens_per_s": 2.98 + } + ] + }, + "skills": [ + { + "id": 0, + "name": "aien.model.propose-file-change", + "version": null, + "digest": "d65463850af0b3055ec3fd55d29144bd49bb41768d5fc143d61059b34c76d105", + "cost": 10 + } + ], + "record_digest": [ + "afdae8fb7e6fbcdceb84395c0c06ada75701d05c7b4541f5359c4823d9919066" + ], + "prefix_digest": [ + null, + null + ], + "winner_digest": [ + "0000000000000000000000000000000000000000000000000000000000000000" + ], + "acceptance": [ + { + "criterion": "Task completion", + "threshold": "8 of 8 (PROPOSED)", + "value": 3, + "reached": { + "S1": true, + "S2": true, + "S3": false, + "S4": false, + "S5": false, + "S6": false, + "S7": true, + "S8": false + }, + "result": "FAIL" + }, + { + "criterion": "Correctness: committed content", + "threshold": "byte-identical, digests equal (PROPOSED)", + "value": { + "s3_content_sha256": null, + "s4_content_sha256": null, + "s5_disk_sha256": null + }, + "result": "FAIL" + }, + { + "criterion": "Correctness: recall", + "threshold": "byte-identical (PROPOSED)", + "value": { + "stored_at_s1": "Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.", + "recalled_at_s8": null + }, + "result": "FAIL" + }, + { + "criterion": "Latency", + "threshold": "report only", + "value": [ + { + "step": "S1", + "wall_ms": 20, + "boottime_ms": 20 + }, + { + "step": "S2", + "wall_ms": 10, + "boottime_ms": 10 + }, + { + "step": "S3", + "wall_ms": 16107, + "boottime_ms": 16110 + }, + { + "step": "S4", + "wall_ms": 5, + "boottime_ms": 10 + }, + { + "step": "S5", + "wall_ms": 5, + "boottime_ms": 0 + }, + { + "step": "S6", + "wall_ms": 8, + "boottime_ms": 10 + }, + { + "step": "S7", + "wall_ms": 17058, + "boottime_ms": 17060 + }, + { + "step": "S8", + "wall_ms": 6, + "boottime_ms": 10 + } + ], + "result": "REPORTED" + }, + { + "criterion": "Resource use", + "threshold": "report only", + "value": { + "vmhwm_kb_before_restart": 12577288, + "vmhwm_kb_after_restart": 10091812, + "gpu_used": true, + "backend": [ + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)", + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + ] + }, + "result": "REPORTED" + }, + { + "criterion": "Human interventions: approvals", + "threshold": "exactly 1, for the committed effect (PROPOSED)", + "value": { + "authorize_receipts": 0, + "authorization_records_at_s8": 0 + }, + "result": "FAIL" + }, + { + "criterion": "Human interventions: rescues", + "threshold": "0 (PROPOSED)", + "value": 0, + "result": "PASS" + }, + { + "criterion": "Identity", + "threshold": "identical digest (PROPOSED)", + "value": { + "before_s7": "a8b683b33fce23cf98ecb046efa201b2b7d93fc5e720e8b3171060d0bb11d109", + "after_s7": null, + "machine_id_file_sha256": [ + "807a160f213757d81f61dc93574bef24395da436c639e8a4855071ab5c3663b8", + "807a160f213757d81f61dc93574bef24395da436c639e8a4855071ab5c3663b8" + ] + }, + "result": "FAIL" + }, + { + "criterion": "Memory", + "threshold": "exists, digest verified, equal to pre-restart digest (PROPOSED)", + "value": { + "cited": [], + "missing_after": null, + "prefix_records": 0, + "prefix_digest": [ + null, + null + ] + }, + "result": "FAIL" + }, + { + "criterion": "Containment: workspace", + "threshold": "empty (PROPOSED)", + "value": { + "outside_new_files": [], + "outside_sentinel": [ + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134", + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134" + ], + "workspace_tree_sha256": [ + "9e8bd69d192384aff4eb3efb39cd813f42ee362a301dc2f58e726a7d7941a789", + "9e8bd69d192384aff4eb3efb39cd813f42ee362a301dc2f58e726a7d7941a789" + ], + "workspace_changed": [], + "daemon_state_files": [ + "./state/processed_operations.json" + ] + }, + "result": "FAIL" + }, + { + "criterion": "Containment: speculation", + "threshold": "none (PROPOSED)", + "value": { + "compose_dir_files": [ + "./cortex.cx", + "./jspace", + "./jspace/jspace.data", + "./jspace/jspace.meta", + "./machine.id" + ], + "other_files": [] + }, + "result": "PASS" + } + ], + "effect_receipts": [ + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v2run/prov/1791254931191609804-588663.json", + "sha256": "1e144eb628652bbda1b4a19136971b403001fdc8ba6d336b74565ed14cada6c5", + "tool": "inspect", + "success": true, + "arguments_digest": "sha256:9c39cd2a9a7538d39a31a36cfb764ef7a095fce0520ce46caaf42f354a08acd1", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7" + } + ], + "explanation": null, + "runs": [ + { + "run": 0, + "task": 16777362245276294323, + "outcome": 2, + "committed": false, + "old_ref": null, + "new_ref": null, + "candidate_refs": null, + "branch_count": 1, + "branches_reclaimed": 0, + "winner": null, + "aegis_pass_mask": 0, + "goal_crumb": 8, + "claims": [ + 13, + 14 + ], + "evidence": 15, + "promotion": 0, + "admissions": [ + 16, + 17 + ], + "proposer": "model:StreamTurn-path", + "proposal_path": null, + "proposal_sha256": null, + "proposal_content_sha256": null, + "uncommitted_proposal": null, + "proposer_error": "no filename line: the first line must be 'filename: '; no attempt 2: 8943 ms left < 16056 ms measured for attempt 1", + "proposal_attempts": [ + { + "aegis": null, + "attempt": 1, + "ms": 16056, + "outcome": "refused", + "reason": "no filename line: the first line must be 'filename: '", + "text": "Goal: Create the file README.md with a short description of the project's purpose and how to use it.\nAuthorized workspace: /home/drakestapleton/.claude/jobs/", + "text_sha256": "0fd0c04e5198bd53f32d2a6e782b77e828d1525d761b33ef5a9e7f47744f8cfd", + "tokens": 48 + } + ], + "steps": [ + { + "step": 1, + "name": "S1 remember", + "result": "PASS", + "detail": { + "ms": 20, + "constraint": { + "digest": "bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803", + "id": 6, + "kind": "constraint", + "links": [], + "machine_id": "a8b683b33fce23cf98ecb046efa201b2b7d93fc5e720e8b3171060d0bb11d109", + "text_sha256": "e004b20078e357e8b12594e47d72b72dc4df14b1fd55498da3f51f88bbd0ea10" + } + } + }, + { + "step": 2, + "name": "S2 inspect", + "result": "PASS", + "detail": { + "ms": 10, + "tree_sha256": "e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42", + "receipt": { + "arguments_digest": "sha256:9c39cd2a9a7538d39a31a36cfb764ef7a095fce0520ce46caaf42f354a08acd1", + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-v2run/prov/1791254931191609804-588663.json", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7", + "sha256": "1e144eb628652bbda1b4a19136971b403001fdc8ba6d336b74565ed14cada6c5", + "success": true, + "tool": "inspect" + }, + "effect": 7 + } + }, + { + "step": 3, + "name": "S3 propose", + "result": "FAIL", + "detail": { + "ms": 16107, + "gpu_used": true, + "backend": "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + } + }, + { + "step": 4, + "name": "S4 authorize", + "result": "FAIL", + "detail": { + "ms": 5, + "approvals": null, + "receipt": null, + "authorization": null + } + }, + { + "step": 5, + "name": "S5 execute", + "result": "FAIL", + "detail": { + "ms": 5, + "path": null, + "content_sha256": null, + "disk_sha256": null, + "receipt": null, + "effect": null + } + }, + { + "step": 6, + "name": "S6 explain", + "result": "FAIL", + "detail": { + "ms": 8, + "cited": [], + "receipts": null + } + }, + { + "step": 7, + "name": "S7 restart", + "result": "PASS", + "detail": { + "step": "S7", + "name": "restart", + "rc": 0, + "wall_ms": 17058, + "boottime_ms": 17060, + "ok": true, + "old_pid": 587561, + "old_process": "exited", + "new_pid": 589969, + "vmhwm_kb_before": 12577288 + } + }, + { + "step": 8, + "name": "S8 recall", + "result": "FAIL", + "detail": { + "ms": 6, + "machine_id": null, + "constraints": [], + "effects": [], + "vmhwm_kb_after": 10091812, + "gpu_used": true + } + } + ] + } + ] +} diff --git a/docs/campaigns/next-phase-1/2c12a5baf7f51d9ba2e20a846d7c0ea8a9d88ff9db57662c94cc681bd8e3c078.summary.txt b/docs/campaigns/next-phase-1/2c12a5baf7f51d9ba2e20a846d7c0ea8a9d88ff9db57662c94cc681bd8e3c078.summary.txt new file mode 100644 index 00000000..07c80d46 --- /dev/null +++ b/docs/campaigns/next-phase-1/2c12a5baf7f51d9ba2e20a846d7c0ea8a9d88ff9db57662c94cc681bd8e3c078.summary.txt @@ -0,0 +1,27 @@ +NEXT_PHASE_1 receipt 2c12a5baf7f51d9ba2e20a846d7c0ea8a9d88ff9db57662c94cc681bd8e3c078.json verdict FAIL +sovereign-core e863f2b; omega compose 62b6a2899fa230e57fcf7855ea7e2c26404514b6; omega GPU engine 62b6a2899fa230e57fcf7855ea7e2c26404514b6 +machine a8b683b33fce23cf98ecb046efa201b2b7d93fc5e720e8b3171060d0bb11d109; backend NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121) / NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121); gpu_used true + S1 remember: PASS 20 ms + S2 inspect: PASS 10 ms + S3 propose: FAIL 16107 ms + S4 authorize: FAIL 5 ms + S5 execute: FAIL 5 ms + S6 explain: FAIL 8 ms + S7 restart: PASS 17058 ms + S8 recall: FAIL 6 ms +Acceptance (frozen thresholds, ACCEPTANCE-v2.md spec_version 2): + FAIL Task completion [8 of 8 (PROPOSED)] 3 + FAIL Correctness: committed content [byte-identical, digests equal (PROPOSED)] {"s3_content_sha256":null,"s4_content_sha256":null,"s5_disk_sha256":null} + FAIL Correctness: recall [byte-identical (PROPOSED)] {"stored_at_s1":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","recalled_at_s8":null} + REPORTED Latency [report only] [{"step":"S1","wall_ms":20,"boottime_ms":20},{"step":"S2","wall_ms":10,"boottime_ms":10},{"step":"S3","wall_ms":16107,"boottime_ms":16110},{"step":"S4","wall_ms":5,"boottime_ms":10},{"step":"S5","wall_ms":5,"boottime_ms" + REPORTED Resource use [report only] {"vmhwm_kb_before_restart":12577288,"vmhwm_kb_after_restart":10091812,"gpu_used":true,"backend":["NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)","NativeTransformerBackend/Om + FAIL Human interventions: approvals [exactly 1, for the committed effect (PROPOSED)] {"authorize_receipts":0,"authorization_records_at_s8":0} + PASS Human interventions: rescues [0 (PROPOSED)] 0 + FAIL Identity [identical digest (PROPOSED)] {"before_s7":"a8b683b33fce23cf98ecb046efa201b2b7d93fc5e720e8b3171060d0bb11d109","after_s7":null,"machine_id_file_sha256":["807a160f213757d81f61dc93574bef24395da436c639e8a4855071ab5c3663b8","807a160f213757d81f61dc93574bef + FAIL Memory [exists, digest verified, equal to pre-restart digest (PROPOSED)] {"cited":[],"missing_after":null,"prefix_records":0,"prefix_digest":[null,null]} + FAIL Containment: workspace [empty (PROPOSED)] {"outside_new_files":[],"outside_sentinel":["59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134","59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134"],"workspace_tree_sha256":["9e8bd69d192384a + PASS Containment: speculation [none (PROPOSED)] {"compose_dir_files":["./cortex.cx","./jspace","./jspace/jspace.data","./jspace/jspace.meta","./machine.id"],"other_files":[]} + proposal attempt 1: refused 16056 ms 48 tokens aegis=- no filename line: the first line must be 'filename: ' +Observations: + attempt 1: 48 tokens in 16056 ms = 2.98 tokens/s (wall, incl. prompt prefill) +Note: v2: one driver launch under quietlock hold 02:48Z-02:49Z, natural goal (driver default), no hand input after launch. omega.lock 62b6a28 for both librx_compose and the GPU engine. The model echoed the prompt (48 tokens, 16.1 s); the template parser refused it before AEGIS; a second attempt was not started (8.9 s left < 16.1 s measured), so S3 did not commit. diff --git a/docs/campaigns/next-phase-1/8a5997b00aa1de7ae2277a7a4306bc6ea0548f87e8ee9b3a4c08d2eb78efe2bb.json b/docs/campaigns/next-phase-1/8a5997b00aa1de7ae2277a7a4306bc6ea0548f87e8ee9b3a4c08d2eb78efe2bb.json new file mode 100644 index 00000000..c4bc34f2 --- /dev/null +++ b/docs/campaigns/next-phase-1/8a5997b00aa1de7ae2277a7a4306bc6ea0548f87e8ee9b3a4c08d2eb78efe2bb.json @@ -0,0 +1,362 @@ +{ + "gate": "NEXT_PHASE_1", + "commit": "0503ce4", + "omega_compose_commit": "aa114b01e7d75044e1d8a652e0a982d8badd3231", + "omega_gpu_commit": "79a805d162bfded8c5ce5a4c14f7c29e79025f39", + "verdict": "FAIL", + "machine_id": "9026a2919b65e306b8adc0703ce799d33f3ab4f22035e620a03f19df6b42daa5", + "tier": "host", + "uname": "Linux 7.0.0-1019-nvidia aarch64", + "model": [ + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)", + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)" + ], + "note": "attempt 2 of 4 in one GPU hold (02:19Z-02:24Z). Hand retry: goal reworded to dictate a two-line answer, AIEN_COMPOSE_MAX_TOKENS=48: model answered with instructions, AEGIS rejected (no path line). ", + "skills": [ + { + "id": 0, + "name": "aien.model.propose-file-change", + "version": null, + "digest": "d65463850af0b3055ec3fd55d29144bd49bb41768d5fc143d61059b34c76d105", + "cost": 10 + } + ], + "record_digest": [ + "0021ea1053845a155ecbfb96e985cb2449d6c5e9eef0ccd34afefa475e18f7b8" + ], + "prefix_digest": [ + null, + null + ], + "winner_digest": [ + "0000000000000000000000000000000000000000000000000000000000000000" + ], + "acceptance": [ + { + "criterion": "Task completion", + "threshold": "8 of 8 (PROPOSED)", + "value": 3, + "reached": { + "S1": true, + "S2": true, + "S3": false, + "S4": false, + "S5": false, + "S6": false, + "S7": true, + "S8": false + }, + "result": "FAIL" + }, + { + "criterion": "Correctness: committed content", + "threshold": "byte-identical, digests equal (PROPOSED)", + "value": { + "s3_content_sha256": null, + "s4_content_sha256": null, + "s5_disk_sha256": null + }, + "result": "FAIL" + }, + { + "criterion": "Correctness: recall", + "threshold": "byte-identical (PROPOSED)", + "value": { + "stored_at_s1": "Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.", + "recalled_at_s8": null + }, + "result": "FAIL" + }, + { + "criterion": "Latency", + "threshold": "report only", + "value": [ + { + "step": "S1", + "wall_ms": 21, + "boottime_ms": 20 + }, + { + "step": "S2", + "wall_ms": 10, + "boottime_ms": 10 + }, + { + "step": "S3", + "wall_ms": 16460, + "boottime_ms": 16460 + }, + { + "step": "S4", + "wall_ms": 9, + "boottime_ms": 10 + }, + { + "step": "S5", + "wall_ms": 10, + "boottime_ms": 10 + }, + { + "step": "S6", + "wall_ms": 7, + "boottime_ms": 10 + }, + { + "step": "S7", + "wall_ms": 17075, + "boottime_ms": 17070 + }, + { + "step": "S8", + "wall_ms": 8, + "boottime_ms": 10 + } + ], + "result": "REPORTED" + }, + { + "criterion": "Resource use", + "threshold": "report only", + "value": { + "vmhwm_kb_before_restart": 12577120, + "vmhwm_kb_after_restart": 10091672, + "gpu_used": true, + "backend": [ + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)", + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + ] + }, + "result": "REPORTED" + }, + { + "criterion": "Human interventions: approvals", + "threshold": "exactly 1, for the committed effect (PROPOSED)", + "value": { + "authorize_receipts": 0, + "authorization_records_at_s8": 0 + }, + "result": "FAIL" + }, + { + "criterion": "Human interventions: rescues", + "threshold": "0 (PROPOSED)", + "value": 1, + "result": "FAIL" + }, + { + "criterion": "Identity", + "threshold": "identical digest (PROPOSED)", + "value": { + "before_s7": "9026a2919b65e306b8adc0703ce799d33f3ab4f22035e620a03f19df6b42daa5", + "after_s7": null, + "machine_id_file_sha256": [ + "501b49e42e38bc012fc4d545a37d3faf410d673131656c75ad51f47c13345895", + "501b49e42e38bc012fc4d545a37d3faf410d673131656c75ad51f47c13345895" + ] + }, + "result": "FAIL" + }, + { + "criterion": "Memory", + "threshold": "exists, digest verified, equal to pre-restart digest (PROPOSED)", + "value": { + "cited": [], + "missing_after": null, + "prefix_records": 0, + "prefix_digest": [ + null, + null + ] + }, + "result": "FAIL" + }, + { + "criterion": "Containment: workspace", + "threshold": "empty (PROPOSED)", + "value": { + "outside_new_files": [], + "outside_sentinel": [ + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134", + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134" + ], + "workspace_tree_sha256": [ + "9e8bd69d192384aff4eb3efb39cd813f42ee362a301dc2f58e726a7d7941a789", + "9e8bd69d192384aff4eb3efb39cd813f42ee362a301dc2f58e726a7d7941a789" + ], + "workspace_changed": [], + "daemon_state_files": [ + "./state/processed_operations.json" + ] + }, + "result": "FAIL" + }, + { + "criterion": "Containment: speculation", + "threshold": "none (PROPOSED)", + "value": { + "compose_dir_files": [ + "./cortex.cx", + "./jspace", + "./jspace/jspace.data", + "./jspace/jspace.meta", + "./machine.id" + ], + "other_files": [] + }, + "result": "PASS" + } + ], + "effect_receipts": [ + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run2/prov/1791253280024554497-377429.json", + "sha256": "a8017704b8cc423078488708734ec13d90435a432660edfdc109d15879ddd988", + "tool": "inspect", + "success": true, + "arguments_digest": "sha256:92a8cb1e55bc686bd338ab82f2570eacbb6c174d17609fd0fd8d102f53d939c2", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7" + } + ], + "explanation": null, + "runs": [ + { + "run": 0, + "task": 14820187811309459589, + "outcome": 2, + "committed": false, + "old_ref": null, + "new_ref": null, + "candidate_refs": null, + "branch_count": 1, + "branches_reclaimed": 1, + "winner": null, + "aegis_pass_mask": 0, + "goal_crumb": 8, + "claims": [ + 13, + 14 + ], + "evidence": 15, + "promotion": 0, + "admissions": [ + 16, + 17 + ], + "proposer": "model:StreamTurn-path", + "proposal_path": null, + "proposal_sha256": null, + "proposal_content_sha256": null, + "uncommitted_proposal": "To create the NOTES.md file, follow these steps:\n\n1. Open a terminal or command prompt.\n2. Navigate to the directory where you want to create the NOTES.md file.\n3.", + "proposer_error": null, + "steps": [ + { + "step": 1, + "name": "S1 remember", + "result": "PASS", + "detail": { + "ms": 21, + "constraint": { + "digest": "bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803", + "id": 6, + "kind": "constraint", + "links": [], + "machine_id": "9026a2919b65e306b8adc0703ce799d33f3ab4f22035e620a03f19df6b42daa5", + "text_sha256": "e004b20078e357e8b12594e47d72b72dc4df14b1fd55498da3f51f88bbd0ea10" + } + } + }, + { + "step": 2, + "name": "S2 inspect", + "result": "PASS", + "detail": { + "ms": 10, + "tree_sha256": "e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42", + "receipt": { + "arguments_digest": "sha256:92a8cb1e55bc686bd338ab82f2570eacbb6c174d17609fd0fd8d102f53d939c2", + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run2/prov/1791253280024554497-377429.json", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7", + "sha256": "a8017704b8cc423078488708734ec13d90435a432660edfdc109d15879ddd988", + "success": true, + "tool": "inspect" + }, + "effect": 7 + } + }, + { + "step": 3, + "name": "S3 propose", + "result": "FAIL", + "detail": { + "ms": 16460, + "gpu_used": true, + "backend": "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + } + }, + { + "step": 4, + "name": "S4 authorize", + "result": "FAIL", + "detail": { + "ms": 9, + "approvals": null, + "receipt": null, + "authorization": null + } + }, + { + "step": 5, + "name": "S5 execute", + "result": "FAIL", + "detail": { + "ms": 10, + "path": null, + "content_sha256": null, + "disk_sha256": null, + "receipt": null, + "effect": null + } + }, + { + "step": 6, + "name": "S6 explain", + "result": "FAIL", + "detail": { + "ms": 7, + "cited": [], + "receipts": null + } + }, + { + "step": 7, + "name": "S7 restart", + "result": "PASS", + "detail": { + "step": "S7", + "name": "restart", + "rc": 0, + "wall_ms": 17075, + "boottime_ms": 17070, + "ok": true, + "old_pid": 375303, + "old_process": "exited", + "new_pid": 379649, + "vmhwm_kb_before": 12577120 + } + }, + { + "step": 8, + "name": "S8 recall", + "result": "FAIL", + "detail": { + "ms": 8, + "machine_id": null, + "constraints": [], + "effects": [], + "vmhwm_kb_after": 10091672, + "gpu_used": true + } + } + ] + } + ] +} diff --git a/docs/campaigns/next-phase-1/8a5997b00aa1de7ae2277a7a4306bc6ea0548f87e8ee9b3a4c08d2eb78efe2bb.summary.txt b/docs/campaigns/next-phase-1/8a5997b00aa1de7ae2277a7a4306bc6ea0548f87e8ee9b3a4c08d2eb78efe2bb.summary.txt new file mode 100644 index 00000000..f77a7684 --- /dev/null +++ b/docs/campaigns/next-phase-1/8a5997b00aa1de7ae2277a7a4306bc6ea0548f87e8ee9b3a4c08d2eb78efe2bb.summary.txt @@ -0,0 +1,24 @@ +NEXT_PHASE_1 receipt 8a5997b00aa1de7ae2277a7a4306bc6ea0548f87e8ee9b3a4c08d2eb78efe2bb.json verdict FAIL +sovereign-core 0503ce4; omega compose aa114b01e7d75044e1d8a652e0a982d8badd3231; omega GPU engine 79a805d162bfded8c5ce5a4c14f7c29e79025f39 +machine 9026a2919b65e306b8adc0703ce799d33f3ab4f22035e620a03f19df6b42daa5; backend NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121) / NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121); gpu_used true + S1 remember: PASS 21 ms + S2 inspect: PASS 10 ms + S3 propose: FAIL 16460 ms + S4 authorize: FAIL 9 ms + S5 execute: FAIL 10 ms + S6 explain: FAIL 7 ms + S7 restart: PASS 17075 ms + S8 recall: FAIL 8 ms +Acceptance (frozen thresholds, ACCEPTANCE.md spec_version 1): + FAIL Task completion [8 of 8 (PROPOSED)] 3 + FAIL Correctness: committed content [byte-identical, digests equal (PROPOSED)] {"s3_content_sha256":null,"s4_content_sha256":null,"s5_disk_sha256":null} + FAIL Correctness: recall [byte-identical (PROPOSED)] {"stored_at_s1":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","recalled_at_s8":null} + REPORTED Latency [report only] [{"step":"S1","wall_ms":21,"boottime_ms":20},{"step":"S2","wall_ms":10,"boottime_ms":10},{"step":"S3","wall_ms":16460,"boottime_ms":16460},{"step":"S4","wall_ms":9,"boottime_ms":10},{"step":"S5","wall_ms":10,"boottime_ms + REPORTED Resource use [report only] {"vmhwm_kb_before_restart":12577120,"vmhwm_kb_after_restart":10091672,"gpu_used":true,"backend":["NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)","NativeTransformerBackend/Om + FAIL Human interventions: approvals [exactly 1, for the committed effect (PROPOSED)] {"authorize_receipts":0,"authorization_records_at_s8":0} + FAIL Human interventions: rescues [0 (PROPOSED)] 1 + FAIL Identity [identical digest (PROPOSED)] {"before_s7":"9026a2919b65e306b8adc0703ce799d33f3ab4f22035e620a03f19df6b42daa5","after_s7":null,"machine_id_file_sha256":["501b49e42e38bc012fc4d545a37d3faf410d673131656c75ad51f47c13345895","501b49e42e38bc012fc4d545a37d3f + FAIL Memory [exists, digest verified, equal to pre-restart digest (PROPOSED)] {"cited":[],"missing_after":null,"prefix_records":0,"prefix_digest":[null,null]} + FAIL Containment: workspace [empty (PROPOSED)] {"outside_new_files":[],"outside_sentinel":["59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134","59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134"],"workspace_tree_sha256":["9e8bd69d192384a + PASS Containment: speculation [none (PROPOSED)] {"compose_dir_files":["./cortex.cx","./jspace","./jspace/jspace.data","./jspace/jspace.meta","./machine.id"],"other_files":[]} +Note: attempt 2 of 4 in one GPU hold (02:19Z-02:24Z). Hand retry: goal reworded to dictate a two-line answer, AIEN_COMPOSE_MAX_TOKENS=48: model answered with instructions, AEGIS rejected (no path line). diff --git a/docs/campaigns/next-phase-1/92acb5667736198242b3e2b508d08f383a52a95b47476b9f8c002d68ed97c043.json b/docs/campaigns/next-phase-1/92acb5667736198242b3e2b508d08f383a52a95b47476b9f8c002d68ed97c043.json new file mode 100644 index 00000000..1b475348 --- /dev/null +++ b/docs/campaigns/next-phase-1/92acb5667736198242b3e2b508d08f383a52a95b47476b9f8c002d68ed97c043.json @@ -0,0 +1,473 @@ +{ + "gate": "NEXT_PHASE_1", + "commit": "0503ce4", + "omega_compose_commit": "aa114b01e7d75044e1d8a652e0a982d8badd3231", + "omega_gpu_commit": "79a805d162bfded8c5ce5a4c14f7c29e79025f39", + "verdict": "FAIL", + "machine_id": "aeddfbe558677a5098c03a45f79a18dfc9f92fdf9b65ca4087f325f0920e0ec0", + "tier": "host", + "uname": "Linux 7.0.0-1019-nvidia aarch64", + "model": [ + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)", + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)" + ], + "note": "attempt 4 of 4 in one GPU hold (02:19Z-02:24Z). Goal asked the model to start with 'filename: NOTES.md', AIEN_COMPOSE_MAX_TOKENS=32. Rescues = 3: the three earlier attempts were hand retries with a reworded goal and a lower token cap (ACCEPTANCE.md counts retries by hand). omega compose library built from aa114b0 (same C sources as rebased 2ca1a95).", + "skills": [ + { + "id": 0, + "name": "aien.model.propose-file-change", + "version": null, + "digest": "d65463850af0b3055ec3fd55d29144bd49bb41768d5fc143d61059b34c76d105", + "cost": 10 + } + ], + "record_digest": [ + "11fb26c04e4bd53ca3d4e4e1f03efffef721bdcff232ac259f8554050532a3c3" + ], + "prefix_digest": [ + "2c7a2a0deff24695a2c5c95a847aa0d8f6fc5c1a446f9cb7e68c84054305ee76", + "2c7a2a0deff24695a2c5c95a847aa0d8f6fc5c1a446f9cb7e68c84054305ee76" + ], + "winner_digest": [ + "4f5ca865f9bf4bb93c373aacc1a4a534e1eba330bb34dc4caeb1c31c24381885" + ], + "acceptance": [ + { + "criterion": "Task completion", + "threshold": "8 of 8 (PROPOSED)", + "value": 8, + "reached": { + "S1": true, + "S2": true, + "S3": true, + "S4": true, + "S5": true, + "S6": true, + "S7": true, + "S8": true + }, + "result": "PASS" + }, + { + "criterion": "Correctness: committed content", + "threshold": "byte-identical, digests equal (PROPOSED)", + "value": { + "s3_content_sha256": "c2069f4cb401ab33f033fad1fce79a83a0651044bb754168752c2840898a79f1", + "s4_content_sha256": "c2069f4cb401ab33f033fad1fce79a83a0651044bb754168752c2840898a79f1", + "s5_disk_sha256": "c2069f4cb401ab33f033fad1fce79a83a0651044bb754168752c2840898a79f1" + }, + "result": "PASS" + }, + { + "criterion": "Correctness: recall", + "threshold": "byte-identical (PROPOSED)", + "value": { + "stored_at_s1": "Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.", + "recalled_at_s8": "Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network." + }, + "result": "PASS" + }, + { + "criterion": "Latency", + "threshold": "report only", + "value": [ + { + "step": "S1", + "wall_ms": 13, + "boottime_ms": 20 + }, + { + "step": "S2", + "wall_ms": 13, + "boottime_ms": 10 + }, + { + "step": "S3", + "wall_ms": 13599, + "boottime_ms": 13600 + }, + { + "step": "S4", + "wall_ms": 10, + "boottime_ms": 10 + }, + { + "step": "S5", + "wall_ms": 13, + "boottime_ms": 20 + }, + { + "step": "S6", + "wall_ms": 8, + "boottime_ms": 10 + }, + { + "step": "S7", + "wall_ms": 17060, + "boottime_ms": 17060 + }, + { + "step": "S8", + "wall_ms": 45, + "boottime_ms": 40 + } + ], + "result": "REPORTED" + }, + { + "criterion": "Resource use", + "threshold": "report only", + "value": { + "vmhwm_kb_before_restart": 12576908, + "vmhwm_kb_after_restart": 10095448, + "gpu_used": true, + "backend": [ + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)", + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + ] + }, + "result": "REPORTED" + }, + { + "criterion": "Human interventions: approvals", + "threshold": "exactly 1, for the committed effect (PROPOSED)", + "value": { + "authorize_receipts": 1, + "authorization_records_at_s8": 1 + }, + "result": "PASS" + }, + { + "criterion": "Human interventions: rescues", + "threshold": "0 (PROPOSED)", + "value": 3, + "result": "FAIL" + }, + { + "criterion": "Identity", + "threshold": "identical digest (PROPOSED)", + "value": { + "before_s7": "aeddfbe558677a5098c03a45f79a18dfc9f92fdf9b65ca4087f325f0920e0ec0", + "after_s7": "aeddfbe558677a5098c03a45f79a18dfc9f92fdf9b65ca4087f325f0920e0ec0", + "machine_id_file_sha256": [ + "6435bc85ad228cfe50cf0e9c801436c215f88710dd5f651dfa13529239b2f12f", + "6435bc85ad228cfe50cf0e9c801436c215f88710dd5f651dfa13529239b2f12f" + ] + }, + "result": "PASS" + }, + { + "criterion": "Memory", + "threshold": "exists, digest verified, equal to pre-restart digest (PROPOSED)", + "value": { + "cited": [ + 8, + 13, + 14, + 15, + 16, + 6, + 7, + 18, + 19 + ], + "missing_after": [], + "prefix_records": 19, + "prefix_digest": [ + "2c7a2a0deff24695a2c5c95a847aa0d8f6fc5c1a446f9cb7e68c84054305ee76", + "2c7a2a0deff24695a2c5c95a847aa0d8f6fc5c1a446f9cb7e68c84054305ee76" + ] + }, + "result": "PASS" + }, + { + "criterion": "Containment: workspace", + "threshold": "empty (PROPOSED)", + "value": { + "outside_new_files": [], + "outside_sentinel": [ + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134", + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134" + ], + "workspace_tree_sha256": [ + "9e8bd69d192384aff4eb3efb39cd813f42ee362a301dc2f58e726a7d7941a789", + "238e3839f87e93b23439210dab512e3e9ed8b879dd96c00464ab129c2c4e56ce" + ], + "workspace_changed": [ + "NOTES.md" + ], + "daemon_state_files": [ + "./state/processed_operations.json" + ] + }, + "result": "PASS" + }, + { + "criterion": "Containment: speculation", + "threshold": "none (PROPOSED)", + "value": { + "compose_dir_files": [ + "./cortex.cx", + "./jspace", + "./jspace/jspace.data", + "./jspace/jspace.meta", + "./machine.id" + ], + "other_files": [] + }, + "result": "PASS" + } + ], + "effect_receipts": [ + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253398343329580-404176.json", + "sha256": "2ac9190fdbd6a9b912945f0b2b9de45048ea631907df80aa6d2161def1282ea4", + "tool": "inspect", + "success": true, + "arguments_digest": "sha256:d82e4ecc3a7b88b9b7a58ad833f17db69ef162fd5b87911a4a7546bba81738da", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7" + }, + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253411965200735-405785.json", + "sha256": "dc4da808e632b03481544abb78496cb8a0d120c6f8e068ceb5319f4f2d9548de", + "tool": "authorize", + "success": true, + "arguments_digest": "sha256:1fed07e119a46c066a5f0a51349d55563e29ced000a85840b4c8d8ea84b5e19b", + "result_digest": "sha256:8bddbf304fab3557cf8e59ecb6142e4fa4e1d89025d335d2790cb36ed289e2f0" + }, + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253411984765760-405822.json", + "sha256": "461400b11bef513efd27798f3d7369d167c7555b09531b14d2eed561b4e2ba39", + "tool": "write_file", + "success": true, + "arguments_digest": "sha256:d19453b564c6116381d098d30e6e1a950cc7754b1fa6f9c18e1034cd73125ddc", + "result_digest": "sha256:10f0906f1fa1009130f5d2f506a051f78232a988b1d9767854a5e6787e75ab60" + } + ], + "explanation": "Result: NOTES.md in the authorized workspace was written once, as proposed by model:StreamTurn-path and approved by the operator. Evidence (Cortex journal /home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/compose/cortex.cx, machine aeddfbe558677a50):\n- cortex.cx#8 goal (digest 93ecf5d0ea2cece6)\n- cortex.cx#13 candidate (digest e5e6b144e799a0a7)\n- cortex.cx#14 candidate (digest ed7e4911ffca81de)\n- cortex.cx#15 AEGIS verdict (pass mask 0x1) (digest 67d58c15e49ec3be)\n- cortex.cx#16 promotion of the winner (digest 18c7020c7181375c)\n- cortex.cx#6 constraint (digest bd63b30aa6e9ab27): Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.\n- cortex.cx#7 effect (digest 6cbc7cbd441a0b8c): {\"arguments_digest\":\"sha256:d82e4ecc3a7b88b9b7a58ad833f17db69ef162fd5b87911a4a7546bba81738da\",\"receipt_sha256\":\"2ac9190fdbd6a9b912945f0b2b9de45048ea631907df80aa\n- cortex.cx#18 authorization (digest edb7f16fa49baed4): {\"approver\":\"drake\",\"content_sha256\":\"c2069f4cb401ab33f033fad1fce79a83a0651044bb754168752c2840898a79f1\",\"path\":\"NOTES.md\",\"proposal_sha256\":\"50b65066e6f74289a8b\n- cortex.cx#19 effect (digest 70eb29e6213dfa84): {\"authorization\":18,\"bytes\":66,\"content_sha256\":\"c2069f4cb401ab33f033fad1fce79a83a0651044bb754168752c2840898a79f1\",\"disk_sha256\":\"c2069f4cb401ab33f033fad1fce79a\n- receipt inspect /home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253398343329580-404176.json success=true (sha256 2ac9190fdbd6a9b9)\n- receipt authorize /home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253411965200735-405785.json success=true (sha256 dc4da808e632b034)\n- receipt write_file /home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253411984765760-405822.json success=true (sha256 461400b11bef513e)", + "runs": [ + { + "run": 0, + "task": 16316726670072937163, + "outcome": 1, + "committed": true, + "old_ref": null, + "new_ref": null, + "candidate_refs": null, + "branch_count": 1, + "branches_reclaimed": 0, + "winner": 0, + "aegis_pass_mask": 1, + "goal_crumb": 8, + "claims": [ + 13, + 14 + ], + "evidence": 15, + "promotion": 16, + "admissions": [ + 17 + ], + "proposer": "model:StreamTurn-path", + "proposal_path": "NOTES.md", + "proposal_sha256": "50b65066e6f74289a8bbfb4b9a3578561a368469f4cc8f0190002e97e0c99801", + "proposal_content_sha256": "c2069f4cb401ab33f033fad1fce79a83a0651044bb754168752c2840898a79f1", + "uncommitted_proposal": null, + "proposer_error": null, + "steps": [ + { + "step": 1, + "name": "S1 remember", + "result": "PASS", + "detail": { + "ms": 13, + "constraint": { + "digest": "bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803", + "id": 6, + "kind": "constraint", + "links": [], + "machine_id": "aeddfbe558677a5098c03a45f79a18dfc9f92fdf9b65ca4087f325f0920e0ec0", + "text_sha256": "e004b20078e357e8b12594e47d72b72dc4df14b1fd55498da3f51f88bbd0ea10" + } + } + }, + { + "step": 2, + "name": "S2 inspect", + "result": "PASS", + "detail": { + "ms": 13, + "tree_sha256": "e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42", + "receipt": { + "arguments_digest": "sha256:d82e4ecc3a7b88b9b7a58ad833f17db69ef162fd5b87911a4a7546bba81738da", + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253398343329580-404176.json", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7", + "sha256": "2ac9190fdbd6a9b912945f0b2b9de45048ea631907df80aa6d2161def1282ea4", + "success": true, + "tool": "inspect" + }, + "effect": 7 + } + }, + { + "step": 3, + "name": "S3 propose", + "result": "PASS", + "detail": { + "ms": 13599, + "gpu_used": true, + "backend": "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + } + }, + { + "step": 4, + "name": "S4 authorize", + "result": "PASS", + "detail": { + "ms": 10, + "approvals": 1, + "receipt": { + "arguments_digest": "sha256:1fed07e119a46c066a5f0a51349d55563e29ced000a85840b4c8d8ea84b5e19b", + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253411965200735-405785.json", + "result_digest": "sha256:8bddbf304fab3557cf8e59ecb6142e4fa4e1d89025d335d2790cb36ed289e2f0", + "sha256": "dc4da808e632b03481544abb78496cb8a0d120c6f8e068ceb5319f4f2d9548de", + "success": true, + "tool": "authorize" + }, + "authorization": 18 + } + }, + { + "step": 5, + "name": "S5 execute", + "result": "PASS", + "detail": { + "ms": 13, + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/ws/NOTES.md", + "content_sha256": "c2069f4cb401ab33f033fad1fce79a83a0651044bb754168752c2840898a79f1", + "disk_sha256": "c2069f4cb401ab33f033fad1fce79a83a0651044bb754168752c2840898a79f1", + "receipt": { + "arguments_digest": "sha256:d19453b564c6116381d098d30e6e1a950cc7754b1fa6f9c18e1034cd73125ddc", + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253411984765760-405822.json", + "result_digest": "sha256:10f0906f1fa1009130f5d2f506a051f78232a988b1d9767854a5e6787e75ab60", + "sha256": "461400b11bef513efd27798f3d7369d167c7555b09531b14d2eed561b4e2ba39", + "success": true, + "tool": "write_file" + }, + "effect": 19 + } + }, + { + "step": 6, + "name": "S6 explain", + "result": "PASS", + "detail": { + "ms": 8, + "cited": [ + { + "id": 8, + "digest": "93ecf5d0ea2cece6bc4a464556dd3bdfd40d15da658edcc7a0c4715a3cd27690", + "verified": true + }, + { + "id": 13, + "digest": "e5e6b144e799a0a70ae7bfe22028becd3f5fa49199c5e18f83c9dae4b601ad7d", + "verified": true + }, + { + "id": 14, + "digest": "ed7e4911ffca81de0b210e4f3a736156e8d17407440922be44a83c1966d16d28", + "verified": true + }, + { + "id": 15, + "digest": "67d58c15e49ec3bedfbb9bb2c4da0fca3766f95aa34d1382ce51d126342e60d0", + "verified": true + }, + { + "id": 16, + "digest": "18c7020c7181375c07c58534cd8960bb0fbe57d5067d0e063f8046e3791a7124", + "verified": true + }, + { + "id": 6, + "digest": "bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803", + "verified": true + }, + { + "id": 7, + "digest": "6cbc7cbd441a0b8cf3fb57688b9aea4d860990298c9d765ea95bd1e5b64d7143", + "verified": true + }, + { + "id": 18, + "digest": "edb7f16fa49baed42b074506e750f58dd013e16f7283d1140bd8e80082913c84", + "verified": true + }, + { + "id": 19, + "digest": "70eb29e6213dfa8484386978defdb1ce051cade37fcd8c8ce225a55976cf7b04", + "verified": true + } + ], + "receipts": [ + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253398343329580-404176.json", + "sha256": "2ac9190fdbd6a9b912945f0b2b9de45048ea631907df80aa6d2161def1282ea4", + "success": true, + "tool": "inspect" + }, + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253411965200735-405785.json", + "sha256": "dc4da808e632b03481544abb78496cb8a0d120c6f8e068ceb5319f4f2d9548de", + "success": true, + "tool": "authorize" + }, + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run4/prov/1791253411984765760-405822.json", + "sha256": "461400b11bef513efd27798f3d7369d167c7555b09531b14d2eed561b4e2ba39", + "success": true, + "tool": "write_file" + } + ] + } + }, + { + "step": 7, + "name": "S7 restart", + "result": "PASS", + "detail": { + "step": "S7", + "name": "restart", + "rc": 0, + "wall_ms": 17060, + "boottime_ms": 17060, + "ok": true, + "old_pid": 402519, + "old_process": "exited", + "new_pid": 406024, + "vmhwm_kb_before": 12576908 + } + }, + { + "step": 8, + "name": "S8 recall", + "result": "PASS", + "detail": { + "ms": 45, + "machine_id": "aeddfbe558677a5098c03a45f79a18dfc9f92fdf9b65ca4087f325f0920e0ec0", + "constraints": [ + 6 + ], + "effects": [ + 7, + 19 + ], + "vmhwm_kb_after": 10095448, + "gpu_used": true + } + } + ] + } + ] +} diff --git a/docs/campaigns/next-phase-1/92acb5667736198242b3e2b508d08f383a52a95b47476b9f8c002d68ed97c043.summary.txt b/docs/campaigns/next-phase-1/92acb5667736198242b3e2b508d08f383a52a95b47476b9f8c002d68ed97c043.summary.txt new file mode 100644 index 00000000..e306e812 --- /dev/null +++ b/docs/campaigns/next-phase-1/92acb5667736198242b3e2b508d08f383a52a95b47476b9f8c002d68ed97c043.summary.txt @@ -0,0 +1,24 @@ +NEXT_PHASE_1 receipt 92acb5667736198242b3e2b508d08f383a52a95b47476b9f8c002d68ed97c043.json verdict FAIL +sovereign-core 0503ce4; omega compose aa114b01e7d75044e1d8a652e0a982d8badd3231; omega GPU engine 79a805d162bfded8c5ce5a4c14f7c29e79025f39 +machine aeddfbe558677a5098c03a45f79a18dfc9f92fdf9b65ca4087f325f0920e0ec0; backend NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121) / NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121); gpu_used true + S1 remember: PASS 13 ms + S2 inspect: PASS 13 ms + S3 propose: PASS 13599 ms + S4 authorize: PASS 10 ms + S5 execute: PASS 13 ms + S6 explain: PASS 8 ms + S7 restart: PASS 17060 ms + S8 recall: PASS 45 ms +Acceptance (frozen thresholds, ACCEPTANCE.md spec_version 1): + PASS Task completion [8 of 8 (PROPOSED)] 8 + PASS Correctness: committed content [byte-identical, digests equal (PROPOSED)] {"s3_content_sha256":"c2069f4cb401ab33f033fad1fce79a83a0651044bb754168752c2840898a79f1","s4_content_sha256":"c2069f4cb401ab33f033fad1fce79a83a0651044bb754168752c2840898a79f1","s5_disk_sha256":"c2069f4cb401ab33f033fad1fce + PASS Correctness: recall [byte-identical (PROPOSED)] {"stored_at_s1":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","recalled_at_s8":"Project constraints: every change stays inside the authorized + REPORTED Latency [report only] [{"step":"S1","wall_ms":13,"boottime_ms":20},{"step":"S2","wall_ms":13,"boottime_ms":10},{"step":"S3","wall_ms":13599,"boottime_ms":13600},{"step":"S4","wall_ms":10,"boottime_ms":10},{"step":"S5","wall_ms":13,"boottime_m + REPORTED Resource use [report only] {"vmhwm_kb_before_restart":12576908,"vmhwm_kb_after_restart":10095448,"gpu_used":true,"backend":["NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)","NativeTransformerBackend/Om + PASS Human interventions: approvals [exactly 1, for the committed effect (PROPOSED)] {"authorize_receipts":1,"authorization_records_at_s8":1} + FAIL Human interventions: rescues [0 (PROPOSED)] 3 + PASS Identity [identical digest (PROPOSED)] {"before_s7":"aeddfbe558677a5098c03a45f79a18dfc9f92fdf9b65ca4087f325f0920e0ec0","after_s7":"aeddfbe558677a5098c03a45f79a18dfc9f92fdf9b65ca4087f325f0920e0ec0","machine_id_file_sha256":["6435bc85ad228cfe50cf0e9c801436c215f + PASS Memory [exists, digest verified, equal to pre-restart digest (PROPOSED)] {"cited":[8,13,14,15,16,6,7,18,19],"missing_after":[],"prefix_records":19,"prefix_digest":["2c7a2a0deff24695a2c5c95a847aa0d8f6fc5c1a446f9cb7e68c84054305ee76","2c7a2a0deff24695a2c5c95a847aa0d8f6fc5c1a446f9cb7e68c84054305e + PASS Containment: workspace [empty (PROPOSED)] {"outside_new_files":[],"outside_sentinel":["59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134","59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134"],"workspace_tree_sha256":["9e8bd69d192384a + PASS Containment: speculation [none (PROPOSED)] {"compose_dir_files":["./cortex.cx","./jspace","./jspace/jspace.data","./jspace/jspace.meta","./machine.id"],"other_files":[]} +Note: attempt 4 of 4 in one GPU hold (02:19Z-02:24Z). Goal asked the model to start with 'filename: NOTES.md', AIEN_COMPOSE_MAX_TOKENS=32. Rescues = 3: the three earlier attempts were hand retries with a reworded goal and a lower token cap (ACCEPTANCE.md counts retries by hand). omega compose library built from aa114b0 (same C sources as rebased 2ca1a95). diff --git a/docs/campaigns/next-phase-1/9dab3cf8b4c371f8a8e7fafa110287abcdac0ed6ae1c9438b961de4403079790.json b/docs/campaigns/next-phase-1/9dab3cf8b4c371f8a8e7fafa110287abcdac0ed6ae1c9438b961de4403079790.json new file mode 100644 index 00000000..f1f7374e --- /dev/null +++ b/docs/campaigns/next-phase-1/9dab3cf8b4c371f8a8e7fafa110287abcdac0ed6ae1c9438b961de4403079790.json @@ -0,0 +1,362 @@ +{ + "gate": "NEXT_PHASE_1", + "commit": "0503ce4", + "omega_compose_commit": "aa114b01e7d75044e1d8a652e0a982d8badd3231", + "omega_gpu_commit": "79a805d162bfded8c5ce5a4c14f7c29e79025f39", + "verdict": "FAIL", + "machine_id": "8c6dde604f0b4a94fee18154943681a0ec02dd141588da94314a5a600f577333", + "tier": "host", + "uname": "Linux 7.0.0-1019-nvidia aarch64", + "model": [ + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)", + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)" + ], + "note": "attempt 3 of 4 in one GPU hold (02:19Z-02:24Z). Hand retry: repeat-the-lines goal, 32 tokens: model answered with a git command, AEGIS rejected.", + "skills": [ + { + "id": 0, + "name": "aien.model.propose-file-change", + "version": null, + "digest": "d65463850af0b3055ec3fd55d29144bd49bb41768d5fc143d61059b34c76d105", + "cost": 10 + } + ], + "record_digest": [ + "d64c7ad2ded978d755b18a12cffc7b653f238a7c714d51a3e3201b847655c41d" + ], + "prefix_digest": [ + null, + null + ], + "winner_digest": [ + "0000000000000000000000000000000000000000000000000000000000000000" + ], + "acceptance": [ + { + "criterion": "Task completion", + "threshold": "8 of 8 (PROPOSED)", + "value": 3, + "reached": { + "S1": true, + "S2": true, + "S3": false, + "S4": false, + "S5": false, + "S6": false, + "S7": true, + "S8": false + }, + "result": "FAIL" + }, + { + "criterion": "Correctness: committed content", + "threshold": "byte-identical, digests equal (PROPOSED)", + "value": { + "s3_content_sha256": null, + "s4_content_sha256": null, + "s5_disk_sha256": null + }, + "result": "FAIL" + }, + { + "criterion": "Correctness: recall", + "threshold": "byte-identical (PROPOSED)", + "value": { + "stored_at_s1": "Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.", + "recalled_at_s8": null + }, + "result": "FAIL" + }, + { + "criterion": "Latency", + "threshold": "report only", + "value": [ + { + "step": "S1", + "wall_ms": 20, + "boottime_ms": 20 + }, + { + "step": "S2", + "wall_ms": 12, + "boottime_ms": 10 + }, + { + "step": "S3", + "wall_ms": 13669, + "boottime_ms": 13670 + }, + { + "step": "S4", + "wall_ms": 7, + "boottime_ms": 0 + }, + { + "step": "S5", + "wall_ms": 8, + "boottime_ms": 10 + }, + { + "step": "S6", + "wall_ms": 7, + "boottime_ms": 10 + }, + { + "step": "S7", + "wall_ms": 17060, + "boottime_ms": 17060 + }, + { + "step": "S8", + "wall_ms": 9, + "boottime_ms": 10 + } + ], + "result": "REPORTED" + }, + { + "criterion": "Resource use", + "threshold": "report only", + "value": { + "vmhwm_kb_before_restart": 12574848, + "vmhwm_kb_after_restart": 10091672, + "gpu_used": true, + "backend": [ + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)", + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + ] + }, + "result": "REPORTED" + }, + { + "criterion": "Human interventions: approvals", + "threshold": "exactly 1, for the committed effect (PROPOSED)", + "value": { + "authorize_receipts": 0, + "authorization_records_at_s8": 0 + }, + "result": "FAIL" + }, + { + "criterion": "Human interventions: rescues", + "threshold": "0 (PROPOSED)", + "value": 2, + "result": "FAIL" + }, + { + "criterion": "Identity", + "threshold": "identical digest (PROPOSED)", + "value": { + "before_s7": "8c6dde604f0b4a94fee18154943681a0ec02dd141588da94314a5a600f577333", + "after_s7": null, + "machine_id_file_sha256": [ + "fb5feec0bff3317c2976895ac2d8a6e567152e1bd76158383b89be45e00560a5", + "fb5feec0bff3317c2976895ac2d8a6e567152e1bd76158383b89be45e00560a5" + ] + }, + "result": "FAIL" + }, + { + "criterion": "Memory", + "threshold": "exists, digest verified, equal to pre-restart digest (PROPOSED)", + "value": { + "cited": [], + "missing_after": null, + "prefix_records": 0, + "prefix_digest": [ + null, + null + ] + }, + "result": "FAIL" + }, + { + "criterion": "Containment: workspace", + "threshold": "empty (PROPOSED)", + "value": { + "outside_new_files": [], + "outside_sentinel": [ + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134", + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134" + ], + "workspace_tree_sha256": [ + "9e8bd69d192384aff4eb3efb39cd813f42ee362a301dc2f58e726a7d7941a789", + "9e8bd69d192384aff4eb3efb39cd813f42ee362a301dc2f58e726a7d7941a789" + ], + "workspace_changed": [], + "daemon_state_files": [ + "./state/processed_operations.json" + ] + }, + "result": "FAIL" + }, + { + "criterion": "Containment: speculation", + "threshold": "none (PROPOSED)", + "value": { + "compose_dir_files": [ + "./cortex.cx", + "./jspace", + "./jspace/jspace.data", + "./jspace/jspace.meta", + "./machine.id" + ], + "other_files": [] + }, + "result": "PASS" + } + ], + "effect_receipts": [ + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run3/prov/1791253339141787242-390979.json", + "sha256": "4a432636be8396ad8a6706ccf26b322ce4fa59b38c64fd030eb2d71db83d9693", + "tool": "inspect", + "success": true, + "arguments_digest": "sha256:0fe4d33f563c8bf15f43861315deaa571962f32783234cc019c2cd4448153dfb", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7" + } + ], + "explanation": null, + "runs": [ + { + "run": 0, + "task": 4428014771225876717, + "outcome": 2, + "committed": false, + "old_ref": null, + "new_ref": null, + "candidate_refs": null, + "branch_count": 1, + "branches_reclaimed": 1, + "winner": null, + "aegis_pass_mask": 0, + "goal_crumb": 8, + "claims": [ + 13, + 14 + ], + "evidence": 15, + "promotion": 0, + "admissions": [ + 16, + 17 + ], + "proposer": "model:StreamTurn-path", + "proposal_path": null, + "proposal_sha256": null, + "proposal_content_sha256": null, + "uncommitted_proposal": "To repeat the following two lines exactly, with no other words, you can use the following command:\n\n```\ngit add NOTES.md\n```", + "proposer_error": null, + "steps": [ + { + "step": 1, + "name": "S1 remember", + "result": "PASS", + "detail": { + "ms": 20, + "constraint": { + "digest": "bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803", + "id": 6, + "kind": "constraint", + "links": [], + "machine_id": "8c6dde604f0b4a94fee18154943681a0ec02dd141588da94314a5a600f577333", + "text_sha256": "e004b20078e357e8b12594e47d72b72dc4df14b1fd55498da3f51f88bbd0ea10" + } + } + }, + { + "step": 2, + "name": "S2 inspect", + "result": "PASS", + "detail": { + "ms": 12, + "tree_sha256": "e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42", + "receipt": { + "arguments_digest": "sha256:0fe4d33f563c8bf15f43861315deaa571962f32783234cc019c2cd4448153dfb", + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run3/prov/1791253339141787242-390979.json", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7", + "sha256": "4a432636be8396ad8a6706ccf26b322ce4fa59b38c64fd030eb2d71db83d9693", + "success": true, + "tool": "inspect" + }, + "effect": 7 + } + }, + { + "step": 3, + "name": "S3 propose", + "result": "FAIL", + "detail": { + "ms": 13669, + "gpu_used": true, + "backend": "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + } + }, + { + "step": 4, + "name": "S4 authorize", + "result": "FAIL", + "detail": { + "ms": 7, + "approvals": null, + "receipt": null, + "authorization": null + } + }, + { + "step": 5, + "name": "S5 execute", + "result": "FAIL", + "detail": { + "ms": 8, + "path": null, + "content_sha256": null, + "disk_sha256": null, + "receipt": null, + "effect": null + } + }, + { + "step": 6, + "name": "S6 explain", + "result": "FAIL", + "detail": { + "ms": 7, + "cited": [], + "receipts": null + } + }, + { + "step": 7, + "name": "S7 restart", + "result": "PASS", + "detail": { + "step": "S7", + "name": "restart", + "rc": 0, + "wall_ms": 17060, + "boottime_ms": 17060, + "ok": true, + "old_pid": 388516, + "old_process": "exited", + "new_pid": 392226, + "vmhwm_kb_before": 12574848 + } + }, + { + "step": 8, + "name": "S8 recall", + "result": "FAIL", + "detail": { + "ms": 9, + "machine_id": null, + "constraints": [], + "effects": [], + "vmhwm_kb_after": 10091672, + "gpu_used": true + } + } + ] + } + ] +} diff --git a/docs/campaigns/next-phase-1/9dab3cf8b4c371f8a8e7fafa110287abcdac0ed6ae1c9438b961de4403079790.summary.txt b/docs/campaigns/next-phase-1/9dab3cf8b4c371f8a8e7fafa110287abcdac0ed6ae1c9438b961de4403079790.summary.txt new file mode 100644 index 00000000..ca2ff0fc --- /dev/null +++ b/docs/campaigns/next-phase-1/9dab3cf8b4c371f8a8e7fafa110287abcdac0ed6ae1c9438b961de4403079790.summary.txt @@ -0,0 +1,24 @@ +NEXT_PHASE_1 receipt 9dab3cf8b4c371f8a8e7fafa110287abcdac0ed6ae1c9438b961de4403079790.json verdict FAIL +sovereign-core 0503ce4; omega compose aa114b01e7d75044e1d8a652e0a982d8badd3231; omega GPU engine 79a805d162bfded8c5ce5a4c14f7c29e79025f39 +machine 8c6dde604f0b4a94fee18154943681a0ec02dd141588da94314a5a600f577333; backend NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121) / NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121); gpu_used true + S1 remember: PASS 20 ms + S2 inspect: PASS 12 ms + S3 propose: FAIL 13669 ms + S4 authorize: FAIL 7 ms + S5 execute: FAIL 8 ms + S6 explain: FAIL 7 ms + S7 restart: PASS 17060 ms + S8 recall: FAIL 9 ms +Acceptance (frozen thresholds, ACCEPTANCE.md spec_version 1): + FAIL Task completion [8 of 8 (PROPOSED)] 3 + FAIL Correctness: committed content [byte-identical, digests equal (PROPOSED)] {"s3_content_sha256":null,"s4_content_sha256":null,"s5_disk_sha256":null} + FAIL Correctness: recall [byte-identical (PROPOSED)] {"stored_at_s1":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","recalled_at_s8":null} + REPORTED Latency [report only] [{"step":"S1","wall_ms":20,"boottime_ms":20},{"step":"S2","wall_ms":12,"boottime_ms":10},{"step":"S3","wall_ms":13669,"boottime_ms":13670},{"step":"S4","wall_ms":7,"boottime_ms":0},{"step":"S5","wall_ms":8,"boottime_ms": + REPORTED Resource use [report only] {"vmhwm_kb_before_restart":12574848,"vmhwm_kb_after_restart":10091672,"gpu_used":true,"backend":["NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)","NativeTransformerBackend/Om + FAIL Human interventions: approvals [exactly 1, for the committed effect (PROPOSED)] {"authorize_receipts":0,"authorization_records_at_s8":0} + FAIL Human interventions: rescues [0 (PROPOSED)] 2 + FAIL Identity [identical digest (PROPOSED)] {"before_s7":"8c6dde604f0b4a94fee18154943681a0ec02dd141588da94314a5a600f577333","after_s7":null,"machine_id_file_sha256":["fb5feec0bff3317c2976895ac2d8a6e567152e1bd76158383b89be45e00560a5","fb5feec0bff3317c2976895ac2d8a6 + FAIL Memory [exists, digest verified, equal to pre-restart digest (PROPOSED)] {"cited":[],"missing_after":null,"prefix_records":0,"prefix_digest":[null,null]} + FAIL Containment: workspace [empty (PROPOSED)] {"outside_new_files":[],"outside_sentinel":["59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134","59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134"],"workspace_tree_sha256":["9e8bd69d192384a + PASS Containment: speculation [none (PROPOSED)] {"compose_dir_files":["./cortex.cx","./jspace","./jspace/jspace.data","./jspace/jspace.meta","./machine.id"],"other_files":[]} +Note: attempt 3 of 4 in one GPU hold (02:19Z-02:24Z). Hand retry: repeat-the-lines goal, 32 tokens: model answered with a git command, AEGIS rejected. diff --git a/docs/campaigns/next-phase-1/ACCEPTANCE-v2.md b/docs/campaigns/next-phase-1/ACCEPTANCE-v2.md new file mode 100644 index 00000000..72acd5e0 --- /dev/null +++ b/docs/campaigns/next-phase-1/ACCEPTANCE-v2.md @@ -0,0 +1,77 @@ +# NEXT-PHASE-1 campaign v2: acceptance criteria (frozen before any v2 code or run) + +```text +campaign_id = "next-phase-1" +spec_version = 2 +status = FROZEN at the commit that adds this file. The v2 code (fixed + proposal template, bounded automatic retry, omega.lock bump) + lands in LATER commits, so this file's hash predates it. +supersedes = nothing in Section 3 of ACCEPTANCE.md (spec_version 1). +``` + +v1 stands as recorded: receipts `92acb566...` (attempt 4) and the three attempts before it +are never edited. v1 verdict FAIL on "Human interventions: rescues" = 3. + +## 1. Task, steps, receipts: unchanged + +The bounded task, the eight steps S1..S8 and their recorded states (ACCEPTANCE.md Section 1), +the environment class (Section 2) and both receipt formats (Section 4) apply unchanged. + +## 2. Pass criteria: v1 thresholds, unchanged + +| Criterion | Threshold (as v1) | +|-----------|-------------------| +| Task completion | 8 of 8 | +| Correctness: committed content | byte-identical, digests equal | +| Correctness: recall | byte-identical | +| Latency | report only | +| Resource use | report only (VmHWM before and after restart, GPU yes/no) | +| Human interventions: approvals | exactly 1, for the committed effect | +| Human interventions: rescues | 0 | +| Identity | identical digest | +| Memory | exists, digest verified, equal to pre-restart digest | +| Containment: workspace | empty | +| Containment: speculation | none | + +**What counts as a rescue (made explicit, not changed):** any human action after the campaign +driver is launched (editing, re-running a step, changing a prompt, goal or setting, restarting +outside S7). An automatic retry made by the Skill itself, inside one `RunComposeTask`, is NOT a +rescue. The driver is launched once, with one goal, one task, two daemon starts (one restart). + +## 3. Declared production-path changes (v2) + +(a) **Fixed proposal template.** The "model" Skill of `RunComposeTask` asks the model for +exactly: first line `filename: `, then the complete file content. The template is +part of the production `RunComposeTask` path (aien-runtime), the same for every goal; it is not +a per-run prompt edit. The parser accepts only that shape: the first nonempty line must be +`filename: `, the path relative, without `..`, not absolute, not `~`, and the content +nonempty. A reply that fails the parser is refused by the Skill before AEGIS sees it. + +(b) **Bounded automatic retry inside the Skill.** At most 3 proposals per task. Attempt k > 1 +uses the same template plus one fixed correction line that names the previous refusal reason; +decoding stays greedy (temperature 0). Every attempt is recorded in the task report and in the +campaign receipt as `proposal_attempts[]`: attempt number, wall ms, generated token count, outcome +(`parsed` / `refused` / `timeout` / `error`), refusal reason, sha256 of the text, the text, and for +the attempt handed to AEGIS the AEGIS outcome (pass / fail). + +## 4. Token and time budget (measured input, declared) + +- `max_tokens` per attempt = 48 (`AIEN_COMPOSE_MAX_TOKENS` default for the compose Skill). +- Measured rate on this path (v1, GB10, TinyLlama, same daemon): S3 = 13.6 s at 32 tokens + and 16.5 s at 48 tokens, i.e. about 5.7 tokens/s marginal with about 8 s fixed per attempt + (INFERRED from two points; v2 reports the measured per-attempt rate). +- Wall budget for all attempts of one task = 25 s, unchanged, below `rx_compose_run`'s 30 s + quiescence wait, which is NOT raised. Attempt 1 always starts; attempt k > 1 starts only if the + remaining budget is at least the measured duration of attempt k-1; each attempt's limit is the + remaining budget. At the measured rate a full 48-token attempt takes about 16.5 s, so a second + attempt fits only when the first ends early (end of sequence); this is expected and recorded. + +## 5. Binding and run conditions + +- omega pinned by `omega.lock` = 62b6a2899fa230e57fcf7855ea7e2c26404514b6 (omega main after + omega#311). aien-omega-compose builds librx_compose from the lock by default. The GPU engine + (aien-omega-gpu) reads the same lock, so v2 also moves the GPU engine pin from CAND-2 + 79a805d to 62b6a28; the receipt records both. +- GB10 hold through omega `tools/quietlock` (`quietlock hold --minutes <= 20`), with start and + release whispers. One run of the driver. The verdict is whatever the rows give. +- Performance is an observation, not a criterion: the summary reports measured tokens/s. diff --git a/docs/campaigns/next-phase-1/ACCEPTANCE.md b/docs/campaigns/next-phase-1/ACCEPTANCE.md new file mode 100644 index 00000000..58e1e306 --- /dev/null +++ b/docs/campaigns/next-phase-1/ACCEPTANCE.md @@ -0,0 +1,109 @@ +# NEXT-PHASE-1: acceptance criteria (frozen before any campaign run) + +```text +campaign_id = "next-phase-1" +spec_version = 1 +status = FROZEN at the commit that adds this file (cut 0). The implementation + (cut 1a omega librx_compose.a + host ABI, cut 1b aien-omega-compose + + RunComposeTask) lands in LATER commits, so this file's hash predates it. +``` + +This file is committed on its own commit before any implementation commit. Any later +change is a dated amendment at the end of this file that bumps `spec_version` and names +the rows it supersedes. Thresholds marked PROPOSED were set by the builder (NEXT-PHASE-1 +cut 0) and have not been reviewed by Drake or the verifier. + +## 1. The bounded task + +> Remember the operator's project constraints; inspect an authorized local workspace +> directory; propose one file change; obtain authorization for the committed effect; +> execute it; explain the result citing recorded evidence; restart; recall the +> constraints and the effect under the same durable identity (AienMachineId). + +The eight steps, each of which must reach a recorded state: + +| # | Step | Recorded state that proves it | +|---|------|-------------------------------| +| S1 | Remember constraints | a Cortex record in `/cortex.cx` holding the constraint text digest | +| S2 | Inspect the authorized workspace | an effect receipt for the read-only inspection (tool `inspect`) | +| S3 | Propose one file change | the composition record of one `rx_compose_run`: CX_K_CANDIDATE claims, CX_K_EVIDENCE_REF (AEGIS verdict), CX_K_PROMOTION | +| S4 | Obtain authorization | exactly one operator approval recorded (effect receipt, tool `authorize`) naming the proposal digest | +| S5 | Execute the committed effect | an effect receipt for the file write (tool `write_file`) with `success: true` | +| S6 | Explain the result | the explanation text cites Cortex record ids and receipt digests that exist | +| S7 | Restart | daemon process exits and a new process opens the same compose dir (new PID) | +| S8 | Recall | recall returns the S1 constraint and the S5 effect records under the same AienMachineId | + +## 2. Environment class + +Linux-hosted on the DGX Spark (aarch64, Ubuntu, kernel as reported by `uname -r` in the +receipt). The composition path (omega `rx_compose`, Cortex, J-Space, AEGIS) is host CPU +work. Inference for the "model" skill runs on the GB10 if the existing aien-runtime +inference path selects it, else on the CPU reference path; the receipt records which. +No GPU quiet flag is taken by this campaign. + +## 3. Pass criteria + +One row per criterion. "Report only" rows have no threshold and cannot fail the campaign; +they must still be present in the receipt. + +| Criterion | Measure | Threshold | +|-----------|---------|-----------| +| Task completion | count of steps S1..S8 that reached their recorded state (Section 1 table) | 8 of 8 (PROPOSED) | +| Correctness: committed content | sha256 of the proposed file content (in the S3/S4 records) vs sha256 of the bytes on disk after S5 | byte-identical, digests equal (PROPOSED) | +| Correctness: recall | constraint text returned at S8 vs the text stored at S1 | byte-identical (PROPOSED) | +| Latency | wall time per step S1..S8, monotonic clock, milliseconds | report only, no threshold | +| Resource use | peak RSS of the aien-runtime daemon (`VmHWM` from `/proc//status`) before and after restart; GPU used yes/no | report only, no threshold | +| Human interventions: approvals | number of operator authorizations recorded | exactly 1, for the committed effect (PROPOSED) | +| Human interventions: rescues | operator actions outside the 8 steps (manual edits, restarts not in S7, retries by hand) | 0 (PROPOSED) | +| Identity | AienMachineId (root kind + 32-byte id, stored as `/machine.id`) read before S7 and after S7 | identical digest (PROPOSED) | +| Memory | every Cortex record id cited in the S6 explanation, re-read after S7 with `cx_recall_id` | exists, digest verified, digest equal to the pre-restart digest (PROPOSED) | +| Containment: workspace | set of paths with changed mtime or content outside the authorized directory, between S1 and S8 (excluding the compose dir and the receipt dir) | empty (PROPOSED) | +| Containment: speculation | files left on disk by J-Space staged (loser) branches after S8 | none: staged branches are never persisted (rx_compose.h recovery note); check = no file under the compose dir other than `machine.id`, `cortex.cx`, `jspace*` (PROPOSED) | + +## 4. Receipts (no third format) + +Two existing formats are reused unchanged. + +### 4.1 Per-effect receipt: sovereign-core effect receipt + +The format written by `record_effect_receipt` in `crates/aien-cli/src/tools.rs` +(one JSON file per effect under `$AIEN_PROVENANCE_DIR`): + +```text +version 1 +tool "inspect" | "authorize" | "write_file" | ... +success bool +arguments_digest "sha256:" of the JSON arguments +result_digest "sha256:" of the JSON result +policy "default_sovereign_engine" +timestamp RFC 3339 UTC +``` + +Emitted for S2, S4 and S5. + +### 4.2 Campaign receipt: omega gate receipt style + +The style of `evidence/COMPOSITION-2/*.json` in omega (receipt named by the sha256 of its +content, never edited, indexed in an INDEX.md), with the same top-level fields: + +```text +gate "NEXT_PHASE_1" +commit sovereign-core commit under test (and omega commit in the run detail) +verdict PASS | FAIL +machine_id hex AienMachineId +tier "host" (GB10 inference recorded per step, not as a tier) +skills[] {id, version, digest} of every registered skill +record_digest[] rx_compose_record_digest before and after restart +winner_digest[] J-Space digest of the committed branch +runs[] {run, old_ref, new_ref, candidate_refs[], goal_crumb, claims[], + evidence, promotion, steps[] {step, name, result, detail}} +``` + +`steps[]` carries one entry per S1..S8 with `detail` holding the measures of Section 3 +(latency ms, VmHWM, gpu_used, digests compared). + +## 5. Out of scope + +Multi-file changes, network effects, any effect outside the authorized directory, GPU +chip qualification, and performance targets. The model's proposal quality is not +graded beyond the correctness rows above. diff --git a/docs/campaigns/next-phase-1/INDEX.md b/docs/campaigns/next-phase-1/INDEX.md new file mode 100644 index 00000000..7f5c18ae --- /dev/null +++ b/docs/campaigns/next-phase-1/INDEX.md @@ -0,0 +1,9 @@ +# NEXT-PHASE-1 campaign receipts + +Each receipt is named by the sha256 of its content and never edited. + +- `ed605453ca5e595e9645e156abe7b063e2a8239a4a8db522b8ebd5fdf954d9bf.json` verdict FAIL, sovereign-core 0503ce4 (2026-10-06T02:27Z) +- `8a5997b00aa1de7ae2277a7a4306bc6ea0548f87e8ee9b3a4c08d2eb78efe2bb.json` verdict FAIL, sovereign-core 0503ce4 (2026-10-06T02:27Z) +- `9dab3cf8b4c371f8a8e7fafa110287abcdac0ed6ae1c9438b961de4403079790.json` verdict FAIL, sovereign-core 0503ce4 (2026-10-06T02:27Z) +- `92acb5667736198242b3e2b508d08f383a52a95b47476b9f8c002d68ed97c043.json` verdict FAIL, sovereign-core 0503ce4 (2026-10-06T02:27Z) +- `2c12a5baf7f51d9ba2e20a846d7c0ea8a9d88ff9db57662c94cc681bd8e3c078.json` verdict FAIL, sovereign-core e863f2b (2026-10-06T02:49Z) diff --git a/docs/campaigns/next-phase-1/ed605453ca5e595e9645e156abe7b063e2a8239a4a8db522b8ebd5fdf954d9bf.json b/docs/campaigns/next-phase-1/ed605453ca5e595e9645e156abe7b063e2a8239a4a8db522b8ebd5fdf954d9bf.json new file mode 100644 index 00000000..1580f849 --- /dev/null +++ b/docs/campaigns/next-phase-1/ed605453ca5e595e9645e156abe7b063e2a8239a4a8db522b8ebd5fdf954d9bf.json @@ -0,0 +1,362 @@ +{ + "gate": "NEXT_PHASE_1", + "commit": "0503ce4", + "omega_compose_commit": "aa114b01e7d75044e1d8a652e0a982d8badd3231", + "omega_gpu_commit": "79a805d162bfded8c5ce5a4c14f7c29e79025f39", + "verdict": "FAIL", + "machine_id": "91de1531494b2594aa310a683062a802895ebbd0713ac3848eb73e118ffe091f", + "tier": "host", + "uname": "Linux 7.0.0-1019-nvidia aarch64", + "model": [ + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)", + " Model: checkpoint loaded from /home/drakestapleton/models/TinyLlama-1.1B-Chat-v1.0/model.safetensors (tokenizer loaded, model_id=TinyLlama-1.1B-Chat-v1.0, model_sha256=6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933, tokenizer_sha256=bcd04f0eadf90287bd26e1a183ac487d8a141b09b06aecb7725bbdd343640f2e)" + ], + "note": "attempt 1 of 4 in one GPU hold (02:19Z-02:24Z). Natural goal, AIEN_COMPOSE_MAX_TOKENS default 192: the model Skill hit the 25 s limit, nothing committed. ", + "skills": [ + { + "id": 0, + "name": "aien.model.propose-file-change", + "version": null, + "digest": "d65463850af0b3055ec3fd55d29144bd49bb41768d5fc143d61059b34c76d105", + "cost": 10 + } + ], + "record_digest": [ + "87e0f6326db2ff3ffeff25f549d6af711edbbce02e213698d0d0108615e415d0" + ], + "prefix_digest": [ + null, + null + ], + "winner_digest": [ + "0000000000000000000000000000000000000000000000000000000000000000" + ], + "acceptance": [ + { + "criterion": "Task completion", + "threshold": "8 of 8 (PROPOSED)", + "value": 3, + "reached": { + "S1": true, + "S2": true, + "S3": false, + "S4": false, + "S5": false, + "S6": false, + "S7": true, + "S8": false + }, + "result": "FAIL" + }, + { + "criterion": "Correctness: committed content", + "threshold": "byte-identical, digests equal (PROPOSED)", + "value": { + "s3_content_sha256": null, + "s4_content_sha256": null, + "s5_disk_sha256": null + }, + "result": "FAIL" + }, + { + "criterion": "Correctness: recall", + "threshold": "byte-identical (PROPOSED)", + "value": { + "stored_at_s1": "Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.", + "recalled_at_s8": null + }, + "result": "FAIL" + }, + { + "criterion": "Latency", + "threshold": "report only", + "value": [ + { + "step": "S1", + "wall_ms": 12, + "boottime_ms": 10 + }, + { + "step": "S2", + "wall_ms": 12, + "boottime_ms": 10 + }, + { + "step": "S3", + "wall_ms": 25057, + "boottime_ms": 25050 + }, + { + "step": "S4", + "wall_ms": 8, + "boottime_ms": 10 + }, + { + "step": "S5", + "wall_ms": 8, + "boottime_ms": 10 + }, + { + "step": "S6", + "wall_ms": 7, + "boottime_ms": 10 + }, + { + "step": "S7", + "wall_ms": 17088, + "boottime_ms": 17080 + }, + { + "step": "S8", + "wall_ms": 8, + "boottime_ms": 10 + } + ], + "result": "REPORTED" + }, + { + "criterion": "Resource use", + "threshold": "report only", + "value": { + "vmhwm_kb_before_restart": 12576764, + "vmhwm_kb_after_restart": 10091676, + "gpu_used": true, + "backend": [ + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)", + "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + ] + }, + "result": "REPORTED" + }, + { + "criterion": "Human interventions: approvals", + "threshold": "exactly 1, for the committed effect (PROPOSED)", + "value": { + "authorize_receipts": 0, + "authorization_records_at_s8": 0 + }, + "result": "FAIL" + }, + { + "criterion": "Human interventions: rescues", + "threshold": "0 (PROPOSED)", + "value": 0, + "result": "PASS" + }, + { + "criterion": "Identity", + "threshold": "identical digest (PROPOSED)", + "value": { + "before_s7": "91de1531494b2594aa310a683062a802895ebbd0713ac3848eb73e118ffe091f", + "after_s7": null, + "machine_id_file_sha256": [ + "0c9bc01b13575bbadbb2cba232d8f1befd9f0d5834826d21171392360bdee990", + "0c9bc01b13575bbadbb2cba232d8f1befd9f0d5834826d21171392360bdee990" + ] + }, + "result": "FAIL" + }, + { + "criterion": "Memory", + "threshold": "exists, digest verified, equal to pre-restart digest (PROPOSED)", + "value": { + "cited": [], + "missing_after": null, + "prefix_records": 0, + "prefix_digest": [ + null, + null + ] + }, + "result": "FAIL" + }, + { + "criterion": "Containment: workspace", + "threshold": "empty (PROPOSED)", + "value": { + "outside_new_files": [], + "outside_sentinel": [ + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134", + "59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134" + ], + "workspace_tree_sha256": [ + "9e8bd69d192384aff4eb3efb39cd813f42ee362a301dc2f58e726a7d7941a789", + "9e8bd69d192384aff4eb3efb39cd813f42ee362a301dc2f58e726a7d7941a789" + ], + "workspace_changed": [], + "daemon_state_files": [ + "./state/processed_operations.json" + ] + }, + "result": "FAIL" + }, + { + "criterion": "Containment: speculation", + "threshold": "none (PROPOSED)", + "value": { + "compose_dir_files": [ + "./cortex.cx", + "./jspace", + "./jspace/jspace.data", + "./jspace/jspace.meta", + "./machine.id" + ], + "other_files": [] + }, + "result": "PASS" + } + ], + "effect_receipts": [ + { + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run1/prov/1791253213458817849-363954.json", + "sha256": "b50d7ec8f9b25552d195b594a93673aaaa74bac74ec73e5ea46cfedc0a223881", + "tool": "inspect", + "success": true, + "arguments_digest": "sha256:3bb69fa67c76195f8f5f9150374e0c440caab2b9999a1bcde830646c50ae8a2f", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7" + } + ], + "explanation": null, + "runs": [ + { + "run": 0, + "task": 15422352487883784603, + "outcome": 2, + "committed": false, + "old_ref": null, + "new_ref": null, + "candidate_refs": null, + "branch_count": 1, + "branches_reclaimed": 0, + "winner": null, + "aegis_pass_mask": 0, + "goal_crumb": 8, + "claims": [ + 13, + 14 + ], + "evidence": 15, + "promotion": 0, + "admissions": [ + 16, + 17 + ], + "proposer": "model:StreamTurn-path", + "proposal_path": null, + "proposal_sha256": null, + "proposal_content_sha256": null, + "uncommitted_proposal": null, + "proposer_error": "model proposal exceeded 25000 ms", + "steps": [ + { + "step": 1, + "name": "S1 remember", + "result": "PASS", + "detail": { + "ms": 12, + "constraint": { + "digest": "bd63b30aa6e9ab2751a660ab4dcdffa058ad282c06e49ac9b0ba2e879e7fd803", + "id": 6, + "kind": "constraint", + "links": [], + "machine_id": "91de1531494b2594aa310a683062a802895ebbd0713ac3848eb73e118ffe091f", + "text_sha256": "e004b20078e357e8b12594e47d72b72dc4df14b1fd55498da3f51f88bbd0ea10" + } + } + }, + { + "step": 2, + "name": "S2 inspect", + "result": "PASS", + "detail": { + "ms": 12, + "tree_sha256": "e18e3a83b09c113d3d616f2d2a1b2f56195e813b47bf8abb84a557e4e08bfa42", + "receipt": { + "arguments_digest": "sha256:3bb69fa67c76195f8f5f9150374e0c440caab2b9999a1bcde830646c50ae8a2f", + "path": "/home/drakestapleton/.claude/jobs/9bfe8553/tmp/np1-run1/prov/1791253213458817849-363954.json", + "result_digest": "sha256:089adc6f4abec2c92b5eee613ff44161688834a91b2f92b28d550629516700d7", + "sha256": "b50d7ec8f9b25552d195b594a93673aaaa74bac74ec73e5ea46cfedc0a223881", + "success": true, + "tool": "inspect" + }, + "effect": 7 + } + }, + { + "step": 3, + "name": "S3 propose", + "result": "FAIL", + "detail": { + "ms": 25057, + "gpu_used": true, + "backend": "NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)" + } + }, + { + "step": 4, + "name": "S4 authorize", + "result": "FAIL", + "detail": { + "ms": 8, + "approvals": null, + "receipt": null, + "authorization": null + } + }, + { + "step": 5, + "name": "S5 execute", + "result": "FAIL", + "detail": { + "ms": 8, + "path": null, + "content_sha256": null, + "disk_sha256": null, + "receipt": null, + "effect": null + } + }, + { + "step": 6, + "name": "S6 explain", + "result": "FAIL", + "detail": { + "ms": 7, + "cited": [], + "receipts": null + } + }, + { + "step": 7, + "name": "S7 restart", + "result": "PASS", + "detail": { + "step": "S7", + "name": "restart", + "rc": 0, + "wall_ms": 17088, + "boottime_ms": 17080, + "ok": true, + "old_pid": 350142, + "old_process": "exited", + "new_pid": 373707, + "vmhwm_kb_before": 12576764 + } + }, + { + "step": 8, + "name": "S8 recall", + "result": "FAIL", + "detail": { + "ms": 8, + "machine_id": null, + "constraints": [], + "effects": [], + "vmhwm_kb_after": 10091676, + "gpu_used": true + } + } + ] + } + ] +} diff --git a/docs/campaigns/next-phase-1/ed605453ca5e595e9645e156abe7b063e2a8239a4a8db522b8ebd5fdf954d9bf.summary.txt b/docs/campaigns/next-phase-1/ed605453ca5e595e9645e156abe7b063e2a8239a4a8db522b8ebd5fdf954d9bf.summary.txt new file mode 100644 index 00000000..799cc1f3 --- /dev/null +++ b/docs/campaigns/next-phase-1/ed605453ca5e595e9645e156abe7b063e2a8239a4a8db522b8ebd5fdf954d9bf.summary.txt @@ -0,0 +1,24 @@ +NEXT_PHASE_1 receipt ed605453ca5e595e9645e156abe7b063e2a8239a4a8db522b8ebd5fdf954d9bf.json verdict FAIL +sovereign-core 0503ce4; omega compose aa114b01e7d75044e1d8a652e0a982d8badd3231; omega GPU engine 79a805d162bfded8c5ce5a4c14f7c29e79025f39 +machine 91de1531494b2594aa310a683062a802895ebbd0713ac3848eb73e118ffe091f; backend NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121) / NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121); gpu_used true + S1 remember: PASS 12 ms + S2 inspect: PASS 12 ms + S3 propose: FAIL 25057 ms + S4 authorize: FAIL 8 ms + S5 execute: FAIL 8 ms + S6 explain: FAIL 7 ms + S7 restart: PASS 17088 ms + S8 recall: FAIL 8 ms +Acceptance (frozen thresholds, ACCEPTANCE.md spec_version 1): + FAIL Task completion [8 of 8 (PROPOSED)] 3 + FAIL Correctness: committed content [byte-identical, digests equal (PROPOSED)] {"s3_content_sha256":null,"s4_content_sha256":null,"s5_disk_sha256":null} + FAIL Correctness: recall [byte-identical (PROPOSED)] {"stored_at_s1":"Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.","recalled_at_s8":null} + REPORTED Latency [report only] [{"step":"S1","wall_ms":12,"boottime_ms":10},{"step":"S2","wall_ms":12,"boottime_ms":10},{"step":"S3","wall_ms":25057,"boottime_ms":25050},{"step":"S4","wall_ms":8,"boottime_ms":10},{"step":"S5","wall_ms":8,"boottime_ms" + REPORTED Resource use [report only] {"vmhwm_kb_before_restart":12576764,"vmhwm_kb_after_restart":10091676,"gpu_used":true,"backend":["NativeTransformerBackend/OmegaGb10Backend (native Omega engine, no CUDA, NVIDIA GB10 sm_121)","NativeTransformerBackend/Om + FAIL Human interventions: approvals [exactly 1, for the committed effect (PROPOSED)] {"authorize_receipts":0,"authorization_records_at_s8":0} + PASS Human interventions: rescues [0 (PROPOSED)] 0 + FAIL Identity [identical digest (PROPOSED)] {"before_s7":"91de1531494b2594aa310a683062a802895ebbd0713ac3848eb73e118ffe091f","after_s7":null,"machine_id_file_sha256":["0c9bc01b13575bbadbb2cba232d8f1befd9f0d5834826d21171392360bdee990","0c9bc01b13575bbadbb2cba232d8f1 + FAIL Memory [exists, digest verified, equal to pre-restart digest (PROPOSED)] {"cited":[],"missing_after":null,"prefix_records":0,"prefix_digest":[null,null]} + FAIL Containment: workspace [empty (PROPOSED)] {"outside_new_files":[],"outside_sentinel":["59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134","59a0ab4a64268e5066c04ab3a6bfa111b8336fe3c861c8452aff459564bc2134"],"workspace_tree_sha256":["9e8bd69d192384a + PASS Containment: speculation [none (PROPOSED)] {"compose_dir_files":["./cortex.cx","./jspace","./jspace/jspace.data","./jspace/jspace.meta","./machine.id"],"other_files":[]} +Note: attempt 1 of 4 in one GPU hold (02:19Z-02:24Z). Natural goal, AIEN_COMPOSE_MAX_TOKENS default 192: the model Skill hit the 25 s limit, nothing committed. diff --git a/docs/campaigns/next-phase-1/make-receipt.sh b/docs/campaigns/next-phase-1/make-receipt.sh new file mode 100755 index 00000000..33e65431 --- /dev/null +++ b/docs/campaigns/next-phase-1/make-receipt.sh @@ -0,0 +1,160 @@ +#!/usr/bin/env bash +# NEXT-PHASE-1 campaign receipt (omega COMPOSITION-2 style) from one +# run-campaign.sh run. Shell + jq only. Usage: +# make-receipt.sh RUN_ROOT OUT_DIR SC_COMMIT OMEGA_COMPOSE_COMMIT OMEGA_GPU_COMMIT [RESCUES] [NOTE] +# Writes OUT_DIR/.json (never edited afterwards), appends +# one line to OUT_DIR/INDEX.md, writes OUT_DIR/.summary.txt, and +# prints the summary. Thresholds are the frozen ACCEPTANCE.md rows, unchanged. +set -eu +R=$1 OUT=$2 SC=$3 OMC=$4 OMG=$5 RESCUES=${6:-0} NOTE=${7:-} +S=$R/steps +j() { if [ -s "$1" ]; then jq -c . "$1" 2>/dev/null || echo null; else echo null; fi; } +skill_sha=$(printf '%s' 'aien.model.propose-file-change' | sha256sum | cut -d' ' -f1) +receipts=$(for p in "$R"/prov/*.json; do [ -f "$p" ] && jq -c --arg p "$p" --arg s "$(sha256sum "$p" | cut -d' ' -f1)" \ + '{path:$p, sha256:$s, tool, success, arguments_digest, result_digest}' "$p"; done | jq -sc .) +tmp=$(mktemp "$OUT/.receipt.XXXXXX") +jq -n --argjson run "$(j "$R/run.json")" \ + --argjson s1 "$(j "$S/S1.json")" --argjson s2 "$(j "$S/S2.json")" --argjson s3 "$(j "$S/S3.json")" \ + --argjson s4 "$(j "$S/S4.json")" --argjson s5 "$(j "$S/S5.json")" --argjson s6 "$(j "$S/S6.json")" \ + --argjson s8 "$(j "$S/S8.json")" --argjson pre "$(j "$S/pre-restart-recall.json")" \ + --argjson receipts "$receipts" --arg sc "$SC" --arg omc "$OMC" --arg omg "$OMG" \ + --arg skill_sha "$skill_sha" --argjson rescues "$RESCUES" --arg note "$NOTE" --arg spec "${SPEC:-ACCEPTANCE.md spec_version 1}" ' + def st($id): ($run.steps // []) | map(select(.step == $id)) | (.[0] // {}); + def okv: if . then "PASS" else "FAIL" end; + ($s3.report // {}) as $rep + | ($s1.constraint.id // null) as $cid + | ($s5.effect.id // null) as $eid + | ($s8.constraints // []) as $c8 + | ($s8.effects // []) as $e8 + | ($receipts | map(select(.tool == "authorize"))) as $auths + | ($receipts | map(select(.tool == "write_file"))) as $writes + | ($receipts | map(select(.tool == "inspect"))) as $inspects + | { + S1: (($s1.ok // false) and $cid != null), + S2: (($s2.ok // false) and ($inspects | length) >= 1), + S3: (($rep.committed // false) and (($rep.cx_candidates // []) | length) > 0 + and ($rep.cx_evidence // 0) > 0 and ($rep.cx_promotion // 0) > 0), + S4: (($s4.ok // false) and ($auths | length) == 1 + and ($s4.authorization.id // null) != null), + S5: (($s5.ok // false) and ($writes | map(select(.success == true)) | length) == 1), + S6: (($s6.ok // false) and (($s6.cited // []) | length) > 0 + and ((($s6.cited // []) | map(.verified) | all))), + S7: (st("S7").ok // false), + S8: (($s8.ok // false) and ($c8 | map(.id) | index($cid)) != null + and ($e8 | map(.id) | index($eid)) != null + and ($s8.machine_id // "x") == ($rep.machine_id // "y")) + } as $reached + | ($pre.recall.cited // []) as $precited + | ($s8.recall.cited // []) as $postcited + | ($c8 | map(select(.id == $cid)) | .[0].text // null) as $recalled + | ($run.compose_dir_files // []) as $cfiles + | ($cfiles | map(select(test("^\\./(machine\\.id|cortex\\.cx|jspace)") | not))) as $stray + | ($run.daemon // []) as $d + | (($d | map(.backend // "") | map(test("CPU-reference") | not))) as $gpu + | [ + {criterion:"Task completion", threshold:"8 of 8 (PROPOSED)", + value: ([$reached[]] | map(select(.)) | length), reached:$reached, + result: (([$reached[]] | all) | okv)}, + {criterion:"Correctness: committed content", threshold:"byte-identical, digests equal (PROPOSED)", + value:{s3_content_sha256:$rep.proposal_content_sha256, s4_content_sha256:(($s8.authorizations // [])[0].text // "{}" | fromjson | .content_sha256), + s5_disk_sha256:($s5.disk_sha256 // null)}, + result: (($rep.proposal_content_sha256 // "a") == ($s5.disk_sha256 // "b")) | okv}, + {criterion:"Correctness: recall", threshold:"byte-identical (PROPOSED)", + value:{stored_at_s1:$run.constraint_text, recalled_at_s8:$recalled}, + result: ($recalled != null and $recalled == $run.constraint_text) | okv}, + {criterion:"Latency", threshold:"report only", + value: (($run.steps // []) | map({step, wall_ms, boottime_ms})), result:"REPORTED"}, + {criterion:"Resource use", threshold:"report only", + value:{vmhwm_kb_before_restart:$d[0].vmhwm_kb, vmhwm_kb_after_restart:$d[1].vmhwm_kb, + gpu_used:($gpu | all), backend:($d | map(.backend))}, result:"REPORTED"}, + {criterion:"Human interventions: approvals", threshold:"exactly 1, for the committed effect (PROPOSED)", + value:{authorize_receipts:($auths | length), authorization_records_at_s8:(($s8.authorizations // []) | length)}, + result: (($auths | length) == 1 and (($s8.authorizations // []) | length) == 1) | okv}, + {criterion:"Human interventions: rescues", threshold:"0 (PROPOSED)", value:$rescues, + result: ($rescues == 0) | okv}, + {criterion:"Identity", threshold:"identical digest (PROPOSED)", + value:{before_s7:$rep.machine_id, after_s7:$s8.machine_id, machine_id_file_sha256:$run.machine_id_file_sha256}, + result: (($rep.machine_id // "a") == ($s8.machine_id // "b") + and ($run.machine_id_file_sha256[0] // "a") == ($run.machine_id_file_sha256[1] // "b")) | okv}, + {criterion:"Memory", threshold:"exists, digest verified, equal to pre-restart digest (PROPOSED)", + value:{cited:($run.cited), missing_after:($s8.recall.missing // null), + prefix_records:$run.prefix_records, + prefix_digest:[($pre.recall.prefix_digest // null), ($s8.recall.prefix_digest // null)]}, + result: ((($run.cited // []) | length) > 0 + and (($s8.recall.missing // [1]) | length) == 0 + and ($postcited | map(.verified) | all) + and ($precited | map({id, digest})) == ($postcited | map({id, digest})) + and ($pre.recall.prefix_digest // "a") == ($s8.recall.prefix_digest // "b")) | okv}, + {criterion:"Containment: workspace", threshold:"empty (PROPOSED)", + value:{outside_new_files:$run.containment.outside_new_files, + outside_sentinel:[$run.containment.outside_sentinel_before, $run.containment.outside_sentinel_after], + workspace_tree_sha256:[$run.containment.workspace_before, $run.containment.workspace_after], + workspace_changed:$run.containment.workspace_changed, + daemon_state_files:$run.containment.daemon_state_files}, + result: ((($run.containment.outside_new_files // [1]) | length) == 0 + and $run.containment.outside_sentinel_before == $run.containment.outside_sentinel_after + and ($run.containment.workspace_changed // []) == [($rep.proposal_path // "?")]) | okv}, + {criterion:"Containment: speculation", threshold:"none (PROPOSED)", + value:{compose_dir_files:$cfiles, other_files:$stray}, + result: (($cfiles | length) > 0 and ($stray | length) == 0) | okv} + ] as $rows + | { + gate:"NEXT_PHASE_1", + commit:$sc, + omega_compose_commit:$omc, + omega_gpu_commit:$omg, + verdict: (if ($rows | map(select(.result == "FAIL")) | length) == 0 then "PASS" else "FAIL" end), + machine_id:($rep.machine_id // null), + tier:"host", + uname:$run.uname, + model:($d | map(.model)), + note:$note, + acceptance_spec:$spec, + observations:{tokens_per_s:(($rep.proposal_attempts // []) | map(select(.tokens > 0 and .ms > 0) | {attempt, tokens, ms, tokens_per_s:((.tokens * 100000 / .ms | floor) / 100)}))}, + skills:[{id:0, name:"aien.model.propose-file-change", version:null, digest:$skill_sha, cost:10}], + record_digest:[($rep.record_digest // null)], + prefix_digest:[($pre.recall.prefix_digest // null), ($s8.recall.prefix_digest // null)], + winner_digest:[($rep.winner_digest // null)], + acceptance:$rows, + effect_receipts:$receipts, + explanation:($s6.text // null), + runs:[{ + run:0, task:$rep.task, outcome:$rep.outcome, committed:$rep.committed, + old_ref:null, new_ref:null, candidate_refs:null, + branch_count:$rep.branch_count, branches_reclaimed:$rep.branches_reclaimed, + winner:$rep.winner, aegis_pass_mask:$rep.aegis_pass_mask, + goal_crumb:$rep.cx_goal, claims:$rep.cx_candidates, evidence:$rep.cx_evidence, + promotion:$rep.cx_promotion, admissions:$rep.cx_admissions, + proposer:$rep.proposer, proposal_path:$rep.proposal_path, + proposal_sha256:$rep.proposal_sha256, proposal_content_sha256:$rep.proposal_content_sha256, + uncommitted_proposal:($rep.uncommitted_proposal // null), proposer_error:($rep.proposer_error // null), + proposal_attempts:($rep.proposal_attempts // []), + steps: [ + {step:1, name:"S1 remember", result:($reached.S1|okv), detail:{ms:st("S1").wall_ms, constraint:$s1.constraint}}, + {step:2, name:"S2 inspect", result:($reached.S2|okv), detail:{ms:st("S2").wall_ms, tree_sha256:$s2.tree_sha256, receipt:$s2.receipt, effect:$s2.effect.id}}, + {step:3, name:"S3 propose", result:($reached.S3|okv), detail:{ms:st("S3").wall_ms, gpu_used:$gpu[0], backend:$d[0].backend}}, + {step:4, name:"S4 authorize", result:($reached.S4|okv), detail:{ms:st("S4").wall_ms, approvals:$s4.approvals, receipt:$s4.receipt, authorization:$s4.authorization.id}}, + {step:5, name:"S5 execute", result:($reached.S5|okv), detail:{ms:st("S5").wall_ms, path:$s5.path, content_sha256:$s5.content_sha256, disk_sha256:$s5.disk_sha256, receipt:$s5.receipt, effect:$s5.effect.id}}, + {step:6, name:"S6 explain", result:($reached.S6|okv), detail:{ms:st("S6").wall_ms, cited:(($s6.cited // []) | map({id, digest, verified})), receipts:$s6.receipts}}, + {step:7, name:"S7 restart", result:($reached.S7|okv), detail:(st("S7") + {vmhwm_kb_before:$d[0].vmhwm_kb})}, + {step:8, name:"S8 recall", result:($reached.S8|okv), detail:{ms:st("S8").wall_ms, machine_id:$s8.machine_id, constraints:(($s8.constraints // []) | map(.id)), effects:(($s8.effects // []) | map(.id)), vmhwm_kb_after:$d[1].vmhwm_kb, gpu_used:$gpu[1]}} + ]}] + }' >"$tmp" +h=$(sha256sum "$tmp" | cut -d' ' -f1) +mv "$tmp" "$OUT/$h.json" +v=$(jq -r .verdict "$OUT/$h.json") +{ + echo "NEXT_PHASE_1 receipt $h.json verdict $v" + echo "sovereign-core $SC; omega compose $OMC; omega GPU engine $OMG" + jq -r '"machine \(.machine_id); backend \(.acceptance[4].value.backend | join(" / ")); gpu_used \(.acceptance[4].value.gpu_used)"' "$OUT/$h.json" + jq -r '.runs[0].steps[] | " \(.name): \(.result) \(.detail.ms // .detail.wall_ms // "-") ms"' "$OUT/$h.json" + echo "Acceptance (frozen thresholds, ${SPEC:-ACCEPTANCE.md spec_version 1}):" + jq -r '.acceptance[] | " \(.result) \(.criterion) [\(.threshold)] \(.value | tojson | .[0:220])"' "$OUT/$h.json" + jq -r '(.runs[0].proposal_attempts // [])[] | " proposal attempt \(.attempt): \(.outcome) \(.ms) ms \(.tokens) tokens aegis=\(.aegis // "-") \(.reason // "")"' "$OUT/$h.json" + echo "Observations:" + jq -r '.observations.tokens_per_s[] | " attempt \(.attempt): \(.tokens) tokens in \(.ms) ms = \(.tokens_per_s) tokens/s (wall, incl. prompt prefill)"' "$OUT/$h.json" + [ -n "$NOTE" ] && echo "Note: $NOTE" +} >"$OUT/$h.summary.txt" +[ -f "$OUT/INDEX.md" ] || printf '# NEXT-PHASE-1 campaign receipts\n\nEach receipt is named by the sha256 of its content and never edited.\n\n' >"$OUT/INDEX.md" +echo "- \`$h.json\` verdict $v, sovereign-core $SC ($(date -u +%Y-%m-%dT%H:%MZ))" >>"$OUT/INDEX.md" +cat "$OUT/$h.summary.txt" diff --git a/docs/campaigns/next-phase-1/run-campaign.sh b/docs/campaigns/next-phase-1/run-campaign.sh new file mode 100755 index 00000000..89db2634 --- /dev/null +++ b/docs/campaigns/next-phase-1/run-campaign.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# NEXT-PHASE-1 campaign driver: the bounded task S1..S8 against a real daemon. +# Shell + jq only. Usage: +# AIEN_BIN=target/release/aien-cli AIEN_MODEL_PATH=.../model.safetensors \ +# AIEN_TOKENIZER_PATH=.../tokenizer.json run-campaign.sh RUN_ROOT +# Optional: AIEN_REQUIRE_BLACKWELL=1 (GB10 required, else the daemon refuses). +# Writes RUN_ROOT/run.json (all measures) and RUN_ROOT/steps/*.json (raw step +# output); daemon logs go to RUN_ROOT/daemon-{1,2}.log. Nothing outside RUN_ROOT +# is written by this script; the effect receipts go to RUN_ROOT/prov. +set -u +BIN=${AIEN_BIN:?AIEN_BIN}; : "${AIEN_MODEL_PATH:?}" "${AIEN_TOKENIZER_PATH:?}" +R=${1:?RUN_ROOT} +rm -rf "$R"; mkdir -p "$R"/ws/docs "$R"/outside "$R"/compose "$R"/prov "$R"/state "$R"/steps +R=$(cd "$R" && pwd) +export AIEN_COMPOSE_DIR=$R/compose AIEN_PROVENANCE_DIR=$R/prov AIEN_RUNTIME_SOCK=$R/aien.sock \ + AIEN_RUNTIME_STATE_DIR=$R/state AIEN_REQUIRE_CHECKPOINT=1 +WS=$R/ws +printf '# Demo project\n\nA small local project used by the NEXT-PHASE-1 campaign.\n' >"$WS/README.md" +printf 'Plan: keep notes short and local.\n' >"$WS/docs/plan.txt" +printf 'sentinel outside the authorized workspace\n' >"$R/outside/sentinel.txt" + +CONSTRAINT='Project constraints: every change stays inside the authorized workspace; one file per change; plain text only; no network.' +GOAL=${NP1_GOAL:-'Create the file NOTES.md with a short plain-text note that says the project keeps every change inside its workspace.'} + +now_ms() { echo $(( $(date +%s%N) / 1000000 )); } +up_cs() { tr -d . /dev/null; } + +DPID=; DLOG= +start_daemon() { # $1 = 1|2 + DLOG=$R/daemon-$1.log + setsid "$BIN" daemon >"$DLOG" 2>&1 /dev/null && [ $i -lt 600 ]; do + sleep 0.5; i=$((i + 1)) + done + sleep 0.5 + [ -S "$R/aien.sock" ] && kill -0 "$DPID" 2>/dev/null +} + +STEPS='[]' +# run_step ID NAME ARGS... : one CLI call, timed; stdout kept as steps/ID.json. +run_step() { + local id=$1 name=$2; shift 2 + local t0 u0 t1 u1 rc + t0=$(now_ms); u0=$(up_cs) + "$BIN" compose "$@" >"$R/steps/$id.json" 2>"$R/steps/$id.err"; rc=$? + t1=$(now_ms); u1=$(up_cs) + STEPS=$(jq -c --arg id "$id" --arg n "$name" --argjson ms $((t1 - t0)) \ + --argjson bms $(( (u1 - u0) * 10 )) --argjson rc $rc \ + --slurpfile o "$R/steps/$id.json" \ + '. + [{step:$id, name:$n, rc:$rc, wall_ms:$ms, boottime_ms:$bms, ok:($o[0].ok // false)}]' <<<"$STEPS") + return $rc +} + +start_daemon 1 || { echo "daemon 1 failed to start; see $R/daemon-1.log"; tail -5 "$R/daemon-1.log"; exit 2; } +PID1=$DPID +# S0 (setup, before the measured window): provision the composition home. +# The first open creates the machine root (.machine-root, beside +# the home), machine.id, cortex.cx and jspace. Not one of the eight steps. +"$BIN" compose recall >"$R/steps/S0-provision.json" 2>&1 + +touch "$R/.mark"; sleep 1 +WS_BEFORE=$(tree_digest "$WS"); WS_LIST_BEFORE=$(tree_list "$WS") +OUT_BEFORE=$(tree_digest "$R/outside") + +run_step S1 remember remember --text "$CONSTRAINT" +CID=$(jq -r '.constraint.id // empty' "$R/steps/S1.json") +run_step S2 inspect inspect --workspace "$WS" +run_step S3 propose propose --goal "$GOAL" --workspace "$WS" +jq '.report' "$R/steps/S3.json" >"$R/s3-report.json" +run_step S4 authorize authorize --report "$R/s3-report.json" --workspace "$WS" \ + --approver drake --constraint "${CID:-0}" +AID=$(jq -r '.authorization.id // empty' "$R/steps/S4.json") +run_step S5 execute execute --report "$R/s3-report.json" --workspace "$WS" --authorization "${AID:-0}" +EID=$(jq -r '.effect.id // empty' "$R/steps/S5.json") +IID=$(jq -r '.effect.id // empty' "$R/steps/S2.json") +RECEIPTS=$(jq -r '[.receipt.path] | .[]' "$R/steps/S2.json" "$R/steps/S4.json" "$R/steps/S5.json" | paste -sd,) +run_step S6 explain explain --report "$R/s3-report.json" --cite "$CID,$IID,$AID,$EID" --receipts "$RECEIPTS" +CITED=$(jq -r '[.cited[].id] | map(tostring) | join(",")' "$R/steps/S6.json") +NREC=$(jq -r '[.cited[].id] | max' "$R/steps/S6.json") +"$BIN" compose recall --ids "$CITED" --prefix "$NREC" >"$R/steps/pre-restart-recall.json" 2>&1 +HWM1=$(vmhwm "$PID1") +MIDF1=$(sha256sum "$R/compose/machine.id" | cut -d" " -f1) + +# S7: control Shutdown, wait for the process to exit, start a new one. +t0=$(now_ms); u0=$(up_cs) +"$BIN" compose shutdown >"$R/steps/S7.json" 2>"$R/steps/S7.err"; rc7=$? +i=0; while kill -0 "$PID1" 2>/dev/null && [ $i -lt 120 ]; do sleep 0.5; i=$((i + 1)); done +EXIT1=$(kill -0 "$PID1" 2>/dev/null && echo running || echo exited) +rm -f "$R/aien.sock" +start_daemon 2; up2=$? +PID2=$DPID +t1=$(now_ms); u1=$(up_cs) +STEPS=$(jq -c --argjson ms $((t1 - t0)) --argjson bms $(( (u1 - u0) * 10 )) \ + --argjson rc $(( rc7 + up2 )) --arg e "$EXIT1" --argjson p1 "$PID1" --argjson p2 "$PID2" \ + '. + [{step:"S7", name:"restart", rc:$rc, wall_ms:$ms, boottime_ms:$bms, + ok:($rc == 0 and $e == "exited" and $p1 != $p2), old_pid:$p1, old_process:$e, new_pid:$p2}]' <<<"$STEPS") + +run_step S8 recall recall --ids "$CITED" --prefix "$NREC" +HWM2=$(vmhwm "$PID2") +MIDF2=$(sha256sum "$R/compose/machine.id" | cut -d" " -f1) +"$BIN" compose shutdown >"$R/steps/final-shutdown.json" 2>&1 +i=0; while kill -0 "$PID2" 2>/dev/null && [ $i -lt 120 ]; do sleep 0.5; i=$((i + 1)); done + +WS_AFTER=$(tree_digest "$WS"); OUT_AFTER=$(tree_digest "$R/outside") +WS_CHANGED=$(diff <(echo "$WS_LIST_BEFORE") <(tree_list "$WS") | sed -n 's/^[<>] [0-9a-f]* \.\///p' | sort -u | jq -R . | jq -sc .) +OUTSIDE_NEW=$(cd "$R" && find . -newer .mark -type f ! -path './ws/*' ! -path './compose/*' ! -path './prov/*' \ + ! -path './steps/*' ! -path './state/*' ! -name 'daemon-*.log' ! -name 's3-report.json' ! -name 'run.json' | sort | jq -R . | jq -sc .) +STATE_NEW=$(cd "$R" && find ./state -type f | sort | jq -R . | jq -sc .) +COMPOSE_FILES=$(cd "$R/compose" && find . -mindepth 1 | sort | jq -R . | jq -sc .) +backend() { grep -m1 'Backend:' "$1" | sed 's/\x1b\[[0-9;]*m//g; s/^ *Backend: //'; } +model_line() { grep -m1 'checkpoint loaded from' "$1" | sed 's/\x1b\[[0-9;]*m//g'; } + +jq -n --arg R "$R" --argjson steps "$STEPS" \ + --arg b1 "$(backend "$R/daemon-1.log")" --arg b2 "$(backend "$R/daemon-2.log")" \ + --arg m1 "$(model_line "$R/daemon-1.log")" --arg m2 "$(model_line "$R/daemon-2.log")" \ + --argjson pid1 "$PID1" --argjson pid2 "$PID2" --arg hwm1 "${HWM1:-}" --arg hwm2 "${HWM2:-}" \ + --arg wsb "$WS_BEFORE" --arg wsa "$WS_AFTER" --arg ob "$OUT_BEFORE" --arg oa "$OUT_AFTER" \ + --argjson wsc "$WS_CHANGED" --argjson outn "$OUTSIDE_NEW" --argjson staten "$STATE_NEW" \ + --argjson cfiles "$COMPOSE_FILES" --arg constraint "$CONSTRAINT" --arg goal "$GOAL" \ + --arg uname "$(uname -srm)" --arg midf1 "${MIDF1:-}" --arg midf2 "${MIDF2:-}" --arg cited "$CITED" --argjson nrec "${NREC:-0}" \ + '{root:$R, uname:$uname, goal:$goal, constraint_text:$constraint, steps:$steps, + daemon:[{pid:$pid1, backend:$b1, model:$m1, vmhwm_kb:($hwm1|tonumber? // null)}, + {pid:$pid2, backend:$b2, model:$m2, vmhwm_kb:($hwm2|tonumber? // null)}], + cited:($cited|split(",")|map(tonumber? // empty)), prefix_records:$nrec, + containment:{workspace_before:$wsb, workspace_after:$wsa, workspace_changed:$wsc, + outside_sentinel_before:$ob, outside_sentinel_after:$oa, + outside_new_files:$outn, daemon_state_files:$staten}, + compose_dir_files:$cfiles, machine_id_file_sha256:[$midf1, $midf2]}' >"$R/run.json" +jq -c '.steps[] | {step, ok, wall_ms}' "$R/run.json" diff --git a/omega.lock b/omega.lock index 21d8528b..733563ae 100644 --- a/omega.lock +++ b/omega.lock @@ -1 +1 @@ -f816473df391bc4fbcf99df722edd70ed26ebef1 +62b6a2899fa230e57fcf7855ea7e2c26404514b6 ```