diff --git a/.crumb b/.crumb index 5eaa7d33..5d4d3822 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:2773d5ada0e6ae8b446499314f4a704361ab91a14a35259a62607b7c731d0ab9", - "compiled_at": "2026-10-08T04:50:36Z", + "compiled_at": "2026-10-08T06:17:09Z", "compiler": "crumb-compile/1", - "digest": "sha256:ff69289f391ef90d3e32979ebf67189eafba997a84eb53cb55717d504dc8f927", + "digest": "sha256:b638673eea730af338429e079bad5c5c346a4b1e71e9ffeae4e28f5ea81a3d40", "evidence_files": 187, "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", - "files": 1357, - "generated_at_commit": "2010f3d7d0bbbff9a83bfa2e7990dfbc285cf1ab", - "source_tree": "sha256:c61692a41d9cbf270c1d9382f45440b140baf8d3273ff69d2e63d5410b9af555" + "files": 1359, + "generated_at_commit": "a720af06dd282faeaf4e549a6f39d556a7ccfb72", + "source_tree": "sha256:98fd8c938ef1e74410f167ed3c35d2ea34ae22eb3c7db53ea40ddc5bcb6fb0ee" } }, "history": [], diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 2bfe8d24..cdf8be52 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -35,20 +35,20 @@ "children": [ { "digest": "bda1cf3ea7725b89dcc8c0a6f9019ca8f8a98e9173b99f48c434a6ff7e7b857d", - "last_commit": "2010f3d", + "last_commit": "fe5a7d7", "name": "src", "purpose": "" } ], "children_root": "sha256:79480b7c03456483de758f44f99f3f3661cb24bf829761bf11b58a04e27d8d18", - "compiled_at": "2026-10-08T04:50:36Z", + "compiled_at": "2026-10-08T06:06:34Z", "compiler": "crumb-compile/1", - "digest": "sha256:2613d61b92b3c31c80423a0f4a4ba57c84f22014d7fe737b33464f30f81de1b3", + "digest": "sha256:0046cb97b5d9a3b54de4d50ebb5e07580df7d08ae2f88e44000068566f8dcd4f", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 31, - "generated_at_commit": "2010f3d7d0bbbff9a83bfa2e7990dfbc285cf1ab", - "source_tree": "sha256:c54c329521dab8d8d4a7a896d5087a4f6f738bca543aa0eca1debda2124affba" + "files": 32, + "generated_at_commit": "50c1d0d9c56e7285894776acd1ce0a8d1eb4ae20", + "source_tree": "sha256:99101c50730adcbb628a1100a1d846e567d2ac3d356ceb4f4536828d7e4d1638" } }, "history": [ diff --git a/crates/aien-cli/tests/provenance_link_live_test.rs b/crates/aien-cli/tests/provenance_link_live_test.rs new file mode 100644 index 00000000..7389aa8b --- /dev/null +++ b/crates/aien-cli/tests/provenance_link_live_test.rs @@ -0,0 +1,246 @@ +//! Provenance link (arch#162), live: the real `aien daemon` process with +//! SmolLM2-1.7B on the CPU reference backend, and the real `aien compose` +//! CLI. `propose` -> `authorize` -> `execute`, then every record of the +//! commit is read back from the ledger: each names the generation record of +//! the model's proposal, whose `model_sha256` is the sha256 of the weights +//! file the daemon loaded (hashed here, independently, from the file). +//! +//! IGNORED, like recovery_matrix_test: it needs a prebuilt compose-linked CPU +//! binary and the model (minutes of CPU inference), so it cannot run in the +//! default suite. Build once, then run: +//! +//! ```text +//! AIEN_OMEGA_COMPOSE_LIB= cargo build --release -p aien-cli +//! AIEN_BIN=target/release/aien-cli cargo test -p aien-cli --test provenance_link_live_test \ +//! -- --ignored --nocapture +//! ``` +//! +//! `AIEN_PROPOSER_MODEL` overrides the model directory +//! (default `$HOME/models/SmolLM2-1.7B-Instruct-31b70e2e869a`). The daemon +//! must report the CPU reference backend or the test stops (no GPU use). +use serde_json::Value; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::Duration; + +fn file_sha256(p: &Path) -> String { + use std::io::Read; + let mut f = std::fs::File::open(p).unwrap(); + let mut h = Sha256::new(); + let mut buf = vec![0u8; 1 << 20]; + loop { + let n = f.read(&mut buf).unwrap(); + if n == 0 { + break; + } + h.update(&buf[..n]); + } + aien_omega_compose::hex(&h.finalize()) +} + +struct Rig { + bin: PathBuf, + root: PathBuf, + _tmp: tempfile::TempDir, +} + +impl Rig { + fn env(&self, c: &mut Command) { + c.current_dir(&self.root) + .env("HOME", self.root.join("home")) + .env("NO_COLOR", "1") + .env("AIEN_RUNTIME_SOCK", self.root.join("s")) + .env("AIEN_RUNTIME_STATE_DIR", self.root.join("state")) + .env("AIEN_COMPOSE_DIR", self.root.join("compose")) + .env("AIEN_PROVENANCE_DIR", self.root.join("prov")) + .env("AIEN_REQUIRE_CHECKPOINT", "1"); + for k in [ + "AIEN_OMEGA_DIR", + "AIEN_OMEGA_GPU_LIB", + "AIEN_REQUIRE_BLACKWELL", + "AIEN_GPU_BACKEND", + "AIEN_MODEL_DIR", + "AIEN_ALLEN_SUBJECT", + "AIEN_ALLEN_ADOPT", + "AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK", + ] { + c.env_remove(k); + } + } + + fn cli(&self, args: &[&str]) -> Value { + let mut c = Command::new(&self.bin); + c.arg("compose").args(args); + self.env(&mut c); + let o = c.output().expect("run aien compose"); + let out = String::from_utf8_lossy(&o.stdout).to_string(); + out.lines() + .rev() + .find_map(|l| serde_json::from_str::(l).ok()) + .unwrap_or_else(|| { + panic!( + "no JSON from {args:?}: {out} {}", + String::from_utf8_lossy(&o.stderr) + ) + }) + } + + /// Text of one ledger record, digest-verified. + fn record(&self, id: u64) -> Value { + let v = self.cli(&["recall", "--ids", &id.to_string()]); + let c = &v["recall"]["cited"][0]; + assert_eq!(c["verified"], true, "record {id}: {v}"); + serde_json::from_str(c["text"].as_str().expect("record text")).unwrap() + } +} + +struct Daemon(Child); + +impl Drop for Daemon { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +#[test] +#[ignore = "live: needs AIEN_BIN (compose-linked CPU build) and SmolLM2 on disk; minutes of CPU"] +fn a_live_model_commit_names_its_generation_record_and_weights_digest() { + let bin = PathBuf::from( + std::env::var("AIEN_BIN").expect("AIEN_BIN: the compose-linked CPU aien-cli"), + ); + let model_dir = std::env::var("AIEN_PROPOSER_MODEL") + .map(PathBuf::from) + .unwrap_or_else(|_| { + PathBuf::from(std::env::var("HOME").unwrap()) + .join("models/SmolLM2-1.7B-Instruct-31b70e2e869a") + }); + let weights = model_dir.join("model.safetensors"); + let tmp = tempfile::Builder::new() + .prefix("pl-") + .tempdir_in("/tmp") + .unwrap(); + let root = std::fs::canonicalize(tmp.path()).unwrap(); + for d in ["ws", "state", "home", "prov"] { + std::fs::create_dir_all(root.join(d)).unwrap(); + } + let rig = Rig { + bin: bin.clone(), + root: root.clone(), + _tmp: tmp, + }; + let log = root.join("daemon.log"); + let f = std::fs::File::create(&log).unwrap(); + let mut c = Command::new(&bin); + c.arg("daemon") + .env("AIEN_MODEL_PATH", &weights) + .env("AIEN_TOKENIZER_PATH", model_dir.join("tokenizer.json")) + .env("AIEN_COMPOSE_EDIT_BUDGET_MS", "599000") + .env("AIEN_COMPOSE_DOC_BUDGET_MS", "599000") + .stdin(Stdio::null()) + .stdout(f.try_clone().unwrap()) + .stderr(f); + rig.env(&mut c); + let mut daemon = Daemon(c.spawn().expect("spawn daemon")); + let mut up = false; + for _ in 0..2400 { + std::thread::sleep(Duration::from_millis(500)); + assert!( + daemon.0.try_wait().unwrap().is_none(), + "daemon exited: {}", + std::fs::read_to_string(&log).unwrap_or_default() + ); + let t = std::fs::read_to_string(&log).unwrap_or_default(); + if root.join("s").exists() && t.contains("Replay reconcile:") { + let backend = t.lines().find(|l| l.contains("Backend:")).unwrap_or(""); + assert!( + backend.contains("CPU-reference"), + "not the CPU backend: {backend}" + ); + up = true; + break; + } + } + assert!(up, "daemon did not come up in 20 min"); + + let ws = root.join("ws"); + let report_file = root.join("propose.json"); + let propose = rig.cli(&[ + "propose", + "--goal", + "Write garden.md in the workspace, a garden plan.", + "--workspace", + ws.to_str().unwrap(), + ]); + std::fs::write(&report_file, propose.to_string()).unwrap(); + let report = &propose["report"]; + assert_eq!( + report["committed"], true, + "the model's proposal did not commit: {propose}" + ); + let gen_id = report["generation_record"] + .as_u64() + .expect("report names the generation record"); + let commit = report["compose_commit"].as_u64().unwrap(); + let auth = rig.cli(&[ + "authorize", + "--report", + report_file.to_str().unwrap(), + "--workspace", + ws.to_str().unwrap(), + "--approver", + "drake", + ]); + assert_eq!(auth["ok"], true, "{auth}"); + let grant = auth["authorization"]["id"].as_u64().unwrap(); + let exec = rig.cli(&[ + "execute", + "--report", + report_file.to_str().unwrap(), + "--workspace", + ws.to_str().unwrap(), + "--authorization", + &grant.to_string(), + ]); + assert_eq!(exec["state"], "DONE", "{exec}"); + let effects = rig.cli(&["effects"]); + let intents = effects["ledger"]["intents"].as_array().expect("intents"); + assert_eq!(intents.len(), 1); + let intent = intents[0]["intent"].as_u64().unwrap(); + let ack = intents[0]["state_record"].as_u64().unwrap(); + + let want_model = file_sha256(&weights); + let want_tok = file_sha256(&model_dir.join("tokenizer.json")); + for (name, id) in [ + ("compose_commit", commit), + ("grant", grant), + ("intent", intent), + ("ack", ack), + ] { + let r = rig.record(id); + assert_eq!(r["provenance"]["generation_record"], gen_id, "{name}: {r}"); + assert_eq!(r["provenance"]["allen_agent"], "none", "{name}: {r}"); + } + let g = rig.record(gen_id); + assert_eq!(g["generation"], 1); + assert_eq!(g["origin"], "compose_proposal"); + assert_eq!( + g["model_sha256"], want_model, + "the digest of the loaded weights file" + ); + assert_eq!(g["tokenizer_sha256"], want_tok); + assert_eq!(g["task"], report["task"]); + let attempt = report["proposal_attempts"] + .as_array() + .unwrap() + .iter() + .find(|a| a["outcome"] == "parsed") + .expect("the parsed attempt"); + assert_eq!(g["attempt"], attempt["attempt"]); + assert_eq!(g["prompt_ids_sha256"], attempt["prompt_ids_sha256"]); + assert_eq!(g["output_text_sha256"], attempt["text_sha256"]); + println!( + "LIVE_PROVENANCE generation_record={gen_id} model_sha256={want_model} commit={commit} grant={grant} intent={intent} ack={ack}" + ); +} diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index ec0161e2..e99a5b4e 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -644,6 +644,11 @@ pub struct ComposeTaskReport { /// committed a one-file proposal on the ordinary (non-approved) path. #[serde(default)] pub compose_commit: Option, + /// Ledger id of the generation record of the attempt the committed + /// proposal came from (arch#162). Evidence only; absent when no record + /// was written (no model identity, approved proposal, failed append). + #[serde(default)] + pub generation_record: Option, /// Composition home (holds machine.id, cortex.cx, jspace). pub compose_dir: String, /// AienMachineId (32 bytes, hex) the home is bound to. diff --git a/crates/aien-runtime/src/effects.rs b/crates/aien-runtime/src/effects.rs index c9da646a..38e642f6 100644 --- a/crates/aien-runtime/src/effects.rs +++ b/crates/aien-runtime/src/effects.rs @@ -733,6 +733,13 @@ pub fn check_reserved_note(kind: &str, text: &str) -> Result<(), String> { let Ok(v) = serde_json::from_str::(text) else { return Ok(()); }; + // Provenance evidence is copied by the daemon along its own chain; no caller sets it. + if v.get(crate::generation::PROVENANCE).is_some() { + return Err( + "ComposeNote: the provenance field is written only by the daemon (generation link and ALLEN agent id)" + .into(), + ); + } match kind { // The daemon's generation record (evidence only, never an input to any // decision): effect-class note with the marker field. @@ -1195,6 +1202,9 @@ pub(crate) fn write_approved_grant( "workspace": workspace, "prior_sha256": prior, "approval_key": link.approval_key, "replay_claim": link.replay_claim, "cx_promotion": link.cx_promotion, "cx_evidence": link.cx_evidence, + // An approved proposal runs no model: no generation record, the ALLEN only. + crate::generation::PROVENANCE: + crate::generation::Provenance::new(None, home.allen.as_ref()).to_json(), }); if let (Some(t), Some(i)) = (text.as_object_mut(), ids.as_object()) { for (k, v) in i { @@ -1245,6 +1255,14 @@ fn check_minted_backing(l: &Ledger, g: &Grant) -> Result<(), Refusal> { Ok(()) } +/// Copy the provenance evidence of record `source` onto `text`, a record the +/// daemon is about to append. EVIDENCE ONLY: this is the single place the +/// ledger-side code reads provenance, it never fails and is called after every +/// decision of its caller (`provenance_changes_no_decision` scans for that). +fn stamp(text: &mut Value, views: &[ComposeRecordView], source: u64) { + text[crate::generation::PROVENANCE] = crate::generation::inherit(views, source).to_json(); +} + /// The record the daemon writes when its own compose run COMMITTED a /// one-file proposal (#261): the only thing `ComposeAuthorize` mints from. /// Linked to the promotion and evidence. Returns the record id. @@ -1258,11 +1276,22 @@ pub(crate) fn write_compose_commit( proposal_sha256: &str, path: &str, content_sha256: &str, + prov: &crate::generation::Provenance, ) -> Result { + // Refused at write time: a record never names a generation id that is not + // a verified generation record of this ledger. + if let Some(g) = prov.generation_record { + if !crate::generation::generation_exists(&host_views(home)?, g) { + return Err(format!( + "compose-commit not written: provenance names generation record #{g}, which is not a verified generation record" + )); + } + } let text = json!({ COMPOSE_COMMIT: 1, "task": task, "cx_promotion": cx_promotion, "cx_evidence": cx_evidence, "proposal_sha256": proposal_sha256, "path": path, "content_sha256": content_sha256, "workspace": workspace, + crate::generation::PROVENANCE: prov.to_json(), }); append(home, NoteKind::Effect, &[cx_promotion, cx_evidence], &text).map(|n| n.id) } @@ -1331,7 +1360,8 @@ pub fn authorize( } else { None }; - let l = ledger(home)?; + let views = host_views(home)?; + let l = Ledger::from_records(&views).map_err(|r| r.to_string())?; let mut hits = l .commits .values() @@ -1433,6 +1463,7 @@ pub fn authorize( text["desk_nonce"] = json!(p.nonce); text["desk_key_id"] = json!(key.id()); } + stamp(&mut text, &views, c.id); append(home, NoteKind::Authorization, &links, &text) })) } @@ -1585,12 +1616,13 @@ pub fn open_intent(b: &ComposeBridge, req: &IntentRequest) -> ControlResponse { } check_approved_backing(&l, g, &views).map_err(|r| r.to_string())?; check_minted_backing(&l, g).map_err(|r| r.to_string())?; - let text = json!({ + let mut text = json!({ "phase": PHASE_INTENT, "tool": "write_file", "authorization": g.id, "proposal_sha256": req.proposal_sha256, "path": req.path, "target": req.target, "content_sha256": req.content_sha256, "prior_sha256": current, "executor": {"pid": req.executor_pid, "start": req.executor_start}, }); + stamp(&mut text, &views, g.id); append(home, NoteKind::Effect, &[g.id], &text) })) } @@ -1602,7 +1634,8 @@ pub fn ack(b: &ComposeBridge, intent: u64, reported: &Value) -> ControlResponse return ControlResponse::Error(e); } noted(b.with_home(|home| { - let l = ledger(home)?; + let views = host_views(home)?; + let l = Ledger::from_records(&views).map_err(|r| r.to_string())?; let row = l .intents .get(&intent) @@ -1615,12 +1648,13 @@ pub fn ack(b: &ComposeBridge, intent: u64, reported: &Value) -> ControlResponse )); } let (st, disk) = confined_world_state(&l, row); - let text = json!({ + let mut text = json!({ "phase": PHASE_ACK, "intent": intent, "authorization": row.authorization, "tool": "write_file", "path": row.path, "content_sha256": row.content_sha256, "state": st.name(), "disk_sha256": disk.as_ref().ok().cloned().flatten(), "disk_error": disk.as_ref().err(), "executor_reported": reported, }); + stamp(&mut text, &views, intent); append(home, NoteKind::Effect, &[intent, row.authorization], &text) })) } @@ -2001,6 +2035,311 @@ mod tests { assert!(check_reserved_note("generation", g).is_err()); } + #[test] + fn provenance_cannot_be_set_through_compose_note() { + let p = r#"{"provenance":{"generation_record":3,"allen_agent":"none"}}"#; + for kind in ["effect", "constraint", "authorization", "provenance"] { + assert!(check_reserved_note(kind, p).is_err(), "{kind}"); + } + // A forged copy of the daemon's own records, with provenance, is refused too. + let c = r#"{"compose_commit":1,"provenance":{"generation_record":3}}"#; + assert!(check_reserved_note("effect", c).is_err()); + // Without the field an ordinary note is still fine. + assert!(check_reserved_note("constraint", r#"{"a":1}"#).is_ok()); + } + + fn commit_row(id: u64, prov: Option) -> ComposeRecordView { + let mut v = json!({"compose_commit": 1, "task": 1, "cx_promotion": 1, "cx_evidence": 1, + "proposal_sha256": "p", "path": "N.md", "content_sha256": "c", "workspace": "/w"}); + if let Some(p) = prov { + v["provenance"] = p; + } + rec(id, "effect", v) + } + + fn with_prov(mut r: ComposeRecordView, prov: Value) -> ComposeRecordView { + let mut v: Value = serde_json::from_str(r.text.as_deref().unwrap()).unwrap(); + v["provenance"] = prov; + r.text = Some(v.to_string()); + r + } + + /// Evidence only: whatever the provenance fields say (valid, absent, naming + /// nothing, the wrong type, hostile), the ledger state and every decision + /// are the ones the same records give without them. + #[test] + fn provenance_changes_no_decision() { + let chain = |prov: Option| { + let mut v = vec![ + commit_row(1, prov.clone()), + grant(2, Value::Null), + intent(3, 2), + settle(4, "ack", 3, "DONE"), + grant(5, Value::Null), + intent(6, 5), + ]; + if let Some(p) = prov { + for r in v.iter_mut().skip(1) { + *r = with_prov(r.clone(), p.clone()); + } + } + v + }; + let base = Ledger::from_records(&chain(None)).unwrap(); + for prov in [ + json!({"generation_record": 7, "allen_agent": "ab".repeat(32)}), + json!({"generation_record": 99999, "allen_agent": "none"}), + json!({"generation_record": null, "allen_agent": "none"}), + json!({"generation_record": null, "allen_agent": "none", "generation_record_stale": 9, "provenance_note": "generation_record_stale"}), + json!({"generation_record": "seven", "allen_agent": 5}), + json!("garbage"), + json!(null), + json!({"generation_record": u64::MAX, "allen_agent": "\u{0}x".repeat(500)}), + ] { + let l = Ledger::from_records(&chain(Some(prov.clone()))).unwrap(); + assert_eq!(base.view(), l.view(), "{prov}"); + for a in [2u64, 5, 9] { + assert_eq!(refusal(&base, a, None), refusal(&l, a, None), "{prov} #{a}"); + } + assert_eq!( + base.check_intent(&req(5), &None).map(|g| g.id), + l.check_intent(&req(5), &None).map(|g| g.id) + ); + assert_eq!(base.commits, l.commits, "{prov}"); + assert_eq!(base.grants, l.grants, "{prov}"); + assert_eq!(base.intents, l.intents, "{prov}"); + } + } + + /// The same, for the code: the only reader of provenance is + /// `Provenance::from_text`, reached only through `stamp`/`inherit`, and the + /// ledger-side code that mentions provenance is a short, named list of + /// writers that call it after their decisions are made. Nothing in + /// `Ledger`, `check_*`, the world checks or reconcile can see it. + #[test] + fn provenance_is_read_by_no_decision_code() { + let src = include_str!("effects.rs"); + let prod = src.split("#[cfg(test)]\nmod tests").next().unwrap(); + let tokens = [ + "PROVENANCE", + "Provenance", + "provenance", + "stamp(", + "inherit(", + "generation_record", + "allen_agent", + "stale_generation", + "provenance_note", + ]; + // The enclosing `fn` of every mention. + let mut cur = String::from(""); + let mut hits: Vec<(String, String)> = Vec::new(); + for line in prod.lines() { + let t = line.trim_start(); + if let Some(i) = t.find("fn ") { + let pre = &t[..i]; + if pre.is_empty() || pre == "pub " || pre == "pub(crate) " { + cur = t[i + 3..] + .split(|c: char| !(c.is_alphanumeric() || c == '_')) + .next() + .unwrap() + .to_string(); + } + } + if t.starts_with("//") { + continue; + } + if tokens.iter().any(|k| line.contains(k)) { + hits.push((cur.clone(), t.to_string())); + } + } + let writers = [ + "stamp", + "write_compose_commit", + "write_approved_grant", + "authorize", + "open_intent", + "ack", + "check_reserved_note", + ]; + for (f, line) in &hits { + assert!( + writers.contains(&f.as_str()), + "{f} mentions provenance: {line}" + ); + } + // Inside the writers that also decide, the only mention is the stamp + // call (or the reserved-field refusal), never a read of the fields. + for (f, line) in &hits { + if ["authorize", "open_intent", "ack"].contains(&f.as_str()) { + assert!( + line.starts_with("stamp(&mut text, &views, "), + "{f} touches provenance other than by stamp: {line}" + ); + } + } + // Everything else in the crate: the field's name and its reader appear + // only in generation.rs (definition), effects.rs (above), spine.rs + // (the writer of the commit) and server.rs/control.rs (plumbing). + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + for e in std::fs::read_dir(dir).unwrap() { + let p = e.unwrap().path(); + let name = p.file_name().unwrap().to_string_lossy().into_owned(); + if !name.ends_with(".rs") { + continue; + } + let s = std::fs::read_to_string(&p).unwrap(); + let s = s.split("#[cfg(test)]").next().unwrap(); + let reads = s.contains("Provenance::from_text") || s.contains("generation::inherit"); + let allowed = ["generation.rs", "effects.rs"].contains(&name.as_str()); + assert!(!reads || allowed, "{name} reads provenance"); + } + // The Ledger types carry no provenance field at all. + for ty in [ + "pub struct Grant", + "pub struct CommitRow", + "pub struct IntentRow", + "pub struct Ledger", + ] { + let body = prod + .split(ty) + .nth(1) + .unwrap() + .split("\n}\n") + .next() + .unwrap(); + assert!(!body.to_lowercase().contains("provenance"), "{ty}"); + } + } + + #[test] + fn old_records_without_provenance_read_as_explicit_none() { + use crate::generation::{inherit, Provenance, NO_AGENT}; + let old = vec![commit_row(1, None), grant(2, Value::Null), intent(3, 2)]; + // The ledger opens and verifies as before. + assert!(Ledger::from_records(&old).is_ok()); + let p = inherit(&old, 1); + assert_eq!(p, Provenance::default()); + assert_eq!(p.allen_agent, NO_AGENT); + assert_eq!(p.generation_record, None); + // Missing record, or text that is not a record at all: the plain default + // (no provenance field was ever there), never an error. + assert_eq!(inherit(&old, 77), Provenance::default()); + assert_eq!(Provenance::from_text("not json"), Provenance::default()); + // A provenance field that is PRESENT but damaged is not silently "none": + // the values default and a visible note says why. + let bad_agent = Provenance::from_text( + r#"{"provenance":{"allen_agent":"nope","generation_record":-1}}"#, + ); + assert_eq!(bad_agent.allen_agent, NO_AGENT); + assert_eq!(bad_agent.note.as_deref(), Some("allen_agent_malformed")); + assert_ne!(bad_agent, Provenance::default()); + assert_eq!( + bad_agent.to_json()["provenance_note"], + "allen_agent_malformed" + ); + let not_obj = Provenance::from_text(r#"{"provenance":"garbage"}"#); + assert_eq!(not_obj.note.as_deref(), Some("provenance_malformed")); + // A generation id that names no generation record is not copied as a + // plain null: the old id stays visible and a note says it is stale. + let named = vec![commit_row( + 1, + Some(json!({"generation_record": 9, "allen_agent": "ab".repeat(32)})), + )]; + let p = inherit(&named, 1); + assert_eq!(p.generation_record, None); + assert_eq!(p.stale_generation, Some(9)); + assert_eq!(p.note.as_deref(), Some("generation_record_stale")); + assert_eq!(p.allen_agent, "ab".repeat(32)); + let j = p.to_json(); + assert_eq!(j["generation_record"], Value::Null); + assert_eq!(j["generation_record_stale"], 9); + assert_eq!(j["provenance_note"], "generation_record_stale"); + // The marker survives the next copy down the chain (grant -> intent). + let next = vec![rec( + 2, + "effect", + json!({"phase": "intent", "provenance": j}), + )]; + let q = inherit(&next, 2); + assert_eq!(q.stale_generation, Some(9)); + assert_eq!(q.note.as_deref(), Some("generation_record_stale")); + // ... and kept when it does (the record must be a verified generation record). + let mut with_gen = named.clone(); + with_gen.push(generation_row(9)); + assert_eq!(inherit(&with_gen, 1).generation_record, Some(9)); + // A non-generation record (or an unverified one) does not count. + let mut not_gen = named; + not_gen.push(rec(9, "effect", json!({"x": 1}))); + assert_eq!(inherit(¬_gen, 1).generation_record, None); + let mut bad = with_gen; + bad[1].verified = false; + assert_eq!(inherit(&bad, 1).generation_record, None); + } + + /// A record that names a nonexistent generation id is refused at write time. + #[test] + fn a_commit_naming_no_generation_record_is_not_written() { + use crate::generation::Provenance; + use crate::spine::{ComposeBridge, Generation}; + if !aien_omega_compose::LINKED { + eprintln!("NOT_RUN: stub compose build"); + return; + } + let t = tempfile::tempdir().unwrap(); + let proposer: crate::spine::ComposeProposer = + std::sync::Arc::new(|_: &str, _: std::time::Duration| Ok(Generation::default())); + let b = ComposeBridge::new(t.path().join("compose"), proposer, "test:fixed"); + let note = match b.note("constraint", "an ordinary note", &[]) { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("{other:?}"), + }; + let write = |g: Option| { + b.with_home(|home| { + write_compose_commit( + home, + "/w", + 1, + 1, + 1, + "p", + "N.md", + "c", + &Provenance { + generation_record: g, + allen_agent: "none".into(), + ..Default::default() + }, + ) + }) + }; + let before = host_count(&b); + for bad in [999_999u64, note, 1] { + let e = write(Some(bad)).unwrap_err(); + assert!(e.contains("not a verified generation record"), "{bad}: {e}"); + } + assert_eq!(host_count(&b), before, "nothing was written"); + // A real generation record is accepted, and none is accepted. + let g = b + .with_home(|home| crate::generation::write(home, &generation_json())) + .unwrap(); + let ok = write(Some(g)); + assert!(ok.is_ok(), "{ok:?}"); + let ok = write(None); + assert!(ok.is_ok(), "{ok:?}"); + } + + fn generation_json() -> Value { + json!({"generation": 1, "v": 1, "model_sha256": "x"}) + } + + fn host_count(b: &crate::spine::ComposeBridge) -> usize { + match b.recall(&[], None) { + ControlResponse::ComposeRecalled(r) => r.host.len(), + other => panic!("{other:?}"), + } + } + #[test] fn fresh_grant_opens_once() { let l = Ledger::from_records(&[grant(2, Value::Null)]).unwrap(); diff --git a/crates/aien-runtime/src/generation.rs b/crates/aien-runtime/src/generation.rs index e04831ea..34fd8874 100644 --- a/crates/aien-runtime/src/generation.rs +++ b/crates/aien-runtime/src/generation.rs @@ -89,3 +89,214 @@ pub fn build_record(id: &ModelIdentity, t: &TurnEvidence, start: DaemonStart) -> pub(crate) fn write(home: &mut crate::spine::ComposeHome, record: &Value) -> Result { crate::effects::append(home, aien_omega_compose::NoteKind::Effect, &[], record).map(|n| n.id) } + +// --------------------------------------------------------------------------- +// Provenance link: which generation produced a committed proposal, and which +// ALLEN asked for it. EVIDENCE ONLY, like the generation record itself. +// --------------------------------------------------------------------------- + +use crate::control::ComposeRecordView; + +/// Top-level field of the evidence the daemon copies along the chain +/// compose-commit -> minted grant -> intent -> ack (and onto an approved +/// grant). Reserved: `ComposeNote` refuses any note that carries it, and no +/// ledger reader (`effects::Ledger`) parses it. Only [`Provenance::from_text`] +/// does, and only `effects::stamp` calls that. +pub const PROVENANCE: &str = "provenance"; + +/// The `allen_agent` value when no ALLEN identity is attached to the daemon. +pub const NO_AGENT: &str = "none"; + +/// The evidence fields of the link. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Provenance { + /// Ledger id of the generation record of the attempt the committed + /// proposal came from. `None` when no record was written (no ledger, no + /// model identity, a proposer that does not expose token ids, an approved + /// proposal): an absent claim, not a pass. + pub generation_record: Option, + /// The ALLEN LogicalAgentId (64 hex, `aien_allen::Resolved::agent`) the + /// task ran under, or [`NO_AGENT`]. + pub allen_agent: String, + /// Set when a copy found the source's generation id not naming a verified + /// generation record: the old id, kept visible. `generation_record` is then + /// null, and this marker tells that apart from "no model ran". + pub stale_generation: Option, + /// Why the evidence is degraded (`generation_record_stale`, + /// `allen_agent_malformed`, `provenance_malformed`), `;`-joined. + /// Absent on ordinary records. + pub note: Option, +} + +impl Default for Provenance { + fn default() -> Self { + Self { + generation_record: None, + allen_agent: NO_AGENT.to_string(), + stale_generation: None, + note: None, + } + } +} + +impl Provenance { + pub fn new(generation_record: Option, allen: Option<&aien_allen::Resolved>) -> Self { + Self { + generation_record, + allen_agent: allen.map_or_else(|| NO_AGENT.to_string(), |r| aien_allen::hex(&r.agent)), + ..Self::default() + } + } + + fn add_note(&mut self, n: &str) { + match &mut self.note { + Some(x) if x.split("; ").any(|y| y == n) => {} + Some(x) => { + x.push_str("; "); + x.push_str(n); + } + None => self.note = Some(n.to_string()), + } + } + + pub fn to_json(&self) -> Value { + let mut v = + json!({"generation_record": self.generation_record, "allen_agent": self.allen_agent}); + if let Some(s) = self.stale_generation { + v["generation_record_stale"] = json!(s); + } + if let Some(n) = &self.note { + v["provenance_note"] = json!(n); + } + v + } + + /// Lenient read of a record's text, never an error. A record with no + /// provenance field at all (an old record) reads as the plain default. + /// A field that is present but damaged reads as the default values PLUS a + /// visible note, so it is never mistaken for "no model ran" / "no ALLEN". + pub fn from_text(text: &str) -> Self { + let Ok(v) = serde_json::from_str::(text) else { + return Self::default(); + }; + let Some(p) = v.get(PROVENANCE) else { + return Self::default(); + }; + let mut out = Self::default(); + if !p.is_object() { + tracing::warn!("provenance field is not an object; copied as default with a note"); + out.add_note("provenance_malformed"); + return out; + } + match p.get("allen_agent").and_then(Value::as_str) { + Some(a) + if a == NO_AGENT + || (a.len() == 64 + && a.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))) => + { + out.allen_agent = a.to_string() + } + _ => { + tracing::warn!( + "provenance allen_agent is missing or malformed; copied as none with a note" + ); + out.add_note("allen_agent_malformed"); + } + } + out.generation_record = p.get("generation_record").and_then(Value::as_u64); + out.stale_generation = p.get("generation_record_stale").and_then(Value::as_u64); + // Carry an earlier note along the chain (bounded, printable ASCII only). + if let Some(n) = p.get("provenance_note").and_then(Value::as_str) { + let n: String = n + .chars() + .filter(|c| c.is_ascii_graphic() || *c == ' ') + .take(200) + .collect(); + for part in n.split("; ").filter(|s| !s.is_empty()) { + out.add_note(part); + } + } + out + } +} + +/// True when `id` names a verified `effect` note in `views` that is a +/// generation record (marker 1, no links). +pub fn generation_exists(views: &[ComposeRecordView], id: u64) -> bool { + views.iter().any(|r| { + r.id == id + && r.verified + && r.note.as_deref() == Some("effect") + && r.links.iter().all(|&l| l == 0) + && r.text + .as_deref() + .and_then(|t| serde_json::from_str::(t).ok()) + .is_some_and(|v| v.get(GENERATION).and_then(Value::as_u64) == Some(1)) + }) +} + +/// The provenance to copy from record `source` onto the next record of the +/// chain. A generation id that does not name a real generation record is +/// dropped (not refused): copying must not change any decision. +pub fn inherit(views: &[ComposeRecordView], source: u64) -> Provenance { + let mut p = views + .iter() + .find(|r| r.id == source) + .and_then(|r| r.text.as_deref()) + .map(Provenance::from_text) + .unwrap_or_default(); + if let Some(g) = p.generation_record { + if !generation_exists(views, g) { + tracing::warn!( + "provenance names generation record #{g}, which is not a verified generation record; copied as null with a stale marker" + ); + p.generation_record = None; + p.stale_generation = Some(g); + p.add_note("generation_record_stale"); + } + } + p +} + +/// What one compose proposal attempt contributes to its generation record. +pub struct ComposeEvidence<'a> { + /// `token_ids_sha256` of the submitted prompt ids. + pub prompt_ids_sha256: &'a str, + pub prompt_tokens: usize, + pub output_ids: &'a [u32], + /// The reply text handed to the template parser (assistant prefix plus the + /// decoded generated tokens). + pub text: &'a str, + pub finish_reason: &'a str, + /// The compose task and attempt (1-based) that made the generation. Daemon-assigned. + pub task: u64, + pub attempt: u32, +} + +/// The generation record of one compose proposal attempt: the same fields as +/// [`build_record`] plus `origin`, `task` and `attempt`. `request_id` and +/// `operation_id` are 0: there is no client envelope for a model call the +/// compose task makes itself. +pub fn build_compose_record(id: &ModelIdentity, e: &ComposeEvidence, start: DaemonStart) -> Value { + let (pid, start_ticks) = crate::effects::self_executor(); + json!({ + GENERATION: 1, + "v": 1, + "origin": "compose_proposal", + "task": e.task, + "attempt": e.attempt, + "model_sha256": id.model_sha256, + "model_path": id.model_path, + "tokenizer_sha256": id.tokenizer_sha256, + "tokenizer_path": id.tokenizer_path, + "prompt_ids_sha256": e.prompt_ids_sha256, + "output_token_ids_sha256": crate::spine::token_ids_sha256(e.output_ids), + "output_text_sha256": hex_sha256(e.text.as_bytes()), + "total_tokens": e.prompt_tokens + e.output_ids.len(), + "output_tokens": e.output_ids.len(), + "finish_reason": e.finish_reason, + "daemon": {"pid": pid, "start_ticks": start_ticks, "started_unix_ms": start.0.to_string()}, + "request_id": 0, + "operation_id": "0", + }) +} diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index ef585e63..0518f226 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -243,6 +243,11 @@ impl AienRuntimeServer { None } }; + // Provenance (arch#162): the compose task writes the generation record of + // the proposal it commits, so the bridge needs the model identity too. + if let (Some(b), Some(id)) = (compose.as_ref(), identity.as_ref()) { + b.set_model_identity((**id).clone(), self.started); + } // NEXT-PHASE-2 (ACCEPTANCE-v2 2.4): settle effects a previous process // left open, before serving anything. Reads the world, never re-runs. // A failed or refused reconcile does not stop the daemon, but every diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index bfd37569..3a0fa6a3 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -1763,6 +1763,14 @@ pub struct ComposeBridge { /// sovereign-core #297: when true, `ComposeAuthorize` needs the approval /// desk's MAC. Default false (legacy OS-user-only authorize). authorize_requires_desk: bool, + /// The loaded model files and the daemon start, set by the daemon after + /// load. Without them a compose proposal gets no generation record. + identity: std::sync::Mutex< + Option<( + crate::generation::ModelIdentity, + crate::generation::DaemonStart, + )>, + >, } impl ComposeBridge { @@ -1776,6 +1784,7 @@ impl ComposeBridge { reconcile_failed: std::sync::Mutex::new(None), closed: std::sync::atomic::AtomicBool::new(false), authorize_requires_desk: false, + identity: std::sync::Mutex::new(None), } } @@ -1785,6 +1794,17 @@ impl ComposeBridge { self } + /// The model files this daemon loaded (digests hashed at load) and when it + /// started. Set once by the daemon; the compose task uses them to write the + /// generation record of the proposal it commits. Evidence only. + pub fn set_model_identity( + &self, + identity: crate::generation::ModelIdentity, + started: crate::generation::DaemonStart, + ) { + *self.identity.lock().unwrap_or_else(|e| e.into_inner()) = Some((identity, started)); + } + /// Turn the desk-MAC requirement on `ComposeAuthorize` on or off (#297). pub fn with_authorize_requires_desk(mut self, on: bool) -> Self { self.authorize_requires_desk = on; @@ -2180,6 +2200,7 @@ impl ComposeBridge { // THIS proposal. `ComposeAuthorize` mints only from it. An approved // proposal has its own replay claim and grant, so it gets none. let mut compose_commit = None; + let mut generation_record = None; if let (true, None, Some(p), Some(text)) = ( committed, approved_text, @@ -2190,6 +2211,11 @@ impl ComposeBridge { .map_err(|e| format!("workspace {}: {e}", ws.display()))? .display() .to_string(); + // Provenance (arch#162): the generation record of the attempt the + // proposal came from, written now under the lock this run holds + // (the model call itself cannot take it). Evidence only. + generation_record = self.write_task_generation(home, task, &proposal_attempts); + let prov = crate::generation::Provenance::new(generation_record, home.allen.as_ref()); let id = crate::effects::write_compose_commit( home, &wsc, @@ -2199,6 +2225,7 @@ impl ComposeBridge { &hex(&Sha256::digest(text.as_bytes())), &p.path, &hex(&Sha256::digest(p.content.as_bytes())), + &prov, ) .map_err(|e| { format!( @@ -2213,6 +2240,7 @@ impl ComposeBridge { } Ok(ComposeTaskReport { compose_commit, + generation_record, compose_dir: self.dir.display().to_string(), machine_id: home.machine_id.clone(), @@ -2252,6 +2280,51 @@ impl ComposeBridge { }) } + /// Write the generation record of the proposal attempt a committed task + /// came from. `None` (with the reason logged when a write failed) when the + /// daemon has no model identity, the attempt did not expose its token ids, + /// or the append failed: no record means no claim, and the commit stands. + fn write_task_generation( + &self, + home: &mut ComposeHome, + task: u64, + attempts: &[ProposalAttempt], + ) -> Option { + let (identity, started) = self + .identity + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone()?; + let a = attempts.iter().find(|a| a.outcome == "parsed")?; + let (ids, text, prompt_sha, prompt_tokens) = ( + a.token_ids.as_deref()?, + a.text.as_deref()?, + a.prompt_ids_sha256.as_deref()?, + a.prompt_tokens?, + ); + let record = crate::generation::build_compose_record( + &identity, + &crate::generation::ComposeEvidence { + prompt_ids_sha256: prompt_sha, + prompt_tokens, + output_ids: ids, + text, + finish_reason: a.finish_reason.as_deref().unwrap_or("unknown"), + task, + attempt: a.attempt, + }, + started, + ); + match crate::generation::write(home, &record) { + Ok(id) => Some(id), + Err(e) => { + tracing::warn!("generation record not written: {e}"); + eprintln!("generation record not written: {e}"); + None + } + } + } + /// Append the daemon's generation record (evidence only; see /// `crate::generation`). Returns the record id only once it is written. pub fn record_generation(&self, record: &serde_json::Value) -> Result { diff --git a/crates/aien-runtime/tests/allen_persona_test.rs b/crates/aien-runtime/tests/allen_persona_test.rs index de64f71b..2ad90079 100644 --- a/crates/aien-runtime/tests/allen_persona_test.rs +++ b/crates/aien-runtime/tests/allen_persona_test.rs @@ -342,6 +342,7 @@ fn only_the_command_handler_can_write_the_profile() { fn old_reports_without_persona_still_parse() { let report = ComposeTaskReport { compose_commit: None, + generation_record: None, compose_dir: "d".into(), machine_id: "m".into(), task: 1, diff --git a/crates/aien-runtime/tests/provenance_link_test.rs b/crates/aien-runtime/tests/provenance_link_test.rs new file mode 100644 index 00000000..7da01c16 --- /dev/null +++ b/crates/aien-runtime/tests/provenance_link_test.rs @@ -0,0 +1,473 @@ +//! Provenance link (arch#162, ALLEN end-to-end demo v1 steps S4 and S8): a +//! commit the model produced through the compose path names the generation +//! record of that proposal and the ALLEN the task ran under. +//! +//! The real compose library, the real daemon server on its socket and the +//! ordinary operator flow: propose (RunComposeTask) -> authorize -> intent -> +//! write -> ack. Only the model is replaced by a fixed proposer that returns +//! the token ids the real inference path returns; the daemon is told the +//! "loaded model" digest with `set_model_identity`, exactly as the CLI does +//! after it loads weights. The live SmolLM2 version of this flow is +//! `crates/aien-cli/tests/provenance_link_live_test.rs` (ignored: it needs a +//! prebuilt binary and the model, like recovery_matrix_test). +//! +//! Everything here reads the ledger through the socket (`ComposeRecall`) and +//! the report as JSON, so the test is the same on a build without the link. +//! Every test needs the linked composition archive and is IGNORED in a stub +//! build, never passed. +#[path = "../../aien-allen/tests/support/mod.rs"] +mod support; + +use aien_allen::{hex as ahex, ENV_ADOPT, ENV_SUBJECT}; +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::create_shared_kv_manager; +use aien_omega_compose::{hex, Compose, RootKind}; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::{ControlCommand, ControlResponse}; +use aien_runtime::generation::ModelIdentity; +use aien_runtime::server::AienRuntimeServer; +use aien_runtime::spine::{ + token_ids_sha256, AienRuntimeSpine, ComposeBridge, ComposeProposer, Generation, +}; +use aien_scheduler::SchedulerConfig; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +/// The composition engine holds one home at a time per process, and the ALLEN +/// variables are process-wide. +static ONE_HOME: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +const PROPOSAL: &str = "filename: NOTES.md\nkeep every change inside the workspace\n"; +const CONTENT: &str = "keep every change inside the workspace\n"; +const OUT_IDS: [u32; 3] = [11, 12, 13]; +const PROMPT_IDS: [u32; 5] = [1, 2, 3, 4, 5]; + +fn sha(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +fn identity() -> ModelIdentity { + ModelIdentity { + model_sha256: "ab".repeat(32), + model_path: "/models/toy/model.safetensors".into(), + tokenizer_sha256: "cd".repeat(32), + tokenizer_path: "/models/toy/tokenizer.json".into(), + } +} + +/// The reply the real inference path gives: text, generated ids, prompt ids hash. +fn proposer() -> ComposeProposer { + Arc::new(|_p: &str, _l: Duration| { + Ok(Generation { + text: PROPOSAL.to_string(), + tokens: OUT_IDS.len(), + finish_reason: Some("eos".into()), + token_ids: Some(OUT_IDS.to_vec()), + prompt_tokens: Some(PROMPT_IDS.len()), + prompt_ids_sha256: Some(token_ids_sha256(&PROMPT_IDS)), + }) + }) +} + +struct Daemon { + client: AienRuntimeClient, + bridge: Arc, + handle: tokio::task::JoinHandle>, + _tmp: tempfile::TempDir, + ws: PathBuf, +} + +impl Daemon { + /// `home`: an existing compose home (ALLEN tests prepare one), else a fresh one. + async fn start( + model: Option, + home: Option<(tempfile::TempDir, PathBuf)>, + ) -> Self { + let (tmp, home) = home.unwrap_or_else(|| { + let t = tempfile::tempdir().unwrap(); + let h = t.path().join("compose"); + (t, h) + }); + let ws = std::fs::canonicalize({ + let w = tmp.path().join("ws"); + std::fs::create_dir_all(&w).unwrap(); + w + }) + .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 bridge = Arc::new(ComposeBridge::new(home, proposer(), "test:provenance-link")); + let server = AienRuntimeServer::new(spine, &socket).with_compose_bridge(bridge.clone()); + if let Some(m) = model { + server.set_model_identity(m); + } + let handle = tokio::spawn(async move { server.run(MockInferenceBackend::new(1)).await }); + let client = AienRuntimeClient::new(&socket); + for _ in 0..200 { + if client.is_alive().await { + return Self { + client, + bridge, + handle, + _tmp: tmp, + ws, + }; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + panic!("daemon did not come up"); + } + + async fn send(&self, c: ControlCommand) -> ControlResponse { + self.client.send_command(c).await.unwrap() + } + + /// Text of record `id` as JSON, digest-verified. + async fn record(&self, id: u64) -> Value { + match self + .send(ControlCommand::ComposeRecall { + ids: vec![id], + prefix: None, + }) + .await + { + ControlResponse::ComposeRecalled(r) => { + assert_eq!(r.cited.len(), 1, "record {id} missing"); + assert!(r.cited[0].verified, "record {id} does not verify"); + serde_json::from_str(r.cited[0].text.as_deref().unwrap()).unwrap() + } + other => panic!("recall: {other:?}"), + } + } + + async fn host_records(&self) -> usize { + match self + .send(ControlCommand::ComposeRecall { + ids: vec![], + prefix: None, + }) + .await + { + ControlResponse::ComposeRecalled(r) => r.host.len(), + other => panic!("recall: {other:?}"), + } + } + + async fn stop(self) { + let _ = self.client.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), self.handle).await; + } +} + +/// Every record id of one ordinary flow, and its report as JSON. +struct Flow { + report: Value, + commit: u64, + grant: u64, + intent: u64, + ack: u64, +} + +fn noted(r: ControlResponse, what: &str) -> u64 { + match r { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("{what}: {other:?}"), + } +} + +/// propose -> authorize -> intent -> write -> ack, through the socket. +async fn ordinary_flow(d: &Daemon) -> Flow { + let report = match d + .send(ControlCommand::RunComposeTask { + context: None, + goal: "write the note".into(), + workspace: d.ws.to_str().unwrap().into(), + }) + .await + { + ControlResponse::ComposeTaskResult(r) => serde_json::to_value(&*r).unwrap(), + other => panic!("run: {other:?}"), + }; + assert_eq!(report["committed"], true, "{report}"); + let commit = report["compose_commit"].as_u64().expect("commit record"); + let grant = noted( + d.send(ControlCommand::ComposeAuthorize { + cx_promotion: report["cx_promotion"].as_u64().unwrap(), + proposal_sha256: sha(PROPOSAL.as_bytes()), + workspace: d.ws.display().to_string(), + approver: "drake".into(), + constraints: vec![], + desk_proof: None, + }) + .await, + "authorize", + ); + let target = d.ws.join("NOTES.md").display().to_string(); + let (pid, start) = aien_runtime::effects::self_executor(); + let intent = noted( + d.send(ControlCommand::ComposeEffectIntent { + authorization: grant, + proposal_sha256: sha(PROPOSAL.as_bytes()), + path: "NOTES.md".into(), + target: target.clone(), + content_sha256: sha(CONTENT.as_bytes()), + executor_pid: pid, + executor_start: start, + }) + .await, + "intent", + ); + std::fs::write(&target, CONTENT).unwrap(); + let ack = noted( + d.send(ControlCommand::ComposeEffectAck { + intent, + reported: json!({"executor": "test"}), + }) + .await, + "ack", + ); + assert_eq!(d.record(ack).await["state"], "DONE"); + Flow { + report, + commit, + grant, + intent, + ack, + } +} + +/// The assertions of the demo's S4 and S8: the commit's records name a +/// generation record whose model digest is the loaded model's, and the agent. +async fn assert_linked(d: &Daemon, f: &Flow, want_agent: &str) { + let gen_id = f.report["generation_record"] + .as_u64() + .expect("the report names the generation record"); + for (name, id) in [ + ("compose_commit", f.commit), + ("grant", f.grant), + ("intent", f.intent), + ("ack", f.ack), + ] { + let r = d.record(id).await; + assert_eq!(r["provenance"]["generation_record"], gen_id, "{name}: {r}"); + assert_eq!(r["provenance"]["allen_agent"], want_agent, "{name}: {r}"); + } + let g = d.record(gen_id).await; + let want = identity(); + assert_eq!(g["generation"], 1); + assert_eq!(g["origin"], "compose_proposal"); + assert_eq!(g["model_sha256"], want.model_sha256); + assert_eq!(g["tokenizer_sha256"], want.tokenizer_sha256); + assert_eq!(g["task"], f.report["task"]); + assert_eq!(g["attempt"], 1); + assert_eq!(g["prompt_ids_sha256"], token_ids_sha256(&PROMPT_IDS)); + assert_eq!(g["output_token_ids_sha256"], token_ids_sha256(&OUT_IDS)); + assert_eq!(g["output_text_sha256"], sha(PROPOSAL.as_bytes())); + assert_eq!(g["output_tokens"], OUT_IDS.len()); + assert_eq!(g["finish_reason"], "eos"); + assert_eq!(g["daemon"]["pid"], std::process::id()); + // The grant, intent and commit still say what they said before. + assert_eq!( + d.record(f.commit).await["proposal_sha256"], + sha(PROPOSAL.as_bytes()) + ); + assert_eq!( + d.record(f.grant).await["content_sha256"], + sha(CONTENT.as_bytes()) + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn commit_names_generation_record_and_no_agent_when_none_is_attached() { + let _g = ONE_HOME.lock().await; + std::env::remove_var(ENV_SUBJECT); + std::env::remove_var(ENV_ADOPT); + let d = Daemon::start(Some(identity()), None).await; + let f = ordinary_flow(&d).await; + assert_linked(&d, &f, "none").await; + d.stop().await; +} + +/// (machine id, digest of Cortex record 1) of a home the daemon already opened. +fn home_lineage(home: &Path) -> [u8; 32] { + let mut name = home.as_os_str().to_owned(); + name.push(".machine-root"); + let root = std::fs::read(PathBuf::from(name)).unwrap(); + let (mut c, _) = Compose::open(home, RootKind::Provisioned, &root, 0xA1E4_0001).unwrap(); + c.record(1).unwrap().digest +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn commit_names_generation_record_and_the_allen_logical_agent_id() { + let _g = ONE_HOME.lock().await; + std::env::remove_var(ENV_SUBJECT); + std::env::remove_var(ENV_ADOPT); + // A home that already exists (an ALLEN is bound to a journal's lineage). + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("compose"); + { + let p = ComposeBridge::new(home.clone(), proposer(), "test:prepare"); + assert!(matches!( + p.note("constraint", "prepare the home", &[]), + ControlResponse::ComposeNoted(_) + )); + p.close(); + } + let mut fx = support::fx("provenance"); + fx.cortex = home_lineage(&home); + let chain = support::chain(&fx, 2); + let subject = support::write_head(&tmp.path().join("subject.bin"), chain.last().unwrap()); + let agent = ahex(&fx.agent); + std::env::set_var(ENV_SUBJECT, &subject); + std::env::set_var(ENV_ADOPT, &agent); + let d = Daemon::start(Some(identity()), Some((tmp, home))).await; + let f = ordinary_flow(&d).await; + assert_linked(&d, &f, &agent).await; + d.stop().await; + std::env::remove_var(ENV_SUBJECT); + std::env::remove_var(ENV_ADOPT); +} + +/// No model identity (a stub or reference-weights run): no generation record, +/// an explicit null in the chain, the flow itself unchanged. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn no_model_identity_means_no_generation_claim_and_the_flow_still_works() { + let _g = ONE_HOME.lock().await; + std::env::remove_var(ENV_SUBJECT); + std::env::remove_var(ENV_ADOPT); + let d = Daemon::start(None, None).await; + let f = ordinary_flow(&d).await; + assert_eq!(f.report["generation_record"], Value::Null); + for id in [f.commit, f.grant, f.intent, f.ack] { + let r = d.record(id).await; + assert_eq!(r["provenance"]["generation_record"], Value::Null, "{r}"); + assert_eq!(r["provenance"]["allen_agent"], "none"); + } + d.stop().await; +} + +/// A ledger written before this change has no provenance anywhere: it opens, +/// verifies and runs the same flow; what the daemon writes next says "none". +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn an_old_ledger_without_provenance_still_opens_and_runs() { + let _g = ONE_HOME.lock().await; + std::env::remove_var(ENV_SUBJECT); + std::env::remove_var(ENV_ADOPT); + let d = Daemon::start(Some(identity()), None).await; + // The old commit record exactly as #261 wrote it (no provenance field), + // appended below the note guard, as an old journal would hold it. + let target = d.ws.join("OLD.md"); + let old = json!({"compose_commit": 1, "task": 77, "cx_promotion": 777, "cx_evidence": 778, + "proposal_sha256": sha(b"old proposal"), "path": "OLD.md", + "content_sha256": sha(b"old\n"), "workspace": d.ws.display().to_string()}); + let commit = noted( + d.bridge.note_unchecked("effect", &old.to_string(), &[]), + "old commit", + ); + let before = d.record(commit).await; + assert!(before.get("provenance").is_none()); + let grant = noted( + d.send(ControlCommand::ComposeAuthorize { + cx_promotion: 777, + proposal_sha256: sha(b"old proposal"), + workspace: d.ws.display().to_string(), + approver: "drake".into(), + constraints: vec![], + desk_proof: None, + }) + .await, + "authorize on an old commit", + ); + let (pid, start) = aien_runtime::effects::self_executor(); + let intent = noted( + d.send(ControlCommand::ComposeEffectIntent { + authorization: grant, + proposal_sha256: sha(b"old proposal"), + path: "OLD.md".into(), + target: target.display().to_string(), + content_sha256: sha(b"old\n"), + executor_pid: pid, + executor_start: start, + }) + .await, + "intent on an old commit", + ); + std::fs::write(&target, "old\n").unwrap(); + let ack = noted( + d.send(ControlCommand::ComposeEffectAck { + intent, + reported: json!({}), + }) + .await, + "ack", + ); + assert_eq!(d.record(ack).await["state"], "DONE"); + for id in [grant, intent, ack] { + let r = d.record(id).await; + assert_eq!(r["provenance"]["generation_record"], Value::Null, "{r}"); + assert_eq!(r["provenance"]["allen_agent"], "none"); + } + d.stop().await; +} + +/// A caller cannot set the fields: ComposeNote refuses a provenance field on +/// any record, and a forged "generation" a record that names one; a grant +/// request carries only ids and digests, so the copy comes from the daemon's +/// own commit record whatever the request says. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +async fn a_client_cannot_set_the_provenance_fields() { + let _g = ONE_HOME.lock().await; + std::env::remove_var(ENV_SUBJECT); + std::env::remove_var(ENV_ADOPT); + let d = Daemon::start(Some(identity()), None).await; + let before = d.host_records().await; + for (kind, text) in [ + ( + "effect", + r#"{"provenance":{"generation_record":3,"allen_agent":"none"}}"#, + ), + ("constraint", r#"{"provenance":{"generation_record":3}}"#), + ( + "effect", + r#"{"compose_commit":1,"provenance":{"generation_record":3}}"#, + ), + ("effect", r#"{"generation":1,"origin":"compose_proposal"}"#), + ("authorization", r#"{"provenance":{"generation_record":3}}"#), + ] { + match d + .send(ControlCommand::ComposeNote { + kind: kind.into(), + text: text.into(), + links: vec![], + }) + .await + { + ControlResponse::Error(e) => assert!( + e.contains("provenance") || e.contains("generation") || e.contains("authorization"), + "{e}" + ), + other => panic!("FORGED ({kind} {text}): {other:?}"), + } + } + assert_eq!(d.host_records().await, before, "nothing was written"); + // The flow's records carry the daemon's values; the request has no field to say otherwise. + let f = ordinary_flow(&d).await; + assert_linked(&d, &f, "none").await; + d.stop().await; +} diff --git a/docs/DAEMON_GENERATION_RECORD.md b/docs/DAEMON_GENERATION_RECORD.md index d793ca68..3bccd340 100644 --- a/docs/DAEMON_GENERATION_RECORD.md +++ b/docs/DAEMON_GENERATION_RECORD.md @@ -90,3 +90,102 @@ The turn still succeeds, with `generation_record` absent, when: was not written. A verifier must treat an absent record as an absent claim, not as a pass. + +## Provenance link: which generation made a commit, and which ALLEN asked + +The `StreamTurn` record above says what the daemon generated. It did not say +which commit that text became. The compose path (`aien compose propose`, the +model Skill) now closes that gap (arch#162, ALLEN end-to-end demo v1 steps S4 +and S8). + +### What the daemon does + +1. When a compose task commits a model proposal, the daemon writes one + generation record for the proposal attempt the commit came from (the + `parsed` attempt), in the same format and with the same writer as above. + It is written under the compose home lock the task already holds (the + model call itself cannot take it). Extra fields on this record: + `origin` = `compose_proposal`, `task` (the compose task id) and `attempt` + (1-based). `request_id` is 0 and `operation_id` is `"0"`: the task makes + this model call itself, there is no client envelope. `prompt_ids_sha256` + and `output_token_ids_sha256` are the hashes of the ids the inference path + returned for that attempt. `output_text_sha256` is the digest of the reply + handed to the template parser (the assistant prefix plus the decoded + tokens), the same digest the attempt records as `text_sha256`. In edit + mode the committed proposal is that reply merged into the prior file, so + the proposal digest is not this one; the link is by record id, below. +2. The id is returned in `ComposeTaskReport.generation_record` (optional + field, absent in old reports) and written into the daemon's + `compose_commit` record. +3. Every record of the commit chain carries one evidence object, + `"provenance": {"generation_record": , "allen_agent": "<64 hex or none>"}`: + the `compose_commit` record, the minted grant (`ComposeAuthorize`), the + intent, and the ack. Each is copied by the daemon from the record before it + (grant from commit, intent from grant, ack from intent), never from the + request. An approved grant (`ComposeApprovedProposal`) carries + `generation_record` null (no model ran) and the ALLEN agent. A reconcile + record is not stamped; its intent is. +4. `allen_agent` is the ALLEN LogicalAgentId (`aien_allen::Resolved::agent`, + the 64 hex shown in the `ALLEN: engaged agent=...` line) of the daemon that + ran the task, or the explicit string `none` when no ALLEN is attached. No + second identity system. + +A verifier follows the commit's records (`aien compose recall --ids ...`) to +`provenance.generation_record`, reads that record, and compares its +`model_sha256` with the weights it holds. `aien compose effects` does not +print provenance: the effect ledger deliberately does not parse it. + +### What it does not change (separation from authorization) + +Provenance is evidence, never an input. `Ledger`, `check_intent`, +`check_minted_backing`, `check_approved_backing`, the world checks and +reconcile never read it: their row types have no provenance field. The only +reader is `generation::Provenance::from_text`, called from one writer helper +(`effects::stamp`) after the writer's decisions are made. A damaged, +absent or wrong-typed field reads as `generation_record` null and +`allen_agent` `none`; it can never refuse or allow anything. Tests: +`effects::provenance_changes_no_decision` (ledgers with absent, valid, bogus +and hostile provenance give identical state and identical refusals), +`effects::provenance_is_read_by_no_decision_code` (a source scan: which +functions may mention provenance, and that no ledger type has the field). + +### Not forgeable by a client + +`ComposeNote` refuses any note, of any kind, whose JSON has a top-level +`provenance` field, and still refuses kind `generation` and any `effect` note +with the `generation` field. The grant, intent and ack requests carry only +ids and digests, so there is no field a client can fill. A record the daemon +writes that names a generation id is refused at write time unless that id is a +verified generation record of the same ledger (`write_compose_commit`: +`compose-commit not written: provenance names generation record #N ...`). +When the daemon copies provenance along the chain (grant, intent, ack), an id +that no longer names a verified generation record is copied as null instead of +refused, so copying can never change an authorization outcome. + +### Old ledgers + +Records written before this change have no `provenance` field. They open and +verify as before, and a grant, intent or ack the daemon writes from them +carries the explicit default (`generation_record` null, `allen_agent` `none`). +`ComposeTaskReport.generation_record` defaults to absent on old reports. +Test: `an_old_ledger_without_provenance_still_opens_and_runs`. + +### No generation record means no claim + +`generation_record` is null when the daemon has no model identity (stub run, +reference weights), the attempt did not expose its token ids, the proposal is +an approved one, or the ledger append failed (logged as +`generation record not written`). The commit still stands; a verifier treats +null as an absent claim, not a pass. The same limits as above apply: the +digest is of the file read at load time, the ledger is not signed, and the +record proves nothing about capability or authority. + +### Tests + +- `crates/aien-runtime/tests/provenance_link_test.rs`: the real compose + library and the real daemon server, ordinary flow through the socket; + asserts the commit's records give a generation id whose `model_sha256` is the + loaded model's digest and the expected agent (an engaged ALLEN, and `none`). +- `crates/aien-cli/tests/provenance_link_live_test.rs`: the same with the real + `aien daemon` process, SmolLM2-1.7B on CPU, the real CLI. Ignored (needs a + prebuilt binary and the model).