Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-runtime/src/control.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-runtime / src / control.rs` 1104 lines ยท 43903 bytes Raw Blame History 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 //! Typed Operator Control Protocol and RuntimeController 17 //! Connects external operator CLI tools to the in-process runtime over local domain sockets. 18 19 use serde::{Deserialize, Serialize}; 20 use std::collections::HashSet; 21 22 #[derive(Debug, Clone, Serialize, Deserialize)] 23 pub struct LaunchSwarmReq { 24 pub model_handle: u64, 25 pub branch_count: usize, 26 pub max_active_sequences: usize, 27 pub max_tokens_per_branch: usize, 28 pub root_world_id: u64, 29 pub priority: u8, 30 pub prompt_tokens: Vec, 31 } 32 33 #[derive(Debug, Clone, Serialize, Deserialize)] 34 pub struct ChatTurn { 35 pub role: String, 36 pub content: String, 37 } 38 39 /// Role `tool` is refused on this path (issue #310): untrusted tool output must enter through 40 /// `aien_inference_abi::tool_boundary::ToolConversation`, which refuses control sequences and 41 /// checks call/result pairing. Otherwise a `ChatTurn` with role `tool` would reach the 42 /// byte-exact Qwen3 renderer unguarded. 43 fn refuse_tool_turns(messages: &[ChatTurn]) -> Result<(), aien_inference_abi::TokenizerError> { 44 if messages 45 .iter() 46 .any(|m| m.role.trim().eq_ignore_ascii_case("tool")) 47 { 48 return Err(aien_inference_abi::TokenizerError::ToolTurnRefused( 49 "role tool refused on the ChatTurn path: use tool_boundary::ToolConversation".into(), 50 )); 51 } 52 Ok(()) 53 } 54 55 /// Renders the chat with a model's template. Generation continues from an assistant 56 /// header unless the last turn is a non-empty assistant turn. Role `tool` and a plain model 57 /// (no chat template) are refused with an error, never a panic. 58 pub fn format_chat( 59 template: aien_inference_abi::ChatTemplate, 60 messages: &[ChatTurn], 61 ) -> Result { 62 try_format_chat(template, messages) 63 } 64 65 /// Same as [`format_chat`]; kept as the explicit fallible name. 66 pub fn try_format_chat( 67 template: aien_inference_abi::ChatTemplate, 68 messages: &[ChatTurn], 69 ) -> Result { 70 refuse_tool_turns(messages)?; 71 let turns: Vec<(&str, &str)> = messages 72 .iter() 73 .map(|m| (m.role.as_str(), m.content.as_str())) 74 .collect(); 75 template.try_render(&turns) 76 } 77 78 /// TinyLlama chat template. Generation always continues from an assistant header. 79 pub fn format_tinyllama_chat( 80 messages: &[ChatTurn], 81 ) -> Result { 82 format_chat(aien_inference_abi::ChatTemplate::Zephyr, messages) 83 } 84 85 #[derive(Debug, Clone, Serialize, Deserialize)] 86 pub enum ControlCommand { 87 LaunchSwarm(LaunchSwarmReq), 88 InspectSwarm(u64), 89 CancelSwarm(u64), 90 GetRuntimeStatus, 91 Shutdown, 92 /// One operator turn on the in-process PR #68 spine. The server streams 93 /// `TurnDelta` lines, then `TurnFinished` only for StopToken; token limits, 94 /// aborts and preemption terminate with a reason-bearing `Error`. 95 StreamTurn { 96 messages: Vec, 97 max_tokens: usize, 98 temperature: f32, 99 }, 100 /// NEXT-PHASE-1 cut 1b: one goal through omega COMPOSITION-2 (J-Space 101 /// alternatives, AEGIS verification, World commit, Cortex record) with a 102 /// "model" Skill that proposes one file change for `workspace`. Handled on 103 /// the socket connection (it runs inference). Nothing is written to 104 /// `workspace` in this cut: the committed result is the proposal record. 105 RunComposeTask { 106 goal: String, 107 workspace: String, 108 /// ALLEN memory context for this task (`personal`, `work`, `project:`), 109 /// supplied by the operator only. `None`: no memory is included. 110 #[serde(default)] 111 context: Option, 112 }, 113 /// NEXT-PHASE-1 cut 2: append one operator record (`kind` = "constraint", 114 /// "authorization" or "effect") to the composition's Cortex journal through 115 /// its own writer. `links` name related Cortex ids (each must exist). 116 ComposeNote { 117 kind: String, 118 text: String, 119 links: Vec, 120 }, 121 /// NEXT-PHASE-1 cut 2: recall every host record (constraints, authorizations, 122 /// effects, repair records) plus the records named in `ids`, each digest 123 /// re-checked; `prefix` (records 1..=prefix) gets a digest over their digests 124 /// so a restart can be compared byte for byte. 125 ComposeRecall { 126 ids: Vec, 127 prefix: Option, 128 }, 129 /// NEXT-PHASE-1 cut 2: operator repair of a compose home that refuses to open 130 /// (torn journal tail, or a journal behind its J-Space anchor). Closes this 131 /// process's handle first; the cut is recorded in the journal. 132 RecoverComposeHome, 133 /// ALLEN persona profile (arch#159): identity, profile, model and unsupported 134 /// facilities in one answer. Handled on the socket connection. 135 AllenStatus, 136 /// The saved profile (or the defaults when none). 137 AllenProfileShow, 138 /// Change the profile; `expected_revision` is the compare-and-swap guard. 139 AllenProfileSet { 140 expected_revision: u64, 141 changes: aien_allen_profile::Changes, 142 }, 143 /// Every saved revision, oldest first. 144 AllenProfileHistory, 145 /// Write a NEW revision that copies revision `to`. 146 AllenProfileRevert { 147 expected_revision: u64, 148 to: u64, 149 }, 150 /// Write a NEW revision with the defaults. The identity is untouched. 151 AllenProfileReset { 152 expected_revision: u64, 153 }, 154 /// ALLEN scoped memory (arch#159). `context` is parsed by the daemon from this 155 /// operator command only; no model text or file content ever reaches it. 156 AllenMemoryPut { 157 context: String, 158 /// `fact` or `preference`. 159 kind: String, 160 text: String, 161 }, 162 AllenMemoryRecall { 163 context: String, 164 query: Option, 165 }, 166 /// One context, or `owner` = true for every context (exactly one of the two). 167 AllenMemoryInspect { 168 context: Option, 169 owner: bool, 170 }, 171 AllenMemoryCorrect { 172 context: String, 173 item: String, 174 text: String, 175 }, 176 /// Forget one `item`, or everything in `context` (`all_in_context`); exactly one. 177 AllenMemoryForget { 178 context: String, 179 item: Option, 180 all_in_context: bool, 181 }, 182 AllenMemoryExport { 183 context: Option, 184 owner: bool, 185 }, 186 AllenGoalsList { 187 context: Option, 188 owner: bool, 189 }, 190 AllenGoalAdd { 191 context: String, 192 text: String, 193 }, 194 AllenGoalClose { 195 context: String, 196 item: String, 197 }, 198 /// NEXT-PHASE-2: the effect-boundary checks and the durable intent, in one 199 /// step (ACCEPTANCE-v2 2.1, 2.3). Answered with `ComposeNoted` (the intent). 200 ComposeEffectIntent { 201 authorization: u64, 202 proposal_sha256: String, 203 path: String, 204 target: String, 205 content_sha256: String, 206 executor_pid: u32, 207 executor_start: u64, 208 }, 209 /// NEXT-PHASE-2: the executor's report after the write; the daemon records 210 /// the state it reads from the world. Answered with `ComposeNoted`. 211 ComposeEffectAck { 212 intent: u64, 213 reported: serde_json::Value, 214 }, 215 /// NEXT-PHASE-2: reconcile unsettled effects, or record one operator 216 /// declaration (ACCEPTANCE-v2 2.4). 217 ComposeReconcile { 218 declare: Option, 219 }, 220 /// sovereign-core #249: one approved proposal through the proposer hook 221 /// (crate::approved): desk-key MAC authentication, a durable replay claim, 222 /// then the production compose run (J-Space, AEGIS verify, World commit, 223 /// Cortex records) with `workspace` as the task's workspace. Answered with 224 /// `ComposeApprovedResult` or `ComposeApprovedRefused`. Writes nothing to 225 /// `workspace`; the effect still needs an authorization, an intent and an ack. 226 ComposeApprovedProposal { 227 proposal: crate::approved::ApprovedProposal, 228 workspace: String, 229 }, 230 /// sovereign-core #261: the operator approves ONE proposal this daemon 231 /// committed (`RunComposeTask`), and the daemon mints the grant itself. 232 /// The caller names only the promotion, the proposal digest, the workspace 233 /// it expects and who approves; path, content and target come from the 234 /// daemon's own commit record. Answered with `ComposeNoted` (the grant). 235 /// This replaces a client-written `authorization` note, which is refused. 236 ComposeAuthorize { 237 cx_promotion: u64, 238 proposal_sha256: String, 239 workspace: String, 240 approver: String, 241 constraints: Vec, 242 /// sovereign-core #297: the approval desk's MAC over this authorize. 243 /// Optional on the wire (old clients omit it; `None` is not written). 244 /// Required only when the daemon runs with the desk switch ON. 245 #[serde(default, skip_serializing_if = "Option::is_none")] 246 desk_proof: Option, 247 /// sovereign-core #408: the objective record this approval is for 248 /// (`compose propose --objective-id`). Optional on the wire; `None` is 249 /// not written and mints exactly as before. When given, the daemon 250 /// re-reads the record and binds the grant to it, or refuses by name. 251 #[serde(default, skip_serializing_if = "Option::is_none")] 252 objective_id: Option, 253 }, 254 /// NEXT-PHASE-2: operator `stop`, `resume`, `revoke` (ACCEPTANCE-v2 2.5, 2.6). 255 ComposeControl { 256 action: String, 257 approver: String, 258 authorization: Option, 259 }, 260 } 261 262 /// The desk key's proof for one `ComposeAuthorize` (sovereign-core #297): a 263 /// fresh nonce and the HMAC over the authorize binding 264 /// (`approved_auth::AuthorizeBinding`). 265 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 266 pub struct DeskProof { 267 pub nonce: String, 268 pub mac: String, 269 } 270 271 /// An operator's decision for one unsettled effect. 272 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 273 pub struct ReconcileDeclare { 274 pub intent: u64, 275 /// "done" or "not_done". 276 pub state: String, 277 pub approver: String, 278 } 279 280 #[derive(Debug, Clone, Serialize, Deserialize)] 281 pub struct ControlEnvelope { 282 pub protocol_version: u16, 283 pub request_id: u64, 284 pub operation_id: u128, 285 pub operator_session: u64, 286 pub command: ControlCommand, 287 } 288 289 #[derive(Debug, Clone, Serialize, Deserialize)] 290 pub struct RuntimeStatusReport { 291 pub active_sequences: usize, 292 pub active_swarms: usize, 293 pub active_worlds: usize, 294 /// Alias of `kv_pool_free_blocks` (kept for existing clients). 295 pub free_kv_blocks: usize, 296 /// Alias of `kv_pool_total_blocks` (kept for existing clients). 297 pub total_kv_blocks: usize, 298 pub shared_kv_pages: usize, 299 pub cow_faults: usize, 300 pub gpu_utilization_pct: f32, 301 /// The one pool allocation in bytes (`KvLayout::total_bytes`). Constant 302 /// after start: freeing blocks does not release RAM (METRICS_AND_SETTINGS). 303 /// 0 for a manager without a tensor pool. 304 #[serde(default)] 305 pub kv_pool_allocated_bytes: u64, 306 #[serde(default)] 307 pub kv_pool_total_blocks: usize, 308 #[serde(default)] 309 pub kv_pool_free_blocks: usize, 310 #[serde(default)] 311 pub kv_pool_used_blocks: usize, 312 /// Blocks referenced by storage holders (park sources, restore destinations). 313 #[serde(default)] 314 pub kv_pool_holder_blocks: usize, 315 /// Persistent KV (ADR 0003); `None` when `AIEN_KV_STORE_DIR` is unset. 316 #[serde(default)] 317 pub kv_persist: Option>, 318 } 319 320 /// Persistent-KV status fields, named as in docs/persistent-kv/METRICS_AND_SETTINGS.md. 321 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] 322 pub struct KvPersistReport { 323 /// `recovering`, `open`, `degraded` or `failed`. 324 pub kv_store_state: String, 325 pub kv_store_persisted_bytes: u64, 326 pub kv_store_persisted_objects: u64, 327 pub kv_store_quota_bytes: u64, 328 pub kv_store_max_objects: u64, 329 pub kv_store_over_cap: bool, 330 pub kv_store_reserved_bytes: u64, 331 pub kv_store_unindexed_bytes: u64, 332 pub kv_store_unindexed_objects: u64, 333 pub kv_store_inflight_ops: u64, 334 pub kv_store_inflight_bytes: u64, 335 pub kv_store_restore_ops: u64, 336 pub kv_store_park_ops: u64, 337 pub kv_restore_inflight_blocks: u64, 338 pub kv_park_jobs_total: u64, 339 pub kv_park_bytes_total: u64, 340 pub kv_park_failed_total: u64, 341 pub kv_park_dedup_total: u64, 342 pub kv_park_indeterminate_total: u64, 343 pub kv_restore_jobs_total: u64, 344 pub kv_restore_bytes_total: u64, 345 pub kv_restore_failed_total: u64, 346 pub kv_restore_coalesced_total: u64, 347 pub kv_restore_fallback_prefill_total: u64, 348 pub kv_restore_retry_suppressed_total: u64, 349 pub kv_restore_tokens_total: u64, 350 pub kv_store_stale_completions_total: u64, 351 pub kv_store_cancelled_total: u64, 352 pub kv_store_queue_full_total: u64, 353 /// Empty unless persistence was refused at start (ADR 0003 section 20): 354 /// `key_missing` or `key_malformed` (`AIEN_KV_STORE_KEY`). With a reason the 355 /// state is `refused`: no park, no restore, every prompt is prefilled. 356 #[serde(default)] 357 pub kv_store_refused_reason: String, 358 /// Process total of store-key refusals (missing or malformed key). 359 #[serde(default)] 360 pub kv_store_key_refused_total: u64, 361 /// Process total of loads whose authenticated decryption failed (wrong 362 /// key, tampered bytes, swapped identity header); each object was 363 /// discarded and its prefix recomputed. Old plaintext-format files are 364 /// discarded at recovery and counted as corrupt there. 365 #[serde(default)] 366 pub kv_store_seal_rejected_total: u64, 367 } 368 369 #[derive(Debug, Clone, Serialize, Deserialize)] 370 pub enum ControlResponse { 371 SwarmAccepted { 372 swarm_id: u64, 373 operation_id: u128, 374 }, 375 SwarmCancelled { 376 swarm_id: u64, 377 }, 378 Status(RuntimeStatusReport), 379 ShutdownAck, 380 TurnDelta { 381 text: String, 382 }, 383 /// A normally stopped answer, never a token-limited/aborted/preempted turn. 384 TurnFinished { 385 text: String, 386 total_tokens: usize, 387 /// Compose ledger id of the daemon's generation record for this turn 388 /// (docs/DAEMON_GENERATION_RECORD.md). `None` = no record, no claim: 389 /// no ledger, no model identity, or the append failed. 390 #[serde(default, skip_serializing_if = "Option::is_none")] 391 generation_record: Option, 392 }, 393 /// Result record of `RunComposeTask`. 394 ComposeTaskResult(Box), 395 /// Result of `AllenStatus`. 396 AllenStatusReport(Box), 397 /// Result of `AllenProfileShow`, `AllenProfileSet`, `AllenProfileRevert`, `AllenProfileReset`. 398 AllenProfile(Box), 399 /// Result of `AllenProfileHistory`. 400 AllenHistory(Box), 401 /// A profile command was refused; nothing was changed. 402 AllenRefused(Box), 403 /// Result of an `AllenMemory*` or `AllenGoal*` command. 404 AllenMemoryResult(Box), 405 /// Result of `ComposeNote`. 406 ComposeNoted(ComposeNoteReport), 407 /// Result of `ComposeRecall`. 408 ComposeRecalled(Box), 409 /// Result of `RecoverComposeHome`. 410 ComposeRecovered(Box), 411 /// Result of `ComposeReconcile`. 412 ComposeReconciled(Box), 413 /// Result of `ComposeControl`. 414 ComposeControlled(Box), 415 /// `ComposeApprovedProposal` committed (state COMMITTED or ALREADY_COMMITTED). 416 ComposeApprovedResult(Box), 417 /// `ComposeApprovedProposal` refused (named; nothing ran unless the 418 /// refusal says the run happened). 419 ComposeApprovedRefused(Box), 420 Error(String), 421 } 422 423 /// Actor managing operator sessions and enforcing idempotent command execution. 424 /// Processed operation IDs persist to disk so idempotency survives restarts. 425 /// 426 /// The state file path is fixed when the controller is built (#275): a later 427 /// change of `AIEN_RUNTIME_STATE_DIR` never redirects its writes. Every save 428 /// is a read-merge-write under an exclusive `flock` on `.lock`, through 429 /// a temp file unique to that write, fsynced, then renamed (#299). Two 430 /// controllers sharing one file (threads or processes) therefore never tear 431 /// it and never drop each other's ids. 432 pub struct RuntimeController { 433 processed_operations: HashSet, 434 state_path: std::path::PathBuf, 435 } 436 437 /// The state file: `$AIEN_RUNTIME_STATE_DIR/processed_operations.json`, else 438 /// the machine-wide `/tmp/aien-runtime-processed-ops.json`. Unit tests of this 439 /// crate fall back to a per-process directory instead, so no lib test reads 440 /// state another program wrote. 441 fn operations_state_path() -> std::path::PathBuf { 442 if let Ok(dir) = std::env::var("AIEN_RUNTIME_STATE_DIR") { 443 if !dir.trim().is_empty() { 444 return std::path::PathBuf::from(dir.trim()).join("processed_operations.json"); 445 } 446 } 447 #[cfg(test)] 448 { 449 let dir = std::env::temp_dir().join(format!("aien-runtime-unit-{}", std::process::id())); 450 let _ = std::fs::create_dir_all(&dir); 451 dir.join("processed_operations.json") 452 } 453 #[cfg(not(test))] 454 std::path::PathBuf::from("/tmp/aien-runtime-processed-ops.json") 455 } 456 457 /// Reads the ids in `path`. Absent = empty; unreadable or unparsable = error. 458 fn read_operations(path: &std::path::Path) -> Result, String> { 459 match std::fs::read(path) { 460 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), 461 Err(e) => Err(format!("idempotency state {}: {e}", path.display())), 462 Ok(bytes) => serde_json::from_slice::>(&bytes).map_err(|e| { 463 format!( 464 "idempotency state {} is damaged ({e}); refusing to start rather than forget processed operations", 465 path.display() 466 ) 467 }), 468 } 469 } 470 471 /// Exclusive advisory lock on `.lock`, released on drop. 472 struct StateLock(std::fs::File); 473 474 impl StateLock { 475 fn acquire(path: &std::path::Path) -> Result { 476 use std::os::fd::AsRawFd; 477 let lock_path = path.with_extension("json.lock"); 478 let file = std::fs::OpenOptions::new() 479 .create(true) 480 .truncate(false) 481 .write(true) 482 .open(&lock_path) 483 .map_err(|e| format!("idempotency lock {}: {e}", lock_path.display()))?; 484 loop { 485 // SAFETY: flock on a file descriptor this function owns. 486 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } == 0 { 487 return Ok(Self(file)); 488 } 489 let e = std::io::Error::last_os_error(); 490 if e.kind() != std::io::ErrorKind::Interrupted { 491 return Err(format!("idempotency lock {}: {e}", lock_path.display())); 492 } 493 } 494 } 495 } 496 497 impl Drop for StateLock { 498 fn drop(&mut self) { 499 use std::os::fd::AsRawFd; 500 // SAFETY: unlock the descriptor locked in acquire (close would too). 501 unsafe { libc::flock(self.0.as_raw_fd(), libc::LOCK_UN) }; 502 } 503 } 504 505 static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); 506 507 impl Default for RuntimeController { 508 fn default() -> Self { 509 Self::new() 510 } 511 } 512 513 impl RuntimeController { 514 /// Panics when the state file exists but is damaged (see [`Self::load`]); 515 /// the daemon calls `load` first and refuses to start instead. 516 pub fn new() -> Self { 517 Self::load().unwrap_or_else(|e| panic!("{e}")) 518 } 519 520 /// Loads the persisted operation ids from the default state file. An 521 /// absent file is an empty set; a file that cannot be read or parsed is 522 /// an error (NEXT-PHASE-2, ACCEPTANCE-v2 2.8): idempotency state is never 523 /// reset silently. 524 pub fn load() -> Result { 525 Self::load_from(operations_state_path()) 526 } 527 528 /// [`Self::load`] for an explicit state file, independent of the 529 /// environment. 530 pub fn load_from(state_path: std::path::PathBuf) -> Result { 531 let ids = read_operations(&state_path)?; 532 Ok(Self { 533 processed_operations: ids.into_iter().collect(), 534 state_path, 535 }) 536 } 537 538 /// The file this controller reads and writes. 539 pub fn state_path(&self) -> &std::path::Path { 540 &self.state_path 541 } 542 543 pub fn is_operation_processed(&self, op_id: u128) -> bool { 544 self.processed_operations.contains(&op_id) 545 } 546 547 /// Records `op_id` in memory and on disk. The id stays recorded in memory 548 /// even when the disk write fails; the error says the record is not 549 /// durable (a restart would forget it). A damaged file on disk is an 550 /// error and is never overwritten. 551 pub fn mark_operation_processed(&mut self, op_id: u128) -> Result<(), String> { 552 self.processed_operations.insert(op_id); 553 let _lock = StateLock::acquire(&self.state_path)?; 554 // Merge with what other controllers on this file recorded meanwhile. 555 let on_disk = read_operations(&self.state_path)?; 556 self.processed_operations.extend(on_disk); 557 let ids: Vec = self.processed_operations.iter().copied().collect(); 558 let bytes = serde_json::to_vec(&ids).map_err(|e| format!("idempotency state: {e}"))?; 559 // Write a temp file unique to this write, sync, then rename: a crash 560 // or a concurrent writer never leaves a truncated state file. 561 let tmp = self.state_path.with_extension(format!( 562 "json.tmp.{}.{}", 563 std::process::id(), 564 TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) 565 )); 566 let write = || -> std::io::Result<()> { 567 use std::io::Write; 568 let mut f = std::fs::File::create(&tmp)?; 569 f.write_all(&bytes)?; 570 f.sync_all()?; 571 std::fs::rename(&tmp, &self.state_path) 572 }; 573 write().map_err(|e| { 574 let _ = std::fs::remove_file(&tmp); 575 format!( 576 "idempotency state {}: write failed ({e}); operation {op_id:#x} is not durable", 577 self.state_path.display() 578 ) 579 }) 580 } 581 } 582 583 #[cfg(test)] 584 mod tests { 585 use super::*; 586 587 fn state_file(dir: &tempfile::TempDir) -> std::path::PathBuf { 588 dir.path().join("processed_operations.json") 589 } 590 591 #[test] 592 fn idempotency_survives_restart() { 593 // Explicit path: this test never sets the process-wide 594 // AIEN_RUNTIME_STATE_DIR other tests in this binary read (#275). 595 let dir = tempfile::tempdir().unwrap(); 596 let path = state_file(&dir); 597 let op_id = 0xC0FFEEu128; 598 599 { 600 let mut first = RuntimeController::load_from(path.clone()).unwrap(); 601 assert!(!first.is_operation_processed(op_id)); 602 first.mark_operation_processed(op_id).unwrap(); 603 assert!(first.is_operation_processed(op_id)); 604 } 605 606 // Simulate a process restart: a fresh controller reloads from disk. 607 { 608 let second = RuntimeController::load_from(path.clone()).unwrap(); 609 assert!( 610 second.is_operation_processed(op_id), 611 "replayed operation ID must be rejected after restart" 612 ); 613 } 614 615 // NEXT-PHASE-2: a damaged state file is refused, never reset. 616 std::fs::write(&path, b"{").unwrap(); 617 let err = RuntimeController::load_from(path.clone()) 618 .err() 619 .expect("damaged state must be refused"); 620 assert!(err.contains("is damaged"), "{err}"); 621 std::fs::write(&path, b"[1, 2").unwrap(); 622 assert!(RuntimeController::load_from(path.clone()).is_err()); 623 // An empty file (what the #299 race left behind) is damaged too. 624 std::fs::write(&path, b"").unwrap(); 625 assert!(RuntimeController::load_from(path).is_err()); 626 } 627 628 #[test] 629 fn a_save_never_overwrites_damaged_state() { 630 let dir = tempfile::tempdir().unwrap(); 631 let path = state_file(&dir); 632 let mut c = RuntimeController::load_from(path.clone()).unwrap(); 633 std::fs::write(&path, b"[1, 2").unwrap(); 634 let err = c.mark_operation_processed(7).unwrap_err(); 635 assert!(err.contains("is damaged"), "{err}"); 636 assert_eq!( 637 std::fs::read(&path).unwrap(), 638 b"[1, 2", 639 "damaged file kept as found" 640 ); 641 assert!(c.is_operation_processed(7), "still recorded in memory"); 642 } 643 644 #[test] 645 fn concurrent_saves_never_damage_or_drop_state() { 646 // #299 root cause: every save used the temp name `json.tmp.`, so 647 // two controllers in one process truncated each other's temp file and 648 // renamed an empty file into place. Red on `12c1a5f`: "is damaged (EOF 649 // while parsing a value at line 1 column 0)". 650 let dir = tempfile::tempdir().unwrap(); 651 let path = state_file(&dir); 652 let threads: Vec<_> = (0..8u128) 653 .map(|t| { 654 let path = path.clone(); 655 std::thread::spawn(move || { 656 let mut c = RuntimeController::load_from(path).unwrap(); 657 for i in 0..200u128 { 658 c.mark_operation_processed(t * 1000 + i).unwrap(); 659 } 660 }) 661 }) 662 .collect(); 663 for t in threads { 664 t.join().unwrap(); 665 } 666 let after = RuntimeController::load_from(path).expect("state loads after concurrent saves"); 667 for t in 0..8u128 { 668 for i in 0..200u128 { 669 assert!( 670 after.is_operation_processed(t * 1000 + i), 671 "id {t}/{i} forgotten" 672 ); 673 } 674 } 675 } 676 677 #[test] 678 fn interrupted_save_leaves_the_last_good_state() { 679 // A process killed mid-save leaves its temp file (and the lock file) 680 // behind; the state file itself is the last complete write. 681 let dir = tempfile::tempdir().unwrap(); 682 let path = state_file(&dir); 683 let mut c = RuntimeController::load_from(path.clone()).unwrap(); 684 c.mark_operation_processed(1).unwrap(); 685 std::fs::write(path.with_extension("json.tmp.999999.0"), b"[1, 2, 3").unwrap(); 686 let mut restarted = RuntimeController::load_from(path.clone()).unwrap(); 687 assert!(restarted.is_operation_processed(1)); 688 assert!( 689 !restarted.is_operation_processed(3), 690 "half-written temp file is never read" 691 ); 692 restarted.mark_operation_processed(2).unwrap(); 693 let again = RuntimeController::load_from(path).unwrap(); 694 assert!(again.is_operation_processed(1) && again.is_operation_processed(2)); 695 } 696 697 #[test] 698 fn path_is_fixed_at_construction() { 699 // #275: a controller keeps writing where it loaded from, whatever a 700 // parallel test does to AIEN_RUNTIME_STATE_DIR afterwards. 701 let dir = tempfile::tempdir().unwrap(); 702 let path = state_file(&dir); 703 let mut c = RuntimeController::load_from(path.clone()).unwrap(); 704 assert_eq!(c.state_path(), path.as_path()); 705 c.mark_operation_processed(5).unwrap(); 706 assert!(RuntimeController::load_from(path) 707 .unwrap() 708 .is_operation_processed(5)); 709 } 710 711 #[test] 712 fn chat_template_opens_an_assistant_turn() { 713 let prompt = format_tinyllama_chat(&[ 714 ChatTurn { 715 role: "system".into(), 716 content: "You are AIEN.".into(), 717 }, 718 ChatTurn { 719 role: "user".into(), 720 content: "Status?".into(), 721 }, 722 ]) 723 .expect("chat"); 724 assert!(prompt.starts_with("<|system|>\nYou are AIEN.\n")); 725 assert!(prompt.contains("<|user|>\nStatus?\n")); 726 assert!(prompt.ends_with("<|assistant|>\n")); 727 } 728 } 729 730 /// The record of one `RunComposeTask` (omega rxc_host result, NEXT-PHASE-1). 731 /// Cortex ids name records in `/cortex.cx`; digests are hex. 732 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 733 pub struct ComposeTaskReport { 734 /// The daemon's compose-commit record for this run (#261), when it 735 /// committed a one-file proposal on the ordinary (non-approved) path. 736 #[serde(default)] 737 pub compose_commit: Option, 738 /// Ledger id of the generation record of the attempt the committed 739 /// proposal came from (arch#162). Evidence only; absent when no record 740 /// was written (no model identity, approved proposal, failed append). 741 #[serde(default)] 742 pub generation_record: Option, 743 /// Composition home (holds machine.id, cortex.cx, jspace). 744 pub compose_dir: String, 745 /// AienMachineId (32 bytes, hex) the home is bound to. 746 pub machine_id: String, 747 pub task: u64, 748 /// RXC_OUT_*: 1 committed, 2 no winner, 3 not committed, 4 not durable, 5 record failed. 749 pub outcome: i32, 750 pub committed: bool, 751 /// Staged J-Space branches forked (one per routed Skill alternative). 752 pub branch_count: u32, 753 pub branches_reclaimed: u32, 754 /// AEGIS verdict: index of the winning alternative (None = no winner) 755 /// and the pass mask (bit k = alternative k met the contract). 756 pub winner: Option, 757 pub aegis_pass_mask: u32, 758 pub cx_goal: u64, 759 pub cx_candidates: Vec, 760 pub cx_evidence: u64, 761 pub cx_promotion: u64, 762 pub cx_admissions: Vec, 763 pub winner_digest: String, 764 pub record_digest: String, 765 /// The committed proposal (the model Skill's output) and its sha256. 766 pub proposal: Option, 767 pub proposal_sha256: Option, 768 /// The proposal parsed as one file change (AEGIS contract): relative path 769 /// and the sha256 of the new content. 770 pub proposal_path: Option, 771 pub proposal_content_sha256: Option, 772 /// When nothing committed: the model text AEGIS rejected (it did not 773 /// parse as one file change), or why the model Skill returned nothing. 774 #[serde(default)] 775 pub uncommitted_proposal: Option, 776 #[serde(default)] 777 pub proposer_error: Option, 778 /// Every proposal the model Skill made for this task (ACCEPTANCE-v2 3b). 779 #[serde(default)] 780 pub proposal_attempts: Vec, 781 /// Requirements recognized in the goal (crate::requirements); the only 782 /// ones checked. Empty = none recognized, nothing checked. 783 #[serde(default)] 784 pub requirements_recognized: Vec, 785 /// Goal text that looks like a measurable requirement but could not be 786 /// interpreted reliably (crate::requirements::analyze). Non-empty = the 787 /// task was refused before any model call. 788 #[serde(default)] 789 pub requirements_uncertain: Vec, 790 /// "model" when the Skill ran inference, or the stub label. 791 pub proposer: String, 792 /// ALLEN persona used for this task (arch#159). Old reports have none. 793 #[serde(default)] 794 pub persona: Option, 795 /// ALLEN memory used for this task (arch#159). Old reports have none. 796 #[serde(default)] 797 pub memory: Option, 798 /// Workspace files whose text the proposal prompt carried (sc#382): name 799 /// relative to the workspace, sha256 and size of the bytes shown. Reading 800 /// inside the workspace is not an effect; this list is its record. 801 #[serde(default)] 802 pub inputs: Vec, 803 /// Input candidates that were not shown to the model, with the reason. 804 #[serde(default)] 805 pub inputs_omitted: Vec, 806 } 807 808 /// One workspace file shown to the model as input (sc#382). 809 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 810 pub struct InputRef { 811 pub name: String, 812 pub sha256: String, 813 pub bytes: usize, 814 } 815 816 /// An input candidate that was not shown, and why. 817 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 818 pub struct InputOmitted { 819 pub name: String, 820 pub reason: String, 821 } 822 823 /// One proposal the compose "model" Skill made (ACCEPTANCE-v2 3b). 824 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 825 pub struct ProposalAttempt { 826 /// 1-based. 827 pub attempt: u32, 828 /// Wall time of the model call. 829 pub ms: u64, 830 /// Generated tokens (0 when the call failed). 831 pub tokens: usize, 832 /// "parsed" | "refused" (template parser) | "timeout" | "error". 833 pub outcome: String, 834 /// Why the attempt was refused or failed. 835 pub reason: Option, 836 pub text_sha256: Option, 837 pub text: Option, 838 /// For the attempt handed to AEGIS: "pass" or "fail". 839 pub aegis: Option, 840 /// How generation stopped: "eos" | "max_tokens" | "aborted" | "preempted" 841 /// (ACCEPTANCE-v5 Q3). None when the call failed or the proposer did not say. 842 #[serde(default)] 843 pub finish_reason: Option, 844 /// Generated token ids in order (NEXT-PHASE-1 v6 R1); None when the call 845 /// failed or the proposer does not expose them. 846 #[serde(default)] 847 pub token_ids: Option>, 848 /// How many prompt token ids were submitted (NEXT-PHASE-1 v6 R1). 849 #[serde(default)] 850 pub prompt_tokens: Option, 851 /// sha256 of the prompt ids, each 4 little-endian bytes (NEXT-PHASE-1 v6 R1). 852 #[serde(default)] 853 pub prompt_ids_sha256: Option, 854 /// How the backend chose this attempt's tokens (sc#294). None when the 855 /// call failed or nothing observed it; omitted from the JSON then. 856 #[serde(default, skip_serializing_if = "Option::is_none")] 857 pub decoding: Option, 858 /// The tensor backend and its op counters when this attempt's call 859 /// finished (sc#337). None when the call failed or the backend does not 860 /// account its ops; omitted from the JSON then. 861 #[serde(default, skip_serializing_if = "Option::is_none")] 862 pub ops: Option, 863 /// Requirements of the goal this attempt's complete document failed 864 /// (crate::requirements); empty when none failed or none were recognized. 865 #[serde(default)] 866 pub unmet_requirements: Vec, 867 /// sc#384 v8 corrective retry: `text_sha256` of the refused reply this 868 /// attempt's prompt quoted back to the model (the previous attempt's 869 /// reply). None on attempt 1 and when the previous attempt had no reply 870 /// (timeout, error): that prompt carries the refusal reason only. 871 #[serde(default, skip_serializing_if = "Option::is_none")] 872 pub shown_refused_text_sha256: Option, 873 } 874 875 /// The record `ComposeNote` appended. 876 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 877 pub struct ComposeNoteReport { 878 pub machine_id: String, 879 pub id: u64, 880 pub kind: String, 881 /// Cortex record digest (hex), re-read after the append. 882 pub digest: String, 883 /// sha256 (hex) of the note text. 884 pub text_sha256: String, 885 pub links: Vec, 886 } 887 888 /// One Cortex record as recalled (digest re-checked by omega). 889 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 890 pub struct ComposeRecordView { 891 pub id: u64, 892 pub cls: u32, 893 pub kind: u32, 894 pub subject: u64, 895 pub tag: u64, 896 pub links: Vec, 897 pub digest: String, 898 pub verified: bool, 899 /// "constraint", "authorization", "effect", "repair_tail" for host records. 900 pub note: Option, 901 /// Host note text (sha256-checked), when the record is a note. 902 pub text: Option, 903 } 904 905 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 906 pub struct ComposeRecallReport { 907 pub compose_dir: String, 908 pub machine_id: String, 909 pub records_total: u64, 910 /// Every host record (subject 0), oldest first. 911 pub host: Vec, 912 /// The records asked for by id (absent ids are listed in `missing`). 913 pub cited: Vec, 914 pub missing: Vec, 915 /// sha256 over the digests of records 1..=prefix (hex), when asked. 916 pub prefix: Option, 917 pub prefix_digest: Option, 918 /// True when the daemon was built with the native Omega composition library 919 /// (not the stub). Absent in older replies (reads as false). 920 #[serde(default)] 921 pub compose_native: bool, 922 /// The omega commit the linked library was pinned to; empty for the stub. 923 #[serde(default)] 924 pub omega_sha: String, 925 } 926 927 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 928 pub struct ComposeRecoverReport { 929 pub compose_dir: String, 930 pub repaired: bool, 931 pub tail_torn: bool, 932 /// CX_ERR_TORN (-8), RX_ERR_REPLAY (-21), 0 = nothing to repair. 933 pub cause: i32, 934 pub cut_lo: u64, 935 pub cut_hi: u64, 936 pub records_kept: u64, 937 pub dropped_records: u64, 938 pub anchor_records: u64, 939 /// Cortex id of the repair record (0 = none). 940 pub repair_record: u64, 941 pub cut_bytes_kept: u64, 942 pub cut_sha256: String, 943 /// The composition opened after the repair (trial open). 944 pub opens: bool, 945 pub open_rc: i32, 946 pub rolled_back: u32, 947 pub recovered_completed: u32, 948 /// ACCEPTANCE-v3 2.3: records the set-aside record mark said were lost 949 /// (0 = the mark was kept or only damaged), where it was kept, and the 950 /// host constraint record that names the repair (0 = none). 951 #[serde(default)] 952 pub mark_lost: u64, 953 #[serde(default)] 954 pub mark_kept_as: Option, 955 #[serde(default)] 956 pub mark_repair_record: u64, 957 } 958 959 /// One unsettled effect as `ComposeReconcile` left it. 960 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 961 pub struct ReconcileOutcome { 962 pub intent: u64, 963 pub authorization: u64, 964 /// OPEN, DONE, NOT_DONE or UNRESOLVED. 965 pub state: String, 966 pub disk_sha256: Option, 967 /// The reconcile record appended (None: nothing recorded this time). 968 pub record: Option, 969 /// Who decided, or why nothing was decided. 970 pub note: String, 971 /// sovereign-core #408: for an intent on an objective-bound grant, what 972 /// re-reading the objective record found. Absent for every other intent 973 /// (and in reports written before #408). 974 #[serde(default, skip_serializing_if = "Option::is_none")] 975 pub objective: Option, 976 } 977 978 /// sovereign-core #408: an effect's objective as one reconcile re-read it. 979 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 980 pub struct ObjectiveBinding { 981 pub objective_id: String, 982 /// `bound` (the record exists and holds the approved text), or the 983 /// refusal name: `ObjectiveMissing`, `ObjectiveMismatch`. 984 pub record: String, 985 /// Why, when not `bound`. 986 #[serde(default, skip_serializing_if = "Option::is_none")] 987 pub detail: Option, 988 /// When `bound`: whether the record file is byte-for-byte the one the 989 /// grant was approved against (false: re-recorded with the same text). 990 #[serde(default, skip_serializing_if = "Option::is_none")] 991 pub record_unchanged: Option, 992 } 993 994 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 995 pub struct ComposeReconcileReport { 996 pub compose_dir: String, 997 pub machine_id: String, 998 /// Unsettled intents looked at. 999 pub checked: u64, 1000 pub outcomes: Vec, 1001 } 1002 1003 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 1004 pub struct ComposeControlReport { 1005 pub action: String, 1006 /// The control record appended (None: nothing recorded). 1007 pub recorded: Option, 1008 /// For `revoke`: false when the grant was already spent or revoked. 1009 pub revoked: Option, 1010 } 1011 1012 /// Which persona a task ran with (arch#159). `state`: `not_engaged` (ALLEN is 1013 /// off, no persona text was added), `default` (no profile saved), `applied` 1014 /// (profile `revision` in use) or `refused` (profile damaged or foreign: 1015 /// defaults used, `reason` says why). 1016 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 1017 pub struct PersonaReport { 1018 pub state: String, 1019 pub display_name: String, 1020 pub revision: u64, 1021 #[serde(default)] 1022 pub reason: Option, 1023 } 1024 1025 /// Latest deployment-record line, when the record exists and verifies. 1026 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 1027 pub struct DeploymentSummary { 1028 pub seq: u64, 1029 pub candidate_id: String, 1030 pub placeholder: bool, 1031 } 1032 1033 /// `AllenStatus`: identity, persona, model and what is not supported yet, 1034 /// reported separately. 1035 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 1036 pub struct AllenStatusReport { 1037 /// `not_engaged` or `engaged` (an engaged identity that cannot resolve stops the daemon). 1038 pub identity: String, 1039 /// First 8 hex characters of the agent id (engaged only). 1040 pub fingerprint: Option, 1041 pub head_sequence: Option, 1042 pub chain_verified: Option, 1043 pub persona: PersonaReport, 1044 /// The proposer label the daemon was started with. 1045 pub model: String, 1046 /// `local_model` or `stub`. 1047 pub execution_mode: String, 1048 pub deployment: Option, 1049 /// Facilities that exist in the plan but not in v1; their controls do not exist. 1050 pub unsupported: Vec, 1051 } 1052 1053 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 1054 pub struct AllenProfileReport { 1055 /// 0 = no profile saved (defaults in effect). 1056 pub revision: u64, 1057 pub state: String, 1058 /// The saved revision; `None` when none is saved. 1059 pub profile: Option, 1060 /// The values in effect when no profile is saved. 1061 pub defaults: Option, 1062 } 1063 1064 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 1065 pub struct AllenHistoryReport { 1066 pub entries: Vec, 1067 } 1068 1069 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 1070 pub struct AllenRefusalReport { 1071 pub code: String, 1072 /// Plain-language reason. 1073 pub message: String, 1074 pub current_revision: Option, 1075 } 1076 1077 /// Which memory a task saw (arch#159). `state`: `not_requested` (no context 1078 /// was given, nothing included), `not_engaged`, `included` (`items_included` 1079 /// notes for exactly `context`) or `refused` (store damaged or foreign: the 1080 /// task ran with no memory, `reason` says why). `items_omitted` notes were left 1081 /// out by the count/byte bound; `items_unresolved` notes in the context could 1082 /// not be read (key missing) and were not shown to the model. 1083 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 1084 pub struct MemoryReport { 1085 pub context: Option, 1086 pub items_included: usize, 1087 #[serde(default)] 1088 pub items_omitted: usize, 1089 #[serde(default)] 1090 pub items_unresolved: usize, 1091 pub state: String, 1092 #[serde(default)] 1093 pub reason: Option, 1094 } 1095 1096 /// Answer to a memory or goal command: what was done, in which context, and 1097 /// the JSON result (items, ids, export). 1098 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 1099 pub struct AllenMemoryReport { 1100 pub action: String, 1101 /// The context the call named; `None` for an owner-wide call. 1102 pub context: Option, 1103 pub result: serde_json::Value, 1104 }