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/1835b9e0068e1acb # 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#244 (code only) closed derived `1835b9e0068e1acb` #244 Imported from GitHub aien-dev/aien-sovereign-core-mv#244 (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 `331f880b56058c4f2bba24b44d8c0e7ca69b7ca3` · Head `5782bdc30bc199b9f4a782fa4ae8aec5101595e2` ### Fetch it A git bundle of the pull request's head, 15876 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/1835b9e0068e1acb.bundle -o 1835b9e0068e1acb.bundle git fetch 1835b9e0068e1acb.bundle refs/pull/244/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 244 5782bdc30bc199b9f4a782fa4ae8aec5101595e2 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":244,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/244","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:30Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 1ecb0d4c..a6565a0a 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:009593670dc7accc2b442a6a8c6f3b848ab73de4d6e61df57401bf4bf00b294a", - "compiled_at": "2026-10-06T23:16:27Z", + "compiled_at": "2026-10-06T23:31:02Z", "compiler": "crumb-compile/1", - "digest": "sha256:93a0643a652866abd03be0400a2aa6afe25da7d85663559b5c06fd0ae67d0ebb", + "digest": "sha256:e0a75f92bf68c2b3a79131e513c355aa986d05caa755cc5d8f1615c6f25d9786", "evidence_files": 90, "evidence_root": "sha256:913405b594470a9dfda6998ea0386eba372f438bce4e9d05c062369a9f7b1e22", - "files": 947, - "generated_at_commit": "0dee0dc6ebbeddf60b9b69a9fcf2c363eb552814", - "source_tree": "sha256:5e454af3e4525e2235ca3ebb75db74ac59c69d70450ad34f31e007f8e3226845" + "files": 950, + "generated_at_commit": "6e6b71ee90ca0251d2762f997ce177f837f68106", + "source_tree": "sha256:7b47e36edbbc29792dc6dd6c45bd07827974fe24303cf7ad83d8bcfb9800cb7a" } }, "history": [], diff --git a/crates/aien-runtime/src/approved.rs b/crates/aien-runtime/src/approved.rs new file mode 100644 index 00000000..fdc377be --- /dev/null +++ b/crates/aien-runtime/src/approved.rs @@ -0,0 +1,221 @@ +//! Proposer hook: an approved proposal enters the production compose path. +//! +//! The approval desk upstream (INTERPLANE `ComposeLedgerAuthority`, +//! interplane#77) hands over one file change it approved. `ProposerHook` +//! checks it, then drives it through the same compose run `RunComposeTask` +//! uses: the model Skill returns the approved text instead of calling the +//! model, AEGIS checks it with the bridge's verify callback, the winner +//! commits through the World on a J-Space branch, Cortex records it. +//! +//! The hook grants nothing. It never writes the workspace and never mints an +//! authorization: the effect still needs an `authorization` note, a +//! `ComposeEffectIntent` and an ack (crate::effects). Anything it cannot +//! verify, any duplicate and any run that does not commit is refused with a +//! named error (`PROPOSAL_REFUSED : ...`), never dropped. +//! +//! Hash semantics (both are reported, never conflated): +//! - `approved_proposal_sha256`: sha256 of the compact JSON object +//! `{"content":..,"path":..}` with sorted keys, as interplane#77 computes it. +//! - `compose_proposal_sha256`: sha256 of the committed proposal text +//! (`filename: \n`), the value `aien compose authorize` puts +//! in the authorization grant and `ComposeEffectIntent` must repeat. +//! +//! Design note: docs/COMPOSE_PROPOSER_HOOK.md. +use crate::control::ComposeTaskReport; +use crate::spine::{check_file_proposal, ComposeBridge}; +use aien_omega_compose::hex; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use sha2::{Digest, Sha256}; +use std::collections::HashSet; +use std::sync::{Arc, Mutex}; + +/// Prefix of every hook refusal. +pub const REFUSED: &str = "PROPOSAL_REFUSED"; + +/// One file change an upstream approval desk approved (the interplane#77 +/// ledger fields plus the correlation ids). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ApprovedProposal { + /// INTERPLANE request id and trace id: carried into the report. + pub request_id: String, + pub trace_id: String, + /// The approval the desk consumed (single use). + pub approval_id: String, + pub approver: String, + /// Workspace-relative path and the complete new content. + pub path: String, + pub content: String, + /// `approved_proposal_sha256(path, content)` as the desk computed it. + pub approved_proposal_sha256: String, + /// sha256 of `content`. + pub content_sha256: String, +} + +/// What a committed approved proposal hands to the effect ledger. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ApprovedComposeReport { + pub request_id: String, + pub trace_id: String, + pub approval_id: String, + pub approver: String, + pub path: String, + pub content_sha256: String, + pub approved_proposal_sha256: String, + /// sha256 of the committed proposal text: the authorization grant and the + /// effect intent must name this value. + pub compose_proposal_sha256: String, + /// Links the authorization grant carries, as `aien compose authorize` + /// does: [cx_promotion, cx_evidence]. + pub grant_links: Vec, + /// The compose run (J-Space branch, AEGIS verdict, World commit records). + pub task: ComposeTaskReport, +} + +fn sha256_hex(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +fn refuse(name: &str, why: impl std::fmt::Display) -> String { + format!("{REFUSED} {name}: {why}") +} + +/// sha256 of the compact JSON `{"content":..,"path":..}`, keys sorted +/// (inserted in sorted order, so serde_json's map ordering does not matter). +pub fn approved_proposal_sha256(path: &str, content: &str) -> String { + let mut m = Map::new(); + m.insert("content".into(), Value::String(content.to_string())); + m.insert("path".into(), Value::String(path.to_string())); + sha256_hex(Value::Object(m).to_string().as_bytes()) +} + +/// The proposal text in the compose template. Refused unless the template +/// parser reads back exactly this path and content (a content the parser +/// would normalise is refused, not silently changed). +pub fn proposal_text(path: &str, content: &str) -> Result { + let text = format!("filename: {path}\n{content}"); + let p = check_file_proposal(&text).map_err(|e| refuse("Unverified", e))?; + if p.path != path || p.content != content { + return Err(refuse( + "Unverified", + "content does not read back unchanged through the compose template \ + (it must end with one newline, not start with a blank line or a code fence)", + )); + } + Ok(text) +} + +/// Every check that needs no compose home. Ok = the proposal text. +pub fn verify(p: &ApprovedProposal) -> Result { + for (k, v) in [ + ("request_id", &p.request_id), + ("trace_id", &p.trace_id), + ("approval_id", &p.approval_id), + ("approver", &p.approver), + ] { + if v.trim().is_empty() { + return Err(refuse("Unverified", format!("empty {k}"))); + } + } + if sha256_hex(p.content.as_bytes()) != p.content_sha256 { + return Err(refuse( + "Unverified", + "content_sha256 does not match content", + )); + } + if approved_proposal_sha256(&p.path, &p.content) != p.approved_proposal_sha256 { + return Err(refuse( + "Unverified", + "approved_proposal_sha256 does not match {content, path}", + )); + } + proposal_text(&p.path, &p.content) +} + +/// The hook over one compose bridge (the daemon's, or a test's). +pub struct ProposerHook { + bridge: Arc, + /// Request and approval ids already submitted by this process. + consumed: Mutex>, +} + +impl ProposerHook { + pub fn new(bridge: Arc) -> Self { + Self { + bridge, + consumed: Mutex::new(HashSet::new()), + } + } + + /// Blocking (runs the composition). Verify, refuse duplicates, run, and + /// return the commit only if the World committed exactly this proposal. + pub fn submit( + &self, + p: &ApprovedProposal, + workspace: &str, + ) -> Result { + let text = verify(p)?; + { + let mut seen = self + .consumed + .lock() + .map_err(|_| refuse("Internal", "replay set lock poisoned"))?; + let keys = [ + format!("request:{}", p.request_id), + format!("approval:{}", p.approval_id), + ]; + if let Some(k) = keys.iter().find(|k| seen.contains(*k)) { + return Err(refuse("Duplicate", format!("{k} was already submitted"))); + } + // Consumed before the run: a failed run never frees the approval. + for k in keys { + seen.insert(k); + } + } + // The goal names the path, so an existing file is an edit target here as + // in RunComposeTask; the approved branch of the Skill ignores it (edit = + // None), see spine.rs. + let goal = format!( + "apply approved proposal for {} (request {})", + p.path, p.request_id + ); + let r = self + .bridge + .run_approved_task(&goal, workspace, &text) + .map_err(|e| refuse("ComposeError", e))?; + if !r.committed { + return Err(refuse( + "NotCommitted", + format!( + "outcome {} (AEGIS pass mask {:#x}); {}", + r.outcome, + r.aegis_pass_mask, + r.proposer_error.as_deref().unwrap_or("no proposer error") + ), + )); + } + let compose_sha = sha256_hex(text.as_bytes()); + if r.proposal.as_deref() != Some(text.as_str()) + || r.proposal_sha256.as_deref() != Some(compose_sha.as_str()) + || r.proposal_path.as_deref() != Some(p.path.as_str()) + || r.proposal_content_sha256.as_deref() != Some(p.content_sha256.as_str()) + { + return Err(refuse( + "Mismatch", + "the committed proposal is not the approved one", + )); + } + Ok(ApprovedComposeReport { + request_id: p.request_id.clone(), + trace_id: p.trace_id.clone(), + approval_id: p.approval_id.clone(), + approver: p.approver.clone(), + path: p.path.clone(), + content_sha256: p.content_sha256.clone(), + approved_proposal_sha256: p.approved_proposal_sha256.clone(), + compose_proposal_sha256: compose_sha, + grant_links: vec![r.cx_promotion, r.cx_evidence], + task: r, + }) + } +} diff --git a/crates/aien-runtime/src/lib.rs b/crates/aien-runtime/src/lib.rs index df644c5b..8bd576a6 100644 --- a/crates/aien-runtime/src/lib.rs +++ b/crates/aien-runtime/src/lib.rs @@ -1,5 +1,6 @@ //! AIEN Runtime: Canonical Single-Process Host for Persistent Branching Intelligence +pub mod approved; pub mod client; pub mod context; pub mod control; diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 8ab879c6..45908df8 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -546,6 +546,10 @@ pub type ComposeProposer = /// The one Skill name; its procedure digest is sha256 of this name. pub const COMPOSE_MODEL_SKILL: &str = "aien.model.propose-file-change"; +/// `ComposeTaskReport::proposer` of a run driven by the proposer hook +/// (crate::approved): the reply came from an approved proposal, not a model. +pub const APPROVED_PROPOSER_LABEL: &str = "hook:approved-proposal"; + /// 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. @@ -1103,6 +1107,8 @@ pub(crate) struct ComposeHome { pub(crate) compose: Compose, pub(crate) machine_id: String, prompts: Arc>>, + /// Proposer hook: task -> approved proposal text (crate::approved). + approved: Arc>>, /// What the model Skill returned per task: the text, or why it gave /// none, and every attempt it made. proposals: Arc>>, @@ -1211,22 +1217,52 @@ impl ComposeBridge { .map_err(|r| mark_refusal(&self.dir, &r))?; let prompts: Arc>> = Arc::default(); let proposals: Arc>> = Arc::default(); + let approved: Arc>> = Arc::default(); let (pr, pp, proposer) = (prompts.clone(), proposals.clone(), self.proposer.clone()); + let pa = approved.clone(); compose .register_skill(COMPOSE_MODEL_SKILL, None, 10, move |task| { let (prompt, target) = pr.lock().get(&task).cloned()?; - // Fixed template + bounded automatic retry (ACCEPTANCE-v2 3a, 3b), - // measured per-attempt budget (ACCEPTANCE-v3 3b); an edit reply - // is merged into the content the model was shown (v7 T5). - let edit = target.as_ref().map(|(p, c)| (p.as_str(), c.as_str())); - let (out, attempts) = propose_task_with_retries( - proposer.as_ref(), - &prompt, - edit, - COMPOSE_SKILL_BUDGET, - COMPOSE_ATTEMPT_BUDGET, - COMPOSE_MAX_ATTEMPTS, - ); + // Proposer hook (crate::approved): an approved proposal for this + // task replaces the model's reply. One attempt, the same + // template check, the same AEGIS contract and commit below. + // edit = None: an approved whole-file proposal never goes + // through merge_edit_reply, so the committed bytes are the + // approved bytes even when the path already exists. + let fixed = pa.lock().get(&task).cloned(); + let (out, attempts) = match fixed { + Some(text) => { + let one = move |_: &str, _: std::time::Duration| { + Ok(Generation { + text: text.clone(), + finish_reason: Some("approved".into()), + ..Default::default() + }) + }; + propose_task_with_retries( + &one, + &prompt, + None, + COMPOSE_SKILL_BUDGET, + COMPOSE_ATTEMPT_BUDGET, + 1, + ) + } + // Fixed template + bounded automatic retry (ACCEPTANCE-v2 3a, 3b), + // measured per-attempt budget (ACCEPTANCE-v3 3b); an edit reply + // is merged into the content the model was shown (v7 T5). + None => { + let edit = target.as_ref().map(|(p, c)| (p.as_str(), c.as_str())); + propose_task_with_retries( + proposer.as_ref(), + &prompt, + edit, + COMPOSE_SKILL_BUDGET, + COMPOSE_ATTEMPT_BUDGET, + COMPOSE_MAX_ATTEMPTS, + ) + } + }; let h = out.as_ref().ok().map(|t| proposal_handle(t)); pp.lock().insert(task, (out, attempts)); h @@ -1259,6 +1295,7 @@ impl ComposeBridge { compose, machine_id: hex(&info.machine_id), prompts, + approved, proposals, mark_path, machine_raw: info.machine_id, @@ -1312,13 +1349,31 @@ impl ComposeBridge { /// 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) { + match self.run_task_inner(goal, workspace, None) { Ok(r) => ControlResponse::ComposeTaskResult(Box::new(r)), Err(e) => ControlResponse::Error(e), } } - fn run_task_inner(&self, goal: &str, workspace: &str) -> Result { + /// Proposer hook entry (crate::approved): one compose run whose model + /// Skill returns `approved_text` instead of calling the proposer. The run + /// is otherwise the RunComposeTask run: J-Space branch, AEGIS verify + /// callback, World commit, Cortex records. Blocking. + pub(crate) fn run_approved_task( + &self, + goal: &str, + workspace: &str, + approved_text: &str, + ) -> Result { + self.run_task_inner(goal, workspace, Some(approved_text)) + } + + fn run_task_inner( + &self, + goal: &str, + workspace: &str, + approved_text: Option<&str>, + ) -> Result { if goal.trim().is_empty() { return Err("RunComposeTask: empty goal".into()); } @@ -1350,9 +1405,13 @@ impl ComposeBridge { *guard = Some(self.open_home()?); } let home = guard.as_mut().expect("opened above"); + if let Some(t) = approved_text { + home.approved.lock().insert(task, t.to_string()); + } home.prompts.lock().insert(task, prompt); let run = home.compose.run(task, now.as_micros() as u64); home.prompts.lock().remove(&task); + home.approved.lock().remove(&task); let output = home.proposals.lock().remove(&task); // A run appends whether or not it commits: move the record mark first. home.advance_mark() @@ -1399,7 +1458,10 @@ impl ComposeBridge { uncommitted_proposal, proposer_error, proposal_attempts, - proposer: self.proposer_label.clone(), + proposer: match approved_text { + Some(_) => APPROVED_PROPOSER_LABEL.to_string(), + None => self.proposer_label.clone(), + }, }) } diff --git a/crates/aien-runtime/tests/approved_proposal_test.rs b/crates/aien-runtime/tests/approved_proposal_test.rs new file mode 100644 index 00000000..133199c9 --- /dev/null +++ b/crates/aien-runtime/tests/approved_proposal_test.rs @@ -0,0 +1,287 @@ +//! Proposer hook (crate::approved): an approved proposal goes through the +//! production compose run (J-Space branch, AEGIS verify, World commit) and +//! then the durable effect ledger; unverified and duplicate proposals are +//! refused with nothing appended. CPU only, no model, no socket: the bridge +//! is driven exactly as the daemon drives it. In a stub build only the +//! refusal paths run. +use aien_omega_compose::hex; +use aien_runtime::approved::{self, ApprovedProposal, ProposerHook}; +use aien_runtime::control::{ComposeRecallReport, ControlResponse}; +use aien_runtime::effects::{self, IntentRequest, Ledger}; +use aien_runtime::spine::{ComposeBridge, ComposeProposer, APPROVED_PROPOSER_LABEL}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::path::Path; +use std::sync::Arc; + +const PATH: &str = "NOTES.md"; +const CONTENT: &str = "approved by the INTERPLANE desk\n"; + +/// The model proposer must never be called on the hook path. +fn model_never_called() -> ComposeProposer { + Arc::new(|_: &str, _: std::time::Duration| panic!("the model proposer ran on the hook path")) +} + +fn sha(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +/// Independent of approved::approved_proposal_sha256: the interplane#77 +/// canonical form written out by hand. +fn interplane_sha(path: &str, content: &str) -> String { + let s = format!( + "{{\"content\":{},\"path\":{}}}", + serde_json::to_string(content).unwrap(), + serde_json::to_string(path).unwrap() + ); + sha(s.as_bytes()) +} + +fn proposal(request: &str, approval: &str) -> ApprovedProposal { + ApprovedProposal { + request_id: request.into(), + trace_id: format!("trace-{request}"), + approval_id: approval.into(), + approver: "interplane-host".into(), + path: PATH.into(), + content: CONTENT.into(), + approved_proposal_sha256: interplane_sha(PATH, CONTENT), + content_sha256: sha(CONTENT.as_bytes()), + } +} + +fn recalled(b: &ComposeBridge, ids: &[u64]) -> ComposeRecallReport { + match b.recall(ids, None) { + ControlResponse::ComposeRecalled(r) => *r, + other => panic!("recall: {other:?}"), + } +} + +fn refused(r: Result, name: &str) { + match r { + Err(e) => assert!( + e.starts_with(&format!("PROPOSAL_REFUSED {name}:")), + "want {name}, got {e}" + ), + Ok(v) => panic!("want PROPOSAL_REFUSED {name}, got {v:?}"), + } +} + +fn setup() -> (tempfile::TempDir, Arc, ProposerHook, String) { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + let b = Arc::new(ComposeBridge::new( + tmp.path().join("compose"), + model_never_called(), + "test:model-never-called", + )); + let hook = ProposerHook::new(b.clone()); + let ws = ws.display().to_string(); + (tmp, b, hook, ws) +} + +#[test] +fn approved_proposal_commits_then_effect_is_done() { + let (_tmp, b, hook, ws) = setup(); + let out = hook.submit(&proposal("req-1", "appr-1"), &ws); + if !aien_omega_compose::LINKED { + refused(out, "ComposeError"); + return; + } + let r = out.unwrap(); + // Correlation and both hash semantics, side by side. + assert_eq!( + (r.request_id.as_str(), r.trace_id.as_str()), + ("req-1", "trace-req-1") + ); + assert_eq!(r.approved_proposal_sha256, interplane_sha(PATH, CONTENT)); + let text = format!("filename: {PATH}\n{CONTENT}"); + assert_eq!(r.compose_proposal_sha256, sha(text.as_bytes())); + assert_ne!(r.approved_proposal_sha256, r.compose_proposal_sha256); + // The compose run: one J-Space branch, AEGIS pass, World commit. + let t = &r.task; + assert!(t.committed, "{t:?}"); + assert_eq!((t.outcome, t.branch_count, t.winner), (1, 1, Some(0))); + assert_eq!(t.aegis_pass_mask & 1, 1); + assert_eq!(t.proposer, APPROVED_PROPOSER_LABEL); + assert_eq!(t.proposal_attempts.len(), 1); + assert_eq!(t.proposal_attempts[0].aegis.as_deref(), Some("pass")); + assert!(t.cx_goal != 0 && t.cx_evidence != 0 && t.cx_promotion != 0); + assert_eq!(r.grant_links, vec![t.cx_promotion, t.cx_evidence]); + // The World commit record is in the Cortex journal and verifies. + let c = recalled(&b, &[t.cx_promotion]); + assert!(c.missing.is_empty(), "{c:?}"); + assert!(c.cited[0].verified, "{:?}", c.cited[0]); + assert_eq!(c.cited[0].id, t.cx_promotion); + // Nothing touched the workspace yet: the hook grants nothing. + let target = Path::new(&ws).join(PATH); + assert!(!target.exists()); + + // Effect: grant (named as aien compose authorize names it), intent, write, ack. + let tgt = target.display().to_string(); + let grant = json!({"proposal_sha256": r.compose_proposal_sha256, "path": r.path, + "content_sha256": r.content_sha256, "approver": r.approver, "target": tgt, + "prior_sha256": Value::Null}); + let a = match b.note("authorization", &grant.to_string(), &r.grant_links) { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("grant: {other:?}"), + }; + let (pid, start) = effects::self_executor(); + let req = IntentRequest { + authorization: a, + proposal_sha256: r.compose_proposal_sha256.clone(), + path: r.path.clone(), + target: tgt.clone(), + content_sha256: r.content_sha256.clone(), + executor_pid: pid, + executor_start: start, + }; + let i = match effects::open_intent(&b, &req) { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("intent: {other:?}"), + }; + std::fs::write(&target, CONTENT).unwrap(); + let k = match effects::ack(&b, i, &json!({"written_sha256": r.content_sha256})) { + ControlResponse::ComposeNoted(n) => n.id, + other => panic!("ack: {other:?}"), + }; + let rec = recalled(&b, &[k]); + let v: Value = serde_json::from_str(rec.cited[0].text.as_deref().unwrap()).unwrap(); + assert_eq!(v["state"], "DONE", "{v}"); + assert_eq!(std::fs::read(&target).unwrap(), CONTENT.as_bytes()); +} + +#[test] +fn unverified_proposal_is_refused_with_zero_effects() { + let (_tmp, b, hook, ws) = setup(); + println!( + "approved_proposal_test: compose LINKED={} (zero-journal assertions {})", + aien_omega_compose::LINKED, + if aien_omega_compose::LINKED { + "run" + } else { + "skipped: stub build" + } + ); + let before = aien_omega_compose::LINKED.then(|| recalled(&b, &[]).records_total); + let mut cases: Vec<(&str, ApprovedProposal)> = Vec::new(); + let mut p = proposal("u1", "a1"); + p.content_sha256 = sha(b"other bytes\n"); + cases.push(("content sha mismatch", p)); + let mut p = proposal("u2", "a2"); + // The compose text sha in the approved slot: the other hash semantics. + p.approved_proposal_sha256 = sha(format!("filename: {PATH}\n{CONTENT}").as_bytes()); + cases.push(("text sha in the approved slot", p)); + let mut p = proposal("u3", "a3"); + p.path = "../escape.md".into(); + p.approved_proposal_sha256 = interplane_sha(&p.path, CONTENT); + cases.push(("path outside the workspace", p)); + let mut p = proposal("u4", "a4"); + p.content = "no trailing newline".into(); + p.content_sha256 = sha(p.content.as_bytes()); + p.approved_proposal_sha256 = interplane_sha(PATH, &p.content); + cases.push(("content the template would change", p)); + let mut p = proposal("u5", ""); + p.approval_id = " ".into(); + cases.push(("no approval id", p)); + let mut p = proposal("", "a6"); + p.request_id = String::new(); + cases.push(("no request id", p)); + for (what, p) in &cases { + let r = hook.submit(p, &ws); + assert!(r.is_err(), "{what}: {r:?}"); + refused(r, "Unverified"); + } + assert!(!Path::new(&ws).join(PATH).exists()); + assert!(!Path::new(&ws).join("../escape.md").exists()); + if let Some(n) = before { + let after = recalled(&b, &[]); + assert_eq!( + after.records_total, n, + "a refused proposal appended records" + ); + let l = Ledger::from_records(&after.host).unwrap(); + assert!(l.grants.is_empty() && l.intents.is_empty()); + } +} + +#[test] +fn duplicate_proposal_is_refused() { + let (_tmp, b, hook, ws) = setup(); + let first = hook.submit(&proposal("req-d", "appr-d"), &ws); + if !aien_omega_compose::LINKED { + refused(first, "ComposeError"); + // Consumed before the run: the replay is refused even in a stub build. + refused(hook.submit(&proposal("req-d", "appr-d"), &ws), "Duplicate"); + return; + } + assert!(first.unwrap().task.committed); + let n = recalled(&b, &[]).records_total; + refused(hook.submit(&proposal("req-d", "appr-d"), &ws), "Duplicate"); + refused( + hook.submit(&proposal("req-other", "appr-d"), &ws), + "Duplicate", + ); + refused( + hook.submit(&proposal("req-d", "appr-other"), &ws), + "Duplicate", + ); + assert_eq!( + recalled(&b, &[]).records_total, + n, + "a duplicate appended records" + ); + // The same change under a fresh request and approval is a new proposal. + assert!( + hook.submit(&proposal("req-e", "appr-e"), &ws) + .unwrap() + .task + .committed + ); +} + +#[test] +fn approved_hash_is_the_interplane_form() { + assert_eq!( + approved::approved_proposal_sha256("a/b.md", "x \"q\"\n\u{1}é\n"), + interplane_sha("a/b.md", "x \"q\"\n\u{1}é\n") + ); +} + +/// The path already exists: RunComposeTask would treat it as an edit target +/// and merge the reply into the seed (v7 T5). An approved whole-file +/// proposal must commit byte-exact, with no seed line merged in. +#[test] +fn approved_proposal_over_existing_file_commits_byte_exact() { + let (_tmp, _b, hook, ws) = setup(); + let seed = "# Notes\nseed line one\nseed line two\n"; + std::fs::write(Path::new(&ws).join(PATH), seed).unwrap(); + // Shares "# Notes" with the seed, so an edit merge would keep both seed lines. + let content = "# Notes\napproved replacement line\n"; + let mut p = proposal("req-x", "appr-x"); + p.content = content.into(); + p.content_sha256 = sha(content.as_bytes()); + p.approved_proposal_sha256 = interplane_sha(PATH, content); + let out = hook.submit(&p, &ws); + if !aien_omega_compose::LINKED { + refused(out, "ComposeError"); + return; + } + let r = out.unwrap(); + let t = &r.task; + assert!(t.committed, "{t:?}"); + let text = format!("filename: {PATH}\n{content}"); + assert_eq!(t.proposal.as_deref(), Some(text.as_str())); + assert!(!t.proposal.as_deref().unwrap().contains("seed line")); + assert_eq!( + t.proposal_content_sha256.as_deref(), + Some(p.content_sha256.as_str()) + ); + assert_eq!(r.compose_proposal_sha256, sha(text.as_bytes())); + // The hook wrote nothing: the seed is untouched. + assert_eq!( + std::fs::read_to_string(Path::new(&ws).join(PATH)).unwrap(), + seed + ); +} diff --git a/docs/COMPOSE_PROPOSER_HOOK.md b/docs/COMPOSE_PROPOSER_HOOK.md new file mode 100644 index 00000000..8c1126c9 --- /dev/null +++ b/docs/COMPOSE_PROPOSER_HOOK.md @@ -0,0 +1,59 @@ +# Compose proposer hook (design note) + +Scope: how an approved proposal from an upstream approval desk (INTERPLANE +`ComposeLedgerAuthority`, interplane#77) enters the production compose path. +Line numbers are for the commit that adds this note. + +## Entry point +`ProposerHook::submit` (crates/aien-runtime/src/approved.rs:152) checks the +proposal (`verify`, approved.rs:109), refuses duplicates, then calls +`ComposeBridge::run_approved_task` (crates/aien-runtime/src/spine.rs:1362), +which is `run_task_inner` (spine.rs:1371), the body `RunComposeTask` runs +(server.rs:593 -> spine.rs:1351). The approved text is staged per task and +the registered model Skill (spine.rs:1224) returns it instead of calling the +`ComposeProposer` (spine.rs:1232); one attempt, the same template check, and edit += None (spine.rs:1245): an approved proposal never goes through +`merge_edit_reply`, so an existing file is replaced byte-exact. + +## Path to J-Space and World commit +`home.compose.run` (spine.rs:1412) -> `Compose::run` +(crates/aien-omega-compose/src/lib.rs:302) -> `rxc_host_run` in omega +`librx_compose.a` (omega.lock c0369e67, archive sha256 dfe0ffb8...): the Skill +result is staged on a J-Space branch, AEGIS calls the bridge's verify callback +(spine.rs:1273: result handle equals the Skill's text and it parses as one +file change), the winner commits through the World, Cortex records goal, +candidates, evidence and promotion (`cx_*` in `ComposeTaskReport`). The hook +returns Ok only if the run committed exactly the approved text. + +## What the ledger hands over (`ApprovedProposal`, approved.rs:39) +request_id, trace_id, approval_id, approver, path, content, +approved_proposal_sha256, content_sha256. The hook returns +`ApprovedComposeReport` (approved.rs:57): the same ids plus +compose_proposal_sha256, grant_links and the compose `task` report. + +## Hash semantics (fix) +- approved_proposal_sha256 = sha256 of compact JSON {"content","path"} with + sorted keys (interplane#77). Checked, then carried for provenance. +- compose_proposal_sha256 = sha256 of the committed text + `filename: \n`. The authorization grant and the + `ComposeEffectIntent` must name this value: `aien compose authorize` does + (crates/aien-cli/src/compose.rs:252) and `Ledger::check_intent` compares it + (crates/aien-runtime/src/effects.rs:341). Grant links = [cx_promotion, + cx_evidence], as compose.rs:271. +- Content the template parser would normalise (no final newline, leading + blank line, code fence) is refused, so content_sha256 is the committed one. + +## Refusals (never silent) +`PROPOSAL_REFUSED Unverified` (hash, ids, path, template round trip; nothing +appended), `Duplicate` (request or approval id already submitted in this +process), `ComposeError`, `NotCommitted`, `Mismatch`. + +## Deferred +- No socket command: the hook is in-process only. A daemon command (and the + `AIEN_COMPOSE_PROPOSER=interplane:` selection) is the next cut. +- Replay set is in memory; after a daemon restart a replay is stopped by the + upstream desk (pending approvals are in memory) and by single-use grants, + not by this hook. A durable request-id record is not written. +- The effect receipt (`record_effect_receipt`) still has no request_id. +- Real model leg NOT_RUN; no GPU. +- approver / approval_id are caller-supplied: authenticate + durable replay first (#249). ```