aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-runtime / src / compose / bridge.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! The compose bridge implementation: proposal parsing, destination and input |
| 17 | //! classification, prompts, bounded retries, the composition home and |
| 18 | //! `ComposeBridge`. Callers use the interface in `crate::compose`. |
| 19 | |
| 20 | use crate::control::{ControlCommand, ControlResponse}; |
| 21 | use std::sync::Arc; |
| 22 | |
| 23 | use crate::control::{ |
| 24 | ComposeNoteReport, ComposeRecallReport, ComposeRecordView, ComposeRecoverReport, |
| 25 | ComposeTaskReport, InputOmitted, InputRef, ProposalAttempt, |
| 26 | }; |
| 27 | use crate::cortex_mark::{self, Mark, MarkRefusal, Plan}; |
| 28 | use aien_omega_compose::{hex, note_bytes, Compose, ComposeError, NoteKind, RootKind}; |
| 29 | use sha2::{Digest, Sha256}; |
| 30 | use std::collections::HashMap; |
| 31 | use std::path::{Path, PathBuf}; |
| 32 | |
| 33 | /// One model reply: the text and how many tokens were generated. |
| 34 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 35 | pub struct Generation { |
| 36 | pub text: String, |
| 37 | pub tokens: usize, |
| 38 | /// How generation stopped: "eos" | "max_tokens" | "aborted" | "preempted" |
| 39 | /// (ACCEPTANCE-v5 Q3); None when unknown. |
| 40 | pub finish_reason: Option<String>, |
| 41 | /// NEXT-PHASE-1 v6 R1: the generated token ids in order (None when the |
| 42 | /// proposer does not expose them). Recorded only; nothing reads them. |
| 43 | pub token_ids: Option<Vec<u32>>, |
| 44 | /// NEXT-PHASE-1 v6 R1: how many prompt token ids were submitted. |
| 45 | pub prompt_tokens: Option<usize>, |
| 46 | /// NEXT-PHASE-1 v6 R1: `token_ids_sha256` of the submitted prompt ids. |
| 47 | pub prompt_ids_sha256: Option<String>, |
| 48 | /// How the backend chose the generated tokens (sc#294), as the scheduler |
| 49 | /// reported it when the sequence finished. None when the proposer or the |
| 50 | /// backend does not observe it: an absent claim, not greedy. |
| 51 | pub decoding: Option<aien_abi_core::DecodeObservation>, |
| 52 | /// The tensor backend and its op counters when the call finished (sc#337). |
| 53 | /// None when the proposer or the backend does not report them: no claim. |
| 54 | pub ops: Option<aien_abi_core::OpEvidence>, |
| 55 | } |
| 56 | |
| 57 | /// sha256 (hex) of token ids, each as 4 little-endian bytes (NEXT-PHASE-1 v6 |
| 58 | /// R1): the daemon and the CPU reference driver hash prompts the same way. |
| 59 | pub fn token_ids_sha256(ids: &[u32]) -> String { |
| 60 | let mut h = Sha256::new(); |
| 61 | for id in ids { |
| 62 | h.update(id.to_le_bytes()); |
| 63 | } |
| 64 | hex(&h.finalize()) |
| 65 | } |
| 66 | |
| 67 | /// The "model" Skill's work: prompt text and a wall limit in, one reply |
| 68 | /// out. The server installs the real inference path (the one `StreamTurn` |
| 69 | /// uses); tests install a deterministic proposer. |
| 70 | pub type ComposeProposer = |
| 71 | Arc<dyn Fn(&str, std::time::Duration) -> Result<Generation, String> + Send + Sync>; |
| 72 | |
| 73 | /// The one Skill name; its procedure digest is sha256 of this name. |
| 74 | const COMPOSE_MODEL_SKILL: &str = "aien.model.propose-file-change"; |
| 75 | |
| 76 | /// `ComposeTaskReport::proposer` of a run driven by the proposer hook |
| 77 | /// (crate::approved): the reply came from an approved proposal, not a model. |
| 78 | const APPROVED_PROPOSER_LABEL: &str = "hook:approved-proposal"; |
| 79 | |
| 80 | /// Composition home: `$AIEN_COMPOSE_DIR`, else `$AIEN_RUNTIME_STATE_DIR/compose`, |
| 81 | /// else `$XDG_STATE_HOME/aien-runtime/compose`, else |
| 82 | /// `$HOME/.local/state/aien-runtime/compose`. Never /tmp. |
| 83 | pub fn compose_dir_from_env() -> Result<PathBuf, String> { |
| 84 | let get = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty()); |
| 85 | if let Some(d) = get("AIEN_COMPOSE_DIR") { |
| 86 | return Ok(PathBuf::from(d.trim())); |
| 87 | } |
| 88 | if let Some(d) = get("AIEN_RUNTIME_STATE_DIR") { |
| 89 | return Ok(PathBuf::from(d.trim()).join("compose")); |
| 90 | } |
| 91 | if let Some(d) = get("XDG_STATE_HOME") { |
| 92 | return Ok(PathBuf::from(d.trim()).join("aien-runtime/compose")); |
| 93 | } |
| 94 | if let Some(h) = get("HOME") { |
| 95 | return Ok(PathBuf::from(h.trim()).join(".local/state/aien-runtime/compose")); |
| 96 | } |
| 97 | Err( |
| 98 | "no AIEN_COMPOSE_DIR, AIEN_RUNTIME_STATE_DIR, XDG_STATE_HOME or HOME for the compose home" |
| 99 | .into(), |
| 100 | ) |
| 101 | } |
| 102 | |
| 103 | /// The provisioned machine root: 32 random bytes kept beside the home |
| 104 | /// (`<home>.machine-root`, mode 0600), created once. STOPGAP until Aienux |
| 105 | /// machine provisioning owns the AienMachineId root. |
| 106 | fn machine_root(dir: &Path) -> Result<Vec<u8>, String> { |
| 107 | use std::io::Read; |
| 108 | use std::os::unix::fs::OpenOptionsExt; |
| 109 | let mut name = dir.as_os_str().to_owned(); |
| 110 | name.push(".machine-root"); |
| 111 | let path = PathBuf::from(name); |
| 112 | if let Ok(b) = std::fs::read(&path) { |
| 113 | if b.len() == 32 { |
| 114 | return Ok(b); |
| 115 | } |
| 116 | return Err(format!( |
| 117 | "{} holds {} bytes, expected 32", |
| 118 | path.display(), |
| 119 | b.len() |
| 120 | )); |
| 121 | } |
| 122 | if let Some(p) = path.parent() { |
| 123 | std::fs::create_dir_all(p).map_err(|e| format!("create {}: {e}", p.display()))?; |
| 124 | } |
| 125 | let mut root = vec![0u8; 32]; |
| 126 | std::fs::File::open("/dev/urandom") |
| 127 | .and_then(|mut f| f.read_exact(&mut root)) |
| 128 | .map_err(|e| format!("read /dev/urandom: {e}"))?; |
| 129 | let mut f = std::fs::OpenOptions::new() |
| 130 | .write(true) |
| 131 | .create_new(true) |
| 132 | .mode(0o600) |
| 133 | .open(&path) |
| 134 | .map_err(|e| format!("create {}: {e}", path.display()))?; |
| 135 | std::io::Write::write_all(&mut f, &root) |
| 136 | .map_err(|e| format!("write {}: {e}", path.display()))?; |
| 137 | f.sync_all() |
| 138 | .map_err(|e| format!("sync {}: {e}", path.display()))?; |
| 139 | Ok(root) |
| 140 | } |
| 141 | |
| 142 | fn proposal_handle(text: &str) -> u64 { |
| 143 | let d = Sha256::digest(text.as_bytes()); |
| 144 | let h = u64::from_le_bytes(d[..8].try_into().expect("8 bytes")); |
| 145 | if h == 0 { |
| 146 | 1 |
| 147 | } else { |
| 148 | h |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | /// ALLEN identity gate (aien-allen, ADR 0035), run once per compose-home open. |
| 153 | /// Not engaged (AIEN_ALLEN_SUBJECT unset): one log line, nothing else changes. |
| 154 | /// Engaged: any refusal is FATAL (message, nonzero exit), never a fallback. |
| 155 | /// Returns the resolved identity when engaged, so the compose home can keep it |
| 156 | /// (persona profile, arch#159); `None` when not engaged. |
| 157 | fn allen_gate( |
| 158 | dir: &Path, |
| 159 | compose: &mut Compose, |
| 160 | machine_id: &[u8; 32], |
| 161 | ) -> Option<aien_allen::Resolved> { |
| 162 | use aien_allen::{Context, Gate}; |
| 163 | static NOT_ENGAGED_ONCE: std::sync::Once = std::sync::Once::new(); |
| 164 | let lineage = compose.record(1).ok().map(|r| r.digest); |
| 165 | let ctx = Context { |
| 166 | machine_id: *machine_id, |
| 167 | lineage, |
| 168 | }; |
| 169 | // The operator adoption variable is honoured once per process: after this |
| 170 | // process wrote the pin, later opens (recover, re-open) see it as spent. |
| 171 | static ADOPTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); |
| 172 | let get = |k: &str| { |
| 173 | if k == aien_allen::ENV_ADOPT && ADOPTED.load(std::sync::atomic::Ordering::SeqCst) { |
| 174 | return None; |
| 175 | } |
| 176 | std::env::var(k).ok() |
| 177 | }; |
| 178 | match aien_allen::gate(dir, &ctx, &get) { |
| 179 | Gate::NotEngaged => { |
| 180 | NOT_ENGAGED_ONCE.call_once(|| println!("{}", aien_allen::NOT_ENGAGED_LINE)); |
| 181 | None |
| 182 | } |
| 183 | Gate::Engaged(r) => { |
| 184 | if r.adopted { |
| 185 | ADOPTED.store(true, std::sync::atomic::Ordering::SeqCst); |
| 186 | } |
| 187 | let adopted = if r.adopted { |
| 188 | " (ADOPTED: pin written once, operator-approved)" |
| 189 | } else { |
| 190 | "" |
| 191 | }; |
| 192 | println!( |
| 193 | "ALLEN: engaged agent={} head_sequence={} chain_verified={}{adopted}", |
| 194 | aien_allen::hex(&r.agent), |
| 195 | r.head_seq, |
| 196 | r.chain_verified |
| 197 | ); |
| 198 | Some(r) |
| 199 | } |
| 200 | Gate::Refused(why) => { |
| 201 | let msg = format!("FATAL ALLEN refused: {why}"); |
| 202 | tracing::error!("{msg}"); |
| 203 | eprintln!("{msg}"); |
| 204 | std::process::exit(aien_allen::EXIT_REFUSED); |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | /// A named refusal for an rxc_host open error: the operator learns what is |
| 210 | /// wrong and that `RecoverComposeHome` is the remedy (never a silent repair). |
| 211 | fn refusal(dir: &Path, e: &ComposeError) -> String { |
| 212 | let why = match e { |
| 213 | ComposeError::Code { code: -3, .. } => { |
| 214 | "Cortex journal tail torn (E_TORN, CX_ERR_TORN); nothing was cut. Run RecoverComposeHome (aien compose recover)" |
| 215 | .to_string() |
| 216 | } |
| 217 | ComposeError::Code { code: -11, detail } => format!( |
| 218 | "Cortex journal behind its J-Space anchor (E_REPLAY, RX_ERR_REPLAY {detail}). Run RecoverComposeHome (aien compose recover)" |
| 219 | ), |
| 220 | other => other.to_string(), |
| 221 | }; |
| 222 | format!("compose home {} refused: {why}", dir.display()) |
| 223 | } |
| 224 | |
| 225 | /// A refusal by the Cortex record mark (ACCEPTANCE-v3 2.2), in the same form. |
| 226 | fn mark_refusal(dir: &Path, r: &MarkRefusal) -> String { |
| 227 | format!("compose home {} refused: {r}", dir.display()) |
| 228 | } |
| 229 | |
| 230 | /// The record chain (`cortex_mark::chain_step`) from `start` over the digests |
| 231 | /// of records #`lo`..=#`hi`, as the open home reads them. |
| 232 | fn record_chain( |
| 233 | compose: &mut Compose, |
| 234 | start: [u8; 32], |
| 235 | lo: u64, |
| 236 | hi: u64, |
| 237 | ) -> Result<[u8; 32], String> { |
| 238 | let mut c = start; |
| 239 | for id in lo..=hi { |
| 240 | let d = compose |
| 241 | .record(id) |
| 242 | .map_err(|e| format!("record {id}: {e}"))? |
| 243 | .digest; |
| 244 | cortex_mark::chain_step(&mut c, &d); |
| 245 | } |
| 246 | Ok(c) |
| 247 | } |
| 248 | |
| 249 | /// One proposed file change: a path relative to the workspace and the |
| 250 | /// complete new content. |
| 251 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 252 | pub struct FileProposal { |
| 253 | pub path: String, |
| 254 | pub content: String, |
| 255 | } |
| 256 | |
| 257 | fn bare(s: &str) -> &str { |
| 258 | s.trim() |
| 259 | .trim_matches(|c| matches!(c, '`' | '"' | '\'' | '*')) |
| 260 | .trim() |
| 261 | } |
| 262 | |
| 263 | /// A path the workspace may hold: relative, at most 255 bytes, letters, |
| 264 | /// digits and `._-/`, no empty, `.` or `..` component, not absolute, not `~`. |
| 265 | fn check_relative_path(p: &str) -> Result<(), String> { |
| 266 | if p.is_empty() { |
| 267 | return Err("empty path on the filename line".into()); |
| 268 | } |
| 269 | if p.starts_with('/') || p.starts_with('~') || p.split('/').any(|c| c == "..") { |
| 270 | return Err(format!("path {p:?} is outside the workspace")); |
| 271 | } |
| 272 | let ok = p.len() <= 255 |
| 273 | && p.chars() |
| 274 | .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/')) |
| 275 | && p.split('/').all(|c| !c.is_empty() && c != "."); |
| 276 | if ok { |
| 277 | Ok(()) |
| 278 | } else { |
| 279 | Err(format!("path {p:?} is not a plain relative path")) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | /// A code-fence line: its backtick run length and whether an info string |
| 284 | /// (such as `bash`) follows the run. Not a fence if fewer than three |
| 285 | /// backticks start the line or the info string itself holds a backtick. |
| 286 | fn fence_line(l: &str) -> Option<(usize, bool)> { |
| 287 | let t = l.trim_start(); |
| 288 | let n = t.bytes().take_while(|&b| b == b'`').count(); |
| 289 | if n < 3 { |
| 290 | return None; |
| 291 | } |
| 292 | let info = t[n..].trim(); |
| 293 | if info.contains('`') { |
| 294 | return None; |
| 295 | } |
| 296 | Some((n, !info.is_empty())) |
| 297 | } |
| 298 | |
| 299 | /// Index (into `body`, which starts after the opening fence of backtick |
| 300 | /// length `open_len`) of the line that closes the outer fence, or None. |
| 301 | /// CommonMark: a closing fence is bare (no info string) and at least as long |
| 302 | /// as the opener, so shorter inner fences are plain content. Inner fences of |
| 303 | /// the same length that carry an info string (` ```bash `) open a nested block |
| 304 | /// that its own bare fence must close first. If that scan finds no balanced |
| 305 | /// close (unbalanced reply), the LAST bare fence of sufficient length is |
| 306 | /// taken, so content is never cut at an inner fence. A bare fence at depth 0 |
| 307 | /// that still has fences after it is a bare inner opener, so the outer fence |
| 308 | /// is closed by the last fence of the reply. Limit: prose that itself holds a |
| 309 | /// fence AFTER the real close is read as part of the file. With no bare fence at |
| 310 | /// all there is no close: the caller keeps the whole body. |
| 311 | fn outer_fence_close(body: &[&str], open_len: usize) -> Option<usize> { |
| 312 | let fences: Vec<(usize, bool)> = body |
| 313 | .iter() |
| 314 | .enumerate() |
| 315 | .filter_map(|(i, l)| fence_line(l).filter(|f| f.0 >= open_len).map(|f| (i, f.1))) |
| 316 | .collect(); |
| 317 | let mut depth = 0usize; |
| 318 | let mut last_bare = None; |
| 319 | for (k, &(i, info)) in fences.iter().enumerate() { |
| 320 | if info { |
| 321 | depth += 1; |
| 322 | } else if depth > 0 { |
| 323 | depth -= 1; |
| 324 | last_bare = Some(i); |
| 325 | } else if k + 1 == fences.len() { |
| 326 | return Some(i); |
| 327 | } else { |
| 328 | // A bare fence with more fences after it opens a bare inner block; |
| 329 | // only the final fence can then be the outer close. |
| 330 | depth += 1; |
| 331 | } |
| 332 | } |
| 333 | last_bare |
| 334 | } |
| 335 | |
| 336 | /// The model's answer in the fixed proposal template: the first nonempty |
| 337 | /// line is `filename: <relative path>` (case-insensitive key; quotes, |
| 338 | /// backticks and asterisks around it or the path are ignored, and so are leading |
| 339 | /// `./` segments of the path, sc#402), everything |
| 340 | /// after it is the complete content (blank lines around it and one |
| 341 | /// surrounding code fence are dropped; it ends with one newline). |
| 342 | /// Err names why the reply is refused. Deterministic: the Skill, the AEGIS |
| 343 | /// contract, the authorization and the write all use this one reading. |
| 344 | pub fn check_file_proposal(text: &str) -> Result<FileProposal, String> { |
| 345 | let lines: Vec<&str> = text.lines().collect(); |
| 346 | let at = lines |
| 347 | .iter() |
| 348 | .position(|l| !l.trim().is_empty()) |
| 349 | .ok_or("empty reply")?; |
| 350 | let first = bare(lines[at]); |
| 351 | const KEY: &str = "filename:"; |
| 352 | // `get`, not `[..]`: byte 9 can fall inside a multi-byte character (issue #546). |
| 353 | let key_matches = first |
| 354 | .get(..KEY.len()) |
| 355 | .is_some_and(|k| k.eq_ignore_ascii_case(KEY)); |
| 356 | if first.len() < KEY.len() || !key_matches { |
| 357 | return Err("no filename line: the first line must be 'filename: <relative path>'".into()); |
| 358 | } |
| 359 | // sc#402: `./report.md` is `report.md`; the strict check then runs as before. |
| 360 | let path = crate::destination::strip_leading_curdir(bare(&first[KEY.len()..])).to_string(); |
| 361 | check_relative_path(&path)?; |
| 362 | let mut body: Vec<&str> = lines[at + 1..].to_vec(); |
| 363 | while body.first().is_some_and(|l| l.trim().is_empty()) { |
| 364 | body.remove(0); |
| 365 | } |
| 366 | if body |
| 367 | .first() |
| 368 | .is_some_and(|l| l.trim_start().starts_with("```")) |
| 369 | { |
| 370 | let open_len = body[0] |
| 371 | .trim_start() |
| 372 | .bytes() |
| 373 | .take_while(|&b| b == b'`') |
| 374 | .count(); |
| 375 | body.remove(0); |
| 376 | if let Some(end) = outer_fence_close(&body, open_len) { |
| 377 | body.truncate(end); |
| 378 | } |
| 379 | } |
| 380 | while body.last().is_some_and(|l| l.trim().is_empty()) { |
| 381 | body.pop(); |
| 382 | } |
| 383 | if body.iter().all(|l| l.trim().is_empty()) { |
| 384 | return Err("empty content after the filename line".into()); |
| 385 | } |
| 386 | let mut content = body.join("\n"); |
| 387 | content.push('\n'); |
| 388 | Ok(FileProposal { path, content }) |
| 389 | } |
| 390 | |
| 391 | /// `check_file_proposal` without the reason. |
| 392 | pub fn parse_file_proposal(text: &str) -> Option<FileProposal> { |
| 393 | check_file_proposal(text).ok() |
| 394 | } |
| 395 | |
| 396 | /// At most this many proposals per task (ACCEPTANCE-v2 Section 3b). |
| 397 | const COMPOSE_MAX_ATTEMPTS: u32 = 3; |
| 398 | /// Wall budget for all attempts of one task: rx_compose_run's 30 s |
| 399 | /// quiescence wait (not raised) less a 1 s margin (ACCEPTANCE-v3 Section 3b). |
| 400 | const COMPOSE_SKILL_BUDGET: std::time::Duration = std::time::Duration::from_secs(29); |
| 401 | /// Wall budget of a full-document task (one that creates a new file): 120 s. |
| 402 | const COMPOSE_DOC_BUDGET: std::time::Duration = std::time::Duration::from_secs(120); |
| 403 | /// Env: wall budget of a small edit, in ms. Unset = `COMPOSE_SKILL_BUDGET` (29 s). |
| 404 | const COMPOSE_EDIT_BUDGET_ENV: &str = "AIEN_COMPOSE_EDIT_BUDGET_MS"; |
| 405 | /// Env: wall budget of a full-document task, in ms. Unset = `COMPOSE_DOC_BUDGET` (120 s). |
| 406 | const COMPOSE_DOC_BUDGET_ENV: &str = "AIEN_COMPOSE_DOC_BUDGET_MS"; |
| 407 | /// Env: output token cap of a full-document task. Unset = `COMPOSE_DOC_MAX_TOKENS_DEFAULT`. |
| 408 | /// (Small edits keep `AIEN_COMPOSE_MAX_TOKENS`, read by the daemon, default 48.) |
| 409 | const COMPOSE_DOC_MAX_TOKENS_ENV: &str = "AIEN_COMPOSE_DOC_MAX_TOKENS"; |
| 410 | /// The one-budget setting this replaced. Setting it is refused, never ignored. |
| 411 | const COMPOSE_BUDGET_ENV_RETIRED: &str = "AIEN_COMPOSE_BUDGET_MS"; |
| 412 | /// Default output token cap of a full-document task. |
| 413 | const COMPOSE_DOC_MAX_TOKENS_DEFAULT: usize = 1024; |
| 414 | /// Accepted range of `AIEN_COMPOSE_DOC_MAX_TOKENS`. |
| 415 | const COMPOSE_DOC_MAX_TOKENS_RANGE: std::ops::RangeInclusive<usize> = 16..=4096; |
| 416 | /// Accepted range of both budget settings: omega waits budget + 1 000 ms and accepts at most 600 000 ms. |
| 417 | const COMPOSE_BUDGET_MS_RANGE: std::ops::RangeInclusive<u64> = 1_000..=599_000; |
| 418 | /// Margin between the skill budget and omega's settle wait. |
| 419 | const COMPOSE_WAIT_MARGIN: std::time::Duration = std::time::Duration::from_millis(1_000); |
| 420 | |
| 421 | /// What a compose task is, for limits: a small edit of an existing file, or |
| 422 | /// the creation of a whole new document. Decided by `classify_target`. |
| 423 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 424 | pub enum ProposalKind { |
| 425 | Edit, |
| 426 | Document, |
| 427 | } |
| 428 | |
| 429 | /// What the goal's named target is, decided by whether the path EXISTS (not by |
| 430 | /// whether an edit block can be built from it). |
| 431 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 432 | pub enum TargetClass { |
| 433 | /// No existing file is named: the task creates a new document. |
| 434 | New, |
| 435 | /// An existing small UTF-8 file inside the workspace: path and content. |
| 436 | Edit(String, String), |
| 437 | /// An existing path that no edit block can be built for (too large, |
| 438 | /// non-UTF-8, unreadable, or resolving outside the workspace). Never a |
| 439 | /// new document, never overwritten. |
| 440 | Refused(String), |
| 441 | } |
| 442 | |
| 443 | impl TargetClass { |
| 444 | pub fn kind(&self) -> ProposalKind { |
| 445 | match self { |
| 446 | Self::Edit(..) => ProposalKind::Edit, |
| 447 | _ => ProposalKind::Document, |
| 448 | } |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | /// The two wall budgets in force. |
| 453 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 454 | pub struct ComposeBudgets { |
| 455 | pub edit: std::time::Duration, |
| 456 | pub doc: std::time::Duration, |
| 457 | } |
| 458 | |
| 459 | impl Default for ComposeBudgets { |
| 460 | fn default() -> Self { |
| 461 | Self { |
| 462 | edit: COMPOSE_SKILL_BUDGET, |
| 463 | doc: COMPOSE_DOC_BUDGET, |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | impl ComposeBudgets { |
| 469 | pub(crate) fn for_kind(&self, kind: ProposalKind) -> std::time::Duration { |
| 470 | match kind { |
| 471 | ProposalKind::Edit => self.edit, |
| 472 | ProposalKind::Document => self.doc, |
| 473 | } |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | /// Parse one budget setting named `name`. `None` (unset) gives `default`; an |
| 478 | /// empty, non-numeric or out-of-range value is refused, never replaced by the default. |
| 479 | fn parse_compose_budget( |
| 480 | name: &str, |
| 481 | default: std::time::Duration, |
| 482 | v: Option<&str>, |
| 483 | ) -> Result<std::time::Duration, String> { |
| 484 | let Some(raw) = v else { |
| 485 | return Ok(default); |
| 486 | }; |
| 487 | let ms: u64 = raw |
| 488 | .trim() |
| 489 | .parse() |
| 490 | .map_err(|_| format!("{name}={raw:?} is not a whole number of milliseconds"))?; |
| 491 | if !COMPOSE_BUDGET_MS_RANGE.contains(&ms) { |
| 492 | return Err(format!( |
| 493 | "{name}={ms} is outside {}..={} ms", |
| 494 | COMPOSE_BUDGET_MS_RANGE.start(), |
| 495 | COMPOSE_BUDGET_MS_RANGE.end() |
| 496 | )); |
| 497 | } |
| 498 | Ok(std::time::Duration::from_millis(ms)) |
| 499 | } |
| 500 | |
| 501 | /// Parse `AIEN_COMPOSE_DOC_MAX_TOKENS` (same refusal rule as the budgets). |
| 502 | fn parse_compose_doc_max_tokens(v: Option<&str>) -> Result<usize, String> { |
| 503 | let Some(raw) = v else { |
| 504 | return Ok(COMPOSE_DOC_MAX_TOKENS_DEFAULT); |
| 505 | }; |
| 506 | let n: usize = raw.trim().parse().map_err(|_| { |
| 507 | format!("{COMPOSE_DOC_MAX_TOKENS_ENV}={raw:?} is not a whole number of tokens") |
| 508 | })?; |
| 509 | if !COMPOSE_DOC_MAX_TOKENS_RANGE.contains(&n) { |
| 510 | return Err(format!( |
| 511 | "{COMPOSE_DOC_MAX_TOKENS_ENV}={n} is outside {}..={} tokens", |
| 512 | COMPOSE_DOC_MAX_TOKENS_RANGE.start(), |
| 513 | COMPOSE_DOC_MAX_TOKENS_RANGE.end() |
| 514 | )); |
| 515 | } |
| 516 | Ok(n) |
| 517 | } |
| 518 | |
| 519 | fn env_opt(name: &str) -> Result<Option<String>, String> { |
| 520 | match std::env::var(name) { |
| 521 | Ok(v) => Ok(Some(v)), |
| 522 | Err(std::env::VarError::NotPresent) => Ok(None), |
| 523 | Err(e) => Err(format!("{name} unreadable: {e}")), |
| 524 | } |
| 525 | } |
| 526 | |
| 527 | /// Env switch for the desk MAC on `ComposeAuthorize` (#297, #328). Required |
| 528 | /// by default: unset or `1` = required. `0` is the dev-only opt-out, accepted |
| 529 | /// only in a dev run (`aien_inference_abi::strict::dev_fallback_active`); a |
| 530 | /// strict run, which is what release qualification runs, refuses it. Anything |
| 531 | /// else stops the daemon (a typo must not leave the requirement silently off). |
| 532 | pub const AUTHORIZE_DESK_ENV: &str = "AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK"; |
| 533 | |
| 534 | /// The rule behind [`authorize_requires_desk_from_env`], for a switch value |
| 535 | /// and whether this is a dev run. |
| 536 | pub fn authorize_desk_setting(value: Option<&str>, dev: bool) -> Result<bool, String> { |
| 537 | match value { |
| 538 | None | Some("1") => Ok(true), |
| 539 | Some("0") if dev => Ok(false), |
| 540 | Some("0") => Err(format!( |
| 541 | "{AUTHORIZE_DESK_ENV}=0 is a dev-only opt-out and is prohibited here: this is a strict run \ |
| 542 | (no {}=1), as release qualification is. Create the desk key with \ |
| 543 | `aien compose desk-key --create 1` and unset {AUTHORIZE_DESK_ENV}", |
| 544 | aien_inference_abi::strict::DEV_FALLBACK_ENV |
| 545 | )), |
| 546 | Some(o) => Err(format!( |
| 547 | "{AUTHORIZE_DESK_ENV} must be 1 (required, the default) or 0 (dev-only opt-out), got {o:?}" |
| 548 | )), |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | pub fn authorize_requires_desk_from_env() -> Result<bool, String> { |
| 553 | authorize_desk_setting( |
| 554 | env_opt(AUTHORIZE_DESK_ENV)?.as_deref(), |
| 555 | aien_inference_abi::strict::dev_fallback_active(), |
| 556 | ) |
| 557 | } |
| 558 | |
| 559 | /// Startup check (#328): a bridge that requires the desk must find a loadable |
| 560 | /// desk key in its compose home, or the daemon refuses to start. Never creates |
| 561 | /// a key: minting one is the operator's `aien compose desk-key --create`. |
| 562 | pub(crate) fn check_desk_key_at_start(compose_dir: &Path) -> Result<(), String> { |
| 563 | let path = crate::approved_auth::desk_key_path(compose_dir); |
| 564 | crate::approved_auth::DeskKey::load(&path).map(|_| ()).map_err(|e| { |
| 565 | format!( |
| 566 | "the approval desk is required ({AUTHORIZE_DESK_ENV} unset or 1) but its key is not usable: {e}. \ |
| 567 | Create it with `aien compose desk-key --create 1` (AIEN_COMPOSE_DIR={}); the daemon refuses to \ |
| 568 | start without it", |
| 569 | compose_dir.display() |
| 570 | ) |
| 571 | }) |
| 572 | } |
| 573 | |
| 574 | /// The daemon's startup rule from the environment (#328): the setting, |
| 575 | /// after the desk key check when the desk is required. |
| 576 | pub fn authorize_desk_at_start_from_env() -> Result<bool, String> { |
| 577 | let required = authorize_requires_desk_from_env()?; |
| 578 | if required { |
| 579 | if let Ok(dir) = compose_dir_from_env() { |
| 580 | check_desk_key_at_start(&dir)?; |
| 581 | } |
| 582 | } |
| 583 | Ok(required) |
| 584 | } |
| 585 | |
| 586 | /// The startup line that states the authorize rule this daemon enforces. |
| 587 | pub(crate) fn authorize_mac_line(required: bool) -> &'static str { |
| 588 | if required { |
| 589 | "Authorize MAC: on (aien compose authorize requires the approval desk key MAC)" |
| 590 | } else { |
| 591 | "Authorize MAC: OFF, DEV OPT-OUT (AIEN_COMPOSE_AUTHORIZE_REQUIRES_DESK=0 in a dev run): \ |
| 592 | authorize is authenticated by the OS user only; not valid for release qualification" |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | /// Both budgets from the environment. Refuses the retired single-budget |
| 597 | /// setting (a stale `AIEN_COMPOSE_BUDGET_MS` must not be silently ignored). |
| 598 | pub fn compose_budgets_from_env() -> Result<ComposeBudgets, String> { |
| 599 | if std::env::var_os(COMPOSE_BUDGET_ENV_RETIRED).is_some() { |
| 600 | return Err(format!( |
| 601 | "{COMPOSE_BUDGET_ENV_RETIRED} is retired; set {COMPOSE_EDIT_BUDGET_ENV} and {COMPOSE_DOC_BUDGET_ENV}" |
| 602 | )); |
| 603 | } |
| 604 | Ok(ComposeBudgets { |
| 605 | edit: parse_compose_budget( |
| 606 | COMPOSE_EDIT_BUDGET_ENV, |
| 607 | COMPOSE_SKILL_BUDGET, |
| 608 | env_opt(COMPOSE_EDIT_BUDGET_ENV)?.as_deref(), |
| 609 | )?, |
| 610 | doc: parse_compose_budget( |
| 611 | COMPOSE_DOC_BUDGET_ENV, |
| 612 | COMPOSE_DOC_BUDGET, |
| 613 | env_opt(COMPOSE_DOC_BUDGET_ENV)?.as_deref(), |
| 614 | )?, |
| 615 | }) |
| 616 | } |
| 617 | |
| 618 | /// The document token cap from the environment. |
| 619 | pub fn compose_doc_max_tokens_from_env() -> Result<usize, String> { |
| 620 | parse_compose_doc_max_tokens(env_opt(COMPOSE_DOC_MAX_TOKENS_ENV)?.as_deref()) |
| 621 | } |
| 622 | |
| 623 | /// Stable prefix of `wall_clock_reason`: `propose_task_checked` classes an |
| 624 | /// attempt as "timeout" by it, and the token-limit cut (`length_cut_refusal`) never has it. |
| 625 | const WALL_CLOCK_REASON_PREFIX: &str = "model proposal exceeded "; |
| 626 | |
| 627 | /// Reason text of a wall-clock timeout. |
| 628 | pub(crate) fn wall_clock_reason(limit_ms: u128) -> String { |
| 629 | format!("{WALL_CLOCK_REASON_PREFIX}{limit_ms} ms") |
| 630 | } |
| 631 | |
| 632 | /// Time one full attempt needs, from the v3 measurement: 173-token retry |
| 633 | /// prompt prefill (2 839 + 896 ms) + 47 decode steps x 166.6 ms + 60 ms |
| 634 | /// = 11 625 ms, rounded up (ACCEPTANCE-v3 Section 3b). Attempt k > 1 starts |
| 635 | /// only if at least this much budget is left. |
| 636 | const COMPOSE_ATTEMPT_BUDGET: std::time::Duration = std::time::Duration::from_millis(12_000); |
| 637 | /// Same rule for a full document. DIAGNOSTIC-LONG-1 (sovereign-core branch |
| 638 | /// 031756/oq3-long-diag) measured replies of 313..649 tokens finishing by |
| 639 | /// themselves in 28.6..61.9 s (~88 ms/token plus prefill), so a retry that |
| 640 | /// has to write a whole document needs about the shortest measured one: |
| 641 | /// 28.6 s, rounded up to 30 s. With the 120 s budget, a first attempt up to the |
| 642 | /// longest measured (61.9 s) leaves 58 s and still allows a retry; one that ran |
| 643 | /// to the token cap (1024 tokens, ~90 s) leaves ~30 s and may not. Capped at |
| 644 | /// half the budget so a small custom doc budget keeps the retry rule meaningful. |
| 645 | const COMPOSE_DOC_ATTEMPT_BUDGET: std::time::Duration = std::time::Duration::from_secs(30); |
| 646 | |
| 647 | /// The per-attempt budget for `kind` under wall budget `budget`. |
| 648 | fn compose_attempt_budget(kind: ProposalKind, budget: std::time::Duration) -> std::time::Duration { |
| 649 | match kind { |
| 650 | ProposalKind::Edit => COMPOSE_ATTEMPT_BUDGET, |
| 651 | ProposalKind::Document => COMPOSE_DOC_ATTEMPT_BUDGET.min(budget / 2), |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | /// Assistant-response prefix of the production RunComposeTask template: the |
| 656 | /// assistant turn starts with it and the model generates the path and the |
| 657 | /// content after it (ACCEPTANCE-v4 Section 2(1)). The reply the parser reads |
| 658 | /// is this prefix followed by the generated text. |
| 659 | /// |
| 660 | /// NEXT-PHASE-1 v5 engine cut: no trailing space. A separate space token after |
| 661 | /// the colon was measured harmful; the model's own tokenization puts the space |
| 662 | /// in front of the path. |
| 663 | pub const COMPOSE_ASSISTANT_PREFIX: &str = "filename:"; |
| 664 | |
| 665 | /// The compose assistant-response prefix for a model's chat template. Zephyr |
| 666 | /// and Llama 3 keep `COMPOSE_ASSISTANT_PREFIX` byte for byte. ChatML |
| 667 | /// (SmolLM2-Instruct) uses the same text: the proposal template asks for a |
| 668 | /// `filename: <relative path>` first line, and in SmolLM2's byte-level BPE |
| 669 | /// `filename:` ends on the colon token, so the path keeps its own leading |
| 670 | /// space token as in Llama 3. `proposal_prompt` is the same for every template. |
| 671 | pub fn compose_assistant_prefix(template: &aien_inference_abi::ChatTemplate) -> &'static str { |
| 672 | use aien_inference_abi::ChatTemplate; |
| 673 | match template { |
| 674 | ChatTemplate::Zephyr | ChatTemplate::Llama3 => COMPOSE_ASSISTANT_PREFIX, |
| 675 | // A plain model never reaches generation (chat render is refused first). |
| 676 | ChatTemplate::None => COMPOSE_ASSISTANT_PREFIX, |
| 677 | ChatTemplate::ChatMl { .. } |
| 678 | | ChatTemplate::ChatMlQwen3 |
| 679 | | ChatTemplate::ChatMlQwen3NoThink |
| 680 | | ChatTemplate::Qwen38 |
| 681 | | ChatTemplate::Qwen36 |
| 682 | | ChatTemplate::Qwen35 => "filename:", |
| 683 | } |
| 684 | } |
| 685 | |
| 686 | /// The logical name of the authorized workspace as the model sees it (sc#429). |
| 687 | /// |
| 688 | /// A constant: the model-visible prompt never carries the machine-specific |
| 689 | /// absolute path (host name, user name, job folder), so equal logical inputs |
| 690 | /// give equal prompt bytes and token ids on every machine. The real path stays |
| 691 | /// in the authorization, confinement, execution and evidence layers |
| 692 | /// (`RunComposeTask` canonicalizes the workspace, the task id hashes it, the |
| 693 | /// commit record stores it). |
| 694 | const WORKSPACE_LABEL: &str = "workspace"; |
| 695 | |
| 696 | /// The fixed proposal template of the production RunComposeTask path. The |
| 697 | /// workspace is named by `WORKSPACE_LABEL`, never by its path (sc#429). |
| 698 | pub fn proposal_prompt(goal: &str) -> String { |
| 699 | let workspace = WORKSPACE_LABEL; |
| 700 | format!( |
| 701 | "Goal: {goal}\nAuthorized workspace: {workspace}\n\ |
| 702 | Propose exactly one file change inside the workspace.\n\ |
| 703 | Answer in exactly this format and nothing else:\n\ |
| 704 | filename: <relative path>\n\ |
| 705 | <the complete new file content>" |
| 706 | ) |
| 707 | } |
| 708 | |
| 709 | /// Largest existing file whose content the edit-mode block carries |
| 710 | /// (NEXT-PHASE-1 v6 T5); a larger file gets no block. |
| 711 | const COMPOSE_EDIT_MAX_BYTES: u64 = 8192; |
| 712 | |
| 713 | /// Decide the task kind from the goal's DESTINATION only (issue #288): the |
| 714 | /// path the goal asks to create or change, found by |
| 715 | /// `crate::destination::named_destination`; paths it merely reads ("about |
| 716 | /// README.md") are never classified. The destination is then judged by the disk: |
| 717 | /// a small UTF-8 file inside the workspace is `Edit`; a missing path inside the |
| 718 | /// workspace is `New`; everything else is `Refused` with the reason: an |
| 719 | /// absolute, `~`, `..` or non-plain path, a symlink or parent resolving outside |
| 720 | /// the workspace, a directory, a file over `COMPOSE_EDIT_MAX_BYTES`, non-UTF-8 |
| 721 | /// or unreadable content, and an ambiguous destination (several candidates). |
| 722 | /// A goal naming no destination is `New` (the model names the file). |
| 723 | pub(crate) fn classify_target(goal: &str, ws: &Path) -> TargetClass { |
| 724 | classify_destination(goal, ws).0 |
| 725 | } |
| 726 | |
| 727 | /// `classify_target` plus the destination path it judged (None when the goal |
| 728 | /// names none). This is the single decision of a task: the prompt, the budget, |
| 729 | /// the merge target and the check of the reply's `filename:` all use it. |
| 730 | pub fn classify_destination(goal: &str, ws: &Path) -> (TargetClass, Option<String>) { |
| 731 | let (class, dest, _) = classify_with_inputs(goal, ws); |
| 732 | (class, dest) |
| 733 | } |
| 734 | |
| 735 | /// Directories of the workspace the goal points at: every "Y folder" phrase and |
| 736 | /// every directory name used as a modifier ("the three inbox files"). |
| 737 | fn goal_dirs(goal: &str, ws: &Path) -> Vec<String> { |
| 738 | const NOUNS: &[&str] = &["files", "documents", "docs", "notes", "texts"]; |
| 739 | let mut out = crate::destination::goal_folders(goal); |
| 740 | let ws_words: Vec<&str> = goal.split_whitespace().collect(); |
| 741 | for pair in ws_words.windows(2) { |
| 742 | let trim = |c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '-'; |
| 743 | let (w, next) = (pair[0].trim_matches(trim), pair[1].trim_matches(trim)); |
| 744 | if !w.is_empty() |
| 745 | && NOUNS.contains(&next.to_ascii_lowercase().as_str()) |
| 746 | && !out.iter().any(|o| o == w) |
| 747 | && ws.join(w).is_dir() |
| 748 | { |
| 749 | out.push(w.to_string()); |
| 750 | } |
| 751 | } |
| 752 | out |
| 753 | } |
| 754 | |
| 755 | /// Where a named input word lives in the workspace: the word itself, else the |
| 756 | /// same name inside a directory the goal points at. None when it does not exist. |
| 757 | fn locate_input(word: &str, ws: &Path, dirs: &[String]) -> Option<String> { |
| 758 | let exists = |p: &str| std::fs::symlink_metadata(ws.join(p)).is_ok(); |
| 759 | if exists(word) { |
| 760 | return Some(word.to_string()); |
| 761 | } |
| 762 | if word.contains('/') { |
| 763 | return None; |
| 764 | } |
| 765 | dirs.iter() |
| 766 | .map(|d| format!("{d}/{word}")) |
| 767 | .find(|p| exists(p)) |
| 768 | } |
| 769 | |
| 770 | /// `classify_destination` plus the other paths the goal names (inputs, as the |
| 771 | /// goal wrote them). A name that exists in the workspace and is not the named |
| 772 | /// destination is an input, never a write target (sc#383). |
| 773 | fn classify_with_inputs(goal: &str, ws: &Path) -> (TargetClass, Option<String>, Vec<String>) { |
| 774 | let Ok(ws) = std::fs::canonicalize(ws) else { |
| 775 | return (TargetClass::New, None, Vec::new()); |
| 776 | }; |
| 777 | let is_file = |w: &str| { |
| 778 | check_relative_path(w).is_ok() && std::fs::metadata(ws.join(w)).is_ok_and(|m| m.is_file()) |
| 779 | }; |
| 780 | let dirs = goal_dirs(goal, &ws); |
| 781 | let is_input = |w: &str| { |
| 782 | check_relative_path(w).is_ok() && locate_input(w, &ws, &dirs).is_some_and(|p| is_file(&p)) |
| 783 | }; |
| 784 | let n = match crate::destination::named_paths(goal, &is_file, &is_input) { |
| 785 | Ok(n) => n, |
| 786 | Err(e) => return (TargetClass::Refused(format!("{e}")), None, Vec::new()), |
| 787 | }; |
| 788 | let Some(w) = n.dest else { |
| 789 | return (TargetClass::New, None, n.inputs); |
| 790 | }; |
| 791 | let class = classify_named(&w, &ws); |
| 792 | (class, Some(w), n.inputs) |
| 793 | } |
| 794 | |
| 795 | /// Input files for the prompt (sc#382): the paths the goal reads, plus the |
| 796 | /// regular files directly inside a folder the goal reads from. All resolved |
| 797 | /// strictly inside the canonical workspace, UTF-8 only, sorted by name, bounded |
| 798 | /// by `COMPOSE_INPUTS_MAX_FILES` and `COMPOSE_INPUTS_MAX_BYTES`. Returns the |
| 799 | /// prompt block ("" when nothing is shown), what was shown and what was left |
| 800 | /// out. A named input that leaves the workspace is refused. Never writes. |
| 801 | fn gather_inputs( |
| 802 | goal: &str, |
| 803 | ws: &Path, |
| 804 | named: &[String], |
| 805 | dest: Option<&str>, |
| 806 | ) -> Result<(String, Vec<InputRef>, Vec<InputOmitted>), String> { |
| 807 | let none = (String::new(), Vec::new(), Vec::new()); |
| 808 | let Ok(ws) = std::fs::canonicalize(ws) else { |
| 809 | return Ok(none); |
| 810 | }; |
| 811 | let dirs = goal_dirs(goal, &ws); |
| 812 | let mut omitted: Vec<InputOmitted> = Vec::new(); |
| 813 | let mut cands: Vec<String> = Vec::new(); |
| 814 | let refuse = |w: &str, why: &str| format!("RunComposeTask: input {w} {why}; refusing"); |
| 815 | for w in named { |
| 816 | if check_relative_path(w).is_err() { |
| 817 | return Err(refuse( |
| 818 | w, |
| 819 | "is not a plain relative path inside the workspace", |
| 820 | )); |
| 821 | } |
| 822 | let Some(rel) = locate_input(w, &ws, &dirs) else { |
| 823 | continue; // does not exist: nothing to read, as before |
| 824 | }; |
| 825 | match std::fs::canonicalize(ws.join(&rel)) { |
| 826 | Ok(full) if full.starts_with(&ws) => { |
| 827 | if full.is_file() && Some(rel.as_str()) != dest && !cands.contains(&rel) { |
| 828 | cands.push(rel); |
| 829 | } |
| 830 | } |
| 831 | _ => return Err(refuse(w, "resolves outside the workspace")), |
| 832 | } |
| 833 | } |
| 834 | for d in crate::destination::input_folders(goal) { |
| 835 | let Ok(full) = std::fs::canonicalize(ws.join(&d)) else { |
| 836 | continue; |
| 837 | }; |
| 838 | if check_relative_path(&d).is_err() || !full.starts_with(&ws) || !full.is_dir() { |
| 839 | continue; |
| 840 | } |
| 841 | let Ok(rd) = std::fs::read_dir(&full) else { |
| 842 | continue; |
| 843 | }; |
| 844 | for e in rd.flatten() { |
| 845 | let rel = format!("{d}/{}", e.file_name().to_string_lossy()); |
| 846 | let ft = e.file_type(); |
| 847 | if ft.as_ref().is_ok_and(|t| t.is_file()) { |
| 848 | if Some(rel.as_str()) != dest && !cands.contains(&rel) { |
| 849 | cands.push(rel); |
| 850 | } |
| 851 | } else if ft.is_ok_and(|t| t.is_symlink()) { |
| 852 | omitted.push(InputOmitted { |
| 853 | name: rel, |
| 854 | reason: "symlink, not followed".into(), |
| 855 | }); |
| 856 | } |
| 857 | } |
| 858 | } |
| 859 | cands.sort(); |
| 860 | let mut included: Vec<InputRef> = Vec::new(); |
| 861 | let mut block = String::new(); |
| 862 | let mut used = 0usize; |
| 863 | for rel in cands { |
| 864 | let skip = |reason: String| InputOmitted { |
| 865 | name: rel.clone(), |
| 866 | reason, |
| 867 | }; |
| 868 | if included.len() >= COMPOSE_INPUTS_MAX_FILES { |
| 869 | omitted.push(skip(format!( |
| 870 | "over the {COMPOSE_INPUTS_MAX_FILES}-file input limit" |
| 871 | ))); |
| 872 | continue; |
| 873 | } |
| 874 | let Ok(meta) = std::fs::metadata(ws.join(&rel)) else { |
| 875 | omitted.push(skip("unreadable".into())); |
| 876 | continue; |
| 877 | }; |
| 878 | if meta.len() as usize > COMPOSE_INPUTS_MAX_BYTES - used { |
| 879 | omitted.push(skip(format!( |
| 880 | "{} bytes does not fit the {COMPOSE_INPUTS_MAX_BYTES}-byte input limit", |
| 881 | meta.len() |
| 882 | ))); |
| 883 | continue; |
| 884 | } |
| 885 | let Ok(bytes) = std::fs::read(ws.join(&rel)) else { |
| 886 | omitted.push(skip("unreadable".into())); |
| 887 | continue; |
| 888 | }; |
| 889 | let Ok(text) = String::from_utf8(bytes) else { |
| 890 | omitted.push(skip("not UTF-8 text".into())); |
| 891 | continue; |
| 892 | }; |
| 893 | if text.len() > COMPOSE_INPUTS_MAX_BYTES - used { |
| 894 | omitted.push(skip("does not fit the input byte limit".into())); |
| 895 | continue; |
| 896 | } |
| 897 | used += text.len(); |
| 898 | let nl = if text.ends_with('\n') { "" } else { "\n" }; |
| 899 | block.push_str(&format!("--- {rel} ---\n{text}{nl}--- end {rel} ---\n")); |
| 900 | included.push(InputRef { |
| 901 | sha256: hex(&Sha256::digest(text.as_bytes())), |
| 902 | bytes: text.len(), |
| 903 | name: rel, |
| 904 | }); |
| 905 | } |
| 906 | omitted.sort_by(|a, b| a.name.cmp(&b.name)); |
| 907 | if !block.is_empty() { |
| 908 | block = format!( |
| 909 | "\nInput files from the workspace (read only, material for the answer, not files to write):\n{block}" |
| 910 | ); |
| 911 | } |
| 912 | Ok((block, included, omitted)) |
| 913 | } |
| 914 | |
| 915 | fn classify_named(w: &str, ws: &Path) -> TargetClass { |
| 916 | let refuse = |why: &str| { |
| 917 | TargetClass::Refused(format!( |
| 918 | "destination {w} cannot be written safely ({why}); refusing" |
| 919 | )) |
| 920 | }; |
| 921 | if check_relative_path(w).is_err() { |
| 922 | return refuse("not a plain relative path inside the workspace"); |
| 923 | } |
| 924 | let joined = ws.join(w); |
| 925 | // symlink_metadata: a dangling or outward symlink still EXISTS. |
| 926 | let Ok(lmeta) = std::fs::symlink_metadata(&joined) else { |
| 927 | // Missing: a new document, if its nearest existing parent is a |
| 928 | // directory inside the workspace (no symlinked parent leaving it). |
| 929 | let mut anc = joined.parent(); |
| 930 | while let Some(a) = anc { |
| 931 | if std::fs::symlink_metadata(a).is_ok() { |
| 932 | break; |
| 933 | } |
| 934 | anc = a.parent(); |
| 935 | } |
| 936 | return match anc.map(std::fs::canonicalize) { |
| 937 | Some(Ok(p)) if p.starts_with(ws) && p.is_dir() => TargetClass::New, |
| 938 | Some(Ok(p)) if p.starts_with(ws) => refuse("a parent is not a directory"), |
| 939 | Some(Ok(_)) => refuse("a parent resolves outside the workspace"), |
| 940 | _ => refuse("unresolvable parent"), |
| 941 | }; |
| 942 | }; |
| 943 | let refuse = |why: &str| { |
| 944 | TargetClass::Refused(format!( |
| 945 | "destination {w} already exists but cannot be edited safely ({why}); refusing instead of treating it as a new document" |
| 946 | )) |
| 947 | }; |
| 948 | let full = match std::fs::canonicalize(&joined) { |
| 949 | Ok(f) => f, |
| 950 | Err(_) if lmeta.file_type().is_symlink() => return refuse("unresolvable symlink"), |
| 951 | Err(_) => return refuse("unresolvable path"), |
| 952 | }; |
| 953 | if !full.starts_with(ws) { |
| 954 | return refuse("resolves outside the workspace"); |
| 955 | } |
| 956 | let Ok(meta) = std::fs::metadata(&full) else { |
| 957 | return refuse("unreadable"); |
| 958 | }; |
| 959 | if meta.is_dir() { |
| 960 | return refuse("it is a directory"); |
| 961 | } |
| 962 | if !meta.is_file() { |
| 963 | return refuse("not a regular file"); |
| 964 | } |
| 965 | if meta.len() > COMPOSE_EDIT_MAX_BYTES { |
| 966 | return refuse(&format!( |
| 967 | "{} bytes is over the {COMPOSE_EDIT_MAX_BYTES}-byte edit limit", |
| 968 | meta.len() |
| 969 | )); |
| 970 | } |
| 971 | let Ok(bytes) = std::fs::read(&full) else { |
| 972 | return refuse("unreadable"); |
| 973 | }; |
| 974 | match String::from_utf8(bytes) { |
| 975 | Ok(content) => TargetClass::Edit(w.to_string(), content), |
| 976 | Err(_) => refuse("not UTF-8 text"), |
| 977 | } |
| 978 | } |
| 979 | |
| 980 | /// The additive new-document block, appended when the goal names a destination |
| 981 | /// that does not exist yet: the model is told which file to write and must |
| 982 | /// answer with that `filename:` line (issue #288). |
| 983 | pub fn new_document_block(path: &str) -> String { |
| 984 | format!("\nWrite the new file {path}. The filename line of your answer must be exactly: filename: {path}") |
| 985 | } |
| 986 | |
| 987 | /// The additive edit-mode block (NEXT-PHASE-1 v6 T5), appended to the fixed |
| 988 | /// proposal template only when the goal names an existing file. |
| 989 | fn edit_block(path: &str, content: &str) -> String { |
| 990 | let nl = if content.ends_with('\n') { "" } else { "\n" }; |
| 991 | format!( |
| 992 | "\nThe file {path} already exists. Its current content is:\n{content}{nl}\ |
| 993 | Write the complete new content of {path}: keep every existing line and make the requested change." |
| 994 | ) |
| 995 | } |
| 996 | |
| 997 | /// The prompt of the production RunComposeTask path: the fixed template, |
| 998 | /// plus the edit-mode block when the goal names an existing file of the |
| 999 | /// canonical workspace `ws` (NEXT-PHASE-1 v6). |
| 1000 | pub fn task_prompt(goal: &str, ws: &Path) -> String { |
| 1001 | task_prompt_and_target(goal, ws).0 |
| 1002 | } |
| 1003 | |
| 1004 | /// `task_prompt` plus the edit target it showed the model: the path and the |
| 1005 | /// exact content of the block, read once (NEXT-PHASE-1 v7 T5). The Skill |
| 1006 | /// merges an edit reply into this same content, so the bytes the model saw |
| 1007 | /// are the bytes the merge keeps. |
| 1008 | fn task_prompt_and_target(goal: &str, ws: &Path) -> (String, Option<(String, String)>) { |
| 1009 | let (prompt, target, _) = task_plan(goal, ws) |
| 1010 | .unwrap_or_else(|_| (proposal_prompt(goal), None, ProposalKind::Document)); |
| 1011 | (prompt, target) |
| 1012 | } |
| 1013 | |
| 1014 | /// Prompt, edit target and kind of a task, or the refusal when the goal names |
| 1015 | /// an existing file that no edit block can be built for. |
| 1016 | fn task_plan(goal: &str, ws: &Path) -> Result<TaskPrompt, String> { |
| 1017 | task_decision(goal, ws).map(|(plan, _)| plan) |
| 1018 | } |
| 1019 | |
| 1020 | /// `task_plan` plus the destination path the goal named (None when it names |
| 1021 | /// none). The one decision of a task: a reply whose `filename:` differs from |
| 1022 | /// the destination is refused by the Skill. |
| 1023 | pub fn task_decision(goal: &str, ws: &Path) -> Result<(TaskPrompt, Option<String>), String> { |
| 1024 | task_decision_with_inputs(goal, ws).map(|(plan, dest, _, _)| (plan, dest)) |
| 1025 | } |
| 1026 | |
| 1027 | /// A task decision with the inputs its prompt carries and the candidates left out. |
| 1028 | type TaskDecisionInputs = (TaskPrompt, Option<String>, Vec<InputRef>, Vec<InputOmitted>); |
| 1029 | |
| 1030 | /// `task_decision` plus the inputs its prompt carries and the candidates left |
| 1031 | /// out (sc#382). The prompt is the fixed template, the input block when the |
| 1032 | /// goal points at workspace files to read, then the edit or new-document block. |
| 1033 | fn task_decision_with_inputs(goal: &str, ws: &Path) -> Result<TaskDecisionInputs, String> { |
| 1034 | let mut prompt = proposal_prompt(goal); |
| 1035 | let (class, dest, named) = classify_with_inputs(goal, ws); |
| 1036 | let kind = class.kind(); |
| 1037 | if let TargetClass::Refused(why) = class { |
| 1038 | return Err(format!("RunComposeTask: {why}")); |
| 1039 | } |
| 1040 | let (block, included, omitted) = gather_inputs(goal, ws, &named, dest.as_deref())?; |
| 1041 | prompt.push_str(&block); |
| 1042 | match class { |
| 1043 | TargetClass::Refused(_) => unreachable!("refused above"), |
| 1044 | TargetClass::Edit(path, content) => { |
| 1045 | prompt.push_str(&edit_block(&path, &content)); |
| 1046 | Ok(( |
| 1047 | (prompt, Some((path, content)), kind), |
| 1048 | dest, |
| 1049 | included, |
| 1050 | omitted, |
| 1051 | )) |
| 1052 | } |
| 1053 | TargetClass::New => { |
| 1054 | if let Some(d) = &dest { |
| 1055 | prompt.push_str(&new_document_block(d)); |
| 1056 | } |
| 1057 | Ok(((prompt, None, kind), dest, included, omitted)) |
| 1058 | } |
| 1059 | } |
| 1060 | } |
| 1061 | |
| 1062 | /// Total bytes of input text a proposal prompt carries (sc#382). |
| 1063 | const COMPOSE_INPUTS_MAX_BYTES: usize = 16384; |
| 1064 | /// Most input files a proposal prompt carries (sc#382). |
| 1065 | const COMPOSE_INPUTS_MAX_FILES: usize = 16; |
| 1066 | |
| 1067 | /// Largest prior-lines x reply-lines table `merge_edit_reply` builds. |
| 1068 | const COMPOSE_EDIT_MERGE_MAX_CELLS: usize = 4 << 20; |
| 1069 | |
| 1070 | /// NEXT-PHASE-1 v7 T5: an edit-mode reply never removes an existing line. |
| 1071 | /// |
| 1072 | /// v6 T5 showed the model answering an edit goal with only the changed part |
| 1073 | /// (the heading it edits under plus the new line), which the v6 Skill wrote |
| 1074 | /// as the whole file. Here the reply's content is merged into `prior`, the |
| 1075 | /// exact content the model was shown: the reply lines that equal prior lines |
| 1076 | /// (longest common subsequence, trailing whitespace ignored) are anchors, |
| 1077 | /// every other reply line is inserted next to its anchor (after the anchor |
| 1078 | /// above it; before the first anchor when no anchor is above it), and every |
| 1079 | /// prior line is kept with its own bytes, in order. A whole-file reply that |
| 1080 | /// keeps every line therefore merges to itself. |
| 1081 | /// |
| 1082 | /// Limits: edit mode is additive. A line the reply leaves out or rewrites |
| 1083 | /// stays in the file (a rewrite appears as an added line next to the old |
| 1084 | /// one). Err when the reply shares no non-blank line with `prior` (no place |
| 1085 | /// for the change), when it changes nothing, or when the table would exceed |
| 1086 | /// `COMPOSE_EDIT_MERGE_MAX_CELLS`. The result ends with one newline. |
| 1087 | #[cfg(test)] |
| 1088 | fn merge_edit_reply(prior: &str, reply_content: &str) -> Result<String, String> { |
| 1089 | merge_edit_reply_placed(prior, reply_content, EditPlacement::NextToAnchor) |
| 1090 | } |
| 1091 | |
| 1092 | /// Where the reply lines that are not anchors go (sc#394). |
| 1093 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 1094 | enum EditPlacement { |
| 1095 | /// Next to the anchor above (before the first anchor when none is above). |
| 1096 | NextToAnchor, |
| 1097 | /// After the last non-blank prior line, in reply order. |
| 1098 | AtEnd, |
| 1099 | } |
| 1100 | |
| 1101 | impl EditPlacement { |
| 1102 | /// `AtEnd` when the goal contains the word `append` as a whole word, |
| 1103 | /// case-insensitive (split on every non-alphanumeric character, so |
| 1104 | /// `appendix` and `appended` do not match); otherwise `NextToAnchor`. |
| 1105 | fn for_goal(goal: &str) -> Self { |
| 1106 | let append = goal |
| 1107 | .split(|c: char| !c.is_ascii_alphanumeric()) |
| 1108 | .any(|w| w.eq_ignore_ascii_case("append")); |
| 1109 | if append { |
| 1110 | EditPlacement::AtEnd |
| 1111 | } else { |
| 1112 | EditPlacement::NextToAnchor |
| 1113 | } |
| 1114 | } |
| 1115 | } |
| 1116 | |
| 1117 | /// `merge_edit_reply` with the placement of the new lines chosen by the |
| 1118 | /// caller. Kept prior lines, the shared-line requirement, the cell limit and |
| 1119 | /// the single final newline are the same for both placements. |
| 1120 | fn merge_edit_reply_placed( |
| 1121 | prior: &str, |
| 1122 | reply_content: &str, |
| 1123 | placement: EditPlacement, |
| 1124 | ) -> Result<String, String> { |
| 1125 | let mut p: Vec<&str> = prior.split('\n').collect(); |
| 1126 | if prior.ends_with('\n') || prior.is_empty() { |
| 1127 | p.pop(); |
| 1128 | } |
| 1129 | let r: Vec<&str> = reply_content.lines().collect(); |
| 1130 | let (n, m) = (p.len(), r.len()); |
| 1131 | if (n + 1).saturating_mul(m + 1) > COMPOSE_EDIT_MERGE_MAX_CELLS { |
| 1132 | return Err(format!( |
| 1133 | "edit reply too large to merge ({n} file lines x {m} reply lines)" |
| 1134 | )); |
| 1135 | } |
| 1136 | let eq = |i: usize, j: usize| p[i].trim_end() == r[j].trim_end(); |
| 1137 | // l[i][j] = LCS length of p[i..] and r[j..]. |
| 1138 | let w = m + 1; |
| 1139 | let mut l = vec![0u32; (n + 1) * w]; |
| 1140 | for i in (0..n).rev() { |
| 1141 | for j in (0..m).rev() { |
| 1142 | l[i * w + j] = if eq(i, j) { |
| 1143 | l[(i + 1) * w + j + 1] + 1 |
| 1144 | } else { |
| 1145 | l[(i + 1) * w + j].max(l[i * w + j + 1]) |
| 1146 | }; |
| 1147 | } |
| 1148 | } |
| 1149 | let mut anchors: Vec<(usize, usize)> = Vec::new(); |
| 1150 | let (mut i, mut j) = (0, 0); |
| 1151 | while i < n && j < m { |
| 1152 | if eq(i, j) && l[i * w + j] == l[(i + 1) * w + j + 1] + 1 { |
| 1153 | anchors.push((i, j)); |
| 1154 | i += 1; |
| 1155 | j += 1; |
| 1156 | } else if l[(i + 1) * w + j] >= l[i * w + j + 1] { |
| 1157 | i += 1; |
| 1158 | } else { |
| 1159 | j += 1; |
| 1160 | } |
| 1161 | } |
| 1162 | if !anchors.iter().any(|&(i, _)| !p[i].trim().is_empty()) { |
| 1163 | return Err( |
| 1164 | "edit reply shares no line with the file: copy the existing line the change goes under, then the new lines" |
| 1165 | .into(), |
| 1166 | ); |
| 1167 | } |
| 1168 | let mut out: Vec<&str> = Vec::with_capacity(n + m); |
| 1169 | if placement == EditPlacement::AtEnd { |
| 1170 | // Every prior line stays in place; the non-anchor reply lines follow |
| 1171 | // the last non-blank prior line, in reply order. |
| 1172 | let mut is_anchor = vec![false; m]; |
| 1173 | for &(_, aj) in &anchors { |
| 1174 | is_anchor[aj] = true; |
| 1175 | } |
| 1176 | let last = p |
| 1177 | .iter() |
| 1178 | .rposition(|l| !l.trim().is_empty()) |
| 1179 | .map_or(0, |i| i + 1); |
| 1180 | out.extend(&p[..last]); |
| 1181 | out.extend( |
| 1182 | r.iter() |
| 1183 | .zip(&is_anchor) |
| 1184 | .filter(|(_, a)| !**a) |
| 1185 | .map(|(l, _)| *l), |
| 1186 | ); |
| 1187 | out.extend(&p[last..]); |
| 1188 | } else { |
| 1189 | let (mut pi, mut rj) = (0, 0); |
| 1190 | for (k, &(ai, aj)) in anchors.iter().chain(std::iter::once(&(n, m))).enumerate() { |
| 1191 | if k == 0 { |
| 1192 | // No anchor above: new lines hug the first anchor from above. |
| 1193 | out.extend(&p[pi..ai]); |
| 1194 | out.extend(&r[rj..aj]); |
| 1195 | } else { |
| 1196 | // New lines hug the anchor above them. |
| 1197 | out.extend(&r[rj..aj]); |
| 1198 | out.extend(&p[pi..ai]); |
| 1199 | } |
| 1200 | if ai < n { |
| 1201 | out.push(p[ai]); |
| 1202 | } |
| 1203 | (pi, rj) = (ai + 1, aj + 1); |
| 1204 | } |
| 1205 | } |
| 1206 | let mut merged = out.join("\n"); |
| 1207 | merged.push('\n'); |
| 1208 | let mut kept = p.join("\n"); |
| 1209 | kept.push('\n'); |
| 1210 | if merged == kept { |
| 1211 | return Err("edit reply changes nothing in the file".into()); |
| 1212 | } |
| 1213 | Ok(merged) |
| 1214 | } |
| 1215 | |
| 1216 | /// The proposal text the Skill hands to AEGIS for one parsed reply. In edit |
| 1217 | /// mode (`edit` = the target path and the content shown to the model) a reply |
| 1218 | /// naming that path is merged into the content by `merge_edit_reply` and |
| 1219 | /// returned in the canonical `filename: <path>` form; any other reply is |
| 1220 | /// returned unchanged (the v5 whole-file proposal). |
| 1221 | pub fn edit_proposal(reply: &str, edit: Option<(&str, &str)>) -> Result<String, String> { |
| 1222 | edit_proposal_placed(reply, edit, EditPlacement::NextToAnchor) |
| 1223 | } |
| 1224 | |
| 1225 | /// `edit_proposal` with the placement of the goal (`EditPlacement::for_goal`). |
| 1226 | fn edit_proposal_placed( |
| 1227 | reply: &str, |
| 1228 | edit: Option<(&str, &str)>, |
| 1229 | placement: EditPlacement, |
| 1230 | ) -> Result<String, String> { |
| 1231 | let p = check_file_proposal(reply)?; |
| 1232 | let Some((path, prior)) = edit.filter(|(path, _)| *path == p.path) else { |
| 1233 | return Ok(reply.to_string()); |
| 1234 | }; |
| 1235 | let merged = merge_edit_reply_placed(prior, &p.content, placement)?; |
| 1236 | let text = format!("filename: {path}\n{merged}"); |
| 1237 | match check_file_proposal(&text) { |
| 1238 | Ok(q) if q.path == path && q.content == merged => Ok(text), |
| 1239 | _ => Err(format!( |
| 1240 | "the merged content of {path} does not survive the proposal format" |
| 1241 | )), |
| 1242 | } |
| 1243 | } |
| 1244 | |
| 1245 | /// Why a reply that stopped at the token limit is never a proposal |
| 1246 | /// (NEXT-PHASE-1 v6 N2): its content may be cut anywhere. |
| 1247 | fn length_cut_refusal(g: &Generation) -> Option<String> { |
| 1248 | (g.finish_reason.as_deref() == Some("max_tokens")).then(|| { |
| 1249 | format!( |
| 1250 | "reply cut at the token limit after {} tokens (finish_reason max_tokens); a cut reply is never a proposal", |
| 1251 | g.tokens |
| 1252 | ) |
| 1253 | }) |
| 1254 | } |
| 1255 | |
| 1256 | /// The one correction line added to attempt k > 1. |
| 1257 | pub fn retry_prompt(base: &str, reason: &str) -> String { |
| 1258 | format!( |
| 1259 | "{base}\nYour previous answer was refused ({reason}). \ |
| 1260 | Start your answer with the line \"filename: <relative path>\"." |
| 1261 | ) |
| 1262 | } |
| 1263 | |
| 1264 | /// Largest refused reply quoted back by [`corrective_retry_prompt`]; a longer |
| 1265 | /// one is cut at a character boundary and marked. A reply is at most the |
| 1266 | /// document token cap (1024 tokens in the v5 tasks), far under this. |
| 1267 | const COMPOSE_FEEDBACK_MAX_BYTES: usize = 8192; |
| 1268 | |
| 1269 | /// The markers around the quoted refused reply. |
| 1270 | const REFUSED_REPLY_BEGIN: &str = "<<<REFUSED ANSWER"; |
| 1271 | const REFUSED_REPLY_END: &str = "REFUSED ANSWER>>>"; |
| 1272 | |
| 1273 | /// sc#384 v8 (Drake 2026-10-12, Option 3): the retry prompt that shows the |
| 1274 | /// model its own refused reply next to the exact validation failure. The |
| 1275 | /// goal, the requirements, the budgets and the attempt limit are untouched; |
| 1276 | /// the quoted reply is prompt text only and never reaches the write path |
| 1277 | /// (only a reply that passes every check becomes a proposal). Without a reply |
| 1278 | /// (the previous attempt timed out or failed) it is [`retry_prompt`] byte for |
| 1279 | /// byte, the v7 prompt. |
| 1280 | pub fn corrective_retry_prompt(base: &str, reason: &str, refused: Option<&str>) -> String { |
| 1281 | let Some(text) = refused else { |
| 1282 | return retry_prompt(base, reason); |
| 1283 | }; |
| 1284 | let mut shown = text.replace(REFUSED_REPLY_END, "[marker removed]"); |
| 1285 | let mut cut = ""; |
| 1286 | if shown.len() > COMPOSE_FEEDBACK_MAX_BYTES { |
| 1287 | let mut end = COMPOSE_FEEDBACK_MAX_BYTES; |
| 1288 | while !shown.is_char_boundary(end) { |
| 1289 | end -= 1; |
| 1290 | } |
| 1291 | shown.truncate(end); |
| 1292 | cut = "\n[the rest of the refused answer is not shown]"; |
| 1293 | } |
| 1294 | let nl = if shown.ends_with('\n') { "" } else { "\n" }; |
| 1295 | format!( |
| 1296 | "{base}\nYour previous answer was refused before anything was written ({reason}). \ |
| 1297 | Here it is, between the markers, so you can see what to fix:\n\ |
| 1298 | {REFUSED_REPLY_BEGIN}\n{shown}{nl}{REFUSED_REPLY_END}{cut}\n\ |
| 1299 | Write a new complete answer that meets every requirement of the goal. \ |
| 1300 | Start your answer with the line \"filename: <relative path>\"." |
| 1301 | ) |
| 1302 | } |
| 1303 | |
| 1304 | fn new_attempt(k: u32) -> ProposalAttempt { |
| 1305 | ProposalAttempt { |
| 1306 | attempt: k, |
| 1307 | ms: 0, |
| 1308 | tokens: 0, |
| 1309 | outcome: String::new(), |
| 1310 | reason: None, |
| 1311 | text_sha256: None, |
| 1312 | text: None, |
| 1313 | aegis: None, |
| 1314 | finish_reason: None, |
| 1315 | token_ids: None, |
| 1316 | prompt_tokens: None, |
| 1317 | prompt_ids_sha256: None, |
| 1318 | decoding: None, |
| 1319 | ops: None, |
| 1320 | unmet_requirements: Vec::new(), |
| 1321 | shown_refused_text_sha256: None, |
| 1322 | } |
| 1323 | } |
| 1324 | |
| 1325 | /// The approved-proposal path of the Skill: exactly one attempt that returns |
| 1326 | /// `text` unchanged, through the same requirement check as a model reply (the |
| 1327 | /// bytes a human approved are still refused, before any write, when the goal |
| 1328 | /// states a requirement they do not meet). |
| 1329 | pub(crate) fn propose_approved( |
| 1330 | text: &str, |
| 1331 | prompt: &str, |
| 1332 | reqs: &[crate::requirements::Requirement], |
| 1333 | budget: std::time::Duration, |
| 1334 | attempt_budget: std::time::Duration, |
| 1335 | ) -> SkillOutput { |
| 1336 | let text = text.to_string(); |
| 1337 | let one = move |_: &str, _: std::time::Duration| { |
| 1338 | Ok(Generation { |
| 1339 | text: text.clone(), |
| 1340 | finish_reason: Some("approved".into()), |
| 1341 | ..Default::default() |
| 1342 | }) |
| 1343 | }; |
| 1344 | propose_task_checked(&one, prompt, None, reqs, budget, attempt_budget, 1) |
| 1345 | } |
| 1346 | |
| 1347 | #[cfg(test)] |
| 1348 | pub(crate) const TEST_DROP_RECORD_MARKER: &str = "drop-the-record-marker"; |
| 1349 | |
| 1350 | /// Why a task is refused when its requirement record is gone (issue #289). |
| 1351 | pub(crate) const MISSING_RECORD_REASON: &str = |
| 1352 | "requirement record missing for this task: refused, an absent record is never treated as no requirements"; |
| 1353 | |
| 1354 | /// A task refused before the model ran: one attempt records the reason. |
| 1355 | pub(crate) fn refused_without_model(why: String) -> SkillOutput { |
| 1356 | let mut a = new_attempt(1); |
| 1357 | a.outcome = "refused".into(); |
| 1358 | a.reason = Some(why.clone()); |
| 1359 | (Err(why), vec![a]) |
| 1360 | } |
| 1361 | |
| 1362 | /// The AEGIS verify decision for one task: the result names exactly the |
| 1363 | /// proposal the Skill recorded, that proposal parses as one file change, and |
| 1364 | /// the COMPLETE content (the bytes that would be saved) meets every requirement |
| 1365 | /// of the goal. A missing requirement record, or any uncertain span, refuses. |
| 1366 | pub(crate) fn verify_task_result( |
| 1367 | ex: Option<&crate::requirements::Extraction>, |
| 1368 | proposal: Option<&SkillOutput>, |
| 1369 | result: u64, |
| 1370 | ) -> bool { |
| 1371 | let Some(ex) = ex else { return false }; |
| 1372 | if ex.refusal().is_some() { |
| 1373 | return false; |
| 1374 | } |
| 1375 | let Some((Ok(t), _)) = proposal else { |
| 1376 | return false; |
| 1377 | }; |
| 1378 | proposal_handle(t) == result |
| 1379 | && parse_file_proposal(t).is_some_and(|p| { |
| 1380 | crate::requirements::refusal_reason(&ex.requirements, &p.content).is_none() |
| 1381 | }) |
| 1382 | } |
| 1383 | |
| 1384 | /// Runs up to `max_attempts` proposals within `budget`: attempt 1 always |
| 1385 | /// starts; attempt k > 1 starts only if the remaining budget is at least |
| 1386 | /// `attempt_budget` (the measured cost of one full attempt), and gets the |
| 1387 | /// remaining budget as its limit. A reply that passes `check_file_proposal` |
| 1388 | /// becomes `edit_proposal(reply, edit)`, so in edit mode the proposal is the |
| 1389 | /// merged file; each attempt still records the model's own reply text. |
| 1390 | /// |
| 1391 | /// Requirement validation: a parsed reply |
| 1392 | /// whose COMPLETE content (the merged file in edit mode, i.e. the bytes that |
| 1393 | /// would be saved) fails any of `reqs` is refused like a parse failure, the |
| 1394 | /// unmet requirement(s) are recorded on the attempt, and the next attempt |
| 1395 | /// gets them as its retry reason. `budget` is one deadline for the whole |
| 1396 | /// task, started when this function starts and never reset per attempt. |
| 1397 | /// Exhaustion returns Err: no proposal exists, so nothing is approved, |
| 1398 | /// committed or written. |
| 1399 | fn propose_task_checked( |
| 1400 | proposer: &(dyn Fn(&str, std::time::Duration) -> Result<Generation, String> + Send + Sync), |
| 1401 | base: &str, |
| 1402 | edit: Option<(&str, &str)>, |
| 1403 | reqs: &[crate::requirements::Requirement], |
| 1404 | budget: std::time::Duration, |
| 1405 | attempt_budget: std::time::Duration, |
| 1406 | max_attempts: u32, |
| 1407 | ) -> (Result<String, String>, Vec<ProposalAttempt>) { |
| 1408 | propose_task_placed( |
| 1409 | proposer, |
| 1410 | base, |
| 1411 | edit, |
| 1412 | EditPlacement::NextToAnchor, |
| 1413 | reqs, |
| 1414 | budget, |
| 1415 | attempt_budget, |
| 1416 | max_attempts, |
| 1417 | ) |
| 1418 | } |
| 1419 | |
| 1420 | /// `propose_task_checked` with the placement of the goal's new lines. |
| 1421 | #[allow(clippy::too_many_arguments)] |
| 1422 | fn propose_task_placed( |
| 1423 | proposer: &(dyn Fn(&str, std::time::Duration) -> Result<Generation, String> + Send + Sync), |
| 1424 | base: &str, |
| 1425 | edit: Option<(&str, &str)>, |
| 1426 | placement: EditPlacement, |
| 1427 | reqs: &[crate::requirements::Requirement], |
| 1428 | budget: std::time::Duration, |
| 1429 | attempt_budget: std::time::Duration, |
| 1430 | max_attempts: u32, |
| 1431 | ) -> (Result<String, String>, Vec<ProposalAttempt>) { |
| 1432 | let start = std::time::Instant::now(); |
| 1433 | let mut attempts: Vec<ProposalAttempt> = Vec::new(); |
| 1434 | // An edit only adds lines (`merge_edit_reply` keeps every prior line), so a |
| 1435 | // prior file that already breaks a MaxLines can never satisfy it: refuse |
| 1436 | // now with a recorded reason instead of spending attempts. |
| 1437 | if let Some((path, prior)) = edit { |
| 1438 | let over: Vec<String> = reqs |
| 1439 | .iter() |
| 1440 | .filter(|r| matches!(r, crate::requirements::Requirement::MaxLines(_))) |
| 1441 | .filter_map(|r| r.check(prior)) |
| 1442 | .collect(); |
| 1443 | if !over.is_empty() { |
| 1444 | let why = format!( |
| 1445 | "unmet requirement: the existing {path} already breaks it ({}) and an edit only adds lines", |
| 1446 | over.join("; ") |
| 1447 | ); |
| 1448 | let mut a = new_attempt(1); |
| 1449 | a.outcome = "refused".into(); |
| 1450 | a.reason = Some(why.clone()); |
| 1451 | a.unmet_requirements = over; |
| 1452 | return (Err(why), vec![a]); |
| 1453 | } |
| 1454 | } |
| 1455 | let mut last_reason = "no attempt made".to_string(); |
| 1456 | // The previous attempt's refused reply (sc#384 v8), quoted in the next |
| 1457 | // prompt; None after a timeout or error, which leave no reply. |
| 1458 | let mut last_refused: Option<String> = None; |
| 1459 | let need_ms = (attempt_budget.as_millis() as u64).max(1); |
| 1460 | for k in 1..=max_attempts { |
| 1461 | let remaining = budget.saturating_sub(start.elapsed()); |
| 1462 | if k > 1 && (remaining.as_millis() as u64) < need_ms { |
| 1463 | last_reason = format!( |
| 1464 | "{last_reason}; no attempt {k}: {} ms left < {need_ms} ms per-attempt budget", |
| 1465 | remaining.as_millis() |
| 1466 | ); |
| 1467 | break; |
| 1468 | } |
| 1469 | let prompt = if k == 1 { |
| 1470 | base.to_string() |
| 1471 | } else { |
| 1472 | corrective_retry_prompt(base, &last_reason, last_refused.as_deref()) |
| 1473 | }; |
| 1474 | let shown = last_refused |
| 1475 | .take() |
| 1476 | .filter(|_| k > 1) |
| 1477 | .map(|t| hex(&Sha256::digest(t.as_bytes()))); |
| 1478 | let t0 = std::time::Instant::now(); |
| 1479 | let out = proposer(&prompt, remaining); |
| 1480 | let last_ms = t0.elapsed().as_millis() as u64; |
| 1481 | let mut a = new_attempt(k); |
| 1482 | a.shown_refused_text_sha256 = shown; |
| 1483 | a.ms = last_ms; |
| 1484 | match out { |
| 1485 | Ok(g) => { |
| 1486 | a.tokens = g.tokens; |
| 1487 | a.finish_reason = g.finish_reason.clone(); |
| 1488 | a.token_ids = g.token_ids.clone(); |
| 1489 | a.prompt_tokens = g.prompt_tokens; |
| 1490 | a.prompt_ids_sha256 = g.prompt_ids_sha256.clone(); |
| 1491 | a.decoding = g.decoding.clone(); |
| 1492 | a.ops = g.ops.clone(); |
| 1493 | a.text_sha256 = Some(hex(&Sha256::digest(g.text.as_bytes()))); |
| 1494 | a.text = Some(g.text.clone()); |
| 1495 | // NEXT-PHASE-1 v6 N2: a length-cut reply is refused before parsing. |
| 1496 | let checked = match length_cut_refusal(&g) { |
| 1497 | Some(why) => Err(why), |
| 1498 | None => edit_proposal_placed(&g.text, edit, placement).and_then(|p| { |
| 1499 | // The complete content that would be saved. |
| 1500 | let content = check_file_proposal(&p)?.content; |
| 1501 | match crate::requirements::refusal_reason(reqs, &content) { |
| 1502 | Some(why) => { |
| 1503 | a.unmet_requirements = crate::requirements::unmet(reqs, &content); |
| 1504 | Err(why) |
| 1505 | } |
| 1506 | None => Ok(p), |
| 1507 | } |
| 1508 | }), |
| 1509 | }; |
| 1510 | match checked { |
| 1511 | Ok(proposal) => { |
| 1512 | a.outcome = "parsed".into(); |
| 1513 | attempts.push(a); |
| 1514 | return (Ok(proposal), attempts); |
| 1515 | } |
| 1516 | Err(e) => { |
| 1517 | a.outcome = "refused".into(); |
| 1518 | a.reason = Some(e.clone()); |
| 1519 | last_reason = e; |
| 1520 | last_refused = Some(g.text.clone()); |
| 1521 | } |
| 1522 | } |
| 1523 | } |
| 1524 | Err(e) => { |
| 1525 | a.outcome = if e.starts_with(WALL_CLOCK_REASON_PREFIX) { |
| 1526 | "timeout" |
| 1527 | } else { |
| 1528 | "error" |
| 1529 | } |
| 1530 | .into(); |
| 1531 | a.reason = Some(e.clone()); |
| 1532 | last_reason = e; |
| 1533 | } |
| 1534 | } |
| 1535 | attempts.push(a); |
| 1536 | } |
| 1537 | (Err(last_reason), attempts) |
| 1538 | } |
| 1539 | |
| 1540 | pub(crate) fn record_view( |
| 1541 | compose: &mut Compose, |
| 1542 | r: &aien_omega_compose::Record, |
| 1543 | ) -> ComposeRecordView { |
| 1544 | let host = r.subject == aien_omega_compose::SUBJECT_HOST; |
| 1545 | let note = if !host { |
| 1546 | None |
| 1547 | } else if r.tag == aien_omega_compose::ffi::RXC_HOST_TAG_REPAIR_TAIL { |
| 1548 | Some("repair_tail".to_string()) |
| 1549 | } else { |
| 1550 | NoteKind::from_tag(r.tag).map(|k| k.name().to_string()) |
| 1551 | }; |
| 1552 | let text = if host && NoteKind::from_tag(r.tag).is_some() { |
| 1553 | compose |
| 1554 | .payload(r.id) |
| 1555 | .ok() |
| 1556 | .and_then(|p| note_bytes(&p)) |
| 1557 | .map(|b| String::from_utf8_lossy(&b).into_owned()) |
| 1558 | } else { |
| 1559 | None |
| 1560 | }; |
| 1561 | ComposeRecordView { |
| 1562 | id: r.id, |
| 1563 | cls: r.cls, |
| 1564 | kind: r.kind, |
| 1565 | subject: r.subject, |
| 1566 | tag: r.tag, |
| 1567 | links: r.links.to_vec(), |
| 1568 | digest: hex(&r.digest), |
| 1569 | verified: r.verified == 1, |
| 1570 | note, |
| 1571 | text, |
| 1572 | } |
| 1573 | } |
| 1574 | |
| 1575 | const CLOSED_REFUSAL: &str = "compose home closed: the daemon is shutting down"; |
| 1576 | |
| 1577 | pub(crate) struct ComposeHome { |
| 1578 | pub(crate) compose: Compose, |
| 1579 | /// The ALLEN identity this home resolved (`None` = not engaged). |
| 1580 | pub(crate) allen: Option<aien_allen::Resolved>, |
| 1581 | /// ALLEN scoped memory (arch#159), opened with the identity above. |
| 1582 | pub(crate) memory: crate::allen_memory::MemoryState, |
| 1583 | pub(crate) machine_id: String, |
| 1584 | prompts: Arc<parking_lot::Mutex<HashMap<u64, TaskEntry>>>, |
| 1585 | /// Proposer hook: task -> approved proposal text (crate::approved). |
| 1586 | approved: Arc<parking_lot::Mutex<HashMap<u64, String>>>, |
| 1587 | /// What the model Skill returned per task: the text, or why it gave |
| 1588 | /// none, and every attempt it made. |
| 1589 | proposals: Arc<parking_lot::Mutex<HashMap<u64, SkillOutput>>>, |
| 1590 | /// The Cortex record mark (ACCEPTANCE-v3 2.1): where it lives, the raw |
| 1591 | /// machine id it binds, and the last mark written (or verified). |
| 1592 | mark_path: PathBuf, |
| 1593 | machine_raw: [u8; 32], |
| 1594 | mark: Option<Mark>, |
| 1595 | /// seq of the last mark this home knows of (0 = none yet). |
| 1596 | mark_seq: u64, |
| 1597 | /// Wall budgets in force; every run sets omega's wait from its own. |
| 1598 | budgets: ComposeBudgets, |
| 1599 | } |
| 1600 | |
| 1601 | impl ComposeHome { |
| 1602 | /// Write a new record mark when the journal holds more records than the |
| 1603 | /// last mark (ACCEPTANCE-v3 2.1). Called only after appends returned, |
| 1604 | /// so the mark never runs ahead of the journal. Returns the mark written. |
| 1605 | pub(crate) fn advance_mark(&mut self) -> Result<Option<Mark>, String> { |
| 1606 | let n = self |
| 1607 | .compose |
| 1608 | .info() |
| 1609 | .map_err(|e| format!("record mark: info: {e}"))? |
| 1610 | .records; |
| 1611 | // A version 1 mark (no chain) is rewritten even at the same count. |
| 1612 | if self |
| 1613 | .mark |
| 1614 | .as_ref() |
| 1615 | .is_some_and(|m| m.records > n || (m.records == n && m.chain.is_some())) |
| 1616 | { |
| 1617 | return Ok(None); |
| 1618 | } |
| 1619 | // Extend the verified chain of the last mark; without one, hash the |
| 1620 | // whole journal as this home opened it. |
| 1621 | let (from, start) = match &self.mark { |
| 1622 | Some(Mark { |
| 1623 | records, |
| 1624 | chain: Some(c), |
| 1625 | .. |
| 1626 | }) => (*records, *c), |
| 1627 | _ => (0, [0u8; 32]), |
| 1628 | }; |
| 1629 | let chain = record_chain(&mut self.compose, start, from + 1, n) |
| 1630 | .map_err(|e| format!("record mark: {e}"))?; |
| 1631 | let digest = if n == 0 { |
| 1632 | [0u8; 32] |
| 1633 | } else { |
| 1634 | self.compose |
| 1635 | .record(n) |
| 1636 | .map_err(|e| format!("record mark: record {n}: {e}"))? |
| 1637 | .digest |
| 1638 | }; |
| 1639 | let m = Mark { |
| 1640 | machine_id: self.machine_raw, |
| 1641 | seq: self.mark_seq + 1, |
| 1642 | records: n, |
| 1643 | digest, |
| 1644 | chain: Some(chain), |
| 1645 | }; |
| 1646 | cortex_mark::write(&self.mark_path, &m)?; |
| 1647 | self.mark_seq = m.seq; |
| 1648 | self.mark = Some(m.clone()); |
| 1649 | Ok(Some(m)) |
| 1650 | } |
| 1651 | } |
| 1652 | |
| 1653 | type SkillOutput = (Result<String, String>, Vec<ProposalAttempt>); |
| 1654 | /// The prompt of one task, its edit target and its kind (`task_plan`). |
| 1655 | pub type TaskPrompt = (String, Option<(String, String)>, ProposalKind); |
| 1656 | /// A task's plan plus the requirements its goal states (`requirements::extract`). |
| 1657 | /// Prompt plan, requirements, and the destination the goal named (one decision). |
| 1658 | type TaskEntry = ( |
| 1659 | TaskPrompt, |
| 1660 | crate::requirements::Extraction, |
| 1661 | (Option<String>, PathBuf), |
| 1662 | EditPlacement, |
| 1663 | ); |
| 1664 | |
| 1665 | /// Owns the composition home of this process. |
| 1666 | pub struct ComposeBridge { |
| 1667 | dir: PathBuf, |
| 1668 | proposer: ComposeProposer, |
| 1669 | /// Proposer for full-document tasks (own token cap); `None` = `proposer`. |
| 1670 | doc_proposer: Option<ComposeProposer>, |
| 1671 | proposer_label: String, |
| 1672 | home: std::sync::Mutex<Option<ComposeHome>>, |
| 1673 | /// Set when the start-up reconcile failed or was refused (ACCEPTANCE-v3 |
| 1674 | /// 2.5): effect commands refuse until an operator reconcile succeeds. |
| 1675 | reconcile_failed: std::sync::Mutex<Option<String>>, |
| 1676 | /// Set by `close`: the daemon is shutting down, the home is closed and |
| 1677 | /// must not be reopened lazily by a connection task that outlives `run` |
| 1678 | /// (sovereign-core #306). |
| 1679 | closed: std::sync::atomic::AtomicBool, |
| 1680 | /// sovereign-core #297, #328: when true, `ComposeAuthorize` needs the |
| 1681 | /// approval desk's MAC. Default true (Drake decision b, 2026-10-08); |
| 1682 | /// false is the legacy OS-user-only authorize, only by explicit choice. |
| 1683 | authorize_requires_desk: bool, |
| 1684 | /// The loaded model files and the daemon start, set by the daemon after |
| 1685 | /// load. Without them a compose proposal gets no generation record. |
| 1686 | identity: std::sync::Mutex< |
| 1687 | Option<( |
| 1688 | crate::generation::ModelIdentity, |
| 1689 | crate::generation::DaemonStart, |
| 1690 | )>, |
| 1691 | >, |
| 1692 | /// Correlation trace (sovereign-core #398). Observational only: events |
| 1693 | /// carry ids and digests, never prompts, proposals or file contents, and |
| 1694 | /// nothing reads them to decide. `NullSink` by default (tracing off). |
| 1695 | trace: Arc<dyn aien_trace::TraceSink>, |
| 1696 | /// One trace id per bridge (per daemon start and compose home). |
| 1697 | trace_id: aien_trace::TraceId, |
| 1698 | /// Event id of the first event this bridge emitted; the parent of all its |
| 1699 | /// later events. 0 until the first event. |
| 1700 | trace_root: std::sync::atomic::AtomicU64, |
| 1701 | } |
| 1702 | |
| 1703 | impl ComposeBridge { |
| 1704 | pub fn new(dir: PathBuf, proposer: ComposeProposer, proposer_label: &str) -> Self { |
| 1705 | Self { |
| 1706 | dir, |
| 1707 | proposer, |
| 1708 | doc_proposer: None, |
| 1709 | proposer_label: proposer_label.to_string(), |
| 1710 | home: std::sync::Mutex::new(None), |
| 1711 | reconcile_failed: std::sync::Mutex::new(None), |
| 1712 | closed: std::sync::atomic::AtomicBool::new(false), |
| 1713 | authorize_requires_desk: true, |
| 1714 | identity: std::sync::Mutex::new(None), |
| 1715 | trace: Arc::new(aien_trace::NullSink), |
| 1716 | trace_id: aien_trace::TraceId::derive( |
| 1717 | aien_trace::now_unix_ms(), |
| 1718 | u64::from(std::process::id()), |
| 1719 | 0, |
| 1720 | ), |
| 1721 | trace_root: std::sync::atomic::AtomicU64::new(0), |
| 1722 | } |
| 1723 | } |
| 1724 | |
| 1725 | /// Installs the correlation trace sink (#398). Default `NullSink`. |
| 1726 | pub(crate) fn with_trace_sink(mut self, sink: Arc<dyn aien_trace::TraceSink>) -> Self { |
| 1727 | self.trace = sink; |
| 1728 | self |
| 1729 | } |
| 1730 | |
| 1731 | /// This bridge's trace id (correlation key, not a secret). |
| 1732 | pub fn trace_id(&self) -> aien_trace::TraceId { |
| 1733 | self.trace_id |
| 1734 | } |
| 1735 | |
| 1736 | /// True when a trace sink is installed. Call sites check this before |
| 1737 | /// building ids so that a disabled sink costs no allocation. |
| 1738 | pub(crate) fn trace_enabled(&self) -> bool { |
| 1739 | self.trace.enabled() |
| 1740 | } |
| 1741 | |
| 1742 | /// Emits one correlation event for this bridge. The first event becomes |
| 1743 | /// the root; every later one is its child. With the sink disabled this |
| 1744 | /// allocates nothing and reads no clock (callers build the ids only after |
| 1745 | /// `trace_enabled`). Returns the event id (0 if off). |
| 1746 | pub(crate) fn trace_event( |
| 1747 | &self, |
| 1748 | kind: aien_trace::EventKind, |
| 1749 | status: aien_trace::EventStatus, |
| 1750 | effect_certainty: Option<aien_trace::EffectCertainty>, |
| 1751 | ids: aien_trace::CorrelationIds, |
| 1752 | refs: aien_trace::EvidenceRefs, |
| 1753 | note: &str, |
| 1754 | ) -> u64 { |
| 1755 | use std::sync::atomic::Ordering; |
| 1756 | if !self.trace.enabled() { |
| 1757 | return 0; |
| 1758 | } |
| 1759 | let id = self.trace.next_event_id(); |
| 1760 | let parent = self |
| 1761 | .trace_root |
| 1762 | .compare_exchange(0, id, Ordering::AcqRel, Ordering::Acquire) |
| 1763 | .err(); |
| 1764 | self.trace.emit(aien_trace::TraceEvent { |
| 1765 | trace_id: self.trace_id, |
| 1766 | event_id: id, |
| 1767 | parent_event_id: parent, |
| 1768 | at_unix_ms: aien_trace::now_unix_ms(), |
| 1769 | kind, |
| 1770 | status, |
| 1771 | effect_certainty, |
| 1772 | ids, |
| 1773 | refs, |
| 1774 | note: (!note.is_empty()).then(|| aien_trace::BoundedNote::new(note)), |
| 1775 | }); |
| 1776 | id |
| 1777 | } |
| 1778 | |
| 1779 | /// Use `doc_proposer` (its own token cap) for full-document tasks. |
| 1780 | pub fn with_doc_proposer(mut self, doc_proposer: ComposeProposer) -> Self { |
| 1781 | self.doc_proposer = Some(doc_proposer); |
| 1782 | self |
| 1783 | } |
| 1784 | |
| 1785 | /// The model files this daemon loaded (digests hashed at load) and when it |
| 1786 | /// started. Set once by the daemon; the compose task uses them to write the |
| 1787 | /// generation record of the proposal it commits. Evidence only. |
| 1788 | pub fn set_model_identity( |
| 1789 | &self, |
| 1790 | identity: crate::generation::ModelIdentity, |
| 1791 | started: crate::generation::DaemonStart, |
| 1792 | ) { |
| 1793 | *self.identity.lock().unwrap_or_else(|e| e.into_inner()) = Some((identity, started)); |
| 1794 | } |
| 1795 | |
| 1796 | /// Turn the desk-MAC requirement on `ComposeAuthorize` on or off (#297). |
| 1797 | /// On by default (#328); off is for dev and tests of the legacy path, and a |
| 1798 | /// server refuses to start with it off in a strict run. |
| 1799 | pub fn with_authorize_requires_desk(mut self, on: bool) -> Self { |
| 1800 | self.authorize_requires_desk = on; |
| 1801 | self |
| 1802 | } |
| 1803 | |
| 1804 | /// True when `ComposeAuthorize` needs the approval desk's MAC (#297). |
| 1805 | pub fn authorize_requires_desk(&self) -> bool { |
| 1806 | self.authorize_requires_desk |
| 1807 | } |
| 1808 | |
| 1809 | pub fn dir(&self) -> &Path { |
| 1810 | &self.dir |
| 1811 | } |
| 1812 | |
| 1813 | /// Close the compose home and refuse to reopen it. Daemon shutdown calls |
| 1814 | /// this before `run` returns: connection tasks hold their own `Arc` of the |
| 1815 | /// bridge and can outlive `run`, so without it `rxc_host_close` (the drop of |
| 1816 | /// the home) ran at an unspecified later time and a successor opening the |
| 1817 | /// same home in that window saw a journal behind its J-Space anchor |
| 1818 | /// (E_REPLAY, sovereign-core #306). Waits for a command in flight (it holds |
| 1819 | /// the home lock). Blocking: call it from a blocking context. |
| 1820 | pub fn close(&self) { |
| 1821 | let mut guard = match self.home.lock() { |
| 1822 | Ok(g) => g, |
| 1823 | Err(p) => p.into_inner(), |
| 1824 | }; |
| 1825 | self.closed.store(true, std::sync::atomic::Ordering::SeqCst); |
| 1826 | *guard = None; |
| 1827 | } |
| 1828 | |
| 1829 | /// True after `close`. |
| 1830 | pub fn is_closed(&self) -> bool { |
| 1831 | self.closed.load(std::sync::atomic::Ordering::SeqCst) |
| 1832 | } |
| 1833 | |
| 1834 | fn open_home(&self) -> Result<ComposeHome, String> { |
| 1835 | self.open_home_marked(None) |
| 1836 | } |
| 1837 | |
| 1838 | /// Open the home and check its Cortex record mark (ACCEPTANCE-v3 2.2). |
| 1839 | /// `rebuilt_from` = the seq of a mark RecoverComposeHome just set aside: |
| 1840 | /// the home then opens without a mark and gets a fresh one. |
| 1841 | fn open_home_marked(&self, rebuilt_from: Option<u64>) -> Result<ComposeHome, String> { |
| 1842 | // The one place every lazy open goes through (with_home, run_task_inner, |
| 1843 | // record_digest, recover): callers hold the home lock and close() sets |
| 1844 | // `closed` under the same lock, so no site can reopen after close. |
| 1845 | if self.is_closed() { |
| 1846 | return Err(CLOSED_REFUSAL.to_string()); |
| 1847 | } |
| 1848 | // Refuse a bad budget before anything is opened (never fall back). |
| 1849 | let budgets = compose_budgets_from_env() |
| 1850 | .map_err(|e| format!("compose home {} refused: {e}", self.dir.display()))?; |
| 1851 | let root = machine_root(&self.dir)?; |
| 1852 | let mark_path = cortex_mark::mark_path(&self.dir); |
| 1853 | let existing = match rebuilt_from { |
| 1854 | Some(_) => None, |
| 1855 | None => cortex_mark::read(&mark_path) |
| 1856 | .map_err(|why| mark_refusal(&self.dir, &MarkRefusal::Damaged(why)))?, |
| 1857 | }; |
| 1858 | let journal_present = std::fs::metadata(self.dir.join("cortex.cx")) |
| 1859 | .map(|m| m.len() > 0) |
| 1860 | .unwrap_or(false); |
| 1861 | // rxc_host_open appends nothing: `info.records` is the read-only probe |
| 1862 | // count, so the count check runs before the open appends anything. |
| 1863 | let (mut compose, info) = |
| 1864 | Compose::open(&self.dir, RootKind::Provisioned, &root, 0xA1E4_0001) |
| 1865 | .map_err(|e: ComposeError| refusal(&self.dir, &e))?; |
| 1866 | // omega settles after a fixed wait. Every run sets it again to its own |
| 1867 | // budget + 1 s (run_task_inner); here the edit value is checked once, so an |
| 1868 | // old omega without rxc_host_set_wait_ms refuses a changed edit budget at open. |
| 1869 | compose |
| 1870 | .set_wait_ms((budgets.edit + COMPOSE_WAIT_MARGIN).as_millis() as u32) |
| 1871 | .map_err(|e| refusal(&self.dir, &e))?; |
| 1872 | let plan = cortex_mark::plan( |
| 1873 | existing.as_ref(), |
| 1874 | &info.machine_id, |
| 1875 | info.records, |
| 1876 | journal_present, |
| 1877 | ) |
| 1878 | .map_err(|r| mark_refusal(&self.dir, &r))?; |
| 1879 | let prompts: Arc<parking_lot::Mutex<HashMap<u64, TaskEntry>>> = Arc::default(); |
| 1880 | let proposals: Arc<parking_lot::Mutex<HashMap<u64, SkillOutput>>> = Arc::default(); |
| 1881 | let approved: Arc<parking_lot::Mutex<HashMap<u64, String>>> = Arc::default(); |
| 1882 | let (pr, pp, proposer) = (prompts.clone(), proposals.clone(), self.proposer.clone()); |
| 1883 | let doc_proposer = self |
| 1884 | .doc_proposer |
| 1885 | .clone() |
| 1886 | .unwrap_or_else(|| self.proposer.clone()); |
| 1887 | let pa = approved.clone(); |
| 1888 | compose |
| 1889 | .register_skill(COMPOSE_MODEL_SKILL, None, 10, move |task| { |
| 1890 | // The requirement record of this task. A missing record is a refusal, |
| 1891 | // never an empty requirement list (issue #289). |
| 1892 | let entry = pr.lock().get(&task).cloned(); |
| 1893 | let Some(((prompt, target, kind), ex, dest, placement)) = entry else { |
| 1894 | pp.lock() |
| 1895 | .insert(task, refused_without_model(MISSING_RECORD_REASON.into())); |
| 1896 | return None; |
| 1897 | }; |
| 1898 | // Goal text that looks like a measurable requirement but could not |
| 1899 | // be read reliably: refuse before any model call. |
| 1900 | if let Some(why) = ex.refusal() { |
| 1901 | pp.lock().insert(task, refused_without_model(why)); |
| 1902 | return None; |
| 1903 | } |
| 1904 | let reqs = ex.requirements; |
| 1905 | // Proposer hook (crate::approved): an approved proposal for this |
| 1906 | // task replaces the model's reply. One attempt, the same |
| 1907 | // template check, the same AEGIS contract and commit below. |
| 1908 | // edit = None: an approved whole-file proposal never goes |
| 1909 | // through merge_edit_reply, so the committed bytes are the |
| 1910 | // approved bytes even when the path already exists. |
| 1911 | let budget = budgets.for_kind(kind); |
| 1912 | let attempt_budget = compose_attempt_budget(kind, budget); |
| 1913 | let fixed = pa.lock().get(&task).cloned(); |
| 1914 | let (out, attempts) = match fixed { |
| 1915 | Some(text) => propose_approved(&text, &prompt, &reqs, budget, attempt_budget), |
| 1916 | // Fixed template + bounded automatic retry (ACCEPTANCE-v2 3a, 3b), |
| 1917 | // measured per-attempt budget (ACCEPTANCE-v3 3b); an edit reply |
| 1918 | // is merged into the content the model was shown (v7 T5). |
| 1919 | None => { |
| 1920 | let edit = target.as_ref().map(|(p, c)| (p.as_str(), c.as_str())); |
| 1921 | let p = match kind { |
| 1922 | ProposalKind::Edit => &proposer, |
| 1923 | ProposalKind::Document => &doc_proposer, |
| 1924 | }; |
| 1925 | propose_task_placed( |
| 1926 | p.as_ref(), |
| 1927 | &prompt, |
| 1928 | edit, |
| 1929 | placement, |
| 1930 | &reqs, |
| 1931 | budget, |
| 1932 | attempt_budget, |
| 1933 | COMPOSE_MAX_ATTEMPTS, |
| 1934 | ) |
| 1935 | } |
| 1936 | }; |
| 1937 | let (out, attempts) = enforce_destination( |
| 1938 | (out, attempts), |
| 1939 | dest.0.as_deref(), |
| 1940 | &dest.1, |
| 1941 | kind == ProposalKind::Edit, |
| 1942 | ); |
| 1943 | let h = out.as_ref().ok().map(|t| proposal_handle(t)); |
| 1944 | pp.lock().insert(task, (out, attempts)); |
| 1945 | // Test seam (compiled only into unit tests): lose the requirement |
| 1946 | // record between the Skill and AEGIS verify, as a bug would (#289). |
| 1947 | #[cfg(test)] |
| 1948 | if prompt.contains(TEST_DROP_RECORD_MARKER) { |
| 1949 | pr.lock().remove(&task); |
| 1950 | } |
| 1951 | h |
| 1952 | }) |
| 1953 | .map_err(|e| format!("compose register skill: {e}"))?; |
| 1954 | let (pv, pq) = (proposals.clone(), prompts.clone()); |
| 1955 | compose |
| 1956 | .set_verify(move |task, result| { |
| 1957 | // AEGIS contract: the result names exactly the proposal text |
| 1958 | // the Skill recorded for this task, and that text parses as one |
| 1959 | // file change (a relative path and nonempty content). |
| 1960 | // The requirements of the goal are checked again on these same |
| 1961 | // bytes, the ones that would be saved. No requirement record |
| 1962 | // for the task means NO approval (issue #289). |
| 1963 | let ex = pq.lock().get(&task).map(|p| p.1.clone()); |
| 1964 | let proposals = pv.lock(); |
| 1965 | verify_task_result(ex.as_ref(), proposals.get(&task), result) |
| 1966 | }) |
| 1967 | .map_err(|e| format!("compose set verify: {e}"))?; |
| 1968 | // Open the composition now, so a home behind its anchor is refused here |
| 1969 | // with its name (E_REPLAY), not inside the first run. |
| 1970 | compose.info().map_err(|e| refusal(&self.dir, &e))?; |
| 1971 | // The digest check needs the open home (the open appended the five |
| 1972 | // start-up records; ACCEPTANCE-v3 G1, G3). |
| 1973 | if let Plan::Verify(m) = &plan { |
| 1974 | if m.records > 0 { |
| 1975 | let at = compose.record(m.records).ok().map(|r| r.digest); |
| 1976 | cortex_mark::check_digest(m, at).map_err(|r| mark_refusal(&self.dir, &r))?; |
| 1977 | // Receipt continuity (#408 row 8): every record before the |
| 1978 | // newest, through the chain the mark carries. |
| 1979 | if m.chain.is_some() { |
| 1980 | let at = record_chain(&mut compose, [0u8; 32], 1, m.records).ok(); |
| 1981 | cortex_mark::check_chain(m, at).map_err(|r| mark_refusal(&self.dir, &r))?; |
| 1982 | } |
| 1983 | } |
| 1984 | } |
| 1985 | // ALLEN identity gate: after the open (record 1 exists, skills are |
| 1986 | // registered), before the home is handed out. Fatal when engaged. |
| 1987 | let allen = allen_gate(&self.dir, &mut compose, &info.machine_id); |
| 1988 | let memory = crate::allen_memory::MemoryState::open(&self.dir, allen.as_ref()); |
| 1989 | let mut home = ComposeHome { |
| 1990 | compose, |
| 1991 | allen, |
| 1992 | memory, |
| 1993 | budgets, |
| 1994 | machine_id: hex(&info.machine_id), |
| 1995 | prompts, |
| 1996 | approved, |
| 1997 | proposals, |
| 1998 | mark_path, |
| 1999 | machine_raw: info.machine_id, |
| 2000 | mark: existing.clone(), |
| 2001 | mark_seq: existing |
| 2002 | .as_ref() |
| 2003 | .map_or(rebuilt_from.unwrap_or(0), |m| m.seq), |
| 2004 | }; |
| 2005 | let written = home.advance_mark().map_err(|e| { |
| 2006 | format!( |
| 2007 | "compose home {} refused: record mark update failed (E_MARK_WRITE): {e}", |
| 2008 | self.dir.display() |
| 2009 | ) |
| 2010 | })?; |
| 2011 | let event = match rebuilt_from { |
| 2012 | Some(_) => written.as_ref().map(|w| { |
| 2013 | format!( |
| 2014 | "Cortex mark: mark rebuilt by RecoverComposeHome (seq {}, records {})", |
| 2015 | w.seq, w.records |
| 2016 | ) |
| 2017 | }), |
| 2018 | None => cortex_mark::open_event(&plan, info.records, written.as_ref()), |
| 2019 | }; |
| 2020 | if let Some(line) = event { |
| 2021 | println!("{line}"); |
| 2022 | } |
| 2023 | Ok(home) |
| 2024 | } |
| 2025 | |
| 2026 | /// Start-up reconcile failed or was refused: effect commands refuse |
| 2027 | /// until an operator reconcile succeeds (ACCEPTANCE-v3 2.5). |
| 2028 | pub fn set_reconcile_failed(&self, why: String) { |
| 2029 | if let Ok(mut g) = self.reconcile_failed.lock() { |
| 2030 | *g = Some(why); |
| 2031 | } |
| 2032 | } |
| 2033 | |
| 2034 | /// Why effect commands are refused, if they are. |
| 2035 | pub fn reconcile_failed(&self) -> Option<String> { |
| 2036 | match self.reconcile_failed.lock() { |
| 2037 | Ok(g) => g.clone(), |
| 2038 | Err(_) => Some("reconcile state lock poisoned".into()), |
| 2039 | } |
| 2040 | } |
| 2041 | |
| 2042 | pub(crate) fn clear_reconcile_failed(&self) { |
| 2043 | if let Ok(mut g) = self.reconcile_failed.lock() { |
| 2044 | *g = None; |
| 2045 | } |
| 2046 | } |
| 2047 | |
| 2048 | /// Blocking: runs inference inside the Skill. Call from a blocking thread. |
| 2049 | pub fn run_task(&self, goal: &str, workspace: &str) -> ControlResponse { |
| 2050 | self.run_task_in(goal, workspace, None) |
| 2051 | } |
| 2052 | |
| 2053 | /// `run_task` with an operator-named ALLEN memory context (`None` = no memory). |
| 2054 | pub fn run_task_in( |
| 2055 | &self, |
| 2056 | goal: &str, |
| 2057 | workspace: &str, |
| 2058 | context: Option<&str>, |
| 2059 | ) -> ControlResponse { |
| 2060 | match self.run_task_inner(goal, workspace, None, context) { |
| 2061 | Ok(r) => ControlResponse::ComposeTaskResult(Box::new(r)), |
| 2062 | Err(e) => ControlResponse::Error(e), |
| 2063 | } |
| 2064 | } |
| 2065 | |
| 2066 | /// Proposer hook entry (crate::approved): one compose run whose model |
| 2067 | /// Skill returns `approved_text` instead of calling the proposer. The run |
| 2068 | /// is otherwise the RunComposeTask run: J-Space branch, AEGIS verify |
| 2069 | /// callback, World commit, Cortex records. Blocking. |
| 2070 | pub(crate) fn run_approved_task( |
| 2071 | &self, |
| 2072 | goal: &str, |
| 2073 | workspace: &str, |
| 2074 | approved_text: &str, |
| 2075 | ) -> Result<ComposeTaskReport, String> { |
| 2076 | self.run_task_inner(goal, workspace, Some(approved_text), None) |
| 2077 | } |
| 2078 | |
| 2079 | fn run_task_inner( |
| 2080 | &self, |
| 2081 | goal: &str, |
| 2082 | workspace: &str, |
| 2083 | approved_text: Option<&str>, |
| 2084 | context: Option<&str>, |
| 2085 | ) -> Result<ComposeTaskReport, String> { |
| 2086 | if goal.trim().is_empty() { |
| 2087 | return Err("RunComposeTask: empty goal".into()); |
| 2088 | } |
| 2089 | let ws = std::fs::canonicalize(workspace) |
| 2090 | .map_err(|e| format!("RunComposeTask: workspace {workspace}: {e}"))?; |
| 2091 | if !ws.is_dir() { |
| 2092 | return Err(format!( |
| 2093 | "RunComposeTask: workspace {} is not a directory", |
| 2094 | ws.display() |
| 2095 | )); |
| 2096 | } |
| 2097 | let (mut plan, dest, inputs, inputs_omitted) = task_decision_with_inputs(goal, &ws)?; |
| 2098 | // The requirements the goal states are checked on every path: the model |
| 2099 | // path and an approved proposal (refused before any write when unmet). |
| 2100 | let machine_goal = |
| 2101 | approved_text.is_some() && goal.starts_with(crate::approved::APPROVED_GOAL_PREFIX); |
| 2102 | let mut reqs = if machine_goal { |
| 2103 | crate::requirements::Extraction::default() |
| 2104 | } else { |
| 2105 | crate::requirements::analyze(goal) |
| 2106 | }; |
| 2107 | // Added-line counts are measured against the file the proposal replaces |
| 2108 | // (the edit target's content, or nothing for a new file). |
| 2109 | if reqs.needs_prior() { |
| 2110 | let prior = plan.1.as_ref().map_or("", |(_, c)| c.as_str()); |
| 2111 | reqs = reqs.resolved(prior); |
| 2112 | } |
| 2113 | let recognized: Vec<String> = reqs.requirements.iter().map(|r| r.label()).collect(); |
| 2114 | let uncertain = reqs.uncertain.clone(); |
| 2115 | let now = std::time::SystemTime::now() |
| 2116 | .duration_since(std::time::UNIX_EPOCH) |
| 2117 | .map_err(|e| format!("clock: {e}"))?; |
| 2118 | let mut h = Sha256::new(); |
| 2119 | h.update(goal.as_bytes()); |
| 2120 | h.update([0u8]); |
| 2121 | h.update(ws.as_os_str().as_encoded_bytes()); |
| 2122 | h.update(now.as_nanos().to_le_bytes()); |
| 2123 | let d = h.finalize(); |
| 2124 | let task = u64::from_le_bytes(d[..8].try_into().expect("8 bytes")) | 1; |
| 2125 | |
| 2126 | let mut guard = self |
| 2127 | .home |
| 2128 | .lock() |
| 2129 | .map_err(|_| "compose home lock poisoned".to_string())?; |
| 2130 | if guard.is_none() { |
| 2131 | *guard = Some(self.open_home()?); |
| 2132 | } |
| 2133 | let home = guard.as_mut().expect("opened above"); |
| 2134 | // ALLEN persona (arch#159): only a model run reads it; an approved |
| 2135 | // proposal runs no model, so it carries no persona. Not engaged: the |
| 2136 | // prompt is exactly what it was. |
| 2137 | // ALLEN memory (arch#159): a model run with an operator-named context only. |
| 2138 | let (memory_block, memory) = match approved_text { |
| 2139 | None => { |
| 2140 | let (b, r) = crate::allen_memory::for_task(&home.memory, context)?; |
| 2141 | (b, Some(r)) |
| 2142 | } |
| 2143 | Some(_) => (None, None), |
| 2144 | }; |
| 2145 | plan.0 = crate::allen_memory::prefix_prompt(&plan.0, memory_block.as_deref()); |
| 2146 | let persona_ctx = match approved_text { |
| 2147 | None => crate::persona::context_for(&self.dir, home.allen.as_ref()), |
| 2148 | Some(_) => None, |
| 2149 | }; |
| 2150 | plan.0 = crate::persona::prefix_prompt(&plan.0, persona_ctx.as_ref()); |
| 2151 | let persona = match approved_text { |
| 2152 | None => Some(crate::persona::report_for(persona_ctx.as_ref())), |
| 2153 | Some(_) => None, |
| 2154 | }; |
| 2155 | // Deadlines agree on both sides: omega settles budget + 1 s after the run |
| 2156 | // starts, the Skill gives up at budget. Set only here, under the lock that |
| 2157 | // serializes runs, never while rx_compose_run is in flight. An omega without |
| 2158 | // rxc_host_set_wait_ms refuses a budget that needs a longer wait (no silent 30 s wait). |
| 2159 | let kind = plan.2; |
| 2160 | let wait = home.budgets.for_kind(kind) + COMPOSE_WAIT_MARGIN; |
| 2161 | home.compose |
| 2162 | .set_wait_ms(wait.as_millis() as u32) |
| 2163 | .map_err(|e| { |
| 2164 | format!( |
| 2165 | "compose run refused: {kind:?} budget needs omega settle wait {} ms: {e}", |
| 2166 | wait.as_millis() |
| 2167 | ) |
| 2168 | })?; |
| 2169 | if let Some(t) = approved_text { |
| 2170 | home.approved.lock().insert(task, t.to_string()); |
| 2171 | } |
| 2172 | home.prompts.lock().insert( |
| 2173 | task, |
| 2174 | ( |
| 2175 | plan, |
| 2176 | reqs, |
| 2177 | (dest, ws.clone()), |
| 2178 | EditPlacement::for_goal(goal), |
| 2179 | ), |
| 2180 | ); |
| 2181 | let run = home.compose.run(task, now.as_micros() as u64); |
| 2182 | home.prompts.lock().remove(&task); |
| 2183 | home.approved.lock().remove(&task); |
| 2184 | let output = home.proposals.lock().remove(&task); |
| 2185 | // A run appends whether or not it commits: move the record mark first. |
| 2186 | home.advance_mark() |
| 2187 | .map_err(|e| format!("compose run: record mark update failed (E_MARK_WRITE): {e}"))?; |
| 2188 | let r = run.map_err(|e| format!("compose run: {e}"))?; |
| 2189 | let committed = r.committed == 1; |
| 2190 | let (out, mut proposal_attempts) = |
| 2191 | output.unwrap_or((Err("the Skill did not run".into()), Vec::new())); |
| 2192 | // The attempt handed to AEGIS is the parsed one; record its verdict. |
| 2193 | if let Some(a) = proposal_attempts.iter_mut().find(|a| a.outcome == "parsed") { |
| 2194 | a.aegis = Some(if committed { "pass" } else { "fail" }.into()); |
| 2195 | } |
| 2196 | let (proposal, uncommitted_proposal, proposer_error) = match out { |
| 2197 | Ok(t) if committed => (Some(t), None, None), |
| 2198 | Ok(t) => (None, Some(t), None), |
| 2199 | Err(e) => (None, None, Some(e)), |
| 2200 | }; |
| 2201 | let parsed = proposal.as_deref().and_then(parse_file_proposal); |
| 2202 | // sovereign-core #261: the daemon's own record that THIS run committed |
| 2203 | // THIS proposal. `ComposeAuthorize` mints only from it. An approved |
| 2204 | // proposal has its own replay claim and grant, so it gets none. |
| 2205 | let mut compose_commit = None; |
| 2206 | let mut generation_record = None; |
| 2207 | if let (true, None, Some(p), Some(text)) = ( |
| 2208 | committed, |
| 2209 | approved_text, |
| 2210 | parsed.as_ref(), |
| 2211 | proposal.as_deref(), |
| 2212 | ) { |
| 2213 | let wsc = std::fs::canonicalize(&ws) |
| 2214 | .map_err(|e| format!("workspace {}: {e}", ws.display()))? |
| 2215 | .display() |
| 2216 | .to_string(); |
| 2217 | // Provenance (arch#162): the generation record of the attempt the |
| 2218 | // proposal came from, written now under the lock this run holds |
| 2219 | // (the model call itself cannot take it). Evidence only. |
| 2220 | generation_record = self.write_task_generation(home, task, &proposal_attempts); |
| 2221 | let prov = crate::generation::Provenance::new(generation_record, home.allen.as_ref()); |
| 2222 | let id = crate::effects::write_compose_commit( |
| 2223 | home, |
| 2224 | &wsc, |
| 2225 | task, |
| 2226 | r.cx_promotion, |
| 2227 | r.cx_evidence, |
| 2228 | &hex(&Sha256::digest(text.as_bytes())), |
| 2229 | &p.path, |
| 2230 | &hex(&Sha256::digest(p.content.as_bytes())), |
| 2231 | Some(&hex(&Sha256::digest(goal.as_bytes()))), |
| 2232 | &prov, |
| 2233 | ) |
| 2234 | .map_err(|e| { |
| 2235 | format!( |
| 2236 | "compose run committed (promotion #{}) but its commit record was not written: {e}", |
| 2237 | r.cx_promotion |
| 2238 | ) |
| 2239 | })?; |
| 2240 | home.advance_mark().map_err(|e| { |
| 2241 | format!("compose run: record mark update failed (E_MARK_WRITE): {e}") |
| 2242 | })?; |
| 2243 | compose_commit = Some(id); |
| 2244 | } |
| 2245 | // Correlation only (#398): the turn happened, what record names it, |
| 2246 | // and whether it committed. No proposal text, no goal text. |
| 2247 | if self.trace_enabled() { |
| 2248 | self.trace_event( |
| 2249 | aien_trace::EventKind::ModelTurn, |
| 2250 | if proposer_error.is_some() { |
| 2251 | aien_trace::EventStatus::Failed |
| 2252 | } else { |
| 2253 | aien_trace::EventStatus::Ok |
| 2254 | }, |
| 2255 | None, |
| 2256 | aien_trace::CorrelationIds { |
| 2257 | generation_record, |
| 2258 | decision_id: compose_commit.map(|c| aien_trace::BoundedId::new(&c.to_string())), |
| 2259 | ..Default::default() |
| 2260 | }, |
| 2261 | aien_trace::EvidenceRefs::default(), |
| 2262 | if proposer_error.is_some() { |
| 2263 | "proposer_error" |
| 2264 | } else if committed { |
| 2265 | "compose_commit" |
| 2266 | } else { |
| 2267 | "uncommitted" |
| 2268 | }, |
| 2269 | ); |
| 2270 | } |
| 2271 | Ok(ComposeTaskReport { |
| 2272 | compose_commit, |
| 2273 | generation_record, |
| 2274 | |
| 2275 | compose_dir: self.dir.display().to_string(), |
| 2276 | machine_id: home.machine_id.clone(), |
| 2277 | task, |
| 2278 | outcome: r.outcome, |
| 2279 | committed, |
| 2280 | branch_count: r.n_branches, |
| 2281 | branches_reclaimed: r.branches_reclaimed, |
| 2282 | winner: (r.winner != aien_omega_compose::NONE).then_some(r.winner), |
| 2283 | aegis_pass_mask: r.aegis_pass_mask, |
| 2284 | cx_goal: r.cx_goal, |
| 2285 | cx_candidates: r.cx_candidate.iter().copied().filter(|&x| x != 0).collect(), |
| 2286 | cx_evidence: r.cx_evidence, |
| 2287 | cx_promotion: r.cx_promotion, |
| 2288 | cx_admissions: r.cx_admission.iter().copied().filter(|&x| x != 0).collect(), |
| 2289 | winner_digest: hex(&r.winner_digest), |
| 2290 | record_digest: hex(&r.record_digest), |
| 2291 | proposal_path: parsed.as_ref().map(|p| p.path.clone()), |
| 2292 | proposal_content_sha256: parsed |
| 2293 | .as_ref() |
| 2294 | .map(|p| hex(&Sha256::digest(p.content.as_bytes()))), |
| 2295 | proposal_sha256: proposal |
| 2296 | .as_ref() |
| 2297 | .map(|t| hex(&Sha256::digest(t.as_bytes()))), |
| 2298 | proposal, |
| 2299 | uncommitted_proposal, |
| 2300 | proposer_error, |
| 2301 | proposal_attempts, |
| 2302 | requirements_recognized: recognized, |
| 2303 | requirements_uncertain: uncertain, |
| 2304 | proposer: match approved_text { |
| 2305 | Some(_) => APPROVED_PROPOSER_LABEL.to_string(), |
| 2306 | None => self.proposer_label.clone(), |
| 2307 | }, |
| 2308 | persona, |
| 2309 | memory, |
| 2310 | inputs, |
| 2311 | inputs_omitted, |
| 2312 | }) |
| 2313 | } |
| 2314 | |
| 2315 | /// Write the generation record of the proposal attempt a committed task |
| 2316 | /// came from. `None` (with the reason logged when a write failed) when the |
| 2317 | /// daemon has no model identity, the attempt did not expose its token ids, |
| 2318 | /// or the append failed: no record means no claim, and the commit stands. |
| 2319 | fn write_task_generation( |
| 2320 | &self, |
| 2321 | home: &mut ComposeHome, |
| 2322 | task: u64, |
| 2323 | attempts: &[ProposalAttempt], |
| 2324 | ) -> Option<u64> { |
| 2325 | let (identity, started) = self |
| 2326 | .identity |
| 2327 | .lock() |
| 2328 | .unwrap_or_else(|e| e.into_inner()) |
| 2329 | .clone()?; |
| 2330 | let a = attempts.iter().find(|a| a.outcome == "parsed")?; |
| 2331 | let (ids, text, prompt_sha, prompt_tokens) = ( |
| 2332 | a.token_ids.as_deref()?, |
| 2333 | a.text.as_deref()?, |
| 2334 | a.prompt_ids_sha256.as_deref()?, |
| 2335 | a.prompt_tokens?, |
| 2336 | ); |
| 2337 | let record = crate::generation::build_compose_record( |
| 2338 | &identity, |
| 2339 | &crate::generation::ComposeEvidence { |
| 2340 | prompt_ids_sha256: prompt_sha, |
| 2341 | prompt_tokens, |
| 2342 | output_ids: ids, |
| 2343 | text, |
| 2344 | finish_reason: a.finish_reason.as_deref().unwrap_or("unknown"), |
| 2345 | task, |
| 2346 | attempt: a.attempt, |
| 2347 | decoding: a.decoding.as_ref(), |
| 2348 | ops: a.ops.as_ref(), |
| 2349 | }, |
| 2350 | started, |
| 2351 | ); |
| 2352 | match crate::generation::write(home, &record) { |
| 2353 | Ok(id) => Some(id), |
| 2354 | Err(e) => { |
| 2355 | tracing::warn!("generation record not written: {e}"); |
| 2356 | eprintln!("generation record not written: {e}"); |
| 2357 | None |
| 2358 | } |
| 2359 | } |
| 2360 | } |
| 2361 | |
| 2362 | /// Append the daemon's generation record (evidence only; see |
| 2363 | /// `crate::generation`). Returns the record id only once it is written. |
| 2364 | pub(crate) fn record_generation(&self, record: &serde_json::Value) -> Result<u64, String> { |
| 2365 | self.with_home(|home| crate::generation::write(home, record)) |
| 2366 | } |
| 2367 | |
| 2368 | pub(crate) fn with_home<T>( |
| 2369 | &self, |
| 2370 | f: impl FnOnce(&mut ComposeHome) -> Result<T, String>, |
| 2371 | ) -> Result<T, String> { |
| 2372 | let mut guard = self |
| 2373 | .home |
| 2374 | .lock() |
| 2375 | .map_err(|_| "compose home lock poisoned".to_string())?; |
| 2376 | if guard.is_none() { |
| 2377 | *guard = Some(self.open_home()?); |
| 2378 | } |
| 2379 | let home = guard.as_mut().expect("opened above"); |
| 2380 | let r = f(home); |
| 2381 | // Ok or not, the closure may have appended: the mark follows. |
| 2382 | if let Err(e) = home.advance_mark() { |
| 2383 | return Err(format!( |
| 2384 | "record mark update failed after the operation (E_MARK_WRITE): {e}" |
| 2385 | )); |
| 2386 | } |
| 2387 | r |
| 2388 | } |
| 2389 | |
| 2390 | /// S1 / S5: one operator record through the composition's writer. Gated |
| 2391 | /// records cannot be forged here, on any path (the socket handler calls |
| 2392 | /// this too): authorizations, effect phases, replay and compose-commit |
| 2393 | /// records are written only by the daemon (sovereign-core #261). |
| 2394 | pub fn note(&self, kind: &str, text: &str, links: &[u64]) -> ControlResponse { |
| 2395 | if let Err(e) = crate::effects::check_reserved_note(kind, text) { |
| 2396 | return ControlResponse::Error(e); |
| 2397 | } |
| 2398 | self.write_note(kind, text, links) |
| 2399 | } |
| 2400 | |
| 2401 | /// `note` WITHOUT the reserved-record check. Cargo feature `test-support` |
| 2402 | /// only: it stands for an attacker who can append to the journal directly, |
| 2403 | /// so the ledger's own defences can be exercised. Not in a normal build. |
| 2404 | #[doc(hidden)] |
| 2405 | #[cfg(feature = "test-support")] |
| 2406 | pub fn note_unchecked(&self, kind: &str, text: &str, links: &[u64]) -> ControlResponse { |
| 2407 | self.write_note(kind, text, links) |
| 2408 | } |
| 2409 | |
| 2410 | fn write_note(&self, kind: &str, text: &str, links: &[u64]) -> ControlResponse { |
| 2411 | let k = match kind { |
| 2412 | "constraint" => NoteKind::Constraint, |
| 2413 | "authorization" => NoteKind::Authorization, |
| 2414 | "effect" => NoteKind::Effect, |
| 2415 | other => { |
| 2416 | return ControlResponse::Error(format!( |
| 2417 | "ComposeNote: kind {other:?} (constraint, authorization, effect)" |
| 2418 | )) |
| 2419 | } |
| 2420 | }; |
| 2421 | if links.len() > 4 { |
| 2422 | return ControlResponse::Error("ComposeNote: at most 4 links".into()); |
| 2423 | } |
| 2424 | let mut l = [0u64; 4]; |
| 2425 | l[..links.len()].copy_from_slice(links); |
| 2426 | let r = self.with_home(|home| { |
| 2427 | let id = home |
| 2428 | .compose |
| 2429 | .note(k, l, text.as_bytes()) |
| 2430 | .map_err(|e| format!("ComposeNote: {e}"))?; |
| 2431 | let rec = home |
| 2432 | .compose |
| 2433 | .record(id) |
| 2434 | .map_err(|e| format!("ComposeNote: re-read {id}: {e}"))?; |
| 2435 | Ok(ComposeNoteReport { |
| 2436 | machine_id: home.machine_id.clone(), |
| 2437 | id, |
| 2438 | kind: k.name().to_string(), |
| 2439 | digest: hex(&rec.digest), |
| 2440 | text_sha256: hex(&Sha256::digest(text.as_bytes())), |
| 2441 | links: links.to_vec(), |
| 2442 | }) |
| 2443 | }); |
| 2444 | match r { |
| 2445 | Ok(r) => ControlResponse::ComposeNoted(r), |
| 2446 | Err(e) => ControlResponse::Error(e), |
| 2447 | } |
| 2448 | } |
| 2449 | |
| 2450 | /// ALLEN persona profile commands (arch#159). Opens the home if needed (the |
| 2451 | /// identity is resolved there). Blocking. |
| 2452 | pub fn allen_command(&self, cmd: &ControlCommand) -> ControlResponse { |
| 2453 | let r = self.with_home(|home| { |
| 2454 | if crate::allen_memory::is_memory_command(cmd) { |
| 2455 | return Ok(crate::allen_memory::handle_command(&home.memory, cmd)); |
| 2456 | } |
| 2457 | Ok(crate::persona::handle_allen_command( |
| 2458 | &self.dir, |
| 2459 | home.allen.as_ref(), |
| 2460 | &self.proposer_label, |
| 2461 | cmd, |
| 2462 | )) |
| 2463 | }); |
| 2464 | r.unwrap_or_else(ControlResponse::Error) |
| 2465 | } |
| 2466 | |
| 2467 | /// S6 / S8: host records plus the cited ids, digests re-checked. |
| 2468 | pub fn recall(&self, ids: &[u64], prefix: Option<u64>) -> ControlResponse { |
| 2469 | let r = self.with_home(|home| { |
| 2470 | let info = home |
| 2471 | .compose |
| 2472 | .info() |
| 2473 | .map_err(|e| format!("ComposeRecall: {e}"))?; |
| 2474 | let (host_recs, _) = home |
| 2475 | .compose |
| 2476 | .recall(aien_omega_compose::SUBJECT_HOST, 4096) |
| 2477 | .map_err(|e| format!("ComposeRecall: host records: {e}"))?; |
| 2478 | let host = host_recs |
| 2479 | .iter() |
| 2480 | .map(|r| record_view(&mut home.compose, r)) |
| 2481 | .collect(); |
| 2482 | let (mut cited, mut missing) = (Vec::new(), Vec::new()); |
| 2483 | for &id in ids { |
| 2484 | match home.compose.record(id) { |
| 2485 | Ok(r) => cited.push(record_view(&mut home.compose, &r)), |
| 2486 | Err(_) => missing.push(id), |
| 2487 | } |
| 2488 | } |
| 2489 | let prefix_digest = match prefix { |
| 2490 | Some(n) if n <= info.records => { |
| 2491 | let mut h = Sha256::new(); |
| 2492 | for id in 1..=n { |
| 2493 | let r = home |
| 2494 | .compose |
| 2495 | .record(id) |
| 2496 | .map_err(|e| format!("ComposeRecall: record {id}: {e}"))?; |
| 2497 | h.update(r.digest); |
| 2498 | } |
| 2499 | Some(hex(&h.finalize())) |
| 2500 | } |
| 2501 | _ => None, |
| 2502 | }; |
| 2503 | Ok(ComposeRecallReport { |
| 2504 | compose_dir: self.dir.display().to_string(), |
| 2505 | machine_id: home.machine_id.clone(), |
| 2506 | records_total: info.records, |
| 2507 | host, |
| 2508 | cited, |
| 2509 | missing, |
| 2510 | prefix, |
| 2511 | prefix_digest, |
| 2512 | compose_native: aien_omega_compose::LINKED, |
| 2513 | omega_sha: if aien_omega_compose::LINKED { |
| 2514 | aien_omega_compose::EXPECTED_OMEGA_SHA.to_string() |
| 2515 | } else { |
| 2516 | String::new() |
| 2517 | }, |
| 2518 | }) |
| 2519 | }); |
| 2520 | match r { |
| 2521 | Ok(r) => ControlResponse::ComposeRecalled(Box::new(r)), |
| 2522 | Err(e) => ControlResponse::Error(e), |
| 2523 | } |
| 2524 | } |
| 2525 | |
| 2526 | /// Operator repair: close this process's handle, run rxc_host_recover, |
| 2527 | /// then check the Cortex record mark (ACCEPTANCE-v3 2.3): a mark that is |
| 2528 | /// damaged, ahead of the records kept, or names a different record is |
| 2529 | /// kept as `<mark>.lost-<seq>` (never deleted), the home is reopened with |
| 2530 | /// a fresh mark and one host `constraint` record names the repair. |
| 2531 | pub fn recover(&self) -> ControlResponse { |
| 2532 | if self.is_closed() { |
| 2533 | return ControlResponse::Error(CLOSED_REFUSAL.to_string()); |
| 2534 | } |
| 2535 | let mut guard = match self.home.lock() { |
| 2536 | Ok(g) => g, |
| 2537 | Err(_) => return ControlResponse::Error("compose home lock poisoned".into()), |
| 2538 | }; |
| 2539 | *guard = None; |
| 2540 | let root = match machine_root(&self.dir) { |
| 2541 | Ok(r) => r, |
| 2542 | Err(e) => return ControlResponse::Error(format!("RecoverComposeHome: {e}")), |
| 2543 | }; |
| 2544 | let mark_path = cortex_mark::mark_path(&self.dir); |
| 2545 | let old_mark = cortex_mark::read(&mark_path); |
| 2546 | let r = match Compose::recover(&self.dir, RootKind::Provisioned, &root) { |
| 2547 | Ok(r) => r, |
| 2548 | Err(e) => { |
| 2549 | return ControlResponse::Error(format!( |
| 2550 | "RecoverComposeHome {}: {e}", |
| 2551 | self.dir.display() |
| 2552 | )) |
| 2553 | } |
| 2554 | }; |
| 2555 | let mut report = ComposeRecoverReport { |
| 2556 | compose_dir: self.dir.display().to_string(), |
| 2557 | repaired: r.repaired == 1, |
| 2558 | tail_torn: r.tail_torn == 1, |
| 2559 | cause: r.cause, |
| 2560 | cut_lo: r.cut_lo, |
| 2561 | cut_hi: r.cut_hi, |
| 2562 | records_kept: r.records_kept, |
| 2563 | dropped_records: r.dropped_records, |
| 2564 | anchor_records: r.anchor_records, |
| 2565 | repair_record: r.event_id, |
| 2566 | cut_bytes_kept: r.cut_bytes_kept, |
| 2567 | cut_sha256: hex(&r.cut_sha256), |
| 2568 | opens: r.opens == 1, |
| 2569 | open_rc: r.open_rc, |
| 2570 | rolled_back: r.rolled_back, |
| 2571 | recovered_completed: r.recovered_completed, |
| 2572 | mark_lost: 0, |
| 2573 | mark_kept_as: None, |
| 2574 | mark_repair_record: 0, |
| 2575 | }; |
| 2576 | // (old mark if readable, records lost, why) when the mark must go. |
| 2577 | let set_aside: Option<(Option<Mark>, u64, &str)> = match old_mark { |
| 2578 | Err(_) => Some((None, 0, "damaged")), |
| 2579 | Ok(None) => None, |
| 2580 | Ok(Some(m)) if m.records > r.records_kept => { |
| 2581 | let lost = m.records - r.records_kept; |
| 2582 | Some((Some(m), lost, "ahead of the journal")) |
| 2583 | } |
| 2584 | Ok(Some(m)) => match self.open_home() { |
| 2585 | Ok(home) => { |
| 2586 | *guard = Some(home); |
| 2587 | None |
| 2588 | } |
| 2589 | Err(e) if e.contains("E_MARK_DIGEST") => { |
| 2590 | Some((Some(m), 0, "names a different record")) |
| 2591 | } |
| 2592 | Err(e) if e.contains("E_MARK_CHAIN") => { |
| 2593 | Some((Some(m), 0, "records before the newest differ")) |
| 2594 | } |
| 2595 | // Refused for another reason: reported as before, mark kept. |
| 2596 | Err(_) => None, |
| 2597 | }, |
| 2598 | }; |
| 2599 | let Some((old, lost, why)) = set_aside else { |
| 2600 | return ControlResponse::ComposeRecovered(Box::new(report)); |
| 2601 | }; |
| 2602 | let old_seq = old.as_ref().map(|m| m.seq); |
| 2603 | let kept_as = cortex_mark::lost_path(&mark_path, old_seq); |
| 2604 | if let Err(e) = std::fs::rename(&mark_path, &kept_as) { |
| 2605 | return ControlResponse::Error(format!( |
| 2606 | "RecoverComposeHome: keep the record mark as {}: {e}", |
| 2607 | kept_as.display() |
| 2608 | )); |
| 2609 | } |
| 2610 | let mut home = match self.open_home_marked(Some(old_seq.unwrap_or(0))) { |
| 2611 | Ok(h) => h, |
| 2612 | Err(e) => { |
| 2613 | return ControlResponse::Error(format!( |
| 2614 | "RecoverComposeHome: record mark kept as {}; the home still refuses: {e}", |
| 2615 | kept_as.display() |
| 2616 | )) |
| 2617 | } |
| 2618 | }; |
| 2619 | let text = serde_json::json!({ |
| 2620 | "repair": "cortex-mark", |
| 2621 | "why": why, |
| 2622 | "mark_records": old.as_ref().map(|m| m.records), |
| 2623 | "journal_records": r.records_kept, |
| 2624 | "lost": lost, |
| 2625 | "old_seq": old_seq, |
| 2626 | "old_digest": old.as_ref().map(|m| hex(&m.digest)), |
| 2627 | "old_chain": old.as_ref().and_then(|m| m.chain.map(|c| hex(&c))), |
| 2628 | "kept_as": kept_as.display().to_string(), |
| 2629 | }) |
| 2630 | .to_string(); |
| 2631 | let id = match home |
| 2632 | .compose |
| 2633 | .note(NoteKind::Constraint, [0; 4], text.as_bytes()) |
| 2634 | .and_then(|id| home.compose.record(id).map(|_| id)) |
| 2635 | { |
| 2636 | Ok(id) => id, |
| 2637 | Err(e) => { |
| 2638 | return ControlResponse::Error(format!( |
| 2639 | "RecoverComposeHome: record mark kept as {}; repair record failed: {e}", |
| 2640 | kept_as.display() |
| 2641 | )) |
| 2642 | } |
| 2643 | }; |
| 2644 | if let Err(e) = home.advance_mark() { |
| 2645 | return ControlResponse::Error(format!( |
| 2646 | "RecoverComposeHome: repair record #{id} written; record mark update failed (E_MARK_WRITE): {e}" |
| 2647 | )); |
| 2648 | } |
| 2649 | report.opens = true; |
| 2650 | report.mark_lost = lost; |
| 2651 | report.mark_kept_as = Some(kept_as.display().to_string()); |
| 2652 | report.mark_repair_record = id; |
| 2653 | *guard = Some(home); |
| 2654 | ControlResponse::ComposeRecovered(Box::new(report)) |
| 2655 | } |
| 2656 | |
| 2657 | /// Recall: the Cortex record by id, digest re-checked (cut 2 uses this |
| 2658 | /// to prove cited ids survive a restart). |
| 2659 | pub fn record_digest(&self, id: u64) -> Result<String, String> { |
| 2660 | let mut guard = self |
| 2661 | .home |
| 2662 | .lock() |
| 2663 | .map_err(|_| "compose home lock poisoned".to_string())?; |
| 2664 | if guard.is_none() { |
| 2665 | *guard = Some(self.open_home()?); |
| 2666 | } |
| 2667 | let home = guard.as_mut().expect("opened above"); |
| 2668 | home.compose |
| 2669 | .record(id) |
| 2670 | .map(|r| hex(&r.digest)) |
| 2671 | .map_err(|e| format!("compose record {id}: {e}")) |
| 2672 | } |
| 2673 | } |
| 2674 | |
| 2675 | /// The reply must write the destination the goal named (issue #288): the |
| 2676 | /// approved proposal and a model reply are both held to the same path, so the |
| 2677 | /// save and the commit land on the file the prompt and budget were chosen for. |
| 2678 | /// A goal that named no destination leaves the model free to name the file. |
| 2679 | fn enforce_destination( |
| 2680 | out: SkillOutput, |
| 2681 | dest: Option<&str>, |
| 2682 | ws: &Path, |
| 2683 | is_edit: bool, |
| 2684 | ) -> SkillOutput { |
| 2685 | let (res, attempts) = out; |
| 2686 | let res = match res { |
| 2687 | Ok(t) => match parse_file_proposal(&t) { |
| 2688 | Some(p) if dest.is_some_and(|d| p.path != d) => Err(format!( |
| 2689 | "the proposal writes {} but the goal named the destination {}", |
| 2690 | p.path, |
| 2691 | dest.unwrap_or_default() |
| 2692 | )), |
| 2693 | // Defence in depth: a new-document task never replaces a file |
| 2694 | // that exists (symlinks and dangling links count as existing). |
| 2695 | Some(p) if !is_edit && std::fs::symlink_metadata(ws.join(&p.path)).is_ok() => { |
| 2696 | Err(format!( |
| 2697 | "the proposal writes {} which already exists; refusing to overwrite it as a new document", |
| 2698 | p.path |
| 2699 | )) |
| 2700 | } |
| 2701 | _ => Ok(t), |
| 2702 | }, |
| 2703 | r => r, |
| 2704 | }; |
| 2705 | (res, attempts) |
| 2706 | } |
| 2707 | |
| 2708 | #[cfg(test)] |
| 2709 | mod requirement_tests { |
| 2710 | use super::*; |
| 2711 | use crate::requirements::extract; |
| 2712 | |
| 2713 | const SHORT: &str = "filename: DOC.md\na\nb\nc\n"; |
| 2714 | |
| 2715 | #[test] |
| 2716 | fn approved_text_is_checked_against_the_goal_requirements() { |
| 2717 | let reqs = extract("write DOC.md in at least 10 lines"); |
| 2718 | let (out, a) = propose_approved( |
| 2719 | SHORT, |
| 2720 | "base", |
| 2721 | &reqs, |
| 2722 | COMPOSE_SKILL_BUDGET, |
| 2723 | COMPOSE_ATTEMPT_BUDGET, |
| 2724 | ); |
| 2725 | let why = out.unwrap_err(); |
| 2726 | assert!( |
| 2727 | why.contains("at least 10 non-empty lines, found 3"), |
| 2728 | "{why}" |
| 2729 | ); |
| 2730 | assert_eq!(a.len(), 1); |
| 2731 | assert_eq!(a[0].outcome, "refused"); |
| 2732 | assert_eq!( |
| 2733 | a[0].unmet_requirements, |
| 2734 | ["at least 10 non-empty lines, found 3"] |
| 2735 | ); |
| 2736 | // Met, or none stated: the approved bytes pass through unchanged. |
| 2737 | let (out, _) = propose_approved( |
| 2738 | SHORT, |
| 2739 | "base", |
| 2740 | &extract("at least 3 lines"), |
| 2741 | COMPOSE_SKILL_BUDGET, |
| 2742 | COMPOSE_ATTEMPT_BUDGET, |
| 2743 | ); |
| 2744 | assert_eq!(out.unwrap(), SHORT); |
| 2745 | let (out, a) = propose_approved( |
| 2746 | SHORT, |
| 2747 | "base", |
| 2748 | &[], |
| 2749 | COMPOSE_SKILL_BUDGET, |
| 2750 | COMPOSE_ATTEMPT_BUDGET, |
| 2751 | ); |
| 2752 | assert_eq!(out.unwrap(), SHORT); |
| 2753 | assert_eq!(a[0].finish_reason.as_deref(), Some("approved")); |
| 2754 | } |
| 2755 | |
| 2756 | #[test] |
| 2757 | fn approved_run_reports_recognized_and_refuses_unmet_before_any_write() { |
| 2758 | let _home = crate::home_guard::home_slot(); |
| 2759 | let tmp = tempfile::tempdir().unwrap(); |
| 2760 | let ws = tmp.path().join("ws"); |
| 2761 | std::fs::create_dir_all(&ws).unwrap(); |
| 2762 | let proposer: ComposeProposer = Arc::new(|_: &str, _: std::time::Duration| { |
| 2763 | panic!("the model proposer ran on the approved path") |
| 2764 | }); |
| 2765 | let bridge = ComposeBridge::new(tmp.path().join("compose"), proposer, "test:approved"); |
| 2766 | let r = bridge.run_approved_task( |
| 2767 | "write DOC.md in at least 10 lines", |
| 2768 | ws.to_str().unwrap(), |
| 2769 | SHORT, |
| 2770 | ); |
| 2771 | if !aien_omega_compose::LINKED { |
| 2772 | assert!(r.is_err()); |
| 2773 | return; |
| 2774 | } |
| 2775 | let r = r.unwrap(); |
| 2776 | assert!(!r.committed, "{r:?}"); |
| 2777 | assert!(r.proposal.is_none()); |
| 2778 | assert_eq!(r.requirements_recognized, ["at least 10 non-empty lines"]); |
| 2779 | assert!(r.proposer_error.unwrap().contains("found 3")); |
| 2780 | assert_eq!(std::fs::read_dir(&ws).unwrap().count(), 0); |
| 2781 | // The same bytes pass when the goal states a requirement they meet. |
| 2782 | let r = bridge |
| 2783 | .run_approved_task( |
| 2784 | "write DOC.md in at least 3 lines", |
| 2785 | ws.to_str().unwrap(), |
| 2786 | SHORT, |
| 2787 | ) |
| 2788 | .unwrap(); |
| 2789 | assert!(r.committed, "{r:?}"); |
| 2790 | assert_eq!(r.requirements_recognized, ["at least 3 non-empty lines"]); |
| 2791 | assert_eq!(r.proposal.as_deref(), Some(SHORT)); |
| 2792 | } |
| 2793 | } |
| 2794 | |
| 2795 | #[cfg(test)] |
| 2796 | mod verify_boundary_tests { |
| 2797 | use super::*; |
| 2798 | use crate::requirements::analyze; |
| 2799 | |
| 2800 | const DOC: &str = "filename: DOC.md\na\nb\nc\n"; |
| 2801 | |
| 2802 | fn recorded(text: &str) -> SkillOutput { |
| 2803 | (Ok(text.to_string()), Vec::new()) |
| 2804 | } |
| 2805 | |
| 2806 | #[test] |
| 2807 | fn verify_accepts_exactly_the_recorded_bytes_that_meet_the_goal() { |
| 2808 | let ex = analyze("write DOC.md in at least 3 lines"); |
| 2809 | let out = recorded(DOC); |
| 2810 | let h = proposal_handle(DOC); |
| 2811 | assert!(verify_task_result(Some(&ex), Some(&out), h)); |
| 2812 | // a result naming other bytes is refused |
| 2813 | assert!(!verify_task_result(Some(&ex), Some(&out), h ^ 1)); |
| 2814 | // bytes that no longer meet the requirement are refused |
| 2815 | let short = analyze("write DOC.md in at least 4 lines"); |
| 2816 | assert!(!verify_task_result(Some(&short), Some(&out), h)); |
| 2817 | // a skill that returned no proposal is refused |
| 2818 | let none: SkillOutput = (Err("no".into()), Vec::new()); |
| 2819 | assert!(!verify_task_result(Some(&ex), Some(&none), h)); |
| 2820 | assert!(!verify_task_result(Some(&ex), None, h)); |
| 2821 | } |
| 2822 | |
| 2823 | /// Issue #289: an absent requirement record used to become an empty list, |
| 2824 | /// so the verify step approved any well-formed file. |
| 2825 | #[test] |
| 2826 | fn missing_requirement_record_is_refused_never_empty() { |
| 2827 | let out = recorded(DOC); |
| 2828 | let h = proposal_handle(DOC); |
| 2829 | // the same bytes that pass with a record are refused without one |
| 2830 | let ex = analyze("write DOC.md in at least 3 lines"); |
| 2831 | assert!(verify_task_result(Some(&ex), Some(&out), h)); |
| 2832 | assert!(!verify_task_result(None, Some(&out), h)); |
| 2833 | // and even a goal with no requirements needs its (empty) record |
| 2834 | let empty = analyze("write DOC.md"); |
| 2835 | assert!(verify_task_result(Some(&empty), Some(&out), h)); |
| 2836 | assert!(!verify_task_result(None, Some(&out), h)); |
| 2837 | } |
| 2838 | |
| 2839 | #[test] |
| 2840 | fn uncertain_goal_is_refused_at_verify_even_when_bytes_look_fine() { |
| 2841 | let ex = analyze("write DOC.md with at least 3 lines of context"); |
| 2842 | assert!(!ex.uncertain.is_empty()); |
| 2843 | assert!(!verify_task_result( |
| 2844 | Some(&ex), |
| 2845 | Some(&recorded(DOC)), |
| 2846 | proposal_handle(DOC) |
| 2847 | )); |
| 2848 | } |
| 2849 | |
| 2850 | #[test] |
| 2851 | fn refused_without_model_records_one_refused_attempt() { |
| 2852 | let (out, a) = refused_without_model(MISSING_RECORD_REASON.into()); |
| 2853 | assert_eq!(out.unwrap_err(), MISSING_RECORD_REASON); |
| 2854 | assert_eq!(a.len(), 1); |
| 2855 | assert_eq!(a[0].outcome, "refused"); |
| 2856 | assert!(a[0].text.is_none()); |
| 2857 | } |
| 2858 | } |
| 2859 | |
| 2860 | #[cfg(test)] |
| 2861 | mod verify_callback_integration_tests { |
| 2862 | use super::*; |
| 2863 | |
| 2864 | fn bridge(dir: &std::path::Path) -> ComposeBridge { |
| 2865 | let proposer: ComposeProposer = Arc::new(|_: &str, _: std::time::Duration| { |
| 2866 | Ok(Generation { |
| 2867 | text: "filename: DOC.md\na\nb\nc\n".into(), |
| 2868 | finish_reason: Some("eos".into()), |
| 2869 | ..Default::default() |
| 2870 | }) |
| 2871 | }); |
| 2872 | ComposeBridge::new(dir.join("compose"), proposer, "test:verify-callback") |
| 2873 | } |
| 2874 | |
| 2875 | /// Issue #289 through the real compose run and the real verify callback: |
| 2876 | /// the same document commits with its requirement record and is refused |
| 2877 | /// by AEGIS (nothing committed, no promotion) when the record is gone. |
| 2878 | #[test] |
| 2879 | fn lost_requirement_record_is_refused_by_the_real_verify_callback() { |
| 2880 | let _home = crate::home_guard::home_slot(); |
| 2881 | if !aien_omega_compose::LINKED { |
| 2882 | return; |
| 2883 | } |
| 2884 | let tmp = tempfile::tempdir().unwrap(); |
| 2885 | let ws = tmp.path().join("ws"); |
| 2886 | std::fs::create_dir_all(&ws).unwrap(); |
| 2887 | let b = bridge(tmp.path()); |
| 2888 | let ok = b.run_task("write DOC.md in at least 3 lines", ws.to_str().unwrap()); |
| 2889 | let ControlResponse::ComposeTaskResult(ok) = ok else { |
| 2890 | panic!("{ok:?}") |
| 2891 | }; |
| 2892 | assert!(ok.committed, "{ok:?}"); |
| 2893 | let goal = format!("write DOC2.md in at least 3 lines {TEST_DROP_RECORD_MARKER}"); |
| 2894 | let lost = b.run_task(&goal, ws.to_str().unwrap()); |
| 2895 | let ControlResponse::ComposeTaskResult(lost) = lost else { |
| 2896 | panic!("{lost:?}") |
| 2897 | }; |
| 2898 | assert!(!lost.committed, "{lost:?}"); |
| 2899 | assert_eq!(lost.aegis_pass_mask & 1, 0, "{lost:?}"); |
| 2900 | assert_eq!(lost.cx_promotion, 0, "{lost:?}"); |
| 2901 | } |
| 2902 | } |
| 2903 | |
| 2904 | #[cfg(test)] |
| 2905 | mod destination_enforcement_tests { |
| 2906 | use super::*; |
| 2907 | |
| 2908 | #[test] |
| 2909 | fn reply_must_write_the_named_destination() { |
| 2910 | let ok = "filename: docs/SUMMARY.md\n# s\n".to_string(); |
| 2911 | let tmp = tempfile::tempdir().unwrap(); |
| 2912 | let ws = tmp.path().to_path_buf(); |
| 2913 | let run = |d: Option<&str>, t: &str| { |
| 2914 | enforce_destination((Ok(t.to_string()), vec![]), d, &ws, false).0 |
| 2915 | }; |
| 2916 | assert_eq!(run(Some("docs/SUMMARY.md"), &ok), Ok(ok.clone())); |
| 2917 | let e = run(Some("README.md"), &ok).unwrap_err(); |
| 2918 | assert!( |
| 2919 | e.contains("docs/SUMMARY.md") && e.contains("README.md"), |
| 2920 | "{e}" |
| 2921 | ); |
| 2922 | assert_eq!(run(None, &ok), Ok(ok)); |
| 2923 | } |
| 2924 | } |
| 2925 | |
| 2926 | #[cfg(test)] |
| 2927 | mod new_document_overwrite_tests { |
| 2928 | use super::*; |
| 2929 | |
| 2930 | #[test] |
| 2931 | fn new_kind_proposal_never_replaces_an_existing_file() { |
| 2932 | let tmp = tempfile::tempdir().unwrap(); |
| 2933 | let ws = tmp.path(); |
| 2934 | std::fs::write(ws.join("README.md"), "# r\n").unwrap(); |
| 2935 | std::os::unix::fs::symlink("nowhere", ws.join("dangling.md")).unwrap(); |
| 2936 | let run = |dest: Option<&str>, path: &str, edit: bool| { |
| 2937 | let t = format!("filename: {path}\nbody\n"); |
| 2938 | enforce_destination((Ok(t), vec![]), dest, ws, edit).0 |
| 2939 | }; |
| 2940 | for dest in [None, Some("README.md")] { |
| 2941 | let e = run(dest, "README.md", false).unwrap_err(); |
| 2942 | assert!(e.contains("already exists"), "{e}"); |
| 2943 | } |
| 2944 | assert!(run(None, "dangling.md", false).is_err()); |
| 2945 | assert!(run(None, "fresh.md", false).is_ok()); |
| 2946 | // An edit-kind task may write its own (existing) target. |
| 2947 | assert!(run(Some("README.md"), "README.md", true).is_ok()); |
| 2948 | } |
| 2949 | } |
| 2950 | |
| 2951 | #[cfg(test)] |
| 2952 | mod folder_destination_enforcement_tests { |
| 2953 | use super::*; |
| 2954 | |
| 2955 | #[test] |
| 2956 | fn proposal_in_the_folder_is_accepted_for_ctrl_goal() { |
| 2957 | let tmp = tempfile::tempdir().unwrap(); |
| 2958 | std::fs::create_dir(tmp.path().join("outbox")).unwrap(); |
| 2959 | let ws = std::fs::canonicalize(tmp.path()).unwrap(); |
| 2960 | let goal = "Write a file named ctrl.md in the outbox folder containing one line: control."; |
| 2961 | let dest = task_decision(goal, &ws).unwrap().1; |
| 2962 | let t = "filename: outbox/ctrl.md\ncontrol\n".to_string(); |
| 2963 | let r = enforce_destination((Ok(t.clone()), vec![]), dest.as_deref(), &ws, false).0; |
| 2964 | assert_eq!(r, Ok(t)); |
| 2965 | } |
| 2966 | } |
| 2967 | |
| 2968 | #[cfg(test)] |
| 2969 | mod append_placement_tests { |
| 2970 | use super::*; |
| 2971 | |
| 2972 | const PRIOR: &str = "# Report\n\nOne.\nTwo.\nThree.\n"; |
| 2973 | const APPEND: &str = "Append one line to report.md naming the topic."; |
| 2974 | |
| 2975 | #[test] |
| 2976 | fn append_goal_places_new_lines_at_end() { |
| 2977 | let placement = EditPlacement::for_goal(APPEND); |
| 2978 | let out = merge_edit_reply_placed(PRIOR, "# Report\nThe topic is harbours.\n", placement) |
| 2979 | .unwrap(); |
| 2980 | assert_eq!(out, format!("{PRIOR}The topic is harbours.\n")); |
| 2981 | } |
| 2982 | |
| 2983 | #[test] |
| 2984 | fn append_goal_with_several_new_lines_keeps_reply_order() { |
| 2985 | let placement = EditPlacement::for_goal(APPEND); |
| 2986 | let out = merge_edit_reply_placed(PRIOR, "# Report\nNew A.\nNew B.\nNew C.\n", placement) |
| 2987 | .unwrap(); |
| 2988 | assert_eq!(out, format!("{PRIOR}New A.\nNew B.\nNew C.\n")); |
| 2989 | } |
| 2990 | |
| 2991 | #[test] |
| 2992 | fn non_append_goal_keeps_anchor_placement() { |
| 2993 | let placement = EditPlacement::for_goal("Add a line under the heading of report.md"); |
| 2994 | assert_eq!(placement, EditPlacement::NextToAnchor); |
| 2995 | let reply = "# Report\nNew line.\n"; |
| 2996 | let out = merge_edit_reply_placed(PRIOR, reply, placement).unwrap(); |
| 2997 | assert_eq!(out, "# Report\nNew line.\n\nOne.\nTwo.\nThree.\n"); |
| 2998 | assert_eq!(out, merge_edit_reply(PRIOR, reply).unwrap()); |
| 2999 | } |
| 3000 | |
| 3001 | #[test] |
| 3002 | fn append_goal_still_needs_a_shared_line() { |
| 3003 | let placement = EditPlacement::for_goal(APPEND); |
| 3004 | assert!(merge_edit_reply_placed(PRIOR, "Nothing shared.\n", placement).is_err()); |
| 3005 | assert!(merge_edit_reply_placed(PRIOR, "\n", placement).is_err()); |
| 3006 | assert!(merge_edit_reply_placed(PRIOR, PRIOR, placement).is_err()); |
| 3007 | } |
| 3008 | |
| 3009 | #[test] |
| 3010 | fn append_word_detection() { |
| 3011 | let at_end = |g: &str| EditPlacement::for_goal(g) == EditPlacement::AtEnd; |
| 3012 | assert!(at_end("Append one line")); |
| 3013 | assert!(at_end("append")); |
| 3014 | assert!(at_end("APPEND")); |
| 3015 | assert!(at_end("Please, append: a line to report.md.")); |
| 3016 | assert!(!at_end("Add a line under the heading of report.md")); |
| 3017 | assert!(!at_end("Write the appendix")); |
| 3018 | assert!(!at_end("The appended line")); |
| 3019 | } |
| 3020 | } |
| 3021 | |
| 3022 | /// sc#402 (RUN-3-GB10 E4): a leading `./` names the same workspace file as |
| 3023 | /// the bare relative path; every other unsafe or non-plain form stays refused. |
| 3024 | #[cfg(test)] |
| 3025 | mod dotslash_tests { |
| 3026 | use super::*; |
| 3027 | |
| 3028 | fn path_of(name: &str) -> Result<String, String> { |
| 3029 | check_file_proposal(&format!("filename: {name}\n# Report\nbody\n")).map(|p| p.path) |
| 3030 | } |
| 3031 | |
| 3032 | #[test] |
| 3033 | fn leading_dot_slash_names_the_bare_path() { |
| 3034 | assert_eq!(path_of("./report.md"), Ok("report.md".into())); |
| 3035 | assert_eq!(path_of("././a/b.md"), Ok("a/b.md".into())); |
| 3036 | assert_eq!(path_of("`./report.md`"), Ok("report.md".into())); |
| 3037 | assert_eq!(path_of("report.md"), Ok("report.md".into())); |
| 3038 | } |
| 3039 | |
| 3040 | #[test] |
| 3041 | fn every_other_form_is_refused_as_before() { |
| 3042 | for bad in [ |
| 3043 | "../x", "./../x", "/x", "a/../b", "a/./b", ".", "./", "~/x", ".//x", "a//b", "a\\b", |
| 3044 | ] { |
| 3045 | assert!(path_of(bad).is_err(), "{bad:?} must stay refused"); |
| 3046 | } |
| 3047 | assert!(check_file_proposal("filename: \n# R\nbody\n").is_err()); |
| 3048 | assert!( |
| 3049 | check_relative_path("./report.md").is_err(), |
| 3050 | "the strict check stays strict" |
| 3051 | ); |
| 3052 | } |
| 3053 | |
| 3054 | #[test] |
| 3055 | fn an_edit_reply_naming_dot_slash_merges_into_the_named_file() { |
| 3056 | let prior = "# Report\n\nOne.\n"; |
| 3057 | let out = edit_proposal_placed( |
| 3058 | "filename: ./report.md\n# Report\n\nOne.\nThe topic is harbours.\n", |
| 3059 | Some(("report.md", prior)), |
| 3060 | EditPlacement::for_goal("Append one line to report.md naming the topic."), |
| 3061 | ) |
| 3062 | .unwrap(); |
| 3063 | assert_eq!( |
| 3064 | out, |
| 3065 | "filename: report.md\n# Report\n\nOne.\nThe topic is harbours.\n" |
| 3066 | ); |
| 3067 | } |
| 3068 | } |
| 3069 | |
| 3070 | /// The daemon proposer's timeout text (server.rs `wall_clock_reason`) and the |
| 3071 | /// classifier that records an attempt as "timeout" share one prefix; a cut at |
| 3072 | /// the token limit never carries it. Internal seam: the interface tests feed |
| 3073 | /// the literal text, so this pins the daemon's own function to it. |
| 3074 | #[cfg(test)] |
| 3075 | mod wall_clock_reason_tests { |
| 3076 | use super::*; |
| 3077 | use std::time::Duration; |
| 3078 | |
| 3079 | #[test] |
| 3080 | fn token_cut_and_wall_clock_reasons_are_distinct() { |
| 3081 | assert_eq!(wall_clock_reason(5), "model proposal exceeded 5 ms"); |
| 3082 | let cut = |_: &str, _: Duration| { |
| 3083 | Ok(Generation { |
| 3084 | text: "filename: a.md\nline\n".into(), |
| 3085 | tokens: 1024, |
| 3086 | finish_reason: Some("max_tokens".into()), |
| 3087 | ..Default::default() |
| 3088 | }) |
| 3089 | }; |
| 3090 | let (out, a) = propose_task_checked( |
| 3091 | &cut, |
| 3092 | "p", |
| 3093 | None, |
| 3094 | &[], |
| 3095 | Duration::from_secs(120), |
| 3096 | Duration::from_secs(30), |
| 3097 | 1, |
| 3098 | ); |
| 3099 | let why = out.expect_err("a cut reply is never a proposal"); |
| 3100 | assert_eq!(a[0].outcome, "refused"); |
| 3101 | assert!( |
| 3102 | why.contains( |
| 3103 | "reply cut at the token limit after 1024 tokens (finish_reason max_tokens)" |
| 3104 | ), |
| 3105 | "{why}" |
| 3106 | ); |
| 3107 | assert!(!why.contains("exceeded"), "{why}"); |
| 3108 | let slow = |_: &str, limit: Duration| -> Result<Generation, String> { |
| 3109 | Err(wall_clock_reason(limit.as_millis())) |
| 3110 | }; |
| 3111 | let (out, a) = propose_task_checked( |
| 3112 | &slow, |
| 3113 | "p", |
| 3114 | None, |
| 3115 | &[], |
| 3116 | Duration::from_secs(120), |
| 3117 | Duration::from_secs(30), |
| 3118 | 1, |
| 3119 | ); |
| 3120 | let why = out.expect_err("timed out"); |
| 3121 | assert_eq!(a[0].outcome, "timeout"); |
| 3122 | assert!( |
| 3123 | why.starts_with("model proposal exceeded ") && why.ends_with(" ms"), |
| 3124 | "{why}" |
| 3125 | ); |
| 3126 | assert!( |
| 3127 | !why.contains("token limit") && !why.contains("max_tokens"), |
| 3128 | "{why}" |
| 3129 | ); |
| 3130 | } |
| 3131 | } |
| 3132 | |
| 3133 | /// Issue #546: a first line whose byte 9 falls inside a multi-byte character |
| 3134 | /// must be refused with the normal reason, not panic. |
| 3135 | #[cfg(test)] |
| 3136 | mod multibyte_first_line_tests { |
| 3137 | use super::*; |
| 3138 | |
| 3139 | #[test] |
| 3140 | fn multibyte_first_line_is_refused_without_panic() { |
| 3141 | // "ééééé" is 10 bytes, so byte 9 is inside the fifth 'é'. |
| 3142 | for first in ["ééééé", "🙂🙂🙂", "é🙂 notes", "éfilename: a.md"] { |
| 3143 | let text = format!("{first}\nbody\n"); |
| 3144 | let err = check_file_proposal(&text).expect_err("must be refused"); |
| 3145 | assert!(err.contains("no filename line"), "{first:?}: {err}"); |
| 3146 | } |
| 3147 | } |
| 3148 | } |